﻿function IsJqueryLoaded() {
    if (typeof jQuery == 'undefined') {
        // jQuery is NOT loaded
        return false;
    }
    return true;
}

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function IsValidEmailAddress(str) {

    var at = "@"
    var dot = "."
    var lat = str.indexOf(at)
    var lstr = str.length
    var ldot = str.indexOf(dot)
    if (str.indexOf(at) == -1) {
        return false
    }

    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        return false
    }

    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        return false
    }

    if (str.indexOf(at, (lat + 1)) != -1) {
        return false
    }

    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        return false
    }

    if (str.indexOf(dot, (lat + 2)) == -1) {
        return false
    }

    if (str.indexOf(" ") != -1) {
        return false
    }

    return true
}

function ValidateForm() {
    var emailID = document.frmSample.txtEmail

    if ((emailID.value == null) || (emailID.value == "")) {
        alert("Please Enter your Email ID")
        emailID.focus()
        return false
    }
    if (echeck(emailID.value) == false) {
        emailID.value = ""
        emailID.focus()
        return false
    }
    return true
}

function CreateNewAjaxRequest() {
    var request1 = new AjaxRequest();
    request1.data = [];
    return request1;
}

function AjaxRequest() {
    AjaxRequest.data = [];
}
AjaxRequest.prototype = new Object();
AjaxRequest.prototype.data = [];
AjaxRequest.prototype.add_data = function(name, value) {
    var item1 = new Object();
    item1.Name = name;
    item1.Value = value;
    var itemCount = this.data.length;
    this.data[itemCount] = item1;
    log.debug("Added data [" + itemCount + "]'" + name + "'='" + value + "' to AjaxRequest");
};
AjaxRequest.prototype.toJson = function() {
    var ajaxRequest1 = new Object();
    ajaxRequest1.Data = this.data;
    return JSON.stringify(ajaxRequest1)
}

function GetAjaxResponse(msg1, servicemethod1) {
    var AjaxResponse1 = null;
    try {
        var AjaxResponse1 = JSON.parse(msg1);
        if (AjaxResponse1.Successful != undefined && AjaxResponse1.Successful == false) {
            if (AjaxResponse1.Messages.length > 0)
                jAlert('error', AjaxResponse1.Messages[0], 'An error has occurred!');
            else
                jAlert('error', "An error occured while processing your request. No more information available about this error.", 'An error has occurred!');
        }
        else {
            return AjaxResponse1;
        }
    }
    catch (error1) {
        jAlert('error', error1, 'An error has occurred reading server response. "' + servicemethod1 + '"!');
    }
    return AjaxResponse1;
}

