var isMSIE6;
var currentCarousel1;
var currentCarousel2;
// Document ready start here
jQuery(document).ready(function() {
	//if(jQuery('.shareBox .linksBox ul li').length)shareshowHide();
	if(jQuery('.commonTopicsWideCol').length)relatedTopicsExpandCollapse();
	if(jQuery('.widerColtoolList .colInnerContent .rows').length)setTimeout('calculatorShowHide()', 1000);
	if(jQuery('.smallerColtoolList .colInnerContent .rows').length)setTimeout('toolsShowHide()', 1000);
	if(jQuery('.goalPlannerList .colInnerContent .rows').length)goalPlannerList();
	if(jQuery('.carouselContainer .hmCarousel').length) currentCarousel1 = setTimeout('carosuelLoadv1()' , 3000);
	if(jQuery('.carouselContainerv2 .hmCarousel2').length) currentCarousel2 = setTimeout('carosuelLoadv2()' , 3000);
	if(jQuery('.colInnerContent .rowsToolsList').length) toolList = setTimeout('showHideToolList()' , 3000);
	if (jQuery(".addthis_toolbox li").length) reloadaddThis1();
	if (jQuery(".benHide").length) quitBens();
	if (jQuery(".Carousel").length) setTimeout('carosuelShowhide()', 1000);
	if (jQuery("#enhancedHero").length) enhancedHero();
	if (jQuery("ul.hmPagination").length) loadHero();
	if(jQuery(".enhancedHome .hmCarousel3").length) loadCarousel();
	if (jQuery(".showHideParent").showHideLists());
	if (jQuery(".Carousel").length) setTimeout('prevNextCarousel()', 1000);
});

// --- Show/Hide function for tools list
function showHideToolList(){
	_whatRow = '.colInnerContent .rowsToolsList';
	var totalList = $(_whatRow).length;
	if(totalList >= 1){
		jQuery('.colInnerContent p.showHide').show();
	}
	$(_whatRow).addClass('hidden');
	$(_whatRow+':first').removeClass('hidden');
	$('.colInnerContent p.showHide a').click(function(e){
		e.preventDefault();
		var currentShowHideText = $.trim($(this).text());
		if(currentShowHideText == 'Show all'){
			jQuery(this).text('Collapse');
			jQuery(this).removeClass('expand');
			jQuery(this).addClass('collapse');
			jQuery(_whatRow).removeClass('hidden');
		}else if(currentShowHideText == 'Collapse'){
			jQuery(this).text('Show all');
			jQuery(this).removeClass('collapse');
			jQuery(this).addClass('expand');
			jQuery(_whatRow).addClass('hidden');
			jQuery(_whatRow+':first').removeClass('hidden');
		}
	});
}

// --- Global Show/Hide function for all show links
function globalShowAll(targetLinks,targetObj){
		jQuery(targetLinks).click(function(e){
		e.preventDefault();
		if ( jQuery(this).hasClass('collapse'))
			{
				jQuery(this).removeClass("collapse").addClass('expand');
				jQuery(targetObj).toggleClass('visible');
				jQuery(this).text('Show all');
			}
			else {			
				jQuery(this).removeClass("expand").addClass("collapse");
				jQuery(targetObj).toggleClass('visible');
				jQuery(this).text('Collapse');
			}        
		});
}

// --- M102-R3 Module ToolList V1 show/hide function

function calculatorShowHide(){
  jQuery('.widerColtoolList').each(function() {
  var rowList=jQuery(this).find('.rows');
  var rowsCount=jQuery(rowList).length;
  var targetLinks=jQuery(this).find("a.showLink");
  var parentlinkItem=jQuery(this).find('.showHide');
  var defaultrowCount=0;
  if(rowsCount<=2){
   jQuery(parentlinkItem).css('display','none');
  }
  else{
   jQuery(parentlinkItem).css('display','block');
   globalShowAll(targetLinks,rowList)
   jQuery(rowList).each(function(){
		 if(defaultrowCount>1){
		  jQuery(rowList).eq(defaultrowCount).addClass('hidden');
		 }
		 defaultrowCount++
	 });
	}
});
}

