﻿//Common___________________________________________

var OnlyIntegers = /^\d+$/
var SessionTimeoutCode = "100118";


//Validation Variables_______________________________________

var DataType = {};

DataType.Email = /([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+/;
DataType.UserName = /[A-Za-z]./;
DataType.Integer = /[0-9]+/;
DataType.Numeric = /([1-9]{0,1})([0-9]{1})(\.[0-9])?/;
DataType.AlphaNumeric = /([a-zA-Z0-9_-]+)/;
DataType.Text = /[A-Za-z]+/;
DataType.Date = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/;
DataType.Phone = /(([0-9]{1})*[- .(]*([0-9a-zA-Z]{3})*[- .)]*[0-9a-zA-Z]{3}[- .]*[0-9a-zA-Z]{4})+/;

//DataType.Date = /(0[1-9]|1[012])[- \/.]((0[1-9]|[12][0-9]|3[01])[- \/.])?(19|20)\\d\\d/;
//Fires Form Submit
$(function() 
{
    $('input.submitField').keypress(submitForm);
});


function submitForm(event) 
{
    if (event.keyCode == '13') {
        $('.submitForm').submit();
        return true;
    }

}



//Cancel Form Button
$(function() 
{
    $('input.cancelFormButton').click(function() 
    {
        CloseModalFormWindow($('.formWrapper'));
    });
});

//Checks Ajax Call Result for Session Expired.
//Refreshes current window to Reload Page and send to login page.
function CheckSession(data) 
{
    if (data.ResultCode == SessionTimeoutCode) 
    {
        window.location = data.ResultObject;
        return false;
    }
}

//Close Modal Window
function CloseMsgWindow() 
{
    $.unblockUI();
}

//Display Modal Window
function DisplayMsgWindow(msg, winTitle) 
{

    var msgObj = $("#winMsg");
    msgObj.text(msg);

    $("#modalWindow").attr("title", winTitle);

    $.blockUI({ message: $('#modalWindow'), baseZ: 99999 });
}

//Displays Modal Window from Html Element
function DisplayModalFormWindow(formElement, formHeight, formWidth, formTitle) 
{

    formElement.dialog({
        bgiframe: true,
        modal: true,
        closeOnEscape : false,
        //hide: 'slide',
        zIndex:900,
        height: formHeight,
        width: formWidth,
        title: formTitle
    });
}

//Hides Modal Form
function HideModalFormWindow(formElement) 
{
    if (formElement.dialog('isOpen')) {
        formElement.dialog('close');    
    }
}

//Shows Modal Form, if It was previously Hidden
function ShowModalFormWindow(formElement) 
{
    if (! formElement.dialog('isOpen')) {
        formElement.dialog('open');
    }
}

function CloseFormWindow() 
{
    CloseModalFormWindow($('.formWrapper'));
}

//Closes and Destroys Form Window.
function CloseModalFormWindow(formElement) 
{
    formElement.dialog('close');
    formElement.dialog('destroy');
}

//Displays Confirmation Window.
function DisplayConfirmationWindow(messgage)
{
    
    $("span#confirmationMessage").html(messgage);

    $("#confirmationWindow").dialog({
        bgiframe: true,
        modal: true,
        title: ResultLabel,
        width: 400,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
                $(this).dialog('destroy');
            }
        }
    });


}

function DisplayConfirmationWindowReload(messgage) {

    $("span#confirmationMessage").html(messgage);

    $("#confirmationWindow").dialog({
        bgiframe: true,
        modal: true,
        title: ResultLabel,
        width: 400,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
                $(this).dialog('destroy');
                window.location.reload();
            }
        }
    });


}

function DisplayConfirmationWindowRedirect(messgage, url, waitMessage) {

    $("span#confirmationMessage").html(messgage);

    $("#confirmationWindow").dialog({
        bgiframe: true,
        modal: true,
        title: ResultLabel,
        width: 400,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
                $(this).dialog('destroy');
                DisplayMsgWindow(waitMessage, waitMessage);
                window.location = url;
            }
        }
    });

    

}


//Validates Only Required Fields_________________________________
function ValidateRequiredFields(selector)
{
    var isValid = true;

    $(selector).each(function()
    {

        if (this.value == '') {

            DisplayConfirmationWindow(this.id + ' ' + IsRequired);
            isValid = false;
        }
    });

    return isValid;
}


//Validates Required Fields _________________________________________________________________________________________________
function ValidateFields(selector) {
    var isValid = true;

    // we validate for is required
    $(selector).each(function() {

        if (this.value == '' || this.value == '-') {
            DisplayConfirmationWindow(this.id + ' ' + IsRequired);
            isValid = false;
            return false;
        }

        if (ValidateData(this) == false) {
            isValid = false;
            return false;
        }
    });

    return isValid;
}

function ValidateDataTypes(selector) {
    var isValid = true;

    $(selector).each(function() {

        if (this.value != '') {
            if (ValidateData(this) == false) {
                isValid = false;
                return false;
            }  
        }

    });

    return isValid;
}

