var gw_lang;
var gw_lang_short;
// random tips
var indexurl_name=document.location.href;
var gw_ominture_pagename = "";
var western_found = indexurl_name.indexOf("#western") != -1 ;
var ontario_found = indexurl_name.indexOf("#ontario") != -1 ;
var quebec_found = indexurl_name.indexOf("#quebec") != -1 ;
var atlantic_found = indexurl_name.indexOf("#atlantic-canada") != -1 ;
var overview_load = indexurl_name.indexOf("#") != -1 ;



$(document).ready(function() {

	//Goodwrench conditional for Western Canada offers
		$('#hero').hide();
		if(ontario_found || quebec_found || atlantic_found) {$('#hero').show();} else {$('#hero').hide();}
		
		(western_found || !overview_load) ? $('.region-header').next().hide() : $('.region-header').next().show(); 

		$('ul.region-list li.western').bind('click', function (evt) {
						$('#hero').hide();
						$('.region-header').next().hide();                             
		});
		// End



	if (getLanguage() == 'fr') {
		gw_lang = 'french';
		gw_lang_short = 'fr';
	}
	else {
		gw_lang = 'english';
		gw_lang_short = 'en';		
	}
	
	// if language is changed, make AJAX call to update offers
	var sideBarOfferLang = $('span.sidebarOfferLang').html();
	if (sideBarOfferLang != null) {
		if (sideBarOfferLang != gw_lang_short) {
			var  postalCode=$('#postal-code-sidebar').val();
			if(validatePostalCode(postalCode)==true) {
				//console.log('offer lang = ' + sideBarOfferLang);
				getSidebarOffers();
			}
		}
	}

// VIDEO PLAYER BEGIN

	if (swfobject != null) {
		// Load flash video player...
		var params = {};
		params.menu = "false";
		params.wmode = "transparent";
		params.allowscriptaccess = "always";
		var attributes = {};
		if (getLanguage() == "fr"){
			swfobject.embedSWF("/media/goodwrench/drivesmart-video/video.swf?lang=fr&filePath=/media/goodwrench/drivesmart-video/content/", "videoContainer", "504", "305", "9.0.0", false, params, attributes);
		}
		else {
			swfobject.embedSWF("/media/goodwrench/drivesmart-video/video.swf?lang=en&filePath=/media/goodwrench/drivesmart-video/content/", "videoContainer", "504", "305", "9.0.0", false, params, attributes);
		}
	}
	
	
	//Goodwrench -> Regional Offers -> Ontario -> Banner ->Popup 
	//***********
	var serviceMaintenanceHTML=$('div.112648').html();
	if (getLanguage() == "fr"){
		$('div#springmaintenancespecial').html(serviceMaintenanceHTML+"<input type='submit' onclick='tb_remove()' value='&nbsp;&nbsp;Fermer&nbsp;&nbsp;' id='Login'>");
	}else if (getLanguage() == "en") {
		$('div#springmaintenancespecial').html(serviceMaintenanceHTML+"<input type='submit' onclick='tb_remove()' value='&nbsp;&nbsp;Close&nbsp;&nbsp;' id='Login'>");
	}
	function tb_remove(){
		$('div#springmaintenancespecial').hide();
	}
	//************
	
	
	// only call if on the Goodwrench site.
	if (indexurl_name.indexOf('/services/goodwrench/') != -1) {
		// Video array - English
		if(indexurl_name.search('english/') > -1)
		{
			gwVideos = new Array(
			'Your-Tires',
			'Your Tires',
			'Choosing the foundation for your ride and tips to help increase tire life.',
			'all-services-maintenance',
			
			'Roadside-Safety-and-OnStar',
			'Roadside Safety and OnStar<sup> &reg;</sup>',
			'Safety tips in case of an emergency and the helpful features of OnStar<sup> &reg;</sup>',
			'all-seasonal-driving-safety-summer',

			'Changing-A-Flat',
			'Changing a Flat',
			'An outline of the steps to safe tire changes.',
			'all-seasonal-driving-services-safety-summer-maintenance',

			'Checking-Your-Oil',
			'Checking Your Oil',
			'How and when to check your oil for the most accurate reading and to help maximize engine protection.',
			'all-driving-maintenance-services',

			'Your-Battery',
			'Your Battery',
			'Tips on proper battery maintenance and help with battery longevity.',
			'all-maintenance-services',

			'Filters',
			'Filters',
			'How to check your filters, and which filters to check to help maximize your vehicle&#39;s performance.',
			'all-maintenance-services',

			'Air-Conditioning',
			'Air Conditioning',
			'Recognize the warning signs that mean your air conditioning system needs Goodwrench service.',
			'all-maintenance-summer',

			'Identifying-Fluids',
			'Identifying Fluids',
			'Fluid leaks can be the first sign of a problem - know what to look for.',
			'all-maintenance',

			'Fluids',
			'Fluids',
			'Learn to recognize fluid problems and the proper action to solve them.',
			'all-maintenance',

			'Belts-and-Hoses',
			'Belts and Hoses',
			'Danger signs to catch before deteriorating belts and hoses cause damage to your vehicle.',
			'all-maintenance',

			'Wiper-Blades',
			'Wiper Blades',
			'All the key facts on one of the most overlooked maintenance items.',
			'all-maintenance-services',

			'Brakes',
			'Brakes',
			'Learn the brake wear warning signs and know the difference between disk and drum brakes.',
			'all-maintenance-services',

			'Headlamps',
			'Headlamps',
			'Get advice on bulb types and spotting dangerous alignment problems.',
			'all-maintenance',

			'Suspension',
			'Suspension',
			'Know the important parts of your suspension and recognize signs of wear.',
			'all-maintenance',

			'Exhaust-System',
			'Exhaust System',
			'A well maintained exhaust system can save your life.',
			'all-maintenance'

			);
		}

		// Video array - French
		if(indexurl_name.search('french/') > -1)
		{
			gwVideos = new Array(
			'Your-Tires',
			'Vos pneus',
			'La s&#233;lection des &#233;l&#233;ments constituant la base essentielle de votre v&#233;hicule et des conseils pour vous aider &#224; prolonger la dur&#233;e de vie utile des pneus.',
			'all-services-maintenance',

			'Roadside-Safety-and-OnStar',
			'La s&#233;curit&#233; routi&#232;re et OnStar<sup>MD</sup>',
			'Des conseils de s&#233;curit&#233; en cas d\'urgence et les fonctions pratiques du syst&#232;me OnStar<sup>MD</sup>.',
			'all-seasonal-driving-safety-summer',
			
			'Changing-A-Flat',
			'Changer un pneu &#224; plat',
			'Un aper&#231;u des &#233;tapes &#224; suivre pour le changement s&#233;curitaire d\'un pneu.',
			'all-seasonal-driving-services-safety-summer-maintenance',

			'Checking-Your-Oil',
			'V&#233;rifier l\'huile moteur',
			'Comment et quand v&#233;rifier l\'huile de votre moteur pour obtenir la mesure de niveau la plus pr&#233;cise et maximiser la protection du moteur.',
			'all-driving-maintenance-services',

			'Your-Battery',
			'La batterie',
			'Des conseils sur l\'entretien des batteries et pour prolonger leur dur&#233;e de vie utile.',
			'all-maintenance-services',

			'Filters',
			'Les filtres',
			'Comment v&#233;rifier les filtres, et quels filtres v&#233;rifier pour un rendement optimal de votre v&#233;hicule.',
			'all-maintenance-services',

			'Air-Conditioning',
			'La climatisation',
			'Reconnaissez les signes indiquant que votre climatiseur a besoin d\'un entretien Goodwrench.',
			'all-maintenance-summer',

			'Identifying-Fluids',
			'Identification des liquides',
			'Les fuites de liquide sont g&#233;n&#233;ralement le signe avant-coureur d\'un probl&#232;me. Sachez quoi faire.',
			'all-maintenance',

			'Fluids',
			'Les liquides',
			'Apprenez &#224; identifier les incidents caus&#233;s par des liquides, et d&#233;couvrez les interventions appropri&#233;es pour rem&#233;dier &#224; ces probl&#232;mes.',
			'all-maintenance',

			'Belts-and-Hoses',
			'Les courroies et les flexibles',
			'Tous les faits importants sur l\'un des entretiens les plus souvent ignor&#233;s.',
			'all-maintenance',

			'Wiper-Blades',
			'Les balais d\'essuie-glace',
			'Tous les faits importants sur l\'un des entretiens les plus souvent ignor&#233;s.',
			'all-maintenance-services',

			'Brakes',
			'Les freins',
			'Reconnaissez les signes d\'avertissement d\'usure des freins et apprenez la diff&#233;rence entre les freins &#224; disque et les freins &#224; tambour.',
			'all-maintenance-services',

			'Headlamps',
			'Les phares',
			'D&#233;couvrez les types d\'ampoule et apprenez &#224; identifier les probl&#232;mes d\'alignement des phares pouvant &#234;tre dangereux.',
			'all-maintenance',

			'Suspension',
			'La suspension',
			'Identifiez les &#233;l&#233;ments importants de la suspension et reconnaissez les signes d\'usure.',
			'all-maintenance',

			'Exhaust-System',
			'L\'&#233;chappement',
			'Un &#233;chappement maintenu en bon &#233;tat peut sauver votre vie.',
			'all-maintenance'

			);
		}

		if(gwVideos != null) {
			// Make left nav
			var makeMenu="";
			var arrSize=gwVideos.length+1;

			var i;
			for(i=0; i<gwVideos.length-2; i=i+4)
			{
				if(indexurl_name.search('drivesmarter/safety-video') > -1)
				{
					if(gwVideos[i+3].search('safety') > -1)
					{			
						makeMenu=makeMenu+'<li class="'+gwVideos[i]+'"><a href="safety-video?id='+gwVideos[i]+'">'+gwVideos[i+1].replace(/-/g," ").replace(/%C2%AE/g,"&reg;")+'</a></li>';
					}
				}
				else if(indexurl_name.search('drivesmarter/services-video') > -1)
				{

					if(gwVideos[i+3].search('services') > -1)
					{
						makeMenu=makeMenu+'<li class="'+gwVideos[i]+'"><a href="services-video?id='+gwVideos[i]+'">'+gwVideos[i+1].replace(/-/g," ").replace(/%C2%AE/g,"&reg;")+'</a></li>';
					}
				}
				else if(indexurl_name.search('drivesmarter/maintenance-video') > -1)
				{
					if(gwVideos[i+3].search('maintenance') > -1)
					{
						makeMenu=makeMenu+'<li class="'+gwVideos[i]+'"><a href="maintenance-video?id='+gwVideos[i]+'">'+gwVideos[i+1].replace(/-/g," ").replace(/%C2%AE/g,"&reg;")+'</a></li>';
					}
				}
				else if(indexurl_name.search('drivesmarter/driving-video') > -1)
				{
					if(gwVideos[i+3].search('driving') > -1)
					{
						makeMenu=makeMenu+'<li class="'+gwVideos[i]+'"><a href="driving-video?id='+gwVideos[i]+'">'+gwVideos[i+1].replace(/-/g," ").replace(/%C2%AE/g,"&reg;")+'</a></li>';
					}
				}

				else if (indexurl_name.search('drivesmarter/seasonal-video') > -1)
				{
					if(gwVideos[i+3].search('seasonal') > -1)
					{		
						makeMenu=makeMenu+'<li class="'+gwVideos[i]+'"><a href="seasonal-video?id='+gwVideos[i]+'">'+gwVideos[i+1].replace(/-/g," ").replace(/%C2%AE/g,"&reg;")+'</a></li>';
					}
				}
				else if (indexurl_name.search('drivesmarter/summer-video') > -1)
				{
					if(gwVideos[i+3].search('summer') > -1)
					{
						makeMenu=makeMenu+'<li class="'+gwVideos[i]+'"><a href="summer-video?id='+gwVideos[i]+'">'+gwVideos[i+1].replace(/-/g," ").replace(/%C2%AE/g,"&reg;")+'</a></li>';
					}
				}
				
			}
		}

		if (indexurl_name.search('-video') > -1)
		{
			var videoID = gup('id');
			// build left nav
			$('#itemList').html('<style>.' + videoID + ' a{font-weight:bold; color:#CF2C0C}</style><ul id="tipsLeftNav" class="tabNav">'+makeMenu+'</ul>');
			// add video title and description
			$('#video-description h1#video-name').html(getVideoTitle(videoID));
			$('#video-description p#video-text').html(getVideoText(videoID));
		}
			
		// Videos link on terriary nav - videos are hardcoded so that it will also work from tips and articles pages.
		var path = location.pathname;
		if (path.indexOf("drivesmarter/seasonal") > -1){		
			if (getLanguage() == "fr"){			
				var videoLink = "/gm/french/services/goodwrench/drivesmarter/seasonal-video?id=Roadside-Safety-and-OnStar";
			}
			else {
				var videoLink = "/gm/english/services/goodwrench/drivesmarter/seasonal-video?id=Roadside-Safety-and-OnStar"; 
			}
			$('#contentNav li:last a').attr('href', videoLink);
		}
		else if (path.indexOf("drivesmarter/driving") > -1){
			if (getLanguage() == "fr"){			
				var videoLink = "/gm/french/services/goodwrench/drivesmarter/driving-video?id=Changing-A-Flat";
			} else {
				var videoLink = "/gm/english/services/goodwrench/drivesmarter/driving-video?id=Changing-A-Flat";
			}
			$('#contentNav li:last a').attr('href', videoLink);
		}
		else if (path.indexOf("drivesmarter/maintenance") > -1){
			if (getLanguage() == "fr"){
				var videoLink = "/gm/french/services/goodwrench/drivesmarter/maintenance-video?id=Checking-Your-Oil";
			}
			else {
				var videoLink = "/gm/english/services/goodwrench/drivesmarter/maintenance-video?id=Checking-Your-Oil";
			}
			$('#contentNav li:last a').attr('href', videoLink);
		}
		else if (path.indexOf("drivesmarter/services") > -1){		
			if (getLanguage() == "fr"){			
				var videoLink = "/gm/french/services/goodwrench/drivesmarter/services-video?id=Your-Tires";
			}
			else {
				var videoLink = "/gm/english/services/goodwrench/drivesmarter/services-video?id=Your-Tires";
			}
			$('#contentNav li:last a').attr('href', videoLink);
		}
		else if (path.indexOf("drivesmarter/safety") > -1){		
			if (getLanguage() == "fr"){
				var videoLink = "/gm/french/services/goodwrench/drivesmarter/safety-video?id=Roadside-Safety-and-OnStar";
			}
			else {
				var videoLink = "/gm/english/services/goodwrench/drivesmarter/safety-video?id=Roadside-Safety-and-OnStar";
			}
			$('#contentNav li:last a').attr('href', videoLink);
		}
		
		// On Drive Smarter landing pages, the Videos link should play the first video in the menu on the video page; this is the featured video 
		// except for Driving and Maintenance - I've made exceptions for those pages to play their first video.
		$('.teaser.last a.links').click(function(){
			var videoLink = $('.teaser.last p.intro a').attr('href');
			if(indexurl_name.search('drivesmarter/driving') > -1) {
				$('.teaser.last a.links').attr('href', indexurl_name + '-video?id=Roadside-Safety-and-OnStar');
			}
			else if (indexurl_name.search('drivesmarter/maintenance') > -1) {
				$('.teaser.last a.links').attr('href', indexurl_name + '-video?id=Your-Tires');
			}
			else if (videoLink) {
				$('.teaser.last a.links').attr('href', videoLink);
			}
		});	
		
		/*** Mark's code for Prev/Next video buttons ***/
		$(".next-video").click(function(event) {
			event.preventDefault(); // override default link action
			var numChildren = $("#tipsLeftNav").children("li").length;
			var count = 1;
			$("#tipsLeftNav").children("li").each(function() {
				if($(this).attr("class") == gup('id') ) {
					if(count < numChildren) {
						location.href = $(this).next().children("a").attr("href");
					}
					else {
						location.href = $(this).parent().children("li:first").children("a").attr("href");
					}
				}
				count ++;
			});
		});
		$(".prev-video").click(function(event) {
			event.preventDefault(); // override default link action
			var count = 1;
			$("#tipsLeftNav").children("li").each(function() {
				if($(this).attr("class") == gup('id') ) {
					if(count != 1) {
						location.href = $(this).prev().children("a").attr("href");
					}
					else {
						location.href = $(this).parent().children("li:last").children("a").attr("href");
					}
				}
				count ++;
			});
		});
	// VIDEO PLAYER END
	}
	
	var tabContainers = $('div.tabs > div.page');
	var tabLinks = $('div.tabs ul.tabNav li a');
	var tabButtons =$('div.buttons');
	tabContainers.hide().filter(':first').show();
	tabButtons.show();
	$('div.tabs ul.tabNav a').click(function () {
		tabContainers.hide();
		tabContainers.filter(this.hash).show();
		$('div.tabs ul.tabNav a').removeClass('selected');
		$(this).addClass('selected');
		return false;
	}).filter(':first').click();
	
	// change links color in the left navigation, when clicked on next or previos button
	$('div.tabs div.buttons a').click(function () {
		//var next_prev_link = this.href + "-link";
		var link_ancer = this.href.split("#");
		var selected_link = link_ancer[1];
		tabContainers.hide();
		tabContainers.filter(this.hash).show();
		$('div.tabs ul.tabNav a').removeClass('selected');
		$('.'+selected_link).addClass('selected');
		return false;
	});
	
	// show correct article when link clicked
	$('a.page_link').click(function () {
		var link_ancer = this.href.split("#");
		var selected_link = link_ancer[1];
		tabContainers.hide();
		tabContainers.filter(this.hash).show();
		$('div.tabs ul.tabNav a').removeClass('selected');
		$('.'+selected_link).addClass('selected');
 		$.scrollTo(0,0);
		return false;
	});

	// if linking to an article page (with left nav), scroll to the top of the page.
	if ($('#tipsLeftNav').is('.tabNav')){
		$.scrollTo(0,0);
	}
	// if already on an article page and going to next/previous article, scroll to the top of the page.
	$('.buttons a').click(function () {
		$.scrollTo(0,0);
	});
	
	// hide title tooltip on hover so English title (used for Ominiture) doesn't display on french page.
    $(".tabNav a").hover(
      function () {
		  this.htmlTitle = this.title;
		  gw_ominture_pagename = this.title;
		  this.title = "";
      }, 
      function () {
		if (this.htmlTitle) {
			this.title = this.htmlTitle;
		}
      }
    );
	// hide title tooltip on hover so English title (used for Ominiture) doesn't display on french page.
    $(".bottom-button a").hover(
      function () {
		  this.htmlTitle = this.title;
		  gw_ominture_pagename = this.title;
		  this.title = "";
      }, 
      function () {
		if (this.htmlTitle) {
			this.title = this.htmlTitle;
		}
      }
    );
		
	// only call if on the Goodwrench site.
	if (indexurl_name.indexOf('/services/goodwrench/') != -1) {
		loadArticlesVideo();
	};

// hightlight teasers on hover
	$(".teaser img").hover(
      function () {
        $(this).parent().parent().find('dt a').css('color', '#CF2C0C');
		$(this).parent().parent().find('dd a').css('color', '#CF2C0C');
      }, 
      function () {
        $(this).parent().parent().find('dt a').css('color', '#000');
		$(this).parent().parent().find('dd a').css('color', '#000');
      }
    );	
	$(".teaser dl").hover(
      function () {
		$(this).find('dt a').css('color', '#CF2C0C');
		$(this).find('dd a').css('color', '#CF2C0C');
      }, 
      function () {
        $(this).find('dt a').css('color', '#000');
		$(this).find('dd a').css('color', '#000');
      }
    );
	
// hightlight homepage teasers on hover
	$(".home-teaser img").hover(
      function () {
        $(this).parent().parent().find('dt a').css('color', '#CF2C0C');
		$(this).parent().parent().find('dd a').css('color', '#CF2C0C');
      }, 
      function () {
        $(this).parent().parent().find('dt a').css('color', '#000');
		$(this).parent().parent().find('dd a').css('color', '#000');
      }
    );	
	$(".home-teaser dl").hover(
      function () {
		$(this).find('dt a').css('color', '#CF2C0C');
		$(this).find('dd a').css('color', '#CF2C0C');
      }, 
      function () {
        $(this).find('dt a').css('color', '#000');
		$(this).find('dd a').css('color', '#000');
      }
    );
	
// highlight graphic input buttons (IE6)
	$('#tire_chooser input').hover(
      function () {
		$(this).css('background-position', '0 -22px');
		$(this).css('cursor', 'pointer');
      }, 
      function () {
        $(this).css('background-position', '0 0');
		$(this).css('cursor', 'default');
      }
    );
	$('#scheduleFormLanding	 input').hover(
      function () {
		$(this).css('background-position', '0 -22px');
		$(this).css('cursor', 'pointer');
      }, 
      function () {
        $(this).css('background-position', '0 0');
		$(this).css('cursor', 'default');
      }
    );	

// Tell a friend
	$('a#email img').click(function() {
		pageTAF();
		//return false;
	})
	$('a#email span').click(function() {
		pageTAF();
	})
	
// Sidebar Offers - AJAX (used on all pages but Regional Offers)
	// click button
	$('#currentOffers #submit-pc.ajax a.noArrButton').click(function(){	
		$('#error-sidebar-offers').empty();
		checkPostalCodeSideBar('ajax');
		return false;
	});
	// click/enter text input
	$('#submit-pc.ajax #postal-code-sidebar').click(function() {
		$(this).val('');
	}).keyup(function(e) {		
		if(e.keyCode == 13) {
			$('#error-sidebar-offers').empty();
			checkPostalCodeSideBar('ajax');
			return false;
		}
	});	
// Sidebar Offers - Form (only used on Regional Offers page)
	$('#currentOffers  #submit-pc.form a.noArrButton').click(function(){
		$('#error-sidebar-offers').empty();
		checkPostalCodeSideBar('form');
		return false;
	});
	$('#submit-pc.form #postal-code-sidebar').click(function() {
		$(this).val('');
	}).keyup(function(e) {
		if(e.keyCode == 13) {
			$('#error-sidebar-offers').empty();
			checkPostalCodeSideBar('form');
			return false;
		}
	});		
	
// Regional Offers main page
	$('#offers-regional a.noArrButton').click(function(){
		checkFormOffers();
		return false;
	});		
	
	$('a#first-tab,a#second-tab,a#third-tab,a#fourth-tab,a#fifth-tab').click(function(){
		if ( readCookie('pc') === null ) {
			checkFormOffers();
		}
		return false;
	});		
	
// On page load, get id & category url param and display correct offer
	var otherOffersContainers = $('div.other_offers');
	//var tabContainers = $('div.tabs > div.page');
	//var tabLinks = $('div.tabs ul.tabNav li a');
	
	var id_param = gup('id');
	var id_cat = gup('cat');
	if (id_cat != "" && id_cat != "Others") {
		switch(id_cat) {
			case 'Tires':
				id_offer = 'first';
				break;
			case 'Seasonalmaint':
				id_offer = 'second';
				break;
			case 'Brakes':
				id_offer = 'third';
				break;
			case 'Batteries':
				id_offer = 'fourth';
				break;	
			case 'Wiper':
				id_offer = 'fifth';
				break;						
			default:
				id_offer = '';
		}		
		// show offer based on category
		otherOffersContainers.hide();
		tabContainers.hide();			
		tabContainers.filter('#' + id_offer).show();
		$('div.tabs ul.tabNav a').removeClass('selected');	
		$('div.tabs ul.tabNav a').filter('#' + id_offer + '-tab').addClass('selected');
	}
	else if (id_cat == "Others") {
		// show offer based on id
		if (id_param != "") {
			otherOffersContainers.hide();
			tabContainers.hide();
			otherOffersContainers.filter('.' + id_param).show();
		}			
	}		

// Display Other offers
	$('div#other_offers_links ul.other_offers_links_list a').click(function () {
		tabContainers.hide();
		id_offer = $(this).attr('class');
		otherOffersContainers.hide();
		tabContainers.hide();
		$('div.tabs ul.tabNav a').removeClass('selected');				
		otherOffersContainers.filter('.' + id_offer).show();
		return false;
	});			

// Display button offers
	$('div.tabs ul.tabNav a').click(function () {
		otherOffersContainers.hide();
		tabContainers.hide();
		tabContainers.filter(this.hash).show();					
		$('div.tabs ul.tabNav a').removeClass('selected');
		$(this).addClass('selected');
		return false;				
	});

// Create RSS link based on postal code input - Sidebar
	$('#rss_feed a').click(function() {
		pc = $('#postal-code-sidebar').val();
		if (validatePostalCode(pc)) {
			if (gw_lang == "french") {
				$(this).attr('href', '/gm/french/services/goodwrench/offers/regional/rss?postalCode=' + pc);
			}
			else {
				$(this).attr('href', '/gm/english/services/goodwrench/offers/regional/rss?postalCode=' + pc);
			}
		}
		else {
			displayPostalCodeSideBarError();
			return false;
		}
	});

// Create RSS link based on postal code input - Offers page
	$('a.rssIcon').click(function() {
		pc = $('#postal-code-body').val();
		if (validatePostalCode(pc)) {
			if (gw_lang == "french") {
				$(this).attr('href', '/gm/french/services/goodwrench/offers/regional/rss?postalCode=' + pc);
			}
			else {
				$(this).attr('href', '/gm/english/services/goodwrench/offers/regional/rss?postalCode=' + pc);
			}
		}
		else {
			displayFormOffersError();
			return false;
		}
	});	

})

