/// <reference path="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.6-vsdoc.js" />

/* Documentation: http://api.jquery.com/ */

/* Menu System  */

$.fn.extend({
    buildMenu: function (options) {
        // Check if the element is a ul.
        if (!$(this) || !$(this).is('ul')) { return false; }

        // Check the options and apply defaults.
        var empty = {};
        var defaults = { submenuclass: '', activemenu: '', collapsearrow: 'icon uarrow', expandarrow: 'icon darrow', highlightclass: 'on', expandclass: 'expanded', collapsecall: null, expandcall: null };
        var settings = $.extend(empty, defaults, options);

        // Find the parent elements.
        // <li class="on"><a href=""/><div class="submenu"/></li>
        // Note: The click function is on the hyperlink.
        var links = $(settings.submenuclass).parents('li').children('a');
        var activemenu = $(settings.activemenu);
        var arrow = $(document.createElement('span')).addClass(settings.expandarrow);

        // Detect if mobile device.
        var agent = navigator.userAgent.toLowerCase();
        var agentid = agent.match(/(iphone|ipod|ipad)/);
        if (agentid) {

            links.each(function () {
                // Add the arrow to the link.
                var instance = arrow.clone();
                $(this).append(instance).hover(function () { instance.addClass('hover'); }, function () { instance.removeClass('hover'); });
            }).toggle(function () {
                // Find any other expanded menu items and toggle them first.
                $(settings.submenuclass).parents('li.' + settings.expandclass).children('a').click();
                // Add up arrow.
                $('span', $(this)).removeClass(settings.expandarrow).addClass(settings.collapsearrow);
                // To expand.
                $(this).parent().addClass(settings.expandclass);
                activemenu.append($(settings.submenuclass, $(this).parent()).clone()).show();
            }, function () {
                // Add down arrow.
                $('span', $(this)).removeClass(settings.collapsearrow).addClass(settings.expandarrow);
                // To collapse.
                $(this).parent().removeClass(settings.expandclass);
                activemenu.hide().empty();
            });
        }
        else {
            
            links.each(function() {
                // Add the arrow to the link.
                var instance = arrow.clone();
                $(this).append(instance).hover(function() { instance.addClass('hover'); }, function() { instance.removeClass('hover'); });
            }).mouseenter(function() {
                // Find any other expanded menu items and toggle them first.
                $('span', links).removeClass(settings.collapsearrow).addClass(settings.expandarrow);
                // Add up arrow.
                $('span', $(this)).removeClass(settings.expandarrow).addClass(settings.collapsearrow);
                activemenu.empty().append($(settings.submenuclass, $(this).parent()).clone()).show();
            });
            // Also add mouse leave on the menu's parent element itself (because leaving the ul closes the active menu).
            $(this).parent().mouseleave(function () {
                // Add down arrow.
                $('span', links).removeClass(settings.collapsearrow).addClass(settings.expandarrow);
                activemenu.hide();
            });

        }
    }
});

/* Print functionality */

function $print()
{
    if (window.print) { window.print(); }
    return false;
}

/* Modal Dialog */

$.fn.extend({
    openModalDialog: function (options) {
        // Check if the element is an input.
        if (!$(this)) { return false; }

        // Check the options and apply defaults.
        var empty = {};
        var defaults = { form: null, clone: true };
        var settings = $.extend(empty, defaults, options);

        // Build the modal dialog.
        if (settings.clone) {
            $(settings.form).clone().modal({
                appendTo: 'form',
                overlayId: 'mod-mask',
                containerId: 'mod-cont',
                overlayClose: true
            });
        }
        else {
            $(settings.form).modal({
                    appendTo: 'form',
                    overlayId: 'mod-mask',
                    containerId: 'mod-cont',
                    overlayClose: true
                }); 
        }
    }
    });

/* Popup Window */

$.extend({
    popupWindow: function (options) {
        // Check the options and apply defaults.
        var empty = {};
        var defaults = { url: '', height: 0, width: 0, x: 0, y: 0, left: 0, top: 0, toolbar: 1, status: 1, scroll: 1, resize: 1, menu: 1, location: 1, auto: true };
        var settings = $.extend(empty, defaults, options);

        // Check settings are valid before continiuing.
        if (settings.url == '') { return; }

        // Apply auto dimensions.
        if (settings.auto) { settings.height = screen.height; settings.width = screen.width; }

        // Create a popup window.
        window.open(settings.url, '', 'height=' + settings.height + ',width=' + settings.width + ',screenX=' + settings.x + ',screenY=' + settings.y + ',' +
            'left=' + settings.left + ',top=' + settings.top + ',toolbar=' + settings.toolbar + ',status=' + settings.status + ',scrollbars=' + settings.scroll + ',resize=' + settings.resize + ',' +
            'menubar=' + settings.menu + ',resizeable=1,location=' + settings.location + ',directories=1');
    },
    popupStartup: function () {
        // Find all links with the class of popup.
        $('a.popup').each(function () {
            if ($(this).attr('title') && $(this).attr('title') != '') { $(this).attr('title', $(this).attr('title') + ' (opens in new window)'); }
            $(this).click(function (event) {
                event.stopPropagation(); // Prevent ASP.Net event bubbling...
                event.stopImmediatePropagation();
                event.preventDefault(); // Immediately prevent the event from executing...
                $.popupWindow({ url: $(this).attr('href') });
            });
        });
    }
});

