// initial processing after the document loads
$(document).ready(function() {
		
	var window_sticker = $(".window_sticker").size();
	if (window_sticker != 0) {
		//remove trim name if it matches the model name.
		//vehicle pages in the right hand window sticker
		var el = $('.model_intro_a');
		el.html(el.html().replace(/WRX WRX/ig, "WRX"));
		el.html(el.html().replace(/TRIBECA TRIBECA/ig,"Tribeca"));
	}
	
	var pop_builds = $(".pop_builds").size();
	if (pop_builds != 0) {
		//remove trim name if it matches the model name.
		//vehicle pages in the right hand window sticker
		var el = $('.pop_builds');
		el.html(el.html().replace(/WRX WRX/ig, "WRX"));
		el.html(el.html().replace(/TRIBECA TRIBECA/ig,"Tribeca"));
	}

	
	$("body").find("${PATHPREFIX}, ${pathprefix}").each(function() {
		var thisPath = $(this).replaceWith(pathPrefix)
	});
	
	mainmenu();
	
	//detect what else to do
	
	//This is for the accordian pod. If it appears on the page, make it work...
	var pod282 = $(".pod282").size();
	//if there are pod282s on the page load the .accordian
	if (pod282 !=0) {
		$('.pod282').css({visibility: "visible"});
		$('.pod282').accordion({
			header: '.heading',
			selectedClass: 'open',
			event: 'click'
		});
	}
	
	var features_tabs = $("#features-tabs").size();
	//if the features-tabs id is used on the page load the .tabs
	if (features_tabs!=0) {
		$('#features-tabs').tabs();
		$('#feature_spec_wrapper > div').hide(); //hides all of them
		//detect if any tds are empty or are "no"
		//delete the tr that contains the offensive td
		$(".table-content td").each(function (i) {
			var thisText = $(this).text();
			if (thisText.length == 0 || thisText == "no" || thisText == "N/A") {
				var thisParent = $(this).parent();
				thisParent.remove();
					
			} 
			if (thisText == "yes"){
				$(this).remove();
			}
				
		});
		hideNstripe();
	}
	  
	var map_overlay = $('#map-overlay').size();
	if (map_overlay!=0) {
		mapLoad();
		/*
		$('#map-overlay').tabs();
		$('#map-overlay').bind('tabsselect', function(e,ui) {showMarkers(ui.index+1)});
		$("#map-overlay").tabs("select", 0);
		*/
		//$(window).unload(GUnload());
	}
	
	var close_class = $(".close").size();
	//if there are divs with the .close listen for them.
	if (close_class !=0) {
		var current;//init the variable
		$(" .popup_window  ").css({display: "none"});//hide the divs
		
		//set up the listener 
		//this is on the vehice page, its the left side flyout window.
		$(".close").hover(function() {
			//hide the big window							
			$(" .popup_window  ").fadeOut(300);	
			//undue the hover class on the li tag
			$(".trims li").removeClass("hover");
			$('div').remove('#arrow_pointer');
		},function(){
			
		});
		
		$(".trims li").hover( function() {
			
			if ( $(this).hasClass('hover') ) {
				return false;
			} else {
				var layer = $(this).attr('class');
				$(".trims li").removeClass("hover");
				$('div').remove('#arrow_pointer');
				$("." + layer).addClass("hover");
				$(" .popup_window  ").css({display: "none"});
				$("#" + layer).show();
				var a = "250px";
				//$('.arrow_pointer').css({top: a});
				if (layer != "lineCompare"){
				$('<div id="arrow_pointer" class="arrow"></div>').appendTo("." + layer)
				}
			}
		},function(){
			
		});
		
		//makes the entire thing clickable
		$(".trims li").click( function() {
			var link_to = $(this).children().attr('href');
			 window.location = link_to;
			return false;
		});
	}
	
	//article component 2b. Allows CMS to put <br class="column_two" /> into the article
	//this will then take content content after that and place it into a second column.
	var two_column = $(".column_two").size();
	if (two_column != 0) {
		var par = $('.column_two').parent();
		$('<div class="tcArticle_col2"></div>').insertAfter(par);

		$('.column_two').siblings().each( function() {
			var nextsib = $('.column_two').next().appendTo('.tcArticle_col2');
		});	
	}

	//BUILD.SWF has a print summary function.
	$('#openmodal').click(function (e) {
		e.preventDefault();	
	});
	
	$('.closeModal').click(function () {
		$('.print_summary').hide('fast');
		$.modal.close();
	});
	
	$('#printSummary').livequery('click', function(e) {
		$('.print_summary').css({display:"block !important"});
		
		$('.print_summary').modal();
		window.print();
		e.preventDefault();
		return false;
	});

	// city/state regular expression
	var csRegVal = /^\s*([a-zA-Z]{3,}\s*)+,\s*([a-zA-Z]{2,})\s*$/;
	var csRegex = new RegExp(csRegVal);
	
	// Find a Dealer form
	$('#dealerZip, #dealerZip2, #dealerZip3').focus(function() {
		$(this).val('Enter State or Zip');
	}).keydown(function(e) {
		var cValue = $(this).val();
		if (cValue == 'Enter State or Zip') {
			// clear the value
			$(this).val('');
		}
	}).keypress(function(e) {
		if (e.which == 13) { // enter key was pressed
			// get the id of the form to submit
			var submitForm = $(this).parent().attr("id");
			var inputValue = $(this).val();
			//var filter = $('#'+submitForm + ' input[name=filtercode]').val();
			
			if (inputValue.match(csRegex)) {
				// validate to ensure the state is valid
				var stateInfo = usStates;
				var inputMatchesState = 'empty';

				// parse inputValue to obtain alleged state
				var inputArray = inputValue.split(",");
				var allegedState = jQuery.trim(inputArray[1]);

				// compare to valid state names and abbreviations
				$(stateInfo).each(function() {
					var sAbbrev = this.stateAbbrev;
					var sName = this.stateName;

					// create lowercase versions of all variables
					var lowerInput = allegedState.toLowerCase();
					var lowerAbbrev = sAbbrev.toLowerCase();
					var lowerName = sName.toLowerCase();

					if (lowerInput == lowerName || lowerInput == lowerAbbrev) {
						inputMatchesState = sAbbrev;
					}
				});

				if (inputMatchesState.length == 2) {
					// replace the value
					var newInputValue = inputArray[0] +", " + inputMatchesState;
					$('#'+submitForm + ' input[name=zipcode]').val(newInputValue);

					// submit the form
					$('#'+submitForm).submit();
				}
				else {
					$('#'+submitForm + ' input[name=zipcode]').val('Enter State or Zip');
				}
			}
			else {
				// determine if a 5-digit zipcode was submitted
				var isZip = inputValue.replace(/[^\d]/g, "").substr(0,5);
			
				if (isZip.length == '5') {
					// submit the form
					$('#'+submitForm).submit();
				}
				else if (isZip.length < '5' || isZip.length > '5') {
					// check for a state or state abbreviation
					var stateInfo = usStates;
					var inputMatchesState = 'empty';
					var stateCaptial = "";
					
					$(stateInfo).each(function() {
						var sAbbrev = this.stateAbbrev;
						var sName = this.stateName;

						// create lowercase versions of all variables
						var lowerInput = inputValue.toLowerCase();
						var lowerAbbrev = sAbbrev.toLowerCase();
						var lowerName = sName.toLowerCase();

						if (lowerInput == lowerName || lowerInput == lowerAbbrev) {
							inputMatchesState = sAbbrev;
							//stateCapital = this.stateCapital;
						}
					});

					if (inputMatchesState.length == 2) {
						// replace the value
						$('#'+submitForm + ' input[name=zipcode]').val(inputMatchesState);

						// submit the form
						$('#'+submitForm).submit();
						/*
						// if this is an spt search
						if (filter == 'spt') {
							// replace the value
							var newInputValue = stateCapital+', '+inputMatchesState;
							$('#'+submitForm + ' input[name=zipcode]').val(newInputValue);
							
							// submit the form
							$('#'+submitForm).submit();
						}
						else {
							// replace the value
							$('#'+submitForm + ' input[name=zipcode]').val(inputMatchesState);

							// submit the form
							$('#'+submitForm).submit();	
						}
						*/
					}
					else {
						$('#'+submitForm + ' input[name=zipcode]').val('Enter State or Zip');
					}
				}
			}
			
		}
		else if ((e.which != 13)) {
			// append the character to the value
			var newValue = $(this).val();
			$(this).val(newValue);
		}
	});
	
	$('.submit_findDealer').click(function(e) {	
		e.preventDefault();
		
		// get the id of the form to submit
		var submitForm = $(this).parent().attr("id");
		var inputValue = $('#'+submitForm + ' input[name=zipcode]').val();
		//var filter = $('#'+submitForm + ' input[name=filtercode]').val();
		
		// if they just clicked the blue arrow
		if (inputValue == "Find Dealer") {
			// redirect to the Find a Dealer page
			var link_to = linkPrefix+"tools/find-dealer.html";
			window.location = link_to;
		}
		
		if (inputValue.match(csRegex)) {
			// validate to ensure the state is valid
			var stateInfo = usStates;
			var inputMatchesState = 'empty';
			
			// parse inputValue to obtain alleged state
			var inputArray = inputValue.split(",");
			var allegedState = jQuery.trim(inputArray[1]);
			
			// compare to valid state names and abbreviations
			$(stateInfo).each(function() {
				var sAbbrev = this.stateAbbrev;
				var sName = this.stateName;

				// create lowercase versions of all variables
				var lowerInput = allegedState.toLowerCase();
				var lowerAbbrev = sAbbrev.toLowerCase();
				var lowerName = sName.toLowerCase();

				if (lowerInput == lowerName || lowerInput == lowerAbbrev) {
					inputMatchesState = sAbbrev;
				}
			});
			
			if (inputMatchesState.length == 2) {
				// replace the value
				var newInputValue = inputArray[0] +", " + inputMatchesState;
				$('#'+submitForm + ' input[name=zipcode]').val(newInputValue);

				// submit the form
				$('#'+submitForm).submit();
			}
			else {
				$('#'+submitForm + ' input[name=zipcode]').val('Enter State or Zip');
			}
		} 
		else {
			// determine if a 5-digit zipcode was submitted
			var isZip = inputValue.replace(/[^\d]/g, "").substr(0,5);

			if (isZip.length == '5') {
				// submit the form
				$('#'+submitForm).submit();
			}
			else if (isZip.length < '5' || isZip.length > '5') {
				// check for a state or state abbreviation
				var stateInfo = usStates;
				var inputMatchesState = 'empty';
				var stateCaptial = "";
				
				$(stateInfo).each(function() {
					var sAbbrev = this.stateAbbrev;
					var sName = this.stateName;

					// create lowercase versions of all variables
					var lowerInput = inputValue.toLowerCase();
					var lowerAbbrev = sAbbrev.toLowerCase();
					var lowerName = sName.toLowerCase();

					if (lowerInput == lowerName || lowerInput == lowerAbbrev) {
						inputMatchesState = sAbbrev;
						//stateCapital = this.stateCapital;
					}
				});

				if (inputMatchesState.length == 2) {
					// replace the value
					$('#'+submitForm + ' input[name=zipcode]').val(inputMatchesState);

					// submit the form
					$('#'+submitForm).submit();
					/*
					// if this is an spt search
					if (filter == 'spt') {
						// replace the value
						var newInputValue = stateCapital+', '+inputMatchesState;
						$('#'+submitForm + ' input[name=zipcode]').val(newInputValue);
						
						// submit the form
						$('#'+submitForm).submit();
					}
					else {
						// replace the value
						$('#'+submitForm + ' input[name=zipcode]').val(inputMatchesState);

						// submit the form
						$('#'+submitForm).submit();	
					}
					*/
				}
				else {
					$('#'+submitForm + ' input[name=zipcode]').val('Enter State or Zip');
				}
			}
		}
		
		return false;
	});
	
	$(".getAQuote_link").click( function() {
		var link_to = linkPrefix;
		link_to += "shopping-tools/get-quote.html";
		link_to += "?model=";
		link_to += g_model;
		link_to += "&trim=";
		link_to += g_trim;
		link_to += "&exteriorcolorcode=";
		link_to += g_exteriorcolorcode;
		link_to += "&accessorycodes=";
		link_to += g_accessorycodes;
		window.location = link_to;
		return false;
	});
		
	$(".scheduleTestDrive_link").click( function() {
		var link_to = linkPrefix;
		link_to += "shopping-tools/schedule-test-drive.html";
		link_to += "?model=";
		link_to += g_model;
		link_to += "&trim=";
		link_to += g_trim;
		link_to += "&exteriorcolorcode=";
		link_to += g_exteriorcolorcode;
		link_to += "&accessorycodes=";
		link_to += g_accessorycodes;
		window.location = link_to;
		return false;
	});
					
	//find sig class. If it's empty hide it.
	var sig_class = $('.sig').size();
	if (sig_class != 0){
		var signature_class = $(".sig").html()
		if (signature_class.length == 0)
		{ 
			$(".sig").addClass('hide');
		}else{
		}
	}
		
	//find 7b. If it contains College info hide the vehicle details portion.
	var vehicle_description_7e = $('.vehicle_description_7e').size();
	if (vehicle_description_7e != 0){
		$(".vehicle_description_7e:first").css({border:"none"});//basically an IE6 fix since you cant do this in the CSS
		$(".vehicle_description_7e h2").each(function (i) {
			var h2Contents = $(this).html();
			if (h2Contents == "College Graduate Program")
			{ //removes the nonsense that is passed through the college special offer since it doesnt relate to a specific vehicle.
				 var thisParent = $(this).parent();
				 thisParent.remove();
			}else{
			
			}
		})	
	}	
			
	//detect vehicle trim pages and hack the CSS for the pages.
	var trimpage = $("#trimpage").size();
	if (trimpage){
		$(".component282_noborder .title ").height(45);
		$(".component282_noborder .title ").css({"min-height": "45px"});
		$(".component282_noborder h1").css({padding: "13px 0 23px 0"});
	}
		
	/* Omniutre */
	// brochure omniture
	$('.brochureLink').livequery('click', function() {
		// get the dealer info from the element title
		var brochureInfo = $(this).attr("title");

		// send the information to omniture
		BroDL(brochureInfo);
	});	

});//end document.ready


	function hideNstripe(){
	var first_item = $('#features-tabs-features > a:first').attr("href");
		$('#feature_spec_wrapper').css({display: "block"}); //because its hidden in general.css (stops it from loading anything before its all ready)

	$('#feature_spec_wrapper ' + first_item).show(); //shows the first one.
	$('#features-tabs-features > a:first').addClass('hover'); //add the default background selected state.
	$('#feature_spec_wrapper td:even').addClass('left_td');
	$('#feature_spec_wrapper td:odd').addClass('right_td');
	$('.tabs a').click(function() { //when the tabs get switched show the default (first) one.
		$('#features-tabs a').removeClass("hover"); //remove all selected backgrounds.
		var the_tab = $(this).attr("href"); //get which tab was clicked
					
		$('#feature_spec_wrapper > div').hide(); //hides all of the right panes
					
		$(the_tab + ' a:first').addClass('hover'); //add the default background selected state. to the left pane.
		var new_first_item = $(the_tab + ' > a:first').attr("href"); //get the value of the first link
		$('tr').removeClass('odd');		//remove all striping	
					
		$(new_first_item).show(); //shows the first one.
		$(new_first_item + ' tr:not([th]):even').addClass('odd'); //stripe whats showing
		return false;
	});
					 
	$('#features-tabs .content a').click(function() {
		$('#features-tabs a').removeClass("hover"); //remove all selected backgrounds.						 
		$('tr').removeClass('odd');		//remove all striping				 
		var theOne =	$(this).attr("href"); //get which left pane to show.
		//alert(theOne);  //debugging
		$(this).addClass("hover"); //add the background to show which is selected.
		$('#feature_spec_wrapper > div').hide(); //hides all of them
			
		$(theOne).show(); //show the one you want
		$(theOne + ' tr:not([th]):even').addClass('odd'); //stripe whats showing
		return false; //stop trying to load # (page jumping)
	});
}//hideNstripe



