/// <reference path="../../../Scripts/jquery-1.2.6.js" />
/// <reference path="../../../Scripts/json2.min.js" />
/// <reference path="../../../Scripts/plugins/jquery.cookie.js" />
/// <reference path="../../../Scripts/Global.js" />
var ERROR_CAPTCHA       = 1000;
var ERROR_WRONG_PIN     = 1001;
var ERROR_NOT_FOUND_WU = 1002;
var ERROR_NOT_APPROVED = 1003;
var ERROR_NO = 0;
var ERROR_EXIST_MAIL = 1007;

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function CloseRightSubmenu(e) {
    var p = $(this).position();
   
    if (InRect(p.left, p.top, $(this).width() + 4, $(this).height() + 4, e.pageX, e.pageY)) {
        $(this).unbind("mouseout", CloseRightSubmenu);
        $(this).slideUp(200, function() {
            $(this).parent().prev().children().removeClass("active").removeClass("ui-open");
        });

    }
}



function ResetAjaxMsgPanel() {
    $("#ajaxMsgPanel").css("left", "0px");
    $("#ajaxMsgPanel").css("top", "0px");
    $("#ajaxMsgPanel").css("width", "100%");
}

  
function getCaptcha(img, fc, loadingTxt) {

    var pos = $(img).position();
    $("#ajaxMsgPanel").css("left",$.browser.msie ?  pos.left :   pos.left + 12);
    $("#ajaxMsgPanel").css("top", pos.top + 5);
    $("#ajaxMsgPanel").width($(img).width() - 10);
    $("#ajaxMsgPanel div:first").width($(img).width() - 20);



    $(img).Callback(fc, { success: function(d) {
        if (d.IsError) {
            alert(d.Message);
            return;
        }

        $(img).attr('src', d.Message);
    },
        loadingMsg: loadingTxt
    });
}

