﻿
// 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();
SE.forms = new Object();
SE.forms.login = new Object();
SE.forms.registration = new Object();


var speedNormal = "normal";
var speedFast = "fast";


jQ(document).ready(function() {
    SE.shouting.addEvents();
});

jQ(window).load(function() {
    processDelayedLoadedImages();
});


// forms
SE.forms.registration.init = function(txtEmailId, txtNickId, txtPassId, txtPassRepeatId, nickErr, passDifferentErr, passRequiredErr, passLengthErr, emailErr, tooShortErr, requiredErr) {
    jQ(document).ready(function() {
        jQ("#" + txtNickId).keyup(function(e) {
            jQ('#Nick').html(jQ("#" + txtNickId).val());
        });

        jQ('form').validate({
            messages: {
                required: requiredErr,
                minlength: jQuery.format(tooShortErr)
            },
            errorPlacement: function(error, element) {
                error.appendTo(element.parent().find(".msgs"));
            },
            errorElement: "li",
            errorClass: "err",
            highlight: function(element, errorClass) {
                jQ(element).parent().removeClass("ok");
                jQ(element).parent().addClass(errorClass);
            },
            unhighlight: function(element, errorClass) {
                jQ(element).parent().removeClass(errorClass);
                jQ(element).parent().addClass("ok");
            }
        });

        jQ("#" + txtEmailId).rules("add", {
            required: true,
            email: true,
            messages: {
                email: emailErr
            }
        });

        jQ("#" + txtNickId).rules("add", {
            required: true,
            minlength: 2
        });

        jQ("#" + txtPassId).rules("add", {
            required: true,
            minlength: 6
        });

        jQ("#" + txtPassRepeatId).rules("add", {
            required: true,
            equalTo: '#' + txtPassId,
            messages: {
                equalTo: passDifferentErr
            }
        });

        jQ('.submit').click(function() {
            return jQ('form').valid();
        });

        //        jQ('input.passwd:first').keyup(function(){
        //            jQ('.passwdStrength:first').html(passwordStrengthLabel + ' ' + passwordStrength(jQ('input.passwd:first').val(),''))
        //        });

        jQ("#" + txtEmailId).focus();
    });
}

SE.forms.login.init = function(txtEmailId, txtPassId, txtNingEmailId, emailErr, tooShortErr, requiredErr) {
    jQ(document).ready(function() {

        jQ('form').validate({
            messages: {
                required: requiredErr,
                minlength: jQuery.format(tooShortErr)
            },
            errorPlacement: function(error, element) {
                error.appendTo(element.parent().find(".msgs"));
            },
            errorElement: "li",
            errorClass: "err",
            highlight: function(element, errorClass) {
                jQ(element).parent().removeClass("ok");
                jQ(element).parent().addClass(errorClass);
            },
            unhighlight: function(element, errorClass) {
                jQ(element).parent().removeClass(errorClass);
                jQ(element).parent().addClass("ok");
            }
        });

        jQ("#" + txtEmailId).rules("add", {
            required: true
        });

        jQ("#" + txtPassId).rules("add", {
            required: true,
            minlength: 6
        });
    });
}



// 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);
}

SE.effects.openTab = function(boxesToClose, boxesToOpen, obj, activeClass) {
    var justOpen = jQ(boxesToClose).is(':visible');
    jQ(boxesToClose).hide();
    if (justOpen == true) {
        jQ(boxesToOpen).show();
    } else {
        jQ(boxesToOpen).slideDown();
    }
    if (activeClass != "") {
        jQ("ul.tabs li").removeClass(activeClass);
        jQ(obj).parent().addClass(activeClass);
    }
    obj.blur();
}

