﻿/*
*  Indaco Systems JS Framework
*/

//#region Namespace definition
var INDACO = INDACO || {};

INDACO.namespace = function (ns_string) {
    var parts = ns_string.split('.'), parent = INDACO, i;

    // strip redundant leading global
    if (parts[0] === "INDACO") {
        parts = parts.slice(1);
    }

    for (i = 0; i < parts.length; i += 1) {
        // create a property if it doesn't exist
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
    return parent;
};

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function (str) {
        return this.slice(-str.length) == str;
    };
}

INDACO.serialize = function (form) {
    return jQuery.param(this.serializeArray(form));
};
INDACO.serializeArray = function (form) {
    return form.map(function () {
        return this.elements ? jQuery.makeArray(this.elements) : this;
    })

		.filter(function () {
		    var rselectTextarea = /^(?:select|textarea)/i, rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i;
		    return this.name && !this.disabled && !jQuery(this).hasClass('placeholder') &&
				(this.checked || rselectTextarea.test(this.nodeName) ||
					rinput.test(this.type));
		})
		.map(function (i, elem) {
		    var val = jQuery(this).val();
		    var rCRLF = /\r?\n/g;

		    return val == null ?
				null :
				jQuery.isArray(val) ?
					jQuery.map(val, function (val, i) {
					    return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
					}) :
					{ name: elem.name, value: val.replace(rCRLF, "\r\n") };
		}).get();
};
INDACO.datePickerMinMax = function () {
    if (typeof $(this).data("datePickerOpts") == "object") {
        minOrMax = $(this).data("datePickerOpts").minOrMax;
        theOther = $($(this).data("datePickerOpts").otherId);
        thatValue = $(this).val();
        if (theOther.val()) {
            var dateFormat = theOther.datepicker("option", "dateFormat");
            theOtherValue = $.datepicker.parseDate(dateFormat, theOther.val().split(" ")[0]);
            $(this).datepicker('option', minOrMax, theOtherValue);
            $(this).val(thatValue);
        }
        else {
            $(this).datepicker('option', minOrMax, null);
            $(this).val(thatValue);
        }
    }
};
INDACO.isCharacterKeyPress = function isCharacterKeyPress(evt) {
    if (typeof evt.which == "undefined") {
        // This is IE, which only fires keypress events for printable keys
        return true;
    } else if (typeof evt.which == "number" && evt.which > 0) {
        // In other browsers except old versions of WebKit, evt.which is
        // only greater than zero if the keypress is a printable key.
        // We need to filter out backspace and ctrl/alt/meta key combinations
        return !evt.ctrlKey && !evt.metaKey && !evt.altKey;
    }
    return false;
};
INDACO.trimToRoot = function trimToRoot(url) {
    if (url != undefined && url != "") {
        url = url.replace("http://", "");
        var arr = url.split("/");
        var found = false;
        var prepUrl = "http://";
        $.each(arr, function (index, val) {
            var self = this;
            $.each(INDACO.langArr, function () {
                if (self.toLowerCase() == this.toLowerCase()) {
                    found = true;
                    return false;
                }
            });
            prepUrl += self + "/";
            if (found) {
                return false;
            }
        });
        return prepUrl;
    }
};
INDACO.modQuery = function modQuery(url, key, value) {
    if (url != undefined && url != "" && key != undefined && key != "") {
        //#region URL explode
        var urlArr = url.split("?");
        var baseUrl = urlArr[0];
        var query = urlArr[1].split("#")[0];
        var sharpData = urlArr[1].split("#")[1];
        var queryPairs = query.split("&");
        var initialDictionary = [];
        $.each(queryPairs, function () {
            pair = this.split("=");
            initialDictionary.push(pair);
        });
        //#endregion
        //#region Establish if we're adding or editing
        var keyIndex = null;
        $.each(initialDictionary, function (index) {
            if (this[0].toLowerCase() == key.toLowerCase()) {
                keyIndex = index;
                return false;
            }
        });
        //#endregion

        if (keyIndex != null) { // editing
            if (value != undefined && value != null && value != "") { // modify
                value = value.toString();
                initialDictionary[keyIndex][1] = value;
            }
            else {
                initialDictionary.splice(keyIndex, 1);
            }
        }
        else { // adding
            if (value != undefined && value != null && value != "") {
                initialDictionary.push([key, value]);
            }
        }
        //#region URL implode
        var returnUrl = baseUrl;
        var pairs = [];
        $.each(initialDictionary, function () {
            pairs.push(this.join("="));
        });
        queryString = pairs.join("&");
        returnUrl += "?" + queryString;
        if (sharpData != undefined) {
            returnUrl += "#" + sharpData;
        }
        //#endregion
        return (returnUrl);
    }


};
INDACO.langArr = [];
INDACO.namespace('region');
var jQDelegate = $.fn.delegate;
jQuery.fn.delegate = function (selector, types, data, fn) {
    if (types && types.indexOf("hover") == -1) {
        selector += ':not(".auth-disabled")';
    }
    return this.live(types, data, fn, selector);
};
jQuery.fn.bind = function (type, data, fn) {
    var handler;
    this.not(':not(".auth-disabled")');
    // Handle object literals
    if (typeof type === "object") {
        for (var key in type) {

            if (typeof (this[name]) === 'function')
                this[name](key, data, type[key], fn);
        }
        return this;
    }

    if (arguments.length === 2 || data === false) {
        fn = data;
        data = undefined;
    }

    if (name === "one") {
        handler = function (event) {
            jQuery(this).off(event, handler);
            return fn.apply(this, arguments);
        };
        handler.guid = fn.guid || jQuery.guid++;
    } else {
        handler = fn;
    }

    if (type === "unload" && name !== "one") {
        this.one(type, data, fn);

    } else {
        for (var i = 0, l = this.length; i < l; i++) {
            jQuery.event.add(this[i], type, handler, data);
        }
    }

    return this;
};
$("html").on("hover", ".auth-disabled", function (e) {
    if (e.type != "mouseenter") {
        return;
    }
    if ($(this).attr("title") !== $("#resource-access-denied").text()) {
        $(this).attr("title", $("#resource-access-denied").text());
    }
});
//#endregion

