// SmileyTest5B.js - January 2010
// Javascript and jQuery code for Ning Networks
// Copyright 2010, B K Services Inc.  www.bkserv.com
// Tested with:
// Known issue: In Forum, Inserts Smiley at end of any text, not at cursor.
// New method of inserting Smileys (Non-Forum):  Smiley click puts img code into textbox.
// 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 replaceCodes() {

    x$('textarea[name="description"], textarea[name="comment"]').each(function() {
        var commentText = " " + x$(this).val();  //V3: In case Smiley is first thing on the line.  It now needs a Space before Code!

        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);
        }

        x$(this).val(commentText);
    });
}

function getBrowserInfo() {
    gBrowserName = navigator.appName;
    var b_version = navigator.appVersion;
    gBrowserVersion = parseFloat(b_version);
}

function addToTextarea(n) {
    // textarea is named comment except for Forum, then its description.

    // Get the img tag code, based on n:
    var imgtag = "";
    if (n < 4) {
        imgtag = imgStart + smileyName[n] + imgEnd;
    }
    else {
        if (window.moreSmileys !== undefined) imgtag = imgStartNoPath + moreSmileys.path + moreSmileys.smiley[n - 4].name + moreSmileys.ext + "' />";
    }

    // Append the img tag at the end of the textbox content:
    // This works in FF.  But in IE8 it shows up as the pic and not the code and is not saved along with the text!
    // x$('textarea[name="comment"], textarea[name="description"]').append(imgtag);


    // This is for FORUMs:
    if (x$('textarea[name="description"]').length > 0) {
        if (gBrowserName == "Microsoft Internet Explorer") {
            x$('textarea[name="description"]').append(imgtag);
        }
        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 += imgtag;

            // 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 += imgtag;
        }
    }

    
    // 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 = ' ' + imgtag + ' ';
            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)
					  + ' ' + imgtag + ' '
					  + value.substring(endPos, value.length));
            cursorPos += imgtag.length + 2;
            myField.focus();
            myField[0].selectionStart = cursorPos;
            myField[0].selectionEnd = cursorPos;
        }
        else {
            myField.attr("value", value + ' ' + imgtag + ' ');
            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 class="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 class='smileyBar'> Click to Insert: " + smileyBar + " | <a style='cursor:pointer' onclick='showMore()'>more</a> </div>");
    
    // Bind mousedown event on button to replace codes with img tags:
    x$("input[value='Add Comment'], input[value='Add Reply']").mousedown(replaceCodes);

});