// --- M102-R3 Module ToolList V2 show/hide function
function goalPlannerList(){
	var goalList=jQuery('.goalPlannerList .colInnerContent .rows');
	var goalrowsCount=jQuery(goalList).length;
	var targetLinks=jQuery(".goalPlannerList a.showLink");
	var parentlinkItem=jQuery('.goalPlannerList .colInnerContent .showHide');
	var defaultrowCount=0;
	if(goalrowsCount<=2){
		jQuery(parentlinkItem).css('display','none');
	}
	else{
		jQuery(parentlinkItem).css('display','block');
		globalShowAll(targetLinks,goalList)
		jQuery(goalList).each(function(){
				if(defaultrowCount>1){
					jQuery(goalList).eq(defaultrowCount).addClass('hidden');
				}
				defaultrowCount++
		});
	}
}
// --- M102-R3 Module tool list show/hide function
function toolsShowHide(){
	jQuery('.smallerColtoolList').each(function(){
	var toolList=jQuery(this).find('.rows');
	var toolsrowsCount=jQuery(toolList).length;
	var targetLinks=jQuery(this).find("a.showLink");
	var parentlinkItem=jQuery(this).find('.showHide');
	var defaultrowCount=0;
	if(toolsrowsCount<=1){
		jQuery(parentlinkItem).css('display','none');
	}
	else{
		jQuery(parentlinkItem).css('display','block');
		globalShowAll(targetLinks,toolList)
		jQuery(toolList).each(function(){
				if(defaultrowCount>0){
					jQuery(toolList).eq(defaultrowCount).addClass('hidden');
				}
				defaultrowCount++
			});
	}
	});
}
var counter=0;
//Home page Carousel
//sorgalla.com/jcarousel/
function carousel_initCallback(carousel) {

		var getContainerId=carousel.options.id;
		var numScollsItem =parseInt(carousel.options.scroll);
		var getcarouselPagination=$(".hmPagination:eq("+counter+")");
        //carousel.options.scroll = jQuery.jcarousel.intval(numScollsItem);
		
jQuery(getcarouselPagination).text("");

        var noLi = $(getContainerId+":eq("+counter+")").find('li').length;
        var requiredLi = Math.ceil(noLi / numScollsItem);
        for (var i = 0; i < requiredLi; i++) {
            var count = i + 1;
            var liSrting = "<li>" + count + "</li>";
            jQuery(getcarouselPagination).append(liSrting);
        }
        if (noLi <= numScollsItem) {
            jQuery(getcarouselPagination).hide();
        }
        else {
            jQuery(getcarouselPagination).show();
        }
        jQuery(getcarouselPagination).children(":first").addClass("selected");
        
        $(".hmPagination:eq("+counter+") li").each(function() {
            jQuery(this).bind("click", function() {
               // $(".hmPagination:eq("+counter+") li").removeClass("selected");
		 jQuery(this).parents(".hmPagination").children("li").removeClass("selected");

                jQuery(this).addClass("selected");
                var noClick = parseInt(jQuery(this).text());
	            var remain = noLi % numScollsItem;
	            if (jQuery(this).text() == "1") {
                    carousel.scroll(jQuery.jcarousel.intval(1))
                }
                if (remain == 0) {
                    var ulLi = jQuery("ul.pagination li").length
                    var scrollNo = ((noClick - 1) * numScollsItem) + 1
                    carousel.scroll(jQuery.jcarousel.intval(scrollNo))
                } else {
                    var scrollNo = ((noClick - 1) * numScollsItem) + 1
                    carousel.scroll(jQuery.jcarousel.intval(scrollNo))
                }
            })
        });
counter++;   
 }
