var productsToCompare = []; //empty variable for passing list of products to compare to grid view

function hideTbContent(hideThis) {
	var tbContainer = $(hideThis);
	//hides all mid content which does not contain open class
	$('#productTable').attr('aria-live','polite').attr('aria-relevant', 'all');
	tbContainer.find('.open').attr('aria-hidden', false);
	tbContainer.find('.midContent:not(.open)').attr('aria-hidden', true).hide().prev().find('.sectionType').addClass('closed');
	
	$('.subHeader a').click(function(e){
		var trSubHeader = $(this).parents('.subHeader');
		e.preventDefault();
		if(trSubHeader.next('.midContent').is(':visible')) {
			trSubHeader.find('.sectionType').addClass('closed');
			trSubHeader.next('.midContent').fadeOut('slow').attr('aria-hidden', true);
		}
		else {
			trSubHeader.find('.sectionType').removeClass('closed');
			trSubHeader.next('.midContent').fadeIn('slow').attr('aria-hidden', false);
		}					
	});
}

// Fixed table header : Start
if (typeof oldIe === "undefined") {
    var oldIe = false;
}

var CompareAcc = (function (a) {
    return function (c) {
        var b = this;
        this.formName = c;
        this.lastPostData = "";
        this.resultsContainer = null;

        this.init = function () {
            this.resultsContainer = a("#productTable" + this.formName);
            this.fixedTableHeader();
        };
        
        this.fixedTableHeader = function () {
            var e = this.resultsContainer.find("table#productComparison");
            if (!e.length) {
                return;
            }
            if (oldIe && (e.offset().top !== e.positionedOffset().top)) {
                return;
            }
            var d = "fixed-table-header" + this.formName;
            a("#" + d).remove();
            e.fixedTableHeader({
                addClass: "productComparison",
                addId: d
            });
        };
		
        this.init();
    };
})(jQuery);
	
(function (b) {
    var a = 0;
    b.fn.fixedTableHeader = function (c) {
        var d = jQuery.extend({
            headerRowSize: 3,
            highlightRow: false,
            highlightClass: "highlight",
            addClass: "",
            addId: true,
            appendToParent: false,
            appendTo: "body"
        }, c);
        return this.each(function () {
            var h = b(this);
            var f = h.find("tr:lt(" + d.headerRowSize + ")");
            var e = "th";
            if (f.find(e).length === 0) {
                e = "td";
            }
            if (f.find(e).length > 0) {
                f.find(e).each(function () {
                    b(this).css("width", b(this).width());
                });
                var g = h.clone().empty();
                if (d.addId === true) {
                    g.attr("id", "fixed-table-header" + a);
                } else {
                    if (d.addId) {
                        g.attr("id", d.addId);
                    }
                }
                a++;
                g.addClass(d.addClass).css({
                    position: "fixed",
                    top: "0",
                    left: h.offset().left
                }).append(f.clone()).width(h.outerWidth()).hide();
                if (d.appendToParent) {
                    g.appendTo(h.parent());
                } else {
                    g.appendTo(b(d.appendTo));
                }
                if (d.highlightRow) {
                    b("tr:gt(" + (d.headerRowSize - 1) + ")", h).hover(function () {
                        b(this).addClass(d.highlightClass);
                    }, function () {
                        b(this).removeClass(d.highlightClass);
                    });
                }
                b(window).scroll(function () {
                    var j = b(window).scrollTop();
                    var i = f.offset().top;
                    if (jQuery.browser.msie && jQuery.browser.version === "6.0") {
                        g.css({
                            position: "absolute",
                            top: j,
                            left: h.offset().left
                        });
                    } else {
                        g.css({
                            position: "fixed",
                            top: "0",
                            left: h.offset().left - b(window).scrollLeft()
                        });
                    }
                    if (j > i && j <= (i + h.height() - f.height())) {
                        g.show();
                    } else {
                        g.hide();
                    }
                });
                b(window).resize(function () {
                    if (g.outerWidth() !== h.outerWidth()) {
                        f.find(e).each(function (j) {
                            var i = b(this).width();
                            b(this).css("width", i);
                            g.find(e).eq(j).css("width", i);
                        });
                        g.width(h.outerWidth());
                    }
                    g.css("left", h.offset().left);
                });
            }
        });
    };
})(jQuery);
	

// Fixed table header : End

function setEqualHeight(columns){
	 var tallestcolumn = 0;
	 columns.each(function(){
		 currentHeight = $(this).height();
			 if(currentHeight > tallestcolumn){
			   tallestcolumn  = currentHeight / 16 * 16 + 20 + "px";
			 }
	 });
   columns.height(tallestcolumn);
}

function productCounter (view){
	var numberOfProducts;
		numberOfProducts = $('#productComparison tr:first-child th').length -1;
		$('ul li a b').html(numberOfProducts);
		return false;
}

