﻿Cufon.replace('.cufon')('h1')('h2')('h3')('p.quote');
Cufon.replace('.float-menu ul li a', { fontFamily: 'HelveticaNeueV2' });
Cufon.replace('.float-header h2', { fontFamily: 'HelveticaNeueV2' });
Cufon.replace('a.close-button', { fontFamily: 'HelveticaNeueV2' });
Cufon.replace('body.home #main-menu ul li.connect2law a', { fontFamily: 'HelveticaNeueV2' });


String.prototype.endsWith = function (str) { return (this.match(str + "$") == str) }
String.prototype.startsWith = function (s) { return this.indexOf(s) == 0; };
String.prototype.contains = function (str) { return this.indexOf(str) != -1; };

function bind_form_events() {

    /* SET FORM FOCUS ENTER SUBMIT OF FOCUSED INPUT  */
    var focussed_form;
    $('input').focus(focus_form);
    $('input').blur(unfocus_form);
    /*$('textarea').focus(focus_form);
    $('textarea').blur(unfocus_form);*/
    $('select').focus(focus_form);
    $('select').blur(unfocus_form);
    $('a.btn').focus(focus_form);
    $('a.btn').blur(unfocus_form);
    $('.select_bg').focus(focus_form);

    $(document).keypress(function(e) {
        if (e.keyCode == 13) {            
            submit_form();
        }
    });
    $('a.preventDefault').click(function(e) {
        e.preventDefault();
    });

    $('a.btn.forinput').click(function(e) {
        e.preventDefault();
        $(this).closest('form').trigger('submit');
    });

    //footer modifications
    var Browser = {
        Version: function () {
            var version = 999; // we assume a sane browser
            if (navigator.appVersion.indexOf("MSIE") != -1)
            // bah, IE again, lets downgrade version number
                version = parseFloat(navigator.appVersion.split("MSIE")[1]);
            return version;
        }
    }
}

function focus_form() {
    focussed_form = $(this).closest('form');
}

function unfocus_form() {
    focussed_form = null;
}

function submit_form() {
    $(focussed_form).trigger('submit');
}

// Get main body to fill height of window
function resizeBodyHeight() {

    var mainContentPadding = parseInt($("#main-body").css("padding-bottom"));
    var maincontentcontainer = $('#main-content');
    var mainContentHeight = $('#main-content').height();

    var footerHeight = $('#footer').height();
    var windowHeight = $("#window-wrapper").height();

    maincontentcontainer.css('height', (mainContentHeight < (windowHeight - (footerHeight + mainContentPadding)) ? (windowHeight - (footerHeight + mainContentPadding)) : mainContentHeight) + 'px');  
}

$(document).ready(function () {

    LoadControls();

    $.preloadCssImages();
    bind_form_events();
    resizeBodyHeight();

    $(window).scroll(function () {
        resizeBodyHeight();
    });

    $(window).resize(function () {
        resizeBodyHeight();
    });

    //var paddingBottom = parseInt($("#main-body").css("padding-bottom") ? $("#main-body").css("padding-bottom") : 0);
    //$('.home #main-body').height($("#window-wrapper").height() - paddingBottom);

    $('select').JellyfishCustomSelect();

    //footer search control hack
    RemoveControls();

    $('#search-content').css('display', 'none');
    $('#newsletter-content').css('display', 'none');
    $('#next-step-numbers').css('display', 'none');

    $("a.category").click(function (event) {
        $(this).parent("li").parent("ul").find("ul.sector").hide();
        $(this).parent("li").find("ul.sector").slideToggle();
        return false;
    });

    $("a.call-us").click(function (event) {
        event.preventDefault();
        $('#next-step-numbers').toggle(function () { });
    });


    
});

function LoadControls() {
    // Replace submit buttons
    $("input.submit").after(function () { return $('<a></a>').attr({ "href": "", "class": "submit-btn btn forinput", "id": $(this).attr('id') }).html($(this).attr('value')); }).remove();
    $('input:checkbox').checkbox();
    $('.float-tabs #footer-search-container').css('display', 'block');
    $('.float-tabs #billpay-container').css('display', 'block');
}

function RemoveControls() {
    $('.float-tabs #footer-search-container').css('display', 'none');
    $('.float-tabs #billpay-container').css('display', 'none');
}

// Search panel

$(document).ready(function () {
    $('body').click(function () {
        $('#search-content').hide();
    });
    $("#search-container").click(function (event) {
        $('#search-content').toggle('', function (e) {
            //event.stopPropagation();
        });
        return false;
    });
});

