﻿// Callback function on error
// First argument is always "error" if server side code throws any exception
// Second argument is usercontext control pass at the time of call
// Third argument is methodName (server side function name)
var _datLastAjaxCallError = new Date();
var _intCountAjaxErrorMessagesForUser = 0;
function OnAjaxCallError(error, userContext, methodName) {
    if (error != null) {
        var strError = error.get_message();
        if (strError != "Thread was being aborted.") {
            try {
                SAServices.LogAjaxError(methodName, strError, null, null, null);
            }
            catch (e)
            { }
            // probabbly a connection error...
            var strPage = document.location.href;
            //alert(strPage);
            if (true || !(strPage.indexOf("localhost") >= 0)) {

                //alert("AJAX ERROR> Method name: " + methodName + ", Error message: " + strError);
                //alert("Internet connection lost - please Log On again.");
                //To suppress multiple messages... see Guy's email from June 02, 2011 1:39 PM [Mantis 818]
                if (DateDiff.inSeconds(_datLastAjaxCallError, new Date()) > 5) {
                    _datLastAjaxCallError = new Date();
                    _intCountAjaxErrorMessagesForUser++;
                    if (_intCountAjaxErrorMessagesForUser >= 3) {
                        alert("Error occurred - Please re-login.");
                        top.location = "/Login.aspx";
                    }
                    else
                        alert("Error occurred - Please submit request again or contact an Administrator.");
                }

            }
            else {
                alert("AJAX ERROR> Method name: " + methodName + ", Error message: " + strError);
            }
        }

    }
    RemovePleaseWait();

    //Dont log out the user... see Guy's email from June 02, 2011 1:39 PM [Mantis 818]
    //top.location = "/Login.aspx";
}

var DateDiff = {

    inSeconds: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2 - t1) / (1000));
    },

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2 - t1) / (24 * 3600 * 1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2 - t1) / (24 * 3600 * 1000 * 7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M + 12 * d2Y) - (d1M + 12 * d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear() - d1.getFullYear();
    }
}


// *********************************** Queue AJAX calls for Server session blocking calls ***********************************
// copied from http://www.codeproject.com/KB/ajax/aspnetajaxtips.aspx
var GlobalCallQueue = {
    _callQueue: [],    // Maintains the list of webmethods to call

    _callInProgress: 0,    // Number of calls currently in progress by browser

    _maxConcurrentCall: 1, // Max number of calls to execute at a time

    _delayBetweenCalls: 50, // Delay between execution of calls 

    call: function(servicePath, methodName, useGet,
        params, onSuccess, onFailure, userContext, timeout) {
        var queuedCall = new QueuedCall(servicePath, methodName, useGet,
            params, onSuccess, onFailure, userContext, timeout);
        //log("methodName = " + methodName);
        if (methodName == "GetUnitTreeTooltip")
            queuedCall.execute();
        else {
            Array.add(GlobalCallQueue._callQueue, queuedCall);
            GlobalCallQueue.run();
        }
    },
    run: function() {
        /// Execute a call from the call queue


        if (0 == GlobalCallQueue._callQueue.length) return;
        if (GlobalCallQueue._callInProgress <
            GlobalCallQueue._maxConcurrentCall) {
            GlobalCallQueue._callInProgress++;
            // Get the first call queued

            var queuedCall = GlobalCallQueue._callQueue[0];
            Array.removeAt(GlobalCallQueue._callQueue, 0);

            // Call the web method

            queuedCall.execute();
        }
        else {
            // cannot run another call. Maximum concurrent 

            // webservice method call in progress

        }
    },
    callComplete: function() {
        GlobalCallQueue._callInProgress--;
        GlobalCallQueue.run();
    }
};

QueuedCall = function(servicePath, methodName, useGet, params,
    onSuccess, onFailure, userContext, timeout) {
    this._servicePath = servicePath;
    this._methodName = methodName;
    this._useGet = useGet;
    this._params = params;

    this._onSuccess = onSuccess;
    this._onFailure = onFailure;
    this._userContext = userContext;
    this._timeout = timeout;
}

QueuedCall.prototype =
{
    execute: function() {
        Sys.Net.WebServiceProxy.original_invoke(
            this._servicePath, this._methodName, this._useGet, this._params,
            Function.createDelegate(this, this.onSuccess), // Handle call complete

            Function.createDelegate(this, this.onFailure), // Handle call complete

            this._userContext, this._timeout);
    },
    onSuccess: function(result, userContext, methodName) {
        if(this._onSuccess!=null)
            this._onSuccess(result, userContext, methodName);
        GlobalCallQueue.callComplete();
    },
    onFailure: function(result, userContext, methodName) {
        if (this._onFailure != null)
            this._onFailure(result, userContext, methodName);
        GlobalCallQueue.callComplete();
    }
};

var _intTotalAJAXCalls = 0;
$(document).ready(function() {
    //if no AJAX (script manager is present)
    if (typeof (Sys) == "undefined")
        return;
    Sys.Net.WebServiceProxy.original_invoke = Sys.Net.WebServiceProxy.invoke;
    Sys.Net.WebServiceProxy.invoke =
                function Sys$Net$WebServiceProxy$invoke(servicePath, methodName,
                    useGet, params, onSuccess, onFailure, userContext, timeout) {
                    _intTotalAJAXCalls++;
                    log(methodName + ': ' + _intTotalAJAXCalls);
                    GlobalCallQueue.call(servicePath, methodName, useGet, params,
                    onSuccess, onFailure, userContext, timeout);
                }

});
// ******************************************************************************************************************