function getSidebarOffers(){
	$('#sidebarOffers').empty().html('<img id="ajax-loader" src="/images/goodwrench/common/ajax-loader.gif" /><br />');
	var  pcSubmit = $('#postal-code-sidebar').val();
	if (pcSubmit != "Postal Code" && pcSubmit != "Code Postal") {
		pcSubmit = pcSubmit.replace(/\s/,'').toUpperCase();
	}
	$.ajax({
		type: "GET",
		url: "/gm/" + gw_lang + "/services/goodwrench/offers/regional?actionType=getOffersSideBar",
		cache: "true",
		dataType: "json",
		data: {pc: pcSubmit},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$('#sidebarOffers').empty();
			//alert('Status: ' + textStatus + '; Error: ' + errorThrown);			
			if (gw_lang == "french") {
				$('#sidebarOffers').html('<p id="offers-msg">Nous sommes en train de mettre &#224; jour les offres dans ce code postal. Veuillez contacter votre concessionaires pour les offres les plus r&#233;centes.</p>');
			}
			else {
				$('#sidebarOffers').html('<p id="offers-msg">We are updating our offers. Please contact your dealer for the latest available offers.</p>');
			}
			
		},
		success: function(json){
			$('#sidebarOffers').empty();
			$.each(json.sidebaroffers,function(i,offer) {
				if (i < 5 && offer.title != "undefined" && offer.price != 'undefined'){
					var linkTitle;
					if (gw_lang == "french") {
						linkTitle = "Plus";
					}
					else {
						linkTitle = "More";
					}
					$('#sidebarOffers').append('<div class="mod sidebarOffers"><div class="mod-content"><div class="hd"><h5>' + offer.title + '</h5></div><div class="bd"><p><span>' + offer.price + '</span></p></div><div class="ft"><p class="ft-content"><a href="' + offer.url + '">' + linkTitle + '</a></p></div></div></div>');
				}
			});
		}
	});	
}

