﻿
// jQuery noConflict
var jQ = jQuery.noConflict();


// namespaces init
var SE = new Object();
SE.effects = new Object();
SE.alerts = new Object();
SE.shouting = new Object();
SE.shouting.th = new Object();
SE.messages = new Object();

var speedNormal = "normal";
var speedFast = "fast";


jQ(document).ready(function() {
    populateColorPickers();
    removeShoutBackgrounds();
    SE.shouting.addEvents();

    // fix for one IE bug
    jQ("div.Shout .thReplies:empty").hide();
    jQ("div.ShoutThumb .thReplies:empty").css("height", "0px");
});

jQ(window).load(function() {
    processDelayedLoadedImages();
});



// effects
SE.effects.toggleSlide = function(box) {
    var visible = jQ(box).is(':visible');
    if (visible) {
        jQ(box).slideUp(speedNormal);
    }
    else {
        jQ(box).slideDown(speedNormal);
    }
}

SE.effects.showSlide = function(box) {
    jQ(box).slideDown(speedNormal);
}

SE.effects.hideSlide = function(box) {
    jQ(box).slideUp(speedNormal);
}

SE.effects.toggleFade = function(box) {
    jQ(box).toggle();
}

SE.effects.showFade = function(box) {
    jQ(box).fadeIn(speedFast);
}

SE.effects.hideFade = function(box) {
    jQ(box).fadeOut(speedNormal);
}


// GUI alerts
SE.alerts.settingsSaved = function(boxId, text) {
    var initialDelay = 1000;
    var box = jQ("#" + boxId);
    box.html(text);
    window.setTimeout("SE.effects.showFade('#" + boxId + "');", initialDelay);
    window.setTimeout("SE.effects.hideFade('#" + boxId + "');", 5000 - initialDelay);
}

SE.alerts.displayMessage = function(boxId, text, imagePath, msgTimeout) {
    if (text != "") {
        var msgId = Math.ceil(100*Math.random());
        var checkmark = "<span id='" + msgId + "' style='display:none;' class='msg'><span><img src='" + imagePath + "' alt='' />&nbsp;";
        var box = jQ("#" + boxId);
        box.append(checkmark + text + "</span></span>");
        SE.effects.showSlide("#" + msgId);
        jQ("#" + msgId + " span").show();
        window.setTimeout("SE.alerts.hide('" + boxId + "', '" + msgId + "');", msgTimeout);
    }
}

SE.alerts.hide = function(boxId, msgId) {
    SE.effects.hideSlide("#" + msgId);
    SE.effects.hideFade("#" + msgId + " span");
    window.setTimeout('jQ("#' + msgId + '").remove()', 1000);
}



//////////////////////////////////////////////////////
// shouting
//////////////////////////////////////////////////////

SE.shouting.addEvents = function() {
    jQ("#ShoutWrite textarea").keydown(function(e) {
        if (e.which == 27) {
            var textarea = jQ("#ShoutWrite textarea");
            var requiredText = textarea.attr("requiredText");
            if (requiredText != null && requiredText != "") {
                textarea[0].value = requiredText;
            } else {
                textarea[0].value = "";
            }
            textarea.keyup();
            textarea.blur();
        }
    });
}


SE.shouting.checkForUpdates = function(urlVariable, boxClass, delay, restricted) {
	var functionCall = "SE.shouting.checkForUpdates('" + urlVariable + "', '" + boxClass + "', " + delay + ", " + restricted + ")";
	if (!restricted || jQ.cookie('ShoutEm')) {
		jQ.getJSON(eval(urlVariable),
			function(data){
				if (data.length != 0) {
					SE.effects.showSlide("." + boxClass);
					// document.title = "(" + data.length + ") " + document.title;
				}
				else {
					setTimeout(functionCall, delay);
				}
			});
	}
	else {
		setTimeout(functionCall, delay);
	}	
}

SE.shouting.th.showHiddenReplies = function(obj, boxId) {
    SE.effects.hideSlide(jQ(obj).parent());
    if (jQ.browser.msie && parseInt(jQ.browser.version) < 8) {
        jQ("#" + boxId).show();
    } else {
        SE.effects.showSlide("#" + boxId);
    }
}