// GUI alerts
SE.alerts.displayMessage = function(boxId, text, imagePath, msgTimeout) {
    if (text != "") {
        var msgId = Math.ceil(100 * Math.random());
        var checkmark = "<div id='" + msgId + "' style='display:none;' class='msg'><span><img src='" + imagePath + "' alt='' style='position:relative; top:2px;' />&nbsp;&nbsp;";
        var box = jQ("#" + boxId);
        box.append(checkmark + text + "</span></div>");
        if (box.is(":hidden")) {
            box.slideDown(speedFast, function() {
                SE.effects.showSlide("#" + msgId);
                jQ("#" + msgId + " span").show();
            });
        } else {
            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);
    jQ("#" + msgId + " span").slideUp(speedFast, function() {
        SE.alerts.remove(boxId, msgId);
    }); 
}

SE.alerts.remove = function(boxId, msgId) {
    jQ("#" + msgId).remove();
    if (jQ("#" + boxId).children().length == 0) {
        jQ("#" + boxId).slideUp(speedFast);
    }
}


//////////////////////////////////////////////////////
// Manage toolbar
//////////////////////////////////////////////////////
jQ(document).ready(function() {
    jQ("#Manage .nav li").hover(
			function() { jQ("ul", this).fadeIn("fast"); },
			function() { }
		);
    if (document.all) {
        jQ("#Manage .nav li").hoverClass("sfHover");
    }


    if (typeof ltIE7 == "undefined") {
        if (jQ.cookie('ManageToolbar') != 'hide') {
            jQ('#Manage').show();
        }
        else {
            jQ('#openManage').show();
        }
    }
});

jQ.fn.hoverClass = function(c) {
    return this.each(function() {
        jQ(this).hover(
				function() { jQ(this).addClass(c); },
				function() { jQ(this).removeClass(c); }
			);
    });
};

function manageToolbarShow(obj) {
    jQ(obj).hide();
    jQ('#Manage').show();
    jQ.cookie('ManageToolbar', null);
}

function manageToolbarHide(obj) {
    jQ(obj).parent().slideUp();
    jQ('#openManage').show();
    jQ.cookie('ManageToolbar', 'hide');

}

//////////////////////////////////////////////////////
// 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.toggleLnkAttBox = function() {
    var linkAttach = jQ('.shoutWrite .attLnk');
    var photoAttach = jQ('.shoutWrite .attImg');

    if (linkAttach.is(':visible')) {
        linkAttach.slideUp(speedFast);
        jQ('.shoutWrite .linkAtt').removeClass("active");
    }
    else {
        var frame = document.getElementById('uploadIframe');
        if (frame.contentDocument)
            frame.contentDocument.getElementById('form1').reset();
        else if (frame.contentWindow && frame.contentWindow.document)
            frame.contentWindow.document.getElementById('form1').reset();
        else if (frame.document)
            frame.document.getElementById('form1').reset();
        jQ('.shoutWrite .photoAtt').removeClass("active");
        if (photoAttach.is(':visible')) {
            photoAttach.slideUp(speedFast, function() {
                linkAttach.slideDown(speedFast);
            });
        } else {
            linkAttach.slideDown(speedFast);
        }
        jQ('.shoutWrite .linkAtt').addClass("active");
    }
}

SE.shouting.toggleImgAttBox = function() {
    var linkAttach = jQ('.shoutWrite .attLnk');
    var photoAttach = jQ('.shoutWrite .attImg');

    if (photoAttach.is(':visible')) {
        photoAttach.slideUp(speedFast);
        jQ('.shoutWrite .photoAtt').removeClass("active");
    }
    else {
        if (linkAttach.is(':visible')) {
            var linkbox = linkAttach.children('input');
            linkbox.val('');
            linkbox.focus();
            linkbox.blur();
            jQ('.shoutWrite .linkAtt').removeClass("active");
            linkAttach.slideUp(speedFast, function() {
                photoAttach.slideDown(speedFast);
            });
        } else {
            photoAttach.slideDown(speedFast);
        }
        jQ('.shoutWrite .photoAtt').addClass("active");
    }
}

SE.shouting.toggleLocAttBox = function() {
    var locationAttach = jQ('.shoutWrite .attLoc');
    if (locationAttach.is(':visible')) {
        locationAttach.slideUp(speedFast);
        jQ('.shoutWrite .locationAtt').removeClass("active");
    }
    else {
        locationAttach.slideDown(speedFast, function() {
//            if (bingMapOptions) {
//                SE.map.load(bingMapOptions, true);
//            }
        });
        jQ('.shoutWrite .locationAtt').addClass("active");
    }
}

SE.shouting.th.showHiddenReplies = function(obj) {
    var hdnReplies = jQ(obj).parent().parent().find(".hdnReplies");
    if (jQ.browser.msie && parseInt(jQ.browser.version) < 8) {
        jQ(obj).parent().hide();
        hdnReplies.show();
        jQ(".shoutBox").hide().show();
    } else {
        SE.effects.hideSlide(jQ(obj).parent());
        SE.effects.showSlide(hdnReplies);
    }
}


