// Hack for IE (i.e. no firebug) to catch any console.log() left behind by mistake
//try { console.assert(1); } catch(e) { console = { log: function() {}, assert: function() {} } }
var lang 		= (document.location.href.indexOf("/french/") != -1) ? "fr" : "en";
var language	= (lang == "fr") ? "french" : "english";
var cookieOptions = { path: '/', expires: 10 };

$(function(){

	/*============= onLoad ==============*/
	setBoxOrder(); // set the order and open/closed state for each box
	setBoxState(); // list of closed box IDs
	setLocateDealerBtn(); // set the href 
	readPcCookie(); // read cookie and populate .PostalCode
	$("#slider").skubeSlider({ // init main Slider
		speed: 	400,
		auto:	true,
		pause:	4000,
		continuous:	false, 
		prevText: 	'',
		nextText: 	''
	}); 
	$("#slider_apps").skubeSlider({ // init main Slider
		numeric:false,
		controlsFade: false,
		continuous:	true, 
		nextId: "nextApps",
		prevId: "prevApps",
		prevText: 		'',
		nextText: 		''
	}); 
	
	
	 
	// Set My Vehicle Dropdown to division
	if (division != "corporate") {
		//var myDivision = division.toUpperCase();
		//$("select#makeBanner option").removeAttr("selected");
		//$("select#makeBanner option[value="+myDivision+"]").attr("selected","selected");
		$("select#makeBanner").hide();
	}

	// Set maintenance button in banner (all dropdowns must be set to go straight to content)
	$("#btn_maint").click(function(){
		//division if make dropdown is hidden
		var make = ($("select#makeBanner:visible").length == 0) ? division : $("select#makeBanner option:selected").val();
		var model = $("select#modelBanner option:selected").val();
		var year = $("select#yearBanner option:selected").val();
		var myCode = year+'_'+make+'_'+model;
		var myADV;
		myCode = myCode.toLowerCase();
		// if any is blank, then all should be blank
		if (make == "" || model == "" || year == "") { myCode = "";}
		myADV = (lang=="fr") ? "98053" : "98052";
		document.location.href = '/gm/'+language+'/owner_centre/'+division+'/resources/schedule/model?vehicle='+myCode+'&adv='+myADV;
		return false;
	});
	

	/* stupid hack to target home */
	if (bucket == "home") {
		// Automatically open drawer for discontinued brands
		if (division == "corporate" || division == "pontiac" || division == "saab" || division == "saturn" || division == "hummer") {
			$("#ocDrawer #btn_drawer").parent('div').stop().animate({top:"178px"},{queue:false, duration: 500}).addClass('open');
			// tweak bg
			$('#contentOuterFrame').css('background-position', '1px 0');
			$('#console').css('background','none')
		}
	}

	/* Set main nav states */
	$('#nameplateNav li[id*='+bucket+']').addClass('selected');
	
	/* Set Services nav states */
	if (bucket == "services") {
		$('#buttons a').removeClass('on');
		var myURL = document.location.href;
		if (myURL.indexOf("/services/overview") != -1) {
			$('#buttons a').eq(0).addClass('on');	
		} else if (myURL.indexOf("/services/maintenance") != -1) {
			$('#buttons a').eq(1).addClass('on');	
		} else if (myURL.indexOf("/services/onstar") != -1) {
			$('#buttons a').eq(2).addClass('on');	
		} else if (myURL.indexOf("/services/gmcard") != -1) {
			$('#buttons a').eq(3).addClass('on');	
		} else if (myURL.indexOf("/services/gmpp") != -1) {
			// not in cadillac
			$('#buttons a').eq(4).addClass('on');	
		}
	}
	/* Set Owner Resources nav states */
	if (bucket == "resources") {
		$('#buttons a').removeClass('on');
		var myURL = document.location.href;
		if (myURL.indexOf("/resources/overview") != -1) {
			$('#buttons a').eq(0).addClass('on');	
		} else if (myURL.indexOf("/resources/manuals") != -1 || myURL.indexOf("/resources/dispVehicle") != -1  || myURL.indexOf("/resources/dispManualInfo") != -1 ) {
			$('#buttons a').eq(1).addClass('on');
			// TODO: figure out a way to set the first dropdown to make
			// Issue: recursive page loads
			//var myProperDivision = division.toUpperCase();
			//setTimeout("$('#selectmenues select[@name=makeName] option[value="+myProperDivision+"]').attr('selected','selected').change(function(){onOCMakeNameChanged();});",100);
		} else if (myURL.indexOf("/resources/schedule") != -1) {
			$('#buttons a').eq(2).addClass('on');	
			// Also, set schedule make to division only if not going to specific (i.e. ?vehicle=2010_chevrolet_avalanche)
			if (ParseQueryString("vehicle") == "") {
				var myProperDivision = division.toProperCase();
				if (division == "gmc" || division == "hummer") {
					myProperDivision = division.toUpperCase();
				}
				setTimeout("$('select#make option[value="+myProperDivision+"]').attr('selected','selected'); $('#make').change();",100);
			}

		} else if (myURL.indexOf("/resources/leaseend") != -1) {
			$('#buttons a').eq(3).addClass('on');	
		} else if (myURL.indexOf("/resources/financing") != -1) {
			$('#buttons a').eq(4).addClass('on');	
		} else if (myURL.indexOf("/resources/warranty") != -1) {
			$('#buttons a').eq(5).addClass('on');	
		}
	}
	
	/* Set Owner Resources nav states */
	if (bucket == "ownerstories") {
		$('#buttons a').removeClass('on');
		var myURL = document.location.href;
		if (myURL.indexOf("/ownerstories/overview?winner") != -1) { //Winner page for past contest
			$('#buttons a').eq(2).addClass('on');	
		} else	if (myURL.indexOf("/ownerstories/overview") != -1) {
			$('#buttons a').eq(0).addClass('on');	
		}  else if (myURL.indexOf("/ownerstories/rules") != -1) {
			$('#buttons a').eq(1).addClass('on');	
		}  else if (myURL.indexOf("/ownerstories/archive") != -1) {
			$('#buttons a').eq(2).addClass('on');	
		}
	}

	// Main Drawer Open/Close
	$('#ocDrawer #btn_drawer').click(function(){
		var myTop = $('#ocDrawer').css('top');
		var drawerOpen, drawerClose; // since brand nameplates may vary
		if (division == 'chevrolet') {
			drawerOpen = '208px';
			drawerClose = '-82px';
		} else { // default Corporate
			drawerOpen = '178px';
			drawerClose = '-122px';
		}
		
		//SC vars
		var s = s_gi('gmcanadacom');
		var o = $("#ocDrawer");
		
		if (myTop < '0px' ) { // assume drawer is in closed position, so open
			$(this).parent('div').stop().animate({top:drawerOpen},{queue:false, duration: 500}).addClass('open');
			//SC tracking
			s.tl(o,'o','Owner Centre Online Site '+ bucket + ' ' + division + ' overview - tools bar - open'); 
		} else { // must be open, so close drawer
			$(this).parent('div').stop().animate({top:drawerClose},{queue:false, duration: 500}).removeClass('open');
			//SC tracking
			s.tl(o,'o','Owner Centre Online Site ' + bucket + ' ' + division + ' overview - tools bar - close'); 		
		}
	});
	
	// All Boxes (Side console and main)
	$('div.box>.header').click(toggleConsole);			
	$('div.box>.header, div.box_open>.header').hover(function(){
		$(this).toggleClass('hover');
	}, function(){
		$(this).toggleClass('hover');
	});
	

	
	// Connect Upside-down Tabs (complicated since IE6 doesn't support multiple selectors)
	$('#bx_connect .tabs li').click(function(){
		if ( !$(this).hasClass('.on,.first_on,.last_on') ) { // as long as not clicking on already showing tab
			$('#bx_connect .tabs li').removeClass('on').removeClass('first_on').removeClass('last_on');
			$('#bx_connect .tabs li:last').addClass('first');
			$('#bx_connect .tabs li:first').addClass('last');
			var myIndx = $('#bx_connect .tabs li').index(this);
			if ( myIndx == 0) { // last since reversed floated
				$(this).removeClass('last').addClass('last_on');
			} else if ( myIndx == $('#bx_connect .tabs li').length - 1 ) { // first since reversed floated
				$(this).removeClass('first').addClass('first_on');
			} else {
				$(this).addClass('on');
			}
			// display content
			// reverse the number since tabs are floated right
			myIndx = ($('#bx_connect .tabs li').length - myIndx);
			$('#tab01_content, #tab02_content, #tab03_content, #tab04_content').hide();
			$('#tab0'+myIndx+'_content').show();
		}
		return false;
	});
	
	
	//Open the last selected tab for the Mobile Apps section
	if($.cookie('lastapptab')){ //If cookie exists
			var tabname=$.cookie('lastapptab'); //read the value of the cookie
			
			if( !$('#'+tabname).hasClass('.first_on')){ //if this is not the first tab
				
				//Remove the first_on class from first tab
				$('#bx_apps .tabs li').removeClass('first_on');
				
				//check if this is the last tab
				if($('#'+tabname).hasClass('.last')){
				
					//If this is the last tab then change the class to last_on
					$('#'+tabname).addClass('last_on').removeClass('last');
					
				}else{
					$('#'+tabname).addClass('on');
				}
				
				//Add the class first to the first tab
				$('#bx_apps .tabs li:last').addClass('first');
				
				//**Show the corresponding content for the selected tab**	
				//First hide all the tab contents
				$('#tabs01_content, #tabs02_content, #tabs03_content, #tabs04_content').hide();
				
				//Get the tab index
				if(tabname=='iphone'){
					tabIndx=1;
				}else if(tabname=='blackberry'){
					tabIndx=2;
				}else if(tabname=='android'){
					tabIndx=3;
				}else{
					tabIndx=4;
				}
				
				//Show the content for this tab
				$('#tabs0'+tabIndx+'_content').show();
			}
	}
	
	
	
	// Mobile Apps Upside-down Tabs (complicated since IE6 doesn't support multiple selectors)
	$('#bx_apps .tabs li').click(function(){
		if ( !$(this).hasClass('.on,.first_on,.last_on') ) { // as long as not clicking on already showing tab
			$('#bx_apps .tabs li').removeClass('on').removeClass('first_on').removeClass('last_on');
			$('#bx_apps .tabs li:last').addClass('first');
			$('#bx_apps .tabs li:first').addClass('last');
			var myIndx = $('#bx_apps .tabs li').index(this);
			if ( myIndx == 0) { // last since reversed floated
				$(this).removeClass('last').addClass('last_on');
			} else if ( myIndx == $('#bx_apps .tabs li').length - 1 ) { // first since reversed floated
				$(this).removeClass('first').addClass('first_on');
			} else {
				$(this).addClass('on');
			}
			
			//set cookie to remember which tab was last clicked
			$.cookie("lastapptab", null);//Reset cookie to null			
			if (!($.browser.msie && parseFloat($.browser.version) < 8)) { //If not IE6 and IE7
				var currentTab=$(this).attr("id");	
				$.cookie("lastapptab", currentTab, { expires: 7, path: '/' }); //Expires in 7 days and is applicable for the whole domain
			}
			
			// display content
			// reverse the number since tabs are floated right
			myIndx = ($('#bx_apps .tabs li').length - myIndx);
			$('#tabs01_content, #tabs02_content, #tabs03_content, #tabs04_content').hide();
			$('#tabs0'+myIndx+'_content').show();
		}
		return false;
	});
	
	
	
	
		
		
	$(window).load(function () {
		$.ajax({
			type: "GET",
			url: "/js/owner_centre/oc.cluetip.apps.js",
			dataType: "script",
			success: function(){
				if (language == "french") {
					var closeTxt='x fermer';
				}else{
					var closeTxt='x close';
				}
				$('a.inrixtraffic').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipark').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.atmhunter').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.shazam').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.mychevrolet').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadmychevrolet').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.bbmychevrolet').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidmychevrolet').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.gasbuddy').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadgasbuddy').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.bbgasbuddy').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidgasbuddy').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.travelcity').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadtravelcity').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.bbtravelcity').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidtravelcity').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.flixster').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadflixster').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.bbflixster').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidflixster').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.yelp').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.bbyelp').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidyelp').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadyelp').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.mybuick').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadmybuick').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidmybuick').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.mygmc').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadmygmc').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidmygmc').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.mycadillac').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadmycadillac').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidmycadillac').cluetip({closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.bbatmhunter').cluetip({leftOffset:-80, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.bbshazam').cluetip({leftOffset:-80, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidinrixtraffic').cluetip({leftOffset:-170, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidshazam').cluetip({leftOffset:-170, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadcruze').cluetip({leftOffset:-170, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadshazam').cluetip({leftOffset:-170, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadtripadvisor').cluetip({leftOffset:-170, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadweathereye').cluetip({leftOffset:-170, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.ipadonstar').cluetip({leftOffset:-170, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.onstar').cluetip({leftOffset:-170, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				$('a.droidonstar').cluetip({leftOffset:-170, closePosition: 'title', closeText:closeTxt, local:true, activation: 'click', width: 50});
				}
			});
		
		$('#bx_apps .header').click(function() {
			  $('#cluetip').hide();
			});

		
		$('#bx_apps li').click(function() {
			  $('#cluetip').hide();
			});
	
	});
		
		
		
	
/*
	// 
	$('#bx_connect .tab li a').click(function(){
		var myPos = $('#bx_connect .tab li a').index(this) + 1;
		// hide all #tabXX_content, show the one clicked
		$('#tab01_content, #tab02_content').hide();
		$('#tab0'+myPos+'_content').show();
		// set 'on' class to tab and following divider
		$(this).parent().siblings('li').removeClass('on').removeClass('on_prev');
		$(this).parent().addClass('on').next().addClass('on');
		$(this).parent().prev().addClass('on_prev');
		return false;
	});
*/

	// toggle tab content for What's New box
	$('#bx_whats_new .nav li').click(function(){
		$('#bx_whats_new .nav li').removeClass('on');
		$(this).addClass('on');
		$('#veh01,#veh02,#veh03,#veh04').hide();
		var myPos = $('#bx_whats_new .nav li').index(this) + 1;
		$('#veh0'+myPos).show();
	}).hover(function(){
		$(this).children('img').css('opacity','0.8');
	},function(){
		$(this).children('img').css('opacity','1');
	});

	
	// FAQ Tabs (complicated since IE6 doesn't support multiple selectors)
	$('#content-faq .tabs li').click(function(){
		if ( !$(this).hasClass('.on,.first_on,.last_on') ) { // as long as not clicking on already showing tab
			$('#content-faq .tabs li').removeClass('on').removeClass('first_on').removeClass('last_on');
			$('#content-faq .tabs li:last').addClass('first');
			$('#content-faq .tabs li:first').addClass('last');
			var myIndx = $('#content-faq .tabs li').index(this);
			if ( myIndx == 0) { // last since reversed floated
				$(this).removeClass('last').addClass('last_on');
			} else if ( myIndx == $('#content-faq .tabs li').length - 1 ) { // first since reversed floated
				$(this).removeClass('first').addClass('first_on');
			} else {
				$(this).addClass('on');
			}
			// display content
			$('.accordion').hide();
			// reverse the number since tabs are floated right
			myIndx = ($('#content-faq .tabs li').length - myIndx);
			$('.content .accordion').eq(myIndx-1).fadeIn().children(".ui-accordion-content-active").css("display","none").removeClass(".ui-accordion-content-active");
			// close the accordion
			return false;
		}
	});

	
	// jQuery UI Sortable for re-arranging console boxes
	$('#console').sortable({
		opacity: 0.7,
		revert: true,
		scroll: true,
		containment: "parent",
		start: function(e) {
			// remove click handler so click event doesn't fire after drop
			$("#console dl.box dt.dt, #console .box .header ").unbind("click");
		},
		stop: function(e) {
			// reattach the item click handler
			$("#console dl.box dt.dt, , #console .box .header").click(toggleConsole);
			// Save order to a cookie			
			var consoleArr = $('#console').sortable('toArray');
			$.cookie('oc_box_order', consoleArr, cookieOptions);
			// remove hover from titles bug
			$("#console .box .header").removeClass("hover");
		}
	});
		
	
	// Live chat button
	$('#bx_live_chat a.btn, #live_chat, #btn_live_chat, .btn_live_chat').click(function(){
		if (language == "french") {
			window.open('https://www.chat.gm.ca/netagent/gm_cimlogin.aspx?questid=995A6FEE-0743-49C8-A2BE-D711E94ECD73&portid=99966668-740D-4506-9F88-0B6BEDD6849E&nareferer='+escape(document.location),'_blank','resizable= yes,width=581,height=437,scrollbars=yes');
			} else {
			window.open('https://www.chat.gm.ca/netagent/gm_cimlogin.aspx?questid=374502E7-C2BE-4A92-8769-01F6CA1241BB&portid=CB60220E-12A5-4130-A46E-16CAA5D0677E&nareferer='+escape(document.location),'_blank','resizable= yes,width=581,height=437,scrollbars=yes');
		}
		return false;
	}); 
	
	// Accordion - re-purposed from motion april 22 10am
	// initialize accordion if necessary, implement deeplinking using query string, and add icons to right side of accordion headers 
	if ($('.accordion').length > 0) {
			
		var params = {};
		var accordion_index;
		var anchor = decodeURI(location.href); //.split('#').pop();
		var accordion_count = $(".accordion").find("h3").length;
		
		// browser sniffing considered harmful, but opera doesn't like long accordions with autoHeight: false
		var doAutoHeight = false;
		if(navigator.userAgent.indexOf('Opera/9') != -1 && accordion_count > 5) {
			doAutoHeight = true;
		}
		// ditto: firefox won't deeplink correctly to long accordions
		if (navigator.userAgent.indexOf('Firefox') != -1 && anchor != '') {
			var anchorOffset = $(".accordion h3 a[name$='"+anchor+"']").offset();
			window.scroll(0, anchorOffset.top);
		}
		if(accordion_count > 1) {
			$(".accordion").accordion({
				header: "h3",
				icons: { 'header': 'ui-icon-triangle-1-s', 'headerSelected': 'ui-icon-triangle-1-n' },
				autoHeight: doAutoHeight,
				collapsible: true
			}).bind('accordionchange', function(event, ui) {
				var newHeaderOffset = ui.newHeader.offset();
				if($(ui.newHeader).attr('class')){
					var anchorName = $(ui.newHeader).attr('class');
					anchorName = anchorName.split(" ");
					window.location.hash = "#" + anchorName[0];
					window.scroll(0, newHeaderOffset.top);
				}
			})
			.find('h3').each(function(i) {
				if ($(this).hasClass('.ui-state-active')) {
					$(this).append('<span class="ui-icon ui-icon-triangle-1-n" style="right:0.5em; left:auto"></span>');
				} else  {
					$(this).append('<span class="ui-icon ui-icon-triangle-1-s" style="right:0.5em; left:auto"></span>');
				}
			});

			// close all accordions at startup
			$(".accordion").accordion("activate" , false );
			
			// set anchor to currently selected accordion
			$('#accordion1 h3 > a').each(function(i) {
				if ($(this).parent('.ui-state-active')) {
					anchor = $(this).attr('name');
					accordion_index = i;
				}
			});			
		}
	}	
	

	
	// highlight table rows
	$('table#event-items tbody tr:odd').addClass('odd');
	$('table#event-items tbody tr:even').addClass('even');

	// Character count for Comments form body.
	$('textarea#comment').keydown( function() {
		charCounter(document.getElementById('comment'), document.getElementById('char-count'), 1000);
	});
	$('textarea#comment').keyup( function() {
		charCounter(document.getElementById('comment'), document.getElementById('char-count'), 1000);
	});
	
 	
	// Archive links
	$('.content .archive:gt(0)').hide(); // hide all years after first (or zero based index)
	$('#years li a').click(function(){
		if ( !$(this).parent().hasClass('.selected') ) { // as long as not already on
			var myIndx = $('#years li a').index(this);
			$('#years li').removeClass('selected');
			$('.content .archive:visible').slideUp(800,function(){
				$('.content .archive:eq('+myIndx+')').show(400);
			});
			$('#years li:eq('+myIndx+')').addClass('selected');
		}
		return false;
	});
	

	// Find Dealer Form - Format PC and Submit Form
	$('.findDealerForm a.btn').click(function(){
		var pc = formatPostalCode($(this).siblings().find('input[name=PostalCode]').val());
		findDealer(pc);
		return false;
	})
	// Handle Submission through default Enter w/ one form behaviour
	$('.findDealerForm').submit(function() {
		var pc = formatPostalCode($(this).find('input[name=PostalCode]').val());
		findDealer(pc);
		return false;
	});
	
	// Handle dropdown submission for TON console
	$("#bx_ton #btn_TON").click(function(){
		// go to value indicate in select
		var myVal = $("#select_TON option:selected").val();
		if (myVal != "") {
		document.location.href = myVal;
		}
		return false;
	});
	
	// Clear Postal Code inputs when clicking into
	$("input.PostalCode").focus(function(){
		$(this).val("");
	});
	
	
	// TEMP Debug
	$('#debugJava').hover(function(){
		$(this).stop().animate({bottom:'0px'},{queue:false, duration: 500}).addClass('open');
	}, function(){
		$(this).stop().animate({bottom:'-145px'},{queue:false, duration: 500}).addClass('open');
	});
	
	//divNav IE6 fix for dropdown burn-thru
	if($.browser.msie && parseFloat($.browser.version) < 7){
		$("#divNav").hover(function(){
			$("select").css("visibility","hidden");
		},function(){
			$("select").css("visibility","visible");
		})
	}


    // Close all open right-nav console boxes first time in..
    if (!$.cookie('oc_box_state')) {
        setCookie("consoleItems", getConsoleItems(), "", "/gm");    // consoleItems is bacially an 'ignore-list' for later
        $('#console>[id^=bx_]>.content:visible').siblings('.header').click();
    }
    else if ($.cookie('consoleItems')) {
        // Check visible panels for any new items: close and add to ignore-list of encountered items.
        arrItems = $.cookie('consoleItems').split(",");
        $('#console>[id^=bx_]>.content:visible').parent().each(function () {
            if ($.inArray(this.id, arrItems) == -1) {
                //console.log(this.id);
                setCookie("consoleItems", $.cookie('consoleItems') + ',' + this.id, "", "/gm");
                $('#' + this.id + '>.header').click();
            }
        });
    }
	
})

