

/*
    http://www.JSON.org/json2.js
    2009-04-16

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html

    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the object holding the key.

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    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;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*jslint evil: true */

/*global JSON */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/

// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    JSON = {};
}
(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());




var lloyds = {};
/*
    lloyds.eh
-----------------------------------------------------------*/
(function($) {
    lloyds.eh = {
        log: function(log) {
            if (typeof(console) != 'undefined') {
                console.log(log);
            }
        },
        logError: function(err) {
            if (typeof (console) != 'undefined') {
            console.error(err);
            }
        }
    };
})(jQuery);

/*
    lloyds ready
-----------------------------------------------------------*/
lloyds.onReady = function() {
    try {
        lloyds.ui.init();
        lloyds.market.init();
    } catch (e) {
        lloyds.eh.logError(e);
    }
};
$().ready(lloyds.onReady);

// ie6 fixes
if (navigator.appName == "Microsoft Internet Explorer"){
	var v = parseFloat(navigator.appVersion.substr(21)) || parseFloat(navigator.appVersion);
	if (v < 7){
		// allow abbr tags to be styled
		document.createElement("abbr");
	}
};


/**
 * lloyds.market
 */
(function($) {

    var dash$ = null;
    var dashColumns$ = null;

    var sortStarted = false;

    // init functions
    function init_modules_titlebars() {
        $(".module-market").prepend('<div class="module-market-titlebar"><div class="module-market-titlebar-left">&nbsp;</div><ul class="module-market-titlebar-right"><li><a href="#" class="module-market-max">maximise this module</a></li><li><a href="#" class="module-market-close">close this module</a></li></ul></div>');
        $("#mod-dash .module-market-max").live('click', module_toggleMax);
        $("#mod-dash .module-market-close").live('click', module_close);
        $(".module-market").hover(module_hoverOver, module_hoverOut);
    };
    function init_modules_sortable() {
        var newHeight = dash$.height() + 50;
        dashColumns$.height(newHeight);

        $("#mod-dash .mod-dash-sortCol").sortable({
            appendTo: '#mod-dash-dragHolder',
            items: '.module-market',
            connectWith: ['.mod-dash-sortCol'],
            /*containment: $('#content'),*/
            distance: 5,
            dropOnEmpty: true,
            forcePlaceholderSize: true,
            handle: '.module-market-titlebar',
            helper: 'clone',
            placeholder: 'mod-dash-placeholder',
            revert: true,
            scroll: true,
            scrollSensitivity: 30,
            scrollSpeed: 40,
            tolerance: 'pointer',
            zIndex: 1000,
            start: dashboard_SortStart,
            stop: dashboard_SortStop,
            update: dashboard_SortUpdate
        })
        .find('.module-market-titlebar')
        .disableSelection();
    };

    // dashboard global
    function dashboard_SortStart(event, ui) {
        if (lloyds.market.sortStart) lloyds.market.sortStart(event, ui);
        if (!sortStarted) {
            sortStarted = true;
            dash$.addClass("mod-dash-sorting");
            var newHeight = dash$.height() + 50;
            dashColumns$.height(newHeight);
        }
    };
    function dashboard_SortStop(event, ui) {
        if (sortStarted) {
            sortStarted = false;
            dash$.removeClass("mod-dash-sorting");
            dashColumns$.height("auto");
            $(".module-market-titlebar").fadeOut(100);
        }
    };
    function dashboard_SortUpdate(event, ui) {
        var settings = [];
        var x = 0;
        var y = 0;
        $("#mod-dash .mod-dash-sortCol").each(function() {
            y = 0;
            $('.module-market', this).each(function() {
                var id = $(this).attr('id');
                settings.push({ id: id, x: x, y: y });
                y++;
            });
            x++;
        });
        var updateJSON = JSON.stringify(settings);
        lloyds.eh.log("dashboard_SortUpdate: " + updateJSON);
        if (lloyds.market.sortUpdate) {
            lloyds.market.sortUpdate(updateJSON);
        }
    };

    // individual module
    function module_close(ev) {
        var mod = $(this).closest(".module-market");
        var title = mod.find(".module-market-title h3").text();
        if (confirm("Are you sure you want to remove the " + title + " module?")) {
            mod.remove();
            dashboard_SortUpdate();
        }
        return false;
    };
    function module_hoverOver() {
        if (!sortStarted) {
            $(".module-market-titlebar", this).fadeIn(100);
        }
    };
    function module_hoverOut() {
        $(".module-market-titlebar", this).fadeOut(100);
    };
    function module_toggleMax(ev) {
        var mod = $(this).closest(".module-market");
        mod.toggleClass("module-market-minimised")
        return false;
    };

    // public methods and variables
    lloyds.market = {
        init: function() {
            lloyds.eh.log("lloyds.market.init");
            dash$ = $("#mod-dash");
            dashColumns$ = $("#mod-dash .mod-dash-sortCol");
            init_modules_titlebars();
            init_modules_sortable();
        },
        // events
        sortStart: null,
        sortUpdate: function(json) {
            $.post("/handlers/SaveDashboardPreferencesHandler.ashx", { settings: json });
        }
    };

})(jQuery);                                                    
// end enclosure