function validatePostalCode (postalCode) {
	if (postalCode != "Postal Code" && postalCode != "Code Postal") {
		var pc = postalCode.replace(/\s/,'').toUpperCase();
	}
	var today = new Date();
	today.setTime(today.getTime());
	var cookieExpiresDate = new Date (today.getTime() + (30*24*60*60*1000));
	var pcRegExp = /(^\D{1}\d{1}\D{1}\s?\d{1}\D{1}\d{1}$)/;
	if (pcRegExp.test(pc)) {
		$("#postal-code-body").val(pc);
		$("#postal-code-sidebar").val(pc);
		setCookie("pc",pc, cookieExpiresDate, "/");
		return true;
	} 
	else {
		return false;
	}
}

function checkPostalCodeSideBar(method) {
	var  postalCode=$('#postal-code-sidebar').val();
	if(validatePostalCode(postalCode)==true)
	{
		if (method == "ajax") {
			getSidebarOffers();
		}
		else if (method == "form") {
			$('form#tire_offer_sidebar').submit();
		}
	}
	else{
		displayPostalCodeSideBarError();
		return false;
	}
}

function displayPostalCodeSideBarError() {
	if (getLanguage() == 'fr') {
		pcErrorMsg = 'Veuillez entrer un code postal valide ';
		pcEg = '(p. ex. : A1A 1A1)';
	}
	else {
		pcErrorMsg = 'Please enter a valid postal code ';
		pcEg = '(i.e. A1A 1A1)';
	}
	//$('#sidebarOffers').html('<div id="error-sidebar-offers"><p>' + pcErrorMsg + '</p><br/></div>');
	$('#error-sidebar-offers').html('<p>' + pcErrorMsg + '</p><p>' + pcEg + '</p>');
}

