//Open external links in a new window
$("a[href^='http:']:not([href*='" + window.location.host + "'])").addClass('exit-popup').live('click', function () {
    $(this).attr('target', '_blank');

});

$(document).ready(function(){ 
	$('#text-only-switch').addClass('textoff');
	$('.textoff').live('click', function(){
		//alert ('text only');
		$('#styleSwitch').attr('href', '/content/frontend/public/css/print.css');
		$(this).text("Full site");
		$(this).removeClass('textoff');
		$(this).addClass('texton');
	});
	$('.texton').live('click', function(){
		$('#styleSwitch').attr('href', '/content/frontend/public/css/global.css');
		$(this).text("Text only");
		$(this).removeClass('texton');
		$(this).addClass('textoff');
	});
});

if (!Lpc) var Lpc = {};

Lpc.searchEndpoint = "/search/help?query=";
Lpc.maxSavedCookiePages = 50;
Lpc.favourites = null;
Lpc.userPrefs = null;

Lpc.retrieveFavourites = function () {
    if (Lpc.favourites != null) { return Lpc.favourites };
    var favouritesCookie = $.cookie('lpc_favourites');
    var favourites = Lpc.decodeKeyValueCollection(favouritesCookie);
    // Cache that data!
    Lpc.favourites = favourites;
    return favourites;
};

Lpc.decodeKeyValueCollection = function (encodedKeyValueCollection) {
    var items = [];
    if (encodedKeyValueCollection == null) { return items; }

    var keyValueCollection = encodedKeyValueCollection.split('|');

    for (index in keyValueCollection) {
        var keyValuePair = keyValueCollection[index].split('#');
        items.push({ key: keyValuePair[0], value: keyValuePair[1] });
    }

    return items;
};

// Save favourite pages to a cookie in following format: guid#title|guid#title ...
Lpc.addFavourite = function (e) {
    var guid = $(e.target).attr("data-page-id");
    var title = $(e.target).attr("data-page-title");
    var favourites = Lpc.retrieveFavourites();
    e.preventDefault();

    if (guid != null && guid.length == 36 && favourites.length <= Lpc.maxSavedCookiePages) {
        for (index in favourites) {
            // Already favourited
            if (favourites[index].key === guid) { return; }
        }

        favourites.push({ key: guid, value: title });
    }

    $.cookie('lpc_favourites', Lpc.encodeKeyValueCollection(favourites), { expires: 365, path: '/' });
    Lpc.updateFavoriteLinks();
};

Lpc.hasFavourite = function (guid) {
    var favourites = Lpc.retrieveFavourites($.cookie('lpc_favourites'));
    if (guid != null && guid.length == 36) {
        for (index in favourites) {
            if (favourites[index].key === guid) {
                return true;
            }
        }
    }
    return false;
};

Lpc.addPref = function (key, value) {
    if (Lpc.userPrefs == null) { Lpc.userPrefs = Lpc.decodeKeyValueCollection($.cookie('lpc_prefs')); }

    if (Lpc.getPref(key) != null) {
        Lpc.removePref(key);
    }

    Lpc.userPrefs.push({ key: key, value: value });
    $.cookie('lpc_prefs', Lpc.encodeKeyValueCollection(Lpc.userPrefs), { expires: 365, path: '/' });
}

Lpc.getPref = function (key) {
    if (Lpc.userPrefs == null) { Lpc.userPrefs = Lpc.decodeKeyValueCollection($.cookie('lpc_prefs')); }

    for (index in Lpc.userPrefs) {
        if (Lpc.userPrefs[index].key === key) {
            return Lpc.userPrefs[index].value;
        }
    }

    return null;
}


Lpc.removePref = function (key) {
    if (Lpc.userPrefs == null) { Lpc.userPrefs = Lpc.decodeKeyValueCollection($.cookie('lpc_prefs')); }

    if (key != null && key.length > 0) {
        for (index in Lpc.userPrefs) {
            if (Lpc.userPrefs[index].key === key) {
                Lpc.userPrefs.splice(index, 1);
            }
        }
    }

    if (Lpc.userPrefs.length === 0) {
        $.cookie('lpc_prefs', null, { path: '/' });
    } else {
        $.cookie('lpc_prefs', Lpc.encodeKeyValueCollection(Lpc.userPrefs), { expires: 365, path: '/' });
    }
}

