var productsToCompare =[]; //empty variable for passing list of products to compare to grid view
$(document).ready(function() {	
// call Carousel 
	var personalCarousel = new Carousel(true);



/* SETEQUALHEIGHTS ****/

	setEqualHeight($('.doormat > li'));

/* SEARCH FORM  *******/
	if (!Modernizr.input.placeholder){  
		var label = $('#search label').text(); 
		$('#q').attr('value', label )
		$('#q').focus(function() {
			if (($('#q').val()) == label) {
	  			$(this).attr('value','')
			}
		});
		$('#q').blur(function() {
			if($(this).val()=="") {
				$(this).attr('value', label)
			}
		});
	} else {
		$('#q').attr('placeholder', $('#q').text())
	}
	$('.search label').remove();
	
/* LOCALE **********/
	var cntryList = function(){
		var listContainer = $("#locale .dropDownLink");
		var innerList = $("#locale .dropDown");
		// Initial DropDown
		$('#locale').css("display",'block');
		listContainer.attr('aria-controls', '#localeDropDown');
		
		listContainer.toggle(function(e) {
				e.preventDefault();
				listContainer.removeClass('dropDownLink')
				listContainer.addClass('on');
				$('#locale .dropDown').fadeIn('fast', function() {}).attr('aria-hidden',false);
			},function(e) {
				e.preventDefault();
				listContainer.removeClass('on')
				listContainer.addClass('dropDownLink')
				$('#locale .dropDown').fadeOut('fast', function() {}).attr('aria-hidden',true);
			});			
	// Inner DropDown
//	$('#locale li a').click(function() {
//		
//		var thisTab = $(this);
//		var thisDropDown = $(this).next("div");
//		 
//		if (thisDropDown.length ) { // Are any tabs currently open?
//			$('.dropDown > div').slideUp('fast', function(){	// If so slide them up	
//				$('#locale a.on').after($(this)); // And once animation stops insert the div back after the currently open tab
//				if ($(thisTab).hasClass('on')) {	
//					$(thisTab).removeClass('on');	// Add class 'on' to the clicked tab	
//				} else {
//					$('#locale a.on').removeClass('on'); // Remove class 'on' from that tab
//					$(thisTab).addClass('on');
//				}
//				$(thisDropDown).insertAfter($(thisTab).parent().parent()).slideDown('fast', function() {}); // Move the menu code for the clicked tab below the list and slide it open
//			});		
//		} else {		
//			$(thisTab).addClass('on'); // Add class 'on' to the clicked tab
//			$(thisDropDown).insertAfter($(thisTab).parent().parent()).slideDown('fast', function() {}); // Move the menu code for the clicked tab below the list and slide it open			
//		}		
//	},function() {
//
//		var thisTab = $(this);	
//	
//		$(thisTab).removeClass('on'); // Remove class from this tab
//		$('.dropDown > div').slideUp('fast', function() { // Slide up any existing open menu
//			$(this).insertAfter(thisTab); // And put it back where it belongs
//			
//		});
//
//
//	});	
	
$('#locale li a#showsites').each(function(){
	var thisTab = $(this);
	var thisDropDown = $(this).next("div");
	thisTab.toggle(function() {
	


		if(thisDropDown){
			
			//$("#locale li a").after($(this)); // And once animation stops insert the div back after the currently open tab
			
			
				$(thisDropDown).prev().addClass('on');
				
				$(thisDropDown).insertAfter($(thisTab).parent().parent()).slideDown('fast', function(){
				}); // Move the menu code for the clicked tab below the list and slide it open
			
		
				}
				
	},function(){
	
		$(thisTab).removeClass('on');
		$(thisDropDown).slideUp('fast', function() { // Slide up any existing open menu	
			$(this).insertAfter(thisTab); // And put it back where it belongs
		});
		
	
	});	
		
		});	

	}
	
	cntryList();  // call function to display locale country list 
	

	
	
	
	

	var mainNav = $("#sections li");
	var doormatList = $("#sections li ul.doormat"); 
	mainNav.focusin(function(e){
		$(this).prev().find('.mainTopNav').removeClass("active");
		$(this).children().css({'left':'-162px'});
		$(this).find('.mainTopNav').addClass("active");
			
			
	});	

	doormatList.focusout(function(){
		$(this).css({'left':'-3000000px'});
	})	
		
	
	

/* PRODUCTNAV **********/
	
	$('#productNav li h2, #productNav li div.acctService').toggle(function(e){
		$(this).parent().addClass('open');
		$(this).parent().siblings().removeClass('open');
		$(this).parent().siblings().find('.dropDown').css('display', 'none').attr('aria-hidden',true);
		$(this).parent().find('.dropDown').css('display', 'block').attr('aria-hidden',false);
		e.stopPropagation();

	}, function() {
		$(this).parent().removeClass('open');
		$(this).parent().find('.dropDown').css('display', 'none').attr('aria-hidden',true);
	});
				

	$("#shareTab").click(function () {
      $("#shareThis").toggle();
	});	

	
	// hide flyout / dropdown menu when click away.
	
/* MODAL *************/

	if ($('#applyModal').length) {
		$('#applyModal').jqm();
		$('#applyModal').jqmAddTrigger('.moreButton.triggerModal');
		//Apply close link here
		$('#applyModal').append('<div id="closeModal"><span></span>Close</div>').jqmAddClose('#closeModal');
	}
	if ($('#emailModal').length) {
		$('#emailModal').jqm();
		$('#emailModal').jqmAddTrigger('.triggerModal');
		//Apply close link here
		$('#emailModal').append('<div id="closeModal"><span></span>Close</div>').jqmAddClose('#closeModal'); 	}
	
		
		
	//shadow below main nav
	$('header.shadow').after('<div class="shadow"> </div>');
	
/* TREENAV ************/

	$('#treeNav li').addClass('closed').find('ul').attr('aria-hidden',true);
	$('#treeNav li h2').toggle(function(){
		$(this).parent().removeClass('closed').addClass('open');
		$(this).parent().find('ul').attr('aria-hidden',false);
	}, function () {
		$(this).parent().removeClass('open').addClass('closed');
		$(this).parent().find('ul').attr('aria-hidden',true);
	})

// for Progress bar in IE7
	
		if ($.browser.msie && parseInt($.browser.version)==7.0) {
					$('#progress li').each(function(index){
						mainIndex = index + 1;
						$(this).prepend('<span>' + mainIndex + '.</span>');
					});
				}
	
	// Apply modal
	$('#advanceCustomersContainer').hide().removeClass("current");
    $('#nonAdvanceCustomersContainer').hide().removeClass("current");


    $('#applyToggleTabs .applyToggle').click(function(){
       
        $('#applyToggleTabs .applyToggle').removeClass("current").filter($(this)).addClass("current");

        if ($(this).attr("href") == '#advanceCustomersContainer') {
            $('#advanceCustomersContainer').show();
            $('#nonAdvanceCustomersContainer').hide();
        } else if ($(this).attr("href") == '#nonAdvanceCustomersContainer') {
            $('#advanceCustomersContainer').hide();
            $('#nonAdvanceCustomersContainer').show();
        }

        return false;
        
    });	


	// Initialise Drawer sliders
	$('#productComparisonListView section h2').drawer();
	
	// Initialise filter show/hide
	initShowHide();
	productCounter ('list');

// work out which products to show in grid view 
// TODO: Wire this up to the grid view
	$('#productComparisonListView section input[type="checkbox"]').each(function() {
		$(this).change(function(){
		productsToCompare =[]
			$('#productComparisonListView section input[type="checkbox"]').each(function(i) {
			var ischecked = $(this).attr('checked');
			if (ischecked === true){productsToCompare.push(i + 1)};
			})
			if(productsToCompare.length > 4){
				//alert('too many!');
				};
			if(productsToCompare.length === 0){
				//alert('too few!');
				};
		})
		
	})
	
	prepareTable(); //check how many products we're comparing, add remove links
	hideExtras('#productComparison tr.additionalBenefits'); // pass in css selectors of stuff you don't want to see initially
	moreLinks();
	
	//Tempoary code to stop the value -1 on productListingModule.html
	$('.productComparisonView b').html('4')	




		
});