/*
    lloyds.ui
-----------------------------------------------------------*/
(function($) {

    lloyds.ui = {

        init: function(context) {
            lloyds.ui.tabs.init();
            lloyds.ui.chapters.init();
            setTimeout('lloyds.ui.sifr.init()', 500);
            $(".nav-accordian").accordian();
            lloyds.ui.nav.init();
            lloyds.ui.createButtons();
            lloyds.ui.createVideoPlayers();
            lloyds.ui.lightBox.init();

            if (typeof (jQuery.fn.maxlength) != 'undefined') $("textarea[maxlength]").maxlength();
            window.addthis_config = { services_exclude: 'print,email' };
            if (!($.browser.msie && $.browser.version < 7)) $(".shadow").addShadow();
            $("#header-search .tb").hint();
        },
        createButtons: function() {
            var pageButtons = [];

            var customBtn = function(original) {
                var btn = jQuery(original);
                var btnValue = btn.val();
                var form = jQuery(original.form);
                var hidden = jQuery('<input type="hidden" />');
                var newBtn = jQuery("<a />");
                var setProperties = function() {
                    btn[0].disabled ? (newBtn.hasClass("btn-disabled") ? null : newBtn.addClass("btn-disabled")) : newBtn.removeClass("btn-disabled");
                    if (btn[0].id) newBtn[0].id = btn[0].id; btn[0].id = '';
                }
                newBtn
                        .attr("class", btn.attr("class"))
                        .addClass("button-big")
                        .append('<span><strong>' + btn.val() + '</strong></span>')
                        .click(function(e) {
                            try {
                                if (newBtn.hasClass("btn-disabled") || btn[0].disabled) {
                                    return false;
                                }
                                if (btn[0].onclick) {
                                    var clickResult = btn[0].onclick.call(btn[0])
                                    //setProperties();
                                    if (clickResult === false) return false;
                                }
                                btn.remove();
                                newBtn.after(hidden);
                                hidden.val(btnValue);
                                form.submit();
                            } catch (e) {
                                lloyds.eh.log(e);
                            }
                        })
                setProperties();
                hidden.attr("name", btn.attr("name"));
                btn.after(newBtn).hide();

                var self = this;
                this.btn = btn;
                this.newBtn = newBtn;
                this.disable = function(shallow) {
                    newBtn.hasClass("btn-disabled") ? null : newBtn.addClass("btn-disabled");
                    if (shallow !== true) btn[0].disabled = true;
                }
                this.enable = function(shallow) {
                    newBtn.removeClass("btn-disabled");
                    if (shallow !== true) btn[0].disabled = false;
                }
                watcher(btn[0], 'disabled', function(prop, oldValue, newValue) {
                    newValue ? self.disable(true) : self.enable(true);
                    return newValue;
                });
                btn[0].disable = this.disable;
                btn[0].enable = this.enable;

            };
            jQuery("input[type=submit]:not(.btn-custom),input[type=button]:not(.btn-custom)").each(function() {
                if (!jQuery(this).hasClass("button-th")) {
                    var btn = new customBtn(this);
                }

            });
        },
        createVideoPlayers: function() {
            jQuery('.cp-video').each(function() {
                var video$ = jQuery(this);
                var videoWidth = video$.width();
                if (videoWidth > 300) {
                    var videoLink = video$.find('>.hotspot-item>a').attr('href');
                    var videoRegEx = /[^?]*?v=([^&]*)&id=([^&]*)&play=([^&]*)&buffer=([^&]*)/;
                    var videoDetails = videoRegEx.exec(videoLink);
                    var flashvars = { config: "{'clip': {'url' : '" + videoDetails[1] + "', 'autoPlay': " + (videoDetails[3] == "1").toString() + ", 'autoBuffering': " + (videoDetails[4] == "1").toString() + "}}" };
                    swfobject.embedSWF("/swf/flowplayer-3.1.5.swf", 'vid-' + videoDetails[2], videoWidth, Math.round((videoWidth * 0.5625) + 24), "9.0.0", null, flashvars, { 'wmode': 'transparent' });
                }
            });
        }
    };

})(jQuery);