SE.shouting.th.hideForm = function(formId, shoutIdShort) {
    var obj = jQ("#" + formId);
    SE.effects.hideSlide(obj);
    jQ(obj).html("");
}

SE.shouting.th.toggleForm = function(obj, formId, shoutIdShort, shoutId, username, shoutBtnText) {
    obj.blur();
    if (jQ("#" + formId + ":first").is(":hidden")) {
        var thFormHtml = SE.shouting.th.generateformHtml(shoutIdShort, shoutId, shoutBtnText);
        jQ("#" + formId).html(thFormHtml);

        var requiredText = "@" + username + " ";
        jQ("#" + shoutIdShort + "-textarea-id").attr("requiredText", requiredText);

        jQ("#" + shoutIdShort + "-textarea-id").keydown(function(e) {
            if (e.which == 27) {
                jQ("#" + shoutIdShort + "-textarea-id").blur();
                SE.shouting.th.hideForm(formId, shoutIdShort);
            }
        });

        jQ("#" + formId).slideDown(speedNormal, function() {
            setFocusAndText(requiredText, shoutIdShort + "-textarea-id", shoutIdShort + "-chars-id");
            if (jQ.browser.msie && parseInt(jQ.browser.version) < 8) {
                jQ("#" + formId).hide().show(); 
            }
        });
    } else {
        SE.shouting.th.hideForm(formId, shoutIdShort);
    }


    //    if (jQ("#" + formId + " #" + shoutIdShort + "-textarea-id").length > 0) {
    //        SE.shouting.th.hideForm(formId, shoutIdShort);
    //    }
    //    else {
    //        var thFormHtml = SE.shouting.th.generateformHtml(shoutIdShort, shoutId);
    //        jQ("#" + formId).html(thFormHtml);

    //        var requiredText = "@" + username + " ";
    //        setFocusAndText(requiredText, shoutIdShort + "-textarea-id", shoutIdShort + "-chars-id");
    //        
    //        jQ("#" + shoutIdShort + "-textarea-id").attr("requiredText", requiredText);
    //    }
}

