function GetQueryStringParams(sParam) {

    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
}



Number.prototype.padLeft = function (base, chr) {
    var len = (String(base || 10).length - String(this).length) + 1;
    return len > 0 ? new Array(len).join(chr || '0') + this : this;
};

Date.prototype.toDisplayTimeString = function (o) {
    var ap = " AM";
    var hours = this.getHours();
    if (hours >= 12) {
        ap = " PM";
        if (hours > 12) {
            hours = hours - 12;
        }
    } else if (hours === 0) {
        hours = 12;
    }

    var mins = this.getMinutes();
    if (mins <= 9) {
        mins = "0" + mins;
    }

    return [hours, mins].join(":") + ap;
};


var widgetId;
var macAddress;
var hmac;
var userID;
var widgetSize;
var widgetRefreshIntervalMilliseconds;
var widgetjQueryTimeOutMilliseconds;
var googleAnalyticsTrackingId;
var schedule;
var widgetId = GetQueryStringParams('widgetId') || GetQueryStringParams('widgetid');
var env = GetQueryStringParams('env') || "";
var debugMode = GetQueryStringParams('debug') || "";
var logMode = GetQueryStringParams('log') || "";
var delayTime = GetQueryStringParams('delay') || "";
var failTest = GetQueryStringParams('fail') || "";
var redirect = GetQueryStringParams("red");

var hitCount_1 = 0;
var hitCount_2 = 0;
var startTime = new Date();
var endTime = null;
var loadingTime = null;
var OasWidget;
var gaService = null;
var ruleInfo = null;
var widgetData = null;
var retryCount = 0;


var success = function (jsondata) {

    //var tm = logLoadingTime(widgetId, "Loading time");

    hitCount_1 = 0;
    if (jsondata) {
        jsondata = $.parseJSON(jsondata);
        jsondata = jsondata[0];
    }
    if (jsondata != null) {
        macAddress = jsondata.MacAddress;
        userID = jsondata.UserId;
        hmac = jsondata.HmacKey;
        widgetSize = jsondata.Size;
        schedule = jsondata.Schedule;

        widgetRefreshIntervalMilliseconds = jsondata.widgetRefreshIntervalMilliseconds;
        widgetjQueryTimeOutMilliseconds = jsondata.widgetjQueryTimeOutMilliseconds;
        googleAnalyticsTrackingId = jsondata.googleAnalyticsTrackingId;

        // Manual All Clear message
        $("#MacMessage").text(jsondata.manualAllClearMessage);

        if (jsondata.Name !== "" && jsondata.Name != null) {
            $('#sitename').html(jsondata.Name).text();

            displayErrorMessage(false);
            ruleInfo = jsondata.RuleInfo;
            widgetData = jsondata.widgetData;
            refreshWidgetInfo();
            gaService.gaEvent("PageLoaded", tm)
            var tm = logLoadingTime(widgetId, "Loading time");
        }
        else {
            var tm = logLoadingTime(widgetId, "Loading time error");
            if (jsondata.Status == "Invalid Widget Id") {
                displayErrorMessage(true);
                gaService.gaEvent("Ivalid Widget Id Error", "")

            }
            else {
                gaService.gaEvent("PageLoaded Error", tm)
                loadWidgetInfo();
            }
        }
    }
    else {
        var tm = logLoadingTime(widgetId, "Loading time error");
        gaService.gaEvent("PageLoaded Error", tm);
        loadWidgetInfo();
    }

};

// This method is called only when there is error
function loadWidgetInfo(delay) {
    if (!delay) {
        if (retryCount == 0) {
            delay = configuration.retryTimeout;
        }
        //else if (retryCount == 1) {
        //    delay = configuration.retrySecondTimeout;
        //}
        else {
            delay = configuration.retryExtendedTimeout;
        }
    }
    retryCount++;
    setTimeout(function () {
        getWidgetParams();
    }, delay);
}

$(document).ready(function () {
    
    if (debugMode) {
        debugger;
    }
    if (!redirect && typeof (version) === "undefined") {
        return;
    }
    var initTime = 50 + Math.random() * 500;
    // Add delay to script to load.
    setTimeout(function () {
        gaService = new gaServiceFunc();
        gaService.gaInit(configuration.ga, "Widget Request", widgetId);

        if (widgetId === undefined || widgetId === '') {
            //error handling for invalid widget id
            //left blank intentionally
            displayErrorMessage(true);
            gaService.gaEvent("Ivalid Widget Id Error", "");

        } else {
            pageStart = new Date();
            getWidgetParams();

        }
    }, initTime);
});