/* Analytics Event Tagging */

$.extend({
    tag: function (options) {
        // Check the options and apply defaults.
        var empty = {};
        var defaults = { category: '', action: '', label: '', type: '20' };
        var settings = $.extend(empty, defaults, options);

        // Check settings are valid before continiuing.
        if (settings.action == '') { return; }

        // Generate a single title.
        var title = settings.category;
        if (settings.action != '') { title += ' - ' + settings.action; }
        if (settings.label != '') { title += ' (' + settings.label + ')'; }

        // WebTrends
        //if (_wttag) {
            // WT.dl LEGEND
            // ============
            // Download Links       = 20
            // Anchor Links	        = 21          
            // Form Button (get)    = 26
            // Form Button (post)   = 27
            // Input Tag Button     = 28
            // Button Tag Button    = 29
            //try {
            //    _wttag.dcsMultiTrack("WT.ti", title, "WT.dl", settings.type);
            //}
            //catch(err) { }
        //}
        // Google Analytics
        if (window._gaq) {
            try {
                _gaq.push(['_trackEvent', settings.category, settings.action, settings.label]);
            }
            catch (err) { }
        }
        // ClickTale
        //if (window.ClickTaleTag) {
        //    try {
        //        ClickTaleTag(title);
        //    }
        //    catch (err) { }
        //}
    }
});

/* Request Information - Populate Address Fields */

$.fn.extend({
    SelectAddressToPopulate: function (options) {
        // Check the options and apply defaults.
        var empty = {};
        var defaults = { address1: '', address2: '', city: '', county: '', postcode: '' };
        var settings = $.extend(empty, defaults, options);

        $(this).change(function() {
            var address;
            $("option:selected", $(this)).each(function() {
                address = $(this).val();
                // Determine whether to populate the address.
                if (address && address != '') {
                    // Populate the address fields.
                    var fields = address.split('|');
                    var mainaddress = fields[0] + ' ' + fields[1];

                    var _address1 = $('#' + settings.address1);
                    var _address2 = $('#' + settings.address2);
                    var _city = $('#' + settings.city);
                    var _county = $('#' + settings.county);
                    var _postcode = $('#' + settings.postcode);

                    // Combine premise and street and determine if they can be seperated evenly.
                    if (mainaddress.indexOf(',') > 0) {
                        var position = mainaddress.lastIndexOf(',');
                        _address1.val(mainaddress.substring(0, position));
                        _address2.val(mainaddress.substring((position + 1)) + ' ' + fields[2]);
                    }
                    else {
                        _address1.val(mainaddress);
                        _address2.val('');
                    }
                    _city.val(fields[3]);
                    _county.val(fields[4]);
                    _postcode.val(fields[5]);

                    // Ensure the lengths of the address are within the maximum lengths.
                    if (_address1 && _address1.val() != '' && _address1.val().length > _address1.maxLength) {
                        _address1.val(_address1.val().substring(0, (_address1.maxLength - 1)));
                    }
                    if (_address2 && _address2.val() != '' && _address2.val().length > _address2.maxLength) {
                        _address1.val(_address2.val().substring(0, (_address2.maxLength - 1)));
                    }
                    if (_city && _city.val() != '' && _city.val().length > _city.maxLength) {
                        _city.val(_city.val().substring(0, (_city.maxLength - 1)));
                    }
                    if (_county && _county.val() != '' && _county.val().length > _county.maxLength) {
                        _county.val(_county.val().substring(0, (_county.maxLength - 1)));
                    }
                    if (_postcode && _postcode.val() != '' && _postcode.val().length > _postcode.maxLength) {
                        _postcode.val(_postcode.val().substring(0, (_postcode.maxLength - 1)));
                    }
                }
            });
        });
    }
});

/* AJAX Spinner */

$.fn.extend({
    ajaxSpinStart: function (options) {
        // Check the options and apply defaults.
        var empty = {};
        var defaults = { css: 'spinner', text: 'Loading...' };
        var settings = $.extend(empty, defaults, options);

        // destroy any spinners in the current element.
        $('.' + settings.css, this).remove().append('<div class="' + settings.css + '"><span class="img"></span><span class="text">' + settings.text + '</span></div>');
    },
    ajaxSpinStop: function (options) {
        // Check the options and apply defaults.
        var empty = {};
        var defaults = { css: 'spinner' };
        var settings = $.extend(empty, defaults, options);

        // destroy any spinners 
        $('.' + settings.css, this).remove();
    }
});

$.extend({
    ajaxSpinDialog: function (options) {
        // Check the options and apply defaults.
        var empty = {};
        var defaults = { container: null, text: 'Please wait...' };
        var settings = $.extend(empty, defaults, options);

        var cont = $(settings.container);

        // Append the elements.
        cont.append('<div class="mod-mask mod-abs"></div><div class="spinner mod-abs"><span class="img"></span><span class="text">' + settings.text + '</span></div>');

        var mask = $('.mod-mask', cont);
        var spin = $('.spinner', cont);
        
        // Adjust the mask.
        mask.css({
            height: cont.height(),
            width: cont.width(),
            left: cont.position().left,
            top: cont.position().top
        });

        // Adjust the spinner.
        spin.css({
            left: mask.position().left + (mask.width() / 2) - (spin.width() / 2),
            top: mask.position().top + (mask.height() / 2) - (spin.height() / 2)
        });
    }
});