$.fn.drawer = function(){
	return $(this).each(function(){

		// Set Components
		var dHeading = $(this);
		var dContent = dHeading.next();

		//modify markup & attributes
		dHeading.addClass('drawerHeading').html("").prepend('<span class="drawerHeadingStatus"></span>').wrapInner('<a href="#" class="drawerToggle"></a>')
		dContent.addClass('drawerContent').insertBefore(dHeading);
		$('<div class="drawerEnd"></div>').insertBefore(dHeading);
		//events
		dHeading.bind('close', function(){
				$(this).addClass('drawerHeadingClosed').find('.drawerHeadingStatus').text('Show More');							
				dContent.slideUp(function(){
					$(this).addClass('drawerContentClosed').removeAttr('style').attr('aria-hidden',true);
				});
			})
			.bind('open', function(){
				$(this).removeClass('drawerHeadingClosed').find('.drawerHeadingStatus').text('Show Less');
				dContent.slideDown(function(){
					$(this).removeClass('drawerContentClosed').removeAttr('style').attr('aria-hidden',false);
				});
			})
			.click(function(){ 
				if( $(this).is('.drawerHeadingClosed') ){
					$(this).trigger('open'); 
				}	
				else {
					$(this).trigger('close'); 
				}
				return false;
			})
			.trigger('close');
	});	
};


