P5.Forum = {};

// by pixelDepth http://www.sitepoint.com/forums/showthread.php?p=2144318#post2144318
P5.Forum.insert = function (theId, in_firstpart, in_lastpart){
    var tArea = document.getElementById(theId);
    var firstpart = (in_firstpart)? in_firstpart : "";
    var lastpart = (in_lastpart)? in_lastpart : "";
    var justInsert = (justInsert) ? justInsert : 0;
    if (!tArea) {
        alert("Did not find textarea with tag " + theId);
        return;
    }
    var oldTop = tArea.scrollTop;
    
    if(tArea.createTextRange){ // was: isIE
        // If I don't do this the entire window scrolls to top (O 9.0beta)
        if ("Opera" == window.navigator.appName) {
            var operaTop = document.body.scrollTop;
        }
        tArea.focus();
        var curSelect = document.selection.createRange();
        curSelect.text = firstpart + curSelect.text + lastpart;
        if ("Opera" == window.navigator.appName) {
            document.body.scrollTop = operaTop;
        }
    } else if(typeof tArea.selectionStart != "undefined"){ // !isIE && 
        var saveStart = tArea.selectionStart;
        var saveStop = tArea.selectionEnd;
        var selStart = tArea.value.substr(0, tArea.selectionStart);
        var selEnd = tArea.value.substr(tArea.selectionEnd, tArea.value.length);
        var curSelection = tArea.value.replace(selStart, '').replace(selEnd, '');
        tArea.value = selStart + firstpart + curSelection + lastpart + selEnd;
        tArea.selectionEnd = saveStop + firstpart.length + lastpart.length;
        tArea.selectionStart = saveStart;
    } else {
        tArea.value += firstpart + lastpart;
        oldTop = tArea.scrollHeight;
    }
    // Scrollbar goes to bottom of screen if we don't do this.
    tArea.scrollTop = oldTop;
};

P5.Forum.isStringNumeric = function (theString)
{
    var i = 0;
    for (i=0; i<theString.length; i++) {
        var kar = theString.charCodeAt(i);
        if (48 > kar || 57 < kar) {
            return false;
        }
    }
    return true;
};

P5.Forum.fixBracketsSub = function (str)
{
    var i;
    var out = "";
    for (i=0; i<str.length; i++) {
        if ('[' == str[i]) {
            out += "[[]";
            continue;
        }
        if (']' == str[i]) {
            out += "[]]";
            continue;
        }
        out += str[i];
    }
    return out;
};

// --- callbacks from buttons below:
P5.Forum.addLink = function (theId)
{
    var my_link = prompt("Enter URL:\nLink starting with / is internal (not starting with http). eg /index.php?page=a","");
    if (null === my_link) { 
        return; 
    }
    var my_text = prompt("Enter text:","");
    if (null === my_text) {
        return;
    }    
    
    P5.Forum.insert(theId, '[link]' + my_link + ' ' + my_text + '[/link]');
};

P5.Forum.addIntref = function (theId)
{
    var my_link = prompt("Enter reference without #:","");
    if (null === my_link) { 
        return; 
    }
    var my_text = prompt("Optional text:","");
    if (null === my_text) {
        return;
    }    
    
    P5.Forum.insert(theId, '[intref]' + my_link + ' ' + my_text + '[/intref]');
};

P5.Forum.addMailto = function (theId)
{
    var my_link = prompt("email address (eg user@example.com)","");
    if (null === my_link) { 
        return; 
    }
    var my_text = prompt("text that should be shown (eg User)","");
    if (null === my_text) {
        return;
    }    
    
    P5.Forum.insert(theId, '[mailto]' + my_link + ' ' + my_text + '[/mailto]');
};

P5.Forum.addBinIcons = function (theId)
{
    var my_itemid = prompt("Itemid of bin (in parenthesis in dropdown left):","");
    if (null === my_itemid) { return; }
    if (! P5.Forum.isStringNumeric(my_itemid)) {
        alert("Binid must be numeric [" + my_itemid + ']');
        return;
    }
    var my_nbr = prompt("How many clips?","");
    if (null === my_nbr) { return; }
    if (! P5.Forum.isStringNumeric(my_nbr) || 1 > my_nbr) {
        alert("nbr of clips must be numeric and >=1");
        return;
    }
    P5.Forum.insert (theId, '[binicons]' + my_itemid + ' h ' + my_nbr + ' icon[/binicons]');
};