/*=============FUNCTIONS==============*/

// Get the current visible right nav console items.
// Used to help close items first time in, and opened items for diff divisions.
function getConsoleItems() {
    items = "";
    $('#console>[id^=bx_]:visible').each(function () {
        items += this.id + ",";
    });
    return items.slice(0, -1);
}

// Open/Close All Boxes
function toggleConsole() {
	var isClosed = $(this).parent().hasClass('closed');
	if( isClosed ) { // open it
		$(this).next().slideDown('fast').parent().removeClass('closed');
	} else { // close it
		$(this).next().slideUp('fast').parent().addClass('closed');
	}
	var myId = new Array( $(this).parent().attr('id') );
	if(!isClosed) { // i.e. has just been closed above, so save to cookie
		if( $.cookie('oc_box_state') ) { // add to existing cookie, if exists
			var tempArr = $.evalJSON( $.cookie('oc_box_state') );
			//console.log(typeof tempArr + ' ' + tempArr.length + ' ' + tempArr);
			tempArr.push(myId[0]);
			$.cookie('oc_box_state', $.toJSON(tempArr), cookieOptions );
		} else { // otherwise, create new cookie, with array length 1
			$.cookie('oc_box_state', $.toJSON(myId), cookieOptions);
		}
	} else { // has just been opened
		// so we need to remove from cookie (which should exist)
		if( $.cookie('oc_box_state') ) {
			var tempArr = $.evalJSON( $.cookie('oc_box_state') );
			// Splice (or actually remove) from array
			tempArr.splice( tempArr.find(myId[0]),1 ); // using prototype array "find" extension
			$.cookie('oc_box_state', $.toJSON(tempArr), cookieOptions );
		}
	}
	//console.log($.cookie('oc_box_state'));
}

