function insertEmoticon(text, element) {
    var range,str1,str2;
    element.focus();
    //IE
    if(document.selection)
    {
        range = document.selection.createRange();
        range.text = text;
    }
    //Gecko
    else if(element.selectionStart || element.selectionStart == "0")
    {
        str1 = element.value.substring(0, element.selectionStart);
        str2 = element.value.substring(element.selectionEnd);
        element.value = str1 + text + str2;
        element.selectionStart = element.selectionEnd = str1.length + text.length;
    }
    else
        element.value = element.value + text;
}

var emoTimer = null;

function initEmoticonDiv(formId) {

    var div = document.getElementById(formId).getElementsByTagName("div")[0];
    var elementId = div.getAttribute("id");
    var img = div.getElementsByTagName("img")[0].cloneNode(true);
    
    img.setAttribute("class", "insertEmoticonImg");
    div.parentNode.insertBefore(img, div);
    img.emoDiv = div.parentNode.removeChild(div);
    div.className = "insertEmoticonDivVisible";
    
    img.onmouseover = function(e) {
        if(!e && event)
            e = event;
        if(!e)
            return false;
        if(emoTimer)
            clearTimeout(emoTimer);
        else
        {
            var scr = scrollbar_position();
            this.emoDiv.style.position = "absolute";
            this.emoDiv.style.left = (e.clientX+scr['x']+10)+"px";
            this.emoDiv.style.top = (e.clientY+scr['y']+10)+"px";
            document.getElementsByTagName("body")[0].appendChild(this.emoDiv);
        }
    }

    img.onmouseout = div.onmouseout = function()
    {
        emoTimer = setTimeout("document.getElementById('"+elementId+"').parentNode.removeChild(document.getElementById('"+elementId+"')); emoTimer = null;", 250);
    }
    
    div.onmouseover = function()
    {
        if(emoTimer)
            clearTimeout(emoTimer);
    }
    
    div.onclick = function()
    {
        document.getElementById(elementId).parentNode.removeChild(document.getElementById(elementId));
        emoTimer = null;
    }
    
    var emoticons = div.getElementsByTagName("img");
    for(i = 0; i < emoticons.length; i++)
    {
        emoticons[i].onclick = function()
        {
            insertEmoticon(this.getAttribute("alt"), img.parentNode.getElementsByTagName("textarea")[0]);
        }
    }
}

pockaj_na("newForumPostSubmit", "initEmoticonDiv('forumNewPostForm')");
pockaj_na("editPostSubmit", "initEmoticonDiv('editPostForm')");