/*
	lloyds.ui.chapters
-------------------------------------------*/
(function($) {
    lloyds.ui.chapters = {};
    lloyds.ui.chapters.init = function() {
        $(".mod-chapters").each(function() {
            var $chapters = $(this).tabs();
            $(".mod-chapters-navPaging a", this).click(function(e) {
                var href = $(this).attr("href");
                $chapters.tabs('select', href);
                return false;
            });
        });
    };
})(jQuery);

/*
	accordian
------------------------------------------------------------*/
(function($) {
    $.fn.accordian = function(settings) {
        if (typeof (settings) == "string") {
            if (settings == "expandAll") {
                this.find(">.nav-accordian-item")
                    .removeClass("nav-selected")
                    .addClass("nav-selected")
                    .find(">.nav-accordian-content").show();
            }
            if (settings == "closeAll") {
                this.find(">.nav-accordian-item")
                    .removeClass("nav-selected")
                    .find(">.nav-accordian-content").hide();
            }
        } else {
            var config = {};
            if (settings) $.extend(config, settings);

            this.find(">.nav-accordian-item>.nav-accordian-header").each(function() {
                var parent = $(this).parent();
                var header = $(this);
                var content = $(this).next();
                if (!parent.hasClass("nav-selected")) {
                    content.hide();
                }
                header.click(function(e) {
                    if (e.target === this) {
                        if (parent.hasClass("nav-selected")) {
                            content.slideUp(100);
                            parent.removeClass("nav-selected");
                        } else {
                            content.slideDown(100);
                            parent.addClass("nav-selected")
                        }
                    }
                });
            });
        }
    };
})(jQuery);

/*
	addShadow
------------------------------------------------------------*/
(function($) {
    $.fn.addShadow = function() {
        this.each(function() {
            var container = $(this);
            container
                .addClass('shadow-active')
                .wrapInner('<div class="shadow-content cc" />')
                .wrapInner('<div class="shadow-content-l" />')
                .wrapInner('<div class="shadow-content-b" />')
                .prepend('<div class="shadow-tl">')
                .prepend('<div class="shadow-tr">')
                .prepend('<div class="shadow-bl">')
                .prepend('<div class="shadow-br">');
        });
    };
})(jQuery);

/*
	lloyds.ui.tabs
-------------------------------------------*/
(function($) {
    lloyds.ui.tabs = {};
    lloyds.ui.tabs.init = function() {
        $(".nav-tabs").tabs();
    }
})(jQuery);