function checkFormOffers() {
	var postalCode = $('#postal-code-body').val();
	if(validatePostalCode(postalCode)==true) {
		$("form#tire_offer").submit();
	}
	else {
		displayFormOffersError() ;
		return false;
	}	
}

function displayFormOffersError() {
	if (getLanguage() == 'fr') {
		pcErrorMsg = 'Veuillez entrer un code postal valide (p. ex. : A1A 1A1)';			
	}
	else {
		pcErrorMsg = 'Please enter a valid postal code (i.e. A1A 1A1)';
	}
	$('#error_offers').html(pcErrorMsg);
}

function getLanguage() {
	var thisURL = location.toString();
	var tfLang;
	if ((thisURL.indexOf('/english') != -1) || (thisURL.indexOf('en_CA') != -1) || (thisURL.indexOf('lang=en') != -1)) { 
		tfLang = "en";
	}
	else if ((thisURL.indexOf('/french') != -1)|| (thisURL.indexOf('fr_CA') != -1) || (thisURL.indexOf('lang=fr') != -1)) { 
		tfLang = "fr"; 		
	}
	return tfLang;
}

// get URL parameters
function gup(name)
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null ) {
		return "";
	}
	else {
		return results[1];
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

//*** TAF CODE begin *****//
// Write a cookie value
function setCookie(name, value, expires, path, domain, secure) {
	domain = location.toString();
	if (domain.indexOf('.gm.ca') != -1){
		if(navigator.appName.indexOf('Microsoft') != -1){
			domain = "";
		}
		else{
			domain = ".gm.ca";
		}
	}
	else if(domain.indexOf('.mminteractive.com') != -1){
		if(navigator.appName.indexOf('Microsoft') != -1)
			domain = "";
		else{
			domain = ".mminteractive.com";
		}
	}
	else{
		domain ="";
	}
	var curCookie = name + '=' + escape(value) + ((expires) ? '; expires=' + expires.toGMTString() : '') + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + ((secure) ? '; secure' : '');
	document.cookie = curCookie;
}

// Retrieve a named cookie value
function getCookie(name) {
	// There is something very flakey with this function. Probably explains why at some unknown time some unknown person created the function get_cookie to be found later in this file. I'm not trashing this function because I think it does work in certain contexts and is probably being used, but it doesn't seem to function predictably. I wouldn't use it if I were you. <3 JRB
	// I think I have fixed this flakeyness, seems fine now - PJ
	
	var dc = document.cookie;

	// find beginning of cookie value in document.cookie
	var prefix = name + "=";
	
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	}
	else begin += 2;

	// find end of cookie value
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;

	// return cookie value
	return unescape(dc.substring(begin + prefix.length, end));
}