// OnLoad: check for order Cookie and re-order
function setBoxOrder(){
	if ($.cookie('oc_box_order')) {
		var myArr = $.cookie('oc_box_order').split(',');
		$.each(myArr, function(index, value){
			// get element and re-order
			$('#'+value).appendTo('#console');
		});
	}
}

// OnLoad:
function setBoxState(){
	if ($.cookie('oc_box_state')) {
		var tempArr = $.evalJSON( $.cookie('oc_box_state') );
		$.each(tempArr, function(index, value){
			// set closed and close
			$('#'+value).addClass('closed').children('.content').hide();
		});
	}
}

function setLocateDealerBtn() {
	// get selected brand in make select should be first dropdown
	var brand = $('#my_vehicle select:first option:selected').val();
	brand = brand.toLowerCase();
	if (brand == '') brand = division;
	var actionAttr,myADV;
	myADV = (lang == "fr") ? "98051" : "98050";
	switch(brand)
	{
		case 'buick':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=4&cta=blank&lang=' + lang + '&MMNAMPLT_1=4' + '&adv=' + myADV;
			break;
		case 'cadillac':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=6&cta=blank&lang=' + lang + '&MMNAMPLT_4=6' + '&adv=' + myADV;
			break;
		case 'chevrolet':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=1&cta=blank&lang=' + lang + '&MMNAMPLT_7=1' + '&adv=' + myADV;
			break;
		case 'gmc':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=G&cta=blank&lang=' + lang + '&MMNAMPLT_2=G' + '&adv=' + myADV;
			break;
		case 'pontiac':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=2&cta=blank&lang=' + lang + '&MMNAMPLT_10=2' + '&adv=' + myADV;
			break;
		case 'hummer':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=7&cta=blank&lang=' + lang + '&MMNAMPLT_11=7' + '&adv=' + myADV;
			break;
		case 'saturn':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=8&cta=blank&lang=' + lang + '&MMNAMPLT_6=8' + '&adv=' + myADV;
			break;
		default:
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=0&cta=blank&lang=' + lang + '&adv=' + myADV;
	}
	//alert(actionAttr);
	$('#btn_locate_dealer').attr('href',actionAttr);
	//$('.dealer-form').attr('action', actionAttr).submit();  
}