function setEqualHeight(columns){
	 var tallestcolumn = 0;
	 columns.each(function(){
		 currentHeight = $(this).height();
			 if(currentHeight > tallestcolumn)
			 {
			 tallestcolumn  = currentHeight;
			 }
	 });
	 columns.height(tallestcolumn);
 }
 

// Carousel
function Carousel(auto) {
	
	var autoScroll = auto || false; 
	var autoScrollDelay = 10; 
	var scrollTimer;												// setInterval handle
	var totalCarouselItems = $('#carouselTabs').children().length;	
	var currentIndex = 1;											// ID of first item
	var newIndex = 1;													
	var scrollStep;													
	var scrollByWidth = 984; 										// width of each carousel item									
	var scrollSpeed = 0.5;											// duration in seconds
	var easingAnimation = "swing"; 									// 'swing' or 'linear' animation
	var animationComplete = true;
	
	this.Carousel = function() {
		
		setEventHandlers();
		
		// use global function to set carousel tabs to same height
		setEqualHeight($('#carouselTabs a'));
		
		if(autoScroll) {
			scrollTimer = setInterval(doAutoScroll, autoScrollDelay * 1000);	
		}
		
    }
	

	function setEventHandlers() {
		$('#carouselTabs a').click(function() {
	
			//stop autoscroll
			stopAutoScroll();
					
			if(animationComplete) {
				itemId = $(this).attr('id');
				newIndex = itemId.split('-')[1];
				
				// remove show class from all articles
				$('#carouselTabs a').removeClass("current").attr('aria-hidden','true');
				$('#carouselTabs li').removeClass("current");
				
				// add class to selected article
				$(this).addClass("current").attr('aria-hidden','false');
				$(this).parent().addClass("current");
	
				if (newIndex > currentIndex) {
					scrollDirection = -1;
					scrollStep = newIndex - currentIndex;
				}
				if (newIndex < currentIndex) {
					scrollDirection = 1;
					scrollStep = currentIndex - newIndex;
				}
					
				if(newIndex != currentIndex) {
					doScroll(scrollDirection, scrollStep, newIndex);	
				}
				
			}
			return false;
		});
	}
	
			
	function doScroll(scrollDirection, scrollStep, newIndex) {		
		animationComplete = false;
		
		currentIndex = newIndex;
			
		// remove show class from all articles
		$('#carouselTabs a').removeClass("current").attr('aria-hidden','true');
		$('#carouselTabs li').removeClass("current");
		
		// add class to selected article
		$('#carouselTabs a').eq(currentIndex-1).addClass("current").attr('aria-hidden','false');
		$('#carouselTabs a').eq(currentIndex-1).parent().addClass("current");
		
		$('#carouselArticles').animate({
			left: '+=' + (scrollByWidth * scrollDirection * scrollStep) + "px"
		}, scrollSpeed * 1000, easingAnimation, function() {
			animationComplete = true;
		});
	}
	
	
	function doAutoScroll() {		
		if(animationComplete) {
			
			newIndex = newIndex + 1;	
			
			// when the carousel reaches the last item, scroll back to first carousel item. 
			// On initial load scroll up by one step at a time through the carousel items.
			if(newIndex == totalCarouselItems + 1) {
				newIndex = 1;
				doScroll(1, totalCarouselItems - 1, newIndex);
			} else {
				doScroll(-1, 1, newIndex);
			}
			
		}
	}
	
	
	function stopAutoScroll() {
		clearInterval(scrollTimer);
	}
	
	this.Carousel();
}