// Delete a named cookie value
function deleteCookie(name, path, domain) {
	var value = getCookie(name);
	if (value != null) document.cookie = name + '=' + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + '; expires=Thu, 01-Jan-70 00:00:01 GMT';
	return value;
}

// Test for cookie support
function supportsCookies(rootPath) {
   setCookie('checking_for_cookie_support', 'testing123', '', (rootPath != null ? rootPath : ''));
   if (getCookie('checking_for_cookie_support')) return true;
   else return false;
}

// function for email page icon, uses escape method to trap multiple instances of ?
var divCode = '';
function pageTAF() {

	var url = escape(document.location.href);
	var dotdo = url.indexOf(".do")
	if (dotdo >= 0 && (document.referrer&&document.referrer!="")) {
		// TAF location must be based on referrer 
		if (document.referrer.indexOf(".do") >= 0)
		{
			url = get_cookie("dotdoref");
			document.location = "/servlet/pageTAF?page=" + url + '&div=' + divCode;
		}
		else {
			setCookie('dotdoref', document.referrer, '', '/');
			document.location = "/servlet/pageTAF?page=" + document.referrer + '&div=' + divCode;
		}
	}
	else {
		deleteCookie("dotdoref");
		document.location = "/servlet/pageTAF?page=" + url + '&div=' + divCode;
	}
}
//*** TAF CODE end *****//