// Banner functions
function onMakeNameChanged() {
    var frm = document.forms['ownerCentreForm']; 
    var path = window.location.pathname;
    frm.method.value ="makeChanged"; 
    //alert(frm.action);
    if (path.match('model') ||path.match('article') ){
        frm.action="../overview";
        //frm.action="../../../../../.."+path;
    }else{
        //frm.action="./overview";
        frm.action="../../../../.."+path;
    }
    //alert(path);
    //alert(frm.action);
    frm.submit();
}

  function onModelYearChanged() {
  var frm = document.forms['ownerCentreForm']; 
  var path = window.location.pathname;
  frm.method.value ="modelYearChanged";
    if (path.match('model') ||path.match('article')){
        frm.action="../overview";
        //frm.action="../../../../../.."+path;
    }else{
        //frm.action="./overview";
        frm.action="../../../../.."+path;
    }
  frm.submit();
}  
    
// Banner button for Owner's Manual
function getVehicleManuals(){
    var frm = document.forms['ownerCentreForm']; 
	frm.action = '/gm/'+language+'/owner_centre/'+division+'/resources/manuals?' +  Math.random();
    frm.submit();
}

function getManualInfo() {
  var frm = document.forms['ownerCentreForm']; 
  frm.submit();
}

// Character counter for textarea
function charCounter(field, cntfield, maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	} else {
		cntfield.value = maxlimit - field.value.length;
	}
}

