﻿

//****************************************************************************************************
//* Main Function
//****************************************************************************************************

$(document).ready(function () {

    $('form').find(':text,:password,select,textarea,:radio,:checkbox').addClass('inpTextbox');

    $('form').find(':text,:password,select,textarea,:radio,:checkbox').focus(function () {
        $(this).removeClass("inpTextbox").addClass("focusField");
    });

    $('form').find(':text,:password,select,textarea,:radio,:checkbox').blur(function () {
        $(this).removeClass("focusField").addClass("inpTextbox");
    });

    $(":input[tabindex=0]").focus();

    $('[type="submit"]').live('click', function (e) {

        SetSystemStatus();

        var _actEnt = $(this).attr('id').split("_");

        walkTheForm($(this).parents('form')[0], _actEnt);

        return false;

    });

});

//****************************************************************************************************
//* Prepare Input Form Variables and Call Webservice
//****************************************************************************************************

function walkTheForm(inForm, inActEnt) {

    var _action = inActEnt[0];
    var _entity = inActEnt[inActEnt.length - 1];

    var inputData = "";

    $(':input', inForm).each(function () {
        if ($(this)[0].type != 'submit' && $(this)[0].type != 'reset') {
            if (this.name.substr(0, 3) == 'txt') {
                inputData += "in" + this.name.substr(3, this.name.length) + ": '" + this.value + "',";
            }
            if (this.name.substr(0, 3) == 'int') {
                inputData += "in" + this.name.substr(3, this.name.length) + ": " + this.value + ",";
            }
            if (this.name.substr(0, 3) == 'bln') {
                inputData += "in" + this.name.substr(3, this.name.length) + ": " + this.value + ",";
            }
        }
    });

    inputData = "{" + inputData.substr(0, inputData.length - 1) + "}";

    //alert(GetServerName() + "Business/" + _entity + "/" + _entity + ".asmx/" + _action);

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: GetServerName() + "Business/" + _entity + "/" + _entity + ".asmx/" + _action,
        data: inputData,
        dataType: 'json',
        success: function (response) {
            window.location = GetServerName() + response.d;
        },
        error: function (request, status, error) {
            var r = jQuery.parseJSON(request.responseText);
            if (r.Message) {
                $("#lbl" + _entity + "Alert").html(r.Message);
            }
            else {
                $("#lbl" + _entity + "Alert").html(request.responseText);
            }

            $(":input[tabindex=0]").focus();
            $("select:first").focus();

            ResetSystemStatus();
        }
    });  // Close AJAX

}


//****************************************************************************************************
//* Load Validate JS
//****************************************************************************************************

function loadValidateJS() {
    checkloadjscssfile('/JScript/Validate.js', 'js');
}

//****************************************************************************************************
//* Global Variables
//****************************************************************************************************

var filesadded = "" //list of files already added

//****************************************************************************************************
//* Check Load JS or CSS File
//****************************************************************************************************

function checkloadjscssfile(filename, filetype) {

    filename = GetServerName() + filename;

    if (filesadded.indexOf("[" + filename + "]") == -1) {
        loadjscssfile(filename, filetype)
        filesadded += "[" + filename + "]" //List of files added in the form "[filename1],[filename2],etc"
    }
    else {
        alert(filetype + ", File Already Added!");
    }
}

//****************************************************************************************************
//* Load JS or CSS File
//****************************************************************************************************

function loadjscssfile(filename, filetype) {
    if (filetype == "js") { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype == "css") { //if filename is an external CSS file
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

//****************************************************************************************************
//* Remove JS or CSS File
//****************************************************************************************************

function removejscssfile(filename, filetype) {
    var targetelement = (filetype == "js") ? "script" : (filetype == "css") ? "link" : "none" //determine element type to create nodelist from
    var targetattr = (filetype == "js") ? "src" : (filetype == "css") ? "href" : "none" //determine corresponding attribute to test for
    var allsuspects = document.getElementsByTagName(targetelement)
    for (var i = allsuspects.length; i >= 0; i--) { //search backwards within nodelist for matching elements to remove
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename) != -1)
            allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
    }
}

//*************************************************************************************************************
//*  Set System Status Indicator
//*************************************************************************************************************

function SetSystemStatus() {

    //$('#lblSystemStatus').html(GetLoading("Processing"));
}

//*************************************************************************************************************
//*  Reset System Status Indicator
//*************************************************************************************************************

function ResetSystemStatus() {
    $('#lblSystemStatus').html("");
}

//*************************************************************************************************************
//*  Get Loading Message / Progress Indicator
//*************************************************************************************************************

function GetLoading(inMessage) {
    return (" " + inMessage + "..." + "<img src='" + GetServerName() + "images/progress.gif' />");
}

//****************************************************************************************************
//* Get Server Name
//****************************************************************************************************

function GetServerName() {
    var str = window.location.protocol + '//' + window.location.hostname;
    if (window.location.hostname == "localhost") {
        str = str + "/auroratechgroup"
    }
    str += "/";

    return str;
}

//*************************************************************************************************************
//*  Do Entity Paging
//*************************************************************************************************************

function SetPaging(inEntity, inCurrentPage) {

    SetSystemStatus();

    _data = "{inCurrentPage:" + inCurrentPage + ", ";
    _data += "inEntity:'" + inEntity + "'}";

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: GetServerName() + "Business/Paging/Paging.asmx/Pager",
        data: _data,
        dataType: 'json',
        success: function (response) {
            window.location = window.location.pathname;
        },
        error: function (request, status, error) {
            var _entityAlert = "lbl" + inEntity + "Alert";
            var r = jQuery.parseJSON(request.responseText);
            if (!isEmpty(r)) {
                $("#" + _entityAlert).html("Error " + r.Message);
            }
            else {
                $("#" + _entityAlert).html("Error " + request.responseText);
            }
            ResetSystemStatus();
        }
    });    // Close AJAX
}

function isEmpty(str) { 
    return (!str || 0 === str.length); 
}