//onFocus - Clears the default value
function search_onFocusSearch(sender) { 
	if (sender.isActive) 
		return; 
	sender.originalValue=sender.value; 

	sender.className="search_active"; //applies the active style
	sender.value=""; 
	sender.isActive=true;
}

//onBlur - Puts the Value back into the search box
function search_onBlurSearch(sender) { 
	if(sender.value=="")
	{
		sender.value=sender.originalValue;
		sender.className="search_inactive"; //applies the inactive style
		sender.isActive=false;
	}
}


//
//Primary Navigation Main Menu Code Uses Suckerfish Menu
//
//drop down on hover menu
function mainmenu(){
$(" .primary_navigation li li div, .shopping_nav li li div ").each(function(){
		$(this).parent().addClass("dropdown");
	});
	sfHover();
	try
	{
	    $(" .primary_navigation li div, .shopping_nav li div ").bgiframe();
	}
	catch (ex) {}
}

//sfHover is for nav
sfHover = function() {
//	var timeout = 1000;
	var timeout = 25;
	var cssClass = "over";

	var queue = [];
	var reCSS = new RegExp("\\b" + cssClass + "\\b");
	//var sfEls = document.getElementById("primary_navigation").getElementsByTagName("li");
	var sfEls = $(".primary_navigation li, .shopping_nav li");
	for (var i=0; i<sfEls.length; i++) {

		// mouseover and mouseout handlers for regular mouse based interface.
		sfEls[i].onmouseover = function() {
			queueFlush();
			this.className += " " + cssClass;
		}
		sfEls[i].onmouseout = function() {
			queue.push([setTimeout(queueTimeout, timeout), this]);
		}

		// focus and blur handlers for keyboard based navigation.
		sfEls[i].onfocus = function() {
			queueFlush();
			this.className += " " + cssClass;
		}
		sfEls[i].onblur = function() {
			queue.push([setTimeout(queueTimeout, timeout), this]);
		}

		// click event handler needed for tablet type interfaces (e.g. Apple iPhone).
		sfEls[i].onclick = function(e) {
			if (this.className.search(reCSS) == -1) {
				// CSS not set, so clear all sibling (and decendants) menus, and then set CSS on this menu...
				var elems = this.parentNode.getElementsByTagName("li");
				for (var i=0; i<elems.length; i++) {
					elems[i].className = elems[i].className.replace(reCSS, "");
				}
				this.className += " " + cssClass;
			} else {
				// CSS already set, so clear all decendant menus and then this menu...
				var elems = this.getElementsByTagName("li");
				for (var i=0; i<elems.length; i++) {
					elems[i].className = elems[i].className.replace(reCSS, "");
				}
				this.className = this.className.replace(reCSS, "");
			}
			if (e && e.stopPropagation)
				e.stopPropagation();
			else
				window.event.cancelBubble = true;
		}
	}

	queueFlush = function () {
		while (queue.length) {
			clearTimeout(queue[0][0]);
			queueTimeout();
		}
	}

	queueTimeout = function() {
		if (queue.length) {
			var el = queue.shift()[1];
			el.className = el.className.replace(reCSS, "");
		}
	}
}