// Taken from old motion.js
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=/;";
	//alert(readCookie('pc'));
}
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);
}
function readPcCookie() {
	var pc = readCookie('pc');
	//alert(pc);
	if (validatePostalCode(pc)) {
		$('.PostalCode').val(pc);
	}
}
function validatePostalCode(postalCode) {
	var pc = postalCode;
	var pcRegExp = /(^\D{1}\d{1}\D{1}\s?\d{1}\D{1}\d{1}$)/;
	if (pcRegExp.test(pc)) {
		return true;
	} else {
		return false;
	}
}

function formatPostalCode(postalCode) {
	if (postalCode != "Postal Code" && postalCode != "Code Postal") {
		var pc = postalCode.replace(/\s/,'').toUpperCase();
		$('.PostalCode').val(pc);
		return pc;
	}
}

function displayPostalCodeError() {
	if (lang == '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)';
	}
	$('.error-pc').html('<span>' + pcErrorMsg + '<br />' + pcEg + '</span>');
}


// Find a Locale Dealer Form based on Division/brand
function submitDealerForm() {
	var actionAttr,myADV;
	myADV = (lang=='fr') ? "98051" : "98050" ;
	switch(division) {
		case 'buick':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=4&cta=blank&lang=' + lang + '&MMNAMPLT_1=4' + '&adv=' + myADV;
			break;
		case 'cadillac':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=6&cta=blank&lang=' + lang + '&MMNAMPLT_4=6' + '&adv=' + myADV;
			break;
		case 'chevrolet':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=1&cta=blank&lang=' + lang + '&MMNAMPLT_7=1' + '&adv=' + myADV;
			break;
		case 'gmc':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=G&cta=blank&lang=' + lang + '&MMNAMPLT_2=G' + '&adv=' + myADV;
			break;
		case 'pontiac':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=2&cta=blank&lang=' + lang + '&MMNAMPLT_10=2' + '&adv=' + myADV;
			break;
		case 'hummer':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=7&cta=blank&lang=' + lang + '&MMNAMPLT_11=7' + '&adv=' + myADV;
			break;
		case 'saturn':
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=8&cta=blank&lang=' + lang + '&MMNAMPLT_6=8' + '&adv=' + myADV;
			break;
		default:
			actionAttr = '/gm/' + language + '/hostredirect?host=http://apps.gm.ca/app/GMCanada/DealerLocatorSearch.do&nav=0asdf&cta=blank&lang=' + lang + '&adv=' + myADV;
	}
	//alert(actionAttr);
	//$('.findDealerForm').attr('action', actionAttr).submit();
	document.location.href = actionAttr;
	return false;
} 