function prevNextCarousel(){
	jQuery(".jcarousel-next").click(function() {

	     jQuery(this).parents(".Carousel").find(".hmPagination").find("li.selected").next().addClass("selected");
            jQuery(this).parents(".Carousel").find(".hmPagination").find("li.selected:last").prev().removeClass("selected");
        });
        jQuery(".jcarousel-prev").click(function() {
	 	 jQuery(this).parents(".Carousel").find(".hmPagination").find("li.selected:last").prev().addClass("selected");
               jQuery(this).parents(".Carousel").find(".hmPagination").find("li.selected").next().removeClass("selected")

        });
}
//directory template Carousel
function carosuelLoadv1(){
	if($('.hmCarousel li').size() > 6){
		jQuery(".carouselContent .showHide").show();
		var hmCarousel = ".hmCarousel";
	    	if (jQuery(hmCarousel)){
              	jQuery(hmCarousel).jcarousel({
 				scroll: 6,
				id:".hmCarousel",
	            		initCallback: carousel_initCallback
	        	});
			var getWidth = jQuery(hmCarousel).width();
	        var setWidth = getWidth + 200;
	        jQuery(hmCarousel).width(setWidth);
			// set height of <a> to be equal - if more than one line length
			$('.hmCarousel > li > a').equalHeight();
		}
    } else {
		jQuery('.carouselContent p.showHide').remove();
		jQuery('.hmCarousel > li > a').equalHeight();
	}
window.clearTimeout(currentCarousel1);
}

// hub template carousel
function carosuelLoadv2(){
	if($('.hmCarousel2 li').size() > 5){
		jQuery(".carouselContent .showHide").show();
	    var hmCarousel2 = ".hmCarousel2";
	    if (jQuery(hmCarousel2)){
	        jQuery(hmCarousel2).jcarousel({
	            scroll: 5,
				id:".hmCarousel2",
	            initCallback: carousel_initCallback
	        });
	        var getWidth = jQuery(hmCarousel2).width();
	        var setWidth = getWidth + 200;
	        jQuery(hmCarousel2).width(setWidth);
			// set height of <a> to be equal - if more than one line length
			$('.hmCarousel2 > li > a').equalHeight();
	    }
	}
	else {
		jQuery('.carouselContent p.showHide').remove();
		jQuery('.hmCarousel2 > li > a').equalHeight();
	}
window.clearTimeout(currentCarousel2);	
}

function reloadaddThis1(){
    var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
	var addthis_brand = "Bupa.co.uk";
	var addthis_header_color = "#0099ff";
    jQuery.getScript(script);
}

function quitBens() {
	jQuery(".benHide").hide();
	jQuery(".timeQuitBenefits").click(function() {
		jQuery(this).next().toggle();
	});
}
// --- collapse/expand for common topic module show all links
function relatedTopicsExpandCollapse(){
	if(jQuery(".listContentCollapsed").length){
		jQuery(".listContentCollapsed").removeClass("hide");
	}
	if(jQuery(".listContentExpand").length){
		jQuery(".listContentExpand").addClass("hide");
	}
	jQuery(".commonTopicsWideCol p.showHide").css('display','block');
	jQuery(".commonTopicsWideCol p.showHide a").click(function(){
			var currentStatus = jQuery(this).attr("class");	
			if(currentStatus == "expand"){
				 jQuery(this).attr("class","collapse");
				 jQuery(".listContentCollapsed").addClass("hide");
				 jQuery(".listContentExpand").removeClass("hide");
				 jQuery(".commonTopicsWideCol p.showHide a").text("Collapse");

			}
			else{
				 jQuery(this).attr("class","expand");
				 jQuery(".listContentCollapsed").removeClass("hide");
				 jQuery(".listContentExpand").addClass("hide");
				 jQuery(".commonTopicsWideCol p.showHide a").text("Show all");
			}
				 return false;
	   });
}