//*** GLOSSARY CODE begin *****//
function loadGlossary(){
    $("a.glossaryItem").css('display','inline');
    $('a.glossaryItem').cluetip({
          hoverClass: 'highlight',
          sticky: false,
          closePosition: 'top',
          showTitle: false,
          waitImage: true,
          closeText: ''
    });
}

$(window).load(function () {
	if (!/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Opera/x.x or Opera x.x (ignoring remaining decimal places);
		if ($('.glossary').length > 0) {
			$(".glossary").each(function (i) {
				var glossaryHTML = $(this).html();
				var thisID = $(".glossary").attr('class');
				thisID = thisID.replace(/glossary g_2_/,'');
				thisID = "/gm/"+gw_lang+"/getxmlcontent?section=2&amp;id="+thisID;                           
				$(this).replaceWith('<span style="white-space:nowrap;"><a class="glossaryItem" href="'+thisID+'" rel="'+thisID+'"><img src="/images/common/glossaryIcon.gif" alt="i" /></a>'+glossaryHTML+'</span>');
			});		   

			$.ajax({
				type: "GET",
				url: "/js/common/cluetip/jquery.cluetip.js",
				dataType: "script",
				cache: true,
				timeout: 2000,
				success: function(msg){
					setTimeout ( "loadGlossary()", 1000 ); 
				}
			});
		}
	}
});
//*** GLOSSARY CODE end *****//