// Validates the datatype
function ValidateData(element) 
{
    var isValid = true;

    var datatype = $(element).attr("datatype");

    if (datatype == null) {
        var classList = $(element).attr('class').split(' ');

        $.each(classList, function(index, item) {
            if (item.substr(0, 1) == '_') {
                datatype = item.substr(1);
                return false;
            }
        });
    }

    if(datatype != null){
        switch (datatype) {
            case "email":
                if (!element.value.match(DataType.Email)) {

                    DisplayConfirmationWindow(element.id + ' ' + IsInvalid);
                    isValid = false;
                    return false;
                }
                break;

            case "phone":
                if (!element.value.match(DataType.Phone)) {

                    DisplayConfirmationWindow(element.id + ' ' + IsInvalid);
                    isValid = false;
                    return false;
                }
                break;

            case "username":
                if (!element.value.match(DataType.UserName)) {

                    DisplayConfirmationWindow(element.id + ' ' + IsInvalid);
                    isValid = false;
                    return false;
                }
                break;

            case "integer":
                if (!element.value.match(DataType.Integer)) {

                    DisplayConfirmationWindow(element.id + ' ' + IsInvalid);
                    isValid = false;
                    return false;
                }
                break;

            case "numeric":
                if (!element.value.match(DataType.Numeric)) {

                    DisplayConfirmationWindow(element.id + ' ' + IsInvalid);
                    isValid = false;
                    return false;
                }
                break;

            case "nonnumeric":
                if (!element.value.match(DataType.NonNumeric)) {

                    DisplayConfirmationWindow(element.id + ' ' + IsInvalid);
                    isValid = false;
                    return false;
                }
                break;

            case "alphanumeric":
                if (!element.value.match(DataType.AlphaNumeric)) {

                    DisplayConfirmationWindow(element.id + ' ' + IsInvalid);
                    isValid = false;
                    return false;
                }
                break;

            case "money":
                if (!element.value.match(DataType.Money)) {

                    DisplayConfirmationWindow(element.id + ' ' + IsInvalid);
                    isValid = false;
                    return false;
                }
                break;

            case "text":
                if (!element.value.match(DataType.Text)) {

                    DisplayConfirmationWindow(element.id + ' ' + IsInvalid);
                    isValid = false;
                    return false;
                }
                break;
            case "date":
                if (!element.value.match(DataType.Date)) {

                    DisplayConfirmationWindow(element.id + ' ' + IsInvalid);
                    isValid = false;
                    return false;
                }
                break;
        }
    }

    return isValid;
}

//Builds the Post Data as JSON____________________________________________________________________________________________________
function BuildPostData(elementSelector) {

    var postData = {};

    $(elementSelector).each(function() {
        postData[this.name] = $.trim(this.value);
    });

    return postData;
}

// Converts a date returned by a json call into a javascript date
function ConvertJsonToDate(jsonDate)
{
    // Convert the date by extracting the date number
    var jsonDateRe = /(\d+)/g;
    
    // Create the javascript date
    return new Date(parseInt(jsonDate.match(jsonDateRe)[0]));
}

// Converts a date returned by a json call into a javascript date
function ConvertJsonToDateString(jsonDate, dateFormat, includeTime)
{
    // Convert the date to a string
    var theDate = ConvertJsonToDate(jsonDate);
    
    var dateHours = theDate.getHours();
    var dateMins = theDate.getMinutes();
    
    if (dateMins < 10)
    {
        dateMins = "0" + dateMins;
    }
    
    if (dateHours < 10)
    {
        dateHours = "0" + dateHours;
    }
    
    // Format the time
    var dateTime = null;
    if (includeTime == true)
    {
        dateTime = " " + dateHours + ":" + dateMins;
    }
    
    // Return the fully formatted date time string
    return $.datepicker.formatDate(dateFormat, theDate) + dateTime;
}

// Called to format a decimal to a proper string
function FormatCurrency(num)
{
    num = num.toString().replace(/\$|\,/g,'');
    if (isNaN(num))
    {
        num = "0";
    }
    
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    
    if (cents < 10)
    {
        cents = "0" + cents;
    }
    
    for (var i = 0; i < Math.floor((num.length - (1+i)) / 3); i++)
    {
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length-(4 * i + 3));
    }
    
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

// Called to format a number with commas
function FormatNumber(amount)
{
    amount = amount.toString().replace(/\$|\,/g,'');
    
    if (isNaN(amount))
    {
        amount = "0";
    }
    
    x = amount.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';

    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1))
    {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    
    return x1 + x2;
}

$(document).ready(function() {
    // Popup window
    $("#popupWindow").click(function() {
        if (PopupWindowURL != null) {
            openWindowWithScrollBar(PopupWindowURL);
        }
        return false;
    });
});

function openWindow(s) {
    if (document.getElementById) {
        var w = 0;
        var h = 0;
        w = document.body.clientWidth;
        h = document.body.clientHeight;
    }
    var popW = 800, popH = 600;
    var leftPos = (w - popW) / 2, topPos = (h - popH) / 2;
    window.open(s, '_blank', 'directories=no,fullscreen=no,height=600,location=no,menubar=no,resizable=yes,scrollbars=no,statusbar=no,titlebar=no,toolbar=no,width=800,left=' + leftPos + ',top=' + topPos)
}

function openWindowWithScrollBar(s) {
    if (document.getElementById) {
        var w = 0;
        var h = 0;
        w = document.body.clientWidth;
        h = document.body.clientHeight;
    }
    var popW = 800, popH = 600;
    var leftPos = (w - popW) / 2, topPos = (h - popH) / 2;
    window.open(s, '_blank', 'directories=no,fullscreen=no,height=600,location=no,menubar=no,resizable=yes,scrollbars=yes,statusbar=no,titlebar=no,toolbar=no,width=800,left=' + leftPos + ',top=' + topPos)
}    

