﻿var pageLoaded = true;
var globalDialogCallback = null;

function Validation(fieldId, validatorId, evaluator) {

    this.fieldId = fieldId;
    this.fieldSelector = "#" + fieldId;
    this.validatorId = validatorId;
    this.validatorSelector = "#" + validatorId;
    this.evaluator = evaluator;


    this.toggleValidationClass = function () {
        var helper = $(this.validatorSelector);
        helper.removeClass("validatorAlert");
        helper.addClass("validator");
    }

    this.toggleValidationAlertClass = function () {

        var helper = $(this.validatorSelector);
        helper.removeClass("validator");
        helper.addClass("validatorAlert");
    }

    this.InitValidation();
}

function ValidateEmail(val) {

    var emailPattern = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

    return ValidateRegEx(val, emailPattern);
}

function ValidateRequired(val) {
    return val != "";
}

function ValidatePhone(val) {

    var phonePattern = "^\\d{3}-\\d{3}-\\d{4}$";

    return ValidateRegEx(val, phonePattern);
}

function ValidateZipCode(val) {
    var zipCodePattern = "^\\d{5}([\-]\\d{4})?$";

    return ValidateRegEx(val, zipCodePattern);
}

function ValidateRegEx(val, expression) {
    var regex = new RegExp(expression);

    return regex.test(val);
}



//Add validation logic using a field and validation display
//Evaluator is a function that take the valye of field and returns a bool
Validation.prototype.InitValidation = function () {
    var _this = this;

    var validator = $(_this.validatorSelector);
    validator.addClass("validator");

    var field = $("#" + this.fieldId);

    this.onFocusIn = function () {

        var elem = $(_this.validatorSelector);
        elem.removeClass("displayNone");

    };

    this.onFocusOut = function () {
        _this.Evaluate();
    };

    this.Evaluate = function () {
        var helperSelector = "#" + _this.validatorId;
        var helper = $(helperSelector);

        var value = $("#" + _this.fieldId).val();

        var result = _this.evaluator(value);

        if (result == true) {
            helper.addClass("displayNone");
            _this.toggleValidationClass();
        }
        else {
            helper.removeClass("displayNone");
            _this.toggleValidationAlertClass();
        }

        return result;
    }

    this.GetValidationText = function () {
        var validator = $get(_this.validatorId);

        return validator.innerHTML;
    }

    this.setFocus = function () {
        var field = $("#" + _this.fieldId);
        field.focus();
    }

    field.focusin(this.onFocusIn);

    field.focusout(this.onFocusOut);
};

function Validate(validations) {
    var valid = true;

    for (var i = 0; i < validations.length; i++) {
        if (validations[i] && validations[i].Evaluate() != true) {
            if (valid == true) {
                valid = false;
                validations[i].setFocus();
                ToggleDropIn(true, validations[i].GetValidationText());
            }

        }

    }
    return valid;
}

function SetVisible(element, isVisible) {
    if (isVisible == true) {
        $(element).show("slow");
    }
    else {
        $(element).hide("fast");
    }
}

function HandleException(exception) {
    if (exception.get_exceptionType() == "System.AccessViolationException") {
        window.location = "/Account/MainPage.aspx";
    }
    else {
        ToggleDropIn(true, exception.get_message());
    }
}

function InitGlobalAlert() {
    $(window).scroll(ResetAlertPosition);
    $("body").scroll(ResetAlertPosition);
    window.onscroll = ResetAlertPosition;

    $(window).resize(ResetAlertPosition);

    ToggleDropIn(false);
}

function ToggleDropIn(show, msg) {
    var alertBox = GetAlert();
    var alertText = $("#alertText");
    alertText.html(msg);

    if (show) {
        if (alertBox.css("visibility") != "hidden")
            alertBox.animate({ marginTop: '-50px' }, 500, "swing", function () { GetAlert().css("visibility", "hidden"); ToggleDropIn(show, msg); });
        else {
            ResetAlertPosition();
            alertBox.css("visibility", "visible");
            alertBox.animate({ marginTop: '0px' }, 500, "swing");
        }
    }
    else {
        alertBox.animate({ marginTop: '-50px' }, 500, "swing", function () { GetAlert().css("visibility", "hidden"); });
    }
}

function ResetAlertPosition() {
    var windowssss = window;

    var alertBox = $("#alertBox");
    alertBox.css("top", GetScrollTop());
    alertBox.css("left", GetScrollLeft());
    alertBox.css("width", window.innerWidth);
}

function GetScrollTop() {
    var ScrollTop = document.body.scrollTop;

    if (ScrollTop == 0) {
        if (window.pageYOffset)
            ScrollTop = window.pageYOffset;
        else
            ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
    }

    return ScrollTop;
}

function GetScrollLeft() {
    var ScrollLeft = document.body.scrollLeft;

    if (ScrollLeft == 0) {
        if (window.pageXOffset)
            ScrollLeft = window.pageXOffset;
        else
            ScrollLeft = (document.body.parentElement) ? document.body.parentElement.scrollLeft : 0;
    }

    return ScrollLeft;
}

function GetAlert() {
    return $("#alertBox");
}

String.prototype.trimEnd = function (c) {
    if (c)
        return this.replace(new RegExp(c.escapeRegExp() + "*$"), '');
    return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function (c) {
    if (c)
        return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), '');
    return this.replace(/^\s+/, '');
}

String.prototype.escapeRegExp = function () {
    return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
};