Lpc.removeFavourite = function (e) {
    var guid = $(e.target).attr("data-page-id");
    var favourites = Lpc.retrieveFavourites();
    e.preventDefault();

    if (guid != null && guid.length == 36) {
        for (index in favourites) {
            if (favourites[index].key === guid) {
                favourites.splice(index, 1);
            }
        }
    }

    if (favourites.length === 0) {
        $.cookie('lpc_favourites', null, { path: '/' });
    } else {
        $.cookie('lpc_favourites', Lpc.encodeKeyValueCollection(favourites), { expires: 365, path: '/' });
    }

    Lpc.updateFavoriteLinks();
};

Lpc.removeFavouriteWithFeedback = function (e) {
    $(e.target.previousElementSibling).addClass('strikethrough');
    Lpc.removeFavourite(e);
    // Remove the delete link itself
    $(e.target).remove(); 
}

// Need to use pipe symbol as a separator because values
// may include other more common characters
Lpc.encodeKeyValueCollection = function (keyValueCollection) {
    var serializedKeyValues = [];

    $.each(keyValueCollection, function (index, item) {
        serializedKeyValues.push(item.key + "#" + item.value);
    });

    return serializedKeyValues.join('|');
};

Lpc.storeMyAreaGuid = function () {
    var guid = $(this).attr("data-area-guid");
    var postcode = $(this).attr("data-area-postcode");
 
    if (postcode != null && postcode.length > 0) {
        var encodedArea = guid + '|' + postcode
    } else {
        var encodedArea = guid + '| '
    }

    $.cookie('lpc_myarea', encodedArea, { expires: 365, path: '/' });
};

Lpc.retrieveMyAreaGuidAndPostcode = function () {
    var encodedArea = $.cookie('lpc_myarea');

    if (encodedArea != null) { return encodedArea.split('|'); }
    return [];
};

Lpc.clearMyAreaGuid = function () {
    $.cookie('lpc_myarea', null, { path: '/' });

    $("#my-area .area").slideUp(300, function () {
        $("#my-area .choose").slideDown(500);
        $("#my-area .area").remove();
    });

    return false;
};

Lpc.clearMyAreaGuidFromMyArea = function () {

    $.cookie('lpc_myarea', null, { path: '/' });
    Lpc.addPref("hideMyArea", "false");

};

Lpc.searchXhrIsInprogress = false;
Lpc.searchXhr;
    
Lpc.fetchSearchResults = function (query, template) {
    if (Lpc.searchXhrIsInprogress && Lpc.searchXhr && Lpc.searchXhr.readyState != 4) {
        Lpc.searchXhr.abort();
    }

    Lpc.searchXhrIsInprogress = true;
    Lpc.searchXhr = $.getJSON(Lpc.searchEndpoint + encodeURIComponent(query), function (data) {

        data.Results.unshift({ CapitalizedValue: query });
        $('#quick-search-items').html(template(data));
        Lpc.searchXhrIsInprogress = false;
    });
};

Lpc.renderSavedPages = function (container, template) {
    var favourites = Lpc.retrieveFavourites();

    if (favourites != null && favourites.length > 0) {
        var savedPages = { favourites: favourites };
        container.html(template(savedPages));
    }
};

Lpc.specialKeys = { up: 38, down: 40, enter: 23 };

Lpc.isSpecialKey = function (keyCode) {
    for (key in Lpc.specialKeys) {
        if (Lpc.specialKeys[key] == keyCode) {
            return true;
        }
    }
    return false;
};

// Suggested search terms list navigation
Lpc.navigateSearchResults = function (e) {
    if (!Lpc.isSpecialKey(e.keyCode)) { return; }

    var suggestedItems = $('#quick-search-items li');
    var currentItem = suggestedItems.filter('.selected'),
    nextItem;

    switch (e.keyCode) {
        case Lpc.specialKeys.up:
            nextItem = currentItem.prev();
            break;
        case Lpc.specialKeys.down:
            if (!suggestedItems.hasClass('selected')) {
                suggestedItems.first().addClass('selected');
            }
            nextItem = currentItem.next();
            break;
        case Lpc.specialKeys.enter:
            if (suggestedItems.hasClass('selected')) {
                $('#quick-search-query').val(currentItem.text());
                return;
            }
            break;
    }

    if (nextItem.is('li')) {
        currentItem.removeClass('selected');
        nextItem.addClass('selected');
    }

    // Copy selected item text to search box
    if (suggestedItems.hasClass('selected')) {
        $('#quick-search-query').val($('.selected').text());
    }

    if (e.keyCode === Lpc.specialKeys.up) return false;

    return;
};