/*
	lloyds.ui.LightBox
-------------------------------------------*/
(function($) {

    lloyds.ui.lightBox = {};
    lloyds.ui.lightBox.lightBoxDiv = null;
    lloyds.ui.lightBox.init = function() {
        var lightBox = this;
        this.lightBoxDiv = $('<div id="lightBox"></div>');
        this.lightBoxDiv.appendTo("body");

        $("#lightBox").dialog({ autoOpen: false, modal: true, resizable: false, width: 580, position: ["center", 100] });

        $("a.lightBox-link").click(function(e) {
            try {
                lightBox.showContent({ url: this.href });
            } catch (ex) { lloyds.eh.logError(ex); }
            return false;
        });
    };
    /**
    * Shows a lightbox according to the settings
    * @param {Object} settings {selector,videoId,url}
    * @return {Object} Returns the jQuery object for the light box div
    */
    lloyds.ui.lightBox.showContent = function(settings) {
        var config = {
            selector: "#lightBox-content",
            videoId: "",
            url: "",
            timeout: 3000
        };
        if (settings)
            $.extend(config, settings);

        var lightBox = $("#lightBox");
        lightBox.html('<div class="lightBox-loading">loading<span></span></div>');
        lightBox.find('div>span').animate({ width: '200px' }, config.timeout-500, function() { $(this).fadeOut(500); });
        lightBox.dialog("open");
        // load content from external url
        var logError = function(ex) {
            lloyds.eh.logError(ex);
            lightBox.html('<div class="lightBox-loading">Sorry there was a problem loading this page...</div>');
            $('<p class="align-center" />').append($('<a href="#">Close this window</a>').click(function() { lightBox.dialog('close'); return false; })).appendTo(lightBox);
        };
        try {
            if (config.url != "") {
                $.ajax({
                    timeout: config.timeout,
                    url: config.url,
                    error: function(xhr, status, error) {
                        logError(error);
                    },
                    success: function(data, textStatus, xhr) {
                        try {
                            var resp$ = $(data);
                            var lightBoxContent$ = resp$.find(config.selector);
                            lightBoxContent$.removeAttr('xmlns');
                            lightBox.html("");
                            lightBox.append(lightBoxContent$);
                            lightBox.find(".nav-accordian").accordian();
                            lloyds.ui.sifr.initLightBox();
                        } catch (ex) { logError(ex); }
                    }
                });
            }
        } catch (ex) {
            logError(ex);
        }
        return lightBox;
    };
})(jQuery);


/*
	lloyds.ui.nav
-------------------------------------------*/
(function($) {

    // Timings
    var tierThreePageWait = 2000;   // time to wait after page loaded before allowing tier 3 to show
    var tierThreeReady = false;
    var tierThreeOnReady = null;

    var tierThreeTimeToOpen = 550; // time mouse needs to hover before registering that the user wants to open the nav
    var tierThreeTimeMouseLeave = 350; // time slack given before registering that the mouse hase left
    var tierThreeTimeToClose = 600; // time slack given before the box nav is closed completely

    var primaryHoverTimeout = -1;
    var mouseHoveringTimeout = -1;
    var mouseLeaveTimeout = -1;
    var itemClicked = false;
    var $currentHoveredItem = null; // the current primary sub item which is mouse hovering
    var $primarySubOpen = null; // the current open item with box
    var primarySubOver = false; // indicates whether the mouse is hovering over the main title

    var tierThreeOpen = null;
    var tierThreeOver = false;

    var primarySubHoverOver = function() {
        $currentHoveredItem = $(this);
        var primarySubItem = this;
        if (mouseHoveringTimeout != -1) clearTimeout(mouseHoveringTimeout);
        if ($currentHoveredItem == $primarySubOpen && mouseLeaveTimeout != -1) clearTimeout(mouseLeaveTimeout);
        var openFn = function() { tierThreeOpen(primarySubItem); };
        tierThreeReady ?
            mouseHoveringTimeout = setTimeout(openFn, tierThreeTimeToOpen) :
            tierThreeOnReady = openFn;
    };
    var primarySubHoverOut = function() {
        $currentHoveredItem = null;
        primarySubOver = false;
        mouseLeaveTimeout = setTimeout(function() { tierThreeClose(); itemClicked = false; }, tierThreeTimeMouseLeave);
    };
    var tierThreeOpen = function(primarySubItem) {
        if ($currentHoveredItem && !itemClicked) {
            $primarySubOpen = $(primarySubItem);
            primarySubOver = true;
            $primarySubOpen.addClass("nav-primary-sub-hover");

            $tierThreeOpen = $(primarySubItem).children(".nav-primary-tier3");
            $tierThreeOpen.show().hover(tierThreeHoverOver, tierThreeHoverOut);
        }
    };
    var tierThreeClose = function() {
        if ($primarySubOpen && ((!primarySubOver && !tierThreeOver) || itemClicked)) {
            $primarySubOpen.removeClass("nav-primary-sub-hover");
            $primarySubOpen = null;
            $tierThreeOpen.hide()
            $tierThreeOpen = null;
        }
    };
    var tierThreeHoverOver = function() {
        tierThreeOver = true;
    };
    var tierThreeHoverOut = function() {
        tierThreeOver = false;
        if (!primarySubOver && !tierThreeOver) {
            tierThreeClose();
        }
    };

    lloyds.ui.nav = {
        init: function() {
            $(".nav-primary-sub > li")
                .hover(primarySubHoverOver, primarySubHoverOut)
                .click(function(ev) {
                    clearTimeout(mouseHoveringTimeout);
                    itemClicked = true;
                    tierThreeClose();
                });
            setTimeout(function() {
                tierThreeReady = true;
                if (tierThreeOnReady) tierThreeOnReady();
            }, tierThreePageWait);
        }
    };

})(jQuery);