/*
//ModelIntro window sticker roll over
function window_sticker_change(layer){
$(".trims li").removeClass("hover");
$('div').remove('.arrow_pointer');
$("." + layer).addClass("hover");
$(" .popup_window  ").css({display: "none"});
$("#" + layer).show();
var a = "250px";
//$('.arrow_pointer').css({top: a});
$('<div class="arrow_pointer" id="arrow"></div>').appendTo("." + layer)
}
*/
function window_sticker_change(layer){return false;}



function window_sticker_release(){
/*		$(".close").hover(function(){
					$('.container950').remove('.arrow_pointer');	
					$('#arrow').css({display: "none"})
					$(" .popup_window  ").hide();	
					$(".trims li").removeClass("hover");
					current = "none";
										   });
*/
}

//
// Opens a modal print summary dialog and populates the dialog
// with data in the specified properties map.
//
function openPrintSummaryModal(properties)
{
	// open the model dialog
	$('.print_summary').modal();
	$('#modalOverlay').css({height:($(document).height().toString() + "px"), overflow:"hidden"});

	// populate the dialog data
	$('.ps_year').html(properties.year);
	$('.ps_model').html(properties.model);
	$('.ps_approx_price').html(properties.retailprice);
	$('.ps_engine').html(properties.engine);
	$('.ps_transmission').html(properties.transmission);
	$('.ps_exterior_color').html(properties.exteriorcolor);
	$('.ps_interior_color').html(properties.interiorcolor);
	$('.ps_mpg_city').html(properties.mpgcity);
	$('.ps_mpg_hwy').html(properties.mpghighway);
	$('.ps_trim').html(properties.trim);
	$('.ps_total_retail_price').html(properties.msrpprice);
	$('.ps_package').html(properties.packagename);
	$('.ps_package_price').html(properties.packageprice);
	$('.ps_dest_del').html(properties.deliverycharge);
	$('.ps_vehicle_image').attr({src : properties.image}); 
	
	// initialize print summary globals
	g_model = properties.model;   
	g_trim  = properties.trim;   
	g_exteriorcolorcode = properties.exteriorcolorcode;   
	g_accessorycodes = "";

	// iterate over the accessories and add them to the print summary
	jQuery.each(properties.accessories, function(i,val)
	{
	    $('.accessory_list').append("<li><span class=\"name\">"+val.name+"</span><span class=\"price\">"+val.price+"</span></li>");
	    g_accessorycodes += (val.code + " ");
	});
}

function printCoupon(){
	window.print();
}

function printSummary(){
	window.print();
	
}

function printComparison(){
	window.print();
}