function carosuelShowhide(){
	jQuery(".carouselContent .showHide").show();
     
	jQuery(".carouselContent .showHide a").click(function(e){
		var elmid=($(this).attr("id"));
              e.preventDefault();
		var targetElm=jQuery(e.target);
             	var targetedElem=jQuery(targetElm).parents().parent().find("div#Carousel"+elmid);
		if(jQuery(targetElm).hasClass("expand")){
			 jQuery(targetedElem).find(".jcarousel-skin-tango").before("<div class='expandedCarousel'><ul></ul></div>");
			 jQuery(targetedElem).find(".jcarousel-skin-tango li").each(function(){
				 var elementLi=jQuery(this).html();
				 jQuery(targetedElem).find(".expandedCarousel ul").append("<li>"+elementLi+"</li>");
			 });
			 jQuery(targetedElem).find(".jcarousel-skin-tango").hide();
			 jQuery(targetedElem).find("ul.hmPagination").hide();
			 jQuery(e.target).removeClass("expand").addClass("collapse")
			 jQuery(e.target).html("Collapse");
	 
		}
		 else{
		 // jQuery(targetElm).parents().parent().find("div.expandedCarousel").remove();
			jQuery(this).parents(".carouselContent").find(".expandedCarousel").remove();

		   jQuery(targetedElem).find(".jcarousel-skin-tango").show();
		   jQuery(targetedElem).find("ul.hmPagination").show();
		   jQuery(e.target).removeClass("collapse").addClass("expand")
		   jQuery(e.target).html("Show all");
	   
			}
	});
 }
 
/* equal height plug-in that checkes height of objects 
   sent to it and returns all objects with the largest height in px */
jQuery.fn.equalHeight = function()
{
	var maxSize = 0;
	
	// iterate over each object and get tallest size
	this.each(function()
 	{
		var currentSize = $(this).height();
		if( currentSize > maxSize)
		{
			maxSize = currentSize;
		}
	});

	// return the objects with the height set to the same size
	return $(this).height(maxSize);
};
/* Start - M150 Enhanced hero module */
function enhancedHero() {
	/* Variables for enhanced hero module */
	var menuItem = jQuery('ul#enhancedHeroMenu li span');
	var numLi = jQuery('ul#enhancedHeroMenu li').length;
	var tabNum;
	var horzBgPosition, vertBgPosition, bgPosition = '';
	
	/* Dynamically create the dot navigation by duplicating the main menu */
	var bulletMenu = jQuery('#enhancedHeroMenu').clone();
	bulletMenu.removeAttr('id');
	bulletMenu.attr('class','hmPagination');
	bulletMenu.insertAfter('#enhancedHeroMenu');
	bulletMenu.wrapAll('<div class="bulletHolder" />');
	bulletMenu.removeAttr('style');
	bulletMenu.show();

	/* Choose correct size for the li's */
	var divHeight = jQuery('#enhancedHero').height();
	// -30 is to allow for bullets at bottom
	var numLiHeight = (divHeight-30) / numLi;
	menuItem.css('height',numLiHeight);
	
	/* set position of background arrows dynamically as we don't now the height,
	   and IE6, IE7 will not centre correctly. */
	menuItem.enhancedHeroMenu();
}

	/* set the padding top of the a's so that they centre in li's */
	/* set each a's height */
	jQuery.fn.enhancedHeroMenu = function()
	{	
		this.each(function() {
			var aHeight = jQuery('a',this).height();
			var spanHeight = jQuery(this).height();
			/* height of 'span' minus height of 'a' divided by 2 */
			var padding = ((spanHeight - aHeight)/2);
			jQuery('a',this).css('paddingTop',padding);
			
			/* set background position of arrow based on dynamic position */
			vertBgPosition = ((Math.floor(aHeight/2)-8) + padding) + 'px';
			/* check if selected arrow, to set horizontal position */
			if(jQuery(this).parent().hasClass('selected')){
				horzBgPosition = '-29px';
			} else {
				horzBgPosition = '160px';
			}
			/* now set arrow position */
			bgPosition = horzBgPosition + ' ' + vertBgPosition;
			jQuery('a',this).css('backgroundPosition',bgPosition);
		});
	};

