﻿if (top.location !== window.location) {
    top.location = window.location.href;
}

var pageTracker;

var Cwo = {
    that: this,

    SetSessionCookie: function (c_name, value) {
        document.cookie = c_name + "=" + value + ";path=/";
    },

    GetCookieTime: function (myDate) {
        var retString = myDate.getMonth() + 1 + "/" + myDate.getDate() + "/" + myDate.getFullYear() + " " + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds();
        return retString;
    },

    RegisterNamespace: function (nameSpace) {
        var nsParts = nameSpace.split("."),
            root = window,
            i = 0;

        for (i = 0; i < nsParts.length; i += 1) {
            if (typeof root[nsParts[i]] === "undefined") {
                root[nsParts[i]] = {};
            }
            root = root[nsParts[i]];
        }
    },

    Collection: function () {
        this.Items = [];

        this.Item = function (index) {
            return this.Items[index];
        };
        this.Add = function (item) {
            this.Items[this.Items.length] = item;
        };
        this.Remove = function (item) {
            var index = this.IndexOf(item);

            if (index > -1) {
                this.Items = this.Items.slice(0, index).concat(this.Items.slice(index + 1, this.Items.length));
            }
        };
        this.Contains = function (item) {
            if (this.IndexOf(item) > -1) {
                return true;
            } else {
                return false;
            }
        };
        this.IndexOf = function (item) {
            var i;
            for (i = 0; i < this.Items.length; i += 1) {
                if (this.Items[i] === item) {
                    return i;
                }
            }
            return -1;
        };
        this.Count = function () {
            // Returns the size of the collection
            return this.Items.length;
        };
        this.Clear = function () {
            // Clears the collection
            var i;
            for (i = 0; i < this.Items.length; i += 1) {
                this[i] = null;
            }
        };
    },

    LogMIActivity: function (activityIdentifier) {
        // JSLint error caused by Google-Analytics code requiring the use of a global variable '_gaq' in the main.master page
        // To suppress this error the following commented line has been added. *** Do not remove ***
        /*global _gaq */
        if (activityIdentifier === undefined) {
            _gaq.push(['_trackPageview']);
        } else {
            _gaq.push(['_trackPageview', activityIdentifier]);
        }
    },

    GetPageTracker: function () {
        if (!pageTracker) {
            if (typeof (_gat) === "object") {
                pageTracker = _gat._getTracker(Cwo.GACode);
            }
        }
        return pageTracker ? pageTracker : null;
    },

    AjaxCall: function (serviceUrl, jsonData, successCallback, errorCallback, analyticsCode, suppressDefaultError) {
        var onSuccess = null,
            guid = "";

        if (analyticsCode !== null) {
            onSuccess = function (data, status) {
                successCallback(data, status);
                try {
                    Cwo.LogMIActivity(analyticsCode);
                } catch (err) { }
            };
        } else {
            onSuccess = function (data, status) {
                successCallback(data, status);
            };
        }

        this.timeout = Cwo.Common.GetCookie("SessionTimeout");

        if (this.timeout !== "") {
            this.timeoutdate = new Date(this.timeout);
            this.currentTime = new Date();

            if (this.currentTime.getTime() > this.timeoutdate.getTime()) {
                
                if (Cwo.Common.GetCookie("EATrackerID") === "") {
                    guid = "00000000-0000-0000-0000-000000000000";
                } else {
                    guid = Cwo.Common.GetCookie("EATrackerID");
                }

                this.currentTime.setMinutes(this.currentTime.getMinutes() + TrackerSessionTimeoutPeriod);
                Cwo.SetSessionCookie("SessionTimeout", Cwo.GetCookieTime(this.currentTime));

                Cwo.AjaxCall("/webservices/UserAccount.asmx/TrackerIDRefresh",
                                    "{ trackerID:'" + guid + "'}",
                                    function () { Cwo.AjaxCall(serviceUrl, jsonData, successCallback, errorCallback, analyticsCode); },
                                    null,
                                    null);
            } else {
                if (jsonData === null) {
                    jsonData = "{}";
                }
                $.ajax({
                    type: "POST",
                    //timeout: 30000, // TODO : We need to handle timeouts and errors in here (call the error callback after X seconds for a timeout?)
                    url: serviceUrl,
                    data: jsonData,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: onSuccess,
                    error:
                        function (xhr, err, ex) {
                            if (errorCallback !== null) {
                                errorCallback();
                            } else {
                                if (!suppressDefaultError) {
                                    // Display error message box
                                    Cwo.Error.Popup("There was a problem", "An unknown error occured. There may be a problem connecting to our website. Please wait a few minutes and try again.\n\n" + err + "\n\n" + xhr.responseText);
                                }
                            }
                        }
                });
            }
        }
    }
};