Lpc.updateFavoriteLinks = function () {
    if ($('#add-favourite-link').length > 0 && $('#remove-favourite-link').length > 0) {
        var guid = $('#add-favourite-link a').attr("data-page-id");
        if (Lpc.hasFavourite(guid) == true) {
            $('#add-favourite-link').hide();
            $('#remove-favourite-link').show();
        } else {
            $('#add-favourite-link').show();
            $('#remove-favourite-link').hide();
        }
    }
}

Lpc.executeSummaryDisplayPrefs = function () {
    if (Lpc.getPref('hideMyArea') === "true") {
        $("#my-area .area, #my-area .choose").hide();
    }
}

Lpc.hidePostCodeSearchLabel = function () {
    $("#enter-postcode").parent().addClass('on');
    $("#enter-postcode").css({ background: "#fff" });
};

Lpc.showPostCodeSearchLabel = function () {
    if ($("#enter-postcode").attr('value') === '') {
        $("#enter-postcode").parent().removeClass('on');
        $("#enter-postcode").css({ background: "transparent" });
    }
};



/*
Lpc.applyTextOnlyMode = function () {
	
	//$('link[href^=/content/frontend/public/css/global.css]').attr('href', '/content/frontend/public/css/print.css"');
	//$("#text-only-switch").text("Full site");
	if (document.createStyleSheet)//for <IE8 .append does not work inside <head>
	{
		document.createStyleSheet("/content/frontend/public/css/print.css");
		//alert('IE styleheet triggered');
	}
	else
	{	 
		$('head').append('<link rel="stylesheet" href="/content/frontend/public/css/print.css" type="text/css" />');
		//alert('stylesheet added');
	}
	$("#text-only-switch").text("Full site");
};

Lpc.exitTextOnlyMode = function () {
	//$('link[href^=/content/frontend/public/css/print.css]').attr('href', '/content/frontend/public/css/global.css"');
	//$("#text-only-switch").text("Text only");
	if (document.createStyleSheet)//for <IE8
	{
		var styleSheets = document.styleSheets;
		var href = '/content/frontend/public/css/print.css';
		for (var i = 0; i < styleSheets.length; i++) {
			if (styleSheets[i].href == href) {
				//alert ('IE stylesheet removed');
				styleSheets[i].disabled = true;
				break;			
				return false;
			}
		}
	}
	else
	{		
		$('head > link[href*="/content/frontend/public/css/print.css"]').remove();
		//alert ('stylesheet removed')
	}
	$("#text-only-switch").text("Text only");
	//alert('style removed');
   
};
*/