// Called once at start
function getWidgetParams() {

    var url = configuration.baseURL;
    if (env) {
        var envUrl = configuration["baseURL" + "_" + env];
        if (envUrl)
            url = envUrl;
    }
    if (failTest == "info")
        url = configuration.failTestURL;

    startTime = new Date();

    url = url.replace("[widgetId]", widgetId);

    $.ajax({
        type: 'GET',
        url: url,
        data: { todo: "jsonp" },
        dataType: "jsonp",
        crossDomain: true,
        cache: false,
        timeout: configuration.requestTimeout, //15000,
        //success:success,
        success: function (jsondata) {
            hitCount_1 = 0;
            var tm = 100;
            if (delayTime)
                tm = parseInt(delayTime);
            setTimeout(function () {
                success(jsondata);
            }, tm);

        },
        error: function (jqXHR, textStatus, errorThrown) {
            var tm = logLoadingTime(widgetId, "Loading time error");
            gaService.gaEvent("PageLoad Error", tm);

            loadWidgetInfo();

            //hitCount_1++;
            //var retry = configuration.retryTimeout; // 3000; // + hitCount_1 * 1000;
            //if (retryCount > 0) {
            //    retry = configuration.retryExtendedTimeout;
            //}
            //retry++;
            //setTimeout(function () {
            //    getWidgetParams();
            //}, retry);


        }
    });

}

function refreshWidgetInfo() {

    OasWidget.ruleInfo = ruleInfo;
    OasWidget.widgetData = widgetData;

    OasWidget.debugMode = debugMode;
    OasWidget.logMode = logMode;
    OasWidget.env = env;
    OasWidget.failTest = failTest;
    OasWidget.requestTimeout = configuration.requestTimeout;
    OasWidget.refreshInterval = parseInt(widgetRefreshIntervalMilliseconds);
    OasWidget.counterInterval = 1000;
    OasWidget.jQueryTimeOut = parseInt(widgetjQueryTimeOutMilliseconds);
    OasWidget.dataUrl = configuration.refreshURL + '?widgetId=' + widgetId + '&macAddress=' + macAddress + '&hmacKey=' + hmac + '&userID=' + userID;
    OasWidget.googleAnalyticsTrackingId = googleAnalyticsTrackingId;

    var widget = OasWidget;

    widget.initSiteRefresh();
}

function displayLoadingMessage(show) {
    if (show)
        $('#LoadingMessage').show();
    else {
        $('#LoadingMessage').hide();
    }
}
function displayErrorMessage(show, message) {
    if (message) {
        $('#errorMessage').text(message);
    }
    if (show)
        $('#errorContainer').show();
    else {
        $('#errorContainer').hide();
    }


}
function logLoadingTime(id, title) {
    if (!id)
        id = "";
    endTime = new Date();
    var tm = (endTime.getTime() - startTime.getTime()) / 1000;
    if (logMode == "true") {
        var dt = this.startTime.toString();
        console.log(title + " for " + id + " = " + tm + " sec at " + dt);
    }
    return tm;
}



function gaServiceFunc() {
    this.gaInit = function (gid, action, widgetid) {
        this.widgetId = widgetid;

        (function (i, s, o, g, r, a, m) {
            i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date(); a = s.createElement(o),
                m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
        })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

        if (!action)
            action = "PageLoad";
        ga('create', gid, 'auto');

        if (action) {
            ga('send', 'pageview', {
                'dimension1': action,
                'widgetid': this.widgetId
            });
        }
        else {
            ga('send', 'pageview');
        }
    };
    this.gaEvent = function (action, time) {

        ga('send', 'event', action, this.widgetId, time);
    };


    // Press d key to turn on data refresh fail test when debug=true
    document.body.onkeydown = function (e) {
        var keyCode = e.keyCode;


        if (logMode && keyCode == 68) {

            if (!OasWidget.failTest)
                OasWidget.failTest = "data";
            else
                OasWidget.failTest = "";

            alert("Data fail test is " + (OasWidget.failTest == "data" ? "on" : "off"));
        }


    };
}