﻿;(function () {
    var ILP = window.ILP = {
        configure: function (func) {
            var configurable = {
                modals: function () {
                    $.nyroModalSettings({
                        zIndexStart: 5100,
                        minWidth: 50,
                        minHeight: 50,
                        cssOpt: {
                            wrapper: { border: 'none' },
                            bg: { 'background-color': '#000' }
                        },
                        wrap: {
                            manual: '<div class="wrapperSmallGreen"></div>',
                            ajax: '<div class="dynamicContent"></div>'
                        },
                        resizable: false,
                        processHandler: function (settings) {
                            var url = settings.url;
                            if (url && url.indexOf('http://www.youtube.com/watch?v=') == 0) {
                                $.nyroModalSettings({
                                    type: 'swf',
                                    height: 330,
                                    width: 540,
                                    url: url.replace(new RegExp("watch\\?v=", "i"), 'v/'),
                                    swf: { autoplay: true }
                                });
                            }
                        },
                        showBackground: function (elts, settings, callback) {
                            elts.bg.css({ opacity: 0 }).fadeTo(500, 0.5, callback);
                        }
                    });
                },
                validators: function () {
                    if (typeof (ILP.validation)) {
                        ILP.validation.activate();
                    }
                },
                widgets: function () {
                    if (typeof (ILP.widgets)) {
                        // creates jquery extensions from widgets
                        $.extend($.fn, ILP.widgets);
                    }
                },
                tooltips: function (container) {
                    if (typeof ($.fn.qtip)) {
                        container = container || document;
                        $('a.txtTip', container).qtip({
                            style: {
                                width: 200,
                                padding: 1,
                                background: '#FF6600',
                                color: 'white',
                                textAlign: 'center',
                                border: { width: 0, radius: 3, color: '#FF6600' },
                                tip: { corner: 'topLeft' },
                                name: 'dark' /* Inherit the rest of the attributes from the preset dark style */
                            },
                            hide: {fixed:true}, /* <- fixes a flickering issue when hovering over tooltips in FireFox. */
                            position: { corner: { target: 'topRight', tooltip: 'topLeft'}, adjust: { y: 14, x: -10 } }
                        });

                        $('a.imgTip', container).qtip({
                            content: { prerender: true },
                            style: {
                                width: 'auto',
                                padding: 0,
                                border: 0,
                                background: 'transparent',
                                tip: { corner: 'topMiddle', color: '#50A4AF' }
                            },
                            hide: {fixed:true}, /* <- fixes a flickering issue when hovering over tooltips in FireFox. */
                            position: { corner: { target: 'topLeft', tooltip: 'topMiddle' }, adjust: { y: 10, x: 10 } }
                        });
                    }
                },
                datepickers: function () {
                    $(".datePicker").datepicker();
                },
                ajax: function () {
                    $.ajaxSetup({ cache: false });
                    $(document).ajaxError(function (e, xhr, settings, exception) {
                        ILP.util.showAjaxError(xhr);
                        $('.ajaxProcessing').each(function () {
                            $(this).attr('disabled', false).attr('src', $(this).attr('oldSrc')).removeClass('ajaxProcessing');
                        });
                    });
                },
                autoNumeric: function () {
                    $($.fn.autoNumeric.defaults.className).autoNumeric();
                },
                idleTimer: function (isAuth, idleAfterMinutes, ajaxTimeout) {
                    if (!$.idleTimeout || !isAuth) return;
                    var secondsPerMinute = 60;
                    $.idleTimeout('#idletimeout', '#idletimeout a', {
                        idleAfter: idleAfterMinutes * secondsPerMinute,
                        pollingInterval: 5 * secondsPerMinute, // five minutes
                        keepAliveURL: '/Validate/SessionActive',
                        AJAXTimeout: ajaxTimeout, // milliseconds
                        serverResponseEquals: 'OK',
                        onTimeout: function () {
                            $(this).slideUp();
                            window.onbeforeunload = null; // detach the "don't leave" dialog handler to avoid unneccessary popups
                            window.location = "/login/logoff";
                        },
                        onIdle: function () {
                            $(this).slideDown(); // show the warning bar
                        },
                        onCountdown: function (counter) {
                            $(this).find("span").html(counter); // update the counter
                        },
                        onResume: function () {
                            $(this).slideUp(); // hide the warning bar
                        }
                    });
                },
                quirks: function () {
                    // Fix login arrow alignment issue in IE 6/7/8
                    if ($.browser.msie) {
                        $('.arrow').css('padding-bottom', '6px');
                    }
                }
            };
            func.call(this, configurable);
        },
        util: {
            browser: {},
            jsonActionResultType: {
                Redirect: 0,
                Ajax: 1,
                Function: 2,
                Modal: 3,
                Message: 4,
				FunctionAndMessage: 5,
				ExternalUrl: 6,
                MessageAndRedirect: 7
            },
            showAjaxError: function (xhr) {
                if (xhr/*&& xhr.status == 500*/) {
                    var statusText = $('<div />').html(xhr.statusText + '&nbsp;').append('<a />').find('a').html('Show more information').click(function () {
                        $('#errorContent').toggle();
                        var msg = 'Show more information';
                        this.innerHTML = this.innerHTML.match(/Show/i) ? this.innerHTML.replace('Show', 'Hide') : this.innerHTML.replace('Hide', 'Show');
                    }).end();
                    var content = xhr.response ? jQuery('<div id="errorContent" style="display: none" />').append('<br /><br />' + xhr.response) : false;

                    if (content !== false)
                        $.nyroModalManual({
                            autoSizable: true,
                            width: 361, height: 180,
                            content: $('<div />').append(statusText).append(content),
                            closeButton: true,
                            wrap: { manual: '<div class="wrapperMedGreen"></div>' }
                        });
                }
            },
            tryProcessJsonActionResult: function (result) {
                var jar = result.JsonActionResult || result;
                if (jar && jar.Action !== undefined) { // only process result if action is defined
                    // process tracking, wait for finish
                    if (jar.Tracking) {
                        var iframe = $('<iframe />', { src: jar.Tracking, style: "width:0;height:0;border:0"
                        }).appendTo('body');
                        // when the frame loads (tracking completes) process the rest of the request
                        iframe.load(function () {
                            jar.Tracking = null;
                            ILP.util.tryProcessJsonActionResult(jar);
                        });
                        return; // return and wait
                    }
                    // process updatables
                    if (jar.Updatables) {
                        for (var key in jar.Updatables) {
                            var fields = $('.updatable.' + key);
                            if (jar.Updatables[key] !== null && fields.length > 0)
                                fields.html(jar.Updatables[key]);
                        }
                    }
                    // process action
                    switch (jar.Action) {
                        case ILP.util.jsonActionResultType.Redirect:
                            location.href = jar.Url;
                            break;
                        case ILP.util.jsonActionResultType.Ajax:
                            $.post(jar.Url, jar.Data, eval(jar.Function));
                            break;
                        case ILP.util.jsonActionResultType.Function:
                            var func = eval(jar.Function);
                            if ((typeof (func) == 'function')) func.call(this, result);
                            break;
                        case ILP.util.jsonActionResultType.Modal:
                            $.nyroModalManual(jar.Data);
                            break;
                        case ILP.util.jsonActionResultType.Message:
                            var mmconfig = {
                                autoSizable: true,
                                content: jar.Data,
                                closeButton: true, wrap: { manual: '<div style="width: auto; height: auto; background: none"></div>' }
                            };
                            var ieSevenOrLess = ($.browser.msie)
                            if (ieSevenOrLess) { // fix width in ie7 and ie8
                                mmconfig = GetSizeForIE7(mmconfig, jar.Data);
                            }
                            $.nyroModalManual(mmconfig);
                            break;
                        case ILP.util.jsonActionResultType.FunctionAndMessage:
                            var mmconfig = {
                                autoSizable: true,
                                content: jar.Data,
                                closeButton: true, wrap: { manual: '<div style="width: auto; height: auto; background: none"></div>' }
                            };
                            var ieSevenOrLess = ($.browser.msie)
                            if (ieSevenOrLess) { // fix width in ie7 and ie8
                                mmconfig = GetSizeForIE7(mmconfig, jar.Data);
                            }
                            $.nyroModalManual(mmconfig);
                            var func = eval(jar.Function);
                            if ((typeof (func) == 'function')) func.call(this, result);
                            break;
                        case ILP.util.jsonActionResultType.MessageAndRedirect:
                            var mmconfig = {
                                endRemove: function () {location.href = jar.Url}, //Redirect on close
                                autoSizable: true,
                                content: jar.Data,
                                closeButton: true, wrap: { manual: '<div style="width: auto; height: auto; background: none"></div>' }
                            };
                            var ieSevenOrLess = ($.browser.msie)
                            if (ieSevenOrLess) { // fix width in ie7 and ie8
                                mmconfig = GetSizeForIE7(mmconfig, jar.Data);
                            }
                            $.nyroModalManual(mmconfig);
                            break;
                    }
                }
            },
            log: function (message) {
                var canLog = window.console && window.console.log;
                if (!canLog) return alert(message);

                var strEval = 'window.console.log(';

                for (var i = 0; i < arguments.length; i++) {
                    strEval += 'arguments[' + i + '],';
                }
                strEval = strEval.delEnd(1) + ');';
                eval(strEval);
            },
            loadAjaxEmptyTabFunc: function (event, i, condition) {
                if (condition === undefined) condition = false;
                // get the pane to be opened
                var pane = this.getPanes().eq(i);
                // only load once. remove the if ( ... ){ } clause if you want the page to be loaded every time
                if (pane.is(":empty") || condition === true) {
                    // load it with a page specified in the tab's href attribute
                    var dataUrl = this.getTabs().eq(i).attr("rel");
                    pane.html($('<div class="ajax-loader"></div>'));
                    pane.load(dataUrl, function (response, status) {
                        if (status == 'success')
                            __MVC_AjaxFormLoad();
                    });
                }
            },
            attachFunctionToLinkClick: function (functionToExecute, replaceCurrentOnclickFunctions, replaceForNewWindows) {
                // Function takes the functionToExecuteAsString and attaches it to every link on the page so the function is
                // executed before the actual link href is executed.  The original href will be stored in an attribute of the link called
                // orgHref.  This will allow you to get access to what the href was.  This is done so the page will not navigate to the href.  You as the user
                // can decide to navigate to the href by accessing this attribute.
                // @param functionToExecute - function to execute on the link click.  The function should be a function object that takes in a string value which will be the orginal href of the link object
                // @param replaceCurrentOnclickFunctions - boolean.  If true then we don't replace the onclick function for links that already have a predifined onclick function
                // @param replaceForNewWindows - boolean.  If true then we don't replace the onclick function for links that are set to open in new windows.
                // @return - The name of the attribute that the href was stored in (orgHref)
                // Define a couple string constants so we don't have to recreate them as we loop through the link elements on the page
                var javascriptVoidFunction = 'javascript:void(0);';
                var locationHref = 'location.href = \'';
                var orgHrefAttribute = 'orgHref';
                var hrefAttribute = 'href';
                var onclickAttribute = 'onclick';
                var targetAttribute = 'target';
                var targetBlank = '_blank';

                $('a:not(#idletimeout-resume)').each(function () {
                    var thisLink = $(this);
                    // Get the current href so we can make sure we call it
                    var orgHref = thisLink.attr(hrefAttribute);

                    // Store the orginal href in the orgHref attribute of the link.  This will allow others to get
                    // access to it.
                    thisLink.attr(orgHrefAttribute, orgHref);


                    // If we shouldn't replace current onclick functions then test and return if it already has an onclick
                    // function
                    if (!replaceCurrentOnclickFunctions) {

                        var onclickFunction = thisLink.attr(onclickAttribute);
                        if (onclickFunction != null && onclickFunction != '')
                            return;
                    }

                    // If we shouldn't replace the onclick function for links that open in new windows then just return
                    if (!replaceForNewWindows) {

                        var target = thisLink.attr(targetAttribute);
                        if (target != null && target == targetBlank)
                            return;
                    }

                    // Set the href to a javascript:void() so we can prevent the page from going to the href
                    $(this).attr(hrefAttribute, javascriptVoidFunction);

                    $(this).click(function () {
                        functionToExecute(orgHref);
                    });
                });
            },
            attachWindowCloseEventHandlers: function (onBeforeUnloadFunction, onUnloadFunction) {
                // Attaches the passed in functions the window unload events.  You can pass null in for either functiion
                window.onbeforeunload = onBeforeUnloadFunction;
                window.onunload = onUnloadFunction;
            },
            detachWindowCloseEventHandlers: function () {
                // Detaches the window unload event handlers
                ILP.util.attachWindowCloseEventHandlers(null, null);
            }
        }
    };
})();

// Native Object Extensions

/// Object->String
String.prototype.delEnd = function (chars) { // chars is Number
    if (this && this.length && this.length > chars) {
        return this.toString().substring(0, this.length - chars);
    }
};
/// Object->Array
Array.prototype.single = function (func) {
    if (this && this.length)
        for (var i in this)
            if (func.call(this, this[i]))
                return this[i] || {};
    return {};
};

function GetSizeForIE7(mmconfig, data) {
    var c = $('<span style="visibility: hidden;">' + data + '</span>').appendTo(document.body);
    var w = c.width();
    var h = c.height();
    c.remove();
    mmconfig.width = w + 15;
    mmconfig.height = h + 12;
    return mmconfig;
};