// Display All Show/Hide Items on Page when JS enabled
function initShowHide() {
	$('.showhideLink').removeClass("jsDisabled"); /* change with code to work with "no-js" class */
	$('.showhideLink').next().hide().addClass("hidden");
	$('.showhideLink').click(function() {
		if( $(this).next('div').hasClass("hidden")) {
			$(this).next('div').show().removeClass("hidden");
			$(this).addClass("expanded");
		} else {
			$(this).next('div').hide().addClass("hidden");
			$(this).removeClass("expanded");
		}
		return false;
	});
}


function productCounter (view){

	var numberOfProducts;
	var view = view;
	if (view == 'list'){
		numberOfProducts = $('#productComparisonListView section').length;
		$('ul li a b').html(numberOfProducts);
		return false;
	}
		if (view == 'grid'){
		numberOfProducts = $('#productComparison tr:first-child td').not(':hidden').length -1;
		$('ul li a b').html(numberOfProducts);
		return false;
	}
}

function prepareTable(){
	var numberOfProducts = $('#productComparison tr:first-child td').not(':hidden').length -1;
	var totalColumns = parseInt(numberOfProducts) + 1;
	$('ul li a b').text(numberOfProducts);
	var containerwidth = $('#productComparison').parent().width();
	//var columnWidth = (containerwidth - 130 / numberOfProducts) - 40; //hmmmm.... see note
	var columnWidth = containerwidth - 130;
	var getColumnWidth = (columnWidth / numberOfProducts) - 40;
	productCounter ('grid');
	// column width = parent width minus 130 (row headings) divided by number of products minus left + right padding
	// need to make parameter driven & or dynamic??
	
	$('#productComparison tr:first-child td').attr('width',getColumnWidth);
	$('#productComparison tr.sectionType th:first-child').attr('colspan', totalColumns);
	$('#productComparison a.remove').remove();
	$('#productComparison td:empty').text('--');
	$('#productComparison td:first-child').attr('class','').text('').attr('width','130');
	if (parseInt(numberOfProducts) >1) {
		//	$('#productComparison tr:first-child td h2').append('<a href="#productComparisonTools" class="remove" title="Remove this product from the comparison table">remove product</a>');
		
		$('#productComparison tr:first-child td h2').append('<a href="#productComparisonTools" class="remove" title="Remove this product from the comparison table">remove product</a>');
		
		/* disabled
$('#productComparison tr:first-child td h2 a.remove').each(function(i) {
      	$(this).click(function(){
		  	removeProduct(i + 2);  
			return false;
		});
		});
*/

	}
		zebra();
		$('#productComparison td').hover(function(){
			$(this).parent('tr').addClass('hover');
			},
			function(){
				$(this).parent('tr').removeClass('hover');});

	return false;
}



function removeProduct(i) {
	$('#productComparison tr td:nth-child(' + i + ')').hide().attr('data-hidden','true');
	//	remove these lines and replace with those below if required	
			prepareTable();
			return false;

		}

function hideExtras(hideThis){
	//when the page loads hide the extra info
	$(hideThis).hide();
	$(hideThis).prev('tr.sectionType').addClass('closed');
	$('.drop-message').text('Show all benefits');
	$(hideThis).prev('tr.sectionType').click(function(){
		
		if($(hideThis).is(':visible')) {
			$(hideThis).fadeOut('slow');
			$(hideThis).prev('tr.sectionType').addClass('closed');
			$('.drop-message').text('Show all benefits');
		}
		else {
			$(hideThis).fadeIn('slow');
			$(hideThis).prev('tr.sectionType').removeClass('closed');
			$('.drop-message').text('Hide all benefits');
		}
	});
}

function moreLinks(){
	$('#productComparison tr a.more').next('p').hide();
	$('#productComparison tr a.more').click(function(){
		$(this).toggleClass('open').next('p').slideToggle();
		return false;
	})
}
function zebra (){
	$('#productComparison tr').find('th:even,td:even').attr('class','even');
	$('#productComparison tr').find('th:odd,td:odd').attr('class','odd');
	$('#productComparison tr').find('td:first-child, th:first-child').attr('class','');
}