function zebra (){
  var productComparison = $('#productComparison tr');
	productComparison.find('th:odd,td:odd').attr('class','odd');
	productComparison.find('th:even,td:even').attr('class','even');
	productComparison.find('td:first-child, th:first-child').attr('class','');
}

function prepareTable(){
	var numberOfProducts = $('#productComparison tr:first-child th').length -1;
	var totalColumns = parseInt(numberOfProducts, 10) + 1;
	$('ul li a b').text(numberOfProducts);
	var containerwidth = $('#productComparison').parent().width();
	var columnWidth = containerwidth - 130;
	var getColumnWidth = (columnWidth / numberOfProducts) - 40;
	productCounter ('grid');
	
	zebra();
	
	return false;
}

function moreLinks(){
  var productComparison = $('#productComparison tr a.more');
	productComparison.parent().next('p').hide().attr('aria-hidden', true);
	productComparison.click(function(e){
	e.preventDefault();
	if($(this).hasClass('open')) {
		$(this).removeClass('open').parent().next('p').slideUp().attr('aria-hidden', true);
	}
	else {
		$(this).toggleClass('open').parent().next('p').slideDown().attr('aria-hidden', false);
	}
	});
}

function checkURLHash(){ 
	if(location.href.indexOf("#") !== -1 && window.location.hash !== '#' && window.location.hash !== '' ) { 
		return true;
    }
	return false;
}

function scrollToElement(e){ 
	var d = 0;
	if (e.length > 0) {
		if ($.browser.msie) { d = 20; }

		$('html,body').delay(d).animate({ scrollTop: e.offset().top }, { duration: 'fast', easing: 'swing'});
	}
}

/***** new carousel ****/
$.fn.infiniteCarousel = function () {

    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }
  
    return this.each(function () {
        var $carouselWrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $carouselWrapper.find('> ul'),
            $items = $slider.children('li'),
            $single = $items.eq(0),
            singleWidth = $single.outerWidth(), 
            visible = Math.ceil($carouselWrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
            currentPage = 1,
            pages = Math.ceil($items.length / visible),
			wait = "";            
		
		function doAutScroll(){
			return gotoPage(currentPage + 1);
		}

		// setInterval and ClearInterval	
		var intervalWait = {
			wait: '',
			start: function (myFunction, speed) {
				//this.wait = setInterval(myFunction, speed || 9000);
				this.wait = setInterval(myFunction, speed || 999999);
			},
			
			stop: function () {
				clearInterval(this.wait);
			}
		};

		// call autoScroll
		intervalWait.start(doAutScroll);
		
	    // 1. Pad so that 'visible' number will always be seen, otherwise create empty items
	    if (($items.length % visible) !== 0) {
	        $items = $slider.find('> li');
	    }
	
	    // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
	    $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
	    $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
	    $items = $slider.find('> li'); // reselect
	
		// 3. iterate through the list and create list-nav elements
		function getImgSiblings(pages){
			var totalItem = $items.length,
				getImg = $slider.find('img'),
				thisTab = $('.carouselWrapper li a.carouselTab'),
				thisChildren = $('.carouselWrapper li:not(.cloned) a.carouselTab'),
				thelastChild = $('.carouselWrapper li a.carouselTab:eq(2)'),
				itemList = $('.carouselWrapper li');
			
			$('.carouselWrapper').parent().attr('aria-live','polite').attr('aria-relevant', 'all');
			
			thisTab.css({'display':'none'});
			thisChildren.css({'display':'block'});
										
			// iterate only on the original list not cloned ones and assigned id attribute
			itemList.each(function(){
				if($(this).hasClass("cloned")){
					$(this).removeAttr('id');
				}
			});
			
			thisTab.each(function(pages){
				$(this).bind('mouseover focusin', function(e){ 
					intervalWait.stop();
					$('#hero').trigger('goto', [ pages ]);
				});
				
				$(this).bind('click', function(e){ 
					e.preventDefault();
					intervalWait.stop();
					$('#hero').trigger('goto', [ pages ]);
				});
				
			});
			
			$items.each(function(pages){
				$(this).bind('mouseover focusin', function(e){ 
					intervalWait.stop();
				});
			});
			
			$('#hero').each(function(pages){
				$('#hero').bind('focusout mouseleave', function(e){
					intervalWait.start(doAutScroll);
				});
			
			});	
		
			// set tab
			thisChildren.each(function(pages){
				var totalTab = parseInt (thisChildren.lengthv, 10),
					setLeft = parseInt (940 / totalTab * pages, 10),
					setTabWidth = parseInt (940 / totalTab - 34, 10);
								
				$(this).css({
					'left': setLeft,
					'width': setTabWidth
				});	
				
				var getW = parseInt (thelastChild.width(), 10);
				if ($(".carouselWrapper li:last a.carouselTab")) {
					$(".carouselWrapper li:last a.carouselTab").width(getW).css({'left':0});
				}	
			});	
		}
			
	    // 4. Set the left position to the first 'real' item
	    $carouselWrapper.scrollLeft(singleWidth * visible);
			
		// the last carousel equal the first carousel.	
		$(".carouselWrapper li.cloned:last a.carouselTab").addClass("current");
		$('.carouselWrapper .tabArticleText').css({'display':'none'});
		$items.eq(1).find('a.carouselTab')
			.addClass('current')
			.siblings('.tabArticleText').fadeIn('fast');
			
		// 5. paging function
		function gotoPage(page) {
			var itemList = $items;
			var dir = page < currentPage ? -1 : 1,
				n = Math.abs(currentPage - page),
				left = singleWidth * dir * visible * n;
			
			$carouselWrapper.filter(':not(:animated)').animate({
					scrollLeft : '+=' + left
				}, 500, function () {
				
				$(".carouselWrapper li a.carouselTab").removeClass("current"); // remove cless="current" from previous
				$(".carouselWrapper .tabArticleText").css({'display':'none'});
								
	            if (page === 0) {
	                $carouselWrapper.scrollLeft(singleWidth * visible * pages);
	                page = pages;				
					
	            } else if (page > pages) {
	                $carouselWrapper.scrollLeft(singleWidth * visible);
	                // reset back to start position
	                page = 1;
	            } 
	
				currentPage = page;
				var whichTabIndex = $(".carouselWrapper li a.carouselTab").eq(page);
				//check if current list image/carousel of index eq 0 then highlight
				if(currentPage===1){
					$(".carouselWrapper li.cloned:last a.carouselTab").addClass("current");
					$items.eq(1).find('a.carouselTab').addClass('current');	
					if ($items.eq(1).find('a.carouselTab').hasClass("current")) {
						$items.eq(1).find('a.carouselTab').siblings(".tabArticleText").fadeIn('fast');
					}			
				}else{	
					whichTabIndex.addClass("current");
					if(whichTabIndex.hasClass("current")){
						whichTabIndex.siblings(".tabArticleText").fadeIn('fast');
					}
				}
			});                
			return false;
		}
		
		getImgSiblings();
		
		// create a public interface to move to a specific page
		$(this).bind('goto', function (event, page) {
			gotoPage(page);
		});
    });  
};
// new carousel ends