//#region Function.prototype.inherit
// prototype inheritance for functions ( object cunstructors only, no virtual objects allowed )
Function.prototype.inherit = function (ParentClass, noParent) {

    if ('undefined' === typeof (ParentClass))
        throw ('.inherit expects a class to be sent, undefined recived');

    if (ParentClass.constructor === Function) {

        this.prototype = new ParentClass();
        this.prototype.constructor = this;

        if (noParent !== false)
            this.prototype.parent = ParentClass.prototype;

        return;
    };

    throw ('.inherit expects argument to be a class not a anonym or virtual object');
};
//#endregion

//#region Function.prototype.chainInherit ( chaining prototype inheritance, preserves same name methos ) NOT USABLE
Function.prototype.chainInherit = function (arr) {

    if ('object' !== typeof (arr))
        throw ('.chainInherit expets argument to be array');

    // preserve the first key
    var dummy = function () { };
    dummy.inherit(arr[0]);

    //#region recInherit
    recInherit = function (arr, key) {

        if (key >= arr.length || key < 1)
            return null;

        if ('function' !== typeof (arr[key - 1]) || 'function' !== typeof (arr[key]))
            throw ('.recInherit expects array elements to be functions');

        var old = arr[key - 1].prototype;

        arr[key - 1].prototype = $.extend(true, new arr[key](), old);

        return recInherit(arr, key - 1);
    };
    //#endregion

    // append a dummy function at the end of the list to preserve the last 
    //  element's prototype in the parent
    arr.push(function () { });

    recInherit(arr, arr.length - 1);

    this.inherit(arr[0], false);

};
//#endregion

