﻿$(document).ready(function () {
    //input fix for shit IE 7
    if ($.browser.msie && $.browser.version == "7.0") {
        $('.headerSearch input[type="text"]').css('width', '130px');
        $('.SearchDropDown').css('top', '0px');
        $('input[type="text"]').each(function (index) {
            if ($(this).attr('name') != "query" && $(this).attr('id') != "LoginPassword" && $(this).attr('id') != "UserName") {
                $(this).css('background-image', 'none');
                $(this).css('background-color', 'transparent');
                $(this).wrap('<div class="InputWapperBase InputWapper' + $(this).attr('size') + '" />');
            }
        });
    }
    //Menu Admin
    $("#AdminMenu").click(function () {
        $(this).parent().find(".SubNavihMenu").slideDown('fast').show();

        $(this).parent().hover(function () { }, function () {
            $(this).parent().find(".SubNavihMenu").hide();
        });

    }).click(function () {
        // $(this).addClass("SubNavihMenuHover");
    });

    $(".SubNavihMenu").hover(function () { $("#AdminMenu").addClass("SubNavihMenuHover"); }, function () { $("#AdminMenu").removeClass("SubNavihMenuHover"); });

    $('#ShowDropDown').click(function () {
        $('#SearchDropDown').toggle();
    });
    $('#SearchDropDown').mouseleave(function () { $('#SearchDropDown').hide(); });

    //search box 
    $('#Query').click(function () { $('#Query').val(''); });

    $('input[name="searchEntity"]').change(function () {
        if ($(this).val() == "All")
            $('#Query').val($(this).attr('id'));
        else
            $('#Query').val($(this).val());
    });
    //Unauthorized?
    if (BT.Common.getQuerystring("unauth", 0, window.location.href) == 1) {
        $('<div id="UnauthorizedDialog"><span>Du har inte behörighet till den begärda funktionen.</span></div>').dialog({
            autoOpen: true,
            modal: true,
            resizable: false,
            draggable: false,
            width: 320,
            minHeight: 20,
            closeOnEscape: true,
            buttons: {
                "Ok": function () {
                    window.location.href = window.location.href.replace("&unauth=1", "").replace("?unauth=1", "");
                }
            }
        });
    }

    //Handle addresses for sections
    $.address.changed = false;

    $("a[rel^='section:']").address(function () {
        $.address.value($(this).attr("rel").replace("section:", ""));
    }).click(function () {
        if (!$.address.changed && $.address.value() == $(this).attr("rel").replace("section:", "")) {
            $(this).parent().next("dd").slideToggle(300);
        }
        $.address.changed = false;
    });

    $.address.change(function (e) {
        $.address.changed = true;
        if (e.pathNames.length == 1) {
            $a = $("a[rel='section:/" + e.pathNames[0] + "']");
            if ($a.length > 0) {
                $("input[name='_Section']").each(function () { $(this).val(e.pathNames[0]); });
                $a.parent().next("dd").parent().children("dd").hide().end().end().slideToggle(300);
            }
        }
    });

    //--- Confirmation functionality ---
    $(".Confirm").each(function () {
        if ($(this).attr("onclick")) {
            $(this).data("onclick", $(this).attr("onclick")).removeAttr("onclick");
        }

        $(this).bind("click", function (e) {
            $buttonConfirm = $(this);

            //Render Dialog
            $('<div id="DialogConfirm"><div><a id="closeconfirm" class="FloatRight CloseConfirm" href="#"></a><h4>' + $buttonConfirm.attr("title") + '</h4><hr class="Confirmseparator"/><a href="javascript://" class="Button ButtonLarge OK"><span><span class="ButtonIcon ConfirmYes">Ja</span></span></a><a href="javascript://" class="Button ButtonLarge CANCEL"><span><span class="ButtonIcon ConfirmNo">Nej</span></span></a></div></div>')
				    .width($(document).width())
				    .height($(document).height())
				    .find("a.OK").click(function () {
				        $("#DialogConfirm").remove();
				        var val = null;
				        if ($buttonConfirm.data("onclick")) {
				            val = eval($buttonConfirm.data("onclick")).call();
				        }
				        if ($buttonConfirm[0].tagName.toLowerCase() == "a") {
				            if (val !== false) {
				                window.location = $buttonConfirm.attr("href");
				            }
				        }
				        else {
				            if (val !== false) {
				                $buttonConfirm.closest("form").submit();
				            }
				        }
				    })
				    .end().find("a.CANCEL").click(function () {
				        $("#DialogConfirm").remove();
				    })
				    .end().find("a.CloseConfirm").click(function () {
				        $("#DialogConfirm").remove();
				    }).end()
				    .appendTo("body")
				    .find("div")
					    .center({ withScrolling: false });

            e.preventDefault();
            return false;
        });
    });
    //--- /Confirmation functionality ---

    //---- Messages ---
    window.BT.MessageCheck();
    window.setInterval(window.BT.MessageCheck, 90000);
    //--- /Messages ---

    //----Basetool 2
    $('<div id="DialogBT2"><a class="CloseBoxIcon FloatRight"><img src="/images/red/close-box-icon.png" /></a>För att administrera ditt eller dina produktblad behöver du besöka Basetool version 2<a class="Go" href="http://vastsverige.basetool.se/start/default.aspx"><img src="/images/basetool2_prompt.png" /><span>Till Basetool 2</span></a></div>')
    .css("overflow", "visible")
    .dialog({
        autoOpen: false,
        draggable: false,
        modal: true,
        resizable: false,
        width: 500
    }).find("a.CloseBoxIcon").click(function () { $("#DialogBT2").dialog('close'); });

    $("#BT2").click(function (e) {
        e.preventDefault();
        $("#DialogBT2").dialog('open');
    });
    //

    //--- Handel globalization  ---
    var selectedCulture = window.BT.Settings.UserCulture;
    // Set culture from select list
    $.preferCulture(selectedCulture);
    $.culture = jQuery.cultures[selectedCulture];
    $.datepicker.setDefaults($.datepicker.regional[selectedCulture]);
    //--- /Handel globalization  ---
});

