var Share =  Share || {};
Share.flash_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'));
		}
    });

// 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')
		.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({
			followScroll:false,
			modal:false,
			width:747,
			height:420,
			opacity:0.5,
			animationSpeed:'fast',
                        type:'iframe'
    });
    
    // 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').mouseenter( function() {
			$(this).stop(true,true).fadeTo('fast', 0.5);			
        }).mouseleave( function() {
			$(this).fadeTo('fast', 1);			
    });



	
// Lightbox - pretty popin Country Selector
	$("a[href^='country-selector']").prettyPopin({
		followScroll:false,
		modal:false, 
		width:935, 
		height:365, 
		opacity:0.5, 
		animationSpeed:'fast', 
        title: $("a[href^='country-selector']").attr('title'),
        type:'iframe'
	});
	
// Lightbox - pretty popin Tyre Reader
	$("a[href^='tyres/tyre-reader/']").prettyPopin({
		followScroll:false,
		modal:false, 
		width:895, 
		height:545, 
		opacity:0.5, 
		animationSpeed:'fast', 
        title: $("a[href^='tyres/tyre-reader/']").attr('title'),
        type:'iframe'
	});
	
	$("a[href^='motorcycles/tyre-reader/']").prettyPopin({
		followScroll:false,
		modal:false, 
		width:895, 
		height:545, 
		opacity:0.5, 
		animationSpeed:'fast', 
        title: $("a[href^='motorcycles/tyre-reader/']").attr('title'),
        type:'iframe'
	});
	
	
// Lightbox - pretty popin Email form
	$("a.share-popin").prettyPopin({
		followScroll:false,
		modal:false, 
		width:450,
		height:347,
		opacity:0.5, 
		animationSpeed:'fast', 
        title: $(".share-popin").attr('title'),
        type:'iframe'
	});
	

// Lightbox - Pretty popin Tyre Large Image
	$('.tyre-lightbox a').prettyPopin({
		followScroll:false,
		modal:false, 
		width:520, 
		height:540, 
		opacity:0.5, 
		animationSpeed:'fast', 
        title:$('.tyre-lightbox a').attr('title'),
        type:'image'
	});

	
 // 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
	            });
		})		
    }
	
	// Learn and Share links
	$(".clickable-item").addClass('clickable');
	$(".clickable-item").click(function(e) {
              e.preventDefault();
              var base_url = $("base").attr("href"); // need to get the base url to preppend to the article link to work on IE
              window.location = base_url + $(this).find('.clickable-item-link a').attr("href");
	});

	
    // Large Version (Learn & Share)
	if ($('#media-gallery-large').length || $('#media-gallery-small').length) {
		// Video Object
		$('#media-gallery-large ul li a[href$=.flv], #media-gallery-small 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"){
				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({
			followScroll:false,
			modal:false, 
			width:747, 
			height:420, 
			opacity:0.5, 
			animationSpeed:'fast', 
	        title: mediaTitle,
	        type:'iframe'
		});
	
		// Visual fade in/out behaviour	
		$('#media-gallery-large li, #media-gallery-small 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;
			var target=$(this.hash).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;
				});
			}
	    
	    });


// 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]').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() {
        $('#eco-container').stop(true,true).slideDown('fast');
    }).mouseleave( function() {
        $('#eco-container').stop(true,true).delay(800).slideUp('fast');
    }).click(function(e){e.preventDefault();})
    
    $('#eco-container').mouseover( function() {
        $(this).stop(true,true);
    }).mouseleave( function() {
        $(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)
				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;
	});
	
        // Share url - adds current URL and title to the share links    
        $("a.share-social").click(function()
        {
            // if in the tyre selector the user made some selection
            if  (Share.flash_url!='')
            {
                // check to see if the url has allready GET params
                var checked_url =  $(location).attr('href');
                if ( checked_url.lastIndexOf("?")==-1 )
                {
                    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 =  checked_url.charAt(checked_url.length-1);
                        
                        if (last_char_in_url == '/')
                        {
                            Share.flash_url = "?" + Share.flash_url;
                        }
                        else
                        {
                            Share.flash_url = "/?" + Share.flash_url;
                        }
                    }
                }
                else
                {
                    Share.flash_url = "&" + Share.flash_url;
                }
            }            
            if (!$(this).parent().hasClass('favorites'))
            {
                var url  =  $(this).attr("href").replace('{u}', encodeURIComponent($(location).attr('href')+Share.flash_url)).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
                window.open(url);
            }
            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(); 

	
// 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() {
                window.location.href=$('p.desc a',this).attr('href');
            });
            

    // Details show + hide
	
		var shown = false;
	
        $('#tyre-launcher ul li:not(.inactive) div').live('mouseenter mouseleave', function(event) {
            if (event.type == 'mouseenter') {
                $(this).parent().parent().parent().addClass('hover');
                $('p.desc', this).stop(true, true).slideDown(200);
				shown = true;
            }
            else {
				var thisel = $(this);
				shown = false;
                $('p.desc', this).stop(true, true).slideUp(200, function() {
					if (shown == false) {
						thisel.parent().parent().parent().removeClass('hover');
					}
				});
            }
        });
        
    };

   
// Tyre Filters init
    if ($('#tyre-filters').length) {
        initLauncherFilters();
    }
	

// 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)
            }
        });
    
    
    // Tyre Launcher strip tabs
    $('#container-tyre-launcher #tabs-lens-trigger li:not(.alt) a').click( function(e) 
    {
        e.preventDefault();
        var attributes = $(this).attr('href').split('?')[1];
        var location = $(this).attr('rel');
        var jQueryThis = $(this);
        
		// 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();
                                $('#' + location).removeClass('loading');
				$('#tyre-launcher-footer ul').animate({width: "750px"}, 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");
                                // 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');
                                    window.location = theBase + 'search/' + 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');

                                        delay( 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=' + 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);
    })

    // Click event
    $('#tyre-filters li a').click( function(e) {
        e.preventDefault();
        var thisel = $(this);
        var location = thisel.attr('rel');
        var thisfilter = thisel.attr('class').split('-')[1];

        $('#' + location + ' > ul').slideUp('fast', 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', .2);

                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);
                    }
            }

            $('#tyre-filters li').removeClass('active');
            thisel.parent().addClass('active');
            $('#' + location + ' ul').slideDown('fast');
        });
            
        $.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)
        {
            var hash_tag = window.location.hash.substr(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');

    }    
	
	// 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', {});
	//}
}

// CUFON Initialization 
    Cufon.replace('.content h3, .article-content h4, .article-intro h3, .article-intro h4, #header h2, #lense-segments h2, #page-title h2, #tyre-details-info h3, #error h2, .hero h2, .search-type-head h3, #ls-accordion h3, #accordion-display h3, #lense-segments a, a.button:not(.big)', {hover: true});
	// drop shadow
    Cufon.replace('#when-to-buy .cases li div h3', {hover: true, textShadow: '1px 1px rgba(0, 0, 0, .4)'});


/**
 * 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, "");
}