function getUrlEncodedKey(key, query) {
    if (!query)
        query = window.location.hash;
    var re = new RegExp("[?|&|#]" + key + "=(.*?)&");
    var matches = re.exec(query + "&");
    if (!matches || matches.length < 2)
        return "";
    return decodeURIComponent(matches[1].replace("+", " "));
}

function setUrlEncodedKey(key, value, query) {

    query = query || window.location.hash;
    var q = query + "&";
    var re = new RegExp("[?|&|#]" + key + "=.*?&");
    if (!re.test(q))
        q += key + "=" + encodeURI(value);
    else
        q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");

    q = q.trimStart("#").trimEnd("#");
    q = q.trimStart("&").trimEnd("&");

    window.location.hash = q;

    return q;
}

function NotImplemented() {
    alert('Not Implemented');
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function queryString(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name.toLowerCase() + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href.toLowerCase());
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}


(function ($) {
    $.fn.verticalScroller = function () {
        var fps = 30;
        var speed = Math.ceil(15 / fps);
        var interval;
        var scroll = this;

        function Animate(obj) {

            var clip = obj;
            var max = clip.height();
            var uls = clip.children("ul");
            var liMax = $(uls[0]).height();

            if (uls.length < 2) {
                var ul = $(uls[0]);
                ul.clone().appendTo(clip);
            }

            interval = setInterval(function () {

                if ((clip.scrollTop() + speed) < liMax) {
                    clip.scrollTop(clip.scrollTop() + speed);
                }
                else {
                    clip.scrollTop(0);
                }

            }, 1000 / fps);

        }

        function StopAnimate() {
            clearInterval(interval);
        }

        Animate(this);

        this.hover(function () {
            StopAnimate();
        },
         function () {
             Animate(scroll);
         });

    }
})(jQuery);

function selectText(element) {
    var text = document.getElementById(element);

    if ($.browser.msie) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    }
    else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
    else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 1);
    }
}

function GetGridLoadingPanelHtml(elem) {
    var width = elem.clientWidth;
    var height = elem.clientHeight;

    var div = "<div style='width:" + width + "px; height:" + height + "px;' class='loadingPanel'>Loading...</div>";
    return div;
}

function SetPageLoaded(loaded) {
    pageLoaded = loaded;

    if (pageLoaded)
        HideMasterLoadingPanel();
    else
        ShowMasterLoadingPanel();
}

function ShowMasterLoadingPanel() {
    if (!pageLoaded) {
        $('#loadingPanel').fadeTo(0, 0.6);
        $('#loadingImage').show();
    }
}

function HideMasterLoadingPanel() {
    if (pageLoaded) {
        $('#loadingPanel').fadeTo(0, 1);
        $('#loadingImage').hide();
    }
}

function ShowLoadingPanel(elem) {
    if (elem == undefined)
        elem = $('div.borderPanelL')[0];

    var body = $('body');
    var loadingPanel = GetLoadingWithPosition(elem);
    body.prepend(loadingPanel);
}

function GetLoadingWithPosition(elem) {
    var width = elem.clientWidth;
    var height = elem.clientHeight;
    var position = $(elem).offset();

    var div = "<div id='loadingPanel' style='width:" + width + "px; height:" + height + "px; position:absolute; top:" + position.top + "px;left:" + position.left + "px; opacity: 0.6; filter: alpha(opacity=60); '  class='loadingPanel'>Loading...</div>";
    return div;
}

function HideLoadingPanel() {
    var panel = $('#loadingPanel');
    panel.remove();
}

function GlobalDialog(title, message, callback) {
    globalDialogCallback = callback;
    globalDialog.Show(message, title);
}

function GlobalDialogClose() {
    globalDialog.Close();

    if (globalDialogCallback != null)
        globalDialogCallback();
}

function MoveDropIn(newParent) {
    if (newParent == undefined) {
        newParent = $('#globalAlertParent');
    }

    $('#' + newParent).prepend(GetAlert());
}

function HandleEnter(elem, func) {
    elem.keypress(function (e) { if (e.which == 13) { e.preventDefault(); func(); return false; } });
}

function initFontSize() {
    setFontSize(parseInt($.getSubCookie('options', 'fontSize')));
}

function setFontSize(size) {
    var percent = 75;

    switch (size) {
        case 1:
            percent = 70;
            break;
        case 3:
            percent = 85;
            break;
        case 2:
        default:
            percent = 75;
            break;
    }

    $('body').css('font-size', percent + '%');
    $.setSubCookie('options', 'fontSize', size, { expires: 9999 });
}

function PreventDefault() {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
}

var qs;

function QueryString(key) {
    if (qs == null) {
        ParseQueryString();
    }

    return qs[key];
}

function ParseQueryString() {
    qs = Object();
    var all = window.location.search.substring(1);
    var vals = all.toString().split('&');

    for (var i = 0; i < vals.length; i++) {
        var pair = vals[i].toString().split('=');
        var key = pair[0];
        var val = pair[1];
        qs[key] = val;
    }
}


function LoadingPanel($elem) {
    var top = ($elem.height() / 2) - 16;
    var left = ($elem.width() / 2) - 16;
    var loading = $('<div style="background:#FFF;opacity: 0.6; filter: alpha(opacity=60);width:98%;position:absolute;top: 0;left: 0;height:' + $elem.height() + 'px;z-index:1"><img src="/App_Themes/Main/images/ajax-loading.gif" style="position:absolute;top:' + top + 'px;left:' + left + 'px;" /></div>').appendTo($elem);
    return loading;
}
