/**************************************************
Site Script

Place utility functions or other miscellaneous useful
things in this file.
******************************************************/

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function () {
    log.history = log.history || [];   // store logs to an array for reference
    log.history.push(arguments);
    arguments.callee = arguments.callee.caller;
    if (this.console) console.log(Array.prototype.slice.call(arguments));
};

// make it safe to use console.log always
(function (b) { function c() { } for (var d = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info, log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","), a; a = d.pop(); ) b[a] = b[a] || c })(window.console = window.console || {});


/*****************************************************************************
Utilities

Place plugins as methods inside this plugin.  They should be chainable using:
return this.each(function() { });
******************************************************************************/

(function ($) {
    var methods = {
        init: function (options) {
           
        },
        /******************************************
        Utility Menu
        Provides a utility menu for the main site
        *******************************************/
        utilityMenu: function(options) {
            var settings = {};

            return this.each(function () {
                var $this = $(this); // refers to the element on which this plugin is acting

                if (options) {
                    $.extend(settings, options);
                }

                $this.hide(); // hide the element while we are reconfiguring it (avoids some "flicker")
                var $hdr = $this.find("h1");
                var $mnu = $this.find("ul");
                $hdr.appendTo($this); // put the header at the bottom of the menu
                $this.css({
                    'top': '-5px',
                    'right': '15%',
                    'position': 'fixed'
                }); //position the menu to the top right and fix it to the window
                $mnu.hide(); // hide the submenu so only the header shows
                $this.hover( //set up the hover to slide the menu up and down
                    function () {
                        $mnu.stop(true, true).slideDown('fast');
                    },
                    function () {
                        $mnu.stop(true, true).slideUp('fast');
                    }
                );
                $this.show(); // show the element now that it is reconfigured
            });
        }, //end utilityMenu
        /*******************************************************
        Main Nav
        ********************************************************/
        mainNav: function(options) {
            var settings = {};

            return this.each(function () {
                var $this = $(this); // refers to the ul on which this plugin is acting

                if (options) {
                    $.extend(settings, options);
                }

                $this.find("ul.subnav").parent().append("<span></span>"); //add a down arrow to indicate a submenu
                $this.find("li:has(ul.subnav)")
                    .bind("mouseenter.mainNav", function() {
                         $(this).find('ul.subnav').stop(true, true).slideDown('fast'); // call stop before animating to prevent menu dancing
                         $(this).find('span').addClass('subhover');
                    })
                    .bind("mouseleave.mainNav", function() {
                         $(this).find("ul.subnav").stop(true, true).slideUp('fast');  // call stop before animating to prevent menu dancing
                         $(this).find('span').removeClass('subhover');
                    });
            });
        }, //end mainNav
        /*********************************************************
        IdleTimeout
        //######
        //## This work is licensed under the Creative Commons Attribution-Share Alike 3.0
        //## United States License. To view a copy of this license,
        //## visit http://creativecommons.org/licenses/by-sa/3.0/us/ or send a letter
        //## to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
        //######


        This jQuery plugin is an extended version of Phil Palmieris work; http://philpalmieri.com/2009/09/jquery-session-auto-timeout-with-prompt/

        My extension is listening to the jQuery event ajaxSend so that the timeout is reset when other ajax requests are sent (assuming they will reset the session timeout on the server)

        /Jonas Myrenås, jonas@myrenas.se
        **********************************************************/
        idleTimeout: function(options) {
             /*
            See AutoLogout.cs for defaults
            */
            var settings = {
                inactivity: null,
                noconfirm: null,
                sessionAlive: null,
                redirect_url: null,
                click_reset: null,
                alive_url: null,
                logout_url: null,
                useAjaxSend: null
            };

            //##############################
            //## Private Variables
            //##############################
            var opts = $.extend(settings, options);
            var liveTimeout, confTimeout, sessionTimeout;
            
            //##############################
            //## Private Functions
            //##############################
            var start_liveTimeout = function () {
                clearTimeout(liveTimeout);
                clearTimeout(confTimeout);
                liveTimeout = setTimeout(logout, opts.inactivity);

                if (opts.sessionAlive) {
                    clearTimeout(sessionTimeout);
                    sessionTimeout = setTimeout(keep_session, opts.sessionAlive);
                }
            };

            var logout = function () {


                confTimeout = setTimeout(redirect, opts.noconfirm);
                $("#timeoutDialog").dialog("open");
            };

            var redirect = function () {
                if (opts.logout_url) {
                    $.get(opts.logout_url, null, success);
                }
                else {
                    window.location.href = opts.redirect_url;
                }
            };

            var stay_logged_in = function (el) {
                start_liveTimeout();
                if (opts.alive_url) {
                    $.get(opts.alive_url);
                }
            };

            var keep_session = function () {
                opts.useAjaxSend = false;

                $.get(opts.alive_url);
                if (opts.sessionAlive) {
                    clearTimeout(sessionTimeout);
                    sessionTimeout = setTimeout(keep_session, opts.sessionAlive);
                }

                opts.useAjaxSend = true;
            };

            var success = function (data, textStatus, jqXHR) {
                window.location.href = opts.redirect_url;
            };

            //Bind keep_alive to ajaxSend-event, so any ajax event resets the timer
            this.ajaxSend(function () {
                if (opts.useAjaxSend) {
                    //console.log("ajaxSend triggered");
                    keep_session();
                }
            });

            //###############################
            //Build & Return the instance of the item as a plugin
            // This is basically your construct.
            //###############################
            return this.each(function () {
                obj = $(this);
                var modal = "<div id='timeoutDialog'><p>You are about to be signed out due to inactivity.</p></div>";
                
                $(modal).dialog({
                buttons: { "Stay Logged In": function () {
                    $(this).dialog('close');
                    stay_logged_in();
                },
                    "Log Out": function () {
                        $(this).dialog('close');
                        redirect();
                    }
                },
                modal: true,
                title: 'Auto Logout',
                autoOpen: false
               });

                start_liveTimeout();
                if (opts.click_reset) {
                    $(document).bind('click', start_liveTimeout);
                }
                if (opts.sessionAlive) {
                    keep_session();
                }
                opts.useAjaxSend = true;
            });
        }, //end idleTimeout
        /*****************************************************************
        Google Analytics Link Tracking

        *******************************************************************/
        trackLinks: function() {
            return this.each(function() {
                $('a').click(function () {
                    var $a = $(this);
                    var href = $a.attr('href');
                    if (href != null) {
                        if ((href.match(/^http/i)) && (!href.match(document.domain))) {
                            var category = 'outgoing';
                            var event = 'click';
                            var label = href;
                            _gaq.push(['_trackEvent', category, event, href]);
                        }
                        else {
                            if (href.match(/\.(doc|pdf|xls|xlsx|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)$/i)) {
                                var category = 'download';
                                var event = 'click';
                                var label = href;
                                _gaq.push(['_trackEvent', category, event, href]);
                            }
                            else {
                                if (href.match(/^mailto:/i)) {
                                    var category = 'mailto';
                                    var event = 'click';
                                    var label = href;
                                    _gaq.push(['_trackEvent', category, event, href]);
                                }
                            }
                        }
                    }
                });
            });
        } //end trackLinks
    }; //end utility plugins

    $.fn.utilities = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.utilities');
        }
    };
})(jQuery);