// Menu
$(document).ready(function() {
   /*$("#main-menu ul").treeview({
        animated: "fast",
        collapsed: true,
        unique: true,
        prerendered: true
    });*/

    $("#main-menu ul a.unclickable").click(function(e) {
        e.preventDefault();
    });
});

// People Key Contacts
$(document).ready(function() {
    $("#key-contacts .contact a.contact-img").mouseover(function() {
        var contacthtml = $(this).parent('.contact').find('h3').html();
        var infoboxhtml = $("#key-contacts").find('.info-box h3').html();
        if (contacthtml != infoboxhtml) {
            $("#key-contacts").find('.info-box').html($("<h3 />").hide().html(contacthtml).fadeIn('slow'));
        }
    });
});

// Publication Issues Loader
$(document).ready(function() {
    $('#publication-issues .issue-thumb a').click(function(e) {
        e.preventDefault();
        //$('#issue-detail').html('');
        show_ajax_loader("#issue-detail");
        var url = '/ajax/PublicationIssueItem?publicationissuereference=' + $(this).attr('rel');
        $.get(url, function(data) {
            $('#issue-detail .content').html(data).hide().fadeIn();
            hide_ajax_loader("#issue-detail");
        });
    });
});

// Adding Publication Issues to list
$(document).ready(function() {

    bind_remove_pub_trigger();

    var message_container = $("#register-updates").find('a#addtolist').parent();
    var error = $('<span />').html('Please select an issue to add to your list.').addClass('field-validation-error').fadeTo('fast', 0);

    $("#register-updates a#addtolist").click(function(e) {
        e.preventDefault();
        var issuevalue = $("#publicationissuedd_customselect").val();
        if (issuevalue == "" || issuevalue == "0") {
            $(message_container).append(error);
            $(error).fadeTo('slow', 1);
        }
        else {
            $(error).fadeTo('slow', 0);
            show_ajax_loader("#subscribed-publications");
            var index = $("#subscribed-publications").find("a#item-index");
            var indexint = parseInt($(index).attr('rel'));
            $.get("/ajax/PublicationIssueFormItem", { Index: indexint, PublicationIssueId: issuevalue, SubscriptionCategoryid: "3" }, function(data) {
                $("#subscribed-publications ul").append(data).find('li:last').hide().fadeIn('slow');
                indexint++
                $(index).attr('rel', indexint);
                bind_remove_pub_trigger();
                hide_ajax_loader("#subscribed-publications");
            });
        }
        return false;
    });

    function bind_remove_pub_trigger() {

        $("#subscribed-publications ul a.remove-btn").click(function(e) {
            e.preventDefault();
            $(this).parent('li').fadeTo(900, 0).slideUp(500, function() {
                $(this).remove();
            });
        });
    }
});

