Core.DOM.Ready(function () {
    Core.Include({
        Widgets: []
        , Events: {
            onLoad: function () {
                var tsv = [
                    { text: '1 minute', value: 1 }
                    , { text: '3 minutes', value: 3 }
                    , { text: '6 minutes', value: 6 }
                    , { text: '1/4 hour', value: 1 * 15 }
                    , { text: '1/2 hour', value: 1 * 30 }
                    , { text: '1 hour', value: 1 * 60 }
                    , { text: '6 hours', value: 1 * 60 * 6 }
                    , { text: '8 hours', value: 1 * 60 * 8 }
                    , { text: '12 hours', value: 1 * 60 * 12 }
                    , { text: '1 day', value: 1 * 60 * 24 }
                    , { text: '2 days', value: 1 * 60 * 24 * 2 }
                    , { text: '4 days', value: 1 * 60 * 24 * 4 }
                    , { text: '1 week', value: 1 * 60 * 24 * 7 }
                    , { text: '10 days', value: 1 * 60 * 24 * 10 }
                    , { text: '2 weeks', value: 1 * 60 * 24 * 7 * 2 }
                    , { text: '1 month', value: 1 * 60 * 24 * 7 * 4 }
                ];

                var scopeIndex = 3;

                var timezone = getParameterByName('timezone');
                var QP = new Core.Database.QueryParameter('@TimeZone', 'CHAR', (timezone != "") ? timezone : null);

                var defaultViews = [];

                var view = getParameterByName('view');

                var viewparam = false; 
                if (view != undefined && view != null && view != "") {
                    viewparam = true; 
                    defaultViews.push(view);
                }

                defaultViews.push("Demo");

                var connectionString = getParameterByName('connstring');
                var catalog = getParameterByName('catalog');

                var datetime = new moment(getParameterByName('datetime'), 'YYYYMMDDHHmmss').toDate();
                var start = new moment(getParameterByName('start'), 'YYYYMMDDHHmmss').toDate();
                var end = new moment(getParameterByName('end'), 'YYYYMMDDHHmmss').toDate();

                if ((start) && (end)) {
                    var value = parseInt((end - start) / 1000 / 60, 10);

                    tsv.push({
                        text: 'Custom',
                        value: value,
                    });

                    _setStateCookie({
                        scope: {
                            start: start,
                            end: end,
                            id: value * 1000 * 60,
                        },
                    });
                }

                var options = {
                    DatabaseParameters: {
                        ConnectionStringName: connectionString, Catalog: catalog
                        , Fixed: [QP]
                    }
                    , Export: { OutputFileName: "Trending", Source: "SERVERCURRENTVIEW" }
                    , View: {
                        Title: " "
                        , ViewNames: defaultViews
                        , ForceView: viewparam
                        , Mode: 'Range'
                    }
                    , Configuration: {
                        TimeSpanValues: tsv,
                        //SelectedIndex: scopeIndex,
                        AutoRefresh: true
                        , Value: 5, MinValue: 1, Unit: "s"
                        , Views: {
                            GlobalViews: true, 
                            GlobalViewsByDefault: false, 
                            ViewGroups: true
                        }
                        , PersistStateCookies: true
                        //, DateTime: (datetime) ? datetime : undefined
                        //, StartDateTime: (start) ? start : undefined
                        //, EndDateTime: (end) ? end : undefined

                        //, ShowZoomPanControls: true
                    }
                    , Debug: { Available: false, LogItems: { Times: true } }
                    , Events: {
                        onViewChanged: function () { }
                    }
                };

                window.icc = new IndustrialChartConfiguration(
                    document.getElementById("trending_widget_container")
                    , options
                );

                //keyboard shortcuts
                Mousetrap.bind("ctrl+s", function () { icc.SaveView(); return false; });
                Mousetrap.bind("ctrl+shift+s", function () { icc.SaveViewAs(); return false; });
                Mousetrap.bind("ctrl+shift+p", function () { icc.ShowConfiguration(); return false; });
                Mousetrap.bind("ctrl+z", function () { icc.Undo(); return false; });
                Mousetrap.bind("ctrl+y", function () { icc.Redo(); return false; });

            }
        }
        , ExternalWidgets: [
        ]
        , Theme: "DZSupervision"
    });
});

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var state_cookie_name = "icconfiguration_persisted_state"; 
function _setStateCookie(opt) {
    var options = {
        viewName: null,
        scope: {
            start: null,
            end: null,
            id: null, 
        }, 
        auto_refresh: null,
        display_scales: null,
        cloud_mode: null,
        display_values: null,
        include_global_views: null, 
    };

    var current = _readCookie(state_cookie_name);
    current = (!current) ? options : current;

    var state = __extend(options, current);
    state = __extend(state, opt);

    state.scope.start = (state.scope.start == -1) ? null : state.scope.start;
    state.scope.end = (state.scope.end == -1) ? null : state.scope.end;

    _addCookie(state_cookie_name, state);
}
function _readStateCookie() {
    return _readCookie(state_cookie_name);
}
function _addCookie(name, value, days) {
    var expires; 
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        var exp_date = new Date(); 
        exp_date.setFullYear(exp_date.getFullYear() + 1); 
        expires = "; expires=" + exp_date.toGMTString();
    }
    document.cookie = escape(name) + "=" + escape(JSON.stringify(value)) + expires + "; path=/";
}
function _readCookie(name) {
    try {
        var cookies = document.cookie.split(";");
        for (var x = 0; x < cookies.length; x++) {
            var oneCookie = cookies[x].split("=");
            if (Core.String.Trim(oneCookie[0]) == Core.String.Trim(escape(name))) {
                return oneCookie[1] ? JSON.parse(unescape(oneCookie[1]), function dateReviver(key, value) {
                    if (typeof value === 'string') {
                        var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                        if (a) {
                            return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
                        }
                    }
                    return value;
                }) : '';
            }
        }
        return null;
    } catch (Error) { }
}
function _eraseCookie(name) {
    _addCookie(name, "", -1); 
}
//<<-- cookie helpers end -->>
var __isObject = function (obj) {
    var type = typeof obj;
    return type === 'function' || type === 'object' && !!obj;
};

var __extend = function (obj) {
    if (!__isObject(obj)) return obj;
    var source, prop;
    for (var i = 1, length = arguments.length; i < length; i++) {
        source = arguments[i];
        for (prop in source) {
            if (Object.prototype.hasOwnProperty.call(source, prop)) {
                obj[prop] = source[prop];
            }
        }
    }
    return obj;
};