// Compile templates and attach handlers when appropriate
Lpc.initializeViews = function () {
    var searchTemplateSrc = $("#search-results-template").html();

    if (searchTemplateSrc != null && searchTemplateSrc.length > 0) {
        Lpc.searchResultTemplate = Handlebars.compile(searchTemplateSrc);
    }

    var savedPagesContainer = $("#my-saved-pages-container");

    if (savedPagesContainer != null && savedPagesContainer.length > 0) {
        var savedPagesTemplateSrc = $("#my-saved-pages-template").html();

        if (savedPagesTemplateSrc != null && savedPagesTemplateSrc.length > 0) {
            var savedPagesTemplate = Handlebars.compile(savedPagesTemplateSrc);
            Lpc.renderSavedPages(savedPagesContainer, savedPagesTemplate);
        }
    }

    if ($('#add-favourite-link > a').length > 0) $('#add-favourite-link > a').click(Lpc.addFavourite);
    if ($('#remove-favourite-link > a').length > 0) $('#remove-favourite-link > a').click(Lpc.removeFavourite);
    if ($('#postcode-search-results').length > 0) $('#postcode-search-results tr').click(Lpc.storeMyAreaGuid);
    if ($('#area-list').length > 0) $('#area-list li').click(Lpc.storeMyAreaGuid);
    if ($('#saved-pages-list').length > 0) $('#saved-pages-list li span').click(Lpc.removeFavouriteWithFeedback);
    if ($('#enter-postcode').length && $('#enter-postcode').val().length > 0) Lpc.hidePostCodeSearchLabel();

    if ($('.myarea-info').length > 0) {
        var guidAndPostcode = Lpc.retrieveMyAreaGuidAndPostcode();
        $('#' + guidAndPostcode[0]).text(guidAndPostcode[1]);
    }

    Lpc.updateFavoriteLinks();

    $('#survey-form').submit(function () {
        return ($(this).valid());
    });


/*
    $("#text-only-switch").click(function () {
        var displayAsTextOnly = Lpc.isTextOnly();
        Lpc.setTextOnly(!displayAsTextOnly);
    });

    var displayAsTextOnly = Lpc.isTextOnly();
    Lpc.setTextOnly(displayAsTextOnly);
};

Lpc.isTextOnly = function () {
    return Lpc.getPref("textOnly") === "true";
}

Lpc.setTextOnly = function (displayAsTextOnly) {
    if (!displayAsTextOnly) {
        Lpc.removePref("textOnly");
        Lpc.exitTextOnlyMode();
    } else {
        Lpc.addPref("textOnly", "true");
        Lpc.applyTextOnlyMode();
    }
*/	
};

Lpc.initializeFontSizes = function () {
    var normalSize = $(".size a:eq(0)"),
        mediumSize = $(".size a:eq(1)"),
        largeSize = $(".size a:eq(2)");

    largeSize.click(function (sender) {
        sender.preventDefault();
        Lpc.setTextSize('large');
    });

    mediumSize.click(function (sender) {
        sender.preventDefault();
        Lpc.setTextSize('medium');
    });

    normalSize.click(function (sender) {
        sender.preventDefault();
        Lpc.setTextSize('small');
    });

    var textSize = $.cookie('lpc_textSize');
    if (textSize != null) { Lpc.setTextSize(textSize); }
};

Lpc.setTextSize = function (size) {
    var textSizeLink = $('#textSizeCssLink');
    var url = textSizeLink.attr('href');
    var newUrl = url.slice(0, url.lastIndexOf('/') + 1) + size + '.css';
    
    textSizeLink.attr('href', newUrl);
    $.cookie('lpc_textSize', size, { path: "/" });
}

Lpc.onMyAreaSummaryDidLoad = function (result) {
    $('#my-area').html(result);
    if ($('#my-area').length > 0) Lpc.executeSummaryDisplayPrefs();

    if ($('#myAreaLink').length > 0) {
        $('#myAreaLink').click(function (e) {

            if ($('#my-area .area').length && !$('#my-area .choose').is(":visible")) {
                $('#my-area .area').slideToggle();
            } else {
                $('#my-area .choose').slideToggle();
            }

            // Allow link to work normally when we aren't on a Myrea pages.
            if ($('#my-area').length) {
                e.preventDefault();
            }
        });
    }

    if ($('#remove-saved-my-area').length > 0) { $('#remove-saved-my-area').click(Lpc.clearMyAreaGuid); }


    if ($('#enter-postcode').length && $('#enter-postcode').val().length > 0) Lpc.hidePostCodeSearchLabel();
    if ($('#saved-pages-count').length > 0) $('#saved-pages-count').text(Lpc.retrieveFavourites().length);

    $('#my-area a.hide').click(function (e) {
        $('#main #my-area .choose, #main #my-area .area').slideUp();
        Lpc.addPref("hideMyArea", "true");
        e.preventDefault;
    });

    Lpc.initializePostcodeSearchBoxEvents();
};


Lpc.initializePostcodeSearchBoxEvents = function () {
    /* my area search form - show/hide labels */
    $('#my-area .choose .search label, #int .myarea-info .search label').click(function () {
        Lpc.hidePostCodeSearchLabel();
    }).blur(function () {
        Lpc.showPostCodeSearchLabel();
    });
	
    $('#my-area .choose .search input, #int .myarea-info .search input, #my-area .choose .search label, #int .myarea-info .search label').focus(function () {
        Lpc.hidePostCodeSearchLabel();
    }).blur(function () {
        Lpc.showPostCodeSearchLabel();
    });
};