// Quick Links
$(document).ready(function() {

    bind_quicklinks_trigger();
    var quicklinkbtn = $(".content-toolbar a.add-quick-links");
    var msg_title = "Page added to quick links";
    var msg_msg = "Your quick link has been added";
    $(quicklinkbtn).click(function(e) {
        e.preventDefault();
        e = $(this);
        e.trigger('blur');

        var ajax_loader_container = '#quick-links-select';

        if ((e).hasClass(':not(.disabled)')) {
            show_ajax_loader(ajax_loader_container);
            var text = $(this).parent('.content-toolbar').find("input:hidden[name='currentpagetitle']").val();
            var value = $(this).parent('.content-toolbar').find("input:hidden[name='currentpageurl']").val();
            var quicklinkadded = $(this).parent('.content-toolbar').find("input:hidden[name='quicklinkadded']").val();
            $.getJSON("/ajax/AddUserAttribute", { attributetypeid: 2, text: text, value: value }, function(data) {
                $("#quicklinksdd_options").addItems(data, "quicklinksdd");
                hide_ajax_loader(ajax_loader_container);
                bind_quicklinks_trigger();
                if (data == "-1") {
                    msg_title = "Unable to add quick link";
                    msg_msg = "An error has occurred";
                    show_confirmationpopup(msg_title, msg_msg, 1);
                }
                else {
                    if (quicklinkadded == 'false') show_confirmationpopup(msg_title, msg_msg, 2);
                    toggle_quicklinkbtn();
                }
            });
        }
    });

    function toggle_quicklinkbtn() {
        var title = msg_title;
        if ((quicklinkbtn).hasClass('disabled')) {
            title = "Add page to quick links";
            $(quicklinkbtn).fadeOut('slow', function() { $(this).html(title).attr('title', title).fadeIn('slow').removeClass('disabled'); });
        }
        else {
            $(quicklinkbtn).fadeOut('slow', function() { $(this).html(msg_title).attr('title', title).fadeIn('slow').addClass('disabled'); });
        }
    }

    function process_remove_item(id, object) {
        $.get("/ajax/removeuserattribute", { attributeid: id },
           function(data) {
               remove_item(object);
               if ((quicklinkbtn).hasClass('disabled')) {
                   title = "Add page to quick links";
                   $(quicklinkbtn).fadeOut('slow', function() { $(this).html(title).attr('title', title).fadeIn('slow').removeClass('disabled'); });
               }
           });
    }

    function remove_item(object) {
        var dd = $(object).closest('.optionswrapper');
        $(dd).css('height', 'auto');
        var newheight = $(dd).height();
        if (newheight > 200) {
            $(dd).height(200);
        }
        else {
            $(dd).parent('.jScrollPaneContainer').css('height', 'auto');
            $(dd).css('height', 'auto');
        }
        $(object).next('.selectitems').fadeTo(900, 0).slideUp(500, function() {
            //hide_dropdown();
            reinitialiseScrollPane();
            $(this).prev('a.remove-btn').remove();
            $(this).remove();
            hide_ajax_loader('#quick-links-select');
        });
    }

    function hide_dropdown() {
        $("#quicklinksdd_holder").fadeOut(250);
        $(document).unbind('keyup');
        $(document).unbind('keypress');
        $('body').unbind('click');
    }

    function bind_quicklinks_trigger() {
        $("#quicklinksdd_options a.remove-btn").click(function(e) {
            e.preventDefault();
            show_ajax_loader('#quick-links-select');
            process_remove_item($(this).attr('rel'), $(this));
            return false;
        });
    }

    // Send to a friend
    var sendtofriendbtn = $(".content-toolbar a.send-to-friend");
    $(sendtofriendbtn).click(function(e) {
        e.preventDefault();
        e = $(this);
        e.trigger('blur');
        var msg_title = "Send this page to a friend";
        var msg_msg = "";
        if ((e).hasClass(':not(.disabled)')) {
            toggle_sendtofriendbtn();
            show_confirmationpopup(msg_title, msg_msg, 3);
        }
    });

    function process_sendtofriend(dialog) {
        // Enable the btn
        toggle_sendtofriendbtn();
        bind_form_events();

        var ajax_loader_container = $(dialog).find('a.btn').parent();
        var error = $('<span />').html('Please complete all required fields correctly.').addClass('field-validation-error').fadeTo('fast', 0);

        $(dialog).find("input:hidden[name='msg.pagetitle']").val(document.title);
        $(dialog).find("input:hidden[name='msg.pageurl']").val(window.location);

        $('#fsendtofriend').submit(function() {
            $(error).fadeTo('fast', 0);
            show_ajax_loader(ajax_loader_container);
            $.post("/ajax/sendtofriend",
                $(this).serialize(),
	                function(data) {
	                    hide_ajax_loader(ajax_loader_container);
	                    if (data == "-1") {
	                        $(ajax_loader_container).append(error);
	                        $(error).fadeTo('slow', 1);
	                    }
	                    else {
	                        $("#fsendtofriend").slideUp('slow', function() {
	                            var h = $("<h2 />").html('You have sent this page to your friend!').hide();
	                            $(this).before(h);
	                            $(h).slideDown();
	                        });
	                    }
	                }
                 );

            return false;
        });
    }

    function toggle_sendtofriendbtn() {
        var title = "Send to a friend";
        $(sendtofriendbtn).fadeOut('slow', function() { $(this).html(title).attr('title', title).fadeIn('slow').toggleClass('disabled'); });
    }

    function hide_confirmationpopup(dialog) {
        $(dialog).fadeOut().remove();
        $("#overlay").fadeOut().remove();
    }
});

function show_ajax_loader(container) {
    $(container).append('<div class="ajax-loader"></div>');
}

function hide_ajax_loader(container) {
    $(container).find('.ajax-loader').remove();
}

