var Share =  Share || {};
Share.flash_url = '';
Share.twitter_to_format_url = '';

$(document).ready( function () {

/*External links with REL*/    
    $("a[rel='external']").live('click', function(e) {
		if (!$(this).parent().hasClass('favorites')) {
	        e.preventDefault();
	        window.open($(this).attr('href'));
		}
    });

   /*clone the share twitter link so that can later one can be apply changes if the user click on tyre selector*/
  Share.twitter_to_format_url =  $("div#share-bar li.share-twitter a.share-social").attr("href");
  /*form submit*/
  $.ajaxSetup({
	contentType: 'application/x-www-form-urlencoded; charset="UTF-8"'
	
  });
  
  /*homepage show / hide */
  
  $('.hero a.toggle-show').click(function(e){				
		e.preventDefault();
		$('.expand-content').show();
		$('.hero a.toggle-show').addClass('select');
		$('.hero a.toggle-hide').removeClass('select');
	});
  
  $('.hero a.toggle-hide').click(function(e){				
		e.preventDefault();
		$('.expand-content').hide();
		$('.hero a.toggle-hide').addClass('select');
		$('.hero a.toggle-show').removeClass('select');
	});
  
  
  /*prevent the Tyre widget from displaying until it is in position*/
  
  $(window).load(function(){
	  $('.campaign-flash .right-widget').css('visibility','visible');
  });
  

/*Tooltip*/
	/*Select all anchor tag with rel set to tooltip*/
	$('.basic-sel-tooltip, p.filters-active span, div.balloon, .WASarticles-list .bubble, a[rel=tooltip], a.tooltip, span.tooltip')
		.live('mouseover mousemove mouseout', function(e){
			if (e.type == 'mouseover') {
				var tip = $(this).attr('title');
				$(this).attr('title', '');
				$('img', this).attr('alt', '');
				if (!$(this).hasClass('tooltip')) {
					$(this).css('cursor','help');
				}
				
				$('body').append('<div id="tooltip"><span class="tooltip-top"><span class="tooltip-left"></span><span class="tooltip-right"></span></span><div class="tooltip-content"><span class="tooltip-left"></span><span class="tooltip-right"></span><span class="tooltip-holder">' + tip + '</span></div><span class="tooltip-bottom"><span class="tooltip-left"></span><span class="tooltip-right"></span></span></div>');
				if ($.browser.msie) {
					$('#tooltip').show();
				}
				else {
					$('#tooltip').delay(100).fadeTo('10', 0.9);
				}
			}
			else 
				if (e.type == 'mousemove') {
					$('#tooltip').css('top', e.pageY + 20);
					if ((e.pageX + 40 + $('#tooltip').width()) > $('body').width()) {
						$('#tooltip').css('left', e.pageX - 10 - $('#tooltip').width());
					}
					else {
						$('#tooltip').css('left', e.pageX + 20);
					}
				}
				else {
					$(this).attr('title', $('.tooltip-holder').html());
					$('div#tooltip').remove();
				}
		});

    /*play any embeded movie in an article*/
    $("div.article-video a[rel^='mediatrigger']").prettyPopin({
			width:737,
			height:420
    });
    
    /*add the play button overlay*/
    $.each($("div.article-video a[rel^='mediatrigger'] img"),function(index,elem){
        $(this).after('<span class="video" />');
    });
    
    /*fading effects on mouseover*/
    $('div.article-video img, div.richtext-media img').mouseenter( function() {
			$(this).stop(true,true).fadeTo('fast', 0.5);			
        }).mouseleave( function() {
			$(this).fadeTo('fast', 1);			
    });



	
/*Lightbox - pretty popin Country Selector*/
	$("a.country-selector").prettyPopin({
		width:935, 
		height:365,
        title: $("a.country-selector").attr('title')
	});
	
/*Lightbox - pretty popin Tyre Reader*/ 
	$("a.tyreReader, a#tyreReader").prettyPopin({
		width:895,
		height:545,
		title: $("a#tyreReader").attr('title')
	});
	$('#tyre-select-info a').prettyPopin({
		width:895,
		height:545,
		title: $('#tyre-select-info a').attr('title')
	});
	
/*Lightbox - pretty popin Email form*/
	$("a.share-popin").prettyPopin({
		width:450,
		height:347,
        title: $(".share-popin").attr('title')
	});
	
	/*Lightbox - pretty popin partners form*/
	$("a.media-image").prettyPopin({
		width:600,
		height:400,
        title: $(".media-image").attr('title'),
		type:'image'
	});
	

/*Lightbox - Pretty popin Tyre Large Image*/
	$('.tyre-lightbox a').prettyPopin({
		width:520, 
		height:540,
        title:$('.tyre-lightbox a').attr('title'),
        type:'image'
	});
	
/*Lightbox - Thumbnail Image*/
	$("div[class^='richtext-image'] a[rel^='mediatrigger']").each(function(){
		var width = parseInt($(this).attr('mwidth'));
		var height = parseInt($(this).attr('mheight'));
		width = width?width:520;
		height = height?height:540;
		$(this).prettyPopin({
			width: width,
			height: height,        
	        type:'image'
		});
	});



/*Lightbox - Thumbnail Media*/
	$("div[class^='richtext-media'] a[rel^='mediatrigger']").each(function(){
		$(this).append('<span class="video"></span>');	
	})		
	$("div[class^='richtext-media'] a[rel^='mediatrigger']").prettyPopin({
		width:737,
		height:420
	});


	
 /*Pagination*/
	if ($('#pagify li').length > 5) {
		var paginationStart = 0;
		var paginationEnd = 0;
		$('#pagify li').each( function(i) {
			if ($(this).hasClass('selected')) {
				paginationStart = i;
			} 
			paginationEnd = i;
		})	/*Find the current class*/
		
		if (($('#pagify li').length % 5) != 0 ) {
			for (i=0;i<=($('#pagify li').length % 5);i++) {
	            $('#pagify ul').append('<li class="blank"></li>');
	        }
		} /*If the results are not a multiple of 5 add some extra li's to the list*/
		
		if ((paginationStart % 5) != 0 ) {
			for (i=0;i<=(paginationStart % 5);i++) {
	            paginationStart++;
	        }
			paginationStart = paginationStart - 5;
		} /*make sure the pagination starts with the current selected item*/
		
		if ((paginationEnd % 5) != 0 ) {
			for (i=0;i<=(paginationEnd % 5);i++) {
	            paginationEnd++;
	        }
			paginationEnd = paginationEnd - 5;
		} /*calculate the number of items to the last full set*/
		
		$(window).load( function() {
	        $('.pagination-holder').prepend("<div class='pagination-prev'><a href='' class='pagination-small-prev disabled'>prev</a></div>")
			$('.pagination-holder').append("<div class='pagination-next'><a href='' class='pagination-small-next'>next</a></div>")
			
			if (paginationStart >= 1) {
				$('a.pagination-small-prev').removeClass('disabled');
			} /*if the current pagination view isn't the first one, then remove the disabled class
*/			
			if (paginationEnd == paginationStart) {
				$('a.pagination-small-next').addClass('disabled');
			} /*if current pagination view is the last one, remove the arrow right*/
			
			$('#pagify')
				.jCarouselLite({
	                btnNext: '.pagination-small-next',
	                btnPrev: '.pagination-small-prev',
					scroll: 5,
	                visible: 5,
					start: paginationStart,
	                circular: false
	            });
		});
	}
		
	$('a.disabled').live('click', function(e) {
		e.preventDefault();
	});

/*Media Gallery*/
	/*Small Version (Tyre Details)*/
    if ($('#media-gallery-small li').length > 2) {
		
		if (($('#media-gallery-small li').length % 2) != 0 ) {
			for (i=0;i<=($('#media-gallery-small li').length % 2);i++) {
	            $('#media-gallery-small ul').append('<li class="blank"></li>');
	        }
		}

		$(window).load( function() {
	        $('#media-gallery-small')
	            .append("<a href='' class='media-gallery-small-next media-nav'></a><a href='' class='media-gallery-small-prev media-nav disabled'></a>")
	            .jCarouselLite({
	                btnNext: '.media-gallery-small-next',
	                btnPrev: '.media-gallery-small-prev',
	                scroll: 2,
	                visible: 2,
	                circular: false
	            });       
	     });
    }
    
    /*media gallery thumb on the media tab*/
    if ($('#media-gallery-small-tab li').length > 6) {
		
		if (($('#media-gallery-small-tab li').length % 6) != 0 ) {
			for (i=0;i<=($('#media-gallery-small-tab li').length % 6);i++) {
	            $('#media-gallery-small-tab ul').append('<li class="blank"></li>');
	        }
		}

		$(window).load( function() {
	        $('#media-gallery-small-tab')
	            .append("<a href='' class='media-gallery-small-tab-next media-nav'></a><a href='' class='media-gallery-small-tab-prev media-nav disabled'></a>")
	            .jCarouselLite({
	                btnNext: '.media-gallery-small-tab-next',
	                btnPrev: '.media-gallery-small-tab-prev',
	                scroll: 6,
	                visible: 6,
	                circular: false
	            });
		});		
    }

    
	
	/*Learn and Share links*/
    $(".clickable-item").addClass("clickable");
    $(".clickable-item a").click(function(e) {
    	e.preventDefault();
    });
	$(".clickable-item").click(function(e) {
		e.preventDefault();
		var rel = $(this).find('.clickable-item-link a:first-child').attr("rel");
		var target = $(this).find('.clickable-item-link a:first-child');
		if($(e.target).attr("href") && $(e.target).attr("href") != target.attr('href')) {
			rel = $(e.target).attr("rel");
			target = $(e.target);
		}
		return xt_click(target[0],'C',xtn2,rel,'N');
	});
	
	/*learn and share transparency*/
	/* by default the background has a black background in case the js is disable other wise replace it with a 
	 transparent div that is added dynamic */
	$(window).load(function(){
		$(".article-list-box-text-container").each(function(){
	    	
	    	var position = $(this).position();
	    	var divHeight = $(this).height();
	    	
	    	var cssProps = {"top"    : position.top+"px",
			    			"left"   : position.left+"px",
			    			"height" : divHeight+"px" };
	    	
	    	var $overlay = $('<div class="transparent80 article-list-overlay">&nbsp;</div>').css(cssProps);
	    	$(this).removeClass("black").before($overlay);
	    	
	    });
	});


	
    /*Large Version (Learn & Share)*/
	if ($('#media-gallery-large').length || $('#media-gallery-small').length || $('#media-gallery-small-tab').length ) {
		/*Video Object*/
		$('#media-gallery-large ul li a[href$=.flv], #media-gallery-small ul li a[href$=.flv], #media-gallery-small-tab ul li a[href$=.flv]').each( function() {
			$(this).append('<span class="video"></span>');
			var galleryType = $(this).parent().parent().parent().attr('id');
			var mediaType;
			
			if ( (galleryType == "media-gallery-small") || (galleryType == "media-gallery-small-tab") ) {
				
				if(window.partnerId){
					var newURL = "media/relatedMedia.action?lensId=" + michelinLensId + "&relatedMediaType=6&partnerId=" + window.partnerId + "#" + $(this).attr('id');
				} else {
					
					var newURL = "media/relatedMedia.action?lensId=" + michelinLensId + "&relatedMediaType=2&tyreId=" + tyreId + "#" + $(this).attr('id');
				}
			}
			else {
				if (currentCategory != null) {
					var newURL = "media/relatedMedia.action?lensId=" + michelinLensId + "&relatedMediaType=1&categoryId=" + currentCategory + "#" + $(this).attr('id');
				}
				else {
					var newURL = "media/relatedMedia.action?lensId=" + michelinLensId + "&relatedMediaType=1#" + $(this).attr('id');
				}
			}
			
			$(this).attr('href',newURL);
		}).addClass('mediatrigger');
		
		var mediaTitle = 'Media Player';
		
		$("a.mediatrigger").prettyPopin({
			width:737, 
			height:420,
	        title: mediaTitle
		});
	
		/*Visual fade in/out behaviour*/	
		$('#media-gallery-large li, #media-gallery-small li, #media-gallery-small-tab li').mouseenter( function() {
			$(this).stop(true,true).fadeTo('fast', 0.5);
			mediaTitle = $('a', this).attr('title');
		}).mouseleave( function() {
			$(this).fadeTo('fast', 1);
			mediaTitle = 'Media Player';
		})
	}
	
	/*Initialize carousel*/
    if ($('#media-gallery-large li').length > 4) {

		if ($('#media-gallery-large li').length % 4 != 0) {
			for (i = 0; i <= ($('#media-gallery-large li').length % 4); i++) {
				$('#media-gallery-large ul').append('<li class="blank"></li>');
			}
		}
		
		$('#media-gallery-large').after("<a href='' class='media-gallery-next media-nav'></a><a href='' class='media-gallery-prev media-nav disabled'></a>");
		
		
		$(window).load( function() {
			$('#media-gallery-large').jCarouselLite({
	            btnNext: '.media-gallery-next',
	            btnPrev: '.media-gallery-prev',
	            scroll: 4,
	            visible: 4,
	            circular: false
	        });
		})		
    }
    
	$('a.media-nav').live('click', function(e) {
        e.preventDefault();
    });
    
/*Smooth scrolling*/
/*Hat tip for the initial idea, heavily modified since:*/
    $('a[rel=internal]')
		.each( function(e) {
			var newHref = document.location + $(this).attr('href');
			$(this).attr('href',newHref);
		})
		.click( function(e) {
			
			e.preventDefault();
			var duration=1000;
			var easing='swing';
			var newHash=this.hash;
			
			/*check to see if the hash has 2 # and use the last one*/
			var aHash = newHash.split('#');			
			if (aHash.length==3)
			{
				newHash = newHash.substring(newHash.lastIndexOf('#'));
				this.hash = newHash;
			}		
			
			if ($(this.hash).length!=0)
			{
				var target=$(this.hash).offset().top;
			}
			else
			{		
				/*if the type size box the old hash is in place and the new tabs are show move to the new target*/
				if ( (this.hash == '#tab-tyres-sizes') && ( $("#tab-tyres-sizes").length==0 ) )
				{	
					var target=$('#tab-type-detail-dimensions').offset().top;
				}				
			}
			
			var oldLocation=window.location.href.replace(window.location.hash, '');
			var newLocation=this;
			
			if(oldLocation+newHash==newLocation) {
				$('html:not(:animated),body:not(:animated)').animate({scrollTop: target}, duration, easing, function() {
					window.location.href=newLocation;
				});
			}
			return false;
	    
	    });

/*get the query string var*/

    function getQueryStringVar(q){
    	var w = window.location.search.substring(1);
    	var qsArr = w.split('&'); 
    	for(var i = 0; i < qsArr.length;i++){
    		var str = qsArr[i].split("=");
    		if(str[0] == q){
    			return str[1];
    		} 
    	} 
    }
    
  if( typeof getQueryStringVar('scrollref') !="undefined" ){
	 
	 setTimeout(function(){
		 $('#tab-tyres-testTab').trigger('click');
		 
	
	 },1000);
  }
/*Popup window*/
	$('a[rel=popup]').click( function(e)  {
		e.preventDefault();
		window.open ($(this).attr('href'), "popup","location=0,status=0,toolbar=0,directories=0,scrollbars=1,width=976,height=500"); 
	})

/*Tyre details smooth scrolling + tab trigger*/
	$('#tyre-details-heading a[rel=internal], .promo-tyre-sizes a[rel=internal], .promo-items a[rel=internal]').click( function(e) {
		$(this.hash).trigger('click');
	})

/*Primary navigation dropdown logic*/
    $('#nav-primary li ul').prepend("<li class='bottom-helper'></li>");
	$('#share-bar li.share-share ul').prepend("<li class='bottom-helper'></li>");


/*Internet Explorer helpers*/
/*TODO - Move to standalone JS file and conditional comment*/
    if ($.browser.msie) {

    /*Handle first/last children in every list*/
        $('ul li:last-child, ol li:last-child').addClass('last-child');
        $('ul li:first-child, ol li:first-child').addClass('first-child');

    /*Hide dropdown menu on load*/
        $('#nav-primary li ul').css('padding-top','0');
		$('#share-bar li.share-share ul').css('padding-top','0');
    }


/*Eco System dropdown logic*/
    $('#lens-trigger').mouseenter( function() {
    	if($('.newDesign').size() > 0) {
    		var elemTriggerPosition = $('#ecosystem #eco-top-level li.change').position();
            $('#eco-container').css("left", elemTriggerPosition.left - 5).stop(true,true).slideDown('fast');
    	}
    	else {
    		$('#eco-container').stop(true,true).slideDown('fast', function() {
    			/* Safari Mac bug fix */
    			$('#eco-container .tab-cont-wrap').scrollTop(1);
				$('#eco-container .tab-cont-wrap').scrollTop(0);
				$('#eco-container .tab-cont-wrap').css("zIndex", 10);
    		});
    	}
    }).mouseleave( function() {
        $('#eco-container').stop(true,true).delay(800).slideUp('fast');
    }).click(function(e){e.preventDefault();})
    
    $('#eco-container').mouseover( function() { 
    	$('#lens-trigger').parent().addClass("active");
        $(this).stop(true,true);
    }).mouseleave( function() {
    	setTimeout(function() {
    		$('#lens-trigger').parent().removeClass("active");
    	},800); 
        $(this).stop(true,true).delay(800).slideUp('fast');
    });
	

/*Hide Show Table details for Low Vis and 2 Wheel*/
    if ($('.two-wheel-table').size()) { 	/*2 wheel reduced table view*/
        $('.front-wheel tr').each( function(i) {
            $('.front-wheel tr:gt(5)').addClass('hide');
        });
        
        $('.rear-wheel tr').each( function(i) {
            $('.rear-wheel tr:gt(5)').addClass('hide');
        });
    }

/*Hides all but the first 5 items for front and rear tyres*/
	$('a.show-hide-table').live('click', function(e) {
		e.preventDefault();	
		$(this).toggleClass('active').nextAll().slideToggle('fast');
    });


/*Tab logic*/
	$(this).find('div.tab-content').hide();
	$('div.tab-cont-wrap').each(function() {
		$(this).find('div.tab-content:first').show();
	});
	
	$("ul.tabs").each( function () {
		$('ul.tabs li > a').click( function(e) {
			e.preventDefault();
		
			if (!$(this).hasClass('current')){
				thisel = $(this);
				
				/*select the current state if the old tabs are in place*/
				if ( thisel.attr('hash').lastIndexOf('#tab-type-detail')==-1 )
				{
					thisel.addClass('current').parent('li').siblings('li')
					.find('a.current').removeClass('current');
				}
				
				$(thisel.attr('rel')).siblings('div.tab-content').slideUp('fast', function() {
					$(thisel.attr('rel')).slideDown('fast')
				});
			}
		});	
	});	
	
    $('#tyre-detail-tab-list').addClass( function() {
  		return 'tabs' + $('#tyre-detail-tab-list').children().length;
	});

	var tyreSizeTableToggle = $('#tyre-size-table-toggle');
	if (tyreSizeTableToggle.length) {
		tyreSizeTableToggle.tyreSizeTableToggle();
	}
	
        /*Share url - adds current URL and title to the share links*/    
        $("a.share-social").click(function()
        {
			var urlParam = "";
            /*if in the tyre selector the user made some selection*/
            if  (Share.flash_url!='')
            {								
                urlParam = $(location).attr('href');				
				var idx1 = urlParam.indexOf('?');				
				var idx2 = urlParam.indexOf('#');
				/*remove old params and hash*/ 								
                urlParam = urlParam.substr(0, Math.min(idx1==-1?urlParam.length:idx1, idx2==-1?urlParam.length:idx2));								               
                
				if (Share.flash_url.lastIndexOf("?")==-1)
				{
					/*check to see if the last character is / if not add it before ? is added*/
                	var last_char_in_url =  urlParam.charAt(urlParam.length-1);
	                if (last_char_in_url == '/')
	                {
	                    Share.flash_url = "?" + Share.flash_url;
	                }
	                else
	                {
	                    Share.flash_url = "/?" + Share.flash_url;
	                }
				}                
				/*add parameters and hash*/
				var urlParam = encodeURIComponent(urlParam) + encodeURIComponent(Share.flash_url + $(location).attr('hash'));				
				
            }else{
				urlParam = encodeURIComponent($(location).attr('href'));
			}				
			
            if (!$(this).parent().hasClass('favorites'))
            {																		
                var url  =  $(this).attr("href").replace('{u}', urlParam).replace('{t}', encodeURIComponent(document.title));							
                /*we don't modify the html but open the link in new window since user might want to share again*/
                var options = '';
                if ($(this).parent().hasClass('share-twitter')) {
                  options += 'width=550,height=450';
                }
                window.open(url, null, options);
            }
            return false;            
        });
     

	/*Hack for forcing favorites link to add to bookmarks instead of opening in a new window*/
	$(".favorites a.share-social").click( function(){
		bookmark();
	})

/*Share button*/
	$('li.share-print a').click( function() {
		window.print();
		return false;
	});

/*Promo roll-up behaviour*/
    $('.promo-items li.promo-effect').each( function() {
		$('span', this).stop(true, true).slideUp('fast');
	}).mouseenter( function() {
		$('span', this).stop(true, true).slideDown('fast', function() {$(this).css('display','block')});
	}).mouseleave( function() {
		$('span', this).stop(true, true).slideUp('fast');
	});
	

/*Table Sort and Zebraisation*/
	$.tablesorter.defaults.widgets = ['zebra']; 
    $('.table-sorter').tablesorter();	
	
	$('.table-sorter-2w:has(tbody tr)').tablesorter({
	  sortList: [[3,0],[0,0],[5,0]] /* by DIAMETER (ASC) WIDTH (ASC) RATION (asc) */	
	}); 
	
	$('.table-segment-902').tablesorter({
		  sortList: [[0,0]] /* by WIDTH (ASC) */	
	});
	$('.table-segment-901,.table-segment-903').tablesorter({
		  sortList: [[0,0]] /* by WIDTH (ASC) */	
	});
	
	$('.type-detail-sizes-tubes').tablesorter({
		  sortList: [[1,0],[6,0],[2,0],[5,0]] /* by TYPE (ASC) CAPACITY OF WIDTH (ASC) VALVE (ASC) WEIGHT (ASC) */	
	});

/*Tyre Launcher init*/	
    if ($('#tyre-launcher').length) {
        
		if ($('#tyre-launcher li').length > 4) {

			$('#container-tyre-launcher .blockContent').css('height','auto');
			
	        /*Even out the display number*/
			if ($('#tyre-launcher li').length % 4 != 0) {
		        for (i=0;i<=($('#tyre-launcher li').length % 4);i++) {
		            $('#tyre-launcher ul').append("<li class='blank'></li>");
		        }
	        }			
	
	        /*Previous + Next buttons*/
			$('#tyre-launcher').before("<a href='' id='prev' class='controls disabled'></a><a href='' id='next' class='controls'></a>");
			$('#container-tyre-launcher .controls').live('click', function(e){
				e.preventDefault();
			})
			
			$(window).load( function() {
		        $('#tyre-launcher')
					.unbind()
					.jCarouselLite({
			            btnNext: '#container-tyre-launcher #next',
			            btnPrev: '#container-tyre-launcher #prev',
			            scroll: 4,
			            visible: 4,
			            circular: false,
			            btnGo: ['#tyre-filters li a']
			        });
			});			
		}
		else {
			$('#container-tyre-launcher .blockContent').css('height','82px')
		}

        /*Block clickable*/
        $('#tyre-launcher ul li:not(.blank)')
            .addClass('clickable')
            .attr('title', '')
            .live('click', function() {
            	var elem = $(this).find("p.desc a").attr("rel"),
					urlLocation = document.location.host + document.location.pathname;
            	
            	window.location.href=$('p.desc a',this).attr('href');
            	
            	if(elem != "" || elem != "undefined"){
            		return xt_click(this,'C',xtn2,'launcher;'+ urlLocation +';' + elem,'N');
            	}
            });
            
        
        /* TL - Footer button analytics */
        $("#tyre-launcher-footer a.more, #tyre-launcher-footer .more a.button, .bicycleTyreSelectionCls").live('click', function(){
        	var elem = $(this).attr("rel"),
				urlLocation = document.location.host + document.location.pathname;
    	
        	if(elem != "" || elem != "undefined"){
        		return xt_click(this,'C',xtn2,'launcher;'+ urlLocation +';' + elem,'N');
        	}
        });
        

        /*Details show + hide*/	
		var shown = false;
		var animLauncher = true;
		var currentElemAnimated =  $('#tyre-launcher ul li:not(.inactive) div:first').parent().attr("id");
		
        $('#tyre-launcher ul li:not(.inactive) div').live('mouseenter mouseleave', function(event) {        	        	
        	
        	if (currentElemAnimated != $(this).parent().attr("id") )
        	{
        		currentElemAnimated = $(this).parent().attr("id");        		
        		animLauncher = true;
        	}
        	
            if (event.type == 'mouseenter') {
            	if (animLauncher == true)
            	{	
            		animLauncher = false;
	                $(this).parent().parent().parent().addClass('hover');	                
	                
	                if ($(this).find('p.desc').is(":visible") == false)
	                {	                	
		                $($(this).find('p.desc'), this).stop(true, true).slideDown(200,function(){		                	
		                	animLauncher = true;
		                });
	                }
	                else
	                {
	                	animLauncher = true;
	                }
					shown = true;					
            	}
            }
            else {
            	if (animLauncher = true)
            	{
            		animLauncher = false;	            	
					var thisel = $(this);
					shown = false;					
					if ($(this).find('p.desc').is(":visible") == true)
					{
		                $($(this).find('p.desc'), this).stop(true,true).slideUp(200, function() {
							if (shown == false) {
								thisel.parent().parent().parent().removeClass('hover');								
								animLauncher = true;
							}
						});
					}
					else
					{
						animLauncher = true;
					}
            	}                
            }
        });
        
    };

   
/*Tyre Filters init*/
    if ($('#tyre-filters').length) {
        initLauncherFilters();
    }

		/*Tyre fitments init*/
		initTyreFitmentsFoldables();
	

/*Tyre inactive hover state*/ 
	$("li.inactive").live('mouseenter mouseleave', function(event) {
            if (event.type == 'mouseenter') {
                $(this).stop(true,true).fadeTo('fast', 0.8)
            }
            else {
                $(this).stop(true,true).fadeTo('fast', 0.2)
            }
        });
   
    function transformTyreLauncherButtonUrl(el,attributes,targetEl){
       
    	var currentUrl = $(el).attr('href');
        var prettyUrls = currentUrl.split('?'+attributes);
        var prettyTargetUrl = document.location.protocol+"//"+document.location.host + "/" + prettyUrls[0];
        $(targetEl).attr('href',prettyTargetUrl);
    }
    
    if($('#container-tyre-launcher #tabs-lens-trigger li a').length > 0){
    	var attributes = $($('#container-tyre-launcher #tabs-lens-trigger li a')[0]).attr('href').split('?')[1];
    	if($('#tyre-launcher-footer .more .button').length > 0){
        	transformTyreLauncherButtonUrl($($('#container-tyre-launcher #tabs-lens-trigger li a')[0]),attributes,$('#tyre-launcher-footer .more .button'));
        } else {
        	transformTyreLauncherButtonUrl($($('#container-tyre-launcher #tabs-lens-trigger li a')[0]),attributes,$('#tyre-launcher-footer .more'));
        }
    }
    
    /*Tyre Launcher strip tabs*/
    $('#container-tyre-launcher #tabs-lens-trigger li:not(.alt,.others) a').click( function(e) 
    {
        e.preventDefault();
       
        var attributes = $(this).attr('href').split('?')[1];
        var location = $(this).attr('rel');
        var jQueryThis = $(this);
        if($('#tyre-launcher-footer .more .button').length > 0){
        	transformTyreLauncherButtonUrl($(this),attributes,$('#tyre-launcher-footer .more .button'));
        } else {
        	transformTyreLauncherButtonUrl($(this),attributes,$('#tyre-launcher-footer .more'));
        }
        
        /*Load tyres*/       
        $('#' + location + ' ul').fadeOut('fast', function()
        {
            $('.controls').remove();
            $('#' + location).addClass('loading');
           
             $.ajax({
                  url      :  'tyreSearch/tyreLauncherSearchResult.action?&' + attributes ,
                  dataType : "html",
                  success  : function(htmlResponse)
                  {
                	  
                        var jQueryResponseObject = $(htmlResponse);                        
                        tyreLauncherBody = $(jQueryResponseObject[0]).find("ul");
                        tyreLaucherFooter = $(jQueryResponseObject[1]).find("ul li");                        
                        $('#tyre-launcher').html(tyreLauncherBody);
                        $('#tyre-launcher').unbind();
                        $('#tyre-filters li a').unbind();
    
				if ($('#tyre-launcher li').length % 4 != 0) {
			        for (i=0;i<=($('#tyre-launcher li').length % 4);i++) {
			            $('#tyre-launcher ul').append("<li class='blank'></li>");
			        }
		        }
                
                        $('#tyre-launcher ul li:not(.blank)').addClass('clickable').attr('title', '');

                        $('#tyre-launcher-footer ul').animate({width: 0}, 300, function() 
                        {
                                $("#tyre-launcher-footer ul").html(tyreLaucherFooter);
                                
                                initLauncherFilters();
								initTyreFitmentsFoldables();
                                $('#' + location).removeClass('loading');
				$('#tyre-launcher-footer ul').animate({width: "650px"}, 500);

				if ($('#tyre-launcher li').length > 4)
                                {
                                    $('#container-tyre-launcher .blockContent').css('height','auto')
                                    $('#tyre-launcher')
						.before("<a href='' id='prev' class='controls disabled'></a><a href='' id='next' class='controls'></a>")
						.jCarouselLite({
							btnNext: '#container-tyre-launcher #next',
							btnPrev: '#container-tyre-launcher #prev',
							scroll: 4,
							visible: 4,
							circular: false,
							btnGo: ['#tyre-filters li a']
						});
				}
				else {
					$('#container-tyre-launcher .blockContent').css('height','82px')
				}
                            
                        });


                        $(jQueryThis).parent('li').siblings('li').removeClass('active');
                        $(jQueryThis).parent('li').addClass('active');
                  }
            });
            
            
        });

       
    });
	
        /*set the autocomplete off property via javascript for xhtml compliance*/
        if ($("#param_search").length)
        {
            $("#param_search").attr("autocomplete","off");
        }
        

	/*Quick Search behaviour*/
	if($('#quick-search').length) {
		
		$('#quick-search')
			.after('<div id="quick-search-results" class="loading"><div class="helper-top"></div></div>')
			.data('oval',$('input#param_search', $(this)).attr('value'))
			.submit(function(e)
                        {
				e.preventDefault();
				var searchTerm = $('#param_search', this).val();
				searchTerm = searchTerm.replace(/%/g,"%25").replace(/&/g,"%26").replace(/\//g,"|||"); /*replace / with |||*/
                                /*prevent user to search for an empty string and for the default text placeholder*/
                                if  ( (jQuery.trim(searchTerm)!='') && (jQuery.trim(searchTerm)!=searchMichelinPlaceholder) )
                                {
                                    var theBase = $('base').attr('href'),
                                    	searchURL = $(this).find('#searchURLLink').val();
                                    
                                    if(searchURL == "" || searchURL == "seo.friendly.search") {
                                    	var searchURLValue = "search/";
                                    }
                                    else {
                                    	var searchURLValue = searchURL + "/"; 
                                    }
                                    
                                    window.location = theBase + searchURLValue + searchTerm;
                                }
			});
		
		$('#quick-search input#param_search')
			.focus( function() {
				el = $(this);
				
				el.attr('value', function() {
					if (el.attr('value') == $('#quick-search').data('oval')) return '';
				});
				
				if (el.attr('value') != $('#quick-search').data('oval')) {
					$(this).trigger('keyup');
				}
			})
			.blur( function() {
				el = $(this);
				
				el.attr('value',function() {
					if (el.attr('value') == '') return $('#quick-search').data('oval');
				});
				
				$('#quick-search-results').delay(500).slideUp('fast');
			})
			.keyup( function(e) {
				el = $(this);
				helper = '<div class="helper-top"></div>';                                
				string = el.val().replace(/%/g,"%25").replace(/^\s+|\s+$/g, '').replace(/\s/g,"%20").replace(/&/g,"%26"); /*trim and clean up spaces*/
                                if (string && e.keyCode!=9 && e.keyCode!=16 && e.keyCode!=17 && e.keyCode!=18 && e.keyCode!=36 && e.keyCode!=35 && e.keyCode!=37 && e.keyCode!=39 && e.keyCode!=46 ) {
					$('#quick-search-results').empty().html(helper);
					$('#quick-search-results').slideDown('fast').addClass('loading');

                                        setTimeout( function()
                                        {
                                                 /*in order to do a search it neads to be at least 3 characters specified*/
                                                 if  (jQuery.trim(el.val()).length>2)
                                                 {
                                                    $('#quick-search-results').load('searchResults/getCompactSearchResults.action?searchText=' + encodeURI(string) + '&lensId=' + michelinLensId, function(){
                                                            $(this).removeClass('loading');
                                                            $(this).append(helper);
                                                    });

                                                    $('#quick-search-results').slideDown('fast');
                                                 }
                                                 else
                                                 {
                                                     $('#quick-search-results').slideUp('fast');
                                                 }
                                        }, 1000);
				}
				else if (!string) {
					$('#quick-search-results').slideUp('fast');
				}
				else {
					
				}
			});
	}

        /*action for button recent searches*/
        $("#search-recent").click(function(e){

               if ($('#quick-search-results').is(":hidden"))
               {
                   var helper = '<div class="helper-top"></div>';                  
                   $('#quick-search-results').empty().html(helper).slideDown('fast').addClass('loading');
                   
                   /*get the recent searches that the user did as json from server*/
                   $.ajax({
                      url: 'searchResults/recentSearches',
                      cache: false,
                      success: function(htmlResponse)
                      {
                           $('#quick-search-results').removeClass('loading').html(htmlResponse).append(helper);
                             Cufon.replace('#recent_searches_container h4');
                      }
                    });
               }
               else
               {
                   $('#quick-search-results').slideUp('fast',function(){
                        $(this).empty();
                   });
               }             
               e.preventDefault();
               return false;
        });
        /*when the search recent lose focus*/
   
        $("#search-recent").blur(function(){            
            $('#quick-search-results').delay(500).slideUp('fast',function(){
                 $(this).empty();
            });
        });
      
        /*clear recent searches*/
        $("#recent-search-clear").live("click",function(e){
            /*get the link for the clear the recent search and perform a ajax call in the background for it*/
            $.get($(this).attr("href"));
            /*hide and clear the quick search results box*/
            $('#quick-search-results').slideUp('fast',function(){
                        $(this).empty();
            });
            e.preventDefault();
            return false;
        });
	
	
/*Dealer Locator mouse events*/
	var mouseWheelEventName = $.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel';
	_globalSettings = $.extend({
		mouseWheelEvent:mouseWheelEventName,
		pngFixSelector:'#tyre, #mast, #tyreReader img, #faqContentList img, #fitmentCarMaker img, #tyreGuide img,.subnav'
	});
	
	
	/*FIXES*/
	$('.share-share').click(function(e){e.preventDefault()});
});

function initLauncherFilters() {
	
    /*Build arrays*/
    $('#tyre-filters li').each( function() {
        
        var location = $('a',this).attr('rel');
        
        var thefilter = $('a',this).attr('class');
        var temparray = new Array;
       
        $($('a',this).attr('class')).removeData();
        
        $('#' + location + ' ul > li p.filters-active span.' + thefilter).each( function() {
            temparray.push($(this).parents('li')[0].id);
        });
            
        $('#tyre-filters').data($('a',this).attr('class'), temparray);
    });

    var pageTitle = $('title:first');
    var lastBreadcrumbItem = $('#bread-crumb li:last');
    var pageH1 = $('h1:first');	

    /*Click event*/
     
     
    
    $('#tyre-filters li a').click( function(e, opts) {
    		
	        e.preventDefault();
	        var thisel = $(this);
	        var location = thisel.attr('rel');
	        var thisfilter = thisel.attr('class').split('-')[1];		
	        var thishash = thisel.attr('href').split('/')[2];
	        var thisid = thisel.attr('id') || '';			
	        if(window.location.href.indexOf('.ru') > 0){
	        		
				if ($('.filters-container').css('visibility') != 'hidden') {
					$('.filters-container').css('height', $('#filter-text-container-' + thisfilter).height());
					$('.filter-text-container').css('visibility', 'hidden');
					$('#filter-text-container-' + thisfilter).css('visibility', 'visible');
				}
	        }
	      
	        if (thisid !== '' && typeof(filterData) !== 'undefined') {
	        	
	            var id = thisfilter;
	            var filterStr = 'filter=' + id;
	
				
	            if (window.location.hash.indexOf('filter=') !== -1) {
	              window.location.hash = window.location.hash.replace(/filter=\w+/, filterStr);
	            } else {
	              if (window.location.hash !== '') {
	                filterStr = '&' + filterStr;
	              }
	
	              window.location.hash += filterStr;
	            }
	            
	
	            var thisFilterData = filterData[id];
	          
	            if (thisFilterData) {
	            	if(window.location.href.indexOf('.ru') > 0){
	            		
						/*change page title using document title attr... work on IE too*/
						
	    				$(document).attr('title', thisFilterData.pageTitle);
		                
		                pageH1.text(thisFilterData.h1Tag);
		
		                var newBreadcrumbItem = $('<li>' + thisFilterData.breadcrumbText + '</li>');
		
		                lastBreadcrumbItem.replaceWith(newBreadcrumbItem);
		
		                lastBreadcrumbItem = newBreadcrumbItem;
		                
	            	}
	            }
	        }
	        
	        var fadeTime = (opts && opts.quick) ? 0.001 : 'fast';
	        var fadeInDelay = (opts && opts.quick) ? 0 : 500;
	        
	        $('#' + location + ' > ul').animate({
	          opacity: 0
	        }, fadeTime, function() {
	        	
	            setTimeout(function() {
	              if (thisel.attr('class') == 'filter-all') {
	                  $('#' + location + ' ul > li').removeClass('inactive').stop(true,true).fadeTo('fast', 1); 
	              }
	              else {			  		
	                  $('#' + location + ' > ul > li').addClass('inactive').stop(true,true).fadeTo('fast', 0.2);
					  if ($('#tyre-filters').data(thisel.attr('class'))) {
						 
					  	for (i = $('#tyre-filters').data(thisel.attr('class')).length - 1; i >= 0; i--) {
					  		$('#' + $('#tyre-filters').data(thisel.attr('class'))[i]).removeClass('inactive').prependTo('#' + location + ' > ul').stop(true, true).fadeTo('fast', 1);
					  	}
					  }
	              }
	
	              $('#' + location + ' ul').animate({
	                opacity: 1
	              }, fadeTime);
	            }, fadeInDelay);
		
	            $('#tyre-filters li').removeClass('active');
	            thisel.parent().addClass('active');
	        });
	            
	        $.post('util/updateSession.action?parameterName=selectedFilter&parameterValue=' + thisfilter);
    	
    });
    
    /*Check for pre-selected filter*/
    if ($('li.active', $('#tyre-filters')).length) {
    	
        /*check to see if there is an hash tag in the url*/
        if (location.href.indexOf("#") !== -1 && location.hash.indexOf('filter=') !== -1)
        {
        	
            var hash_tag = window.location.hash.substr(1).replace(/.*filter=(\w+).*/, '$1');
            /*check to see if there is a tab specific to that hash tag*/
            if ($('li a.filter-'+hash_tag, $('#tyre-filters')).length != 0)
            {
            	
            	
                /*activate the other tabs*/
                $('li.active', $('#tyre-filters')).removeClass("active");
                $('li a.filter-'+hash_tag, $('#tyre-filters')).parent().addClass("active");
            }
        }
      $('li.active a:first', $('#tyre-filters')).trigger('click', { quick: true });

    }    
	
	/*Cookies*/
    /*var value = $.readCookie('Michelin-Perm');
    if( value ){
        alert( "Hey! This cookie exists, and their value is : \\n" + value );
	}else{
        alert( 'This cookie \'non ecziste\'!' );
		$.setCookie( 'Michelin-Perm', 'true', {});
	}*/
}

/*
 * Initialize tyre fitments foldables
 */

var initTyreFitmentsFoldables = function() {
	
	$('#car-fitments').tyreFitmentsFoldable();
	$('#car-fitments').tyreFitmentsHighlightToggle();
	$('#tyre-results li.row-view-row div.tyre-fitments').tyreFitmentsFoldable({
		showText: (typeof tyresSearchFitmentsShowText !== 'undefined') ? tyresSearchFitmentsShowText : '',
		hideText: (typeof tyresSearchFitmentsHideText !== 'undefined') ? tyresSearchFitmentsHideText : ''
	});
	
  $('#tyre-results li.row-view-row div.tyre-fitments a[rel=lightbox]').prettyPopin({
    width: 895,
    height: 683,
    title: $(this).attr('title')
  });
  /*Bicycle related tyres fitments*/
  $('#bike-fitments').tyreFitmentsFoldable({
        showText: (typeof bikeDimensionsShowText !== 'undefined') ? bikeDimensionsShowText : '',
        hideText: (typeof bikeDimensionsHideText !== 'undefined') ? bikeDimensionsHideText : '',
        foldElement: 'div.bicycle-dimensions-table'     
  });
};

$.fn.tyreFitmentsFoldable = function(options) {
	if (!this.length) {
		return this;
	}

	options = $.extend({
		triggerElement: 'p.fitments-toggle a',
		foldElement: 'div.fitments-table',
		expandedClass: 'expanded',
		showText: (typeof carTyreFitmentsShowText !== 'undefined') ? carTyreFitmentsShowText : '',
		hideText: (typeof carTyreFitmentsHideText !== 'undefined') ? carTyreFitmentsHideText : ''
	}, options);

	var foldThis = function(element, triggerElement, foldElement, noAnim) {
		if (noAnim) {
			element.removeClass(options.expandedClass);
			foldElement.hide();
			triggerElement.text(options.showText);
			element.data('contracted', true);

			return;
		}

		if (element.data('contracted')) {
			element.addClass(options.expandedClass);
			foldElement.animate({
				height: 'show'
			}, 'fast');
			triggerElement.text(options.hideText);
			element.data('contracted', false);
		} else {
			element.removeClass(options.expandedClass);
			foldElement.animate({
				height: 'hide'
			}, 'fast');
			triggerElement.text(options.showText);
			element.data('contracted', true);
		}
	};

	this.each(function() {
		var element = $(this);

		if (element.data('fitmentsFoldable')) {
			return;
		}

		var triggerElement = element.find(options.triggerElement);
		var foldElement = element.find(options.foldElement);

		triggerElement.bind('click', function(e) {
			e.preventDefault();

			foldThis(element, triggerElement, foldElement);
		});

		element.data('fitmentsFoldable', true);

		foldThis(element, triggerElement, foldElement, true);
	});

	return this;
};

$.fn.tyreFitmentsHighlightToggle = function(options) {
	if (!this.length) {
		return this;
	}

	options = $.extend({
		triggerElement: 'p.fitments-toggle a',
		repetitions: 3,
		duration: 600,
		easing: "swing",
		opacity: 0.5
	}, options);

	this.each(function() {
		var element = $(this).find(options.triggerElement);
		var highlight = $('<span class="highlight"></span>');

		var opacity = 0;
		highlight.css('opacity', opacity);

		element.before(highlight);

		for (var i = 0; i < options.repetitions * 2 + 1; i++) {
			highlight.animate({
				opacity: opacity
			}, options.duration, options.easing);
			opacity = opacity === 0 ? options.opacity : 0;
		}
	});

	return this;
};

/**
 * Tyre details page size table toggle
 */

$.fn.tyreSizeTableToggle = function(options) {
	if (!this.length || this.length > 1) {
		return this;
	}

	/* Set up variables */
	var firstClass  = 'first',
	    lastClass   = 'last',
	    activeClass = 'active',
	    duration    = 200;

	var allClasses  = ['active', firstClass+'_'+activeClass, lastClass+'_'+activeClass].join(' ');

	var toggle = function(e, initial) {
		e.preventDefault();

		var link = $(this);
		var item = link.parent();

		items.removeClass(allClasses);
		item.addClass(activeClass);
		if (item.hasClass(firstClass)) {
			item.addClass(firstClass+'_'+activeClass);

			if (initial) {
				lastPane.hide();
				firstPane.show();
			} else {
				lastPane.animate({
					height: 'hide'
				}, duration, function() {
					firstPane.animate({
						height: 'show'
					}, duration);
				});
			}
		} else if (item.hasClass(lastClass)) {
			item.addClass(lastClass+'_'+activeClass);

			if (initial) {
				firstPane.hide();
				lastPane.show();
			} else {
				firstPane.animate({
					height: 'hide'
				}, duration, function() {
					lastPane.animate({
						height: 'show'
					}, duration);
				});
			}
		}
	};

	var container = this;
	var items = container.find('li');
	var links = items.find('a');

	var firstPane = $(links.slice(0,1).attr('href'));
	var lastPane  = $(links.slice(1,2).attr('href'));

	/* Bind events */
	links.bind('click', toggle);

	items.slice(0,1).find('a').trigger('click', true);

	return this;
};




/*
 * Placeholder jQuery plugin
 * @alias jQuery.prototype.placeholder
 * @return {jQuery}
 */
jQuery.fn.placeholder = function(opts) {
	jQuery.support.placeholder = typeof $('<input>').attr('placeholder') != 'undefined';
	return this.each( function() {
		if (!jQuery.support.placeholder) {
			var input = $(this);
		}
	});
};

var delay = ( function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

function bookmark() {
	bookmarkurl=document.location;
	bookmarktitle=document.title;
	if (document.all)
		window.external.AddFavorite(bookmarkurl,bookmarktitle)
	else if (window.sidebar) /*firefox*/
		window.sidebar.addPanel(bookmarktitle, bookmarkurl, "");
}

function loadScript(url, callback){
    var script = document.createElement("script")
    script.type = "text/javascript";
    if (script.readyState){  /*IE*/
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  /*Others*/
        script.onload = function(){
            callback();
        };
    }
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

function writeLastPageCookie(){
	var the_date = new Date();
	var unix_time = the_date.getTime();
	var expiration = unix_time + 31556926;
	the_date.setTime(expiration);
	document.cookie = "michelin-survey-last-page="+window.location.href+";expires="+the_date.toGMTString()+";path=/";
}

if(window.hasLastPageCookie) {
	writeLastPageCookie();
}





var UrlFilter = {
		// public method for url encoding
		encode : function (string) {
			return escape(this._utf8_encode(string));
		},
	 
		// public method for url decoding
		decode : function (string) {
			return this._utf8_decode(unescape(string));
		},
	 
		// private method for UTF-8 encoding
		_utf8_encode : function (string) {
			string = string.replace(/\r\n/g,"\n");
			var utftext = "";
	 
			for (var n = 0; n < string.length; n++) {
	 
				var c = string.charCodeAt(n);
	 
				if (c < 128) {
					utftext += String.fromCharCode(c);
				}
				else if((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				}
				else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}
	 
			}
	 
			return utftext;
		},
	 
		// private method for UTF-8 decoding
		_utf8_decode : function (utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
	 
			while ( i < utftext.length ) {
	 
				c = utftext.charCodeAt(i);
	 
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				}
				else if((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				}
				else {
					c2 = utftext.charCodeAt(i+1);
					c3 = utftext.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
			}
			return string;
		}
	 
	}