Lpc.loadMyAreaSummary = function () {
    $.ajax({
        type: 'GET',
        dataType: 'html',
        url: '/template/RenderMyArea',
        success: function (result) {
            Lpc.onMyAreaSummaryDidLoad(result);
        }
    });
};

Lpc.initNewsTicker = function () {

    /* news feed */
    $('#feed .ticker').cycle({
        fx: 'fade',
        next: '#feed-next',
        prev: '#feed-prev'
    });

    $('#feed #feed-pause').click(function () {
        $('#feed .ticker').cycle('pause');
        $(this).parent().hide();
        $('#feed .play').show();
        return false;
    });

    $('#feed .play').hide();

    $('#feed #feed-play').click(function () {
        $('#feed .ticker').cycle('resume', true);
        $(this).parent().hide();
        $('#feed .pause').show();
        return false;
    });

}

Lpc.fetchNextNewsletters = function (e) {

    var currentPage = $(e.currentTarget).attr("currentpage");
    var url = $('#my-area-url').val();

    $.ajax({
        type: 'GET',
        dataType: 'json',
        data: { url: url, currentPage: currentPage },
        url: '/template/FetchNewsletters',
        success: function (result) {

            $('#my-area-newsletter-container').empty();

            var containerSrc = $("#my-area-newsletters-template").html();
            var container = Handlebars.compile(containerSrc);
            var templatedHtml = container(result);

            $('#my-area-newsletter-container').html(templatedHtml);

            currentPage = parseInt(currentPage) + 1;
            $(e.currentTarget).attr("currentpage", currentPage);

            if (!result.HasMorePages) {
                $('#my-area-more-link').hide();
            }
        }
    });
};