function findDealer(pc) {
	if(validatePostalCode(pc) === true) {
		createCookie('pc', pc, 30);
		submitDealerForm();
		return false;
	} else {
		displayPostalCodeError();
		return false;
	}
}

// RSS Feed for Homepage
function displayMediaNews(){
	// Separate core divisions from discontinued divisions
 	var coreDivision; 
	if (division == "buick" || division == "cadillac" || division == "chevrolet" || division == "gmc") {
		coreDivision = division;
	} else {
		coreDivision = "corporate";
	}
	$.ajax({
		type: "GET",
		url: "/gm/" + language + "/owner_centre/" + coreDivision + "/medianews",
		cache: "true",
		dataType: "text",
		error: function(XMLHttpRequest, textStatus, errorThrown){
			//alert(textStatus);
			$('#media_news').append('<li>no news available</li>') ;
		},
		success: function(medianews){
			var news = medianews.split('&&');
			var newsHTML='';
			for (var i =0; i<6; i++){
				var titleText=getTitleFromItem(news[i]);
				var linkText= getLinkFromItem(news[i]);
				var myClass = '';
				if (i==0) { 
					myClass=' class="first"';
				} else if (i==5) { 
					myClass=' class="last"';
				}
				newsHTML = newsHTML + '<li'+myClass+'><a href="'+linkText+'">'+titleText +'</a></li>';
			}
			$('#media_news').prepend(newsHTML);
		}
	});
}
function getTitleFromItem(item){

	var indexb = item.indexOf('<title>');
	var indexe = item.indexOf('</title>');
	var titleText = item.substring(indexb+16, indexe-3);
	return titleText;
}
function getLinkFromItem(item){
	var indexb = item.indexOf('<link>');
	var indexe = item.indexOf('</link>');
	var linkText = item.substring(indexb+15, indexe-3);
	return linkText;
}