$(document).ready(function() {
	
	$.PopupMenu.init();
	$.PillarPagination.init();
	
	/*- / - help/info --*/
	
	var formRegion = $('#mortgageForm');
	var formHelpLink = $('#mortgageForm li .help a');
	
	formRegion.attr('aria-live','polite').attr('aria-relevant', 'all');
	
	formHelpLink.attr('aria-hidden', true);
	
	formHelpLink.bind('mouseover focusin', function(e){
		$(this).parents('li').find('div').show().attr('aria-hidden', false);												
	});
	
	formHelpLink.click(function (e) {
		e.preventDefault();
		$(this).parents('li').find('div').show().attr('aria-hidden', false);
	});
		
	formHelpLink.bind('mouseout focusout', function(e){
		$(this).parents('li').find('div').hide().attr('aria-hidden', true);			
	});

	
	/* remove outline and text-decoration when mouseDown on links ****/	
	
	var skipLinks = $('li.skipLink a');
	skipLinks.each(function(){
		var that = $(this);
		var link = $('#innerPage a:eq(0)');
		that.click(function(e) {
			e.preventDefault();
			link.focus();
		});
	});
	
	var lastLink = $('p.skipLinkLast a');
	lastLink.each(function(){
		var that = $(this);
		var levelList = $("#sections li.level1");
		var link = $('#innerPage a:eq(0)');
		that.click(function(e) {
			e.preventDefault();
			levelList.removeClass('focused');
			levelList.find('div.doormat').removeClass('showdoormat').attr('aria-hidden', true);
			link.focus();
		});
	});
	
	var utilityLinks = $('div#mainTopUtility #tabs a');
	utilityLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var localeLinks = $('div#mainTopUtility #locale a');
	localeLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var logoLinks = $('div#logo a');
	logoLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'outline':'0'});
		});
	});
	
	var aPillarLinks = $('#advance a.pillarArrow');
	aPillarLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'border-color':'#7b7b7b'});
		});
	});
	
	var pPillarLinks = $('#premier a.pillarArrow');
	pPillarLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'border-color':'#181236'});
		});
	});
	
	var controlLinks = $('div#smallCarousel .galleryControls a');
	controlLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'border-color':'transparent'});
		});
	});
	
	var helpLinks = $('#mortgageForm span.help a');
	helpLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'border-color':'#e5e5e5'});
		});
	});

	var bannerLinks = $('div.doormat .info a');
	bannerLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'border-color':'#626469'});
		});
	});
	
	var promoLinks = $('div.contentRow .promo a');
	promoLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'border-color':'#fff'});
		});
	});
	
	var navLinks = $('a.mainTopNav');
	navLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var toggleLinks = $('a.hasMore');
	toggleLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var tabLinks = $('a.carouselTab');
	tabLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var handleLinks = $('div.handle a');
	handleLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var ptabLinks = $('#productTabs li a');
	ptabLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var pgtabLinks = $('#pageTabs li a');
	pgtabLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var cLinks = $('div#grid a');
	cLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'outline':'0'});
		});
	});
	
	var closeLinks = $('.jqmWindow .close a span');
	closeLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'outline':'0'});
		});
	});
	
	var overLinks = $('.jqmWindow a');
	overLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'outline':'0'});
		});
	});
	
	var langLinks = $('div.langList a');
	langLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var greyButtonLinks = $('a.greyBtn');
	greyButtonLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var redButtonLinks = $('a.redBtn');
	redButtonLinks.each(function(){
		var alink = $(this);
		alink.mousedown(function(e){
			alink.css({'text-decoration':'none'});
		});
	});
	
	var allInputs = $('input[type="submit"]');
	allInputs.each(function(){
		var inputlink = $(this);
		inputlink.mousedown(function(e){
			inputlink.css({'border':'0', 'outline':'0'});
		});
	});
	
	// new carousel
	$('#hero').infiniteCarousel();

  /* SETEQUALHEIGHTS ****/
	setEqualHeight($(".productFeature"));
	setEqualHeight($("#sideBar > section.widthBotBorder"));
	setEqualHeight($(".tabcontents .grid_5i, .exploreBox .grid_4i"));
	
  /* SEARCH FORM  *******/
	q = $('#q');
	q.focus(function() {
		if ((q.val()) === "Search") {
			$(this).attr('value','');
		}
	});
		
	q.blur(function() {
		$(this).removeAttr('style');
		if($(this).val() === "") {
			$(this).attr('value', 'Search');
		}
	});

	
	/* toggle locator */
	var locatorList = $(".locator a.greyBtn"); 
	locatorList.each(function(){
		var thatLocation = $(this);
			thatLocation.click(function(e){
			e.preventDefault();
			thatLocation.siblings(".linkList").slideToggle('fast',function(){});
			thatLocation.siblings(".linkList").bind('mouseleave',function(){
					$(this).css('display','none');
				});
	
		});		
	});

  /* LOCALE **********/
	var cntryList = function(){
		var listContainer = $("#locale .dropDownLink"),
			theDropdown = $('#dropDown'),
			dropdownContainer = $('#dropDownWrapper'),
			dropdownLink = $('#dropDown p.skipLink a');
		
		
		listContainer.attr('aria-controls', '#dropDown');
		theDropdown.css('display', 'none').addClass('showDropDown');
		theDropdown.attr('aria-live','polite').attr('aria-relevant', 'all');
				
		listContainer.click(function(e) {
			e.preventDefault();
			if(listContainer.hasClass('on')){
				listContainer.removeClass('on');
				theDropdown.fadeOut("slow", function() {}).attr('aria-expanded', false);
				theDropdown.parent().css('z-index', '1');
				theDropdown.parent().find('select').css('visibility', 'visible');
			}
			else {
				listContainer.addClass('on');
				theDropdown.fadeIn("slow", function() {}).attr('aria-expanded', true);
				theDropdown.parent().css('z-index', '20');
				theDropdown.find('a:eq(1)').focus();
				theDropdown.parent().find('select').css('visibility', 'hidden');
			}
		});
		
		dropdownLink.click(function(e) {
			e.preventDefault();
			listContainer.removeClass('on');
			theDropdown.fadeOut("slow", function() {}).attr('aria-expanded', false);
			theDropdown.parent().css('z-index', '1');
			theDropdown.parent().find('select').css('visibility', 'visible');
			listContainer.focus();				
		});
		
		$('#dropDown .nav li a.hasMore').each(function(){
			var thisTab = $(this);
			var thisDropDown = $(this).next("div");
			
			thisDropDown.attr('aria-hidden', true);
								
			thisTab.bind('focusin mouseover', function(){
				thisTab.addClass('on');
			});
			
			thisTab.bind('focusout mouseleave', function(){
				thisTab.removeClass('on');
			});
			
			thisTab.click(function(e) {
				e.preventDefault();
				if(thisTab.hasClass('on')){
					thisTab.removeClass('on');
					thisTab.addClass('up');
					thisDropDown.slideDown('slow', function(){}).attr('aria-hidden', false);
				}
				else {
					thisTab.removeClass('up');
					thisTab.addClass('on');
					thisDropDown.slideUp('slow', function(){}).attr('aria-hidden', true);
				}
			});
			
		});
		
		$('#dropDown .nav li a.parent').bind('focusin mouseover', function(){
				if($('#dropDown .nav li a[class~="up"]')){
					$('#dropDown .nav li a[class~="up"]').next("div").attr('aria-hidden', true).slideUp('slow', function(){});
					$('#dropDown .nav li a[class~="up"]').removeClass('up');
				}
				else {
					return false;
				}
		});
	};
	
	cntryList();  // call function to display locale country list 

  /* LOCALE **********/
	var logonList = function(){
		var listContainer = $("#authenticate"),
			theDropdown = $('#logon'),
			listParent = $('#authenticate').parents('ul');
		
		theDropdown.attr('aria-hidden', true);
		listParent.attr('aria-live','polite').attr('aria-relevant', 'all');
		
		listContainer.click(function(e) {
			e.preventDefault();
			if(listParent.hasClass('on')){
				theDropdown.fadeOut("slow", function() {}).attr('aria-hidden', true);
				listParent.removeClass('on');
			}
			else {
				listParent.addClass('on');
				theDropdown.fadeIn("slow", function() {}).attr('aria-hidden', false);
			}
		});

		theDropdown.bind('mouseleave', function(){
			theDropdown.fadeOut("slow", function() {}).attr('aria-hidden', true);
			listParent.removeClass('on');
		});
		
		$('#mainTopNavigation').focusin(function() {
			theDropdown.fadeOut("slow", function() {}).attr('aria-hidden', true);
			listParent.removeClass('on');
		});
		
	};
	
	logonList();  // call function to display locale country list 

	// main nav starts
	var mainNav = $("#sections li.level1"),
		mainNavTop = $("#sections li.level1 .mainTopNav"),
		doormatList = $("#sections li.level1 div.doormat");
	
	mainNavTop.attr('title', function(i, val) {
  	return 'Expand menu: ' + val 
	});
	
	doormatList.css("display", "block").attr('aria-hidden', true);
	
	$('#sections').attr('aria-live','polite').attr('aria-relevant', 'all');
	
	mainNav.bind('focusin mouseover', function(e){
		var that = $(this);
		that.addClass('focused');
		that.find('div.doormat').addClass('showdoormat').attr('aria-hidden', false);
		that.prevAll().removeClass('focused');
		that.prevAll().find('div.doormat').removeClass('showdoormat').attr('aria-hidden', true);
		that.nextAll().removeClass('focused');
		that.nextAll().find('div.doormat').removeClass('showdoormat').attr('aria-hidden', true);
	});
	
	mainNav.bind('focusout mouseleave', function(e){
		var that = $(this);
		that.removeClass('focused');
		that.find('div.doormat').removeClass('showdoormat').attr('aria-hidden', true);
	});
	
	mainNavTop.bind('click',function(e){
		e.preventDefault();
		});
	
	$('#sections p.skipLink a').click(function(e) {
		var that = $(this);
		var nextItem = that.parents('li').next('li');
		e.preventDefault();
		mainNav.removeClass('focused');
		mainNav.find('div.doormat').removeClass('showdoormat').attr('aria-hidden', true);
		nextItem.find('a:eq(0)').focus();
	});
	