/* function to handle ajax and update the menus */
function loadHero(){
	var spinner = '<img id="spinner" src="/bupastatic/images/spinner.gif" />';
	
	// check both menus for click and update both
	jQuery('.menuHolder').live('click', function(event) {
		event.preventDefault();
	
		/* check the user is clicking on either the bullets or links */
		if((event.target.nodeName == 'A') || (event.target.nodeName == 'LI'))
		{
			var $enhancedMenu = jQuery('#enhancedHeroMenu li',this);
			var $enhancedBullets = jQuery('.hmPagination li',this);
			
			/* remove  selected class on both menus */
			$enhancedMenu.removeClass('selected');
			$enhancedBullets.removeClass('selected');
	
			/* check which menu has been clicked, and update selected */
				var $target = $(event.target);
				var indexNo = 0;
				
			/* grab what the href of the event - needed for ajax call
			   Get href from tab */
			var targetHref = $(event.target).attr('href');
			
			/* Get from bullet */
			if(targetHref == undefined) {
				targetHref = $('>span>a',$target).attr('href');
			}
			
			/* index needed for demo links only */
			if($target.parent('span').length > 0)
			{
				/* main menu - find index num of li */
				indexNo = $target.parent().parent().index();
			} else {
				/* bullets - find index num of li */
				indexNo = $target.index();
			}
	
			/* add the selected class onto both menus */
			jQuery('ul li',this).each(function() {
				if(jQuery(this).index() == indexNo)
				{
					jQuery(this).addClass('selected');
					jQuery('ul#enhancedHeroMenu li span').enhancedHeroMenu();
				}
			});
			
			/* set demo to 'false' for production use,
			   set demo to 'video' for M150 static video variants
			   set demo to 'css' for M150 static variants */
			var demo = 'false';
			
			switch (demo) {
				case 'css':
					// ONLY FOR TESTING STATIC M150
					var ajaxHref = '/jahiaPrototype/includes/heroTabs/hero' + (indexNo + 1) + '.html';
					break;
				case 'video':
					// ONLY FOR TESTING STATIC VIDEO M150
					var ajaxHref = '/jahiaPrototype/includes/heroTabs/videoHero' + (indexNo + 1) + '.html';
					break;
				default:
					// ONLY FOR PRODUCTION
					var url = window.location.pathname;
					var ajaxHref = url + targetHref + '&ajaxHero=true';
			}
	
			/* Ajax to remove existing tab content */
			jQuery('.ajaxHeroContainer').fadeOut('slow', function()
			{
				jQuery('#enhancedHero').append(spinner);
				jQuery('.enhancedHeroContainer').remove();
				$.ajax({
					url: ajaxHref,
					success: function(data) {
						$('.ajaxHeroContainer').empty().append(data).fadeIn('slow');
						jQuery('#spinner').remove();
					}
				});
			});
		}; 
	});
	
	
	$('.videoOverlay a').live('click',function(e) 
	{
		var videoLink = $(this).attr('href');
		videoLink += '&videoOverlay=true';
		e.preventDefault();
		videoOverlay(videoLink);
	});
}
/* End - M150 Enhanced hero module */

/* M160 - Guides and advice */
function loadCarousel() {
	var i = 1;
	/* Hide the scroll bars for the non-JS version */
	jQuery(".hmCarousel3").parent().css("overflow-x","hidden");
	jQuery(".hmCarousel3").each(function() {
		/* Create a unique class for each carousel on the page */
		var carouselClass = 'carousel'+i;
		jQuery(this).addClass(carouselClass);

		/* Initalise the carousel scroll function */
		jQuery('.'+carouselClass).jcarousel({
			scroll: 3,
			id: carouselClass,
			itemLastInCallback: {
				onAfterAnimation: itemsVisible
			},
			initCallback: carouselPagination
		});
		i++
	});
}