/*
	lloyds.ui.sifr
-------------------------------------------*/
(function($) {

    var a = 'a { color: #019ec9; text-decoration: none; }';
    var aHover = 'a:hover { color: #2dc2e3; text-decoration: underline; }';
    var aBlack = 'a { color: #000000; text-decoration: none; }';
    var aBlackHover = 'a:hover { color: #000000; text-decoration: none; }';
    var aGrey = 'a { color: #5b5b5b; text-decoration: none; }';
    var aGreyHover = 'a:hover { color: #5b5b5b; text-decoration: none; }';

    var rootGrey = '.sIFR-root { color: #5c5c5c; }';
    var orange = '.orange { color: #f99d31; }';

    var navPrimarySettings = { filters: { DropShadow: { alpha: 0.75, knockout: false, distance: -1, color: '#3b3b3b', strength: 2, blurX: 1, blurY: 1} }, forceSingleLine: true };
    var navPrSubSettings = { forceSingleLine: true };

    var addRule = function(selector, css, settings) {
        var sifrOpt = $.extend({ selector: selector, css: css, wmode: 'transparent' }, settings);
        sIFR.replace(sansalloyds, sifrOpt);
    };

    lloyds.ui.sifr = {
        addHeaderRules: function(contextSelector) {
            try {
                // h1 ------------------------------------------------
                addRule(contextSelector + 'h1', [a, aHover]);
                addRule(contextSelector + 'h1.h3SifrMarkets', ['.sIFR-root { color: #B2BC1F; text-decoration: none; font-size: 18px; }']);

                // h2 ------------------------------------------------
                addRule(contextSelector + 'h2.h3SifrMarkets', ['.sIFR-root { color: #B2BC1F; text-decoration: none; font-size: 18px; }']);
                // green h2 within banner
                addRule(contextSelector + '.h2sifrGreen', ['.sIFR-root { color: #b2bb1e; text-decoration: none; font-size: 40px; }', '.dark { color: #666666; }']);
                // orange h2 within banner:
                addRule(contextSelector + '.h2sifr', ['.sIFR-root { color: #f99d31; text-decoration: none; font-size: 40px; }', '.dark { color: #666666; }']);
                // h2 white
                addRule(contextSelector + '.h2sifrWhite', ['.sIFR-root { color: #ffffff;}', '.heading-highlight{color:#F99D31;}', a, aHover]);
                //regular h2
                addRule(contextSelector + 'h2', ['.sIFR-root { color: #5b5b5b;}', a, aHover]);

                // h3 ------------------------------------------------
                addRule(contextSelector + '.shadowed-feature-narrow h3.h3sifr', ['.sIFR-root { color: #4d4d4d; }', a, aHover]);
                addRule(contextSelector + '.h3sifr', [aBlack, aBlackHover, '.orange { color: #f99d31; }']);
                addRule(contextSelector + '.h3sifrsmall', ['.sIFR-root { font-size: 16px;}', a, aHover]);

                // h4 ------------------------------------------------
                addRule(contextSelector + '.h4sifr', [rootGrey, aGrey, aGreyHover, orange]);
                //addRule(contextSelector + '.layout-subc3 .layout-item h4.h4sifrsmall', [rootGrey, 'a { color: #5c5c5c; text-decoration:none; }', 'a:hover { color: #5c5c5c; text-decoration:none; }', ]);
                //addRule(contextSelector + '.structure-container .structure .structure-right h4.h4sifrsmall', ['.sIFR-root { color: #000000; font-size: 14px; }']);

                // h5 ------------------------------------------------
                addRule(contextSelector + '.h5sifr', ['.sIFR-root { color: #5B5B5B; }', a, aHover]);
            } catch (ex) {
                alert(ex.message);
            }
        },
        addToolsRules: function() {
            if (document.getElementById('mod-tool-calendar')) {

                addRule('.mod-tool-tbTop h3', ['.sIFR-root { color: #000000; }']);
                addRule('#mod-tool-calendar .mod-tool-weekEnd .mod-tool-weekDay-title', ['.sIFR-root { color: #5b5b5b; text-align:center; }']);
                addRule('#mod-tool-calendar .mod-tool-weekDay-title', ['.sIFR-root { color: #019ec9; text-align:center; }']);
                addRule('#mod-tool-calendar .mod-tool-event-date span', ['.sIFR-root { color: #019ec9; text-align:center; }']);
                addRule('#mod-tool-calendar .mod-tool-activity-content h4', ['.sIFR-root { color: #019ec9; }', a, aHover]);

                addRule('#mod-tool-calendar .mod-tool-event-title', ['.sIFR-root { color: #ffffff; }']);
                addRule('#mod-tool-calendar .mod-tool-event-note h4', ['.sIFR-root { color: #019ec9; }', a, aHover]);
            }
        },
        addPrimaryNavRules: function() {
            /* sIFR for navigation 
            ----------------------------------------------------------------------------------------*/
            // primary nav tier 2
            //addRule('#nav-primary li ul li.nav-selected .sIFRItem', ['a { color: #2dc2e3; text-decoration: none; font-size: 12px; }', 'a:hover { color: #f99d31; }', '.sIFR-root { color: #ffffff; }'], navPrSubSettings);
            //addRule('#nav-primary li ul li .sIFRItem', ['a { color: #ffffff; text-decoration: none; font-size: 12px; }', 'a:hover { color: #f99d31; }', '.sIFR-root { color: #ffffff; }'], navPrSubSettings);

            // primary nav tier 1 - lloyds/themarket/news
            // selected
            //addRule('#nav-primary li.nav-selected > span.nav-primary-link span.sIFRItem', ['a { color: #2dc2e3; text-decoration: none; font-size: 12px; padding-top: -5; cursor: pointer; white-space: nowrap; }', 'a:hover { color: #f99d31; }'], navPrimarySettings);
            //normal
            //addRule('#nav-primary li > span.nav-primary-link span.sIFRItem', ['a { color: #ffffff; text-decoration: none; font-size: 12px; padding-top: -5; cursor: pointer; white-space: nowrap; }', 'a:hover { color: #f99d31; }'], navPrimarySettings);
        },
        init: function() {

            if (typeof (sIFR) != 'undefined') {

                this.addPrimaryNavRules();

                // Orange hotspot hero box
                addRule('#hotspot-hero-wide .hotspot-container .hotspot h3.h3sifr, #hotspot-hero-wide .hotspot-container .hotspot h4.h4sifr', ['.sIFR-root { color: #7d4e18; }']);

                this.addHeaderRules('');
                this.addToolsRules();

                // banner intro text
                addRule('p.mainintro', ['.sIFR-root { color: #ffffff; font-size: 19px; }']);
                // banner intro text styled black for 360 hub pages
                addRule('p.mainintro-alt', ['.sIFR-root { color: #000000; font-size: 19px; }']);


                // navs ----------------------------------------------------------------------------------
                addRule('.nav-blackBar .nav-h li.nav-firstitem', ['.sIFR-root { color: #ffffff; white-space: nowrap; }'], navPrimarySettings);

            }
        },
        initLightBox: function() {
            this.addHeaderRules('#lightBox-content ');
        }
    };

})(jQuery);


/* Cross Browser Watch Function */
watcher = function(obj, prop, func) {
    if (!Object.watch) {
        if (Object.defineProperty) {
            var _prop = obj[prop];
            Object.defineProperty(obj, prop, {
                get: function() {
                    return _prop;
                },
                set: function(val) {
                    _prop = func.call(obj, prop, _prop, val);
                }
            });
        } else {
            new IEwatch(obj, prop, func);
            return true;
        }
    }
    else {
        obj.watch(prop, func);
        return true;
    }
};
var IEwatch = function(obj, prop, func) {
    var self = this;
    this.obj = obj;
    this.prop = prop;
    this.func = func;
    this.oldvalue = this.obj[this.prop];
    this.check = function() {
        if (self.obj[self.prop] != null && self.obj[self.prop] != self.oldvalue) {
            self.oldvalue = self.func(self.prop, self.oldvalue, self.obj[self.prop]);
        }
    };
    setInterval(self.check, 150);
};