// main nav ends here
	

  /* PRODUCTNAV **********/
  
  	var shareList = $('#productNav #shareTab')
	shareList.each(function(){
		var parent = $(this);
		parent.css('display', 'block');
	});

	var productNavlist = $('#productNav li ul.dropDown')
	productNavlist.each(function(){
		var list = $(this);
		list.css('display', 'none').attr('aria-hidden', true);
		$('#productNav').attr('aria-live','polite').attr('aria-relevant', 'all');
	});
  
  	$('#productNav li a.acctService').bind('click',function(e){
		var parent = $(this).parent();
		var expand = parent.children('.dropDown');
		e.preventDefault();
		if(parent.hasClass('on')){
			parent.removeClass('on').addClass('active');
		}
		parent.addClass('open');
		parent.css({
		'width': parent.width()
		});
		parent.siblings().removeClass('open');
		if (parent.siblings().hasClass('active')) {
			parent.siblings().removeClass('active').addClass('on');
		}
		parent.siblings().find('.dropDown').css('display', 'none').attr('aria-hidden', true);
		expand.css('display', 'block').attr('aria-hidden', false);
		e.stopPropagation();
	});
	
	$('#productNav li').bind('mouseleave',function(e){
		var parent = $(this);
		parent.removeClass('open');
		parent.css('width', 'auto');
		if (parent.hasClass('active')) {
			parent.removeClass('active').addClass('on');
		}
		parent.find('.dropDown').css('display', 'none').attr('aria-hidden', true);
	});
	
	$('#productNav').focusin(function(event) {
		$('#grid').focusin(function() {
			// Hide the menus
			$('#productNav li.open').removeClass("open").css('width', 'auto');
			$('#productNav li.active').removeClass("active").addClass('on');
			$('.dropDown').css('display', 'none').attr('aria-hidden', true);
		});
		event.stopPropagation();
	});

	$('.dropDown').focusin(function(event) {
		$('#productNav').focusin(function() {
			// Hide the menus
			$('#productNav li.open').removeClass("open").css('width', 'auto');
			$('#productNav li.active').removeClass("active").addClass('on');
			$('.dropDown').css('display', 'none').attr('aria-hidden', true);
		});
		event.stopPropagation();
	});
	