P5.Forum.addClip = function (theId)
{
    var my_itemid = prompt("Itemid of clip:","");
    if (null === my_itemid) { return; }
    // TODO do this with yui instead.
    var my_displaytype = prompt("Display how:\n1 - icon\n2 - Search result icon\n3 - player\n","");
    if (null === my_displaytype) { return; }
    var my_link_to_clip;
    if ('3' != my_displaytype) {
        my_link_to_clip = confirm ("Shall I link it to the item page?");
    }
    
    if (null === my_itemid || null === my_displaytype) {
        return;
    }
    
    if (false === P5.Forum.isStringNumeric(my_itemid)) {
        alert ("Itemid of clup must be numeric!");
        return;
    }
    if (false === P5.Forum.isStringNumeric(my_displaytype)) {
        alert ("Itemid of clup must be numeric!");
        return;
    }
    
    var my_text = '';
    if        ('1' == my_displaytype) {
        my_text = 'icon';
    } else if ('2' == my_displaytype) {
        my_text = 'iconsres';
    } else if ('3' == my_displaytype) {
        my_text = 'prev';
    } else {
        alert ("Display how should be in range 1..3");
        return;
    }

    if (my_link_to_clip) {
        P5.Forum.insert (theId, '[link]/stock-footage/' + my_itemid + ' ' +
                         '[item]' + my_itemid + ' ' + my_text + '[/item]' +
                         '[/link]');
    } else {
        P5.Forum.insert (theId, '[item]' + my_itemid + ' ' + my_text + '[/item]');
    }
};

P5.Forum.normalTag = function (theId, tagfirst, taglast)
{
    P5.Forum.insert (theId, tagfirst, taglast);
};

P5.Forum.addColor = function (theId)
{
    var my_color = prompt("Color (six digit hex):","");
    
    if (null === my_color || 6 != my_color.length) {
    	alert ("No, six hexadecimal digits.\nRRGGBB\nExample: red is ff0000");
        return;
    }
    
    P5.Forum.normalTag(theId, '[color #' + my_color + ']', '[/color]');
};

P5.Forum.addBgcolor = function (theId)
{
    var my_color = prompt("Color (six digit hex):","");
    
    if (null === my_color || 6 != my_color.length) {
    	alert ("No, six hexadecimal digits.\nRRGGBB\nExample: red is ff0000");
        return;
    }
    
    P5.Forum.normalTag(theId, '[bgcolor #' + my_color + ']', '[/bgcolor]');
};

P5.Forum.addFSize = function (theId)
{
    var my_size = prompt ("Size of font (0.8 .. 2.0):", "1.0");
    
    if (null === my_size) { return; }
    var my_val = parseFloat (my_size);
    if (isNaN(my_val)) {
        alert ("Please use numeric range of 0.8 .. 2.0");
        return;
    }
    P5.Forum.normalTag (theId, '[fsize ' + my_val.toFixed(1) + ']', '[/fsize]');
};

P5.Forum.addAlign = function (theId)
{
    var my_align = prompt ("Alignment; use one of \"left\",\"center\",\"right\"","");
    if (null === my_align) { return; }
    if ("left" != my_align && "center" != my_align && "right" != my_align) {
        alert("I didn't understand that.");
        return;
    }
    P5.Forum.normalTag (theId, '[align ' + my_align + ']', '[/align]');
};

P5.Forum.fixBrackets = function (theId)
{
    var tArea = document.getElementById(theId);
    var isIE = document.all ? true : false;
    var firstpart = (firstpart)? firstpart : "";
    var lastpart = (lastpart)? lastpart : "";
    var justInsert = (justInsert) ? justInsert : 0;

    if (!tArea) {
        alert("Did not find textarea with tag " + theId);
        return;
    }
    
    if(isIE){
        tArea.focus();
        var curSelect = document.selection.createRange();
        curSelect.text = firstpart + P5.Forum.fixBracketsSub(curSelect.text) + lastpart;
    } else if(typeof tArea.selectionStart != "undefined"){ // !isIE && 
        var saveStart = tArea.selectionStart;
        var saveStop = tArea.selectionEnd;
        var selStart = tArea.value.substr(0, tArea.selectionStart);
        var selEnd = tArea.value.substr(tArea.selectionEnd, tArea.value.length);
        var curSelection = tArea.value.replace(selStart, '').replace(selEnd, '');
        tArea.value = selStart + firstpart + P5.Forum.fixBracketsSub(curSelection) + lastpart + selEnd;
        tArea.selectionEnd = saveStop + firstpart.length + lastpart.length;
        tArea.selectionStart = saveStart;
    } else {
        alert ("You must select something to convert [ => [[] and ] => []]!");
    }
};

