// SmileyTest4E.js - May 2010
// Javascript and jQuery code for Ning Networks
// Copyright 2010, B K Services Inc.  www.bkserv.com
// Tested with: FF, IE7
// Known issue: Inserts at end of any text, not at cursor.
// Smiley will not show right away in new non-forum comments, but will on refresh.
// Will put code at cursor in non-forum comments, will put at end in Forum replies.
// A license to use this code is granted ONLY to members of jQueryHelp.ning.com
// For more information, Email us: bill@bkserv.com

// ----- This will be in a separate file called MoreSmileyData.js -----
// This is how you add your own "More" Smileys...
// var moreSmileys = {
//  "path" : "http://www.bkserv.net/images/", 
//  "ext" : ".gif",
//  "count" : "2",
//  "smiley" :
//    [
//        { "code" : "8)", "name" : "glasses" },
//        { "code" : "=:)", "name" : "hair" }
//    ]
// }

// Built-in Smileys:
var smileyName = ['Grin', 'Smile', 'Frown', 'Tongue'];
var smileyCode = [':D', ':\)', ':\(', ':P'];
var smileyRegex = [':D', ':\\)', ':\\(', ':P'];
var numSmileys = 4;
var imgStart = "<img src='http://www.bkserv.net/images/";
var imgStartNoPath = "<img src='";
var imgEnd = ".gif' />";

// Global variables:
var gMoreOpen = false;
var gBrowserName;
var gBrowserVersion;



function getBrowserInfo() {
    gBrowserName = navigator.appName;
    var b_version = navigator.appVersion;
    gBrowserVersion = parseFloat(b_version);
}

function showSmileys() {
    // Smiley Injection - replace :D with grin, :) with smile, :( with frown, :P with Tongue.
    if (moreSmileys.ext == undefined) moreSmileys.ext = ".gif";  // Default to GIF

    // First, replace codes in existing comments/posts:

    // For FORUM reply:
    x$("dl.discussion div.description").each(function() {
        var commentText = " " + x$(this).html();  //V3: In case Smiley is first thing on the line.  It now needs a Space before Code!

        var commentTextOut = smileyCodeToImage(commentText);

        x$(this).html(commentTextOut);
    });  // This ends EACH function!


    // For Comment Wall comments:
    x$("div#xg_profiles_chatterwall_list").find("dl.comment dd").each(function() {
        var commentText = " " + x$(this).html();  //V3: In case Smiley is first thing on the line.  It now needs a Space before Code!

        var commentTextOut = '';
        var i;
        var codePiece = '';
        var textPiece = '';
        var inAngles = 0;

        for (i = 0; i < commentText.length; i++) {
            if (commentText[i] == '<') {
                // Process textPiece if its not empty:
                if (textPiece != '') {
                    commentTextOut += smileyCodeToImage(textPiece);
                    textPiece = '';
                }
                codePiece += commentText[i];
                inAngles = 1;
            }
            else if (commentText[i] == '>') {
                codePiece += commentText[i];
                inAngles = 0;
                commentTextOut += codePiece;
                codePiece = '';
            }
            else if (inAngles == 1) {
                codePiece += commentText[i];
            }
            else {
                textPiece += commentText[i];
            }
        } // END for
        
        // if there's something left in textPiece then process it.
        if (textPiece != '') commentTextOut += smileyCodeToImage(textPiece);

        x$(this).html(commentTextOut);
    });            // This ends EACH function!


    // For NON-FORUM reply:
    //  If a member chooses to approve comments, there is an extra dd with class=item_approval and
    //   we don't want to look for Smiley codes in there!
    // OUT in 4B: x$("dl.comment dd:not(.item_approval)").each(function() {
    x$("div#comments").find("dl.comment dd:not(.item_approval)").each(function() {  //NEW 4B
        var commentText = " " + x$(this).html();  //V3: In case Smiley is first thing on the line.  It now needs a Space before Code!

        var aTag = '';

        // The a tag to delete the comment is in commentText at this point.
        //  We do NOT want to replace anything in the a tag!!!
        //  So break commentText to text up to a> and then the actually comment which is after that.
        var iMark = commentText.indexOf('a>', 0);
        if (iMark > -1) {
            aTag = commentText.substring(0, iMark + 2);
            commentText = commentText.substring(iMark + 2);
        }

        var commentTextOut = smileyCodeToImage(commentText);

        // Add back in the a tag code along with the comment with the replaced Smiley codes:
        x$(this).html(aTag + commentTextOut);
    });      // This ends EACH function!


    // Second, bind to mouseup so we call this again a second after a new comment/post is added:
    //  (But only for Forum replies, this disables the delete button in non-forum comments!)
    x$("input[value^='Add Reply']").mouseup(function() {
        setTimeout("showSmileys()", 2000);
    });
}