//#region Function.prototype.multiInherit ( appends prototypes, rewrites same name methods ) USES jQuery
Function.prototype.multiInherit = function (arr) {

    if ('object' !== typeof (arr))
        throw ('.chainInherit expets argument to be array');

    //#region recInherit
    recInherit = function (arr, key) {

        if (key >= arr.length || key < 1)
            return null;

        if ('function' !== typeof (arr[key - 1]) || 'function' !== typeof (arr[key]))
            throw ('.recInherit expects array elements to be functions');

        arr[key - 1].prototype = $.extend(true, arr[key].prototype, arr[key - 1].prototype);

        return recInherit(arr, key - 1);
    };
    //#endregion

    recInherit(arr, arr.length - 1);

    this.inherit(arr[0]);

};
//#endregion

//#region Date.getTSeconds
Date.prototype.getTSeconds = function () {
    var mili = this.getTime();

    return mili / 1000;
}
//#endregion

//#region Date.getTMinutes
Date.prototype.getTMinutes = function () {
    var mili = this.getTime();

    return mili / (1000 * 60);
};
//#endregion

//#region Date.getTHours
Date.prototype.getTHours = function () {
    var mili = this.getTime();

    return mili / (1000 * 60 * 60);
};
//#endregion

//#region Date.getTDays
Date.prototype.getTDays = function () {
    var mili = this.getTime();

    return mili / (1000 * 60 * 60 * 24);
};
//#endregion

//#region Date.getTWeeks
Date.prototype.getTWeeks = function () {
    var mili = this.getTime();

    return mili / (1000 * 60 * 60 * 24 * 7);
};
//#endregion

//#region Date.getTMonths
Date.prototype.getTMonths = function () {
    var mili = this.getTime();

    return mili / (1000 * 60 * 60 * 24 * 30);
};
//#endregion

//#region Date.getTYears
Date.prototype.getTYears = function () {
    var mili = this.getTime();

    return mili / (1008 * 60 * 60 * 24 * 30 * 12);
};
//#endregion