$(document).ready(function () {
    Lpc.initializeViews();
    Lpc.initializeFontSizes();
    Lpc.initializePostcodeSearchBoxEvents();
    Lpc.initNewsTicker();

    /* open external links in new window */
    $("a[href*='http://']:not([href*='" + location.hostname + "']),[href*='https://']:not([href*='" + location.hostname + "'])").attr("target", "_blank").attr("title", "Opens new window");

    $("#sub-nav li:last").addClass("last");

    if ($('#home, .col-right').length > 0) {
        Lpc.loadMyAreaSummary();

        $('.home header ul.menu li.my-area').click(function (e) {
            $('#main #my-area .choose, #main #my-area .area').slideToggle();
            e.preventDefault;
        });

        /* colour change animations */
        $('#home #quick-search input.submit, #home #quick-search .searches h3 span').hide();
        window.setTimeout(function () {
            $('#home #quick-search input.submit, #home #quick-search .searches h3 span').fadeIn(1000, function () {
                $('#home #quick-search .searches').addClass('complete');
                $('#home #quick-search .searches h3 span').hide();
            });
            $('#home h2:eq(0)').animate({
                color: 'rgb(198,81,104)'
            }, 1000);
            $('#quick-search, #quick-search .panel').animate({
                backgroundColor: 'rgb(198,81,104)'
            }, 1000);
            $('#quick-search .panel h4, #quick-search .panel li a, #quick-search .panel li').animate({
                color: 'rgb(255,255,255)'
            }, 1000);
            $('#int #quick-search .searches h3').css({
                background: "url(/content/frontend/public/images/template/home-search-arrow-on.png) no-repeat 0 1px"
            });
            $('#int #quick-search input.submit, #int #myarea #quick-search input.submit').css({
                background: "url(/content/frontend/public/images/template/quicksearch-on.png) no-repeat 0 0"
            });
        }, 3000);




        var $tabs = $('a.tab');
        var $panels = $(
            $.map($tabs, function (el) {
                return el.hash;
            }).join(', ')
        );





        $('#tabs').prepend('<ul class="nav" />');
        $('#tabs h2').each(function () {
            var theText = $(this).text();
            var theClass = $(this).attr('class');
            $('#tabs .nav').append('<li class="' + theClass + '">' + theText + '</li>');
        });

        $('#tabs .panel').hide();

        // Remove the # character from location hash
        var requestedTabName = window.location.hash.substring(1);

        if (requestedTabName != null && requestedTabName.length > 0 && $('#tabs .' + requestedTabName).length > 0) {
            $('#tabs .' + requestedTabName).show();
            $('#tabs .nav li.' + requestedTabName).addClass('on');
        } else {
            $('#tabs .panel:eq(0)').show();
            $('#tabs .nav li:first-child').addClass('on');
        }

        $('#tabs .nav li').click(function () {
            if (!$(this).hasClass('on')) {
                var theIndex = $(this).index();
                $(this).addClass('on').siblings().removeClass('on');
                $('#tabs .panel').stop(true, true).hide();
                $('#tabs .panel:eq(' + theIndex + ')').stop(true, true).fadeIn('slow');
            }
        });

    }

    if ($('#remove-saved-my-area-my-area').length > 0) { $('#remove-saved-my-area-my-area').click(Lpc.clearMyAreaGuidFromMyArea); }
    $('#my-area-more-link').click(function (e) { Lpc.fetchNextNewsletters(e) });

    if ($('#int')) {

        $('.tabs').each(function () {
            if ($(this).find('h2').length > 1) {
                $(this).addClass('tabbed').prepend('<ul class="nav" />');
                $(this).find('h2').each(function () {
                    var theText = $(this).text();
                    var theClass = $(this).attr('class');
                    $(this).parent().find('.nav').append('<li class="' + theClass + '">' + theText + '</li>');
                });
                $(this).find('.panel').hide();

                // Remove the # character from location hash
                var requestedTabName = window.location.hash.substring(1);

                if (requestedTabName != null && requestedTabName.length > 0 && $(this).find('.' + requestedTabName).length > 0) {
                    $(this).find('.panel.' + requestedTabName).show();
                    $(this).find('.nav li.' + requestedTabName).addClass('on');
                } else {
                    $(this).find('.panel:eq(0)').show();
                    $(this).find('.nav li:first-child').addClass('on');
                }

                $(this).find('.nav li:last-child').addClass('last');
                $(this).find('.nav li').click(function () {
                    if (!$(this).hasClass('on')) {
                        var theIndex = $(this).index();
                        $(this).addClass('on').siblings().removeClass('on');
                        $(this).parent().parent().find('.panel').stop(true, true).hide();
                        $(this).parent().parent().find('.panel:eq(' + theIndex + ')').stop(true, true).fadeIn('slow');
                    }
                });
            }
        });

        $('.see-also').each(function () {
            if ($(this).find('ul li').length > 2) {
                $(this).find('ul').jcarousel({
                    visible: 2,
                    scroll: 1,
                    wrap: 'circular'
                });
            }
        });

        $('.myarea-team').each(function () {
            if ($(this).find('ul li.item').length > 2) {
                var noItems = $(this).find('ul li.item').length;
                var theWidth = noItems * (100 + 80);
                $(this).find('ul:eq(0)').css({ 'width': theWidth });
                var jsp = $('.myarea-team').jScrollPane({ showArrows: true, animateScroll: true });
                var api = jsp.data('jsp');
                $('.jspArrowRight').bind('click',
		            function () {
		                api.scrollToX(theWidth);
		                return false;
		            }
	            );
                $('.jspArrowLeft').bind('click',
		            function () {
		                api.scrollToX(-theWidth);
		                return false;
		            }
	            );
            }

            if ($(this).find('ul li.item').length == 3) {   //Hack for scroll of officers. Only if there are 3 items apply the last class.
                var thirdItem = $(this).find('ul li.item')[2];
                $(thirdItem).addClass("last");
                $(".jspHorizontalBar").hide();
                $(".jspContainer").css({ height: 170 + "px" });
            }
        });

        // colorboxes
        $('.news-detail .gallery a').colorbox();

        // form validation
        $("#comments .post form").validate();

    }
    // live search
    $('#quick-search').each(function () {
        if ($('#home').length === 1 || $('#myarea').length === 1) {
            dummyText = 'Start typing and suggestions will appear';
        } else {
            dummyText = 'Start typing';
        }
        $(this).prepend('<label for="quick-search-query" class="dummy">' + dummyText + '</label>');
        if (!$('#quick-search-query').attr('value') == '') {
            $('#quick-search').addClass('on');
        }
        $('#quick-search .searches').before('<ul id="quick-search-items"></ul>');
        $('#quick-search-items').hide('slow');
        $('#quick-search-query').focus(function () {
            $('#quick-search').addClass('on');
        }).blur(function () {
            if ($(this).attr('value') === '') {
                $('#quick-search').removeClass('on');
                $('#quick-search-items').hide('slow');
                $('#quick-search-items li').remove();
            }
        });

        $('#quick-search-query').keyup(function (e) {
            // Arrow & enter keys; do not re-fetch data while user is navigating
            if (Lpc.isSpecialKey(e.keyCode)) {
                e.preventDefault();
                return false;
            }

            if ((this.value.length === 0) || (this.value.length === 1)) {
                $('#quick-search-items').slideUp();
                $('#quick-search-items li').remove();
            } else if (this.value.length === 2) {
                $('#quick-search-items').slideUp();
                $('#quick-search-items li').remove();

                Lpc.fetchSearchResults(this.value, Lpc.searchResultTemplate);

                $('#quick-search-items li:gt(9)').hide();
                $('#quick-search-items').slideDown();
            } else if (this.value.length > 2) {
                Lpc.fetchSearchResults(this.value, Lpc.searchResultTemplate);
            }
        });

        $('#quick-search-query').keydown(Lpc.navigateSearchResults);

        $('#quick-search #quick-search-items li').live('click', function () {
            $('#quick-search').addClass('on');
            var theText = $(this).text();
            $('#quick-search-query').attr('value', theText);
            $('#quick-search-items li').remove();
            $('#quick-search-items').slideUp();
            return false;
        });

        $(this).find('.searches li').click(function () {
            $('#quick-search').addClass('on');
            var theText = $(this).text();
            $('#quick-search-query').attr('value', theText);
            $('#quick-search-items li').remove();
            $('#quick-search-items').slideUp();
            return false;
        });
    });
    /* recent/popular searches */
    $('#quick-search .searches .panel').hide();
    $(' #quick-search .searches h3').click(function () {
        $(this).toggleClass('on');
        $(this).parent().find('.panel').slideToggle();
    });

    var pathname = window.location.pathname,
  		pathname = pathname.split("/"),
        $this = $(this);

    if (pathname == ",") {
        $("body").addClass("index");
    }
    else {
        $("body").addClass(pathname[1]);
    }
    $(".menu li a").hover(function () {
        $(".menu li").addClass("inactive");
        $(this).parent().addClass("active").removeClass("inactive");
    }, function () {
        $(".menu li a").parent().removeClass("active inactive");
    });

    $("#aboutus").hover(function () {
        $(".menu li").addClass("inactive");
        $(".menu li").first().addClass("active").removeClass("inactive");
    }, function () {
        $(".menu li a").parent().removeClass("active inactive");
    });

    $("#helpadvice").hover(function () {
        $(".menu li").addClass("inactive");
        $(".menu li:eq(1)").addClass("active").removeClass("inactive");
    }, function () {
        $(".menu li:eq(1) a").removeClass("active inactive");
        $(".menu li a").parent().removeClass("active inactive");
    });

    $("#contactus").hover(function () {
        $(".menu li").addClass("inactive");
        $(".menu li:eq(3)").addClass("active").removeClass("inactive");
    }, function () {
        $(".menu li:eq(3) a").parent().removeClass("active inactive");
        $(".menu li a").parent().removeClass("active inactive");
    });

    $(".sub-menu li:eq(0)").addClass("border");
    $(".sub-menu li:last-child").addClass("last_item");
    $(".sub-menu-col:eq(0)").addClass("first_col");
    $(".sub-menu-col:eq(1)").addClass("second_col");
    $(".sub-menu ul li ul li").addClass("no_border");
    $(".sub-menu a:contains('Departments')").addClass("departments");

    //var db = document.body,
    //dochtml = document.documentElement;

    //var dh = Math.max(db.scrollHeight, db.offsetHeight, dochtml.clientHeight, dochtml.scrollHeight, dochtml.offsetHeight);
    //$("[id^=\"wrap\"]").css("height", dh);

    // Equal column heights 
    if ($('.myarea-team').length > 0) {
        var biggestHeight = 0;
        $('li.item').each(function () {
            if ($(this).height() > biggestHeight) {
                biggestHeight = $(this).height();
            }
        });
        $('li.item').height(biggestHeight);
    }

});

$(window).load(function () {

    $('#sub-nav-wrapper').attr('style', "");

});