// product nav ends here
	
	/* MODAL *************/
	var lightviewDetails = $('#lightviewDetails'),
		lightviewDetails1 = $('#lightviewDetails1'),
		lightviewDetails2 = $('#lightviewDetails2'),
		lightviewDetails3 = $('#lightviewDetails3'),
		lightviewDetails4 = $('#lightviewDetails4'),
		lightviewDetails5 = $('#lightviewDetails5'),
		lightviewDetails6 = $('#lightviewDetails6'),
		lightviewProposition = $('#lightviewProposition'),
		lightviewProduct = $('#lightviewProduct');
		
	lightviewDetails.each(function(){
		
		lightviewDetails.attr('aria-hidden', true);
				
	});
	
	lightviewDetails1.each(function(){
		
		lightviewDetails1.attr('aria-hidden', true);
				
	});
	
	lightviewDetails2.each(function(){
		
		lightviewDetails2.attr('aria-hidden', true);
				
	});
	
	lightviewDetails3.each(function(){
		
		lightviewDetails3.attr('aria-hidden', true);
				
	});
	
	lightviewDetails4.each(function(){
		
		lightviewDetails4.attr('aria-hidden', true);
				
	});
	
	lightviewDetails5.each(function(){
		
		lightviewDetails5.attr('aria-hidden', true);
				
	});
	
	lightviewDetails6.each(function(){
		
		lightviewDetails6.attr('aria-hidden', true);
				
	});
	
	lightviewProposition.each(function(){
		
		lightviewProposition.attr('aria-hidden', true);
				
	});
	
	lightviewProduct.each(function(){
		
		lightviewProduct.attr('aria-hidden', true);
				
	});
								
	var modalOpen = function(hash){ 
		//display the modal window
		hash.w.show().attr('aria-hidden', false);
		
		//focus first link
		hash.w.find('a:eq(1)').focus();
		
		
		//attach esc key to close modal
		$(document).keydown( function( e ) { 
			if( e.which === 27) {  
				if (hash.w.is(":visible")) { 
					hash.w.jqmHide().attr('aria-hidden', true);
					$('#grid').find('a:eq(0)').focus();
				}
			} 
		}); 
		$('html, body').scrollTop(0);
		
		$('.jqmOverlay').css({
			zIndex:2
		});
		$('.jqmWindow').css({
			zIndex:3
		});
		
		$('#top').css({
			position: 'relative',
			zIndex: 1
		});
	};
	
	if(lightviewDetails.length){
		lightviewDetails.jqm({onShow:modalOpen});
		lightviewDetails.jqmAddTrigger('.triggerModalDetails');
		lightviewDetails.jqmAddClose('.close');
	}
	
	if(lightviewDetails1.length){
		lightviewDetails1.jqm({onShow:modalOpen});
		lightviewDetails1.jqmAddTrigger('.triggerModalDetails1');
		lightviewDetails1.jqmAddClose('.close');
	}
	
	if(lightviewDetails2.length){
		lightviewDetails2.jqm({onShow:modalOpen});
		lightviewDetails2.jqmAddTrigger('.triggerModalDetails2');
		lightviewDetails2.jqmAddClose('.close');
	}
	
	if(lightviewDetails3.length){
		lightviewDetails3.jqm({onShow:modalOpen});
		lightviewDetails3.jqmAddTrigger('.triggerModalDetails3');
		lightviewDetails3.jqmAddClose('.close');
	}
	
	if(lightviewDetails4.length){
		lightviewDetails4.jqm({onShow:modalOpen});
		lightviewDetails4.jqmAddTrigger('.triggerModalDetails4');
		lightviewDetails4.jqmAddClose('.close');
	}
	
	if(lightviewDetails5.length){
		lightviewDetails5.jqm({onShow:modalOpen});
		lightviewDetails5.jqmAddTrigger('.triggerModalDetails5');
		lightviewDetails5.jqmAddClose('.close');
	}
	
	if(lightviewDetails6.length){
		lightviewDetails6.jqm({onShow:modalOpen});
		lightviewDetails6.jqmAddTrigger('.triggerModalDetails6');
		lightviewDetails6.jqmAddClose('.close');
	}
	
	if(lightviewProposition.length){
		getLightboxContent($('.triggerModalProposition'), lightviewProposition);
		lightviewProposition.jqm({onShow:modalOpen});
		lightviewProposition.jqmAddTrigger('.triggerModalProposition');
		lightviewProposition.jqmAddClose('.close');
	}
	
	if(lightviewProduct.length){
		getLightboxContent($('.triggerModalProduct'), lightviewProduct);
		lightviewProduct.jqm({onShow:modalOpen});
		lightviewProduct.jqmAddTrigger('.triggerModalProduct');
		lightviewProduct.jqmAddClose('.close');
	}
	
	function getLightboxContent(trigger, lightbox){
		var url = trigger.attr('href'),
			containers = [];
		
		lightbox.find('.ajaxContent').each(function(){
			containers.push($(this).attr('id'));
		});
		
		$.get(url, function(data){
			for(i in containers){
				$(data).find('#' + containers[i].substr(5)).each(function(){
					lightbox.find('#' + containers[i]).append($(this));
				});
			}
		});
	}