function HistoryEnable() {
    if (history && history.length > 0) {
        return true;
    }
    return false;


}
function HistoryBack() {
    if (HistoryEnable) {
        if (history.go) {
            history.go(-1);
        }
    }
}
function OnSearch(language) {
    var txt = $("#txtSearch").val();
    if (txt.length > 0) {
        var enc = encodeURIComponent || escape;
        var srch = enc(txt);
        window.location = "/search.htm?language=" + language + "&search=" + srch;
    } else {
       $("#txtSearch").focus();
    }

}
function ChangeLanguage(newLang, oldLanguage, clb) {
    if (newLang == oldLanguage) return;
    var dat = [];
   
    var enc = encodeURIComponent || escape
    dat.push("NewLanguage=" + enc(newLang));
    dat.push("OldLanguage=" + enc(oldLanguage));
    dat.push("Path=" + enc(window.location.toString()));

     $.Callback(clb, {
         loadingMsg: "Promena pisma/jezika...",
         data: dat.join("&").replace(/%20/g, "+"),
         success: function(json) {
             try {
                 if (!json.IsError && json.Message) {
                     window.location = json.Message;
                 }
             } catch (ex) { }
         }

     });
}
$(document).ready(function() {

    window.IE6 = true; //DEBUG
    if ($.browser.msie) {
        if ($.browser.version.substr(0, 1) == "6") {
            window.IE6 = true; ///jbm..ti !"&%%#"&
        }
    }


    window.language = trim($("#page").attr("lang"));

    $("#left_menu .mn-head").bind("mouseover", function() {
        if (!$(this).hasClass("ui-open")) {
            $("#left_menu .ui-open").parent().next().find("ul:first").slideUp("slow", function() {
                $(this).parent().prev().children().removeClass("active").removeClass("ui-open");
            });
            $(this).addClass("ui-open").addClass("active").parent().next().find("ul:first").slideDown("slow", function() {
                $(this).bind("mouseout", CloseRightSubmenu);
            });
        }

        //.navigate - back
    })
    if (HistoryEnable()) {
        $("div.navigate-back").show();
        $("div.navigate-back").addClass("navigate-back-show");

    }
    $("#txtSearch").focus();
    $("#txtSearch").keydown(function(e) {
        if (e.keyCode == 13) {
            OnSearch($("#txtSearch").attr("lang"));
        }
    })
    var lbop = {};
    lbop.CssRoot = "/App_Shared/images/lightbox/";
    lbop.imageLoading = lbop.CssRoot + 'loading.gif';
    lbop.overlayBgColor = '#000000';
    lbop.overlayOpacity = 0.6;

    lbop.containerResizeSpeed = 350;
    switch (window.language) {
        case "sr-Cyrl-CS":
            lbop.imageBtnClose = lbop.CssRoot + 'close-sr-Cyrl-CS.gif';
            lbop.imageBtnPrev = lbop.CssRoot + 'prev-sr-Cyrl-CS.gif';
            lbop.imageBtnNext = lbop.CssRoot + 'next-sr-Cyrl-CS.gif';
            lbop.txtImage = 'Слика';
            lbop.txtOf = 'од';
            break;
        case "sr-Latn-CS":
            lbop.imageBtnClose = lbop.CssRoot + 'close-sr-Latn-CS.gif';
            lbop.imageBtnPrev = lbop.CssRoot + 'prev-sr-Latn-CS.gif';
            lbop.imageBtnNext = lbop.CssRoot + 'next-sr-Latn-CS.gif';
            lbop.txtImage = 'Slika';
            lbop.txtOf = 'od';
            break;
        case "en-GB":
            lbop.imageBtnClose = lbop.CssRoot + 'close-en-GB.gif';
            lbop.imageBtnPrev = lbop.CssRoot + 'prev-en-GB.gif';
            lbop.imageBtnNext = lbop.CssRoot + 'next-en-GB.gif';
            lbop.txtImage = 'Image';
            lbop.txtOf = 'of';
            break;
    }

    if ($('a[rel*=popup]').lightBox) {
        $('a[rel*=popup]').lightBox(lbop);
    }

    try {
        if ($("#commentContainer").length == 0) {
            allowComment = false;
        } else {
            allowComment = true;
        }
    } catch (e) { allowComment = false; }

    if (allowComment == true) {
        bbcodeOpt =
        {
            nameSpace: "bbcode",
            onTab: { keepDefault: false, replaceWith: '\t' },
            previewParserPath: "/Themes/JKPPU/Content/markitup/prv/previewBBCode.aspx",
            markupSet: [
		{ name: 'Podebljaj', key: 'B', openWith: '[b]', closeWith: '[/b]' },
		{ name: 'Kurziv', key: 'I', openWith: '[i]', closeWith: '[/i]' },
		{ name: 'Podvuci', key: 'U', openWith: '[u]', closeWith: '[/u]' },
		{ name: 'Precrtaj', key: 'S', openWith: '[s]', closeWith: '[/s]' },
        { separator: '---------------' },
    	{ name: 'Link', key: 'L', openWith: '[url=[![Url]!]]', closeWith: '[/url]', placeHolder: SR_AddTextComment },
      { separator: '---------------' },
      { name: 'Colors', openWith: '[color=[![Color]!]]', closeWith: '[/color]', dropMenu: [
          { name: 'Yellow', openWith: '[color=#FFCC00]', closeWith: '[/color]', className: "col1-1" },
          { name: 'Orange', openWith: '[color=#FFA500]', closeWith: '[/color]', className: "col1-2" },
          { name: 'Red', openWith: '[color=#FF0000]', closeWith: '[/color]', className: "col1-3" },
          { name: 'Blue', openWith: '[color=#000099]', closeWith: '[/color]', className: "col2-1" },
          { name: 'Purple', openWith: '[color=#800080]', closeWith: '[/color]', className: "col2-2" },
          { name: 'Green', openWith: '[color=#008000]', closeWith: '[/color]', className: "col2-3" },
          { name: 'Green1', openWith: '[color=#666633]', closeWith: '[/color]', className: "col3-1" },
          { name: 'Gray', openWith: '[color=#808080]', closeWith: '[/color]', className: "col3-2" },
          { name: 'Black', openWith: '[color=#000000]', closeWith: '[/color]', className: "col3-3" }
      ]
      },

            /*
            { separator: '---------------' },
            { name: 'Bulleted list', openWith: '[list]\n', closeWith: '\n[/list]' },
            { name: 'Numeric list', openWith: '[list=1]\n', closeWith: '\n[/list]' },
            { name: 'List item', openWith: '[*] ' },
            { separator: '---------------' },
            { name: 'Citat', openWith: '[quote]', closeWith: '[/quote]' },
            { name: 'Code', openWith: '[code]', closeWith: '[/code]' },
            */
       {separator: '---------------' },

            //(/\[(.*?)\]/g, "") 
		{name: 'Obriši', className: 'clean', replaceWith: function(markitup) { return markitup.selection.replace(/\[(.*?)\]/g, "") } },
		{ name: 'Izgled', className: 'preview', call: 'preview' }
     	]
        }

        $(".commentToggle").toggle(
         function() {
             showCommentFrame();
         }, function() {
             hideCommentFrame();
         }
         );

        $('#txtComment').markItUp(bbcodeOpt);
        $("#SendComment").click(function() {
            var isValid = true;
            if (!window.IE6) {
                isValid = $("#commentContainer").valid();
            } else {
                $(".errorFrame label").parent().hide();
                $(".errorFrame").hide();
                var len = 0;
                var len = $.trim($("#txtName").val()).length;
                if (len == 0 || len > 150) {
                    isValid = false;
                    showError(".errorFrame", "txtName");

                }

                len = $.trim($("#txtEmail").val()).length;
                if (len == 0 || len > 150 || !validMail($.trim($("#txtEmail").val()))) {
                    isValid = false;
                    showError(".errorFrame", "txtEmail");

                }
                len = $.trim($("#txtComment").val()).length;
                if (len == 0 || len > 2048) {
                    isValid = false;
                    showError(".errorFrame", "txtComment");

                }
                len = $.trim($("#txtCaptcha").val()).length;
                if (len < 3 || len > 8) {
                    isValid = false;
                    showError(".errorFrame", "txtCaptcha");

                }

            }
            // } else {



            //  }
            if (isValid) {
                var dat = [];

                dat.push("ContentId=" + pageId);
                dat.push("Captcha=" + encodeURIComponent($("#txtCaptcha").val()));
                dat.push("Name=" + encodeURIComponent($("#txtName").val()));
                dat.push("Email=" + encodeURIComponent($("#txtEmail").val()));
                dat.push("Comment=" + encodeURIComponent($("#txtComment").val()));

                $.Callback($("#commentContainer").attr("action"), {
                    loadingMsg: SR_POST_COMMENT,
                    success: function(data) {
                        if (data.IsError) {
                            alert(data.Message);
                            return;
                        } else {
                            alert(SR_COMMENT_SEND_OK);
                        }
                        var fixIE6 = false;
                        if ($.browser.msie) {
                            if ($.browser.version.substr(0, 1) == "6") {
                                fixIE6 = true;
                            }
                        }
                        if (fixIE6) {
                            // window.location.href = window.location.href;
                            return;
                        }
                        hideCommentFrame();
                        try {
                            if (!window.IE6) {
                                $("#commentContainer").reset();
                            } else {
                                $("#txtComment").val("");
                                $("#txtCaptcha").val("");

                            }
                        } catch (ex) { }


                    },
                    data: dat.join("&").replace(/%20/g, "+")
                });
            }


        });
        $("#NewCaptcha").click(function() { getCaptcha('#captchaImage', newCapc, SR_LOADING); });


    }

});

var commentValidator;

function initCommentValidator() {
    if (!window.IE6) {
        var __errorFrame = $(".errorFrame");
        commentValidator = $("#commentContainer").validate({
            errorContainer: __errorFrame,
            errorLabelContainer: $("ol", __errorFrame),
            wrapper: 'li',
            meta: "validate"
        });
    }

}
var isInitComment = false;
function showCommentFrame() {
    if (!isInitComment) {

        initCommentValidator();
        getCaptcha('#captchaImage', newCapc, SR_LOADING);
        isInitComment = true;

    }

    $("#commentContainer").show();
    $("#txtName").focus();
    $.scrollTo('#commentContainer', 800);

}
function hideCommentFrame() {
    $("#commentContainer").hide();
}
function showError(sel, fld) {
    $(sel + " label[for='" + fld + "']").parent().show();
    $(".errorFrame").show();
}
function validMail(value) {
  return   /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}