function carouselPagination(carousel) {
	/* Create the pagination */
	var carouselId = carousel.options.id;
	/* Add pagination ul into the great grand parent of the carousel */
	jQuery('.'+carouselId).parent().parent().parent().append('<ul class="hmPagination3" id="pag'+carouselId+'"></ul>');
	/* Find out the number of bullets needed */
	var numScrollItems = carousel.options.scroll;
	var numItems = jQuery('.'+carouselId+' li').length;
	var numScroll = numItems / numScrollItems;
	/* Round the number of bullets up if not whole number */
	numScroll = Math.ceil(numScroll);
	/* Create the bullets */
	if (numItems > numScrollItems) {
		for (var i = 1; i <= numScroll; i++) {
			jQuery('#pag'+carouselId).append('<li>'+i+'</li>').show();
		}
	} 
	
	/* Automatically selected the first bullet*/
    jQuery('#pag'+carouselId).children(":first").addClass("selected");
	/*Click next arrow*/
	jQuery('.'+carouselId).parent().parent().find('.jcarousel-next').click(function() {
		jQuery('#pag'+carouselId).find("li.selected").next().addClass("selected");
		jQuery('#pag'+carouselId).find("li.selected:last").prev().removeClass("selected");
	})
	/*Click previous arrow*/
	jQuery('.'+carouselId).parent().parent().find('.jcarousel-prev').click(function() {
		jQuery('#pag'+carouselId).find("li.selected:last").prev().addClass("selected");
		jQuery(".hmPagination3 li.selected").next().removeClass("selected")			
	})
	/* Clicking on the pagination */
	jQuery('#pag'+carouselId+' li').each(function() {
		jQuery(this).bind("click", function() {
			jQuery('#pag'+carouselId+' li').removeClass('selected');
			jQuery(this).addClass('selected');				
			var noClick = parseInt(jQuery(this).text());
			var remain = numItems % numScrollItems;
			if (jQuery(this).text() == "1") {
				carousel.scroll(jQuery.jcarousel.intval(1))	
			}
			if (remain == 0) {			
				var scrollNo = ((noClick - 1) * numScrollItems) + 1
				carousel.scroll(jQuery.jcarousel.intval(scrollNo))
			} else {
				var scrollNo = ((noClick - 1) * numScrollItems) + 1
				carousel.scroll(jQuery.jcarousel.intval(scrollNo))
			}
		});
	});
}

/* Video overlay */
function videoOverlay(videoLink) {
	 $.fn.colorbox({
		href: videoLink,
		transistion:"none",
		rel:"nofollow",
		title:true,
		scrolling:true,
		close:"Close this window",
		onComplete:function(){
			
			var flashHeight = 0;
			if ($('object',this).length){
				flashHeight = $('object',this).height()+120;
			}
			if ($('embed',this).length){
				flashHeight = $('embed',this).height()+120;
			}
			$.colorbox.resize({height: flashHeight});
		}
	});
}

/* Implememt counter for M160 */
function itemsVisible(carousel, item, idx, state) {
	var carouselClass = carousel.options.id;
	var noLi = jQuery('.'+carouselClass+' li').length;
	if(noLi < 3) {
		return;
	} else {
		jQuery('.'+carouselClass).parent().parent().parent().find('.counter').empty().html('<p>'+(idx-2)+' - '+(idx) +' / '+ noLi+'</p>');
	}
}

jQuery.fn.showHideLists = function()
{
	jQuery(this).each(function()
	{
		var hiddenElements = jQuery(this).children('li:gt(0)').hide();
		// choose text for the show/hide link
		var showText="Show all numbers";
		var hideText="Hide all numbers";
		
		if (hiddenElements.size() > 0)
		{
			jQuery(this).each(function()
			{
				jQuery(this).children('li:gt(0)').hide();
				jQuery(this).after("<a href='#' class='showhidden'>"+showText+"</a>");
			});
		}; 
		//GRP 20.0 CMS Release: (HPOV call - 736819) - Web Tech Support Team: 28/09/2011 Start
		jQuery(this).next("a.showhidden").click(function(e)
		//GRP 20.0 CMS Release: (HPOV call - 736819) - Web Tech Support Team: 28/09/2011 End
		{
			e.preventDefault();
			jQuery(this).prev('ul').children('li:gt(0)').toggle();
		  
		// change the link text	
			if (jQuery(this).text()==showText)
			{
				jQuery(this).text(hideText);
			} else {
				jQuery(this).text(showText);
			}
		});
	});
	
	/* add class to force ie to redraw to remove redraw 
	   bugs seen in containers that have carousels  */
	jQuery('.panelSet').addClass('ieFix');
};