// modal ends here
	
  /* TREENAV ************/
  	$('#treeNav').attr('aria-live','polite').attr('aria-relevant', 'all');
  	$('#treeNav').find('li.open').find('ul').attr('aria-hidden', false);
	$('#treeNav').find('li:not(.open)').addClass('closed').find('ul').attr('aria-hidden', true);
	$('#treeNav').find('p a').attr('title', function(i, val) {
  	return 'Expand or collapse menu: ' + val 
	});
	$('#treeNav li p').toggle(function(){
	  var parent = $(this).parent();
		parent.removeClass('closed').addClass('open');
		parent.find('ul').attr('aria-hidden', false);
	}, function () {
	  var parent = $(this).parent();
		parent.removeClass('open').addClass('closed');
		parent.find('ul').attr('aria-hidden', true);
	});

	
	// Apply modal
	var advanceCustomersContainer = $('#advanceCustomersContainer'),
		nonAdvanceCustomersContainer = $('#nonAdvanceCustomersContainer'),
		applyToggleTabs = $('#applyToggleTabs .applyToggle'),
		modalHeader = $('#applyModal .modalHeader');

	//disables click event on modal Header
	modalHeader.click(function(){
		return false;
	});

	advanceCustomersContainer.hide().removeClass("current");
	nonAdvanceCustomersContainer.hide().removeClass("current");

	applyToggleTabs.click(function(){
		var that = $(this);
		applyToggleTabs.removeClass("current").filter(that).addClass("current");
		if (that.attr("href") === '#advanceCustomersContainer') {
			advanceCustomersContainer.show();
			nonAdvanceCustomersContainer.hide();
		} else if (that.attr("href") === '#nonAdvanceCustomersContainer') {
			advanceCustomersContainer.hide();
			nonAdvanceCustomersContainer.show();
		}
		return false;
	});	


	prepareTable(); //check how many products we're comparing, add remove links
	moreLinks();
	hideTbContent('#productComparison');
	
	if (typeof CompareAcc !== "undefined") {
        new CompareAcc("");
    }
	
	//Tempoary code to stop the value -1 on productListingModule.html
	$('.productComparisonView b').html('4');
	
});