function showTips() {
	if(indexurl_name.search('/tires/') > -1)
	{
		//Tires Tips
		var ar = new Array(
		'Replacement Tires',
		'Manufacturers provide detailed specifications on each replacement tire, making tire selection easier.',
		'Look for the symbol',
		'If the tire is not marked with the "Mountain Snowflake Symbol", it is not an approved winter tire.',
		'Performance Tires',
		'Always consult the manufacturer\'s specifications and guidelines on performance tire use.',
		'Tire Failure',
		'Overloading a truck tire can cause excessive heat buildup, leading to tire failure.',
		'Tire Wear',
		'Tread wear grades are only valid when comparing tires from the same manufacturer.',
		'Register Your New Tires',
		'When you buy new tires, fill in and return your tire registration form. In the event of a recall, the manufacturer will contact you. In many cases, you can register online.',
		'Getting Maximum Traction',
		'For maximum traction in wet or snow conditions, replace tires before they reach minimum tread depth.',
		'Handling and Safety',
		'Always install the same type of tire on all four wheels to ensure proper handling and safety.',
		'New Tires',
		'Be careful when you take your new tires on the road. Every tire requires a break-in period during which handling and traction will be slightly compromised.',
		'Tire Pressure',
		'Reducing tire pressure to increase traction doesn\'t work. Driving on under-inflated tires is dangerous any time of year.',
		'Tire Damage',
		'In the event of striking an object on the road, find a safe area to stop and inspect your vehicle. Report any noticeable damage to a GM Goodwrench technician.',
		'Rotating Your Tires',
		'After rotation of your tires, adjust front and rear tire pressure as indicated on the Tire-Loading Information label.'
		)
	}
	var now = new Date()
	var sec = now.getSeconds()
	var arr_num=sec % (ar.length+1);
	if((arr_num%2)==1){arr_num=arr_num+1;}
	if(arr_num==ar.length){arr_num=0;}
	if (document.getElementById('tipsTitle'))
	{
		document.getElementById('tipsTitle').innerHTML=ar[arr_num];
		document.getElementById('tipsLine').innerHTML=ar[arr_num+1];
	}
}