P5.Forum.fixRot13 = function (theId)
{
    var tArea = document.getElementById(theId);
    var isIE = document.all ? true : false;
    var firstpart = (firstpart)? firstpart : "";
    var lastpart = (lastpart)? lastpart : "";
    var justInsert = (justInsert) ? justInsert : 0;

    if (!tArea) {
        alert("Did not find textarea with tag " + theId);
        return;
    }
    
    if(isIE){
        tArea.focus();
        var curSelect = document.selection.createRange();
        curSelect.text = firstpart + P5.rot13(curSelect.text) + lastpart;
    } else if(typeof tArea.selectionStart != "undefined"){ // !isIE && 
        var saveStart = tArea.selectionStart;
        var saveStop = tArea.selectionEnd;
        var selStart = tArea.value.substr(0, tArea.selectionStart);
        var selEnd = tArea.value.substr(tArea.selectionEnd, tArea.value.length);
        var curSelection = tArea.value.replace(selStart, '').replace(selEnd, '');
        tArea.value = selStart + firstpart + P5.rot13(curSelection) + lastpart + selEnd;
        tArea.selectionEnd = saveStop + firstpart.length + lastpart.length;
        tArea.selectionStart = saveStart;
    } else {
        alert ("You must something for this to make sense!");
    }
};

P5.Forum.searchForum = function ()
{
    var tt = $('qfsearchid').value.strip();
    if (''===tt) {
        P5.slideMessage("There is no point with an empty search");
        return;
    }
    window.location = '/index.php?page=community_search&q=' + encodeURIComponent(tt);
};

P5.Forum.gotoCommentXHR = function (json)
{
    $('comments' + json.atDiv).update (json.html);
    eval(json.js);
};

P5.Forum.gotoComment = function (atDiv)
{
    var n=$('comments' + atDiv);
    if (! n) { return; }

    $('umsgat' + P5._l.cmnt).update(P5._l.cmnt);
    $('lmsgat' + P5._l.cmnt).update(P5._l.cmnt);
    $('comments' + P5._l.cmnt).hide();

    P5._l.cmnt = atDiv;
    $('umsgat' + P5._l.cmnt).update("<strong>" + P5._l.cmnt + "</strong>");
    $('lmsgat' + P5._l.cmnt).update("<strong>" + P5._l.cmnt + "</strong>");
    $('comments' + P5._l.cmnt).show();
    if (document.documentElement && document.documentElement.scrollTop) {
        document.documentElement.scrollTop = 0;
    } else if (document.body && document.body.scrollTop) {
        document.body.scrollTop = 0;
    }
    if (Object.isUndefined(P5._l._loadedArr))
    {
        return;
    }
    if (0 === P5._l._loadedArr['c' + atDiv]) {
        P5._l._loadedArr['c' + atDiv] = 2;
        var post_page = '/index.php?page=community_ajax&what=load&forum=' + P5._l._forum + '&thread=' + P5._l._thread + '&atDiv=' + atDiv;
        P5.XHRupdate(post_page, null, P5.Forum.gotoCommentXHR);
    }
};

P5.Forum.addImgFClick = function (in_evt)
{
    P5.Forum.insert($F('listaMedBilderId'), '[img]' + $F('listaMedBilder') + '[/img]');
    P5.hideTT();
    return P5.cancelEvent(in_evt || window.event);
};

P5.Forum.addImgXHR = function (json)
{
    P5.enlargeTT(P5._l.addImgEv, json.out_str, {st:1, tw:400});
};

P5.Forum.addImg = function (in_evt, theId,theDestType)
{
    P5._l.addImgEv = in_evt || window.event;
    var post_page = '/index.php?page=markup_image_ajax&what=addImg&id=' + theId + '&dt=' + theDestType;
    P5.XHRupdate(post_page, null, P5.Forum.addImgXHR);
};