$.PopupMenu = {
	init: function(){
		var position = [];
		
		$('.popupMenu').attr('aria-live','polite').attr('aria-relevant', 'all');
		
		$('.popupMenu .popupMenuItem').each(function(){
			$(this).find('.popupMenuItemContent p.popupItemLink').addClass('hidden').attr('aria-hidden', true);
			position.push($(this).position());
		});
		$('.popupMenu .popupMenuItem').each(function(i){
			var $this = $(this),
				width = $this.width();
			$this.css({
				position: 'absolute',
				top: position[i].top,
				left: position[i].left
			});
			
			var expandedLeft = position[i].left;
			if((i+1) > position.length/2){
				$this.addClass('expanded');
				expandedLeft = position[i].left - ($this.width() - width);
				$this.removeClass('expanded');
				$this.find('img')
					.height(160)
					.width(200);
			}
			
			$this.find('.popupMenuItemInner').bind('focusin mouseover', function(e){
					$this
					.addClass('expanded')
					.css({
						top: -42,
						left: expandedLeft
					})
					.find('p.popupItemLink').removeClass('hidden').attr('aria-hidden', false);
				$this.parents('.grid').css('zIndex', '3');
				$this.find('img')
					.height('auto')
					.width('auto');
			});
			
			$this.find('.popupMenuItemInner').bind('focusout mouseleave', function(e){
				$this
					.removeClass('expanded')
					.css({
						top: position[i].top,
						left: position[i].left
					})
					.find('p.popupItemLink').addClass('hidden').attr('aria-hidden', true);
				$this.parents('.grid').css('zIndex', '1');
				$this.find('img')
					.height(160)
					.width(200);
			});
		});
	}
}