function SendAjaxRequest(AjaxRequest1) {

    log.debug("Sending Ajax request to service = '" + AjaxRequest1.service + "'");

    // determine if AjaxRequest is valid
    if (AjaxRequest1.service === undefined) {
        jAlert('error', 'This request does not have a valid service call', 'Error!');
    }

    var data1 = JSON.stringify(AjaxRequest1);

    var ajaxUrl = "/ajax.aspx?service=" + AjaxRequest1.service;
    if (AjaxRequest1.response_datatype !== undefined) {
        ajaxUrl = "/ajax.aspx?service=" + AjaxRequest1.service + "&datatype=" + AjaxRequest1.response_datatype;
    }

    log.debug("Sending Ajax Service request to  url= " + ajaxUrl + "; Data = " + data1);

    // define a functon to run upon a successful response
    var OnSuccess = function(msg) { log.debug("Received Ajax Service request for: " + AjaxRequest1.service + "; Data = " + msg); };
    if (AjaxRequest1.onSuccess !== undefined) {
        // overwrite it if another if provided
        //OnSuccess = AjaxRequest1.onSuccess;
        OnSuccess = function(msg) {
            // (recommended) add logging to success method
            log.debug("Received Ajax response for: " + AjaxRequest1.service + "; Data = " + msg);
            // convert message to a response object
            var AjaxResponse1 = JSON.parse(msg);

            if (AjaxResponse1 != null) {
                if (AjaxResponse1.Successful) {
                    // retrieve objects as follows:
                    // var OrgDetails = JSON.parse(AjaxResponse1.Json);
                    // retrieve data values as follows:
                    // $("#lblOrganizationName").html(AjaxResponse1.Json.DisplayName);
                    // $("#lblOrganizationSummary").html(AjaxResponse1.Json.Description);

                    //$("#Person1").html(AjaxResponse1.Json.FirstName);
                    AjaxRequest1.onSuccess(AjaxResponse1);

                }
                else {
                    if (AjaxResponse1.Messages !== undefined && AjaxResponse1.Messages.length > 0)
                        jAlert('error', AjaxResponse1.Messages[0], 'An error has occurred!');
                    else
                        jAlert('error', "No more information available.", 'An error has occurred!');
                }
            }

        };
    }
    // define a functon to run upon an error response
    var OnError = function(xhr, error) {
        log.debug("Error response: State=" + xhr.readyState + "; Error =" + error);
        switch (xhr.readyState) {
            case 0:
                // The object has been created, but not initialized (the open method has not been called).
                break;
            case 1:
                // A request has been opened, but the send method has not been called. 
                break;
            case 2:
                // The send method has been called. No data is available yet. 
                break;
            case 3:
                // Some data has been received; however, neither responseText nor responseBody is available.
                break;
            case 4:
                // All the data has been received.
                if (error == "parsererror") {
                    jAlert('error', 'An error has occurred while parsing the response from your request.', 'Parse Error');
                    return;
                }
                if (xhr.status == "404") {
                    jAlert('error', 'The resource requested was not found.', 'Error 404');
                    return;
                }
                else {
                    jAlert('error', 'An error has occurred. Stats = ' + xhr.readyState, 'Error!');
                    return;
                }
                break;
            default:
                jAlert('error', 'An error has occurred!', 'Error!');
        }
    };

    $.ajax({
        type: "POST",
        url: ajaxUrl,
        data: data1,
        success: OnSuccess,
        error: OnError

    });
}

String.repeat = function(chr, count) {
    var str = "";
    for (var x = 0; x < count; x++) { str += chr };
    return str;
}
String.prototype.padL = function(width, pad) {
    if (!width || width < 1)
        return this;
    if (!pad) pad = " ";
    var length = width - this.length
    if (length < 1) return this.substr(0, width);
    return (String.repeat(pad, length) + this).substr(0, width);
}
String.prototype.padR = function(width, pad) {
    if (!width || width < 1)
        return this;
    if (!pad) pad = " ";
    var length = width - this.length
    if (length < 1) this.substr(0, width);
    return (this + String.repeat(pad, length)).substr(0, width);
}

String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }

Date.prototype.formatDate = function(format) {

    var date = this;
    if (!format)
        format = "MM/dd/yyyy";

    var month = date.getMonth() + 1;
    var year = date.getFullYear();

    format = format.replace("MM", month.toString().padL(2, "0"));

    if (format.indexOf("yyyy") > -1)
        format = format.replace("yyyy", year.toString());
    else if (format.indexOf("yy") > -1)
        format = format.replace("yy", year.toString().substr(2, 2));

    format = format.replace("dd", date.getDate().toString().padL(2, "0"));

    var hours = date.getHours();
    if (format.indexOf("t") > -1) {
        if (hours > 11)
            format = format.replace("t", "pm")
        else
            format = format.replace("t", "am")
    }
    if (format.indexOf("HH") > -1)
        format = format.replace("HH", hours.toString().padL(2, "0"));
    if (format.indexOf("hh") > -1) {
        if (hours > 12) hours - 12;
        if (hours == 0) hours = 12;
        format = format.replace("hh", hours.toString().padL(2, "0"));
    }
    if (format.indexOf("mm") > -1)
        format = format.replace("mm", date.getMinutes().toString().padL(2, "0"));
    if (format.indexOf("ss") > -1)
        format = format.replace("ss", date.getSeconds().toString().padL(2, "0"));
    return format;
}

var namespace = function(name, separator, container) {
    var ns = name.split(separator || '.'),
    o = container || window,
    i,
    len;
    for (i = 0, len = ns.length; i < len; i++) {
        o = o[ns[i]] = o[ns[i]] || {};
    }
    return o;
};

/* 

===========================================
namespace function
===========================================
Example usage:

com.example.namespace.test = function() {
alert("In namespaced function.");
};
com.example.namespace.test();

or as a single line:

namespace("com.example.namespace").test = function(){
alert("In namespaced function.");
};

*/