/*=============PROTOTYPE/EXTEND==============*/

// Extends array object to add find functionality to search within arrays
// Returns false if nothing found, otherwise you get an array of indexes
// e.g. myArray.find("something")
// NOTE: Only works with simple arrays, not arrays of objects!
Array.prototype.find = function(searchStr) {
 var returnArray = false;
 for (i=0; i<this.length; i++) {
   if (typeof(searchStr) == 'function') {
     if (searchStr.test(this[i])) {
       if (!returnArray) { returnArray = [] }
       returnArray.push(i);
     }
   } else {
     if (this[i]===searchStr) {
       if (!returnArray) { returnArray = [] }
       returnArray.push(i);
     }
   }
 }
 return returnArray;
}

// proper case string prptotype (JScript 5.5+)
String.prototype.toProperCase = function() {
	return this.toLowerCase().replace(/^(.)|\s(.)/g, 
    function($1) { return $1.toUpperCase(); });
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Nov 2010, Joven
// Dynamic content load from showroom.
// Functions taken from showroom to dynamically pull content for "whats new in 20xx" owner-centre panel.

function createBulletsXMLObj() {
    $.ajax({
        type: "GET",
        // TODO
        url: "/gm/" + language + "/getxmlcontent?section=showroom",
        dataType: ($.browser.msie) ? "text" : "xml",
        async: false,
        success: function (xml) {
            //work around for IE
            var tempXML;
            if (typeof xml == "string") {
                tempXML = new ActiveXObject("Microsoft.XMLDOM");
                tempXML.async = false;
                tempXML.loadXML(xml);
                xml = tempXML;
            }
            xmlBullets = xml;
            //alert(xmlBullets.xml)
        }
    });
}


// Mod of oringal function because only works in IE with jQuery 1.2.6 and OC uses 1.3.2
// Retrieve specs from bullet XML feed
function getBulletSpecs(yr_mk_mdl) {
    var mySpecsLi = "";
    //Search through xmlBullets xml, different for IE
    if ($.browser.msie) {
        var x = xmlBullets.documentElement.selectNodes("featureBullet[nameplate='" + yr_mk_mdl + "']");
        if (x.length > 0)
            for (i = 0; i < x[0].childNodes[1].childNodes.length; i++) {
                mySpecsLi += "<li>" + x[0].childNodes[1].childNodes[i].text + "</li>";
            }
    }
    else {
//        $(xmlBullets).find("featureBullet:has(nameplate:contains(" + yr_mk_mdl + ")) featureList feature").each(function () {
          $(xmlBullets).find("featureBullet:has(nameplate:econtains(" + yr_mk_mdl + ")) featureList feature").each(function () {
            mySpecsLi += "<li>" + $(this).text() + "</li>";
        });
    }
    return mySpecsLi;
}


// Create exact match function to overcome multiple vehicle matches (e.g '2011_cadi_cts' vs '2011_cadi_ctss')
$.expr[":"].econtains = function (obj, index, meta, stack) {
    return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////



/* SITE CATALYST EVENT FUNCTION */
			function SCEvent(Obj, Name){
				
				var s_account="gmcanadacom";
				var s=s_gi('gmcanadacom'); 
				var navLoc = location.toString()
				if (navLoc.indexOf('itl.') != -1) { // we are on ITL
					s_account="devgmcanadacom";
					s=s_gi('devgmcanadacom'); 
				} else if (navLoc.indexOf('preprod.') != -1) { // we are on PREPROD
					s_account="gmcangmcapreprod";
					s=s_gi('gmcangmcapreprod'); 
				} else if (navLoc.indexOf('localhost') != -1) { // we are on LOCALHOST
					s_account="devgmcanadacom";
					s=s_gi('devgmcanadacom'); 
				} else { // default to LIVE
					s_account="gmcanadacom";
					s=s_gi('gmcanadacom'); 
				}

				
				s.tl(this,'o', "Owner Centre Online Site " + Name);
			}
			
			function SCdetectApp(Class){
				
					var app = "";
				
					if(Class.indexOf("inrix") != -1){
						app = "inrix";	
					}else if(Class.indexOf("ipark") != -1){
						app = "ipark";
					}else if(Class.indexOf("poynt") != -1){
						app = "poynt";	
					}else if(Class.indexOf("opentable") != -1){
						app = "opentable";
					}else if(Class.indexOf("atmhunter") != -1){
						app = "atmhunter";
					}else if(Class.indexOf("shazam") != -1){
						app = "shazam";
					}else if(Class.indexOf("cruze") != -1){
						app = "Cruze";
					}else if(Class.indexOf("tripadvisor") != -1){
						app = "tripadvisor";
					}else if(Class.indexOf("weathereye") != -1){
						app = "weathereye";
					}else if(Class.indexOf("onstar") != -1){
						app = "onstar";
					}else{
						app = "";	
					}
					
					return app;
			}
			
			function SCdetectDev(Class){
				
					var dev = "";
				
					if(Class.indexOf("bb") != -1){
						dev = "BB";
					}else if(Class.indexOf("droid") != -1){
						dev = "ANDROID";
					}else if(Class.indexOf("ipad") != -1){
						dev = "IPAD";
					}else{
						dev = "IPHONE";		
					}
					
					return dev;
			}
			
			$(document).ready(function () {
										
				$(".trackAppButton").bind('click', function(e) {
					var address = document.location.href;
					var lang = (address.indexOf("/french/") != -1) ? " FR - " : "";
					var brand = "CORPORATE - ";
					
					if(address.indexOf("/buick/") != -1){
						brand = "BUICK - ";
					}else if(address.indexOf("/cadillac/") != -1){
						brand = "CADILLAC - ";
					}else if(address.indexOf("/gmc/") != -1){
						brand = "GMC - ";
					}else if(address.indexOf("/chevrolet/") != -1){
						brand = "CHEVROLET - ";
					}
						
					var classPar = $(this).attr("class");
					var app = SCdetectApp(classPar);
					var dev = SCdetectDev(classPar);
					SCEvent(this, "home overview - "  + brand + "APPS " + dev + " - " + lang + app + " Btn");
				});		
				
				$(".trackAppDownload").bind('click', function(e) {
					var address = document.location.href;
					var lang = (address.indexOf("/french/") != -1) ? " FR - " : "";
					var brand = "CORPORATE - ";
					
					if(address.indexOf("/buick/") != -1){
						brand = "BUICK - ";
					}else if(address.indexOf("/cadillac/") != -1){
						brand = "CADILLAC - ";
					}else if(address.indexOf("/gmc/") != -1){
						brand = "GMC - ";
					}else if(address.indexOf("/chevrolet/") != -1){
						brand = "CHEVROLET - ";
					}
					
					var classPar = $(this).parents("div:first").attr("id");
					var app = SCdetectApp(classPar);
					var dev = SCdetectDev(classPar);
					SCEvent(this, "home overview - "  + brand + "APPS " + dev + " - " + lang + app + " Download");
				});	
			});