$.PillarPagination = {
	$container: null,
	$content: null,
	$list: null,
	$next: null,
	$prev: null,
	listWidth: 0,
	animSpeed: 500,
	currentPos: 1,
	init:function(){
		var obj = this,
			busy = false;
		this.$container = $('.pillarPagination');
		this.$content = this.$container.find('.pillarContent');
		this.$list = this.$content.find('ul');
		this.$next = $('<a class="pillarNext pillarArrow" href="#"><span>Scroll right</span></a>').appendTo(this.$container);
		this.$prev = $('<a class="pillarPrev pillarArrow" href="#"><span>Scroll left</span></a>').prependTo(this.$container);
		this.listWidth = this.$list.find('li').width();
		
		this.$container.attr('aria-live','polite').attr('aria-relevant', 'all');
		
		this.$list.find('li').each(function(i){
			if($(this).hasClass('current')){
				obj.currentPos = i+1;
			}
		});
		this.$content.css({
			height: this.$list.find('li').height(),
			position: 'relative',
			overflow: 'hidden'
		});
		this.$list.css({
			position: 'absolute',
			top: 0,
			left: 0,
			width: this.$list.find('li').length * this.listWidth
		});
		this.updateAria();
		this.updateArrows();
		
		$('.pillarArrow').click(function(e){
			e.preventDefault();
		});
										   
		this.$next.click(function(){
			if(!$(this).hasClass('pillarNextDisabled') && busy == false){
				busy = true;
				obj.$list.find('li').eq(obj.currentPos+1).css('display', 'block');
				obj.$list.animate({left: -420}, obj.animSpeed, function(){
					obj.currentPos++;
					obj.updateAria();
					obj.$list.css('left', 0);
					obj.updateArrows();
					busy = false;
				});
			}
		});
		this.$prev.click(function(){
			if(!$(this).hasClass('pillarPrevDisabled') && busy == false){
				busy = true;
				obj.$list.find('li').eq(obj.currentPos-2).css('display', 'block');
				obj.$list.css('left', -420);
				obj.$list.animate({left: 0}, obj.animSpeed, function(){
					obj.currentPos--;
					obj.updateAria();
					obj.$list.css('left', 0);
					obj.updateArrows();
					busy = false;
				});
			}
		});
	},
	updateAria: function(){
		var obj = this;
		this.$list.find('li').each(function(i){
			if(i == obj.currentPos-1 || i == obj.currentPos){
				$(this)
					.attr('aria-hidden', false)
					.css('display', 'block');
			}
			else{
				$(this)
					.attr('aria-hidden', true)
					.hide();
			}
		});
	},
	updateArrows: function(){
		if(this.currentPos == this.$list.find('li').length-1){
			this.$next.addClass('pillarNextDisabled');
		}
		else{
			this.$next.removeClass('pillarNextDisabled');
		}
		
		if(this.currentPos == 1){
			this.$prev.addClass('pillarPrevDisabled');
		}
		else{
			this.$prev.removeClass('pillarPrevDisabled');
		}
	}
}
function framecheck() {
	if (top != self)
	{top.location=self.location;}
}
// Debugging Code - Should always be at bottom of all code
var log;
	if (window.console && console.log) { log = console.log;	}
	else { log = function() { }; }

function p(msg) {
	log('Debug mode: ', msg);
}
// Global sims URL
var globalsimsurl = "https://www.financialplanning.expat.hsbc.com/1/2/global-simulators/grow-your-wealth?launchCommand=true&channelCountryCode=JE&channelGroupMemberId=HBIB&chnlID=OHI";
var globalsimsonclick = "window.open('https://www.financialplanning.expat.hsbc.com/1/2/global-simulators/grow-your-wealth?launchCommand=true&channelCountryCode=JE&channelGroupMemberId=HBIB&chnlID=OHI','_blank', 'status=yes,location=yes,menubar=yes,resizable=yes,scrollbars=yes,toolbar=yes'); return false;)";

// Rates urls
var ratesfilesurl = "https://www.hsbcoffshoreinteractive.com/dailyupdates/rates.js"
var fundsfileurl = "https://www.hsbcoffshoreinteractive.com/dailyupdates/fund.js"
//var ratesfileurl = "/1/PA_ES_Content_Mgmt/content/rates/rates.js"
//var fundsfileurl = "/1/PA_ES_Content_Mgmt/content/rates/fund.js"