//#region nsx
// register the namespace method with jQuery
jQuery.nsx = function (ns_string) {
    var parts = ns_string.split('.'),
            parent = jQuery, i;

    // strip redundant leading global
    if (parts[0] === "$") {
        parts = parts.slice(1);
    } else if (parts[0] === "jQuery") {
        parts = parts.slice(1);
    }

    for (i = 0; i < parts.length; i += 1) {
        // create a property if it doesn't exist
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
    return parent;
};
//#endregion

//#region indaco namespace

//#region helpers
// register indaco namespace with jQuery
jQuery.nsx('indaco.h');

jQuery.indaco.h.scrollToElement = function (id) {
    var el = $(id);
    if (el.length > 0) {
        var offsetTop = $(id).offset().top;
        $('html,body').animate({ scrollTop: offsetTop }, 500);
    }
};

jQuery.indaco.h.getViewport = function () {
    var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w.innerHeight || e.clientHeight || g.clientHeight;

    return { width: x, height: y };
};

jQuery.indaco.h.serialize = function (form) {
    return jQuery.param(jQuery.indaco.h.serializeArray(form));
};

jQuery.indaco.h.serializeArray = function (form) {
    return form.map(function () {
        return this.elements ? jQuery.makeArray(this.elements) : this;
    })

		.filter(function () {
		    var rselectTextarea = /^(?:select|textarea)/i, rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i;
		    return this.name && !this.disabled && !jQuery(this).hasClass('placeholder') &&
				(this.checked || rselectTextarea.test(this.nodeName) ||
					rinput.test(this.type));
		})
		.map(function (i, elem) {
		    var val = jQuery(this).val();
		    var rCRLF = /\r?\n/g;

		    return val == null ?
				null :
				jQuery.isArray(val) ?
					jQuery.map(val, function (val, i) {
					    return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
					}) :
					{ name: elem.name, value: val.replace(rCRLF, "\r\n") };
		}).get();
};

jQuery.indaco.h.datePickerMinMax = function () {
    if (typeof $(this).data("datePickerOpts") == "object") {
        minOrMax = $(this).data("datePickerOpts").minOrMax;
        theOther = $($(this).data("datePickerOpts").otherId);
        thatValue = $(this).val();
        if (theOther.val()) {
            var dateFormat = theOther.datepicker("option", "dateFormat");
            theOtherValue = $.datepicker.parseDate(dateFormat, theOther.val().split(" ")[0]);
            $(this).datepicker('option', minOrMax, theOtherValue);
            $(this).val(thatValue);
        }
        else {
            $(this).datepicker('option', minOrMax, null);
            $(this).val(thatValue);
        }
    }
};

jQuery.indaco.h.isCharacterKeyPress = function isCharacterKeyPress(evt) {
    if (typeof evt.which == "undefined") {
        // This is IE, which only fires keypress events for printable keys
        return true;
    } else if (typeof evt.which == "number" && evt.which > 0) {
        // In other browsers except old versions of WebKit, evt.which is
        // only greater than zero if the keypress is a printable key.
        // We need to filter out backspace and ctrl/alt/meta key combinations
        return !evt.ctrlKey && !evt.metaKey && !evt.altKey;
    }
    return false;
};

//#region numericKeyCodes
jQuery.indaco.h.isNumericCode = function (code) {

    var valid = false;

    if ((code >= 48 && code <= 57)
        || (code >= 96 && code <= 105))
        valid = true;

    return valid;

};
//#endregion

//#region isEditCode
jQuery.indaco.h.isEditCode = function (code) {

    var valid = false;

    if (code == 8
    || code == 9
    || code == 12
    || code == 27
    || code == 37
    || code == 39
    || code == 46)
        valid = true;

    return valid;

};
//#endregion

//#endregion

//#region jQuery.indaco.__bind
// allows you to bind a function/method to an event without calling it with another object
// bypasses calls made call: obj.method.call(this) where "this" referes to another object ( like the dom jQuery selector )
// so inside you're method "this" will now refer to the instance of the jQuery selector
//
// usage : this.element.delegate('selector', 'event', $.indaco.__bind(function (e) {
//            return this.method(e);
//        }, this));
jQuery.indaco.__bind = function (fn, me) { return function () { return fn.apply(me, arguments); }; };
//#endregion

//#region jQuery.indaco.__delete
jQuery.indaco.__delete = function (obj) { delete (obj); };
//#endregion

//#region jQuery.indaco.__ajax
jQuery.indaco.__ajax = {
    type: 'POST',
    dataType: 'json',
    data: {},
    url: '',
    success: null,
    error: null,
    complete: null
};
//#endregion

//#region jQuery.indaco.__parseForm
jQuery.indaco.__parseForm = function (element) {

    // don't change the element sent, we allow jq objects or selectors too
    var elem = $(element);

    // object to be returned and where all the data goes
    var data = {};

    // input and select fields 
    var input = elem.find('input[type!="radio"], input[type="radio"]:checked, select, textarea');

    for (key in input) {
        if (!isNaN(key)) {
            var jqEl = $(input[key]);
            var name = jqEl.attr('name');
            var value = jqEl.val();

            if ('undefined' !== typeof (name)) {

                if (jqEl.attr('type') === 'checkbox') {

                    // checkbox
                    value = jqEl.is(':checked');
                    data[name] = value;

                } else if ('object' !== typeof (value)) {

                    // normal input
                    if ('undefined' === typeof (data[name]))
                        data[name] = value;

                } else if (value !== null) {

                    // multiselect
                    for (k in value) {
                        data[name + '[' + k + ']'] = value[k];
                    }
                }
            }
        }
    }

    return data;

};
//#endregion

//#region jQuery.indaco.__parseMessage
jQuery.indaco.__parseMessage = function (data, def) {

    var msg = def;

    if (data && data.Message && data.Message.length > 0)
        msg = data.Message;

    if (data && data.MessageToolTip && data.MessageToolTip.length > 0)
        msg += ' ' + data.MessageToolTip;

    return msg;

};
//#endregion

//#region jQuery.indaco.__removeFromArray
jQuery.indaco.__removeFromArray = function (value, arr) {

    for (key in arr) {

        if (value == arr[key]) {
            arr.splice(key, 1);
            break;
        }

    }
}
//#endregion

//#region jQuery.indaco.__preparePost
jQuery.indaco.__preparePost = function (obj, name) {

    var data = {};

    for (key in obj) {

        data[name + '[' + key + ']'] = obj[key];

    }

    return data;

};
//#endregion

//#region jQuery.indaco.__preparePost2
jQuery.indaco.__preparePost2 = function (obj, name) {

    var data = {};

    if ('object' === typeof (obj)) {

        for (key in obj) {

            data[name + '.' + key] = obj[key];

        }

    } else {
        data[name] = obj;
    }

    return data;

};
//#endregion

//#region jQuery.indaco.__stopEvent
jQuery.indaco.__stopEvent = function (e) {

    e.preventDefault();
    e.stopPropagation();

};
//#endregion

//#region indaco.i
jQuery.nsx('indaco.i');

jQuery.nsx('indaco._c');

$.indaco._c.InitPage = (function () {
    var InitPage = function () { };

    InitPage.prototype.defaultOpt = {
        indexUrl: '',
        sectionParentId: ''
    };

    return InitPage;
})();

jQuery.indaco.i._objects = {};

jQuery.indaco.i.factory = function (opts) {

    if ('object' !== typeof (opts))
        throw ("InitPage.factory expects argument sent to be object");

    if ('string' !== typeof (opts.className))
        throw ("InitPage.factory className not defined");

    $.nsx('indaco._c');

    // constructor
    eval("var " + opts.className + " = classFactory = function (opt) {" +
        "this.options = {};" +
        "$.extend(true, this.options, this.parent.defaultOpt, opt);" +
    "};");

    // extend
    if ('undefined' !== typeof (opts.extend)) {
        if ('undefined' !== typeof ($.indaco._c[opts.extend]))
            classFactory.inherit($.indaco._c[opts.extend]);
        else
            throw ("Class " + opts.extend + " is not defined");
    }
    else {
        // inherit
        classFactory.inherit($.indaco._c.InitPage);
    }

    // methods
    if ('object' === typeof (opts.methods))
        for (key in opts.methods)
            classFactory.prototype[key] = opts.methods[key];

    // register
    $.indaco._c[opts.className] = classFactory;
};

jQuery.indaco.i.register = function (objects) {

    for (key in objects) {
        if ('undefined' !== typeof ($.indaco._c[objects[key].className])) {
            var obj = new $.indaco._c[objects[key].className](objects[key].options);
            var name = objects[key].objName || key;

            if ('undefined' !== typeof ($.indaco.i._objects[name]))
                continue;

            jQuery.indaco.i._objects[name] = obj;
        }
        else {
            //throw(objects[key].class + " was not defined!");
        }
    }

    return jQuery.indaco.i;
};

jQuery.indaco.i.init = function () {

    jQuery.each(jQuery.indaco.i._objects, function (key, value) {

        if (value.__isInit === true)
            return;

        value.__isInit = true;
        value.init();

    });

};

jQuery.indaco.i.del = function (objName) {

    if ('object' == typeof jQuery.indaco.i._objects[objName])
        delete (jQuery.indaco.i._objects[objName]);

};
//#endregion

//#endregion

//#region $.fn.outerHtmlI
$.fn.extend({
    outerHtmlI: function () {
        var s = '';
        $(this).each(function (key, elem) {
            s += $(elem).clone().wrap('<div>').parent().html();
        });
        return s;
    }
});
//#endregion

//#region $.fn.reverse ( reverse a jquery collection )
$.fn.reverse = [].reverse;
//#endregion

//#region $.ajax proxy
(function () { 
    
    if (typeof(jQuery.ajax) === 'function') {
        
        // save old ajax function
        jQuery.ajaxOld = jQuery.ajax;

        // new ajax function
        jQuery.ajax = function () {
            
            // success, error, complete
            var success = arguments[0].success,
                error = arguments[0].error,
                complete = arguments[0].complete
            ;
            delete arguments[0].success;
            delete arguments[0].error;
            delete arguments[0].complete;

            var jqXHR = jQuery.ajaxOld(arguments[0])
                .done(function(){
                    if (typeof (success) === 'function')
                        success.apply(this, arguments);
                })
                .fail(function(){
                    if (typeof (error) === 'function')
                        error.apply(this, arguments);
                })
                .always(function(){
                    if (typeof (complete) === 'function')
                        complete.apply(this, arguments);
                })
            ;

            return jqXHR;
        };

    }

})();
//#endregion


$(function () {
    $("#extra_options h3 a").click(function () {
        if ($(this).parent().hasClass("selected")) {
            $(this).parent().removeClass("selected");
            $(this).parent().next(".expander").removeClass("selected").effect("blind", { mode: "hide", direction: "left" }, 400);

        } else {
            $("#extra_options .expander.selected").effect("blind", { mode: "hide", direction: "left" }, 400);
            $("#extra_options h3.selected, #extra_options .expander.selected").removeClass("selected");
            $(this).parent().addClass("selected");
            $(this).parent().next(".expander").addClass("selected").effect("blind", { mode: "show", direction: "left" }, 400);
        }

        return false;
    });
    $("#expander-search input").keyup(function (key) {
        var txtSearch = $(this).val();
        var txtUrl = window.location.href;
        if (key.keyCode == "13") {
            if (txtSearch.length > 2) {

                if (txtUrl.indexOf("Search") == -1) {

                    if ($(this).attr("data-action") != "Index") {
                        window.location = "../Search#" + txtSearch;
                    }
                    else {
                        window.location = "Search#" + txtSearch;
                    }
                }
                else {
                    window.location = "Search#" + txtSearch;
                    window.location.reload();
                }

            } else {
                $("#expander-search input").addClass("error");
            }
        }

    });
    //#region Show the tooltip of abbr attributes whilst having ctrl pressed in a text input
    $(window).on("keydown", 'input[type="text"]', function (e) {
        if (!$(this).parent().hasClass("field")) {
            return;
        }
        if ($(this).siblings(".info").size() != 1) {
            return;
        }
        if (e.which != 17) {
            return;
        }
        if ($(this).data("infopressed") || $(this).data("infopressed") == true) {
            return;
        }
        var abbr = $(this).siblings(".info");
        abbr.append('<span class="inserted">' + abbr.attr("title") + '</span>');
        var element = abbr.children(".inserted").first();
        //do styling shit
        element.css({
            "position": "absolute",
            "top": "-5px",
            "border": "1px",
            "zoom": "1",
            "white-space": "nowrap",
            "display": "inline-block",
            "word-wrap": "normal",
            "border-style": "solid",
            "border-color": "#777777",
            "font-size": "1.1em",
            "padding": "5px",
            "left": "15px",
            "line-height": "9px",
            "border-radius": "3px",
            "color": "#666666",
            "z-index": "3000"
        });
        if ($.browser.mozilla) {
            element.css("background", "-moz-linear-gradient(center bottom, #eeeeee 0%, white 50%)");
        }
        else if ($.browser.webkit) {
            element.css("background", "-webkit-gradient(linear, left bottom, left top, color-stop(0, #eeeeee), color-stop(0.5, white))");
        }
        else {
            element.css("filter", "progid:DXImageTransform.Microsoft.gradient( startColorstr='#eeeeee', endColorstr='#ffffff',GradientType=0 );");
        }
        $(this).data("infopressed", true);

    });
    $(window).on("keyup", 'input[type="text"]', function (e) {
        if (!$(this).parent().hasClass("field")) {
            return;
        }
        if ($(this).siblings(".info").size() != 1) {
            return;
        }
        if (e.which != 17) {
            return;
        }
        if ($(this).data("infopressed") == undefined || $(this).data("infopressed") == null) {
            return;
        }
        var abbr = $(this).siblings(".info");
        abbr.find(".inserted").remove();

        $(this).data("infopressed", false);
    });
    $(window).on("blur", 'input[type="text"]', function (e) {
        if (!$(this).parent().hasClass("field")) {
            return;
        }
        if ($(this).siblings(".info").size() != 1) {
            return;
        }
        if ($(this).data("infopressed") == undefined || $(this).data("infopressed") == null) {
            return;
        }
        var abbr = $(this).siblings(".info");
        abbr.find(".inserted").remove();

        $(this).data("infopressed", false);
    });
    $(window).on("mouseover", "span.inserted", function () {
        if ($(this).parent().siblings('input[type="text"]').size() > 0) {
            $(this).siblings('input[type="text"]').data("infopressed", false);
        }
        $(this).remove();
    });
    //#endregion
    $("#main_sidebar .sidebar_settings a").on("click", sidebarGlobalClick);

    /* this is for pane but to lazy to create new file */
    $("div.dropdown a.result").click(function () {
        $(this).siblings(".options").toggle();
        return false;
    });
    $("div.dropdown .options a").click(function () {
        $(this).closest(".options").find("a").removeClass("selected");
        $(this).addClass("selected");
        $(this).closest(".dropdown").find("a.result").text($(this).text());
        $(this).closest(".dropdown").find("input").val($(this).data("value"));
        $(this).closest(".options").hide();
        return false;
    });

    jQuery.fn.spanify = function () {
        return this.find("span.field-validation-error").each(function () {
            var spanChild = $(this).find(":nth-child(1)");
            if (spanChild.is("span") == false) {
                $(this).html("<span>" + $(this).text() + "</span>");
            }
        });
    };

    //messages
    jQuery.fn.BoxSuccess = function (success, prepend) {
        prepend = prepend || false;
        if ($(this).find(".message").length > 0) {
            $(this).find(".message").remove();
        }
        var span = $('<span class="message message-success">' + success + '</span>');
        if (!prepend) {
            $(this).append(span);
        }
        else {
            $(this).prepend(span);
        }
        span.delay(5000).fadeOut("500", function () { $(this).remove(); });
    };
    jQuery.fn.BoxInfo = function (info) {
        if ($(this).find(".message").length > 0) {
            $(this).find(".message").remove();
        }
        var span = $('<span class="message message-info">' + info + '</span>');
        $(this).append(span);

        span.delay(10000).fadeOut("500", function () { $(this).remove(); });
    };
    jQuery.fn.BoxWarning = function (warning, prepend) {
        if ($(this).find(".message").length > 0) {
            $(this).find(".message").remove();
        }
        var span = $('<span class="message message-highlight">' + warning + '</span>');
        if (prepend) {
            this.prepend(span);
        } else {
            this.append(span);
        }

        span.delay(10000).fadeOut("500", function () { $(this).remove(); });
    };
    jQuery.fn.BoxError = function (error, prepend, hideTooltip) {
        if ($(this).find(".message").length > 0) {
            $(this).find(".message").remove();
        }
        var smallText = "Warning";
        if ($("#resource-warning").size() > 0 && $("#resource-warning").text() != "") {
            smallText = $("#resource-warning").text();
        }

        var span = '<span class="message message-error">';
        if (hideTooltip) {
            span += error + '</span>';
        } else {
            span += '<span class="title">' + error + '</span>' + smallText + '</span>';
        }

        span = $(span);

        if (prepend) {
            this.prepend(span);
        } else {
            this.append(span);
        }

        span.delay(10000).fadeOut("500", function () { $(this).remove(); });
    };
    $.fn.addEmbeddedMessage = function (options) {
        var defaults = {
            refreshButton: true,
            msg: "",
            msgTooltip: ""
        };

        options = $.extend(defaults, options);
        var msg = '<div class="status_failure">' +
                '<p>' + options.msg;
        if (options.refreshButton) {
            msg += '<a href="#" class="btn-refresh">@TranslatorAdmin.BtnRefresh</a>';
        }

        if (options.msgTooltip) {
            msg += '<span class="field-validation-error"><span>' + options.msgTooltip + '</span></span>';
        }

        msg += '</p>' +
           '</div>';

        $(this).html(msg);
    };

});

function sidebarGlobalClick() {

    var sidebarMode;
    if ($(this).hasClass("selected")) {
        $(this).removeClass("selected");
        $("#main_sidebar").animate({ left: "0" }, 300);
        $("#main_section").animate({ marginLeft: "170px" }, 300);
        $("#admin_logo span").animate({ width: "71px" }, 300);
        $("#admin_logo").animate({ paddingLeft: "34px", paddingRight: "35px", width: "71px" }, 300);

        sidebarMode = false;
    } else {
        $(this).addClass("selected");
        $("#main_sidebar").animate({ left: "-110px" });
        $("#main_section").animate({ marginLeft: "60px" }, 300);
        $("#admin_logo span").animate({ width: "16px" }, 300);
        $("#admin_logo").animate({ paddingLeft: "7px", paddingRight: "7px", width: "17px" }, 300);

        //set sidebar mode for saving
        sidebarMode = true;
    }
    return false;

    var url = indaco.trimToRoot(window.location.href) + "Sidebar/Save";
    $.ajax({
        url: url,
        type: "POST",
        dataType: "JSON",
        data: "sidebarMode=" + sidebarMode
    });
    return false;
}

$(document).ready(function () {
    $('body').on('addEmbeddedMessage', function (e, data) {
        if ('undefined' != typeof data && 'undefined' != typeof data.element) {
            data.element.addEmbeddedMessage(data.opt);
        }
    });
});

$(document).ready(function () {
    $("body").on("click", "label", function (e, data) {
        var self = $(this);
        var labelForAttr = self.attr("for");
        var targetSelect = self.siblings("#" + labelForAttr);
        if (targetSelect.length > 0) {
            var targetSelectChzn = targetSelect.siblings("div[id='" + labelForAttr + "_chzn']");
            if (targetSelectChzn.length > 0) {
                targetSelectChzn.trigger("click");
                targetSelectChzn.focus();
                return false;
            }
        }
    });
});


/*
*  MD5 (Message-Digest Algorithm)
*/

var MD5 = function (string) {

    function RotateLeft(lValue, iShiftBits) {
        return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
    }

    function AddUnsigned(lX, lY) {
        var lX4, lY4, lX8, lY8, lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    }

    function F(x, y, z) { return (x & y) | ((~x) & z); }
    function G(x, y, z) { return (x & z) | (y & (~z)); }
    function H(x, y, z) { return (x ^ y ^ z); }
    function I(x, y, z) { return (y ^ (x | (~z))); }

    function FF(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function GG(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function HH(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function II(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1 = lMessageLength + 8;
        var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
        var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
        var lWordArray = Array(lNumberOfWords - 1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while (lByteCount < lMessageLength) {
            lWordCount = (lByteCount - (lByteCount % 4)) / 4;
            lBytePosition = (lByteCount % 4) * 8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount - (lByteCount % 4)) / 4;
        lBytePosition = (lByteCount % 4) * 8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
        lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
        lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
        return lWordArray;
    };

    function WordToHex(lValue) {
        var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
        for (lCount = 0; lCount <= 3; lCount++) {
            lByte = (lValue >>> (lCount * 8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
        }
        return WordToHexValue;
    };

    function Utf8Encode(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var x = Array();
    var k, AA, BB, CC, DD, a, b, c, d;
    var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
    var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
    var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
    var S41 = 6, S42 = 10, S43 = 15, S44 = 21;

    string = Utf8Encode(string);

    x = ConvertToWordArray(string);

    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;

    for (k = 0; k < x.length; k += 16) {
        AA = a; BB = b; CC = c; DD = d;
        a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
        d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
        c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
        b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
        a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
        d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
        c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
        b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
        a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
        d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
        c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
        b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
        a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
        d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
        c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
        b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
        a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
        d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
        c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
        b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
        a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
        d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
        c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
        b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
        a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
        d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
        c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
        b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
        a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
        d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
        c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
        b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
        a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
        d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
        c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
        b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
        a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
        d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
        c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
        b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
        a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
        d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
        c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
        b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
        a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
        d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
        c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
        b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
        a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
        d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
        c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
        b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
        a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
        d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
        c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
        b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
        a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
        d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
        c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
        b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
        a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
        d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
        c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
        b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
        a = AddUnsigned(a, AA);
        b = AddUnsigned(b, BB);
        c = AddUnsigned(c, CC);
        d = AddUnsigned(d, DD);
    }

    var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);

    return temp.toLowerCase();
}