function smileyCodeToImage(cT) {

    var commentText = cT;
    var ix;
    var r;

    // IF There are MoreSmileys, Turn MoreSmileys codes into img tags:
    if (window.moreSmileys !== undefined) {
        // Turn moreSmileys codes into img tags:
        for (ix = 0; ix < moreSmileys.count; ix++) {
            r = new RegExp(encodeRE(" " + moreSmileys.smiley[ix].code), "g");  //V3: Require Space before Code!
            commentText = commentText.replace(r, imgStartNoPath + moreSmileys.path + moreSmileys.smiley[ix].name + moreSmileys.ext + "' />");
        }
    }

    // Turn Built-in Smileys codes into img tags:
    for (ix = 0; ix < numSmileys; ix++) {
        r = new RegExp(" " + smileyRegex[ix], "g");  //V3: Require Space before Code!
        commentText = commentText.replace(r, imgStart + smileyName[ix] + imgEnd);
    }

    return commentText;
}


function addToTextarea(n) {
    // textarea is named comment except for Forum, then its description

    var s = "";
    if (n < numSmileys)
        s = smileyCode[n];
    else
        if (window.moreSmileys !== undefined) s = moreSmileys.smiley[n - numSmileys].code;


    var text = ' ' + s + ' ';

    // Same as in version 5, but imgtag changed to text.

    // This is for FORUMs:
    if (x$('textarea[name="description"]').length > 0) {
        if (gBrowserName == "Microsoft Internet Explorer") {
            x$('textarea[name="description"]').append(text);
        }
        else {
            var areas = document.getElementsByName("description");

            // TOP... Do for EACH description box!  Might be 2, one at the top and one at the bottom!
            if (areas.item(1) == null || areas.item(1).type != "textarea") {
                return -1;
            }
            var txtarea = areas.item(1);
            txtarea.value += text;

            // BOTTOM... Do for EACH description box!  Might be 2, one at the top and one at the bottom!
            if (areas.item(2) == null || areas.item(2).type != "textarea") {
                return -1;
            }
            txtarea = areas.item(2);
            txtarea.value += text;
        }
    }


    // This is for NON-Forums:
    if (x$('textarea[name="comment"]').length > 0) {
        var myField;
        var value = '';
        myField = x$('textarea[name="comment"]');
        value = x$('textarea[name="comment"]').attr("value");

        if (value == undefined) { value = ''; }
        if (document.selection) {
            myField.focus();
            sel = document.selection.createRange();
            sel.text = ' ' + text + ' ';
            myField.focus();
        }
        else if (myField[0].selectionStart || myField[0].selectionStart == '0') {
            var startPos = myField[0].selectionStart;
            var endPos = myField[0].selectionEnd;
            var cursorPos = endPos;
            myField.attr("value", value.substring(0, startPos)
					  + ' ' + text + ' '
					  + value.substring(endPos, value.length));
            cursorPos += text.length + 2;
            myField.focus();
            myField[0].selectionStart = cursorPos;
            myField[0].selectionEnd = cursorPos;
        }
        else {
            myField.attr("value", value + ' ' + text + ' ');
            myField.focus();
        }
    }
}

function buildSmileyBar() {
    var sStart = " <a style='cursor:pointer' onclick='addToTextarea(";
    var sMid = ")'>";
    var sOut = "";

    var ix;
    for (ix = 0; ix < numSmileys; ix++) {
        sOut += sStart + ix + sMid + imgStart + smileyName[ix] + imgEnd + "</a>";
    }

    return sOut;
}

function getMoreSmileys() {
    var sStart = " <a style='cursor:pointer' onclick='addToTextarea(";
    var sMid = ")'>";
    var sOut = "";

    if (moreSmileys.ext == undefined) moreSmileys.ext = ".gif";  // Default to GIF

    if (window.moreSmileys !== undefined) {
        var ix;
        for (ix = 0; ix < moreSmileys.count; ix++) {
            sOut += sStart + (ix + 4) + sMid + imgStartNoPath + moreSmileys.path + moreSmileys.smiley[ix].name + moreSmileys.ext + "' /></a>";
        }
    }

    return sOut;
}

function showMore() {
    if (gMoreOpen == false) {
        x$('#smileyBar').after('<div id="moreSmileys">MORE Smileys | <a style="cursor:pointer" onclick="closeMore()">Close</a><br />' + getMoreSmileys() + '<br /></div>');
        gMoreOpen = true;
    }
}

function closeMore() {
    x$('div#moreSmileys').remove();
    gMoreOpen = false;
}

function encodeRE(s) {
    return s.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
}

// +++++++++++++++++++++++++++++++++++ READY FUNCTION ++++++++++++++++++++++++++++++++++++++++++++++++++
x$(document).ready(function() {

    getBrowserInfo();

    var smileyBar = buildSmileyBar();

    // Inject the Smiley Bar, before the buttons that start with Add Comment or Add Reply:
    // x$("input[value^='Add Comment'], input[value^='Add Reply']").before("<span id='smileyBar' style='float:left'> Click to Insert: " + smileyBar + " | <a style='cursor:pointer' onclick='showMore()'>more</a> </span>");

    // Inject the Smiley Bar UNDER each textarea:
    x$("div.texteditor").after("<div id='smileyBar'> Click to Insert: " + smileyBar + " | <a style='cursor:pointer' onclick='showMore()'>more</a> </div>");

    showSmileys();

});