window.BT.MessageCheck = function () {
    window.BT.Ajax.GetJSON("/ajax/user/currentuserstatus", {}, function (json) {
        $("#UserName").text(json.BTUser);
        $("#MessagesCount").text(json.Messages);
        if (json.Contacts != "") {
            $("#RequestCount").show().find("a").text(json.Contacts);
        }
    }, null, false);
};

window.BT.Form = function (name, exclude) {
    var _Name = name;
    var _Exclude = exclude;
    var _Hash;

    this.IsDirty = function () {
        var hash = GetHash();
        var equal = (hash == _Hash);
        _Hash = hash;
        return !equal;
    };

    function GetHash() {
        var md5 = "";
        $("form[name='" + _Name + "'] input[type='text'], form[name='" + _Name + "'] input[type='hidden'], form[name='" + _Name + "'] input:checkbox:checked, form[name='" + _Name + "'] select, form[name='" + _Name + "'] textarea").each(function () {
            if (_Exclude.indexOf($(this).attr("name")) == -1)
                md5 += $(this).val();
        });
        return b64_md5(md5);
    }

    _Hash = GetHash();
}

window.BT.Ajax = new function () {
    var _Self = this;
    var _SessionId = $.cookie("vstc");
    var _ErrorMsg = "";
    var _InternalJSON = typeof (JSON) != "undefined" && typeof (JSON.parse) != "undefined";

    $.ajaxSetup({ beforeSend: Ajax_BeforeSend });

    this.SetErrorMsg = function (msg) { _ErrorMsg = msg; };

    this.Load = function (selector, path, params, success, errorMsg) {
        $(selector).load(path, params, success);
    };

    this.GetJSON = function (path, params, success, errorMsg, post) {
        var url = this.GetAjaxUrl(path);
        var callParams = {
            url: url,
            traditional: true,
            processData: true,
            data: params,
            dataType: "json",
            error: function (request, status, error) { Ajax_Error(request, status, error, errorMsg); },
            dataFilter: function (data, type) {
                if (_InternalJSON) {
                    return JSON.parse(data, DataRevive);
                }
                return eval("(" + data + ")");
            }
        };

        if (post) {
            callParams.type = "POST";
        }

        if (success && success != null) {
            callParams.success = success;
        }

        $.ajax(callParams);
    };

    this.Post = function (path, params, success, errorMsg) {
        var url = this.GetAjaxUrl(path);
        var callParams = {
            url: url,
            data: params,
            type: "POST",
            error: function (request, status, error) { Ajax_Error(request, status, error, errorMsg); }
        };
        if (success && success != null) {
            callParams.success = success;
        }
        $.ajax(callParams);
    };

    this.GetAjaxUrl = function () //path, secure
    {
        var path = arguments[0];
        return path;
    };

    function Ajax_BeforeSend(request) {
        request.setRequestHeader("x-vstc", _SessionId);
    }

    function Ajax_Error(request, status, error, msg) {
        $.loaderClear();
        if (msg != null && msg != "") {
            $("#JsError").css("display", "block").html(msg);
            setTimeout(function () { $("#JsError").css("display", "none"); }, 10000);
        }
    }

    function DataRevive(key, value) {
        var a;
        if (typeof value === 'string') {
            a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/.exec(value);
            if (a) {
                return new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
            }
        }
        return value;
    }
}

window.BT.Truncate = function (input, length, appendDots) {
    var text = input;
    if (input.length <= length)
        return input;

    input = input.substring(0, (appendDots) ? length - 3 : length);

    if (appendDots && text.length > length)
        input = input + "...";

    return input;
}

//Function For String Formatting
String.prototype.format = function () {
    var pattern = /\{\d+\}/g;
    var args = arguments;
    return this.replace(pattern, function (capture) { return args[capture.match(/\d+/)]; });
}

window.BT.GetURL = function() {
    var completeURL = window.location.href;
    var URl = completeURL.split("?");
    return URl[0];
}
window.BT.AgreementPopup = function (type) {

    if (type == "Comments") {
        window.open('/Agreements/Comments.htm', 'CommentsAgreements', 'width=600,height=400,menubar=yes,status=yes,scrollbars=yes,resizable=yes');
    }
    else if (type == 'Registration') {
        window.open('/Agreements/Register.htm', 'RegistrationAgreements', 'width=600,height=400,menubar=yes,status=yes,scrollbars=yes,resizable=yes');
    }
    else if (type == 'groups') {
        window.open('/Agreements/groups.htm', 'groupsAgreements', 'width=600,height=400,menubar=yes,status=yes,scrollbars=yes,resizable=yes');
    }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////To solve the submit form twice on IE http://www.webdeveloper.com/forum/archive/index.php/t-107732.html
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.BT.pauseEvent = function (e) {
    if ($.browser.msie) {
        var E = (window.event) ? event : e;
        if (!E) return false;
        if (E.stopPropagation) E.stopPropagation();
        else if (E.cancelBubble) E.cancelBubble = true;
        if (E.preventDefault) E.preventDefault();
        else if (E.returnValue) E.returnValue = false;
        else return false;
    }
}