$(document).ready(function() {

    //$('#bookmark-page').jFav();

    // Add Printing Functionality    
    $('a.print-page').click(function(e) {
        e.preventDefault();
        window.print();
    });

    // add a "rel" attrib if Opera 7+
    if (window.opera) {
        if ($("a.bookmark-page").attr("rel") != "") { // don't overwrite the rel attrib if already set
            $("a.bookmark-page").attr("rel", "sidebar");
        }
    }

    $("a.bookmark-page").click(function (event) {
        event.preventDefault();
        var url = window.location;
        var title = document.title;
        addBookmark(title, url);
    });

    function addBookmark(title, url) {
        if (window.sidebar) {
            window.sidebar.addPanel(title, url, "");
        } else if (document.all) {
            window.external.AddFavorite(url, title);
        } else if (window.opera && window.print) {
            alert('Press ctrl+D to bookmark (Command+D for macs)');
        } else if (window.chrome) {
            alert('Press ctrl+D to bookmark (Command+D for macs)');
        } else {
            alert('Press ctrl+D to bookmark (Command+D for macs)');
        }
    }
});

// Subscription Table
$(document).ready(function() {

    var toggleTable = "#subscription-table .article-section-top a.icon-arrow";
    var toggleChecks = "#subscription-table .check-all a";
    var openAll = "#subscription-table .subscription-table-header a.openall";
    var collapseAll = "#subscription-table .subscription-table-header a.closeall";

    $("#all-subscriptions #subscription-table .article-section").toggleClass('selected');

    $(toggleTable).click(function(e) {
        e.preventDefault();
        $(this).closest('.article-section').toggleClass('selected');
        if ($(this).html() == 'open') $(this).html('close'); else $(this).html('open');
    });

    $(toggleChecks).click(function(e) {
        e.preventDefault();
        var Index = $(this).closest('.article-section-top').find('.sub-col').index($(this).closest('.sub-col'));
        $(this).closest('.article-section').find('.col' + Index + ' input:checkbox').each(function(index) {
            if ($(this).is(':checked')) $(this).attr('checked', false); else $(this).attr('checked', true);
        });
        $(this).closest('.article-section:not(.selected)').addClass('selected').find('.article-section-top .icon-arrow').html('close');
    });

    $(openAll).click(function(e) {
        e.preventDefault();
        $(this).closest('#subscription-table').find('.article-section').addClass('selected').find('.article-section-top .icon-arrow').html('close');
    });

    $(collapseAll).click(function(e) {
        e.preventDefault();
        $(this).closest('#subscription-table').find('.article-section').removeClass('selected').find('.article-section-top .icon-arrow').html('open');
    });
});

// People Search
$(document).ready(function() {

    switchToCustomRadios("#name-radio-switch", "anchor-radio-switch", true);
    switchToCustomRadios("#people-letters", "anchor-radio-switch2", false);

    $("#name-radio-switch a.default").click(function(e) {
        e.preventDefault();
        disableCustomRadios();
    });

    $("#name-radio-switch a:not(.default)").click(function(e) {
        e.preventDefault();
        enableCustomRadios();
    });

    $('input:radio:not(#name-radio-switch input:radio, #people-letters input:radio)').checkbox();

});

function switchToCustomRadios(container, anchor_switch_class, appendslash) {

    var defaultvalue = "";
    var selectedvalue = "";
    var label_count = $(container + ' label').size();
    var anchor_switch_selector = "." + anchor_switch_class;

    $(container).find('label').each(function(i) {

        var input = $('input', this);

        var anchor = '<a href="" rel="' + $('input', this).attr('value') + '" class="' + anchor_switch_class + '">' + $(this).text() + "</a>";

        if (appendslash) {
            if (i < label_count - 1) anchor += " / ";
        }

        $(this).removeAttr('class');
        $(this).html('');
        $(this).append(input);
        $(this).append(anchor);

        if (i == 0) {
            $(input).next("a").addClass('default');
            defaultvalue = $(input).attr('value');
        }

        if ($(input).attr('checked')) {
            $(input).next('a').addClass('selected');
            selectedvalue = $(input).attr('value');
        }

        if (defaultvalue == selectedvalue && container != "#people-letters") {
            disableCustomRadios();
        }

        $(input).css({ position: 'absolute', zIndex: -1, visibility: 'hidden' });
    });

    $(container).append('<div class="message"></div>');
    $(container + " div.message").hide();

    $(container + " a" + anchor_switch_selector).click(function(e) {
        e.preventDefault();
        $(this).blur();

        if ($(this).prev('input').is(':disabled')) {
        }
        else {
            $(this).prev('input').attr('checked', true);
            $(container + " .selected").removeClass("selected");
            $(this).addClass("selected");
            hideMessages();
        }
    });
}