SE.shouting.th.generateformHtml = function(shoutIdShort, shoutId, shoutBtnText) {
    var thFormHtml = "";
    thFormHtml += "<div id='##FORM_ID##' class='clearfix thWrap'>";
    thFormHtml += "<textarea name='' rows='2' id='##TEXTAREA_ID##' ";
    thFormHtml += "onkeyup='updateRemainingCharCount(\"##TEXTAREA_ID##\", \"##CHAR_ID##\")'></textarea><div class='thSubmit'>";
    thFormHtml += "<a class='button' href='javascript:void(0);' onclick='SE.shouting.th.submitReply(\"##FORM_ID##\",\"##SHOUT_ID_SHORT##\", \"##SHOUT_ID##\");'>##BTN_TEXT##</a>";
    thFormHtml += "<span id='##CHAR_ID##' class='cnt' style='display:block;'>";
    thFormHtml += maxCharCount;
    thFormHtml += "</span></div></div>";

    thFormHtml = thFormHtml.replace(/##FORM_ID##/g, shoutIdShort + "-formId");
    thFormHtml = thFormHtml.replace(/##TEXTAREA_ID##/g, shoutIdShort + "-textarea-id");
    thFormHtml = thFormHtml.replace(/##CHAR_ID##/g, shoutIdShort + "-chars-id");
    thFormHtml = thFormHtml.replace(/##SHOUT_ID##/g, shoutId);
    thFormHtml = thFormHtml.replace(/##SHOUT_ID_SHORT##/g, shoutIdShort);
    thFormHtml = thFormHtml.replace(/##BTN_TEXT##/g, shoutBtnText);

    return thFormHtml;
}

SE.shouting.th.submitReply = function(formId, shoutIdShort, shoutId) {
    var replyText = document.getElementById(shoutIdShort + "-textarea-id").value;
    var requiredText = jQ("#" + shoutIdShort + "-textarea-id").attr("requiredText", requiredText);

    if (replyText.replace(/^\s+|\s+$/g, "") == requiredText.replace(/^\s+|\s+$/g, "")) {
        // if text equal to mandatory reply text, ignore action and close box
        SE.shouting.th.hideForm(formId, shoutIdShort);
    }
    else {
        document.getElementById(SWshoutReplyHiddenFieldId).value = shoutId;
        document.getElementById(SWtextareaId).disabled = true;
        document.getElementById(SWtextareaId).value = document.getElementById(shoutIdShort + "-textarea-id").value;

        SE.shouting.th.hideForm(formId, shoutIdShort);
        window.location.href = document.getElementById(shoutButtonId).href;
    }
}

SE.messages.initReply = function(username) {
    var recipient = jQ("#ShoutWrite h3 input");
    var textarea = jQ("#ShoutWrite textarea");
    recipient.val(username);
    textarea.focus();
};



//////////////////////////////////////////////////////
// adds hover effects to shout
//////////////////////////////////////////////////////
function shoutHover(e, shoutObject, mouseInShout) {
//    if (ltIE7 == true) {
//        if (mouseInShout) {
//            shoutObject.className += " ShoutHover";
//        }
//        else {
//            shoutObject.className = shoutObject.className.replace(" ShoutHover", "");
//        }
//    }
}


//function initForcedRefresh() {
//    if (navigator.userAgent.indexOf("IE") != -1) {
//        var hidReloadObj = document.getElementById("hidReload");
//        if (hidReloadObj != null && hidReloadObj.value != 'initialvalue') {
//            window.navigate(document.location.href);
//        }

//        var prm = Sys.WebForms.PageRequestManager.getInstance();
//        if (prm != null) {
//            prm.add_endRequest(function() { document.getElementById("hidReload").value = "newvalue"; });
//        }
//    }
//}


// friend finder service layout toggle
function toggleVisibility() {
    for (var i = 0; i < arguments.length; i++) {
        jQ("#" + arguments[i]).toggle();
    }
}



/******************************************
/*  SHOUTING
/*****************************************/

function updateRemainingCharCount(textareaId, charCntFieldId) {
    var textarea = jQ("#" + textareaId)[0];
    var changeFlag = false;
    var currentText = textarea.value;
    
    var requiredText = jQ(textarea).attr("requiredText");
    if (requiredText != null && requiredText != "") {
        if (currentText.slice(0, requiredText.length) != requiredText) {
            currentText = currentText.slice(requiredText.length - 1, currentText.length);
            currentText = requiredText + currentText;
            changeFlag = true;
        }
    }

    //	if (currentText.indexOf("\n") != -1)
    //	{
    //		currentText = currentText.replace(/\n/gi, "");
    //		changeFlag = true;
    //	}

    if (typeof SWshoutReplyHiddenFieldId != "undefined" && jQ("#" + SWshoutReplyHiddenFieldId)[0].value) {
        if (jQ(textarea).attr("username") != null && jQ(textarea).attr("username") != "") {
            var replyText = "@" + jQ(textarea).attr("username") + " ";
            if (textarea.value.substring(0, replyText.length) != replyText) {
                var title = jQ("#ShoutWrite .shoutWrite");
                if (title.html() == title.attr("replyToTitle"))
                    title.html(title.attr("defaultTitle"));
            } else if (textarea.value.substring(0, replyText.length) == replyText) {
                var title = jQ("#ShoutWrite .shoutWrite");
                if (title.html() != title.attr("replyToTitle"))
                    title.html(title.attr("replyToTitle"));
            }

        }
    }
    
    remainingCharCount = maxCharCount - currentText.length;
    
    var shoutButton = jQ(".ShoutButton").children("a.button:first");
    var disabledClass = "disabled";
    if (remainingCharCount <= 0 && currentText.length > maxCharCount) {
        if (typeof shoutButton.attr("storedhref") == "undefined") shoutButton.attr("storedHref", shoutButton.attr("href"));
        shoutButton.attr("href", "javascript:void(0);");
        shoutButton.attr("class", shoutButton.attr("class") + " " + disabledClass);
    } else {
        if (shoutButton.attr("href") == "javascript:void(0);" && typeof shoutButton.attr("storedhref") != "undefined") shoutButton.attr("href", shoutButton.attr("storedhref"));
        shoutButton.attr("class", shoutButton.attr("class").replace(" " + disabledClass, ""));
    }

    if (currentText == "" && typeof SWshoutReplyHiddenFieldId != "undefined") {
        jQ("#" + SWshoutReplyHiddenFieldId)[0].value = "";
    }

    if (changeFlag == true) textarea.value = currentText;

    // if number has less than 3 digits we add space in front of him
//    temp = remainingCharCount + "";
//    if (temp.length == 2) temp = "&nbsp;" + temp;
    //    if (temp.length == 1) temp = "&nbsp;&nbsp;" + temp;
    jQ("#" + charCntFieldId).html(remainingCharCount);
}

// fixes empty iFrame problem by resetting uploadFrame's src
function fixUploadIFrame(iFrameId) {
    var frame = document.getElementById(iFrameId);
    if (frame != null) frame.src = frame.src;
}


function setFocusAndText(text, textareaId, charCntFieldId) {
    var textarea = jQ("#" + textareaId);
    textarea.focus();
    textarea.val(text);
    updateRemainingCharCount(textareaId, charCntFieldId);
}

function replyTo(shoutId, userName, jumpToTop, modifyInitialText, modifyHeaderText) {
    if (jumpToTop) scroll(0, 0);
    if (modifyInitialText) jQ("#" + SWtextareaId).attr("requiredText", "@" + userName + " ");
    if (modifyHeaderText) {
        var title = jQ("#ShoutWrite h3");
        if (!title.attr("defaultTitle")) {
            title.attr("defaultTitle", title.html());
        }
        title.attr("replyToTitle", "Reply to: " + userName);
        title.html(title.attr("replyToTitle"));
        jQ("#ShoutWrite textarea").attr("username", userName);
    }
    setFocusAndText("@" + userName + " ", SWtextareaId, SWcharCntFieldId);
    document.getElementById(SWshoutReplyHiddenFieldId).value = shoutId;
}

function reShout(shoutId, userName, jumpToTop, reShoutLabel, reShoutLink) {
    if (jumpToTop) scroll(0, 0);
    var content = jQ(reShoutLink).parent().parent().find("p").clone();
    content.find(".uName").remove();
    var shoutText = htmlDecode(content.html());
    shoutText = userName + " " + shoutText;
    shoutText = jQ.trim(shoutText.replace(/\s+/ig, " ").replace(/<br\s*(\/)*>/ig, "\n"));
    shoutText = replaceNickAndTagLinksWithLinkContent(shoutText);
    shoutText = replaceLinksWithLinkHref(shoutText);
    setFocusAndText(reShoutLabel + " @" + shoutText, SWtextareaId, SWcharCntFieldId);
    jQ("#ShoutWrite textarea").focus();
}

function replaceLinksWithLinkContent(text) {
    return jQ.trim(text.replace(/<a\b[^>]*>(.*?)<\/a>/ig, "$1"));
}

function replaceLinksWithLinkHref(text) {
    return jQ.trim(text.replace(/<a.*\s?href=[\"|'](.*?)[\"|'].*<\/a>/ig, "$1"));
}

function replaceNickAndTagLinksWithLinkContent(text) {
    return jQ.trim(text.replace(/([@#])<a\b[^>]*>(.*?)<\/a>/ig, "$1$2"));
}

function htmlDecode(str) {
    return str.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '\"').replace(/&nbsp;/g, ' ');
}

/******************************************
/*  COLOR PICKER
/*****************************************/

var activeColorPickerPopupId = "";
var activeColorPickerPopupTimerId = 0;
var activeLinkObj;

function rgbConvert(str) {
    if (str.indexOf("#") === -1) {
        str = str.replace(/rgb\(|\)/g, "").split(",");
        str[0] = parseInt(str[0], 10).toString(16);
        str[1] = parseInt(str[1], 10).toString(16);
        str[2] = parseInt(str[2], 10).toString(16);
        str[0] = (str[0].length == 1) ? '0' + str[0] : str[0];
        str[1] = (str[1].length == 1) ? '0' + str[1] : str[1];
        str[2] = (str[2].length == 1) ? '0' + str[2] : str[2];
        str = '#' + str.join("");
    }
    return str.toUpperCase();
}

function colorPickerItemClicked(obj, hiddenFieldId, textBoxId, spanErrorId) {
    var hexColor = rgbConvert(obj.style.backgroundColor);
    document.getElementById(hiddenFieldId).value = hexColor;
    document.getElementById(textBoxId).value = hexColor;
    document.getElementById(textBoxId + "Preview").style.backgroundColor = hexColor;
    hideColorPickerPopup(textBoxId + "Popup");
    document.getElementById(spanErrorId).style.visibility = "hidden";
}

function colorPickerItemHover(obj, previewFieldId) {
    var hexColor = rgbConvert(obj.style.backgroundColor);
    document.getElementById(previewFieldId).style.backgroundColor = hexColor;
}

function showColorPickerPopup(obj, popupId) {
    clearTimeout(activeColorPickerPopupTimerId);
    if (activeColorPickerPopupId != "") hideColorPickerPopup(activeColorPickerPopupId);
    activeColorPickerPopupId = popupId;
    activeLinkObj = obj;

    obj.className += " colorPickerShowButtonActive";
    obj.src = activeLinkObj.src.replace("pickerIcon", "pickerIconActive");

    var popupObj = document.getElementById(popupId);
    if (popupObj != null) {
        popupObj.style.display = "block";
        popupObj.style.position = "absolute";
        popupObj.parentNode.style.position = "relative";
    }
    obj.blur();
}

function hideColorPickerPopup(popupId) {
    try {
        document.getElementById(popupId).style.display = "none";
        document.getElementById(popupId).parentNode.style.position = "";
        activeColorPickerPopupId = "";
        activeLinkObj.className = activeLinkObj.className.replace(" colorPickerShowButtonActive", "");
        activeLinkObj.src = activeLinkObj.src.replace("pickerIconActive", "pickerIcon");
    } catch (err) { }
}

function delayedHideColorPickerPopup() {
    clearTimeout(activeColorPickerPopupTimerId);
    activeColorPickerPopupTimerId = setTimeout('hideColorPickerPopup(activeColorPickerPopupId)', 300);
}

function cancelHideColorPickerPopup() {
    clearTimeout(activeColorPickerPopupTimerId);
}

var colorSubCodes = ["00", "33", "66", "99", "CC", "FF"];

function populateColorPickers() {
    if (typeof ColorPickerIDsArray != "undefined") {
        for (var i = 0; i < ColorPickerIDsArray.length; i += 2) {
            var e = document.getElementById(ColorPickerIDsArray[i]);
            if (e != null) {
                var color = "";
                var html = ColorPickerIDsArray[i + 1];
                var temp = "";

                for (var c1 = 0; c1 < colorSubCodes.length; c1++) {
                    for (var c2 = 0; c2 < colorSubCodes.length; c2++) {
                        for (var c3 = 0; c3 < colorSubCodes.length; c3++) {
                            color = "#" + colorSubCodes[c1] + colorSubCodes[c2] + colorSubCodes[c3];
                            temp += html.replace("colorHexCode", color);
                        }
                    }
                }
                e.innerHTML = temp;
            }
        }
    }
}

/******************************************
/*  PNG FIX FOR ICONS AND SHOUTS
/*****************************************/
function imgLoaded(img) {
    img.onload = null;
    if (typeof ltIE7 != "undefined" && ltIE7 == true && img.tagName == 'IMG' && img.src.match(/\.png$/i) !== null) {
        var shim = '/js/x.gif';
        var src = img.src;
        img.style.width = img.width + "px";
        img.style.height = img.height + "px";
        img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
        img.src = shim;
    }
}

function removeShoutBackgrounds() {
    if (typeof ltIE7 != "undefined" && ltIE7 == true) {
        var elements = document.getElementsByTagName("DIV");
        for (var i = 0; i < elements.length; i++) {
            if (elements[i].currentStyle.backgroundImage.match(/\.png/i) !== null && elements[i].className.indexOf("Shout") != -1) {
                elements[i].style.backgroundImage = 'url(/js/x.gif)';
            }
        }
    }
}

function processDelayedLoadedImages() {
    jQ(".linkAttachmentImg").each(function() {
        jQ(this).attr("src", jQ(this).attr("imgurl"));
        imgLoaded(this);
    });
}