// TODO: is function this necessary?	
// Menu slider for Drive smart
var leftMenuNumber;
function startLeftMenu()
{
	tipsLeftNav = document.getElementById("tipsLeftNav");
	items = tipsLeftNav.getElementsByTagName("h4");
	leftMenuNumber=items.length;
	var i=0;
	for(i=2; i < leftMenuNumber+1; i++)
	{	
		tableName="t"+i;
		document.getElementById(tableName).style.display="none";
	}
}
						
// left nav tabs for Articles and Video - used for bookmarking articles (Alexandre)
var tabContainers;
var tabLinks;
function loadArticlesVideo()
{
	var what_url=document.location.href;
	if(what_url.search('#') > -1)
	{
		var what_url_split=what_url.split("#");
		var what_url_id=what_url_split['1'];
		if (what_url_id) {
			var tabContainers = $('div.tabs > div.page');
			tabContainers.hide();								
			document.getElementById(what_url_id).style.display="block";
			$('div.tabs ul.tabNav a').removeClass('selected');
			$('.'+what_url_id).addClass('selected');
		}								
		return false;
	}
}

// pars url for video description
var qsParm = new Array();
function qs() 
{
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) 
	{
		var pos = parms[i].indexOf('=');
		if (pos > 0) 
		{
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
		}
	}
}

// omniture image for articles
function writeOmniture(obj) 
{
	// do nothing...
}	

// VIDEO PLAYER FUNCTIONS BEGIN
function getVideoTitle(id) {
	if (gwVideos != null) {
		for(i=0; i < gwVideos.length-2; i=i+4) {
			if (gwVideos[i] == id){
				return gwVideos[i+1];
			}
		}
	}
}			
function getVideoText(id) {
	if (gwVideos != null) {
		for(i=0; i < gwVideos.length-2; i=i+4) {
			if (gwVideos[i] == id){
				return gwVideos[i+2];
			}	
		}
	}
}
function getVideoCategory(id) {
	if (gwVideos != null) {
		for(i=0; i < gwVideos.length-2; i=i+4) {
			if (gwVideos[i] == id){
				return gwVideos[i+3];
			}		
		}
	}
}	
// VIDEO PLAYER FUNCTIONS END

	$(document).ready(function() {
	$(".hover").hover(
		 function()
		 {
		  this.src = this.src.replace("_off.","_on.");
		 },
		 function()
		 {
		  this.src = this.src.replace("_on.","_off.");
		 }
		);
		
		// prevent addition of tooltip on the word traction
		$('span').removeClass('glossary g_2_8');
		
		
	});