function hideMessages() {
    $("#people-letters div.message").hide();
    $("#name-radio-switch div.message").hide();
}

function enableCustomRadios() {
    $("#people-letters input").removeAttr('disabled');
    $("#people-letters").removeClass('disabled');
}

function disableCustomRadios() {
    $("#people-letters input").attr('disabled', true);
    $("#people-letters").addClass('disabled');
}


function LoadCalendar(element) {

    $(element + ' .dp-select').datePicker({ createButton: false }).bind(
				'click',
				function () {
				    updateSelects($(this).dpGetSelected()[0]);
				    $(this).dpDisplay();
				    return false;
				}
			).bind(
				'dateSelected',
				function (e, selectedDate, $td, state) {
				    updateSelects(selectedDate);
				}
			).bind(
				'dpClosed',
				function (e, selected) {
				    updateSelects(selected[0]);
				}
			);

    var updateSelects = function (selectedDate) {
        var selectedDate = new Date(selectedDate);
        $(element + ' .day option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
        $(element + ' .month option[value=' + (selectedDate.getMonth() + 1) + ']').attr('selected', 'selected');
        $(element + ' .year option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
    }

    $(element + ' .day, ' + element + ' .month, ' + element + ' .year').bind('change',
        function () {
            var d = new Date($(element + ' .year').val(), $(element + ' .month').val() - 1, $(element + ' .day').val());
            $(element).dpSetSelected(d.asString());
        });

    //var today = new Date();
    //updateSelects(today.getTime());
    //$(element + ' .day').trigger('change');
}

    // Request a call back
$(document).ready(function () {

    // Request a call back
    var requestcallbacklink = $("a.request-a-call-back");
    $(requestcallbacklink).click(function (e) {
        e.preventDefault();
        e = $(this);
        e.trigger('blur');
        var msg_title = "Request a call back";
        var msg_msg = "";
        //if ((e).hasClass(':not(.disabled)')) {
        toggle_requestcallbackbtn();
        show_confirmationpopup(msg_title, msg_msg, 4);
        //}
    });

    function process_requestcallback(dialog) {
        // Enable the btn
        toggle_requestcallbackbtn();
        //bind_form_events();

        var ajax_loader_container = $(dialog).find('a.btn').parent();
        var error = $('<span />').html('Please complete all required fields correctly.').addClass('field-validation-error').fadeTo('fast', 0);

        $(dialog).find("input:hidden[name='msg.pagetitle']").val(document.title);
        $(dialog).find("input:hidden[name='msg.pageurl']").val(window.location);

        $('#frequestcallback').submit(function () {
            $(error).fadeTo('fast', 0);
            show_ajax_loader(ajax_loader_container);
            $.post("/ajax/requestcallback",
                $(this).serialize(),
	                function (data) {
	                    hide_ajax_loader(ajax_loader_container);
	                    if (data == "-1") {
	                        $(ajax_loader_container).append(error);
	                        $(error).fadeTo('slow', 1);
	                    }
	                    else {
	                        $("#frequestcallback").slideUp('slow', function () {
	                            var h = $("<p />").addClass('success-message').html('You have requested a callback.  We will get back to you as soon as possible.').hide();
	                            if ($(this).prev('p').length == 0) {
	                                $(this).before(h);
	                            }
	                            $(h).slideDown();
	                        });
	                    }
	                }
                 );

            return false;
        });
    }

    function toggle_requestcallbackbtn() {
        var title = "Request a call back";
        $(requestcallbacklink).fadeOut('slow', function () { $(this).html(title).attr('title', title).fadeIn('slow').toggleClass('disabled'); });
    }

    // Pop Up Boxes
    function show_confirmationpopup(title, message, type) {
        $.get("/ajax/ConfirmationPopUp", { title: title, message: message, type: type }, function (data) {

            $('#window-wrapper').append(data);
            var dialog = $("#confirmation-popup");

            LoadControls();
            bind_form_events();

            if (type == 4) process_requestcallback(dialog);
            if (type == 5) process_registerforupdates(dialog);

            var winH = $(window).height();
            var winW = $(window).width();

            //Set the popup window to center
            $(dialog).css('top', winH / 2 - $(dialog).height() / 2);
            $(dialog).css('left', winW / 2 - $(dialog).width() / 2);

            $("#overlay").fadeTo("slow", 0.5).fadeIn("slow", function () { $(dialog).fadeIn(500); });

            Cufon.replace("#confirmation-popup h2");

            $(dialog).find("a.close-btn").click(function (e) {
                e.preventDefault();
                hide_confirmationpopup(dialog);
            });
            $(dialog).click(function () {
                //hide_confirmationpopup(dialog);
            });
            $("#overlay").click(function () {
                hide_confirmationpopup(dialog);
            });
            $(document).keyup(function (e) {
                /*if (e.which == 13) {
                $(document).unbind('keyup');
                $(document).unbind('keypress');
                hide_confirmationpopup(dialog);
                }*/
                if (e.keyCode == 27) {
                    $(document).unbind('keyup');
                    $(document).unbind('keypress');
                    hide_confirmationpopup(dialog);
                }
            });
        });
    }

    function hide_confirmationpopup(dialog) {
        $(dialog).fadeOut().remove();
        $("#overlay").fadeOut().remove();
    }

});

//Page top Newsletter Panel
$(document).ready(function () {

    $("#newsletter-container").click(function (event) {
        $('#newsletter-content').toggle('', function (e) {

        });
        return false;
    });

    $("#newsletter-result-close").click(function (event) {

        if ($('#newsletter-result-close').html() == 'Try again') {

            $('#newsletter-result').toggle('', function (e) {
                $('#newsletter-form').toggle('', function (e) { });
            });
        }
        else {
            $('#newsletter-content').toggle('', function (e) {
                $('#newsletter-form').show();
                $('#newsletter-result').hide();
                $('#newsletter_yourname').val('Your name...');
                $('#newsletter_youremailaddress').val('Your email address...');
            });
        }
        return false;
    });

    $("#newsletter-signup").click(function (event) {
        event.preventDefault();
        var url = '/ajax/SimpleSignup?sendername=' + $("#newsletter_yourname").attr('value') + '&senderemail=' + $("#newsletter_youremailaddress").attr('value');
        $.get(url, function (data) {
            if (data == 1) {
                $('#newsletter-result-message').html('You have successfully registered for our newsletter.');
                $('#newsletter-result-close').html('Close');
            }
            else {
                $('#newsletter-result-message').html('We could not register you at this time. Check that you have supplied your name and a valid email address and try again.');
                $('#newsletter-result-close').html('Try again');
            };
            $('#newsletter-form').toggle('', function (e) {
                $('#newsletter-result').toggle('', function (e) { });
            });
        });
    });

});

// Register for updates
$(document).ready(function () {

    // Register for updates
    var registerforupdateslink = $("a.register-for-updates");
    $(registerforupdateslink).click(function (e) {
        e.preventDefault();
        e = $(this);
        e.trigger('blur');
        var msg_title = "Register for updates";
        var msg_msg = "";
        if (!$(this).hasClass('.disabled')) {
            toggle_registerforupdateslink();
            show_confirmationpopup(msg_title, msg_msg, 5, $("input:hidden[name='productid']").val());
        }
    });

    function process_registerforupdates(dialog) {
        // Enable the btn
        toggle_registerforupdateslink();
        //bind_form_events();

        var ajax_loader_container = $(dialog).find('a.btn').parent();
        var error = $('<span />').html('Please complete all required fields correctly.').addClass('field-validation-error').fadeTo('fast', 0);

        $(dialog).find("input:hidden[name='msg.pagetitle']").val(document.title);
        $(dialog).find("input:hidden[name='msg.pageurl']").val(window.location);

        $('#fregisterforupdates').submit(function () {
            $(error).fadeTo('fast', 0);
            show_ajax_loader(ajax_loader_container);
            $.post("/ajax/registerforupdates",
                $(this).serialize(),
	                function (data) {
	                    hide_ajax_loader(ajax_loader_container);
	                    if (data == "-1") {
	                        $(ajax_loader_container).append(error);
	                        $(error).fadeTo('slow', 1);
	                    }
	                    else {
	                        $("#fregisterforupdates").slideUp('slow', function () {
	                            var h = $("<p />").html('<br/>You have successfully registered for updates.').hide();
	                            $(this).before(h);
	                            $(h).slideDown();
	                        });
	                    }
	                }
                 );

            return false;
        });
    }

    function toggle_registerforupdateslink() {
        var title = "Register for updates";
        $(registerforupdateslink).fadeOut('slow', function () { $(this).html(title).attr('title', title).fadeIn('slow').toggleClass('disabled'); });
    }

    // Pop Up Boxes
    function show_confirmationpopup(title, message, type, productid) {
        $.get("/ajax/ConfirmationPopUp", { title: title, message: message, type: type, param: productid }, function (data) {

            $('#window-wrapper').append(data);
            var dialog = $("#confirmation-popup");

            LoadControls();
            bind_form_events();

            if (type == 5) process_registerforupdates(dialog);

            var winH = $(window).height();
            var winW = $(window).width();

            //Set the popup window to center
            $(dialog).css('top', winH / 2 - $(dialog).height() / 2);
            $(dialog).css('left', winW / 2 - $(dialog).width() / 2);

            $("#overlay").fadeTo("slow", 0.5).fadeIn("slow", function () { $(dialog).fadeIn(500); });

            Cufon.replace("#confirmation-popup h2");

            $(dialog).find("a.close-btn").click(function (e) {
                e.preventDefault();
                hide_confirmationpopup(dialog);
            });
            $(dialog).click(function () {
                //hide_confirmationpopup(dialog);
            });
            $("#overlay").click(function () {
                hide_confirmationpopup(dialog);
            });
            $(document).keyup(function (e) {
                /*if (e.which == 13) {
                $(document).unbind('keyup');
                $(document).unbind('keypress');
                hide_confirmationpopup(dialog);
                }*/
                if (e.keyCode == 27) {
                    $(document).unbind('keyup');
                    $(document).unbind('keypress');
                    hide_confirmationpopup(dialog);
                }
            });
        });
    }

    function hide_confirmationpopup(dialog) {
        $(dialog).fadeOut().remove();
        $("#overlay").fadeOut().remove();
    }

});

////Floating Toolbar
$(document).ready(function () {

    $(TabsContainer).css({ 'min-height': '10px' });

    checkAndSwap();

    $(window).scroll(function () {
        checkAndSwap();
    });

    $(window).resize(function () {
        checkAndSwap();
    });

    var TabsOpen = "";
    var TabsContainer = ".float-tabs";
    var FloatMenu = ".float-menu";
    var FloatWrapper = ".float-wrapper";

    function checkAndSwap() {

        if (isScrolledIntoView($('#footer-content'))) {
            $('.float-container').css({ position: 'relative', top: null, bottom: null });
        }
        else {
            $('.float-container').css({ position: 'fixed', top: null, bottom: 0 });
        }
    }

    function isScrolledIntoView(elem) {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
    }

    function focusOnActiveLink() {
        $(TabsContainer + " #" + TabsOpen + " a").focus();
        $(TabsContainer + " #" + TabsOpen + " a").addClass("active-link");
    }

    function toggleTabNav(tab) {
        // Clear all the 'on' classes
        $(FloatMenu + ' li').removeClass("selected-menu");

        // Only turn on menu items not already open
        if (TabsOpen != tab) {
            $(FloatMenu + " ." + tab).closest("li").addClass("selected-menu");
        }
    }

    function toggleTab(tab) {

        $(TabsContainer).show(); //Reset for multiple click problem
        $(TabsContainer).css('visibility', 'visible');

        if (TabsOpen) {
            if (TabsOpen === tab) {
                //check if search panel
                if (tab == 'footer-search-container') {
                    var isvisible = true;
                    $(TabsContainer + " #" + 'footer-search-container').css('visibility', (isvisible ? "visible" : "hidden"));
                }

                if (tab == 'footer-newsletter-container') {
                    $('#footer-newsletter-form').show();
                    $('#footer-newsletter-result').hide();
                    $('#footer_newsletter_yourname').val('');
                    $('#footer_newsletter_youremailaddress').val('');
                }

                // Close Already Open Tab(s)
                $(TabsContainer + " .selected-tab").animate({ height: ['toggle', 'easeOutSine'] }, 500, 'easeOutSine', function () {
                    TabsOpen = "";
                    $(TabsContainer).hide();
                }).removeClass("selected-tab");

            } else {
                $(TabsContainer + " #" + tab + " ." + "float-header").css('visibility', 'hidden');
                $(TabsContainer + " #" + tab + " ." + "float-body-content").css('visibility', 'hidden');

                // Close old tab and slide in new tab
                $(TabsContainer + " #" + TabsOpen).animate({ height: ['toggle', 'easeOutSine'] }, 500, 'easeOutSine', function () {

                    $(TabsContainer + " #" + TabsOpen).removeClass("selected-tab").css({ zIndex: 98 });

                    $(TabsContainer + " #" + tab).animate({ height: ['toggle', 'easeOutSine'] }, 500, 'easeOutSine', function () {
                        $(TabsContainer + " #" + tab + " ." + "float-header").css('visibility', 'visible');
                        $(TabsContainer + " #" + tab + " ." + "float-body-content").css('visibility', 'visible');
                    }).addClass("selected-tab");

                    TabsOpen = tab;
                    focusOnActiveLink();
                }).css({ zIndex: 99 }).removeClass("selected-tab");

            }

        } else {
            // Open New Tab                
            $(TabsContainer + " #" + tab).animate({ height: ['toggle', 'easeOutSine'] }, 500, 'easeOutSine', function () {
                TabsOpen = tab;
                focusOnActiveLink();
            }).css({ zIndex: 99 }).addClass("selected-tab");
        }
    }

    // Tab vs Click - Check if the visitor is tabbing through the float navigation 
    $(".float-container").keyup(function (event) {
        if (event.keyCode == '9') {
            $(".float-container").addClass("tab-user");
        }
    });

    $(FloatMenu).mouseup(function (event) {

        $(".float-container").removeClass("tab-user");

    });

    //show or hide content panels
    $(FloatMenu + ' a').click(function (e) {
        e.preventDefault();
        if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }
        checkAndSwap();
        var tab = $(this).attr("class");
        
        if ($(TabsContainer + ' div').is(':animated')) return false;

        toggleTabNav(tab);
        toggleTab(tab);
    });

    // Close Tab by clicking close button
    $(TabsContainer + ' a.close-button').click(function (event) {
        event.preventDefault();
        var tab = $(this).closest("div.selected-tab").attr("id");
        toggleTabNav(tab);
        toggleTab(tab);
        $(FloatMenu + " a." + TabsOpen).focus();
    });

    // Close Tab using ESC button.
    $(TabsContainer).keyup(function (event) {
        if (event.keyCode == '27') {
            closeOpenTab();
            $(FloatMenu + " a." + TabsOpen).focus();
        }
    });

    function closeOpenTab() {
        if (TabsOpen) {
            toggleTabNav(TabsOpen);
            toggleTab(TabsOpen);
        }
    }

    function HandleMultipleClicks() {

    }

    //Footer Newsletter Panel
    $("#footer-newsletter-signup").click(function (event) {

        //event.preventDefault();

        if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; }

        var url = '/ajax/SimpleSignup?sendername=' + $("#footer_newsletter_yourname").attr('value') + '&senderemail=' + $("#footer_newsletter_youremailaddress").attr('value');
        $.get(url, function (data) {
            if (data == 1) {
                $('#footer-newsletter-result .failed-header').hide();
                $('#footer-newsletter-result .success-header').show();
                $('#footer-newsletter-result-message').html('You have successfully registered for our newsletter.');
                $('#footer-newsletter-result-close').html('Close');
            }
            else {
                $('#footer-newsletter-result .success-header').hide();
                $('#footer-newsletter-result .failed-header').show();
                $('#footer-newsletter-result-message').html('We could not register you at this time. Check that you have supplied your name and a valid email address and try again.');
                $('#footer-newsletter-result-close').html('Try again');
            };
            $('#footer-newsletter-form').animate({ height: ['toggle', 'jswing'] }, 500, 'jswing', function (e) {
                $('#footer-newsletter-result').animate({ height: ['toggle', 'jswing'] }, 500, 'jswing', function () { });
            });
        });
    });
    $("#footer-newsletter-result-close").click(function (event) {

        if ($('#footer-newsletter-result-close').html() == 'Try again') {

            $('#footer-newsletter-result').animate({ height: ['toggle', 'jswing'] }, 500, 'jswing', function (e) {
                $('#footer-newsletter-form').animate({ height: ['toggle', 'jswing'] }, 500, 'jswing', function (e) { });
            });
        }
        else {

            var tab = $(this).closest("div.selected-tab").attr("id");
            toggleTabNav(tab);
            toggleTab(tab);
        }
        return false;
    });

    //Search panel
    $('#footer-search-container .keywords').defaultvalue("Enter keyword(s)...");

    //Bill-Pay panel
    //Info-popup.
    $('.fancyiframe').fancybox({
        'width': '75%',
        'height': '100%',
        'autoScale': true,
        'autoDimensions': false,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'type': 'image',
        'speedIn': 600,
        'speedOut': 400
    });
});
