﻿if (typeof Haulix == 'undefined') {
    Haulix = {}
}

$(window).load(function () {
    // find all the forms on the page where an ajax post is supposed to take place
    $('form[data-ajaxpostback]').each(function () {
        var returnFunction = eval($(this).attr('data-ajaxpostback'));

        $(this).submit(function () {
            if (ValidateForm(this)) {
                var json = $(this).serializeObject();
                var path = $(this).attr('action');
                var domain = window.location.protocol + '//' + window.location.host;
                path = path.replace(domain, '');
                var method = $(this).attr('method');

                // make AJAX request to server
                $.ajax({
                    type: method,
                    url: path,
                    data: JSON.stringify(json),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data != null && data.TransitionUrl != null) {
                            window.location = data.TransitionUrl;
                        }
                        else if (data != null && data.Refresh) {
                            window.location.reload(true);
                        }
                        else if (returnFunction != null) {
                            returnFunction(data);
                        }
                        else if (data.Message != null) {
                            alert(data.Message);
                        }
                    }
                });
            }
            return false;
        });
    });
});

function ValidateForm(form) {
    var formObject = $(form);
    var validated = true;

    formObject.find('*[data-required]').each(function () {
        var message = $(this).attr('data-required-message');
        var errorContainer = $('#' + this.id + 'Error');
        if ($(this).val().length == 0) {
            errorContainer.html(message);
            validated = false;
        }
        else {
            // perhaps there's another validation error happening?
            if (errorContainer.html().length > 0 && errorContainer.html() != message) {
                validated = false;
            }
            else {
                errorContainer.html('');
            }
        }
    });

    return validated;
}

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } if (this.value == 'on') {
            // checkbox
            o[this.name] = true;
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Haulix.AlertType = { Success: 0, Error: 1 };

Haulix._AlertBar = function () {
    this._container = null;
    this._message = null;
    this._messageType = Haulix.AlertType.Success;
}

Haulix._AlertBar.prototype = {
    ShowMessage: function (message, messageType) {
        this._message = message;
        if (messageType == Haulix.AlertType.Success || messageType == Haulix.AlertType.Error) {
            this._messageType = messageType;
        }

        this.Draw();
    },

    Draw: function () {
        this.Close();

        var className = this._messageType == Haulix.AlertType.Success ? "Success" : "Error";

        var markup = '<div id="alertBar" class="' + className + '"><span id="message">' + this._message + '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id="closeLink">[&nbsp;<a id="alertBarClose" href="javascript:void(0)">Close</a>&nbsp;]</span></div>';

        $('body').prepend(markup);

        var $this = this;

        $('#alertBarClose').click(function() {
            $('#alertBar').slideUp(100, function() {
                $this.Close();
            });
        });
    },

    Close: function () {
        $('#alertBar').remove();
    }
};

Haulix.AlertBar = new Haulix._AlertBar();

Haulix.Lightbox = function () {
    this._popupContainer = null;
    this._overlay = null;
    this._heading = '';
    this._bodyHtml = '';
    this._buttonHtml = '';
    this._cssClass = '';
    this._isWide = false;
    this._isToolTip = false;
    this._toolTipControl = null;
};

Haulix.Lightbox.prototype = {
    Draw: function () {
        // delete all existing lightboxes and overlays
        this.Close();
        var lightboxClass = this._isWide ? "Lightbox Wide " : "Lightbox ";
        var carat = this._isToolTip ? '<div class="Carat"></div>' : '';
        var overlay = this._isToolTip ? '' : '<div class="LightboxOverlay"></div>';

        var popupMarkup = overlay + '<div class="' + lightboxClass + this._cssClass + '"><div class="LightboxTop"></div>' + carat + '<div class="LightboxBody"></div><div class="LightboxBottom"></div></div>';
        $('body').append(popupMarkup);

        this._popupContainer = $('.Lightbox');
        this._overlay = $('.LightboxOverlay');

        //size overlay
        var $this = this;
        $(window).resize(function () { $this._resizeOverlay(); });
        this._resizeOverlay();

        var markup = '';

        if (this._heading.length > 0) {
            markup += '<h2>' + this._heading + '</h2>';
        }
        if (this._bodyHtml.length > 0) {
            markup += '<div class="LightboxHtmlBody">' + this._bodyHtml + '</div>';
        }
        if (this._buttonHtml.length > 0) {
            markup += '<div class="LightboxButtonContainer">' + this._buttonHtml + '</div>';
        }

        this._popupContainer.find('.LightboxBody').html(markup);

        if (!this._isToolTip || this._toolTipControl == null) {
            var height = this._popupContainer.height();
            var width = this._popupContainer.width();

            var windowHeight = $(window).height();
            var windowWidth = $(window).width();

            var positionLeft = (windowWidth - width) / 2;
            var positionTop = (windowHeight - height) / 2;

            var scrollPosition = this._getScroll();

            this._popupContainer.css({
                'left': positionLeft + scrollPosition.scrollLeft,
                'top': positionTop + scrollPosition.scrollTop
            });
        }
        else {
            var popupHeight = this._popupContainer.height();
            var caratHeight = this._popupContainer.find('.Carat').height();

            this._popupContainer.find('.Carat').css('top', (popupHeight / 2) - (caratHeight / 2));

            var control = $(this._toolTipControl);
            var offset = control.offset();
            var height = control.height();
            var width = control.width();

            var leftPosition = offset.left - this._popupContainer.width();
            var topPosition = offset.top + (height / 2) - (popupHeight / 2);

            this._popupContainer.css({
                'left': leftPosition,
                'top': topPosition
            });
        }
    },

    Close: function () {
        $('.Lightbox').remove();
        $('.LightboxOverlay').remove();
    },

    _resizeOverlay: function () {
        this._overlay.css({
            'height': $(document).height(),
            'width': $(window).width()
        });
    },

    _getScroll: function () {
        if (self.pageYOffset) {
            scrollTop = self.pageYOffset;
            scrollLeft = self.pageXOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
            scrollTop = document.documentElement.scrollTop;
            scrollLeft = document.documentElement.scrollLeft;
        } else if (document.body) {// all other Explorers
            scrollTop = document.body.scrollTop;
            scrollLeft = document.body.scrollLeft;
        }

        return { scrollTop: scrollTop, scrollLeft: scrollLeft };
    },

    setHeading: function (value) {
        this._heading = value;
    },

    setBodyHtml: function (value) {
        this._bodyHtml = value;
    },

    setButtonHtml: function (value) {
        this._buttonHtml = value;
    },

    setCssClass: function (value) {
        this._cssClass = value;
    },

    setIsWide: function (value) {
        this._isWide = value;
    },

    setIsToolTip: function (value, positionControl) {
        this._isToolTip = value;
        this._toolTipControl = positionControl;
    }
};

Haulix.DateExtensions = {
    IsValidDate: function (value, format) {
        if (format == null) { format = "MDY"; }
        format = format.toUpperCase();
        if (format.length != 3) { format = "MDY"; }
        if ((format.indexOf("M") == -1) || (format.indexOf("D") == -1) || 
            (format.indexOf("Y") == -1)) { format = "MDY"; }
        if (format.substring(0, 1) == "Y") { // If the year is first
            var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
            var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
        } else if (format.substring(1, 2) == "Y") { // If the year is second
            var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
            var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
        } else { // The year must be third
            var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
            var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
        }
        // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
        if ((reg1.test(value) == false) && (reg2.test(value) == false)) { return false; }
        var parts = value.split(RegExp.$1); // Split into 3 parts based on what the divider was
        // Check to see if the 3 parts end up making a valid date
        if (format.substring(0, 1) == "M") { var mm = parts[0]; }
        else if (format.substring(1, 2) == "M") { var mm = parts[1]; }
        else { var mm = parts[2]; }
        if (format.substring(0, 1) == "D") { var dd = parts[0]; }
        else if (format.substring(1, 2) == "D") { var dd = parts[1]; }
        else { var dd = parts[2]; }
        if (format.substring(0, 1) == "Y") { var yy = parts[0]; }
        else if (format.substring(1, 2) == "Y") { var yy = parts[1]; }
        else { var yy = parts[2]; }
        if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
        if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
        var dt = new Date(parseFloat(yy), parseFloat(mm) - 1, parseFloat(dd), 0, 0, 0, 0);
        if (parseFloat(dd) != dt.getDate()) { return false; }
        if (parseFloat(mm) - 1 != dt.getMonth()) { return false; }
        return true;
    }
};

function inArray(array, value) {
    for (var i = 0; i < array.length; ++i) {
        if (array[i] == value)
            return true;
    }
    return false;
}

function IsValidEmailAddress(value) {
    var regExp = new RegExp(/^[\w\.\-]+@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]{1,})*(\.[a-zA-Z]{2,3}){1,2}$/);
    return regExp.test(value);
}

RegExp.escape = function (text) {
    if (!arguments.callee.sRE) {
        var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
        arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
    }
    return text.replace(arguments.callee.sRE, '\\$1');
}

function GetParm(key, url) {
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + key + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if (results == null)
        return "";
    else
        return results[1];
}