SE.shouting.th.hideForm = function(formId) {
    var inputBox = jQ("#" + formId + " textarea");
    var form = jQ("#" + formId);
    form.removeClass("expanded");
    form.removeClass("active");
    if (form.siblings().length == 0) {
        form.parent().hide();
    }
    inputBox.blur();
    inputBox.val(inputBox.attr("watermarkText"));
    inputBox.addClass("watermark");
}

SE.shouting.th.initForm = function(obj, formId, shoutId, username, watermarkText, onlyIfClosed) {
    if (onlyIfClosed && jQ("#" + formId).hasClass("expanded")) {
        return;
    }
    var inputBox = jQ("#Txt-" + shoutId);
    jQ("#ThBox-" + shoutId).parent().show();
    var requiredText = "@" + username + " ";
    inputBox.attr("requiredText", requiredText);
    if (jQ("#" + formId).hasClass("expanded")) {

    }
    else {
        inputBox.attr("watermarkText", watermarkText);
        inputBox.removeClass("watermark");
        inputBox.keydown(function(e) {
            if (e.which == 27) {
                SE.shouting.th.hideForm(formId);
            }
        });

        jQ("#" + formId).addClass("expanded");
        jQ("#" + formId).addClass("active");
    }
    inputBox.val("");
    setFocusAndText(requiredText, "Txt-" + shoutId, "Cnt-" + shoutId);

    if (jQ.browser.msie && parseInt(jQ.browser.version) < 8) {
        jQ("#" + formId).parent().parent().next().hide().show();
    }
}

SE.shouting.th.submitReply = function(obj, formId, shoutId) {
    var inputBox = jQ("#Txt-" + shoutId);
    var replyText = inputBox.val();
    var requiredText = inputBox.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);
    }
    else {
        SE.shouting.displayProgressBar(obj, true);
        jQ("#" + SWshoutReplyHiddenFieldId).val(shoutId);
        document.getElementById(SWtextareaId).disabled = true;
        jQ("#" + SWtextareaId).val(replyText);
        var inputBox = jQ("#" + formId + " textarea")[0].disabled = true;

        //SE.shouting.th.hideForm(formId);
        var shoutBtn = jQ("#" + shoutButtonId);
        var href = shoutBtn.attr("href");
        shoutBtn.parent().find("a").attr("onclick", "").attr("href", "javascript:void(0)");
        window.location.href = href;
    }
}

SE.shouting.displayProgressBar = function(obj, disableBtn) {
    if (disableBtn) {
        jQ(obj).attr("href", "javascript:void(0)");
        jQ(obj).attr("onclick", "");
    }
    jQ(obj).html("<img alt='' src='/img/busy.gif' />");
}

SE.messages.initReply = function(username) {
    var recipient = jQ(".shoutWrite h3 input");
    var textarea = jQ(".shoutWrite textarea");
    recipient.val(username);
	scroll(0, 0);
    textarea.focus();
};


/******************************************
/*  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 h3");
                if (title.html() == title.attr("replyToTitle"))
                    title.html(title.attr("defaultTitle"));
            } else if (textarea.value.substring(0, replyText.length) == replyText) {
                var title = jQ(".shoutWrite h3");
                if (title.html() != title.attr("replyToTitle"))
                    title.html(title.attr("replyToTitle"));
            }

        }
    }
    remainingCharCount = maxCharCount - currentText.length;
    var shoutButton = jQ(".shoutDo").children("a.btn");
    var disabledClass = "disabledBtn";
    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);
        shoutButton.addClass(disabledClass);
    } else {
        shoutButton.removeClass(disabledClass);
//        if (shoutButton.attr("href") == "javascript:void(0);" && typeof shoutButton.attr("storedhref") != "undefined") {
//            shoutButton.attr("href", shoutButton.attr("storedhref"));
//            shoutButton.removeClass(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
    //    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, headerText) {
    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", headerText + " " + 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().parent().parent().find("p:first").clone();
    content.find(".nick").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, ' ');
}



/******************************************
/*  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 processDelayedLoadedImages() {
    jQ(".linkAttachmentImg").each(function() {
        jQ(this).attr("src", jQ(this).attr("imgurl"));
        imgLoaded(this);
    });
}
