/*-----------------------------------------------------------------
	website:	www.subaru.com
	type:		landing page scripts only
	desc:
	Date:
	Dependencies: (list jQuery version, and other plugins)
------------------------------------------------------------------


	1.0 Instantiate - $(function() {}
	2.0 create_
	3.0 delete_
	4.0 format_
	5.0 get_
	6.0 instantiate_
	7.0 is_
	8.0 listen_
	9.0 submit_
	10.0 update_
	11.0 validate_
	12.0 validation_objects
	13.0 flash interaction
------------------------------------------------------------------*/

//-----------------------------------------------------------------------------------
//1.0 Instantiate - $(function() {}
// functions called once DOM is ready.
//-----------------------------------------------------------------------------------

$(document).ready(function() {
	//alphabetical order
	//call the functions here - define the functions below

	// instantiate_
	instantiate_accordions();
	instantiate_defaultText(".defaultText");
	instantiate_featuresTabs();
	instantiate_findDealerMap();
	instantiate_findDealerResult();
	instantiate_handrail();
//	instantiate_lazyload();
	instantiate_omniture();
	instantiate_pngFix(document);
	instantiate_rotator();
	instantiate_specialOffersPage();
	instantiate_specialOffersPage_MySubaru();
	instantiate_vehicleLandingPages();

	// listen_
	listen_defaultText(".defaultText");
	listen_dropDowns($("li", ".bottom_menus"));
	listen_findDealerBody();
	listen_findDealerHeader();
	listen_findDealerModal();
	listen_findDealerSPT();
	listen_findDealerWindowSticker();
	listen_hoverClass();
	listen_modalClose();
	listen_twoColumn();

}); //end of document.ready

//-----------------------------------------------------------------------------------
//2.0 create_
//
//usually limited params
//returns html string or .append() straight out to the DOM
//-----------------------------------------------------------------------------------

function create_jsRotator(xmlFilePath,xmlFile,imagePath,targetDiv) {
	get_jsRotatorData(xmlFilePath,xmlFile,imagePath);
}

function create_jsRotator_noRotator(xmlFilePath,xmlFile,imagePath,targetDiv) {
	var rotatorHTML = '';
	var bubbleHTML = '';
	$(targetDiv).html('<ul></ul>');
	$.ajax({
		type: "GET",
		url: '' + xmlFilePath + xmlFile,
		dataType: "xml",
		success: function(xml) {
		// Run the function for tags in the XML file
			$('rotator',xml).each(function(i) {
				rotatorHTML = '';
				bubbleHTML = '';
				$(this).find('bubble').each(function() {
					//standard bubble
						if ($(this).attr('bubbleType') == "standard"){
							if ($(this).attr('fully_closed') != "true"){
								bubbleHTML += '<div class="heroMenuHover"><div class="podFade"><div class="component pod282 pod282_open" style="left:'+ $(this).attr('xPos')+'px;top:'+$(this).attr('yPos')+'px;">';
							} else {
								bubbleHTML += '<div class="heroMenuHover"><div class="podFade"><div class="component pod282 pod282_closed" style="left:'+ $(this).attr('xPos')+'px;top:'+$(this).attr('yPos')+'px;">';
							}
							bubbleHTML +=  '<div class="top"></div><div class="title"><h1>'+ $(this).find('title').text() + '</h1></div><div class="hr"></div>';
							$(this).find('menuItem').each(function() {

								if ($(this).find('read_more ').text() == "") { //Doesnt have a read more link, so nothing links.
								bubbleHTML += '<div class="head_wrapper"><div class="heading"><a class="links" href="#">' + $(this).find('header').text() + '</a></div>';
								bubbleHTML += '<div class="content"><p><span class="nolink_accordion_content_title">' + $(this).find('header').text() + '</span><br />';
								bubbleHTML += $(this).find('text').text() + '</p';
								//bubbleHTML += '<a class="read_more" href="' + linkPrefix + $(this).find('read_more ').text() + '">- Read More</a></div></div>';
								bubbleHTML += '</div></div>';

							} else { //has a link for readmore
									bubbleHTML += '<div class="head_wrapper"><div class="heading"><a class="links" href="#">' + $(this).find('header').text() + '</a></div>';
									bubbleHTML += '<div class="content"><p><a href="' + linkPrefix + $(this).find('read_more ').text() + '">' + $(this).find('header').text() + '</a><br />';
									bubbleHTML += $(this).find('text').text() + '</p';
									//bubbleHTML += '<a class="read_more" href="' + linkPrefix + $(this).find('read_more ').text() + '">- Read More</a></div></div>';
									bubbleHTML += '<div class="readmore_button_container"><span><a class="read_more" href="' + linkPrefix + $(this).find('read_more ').text() + '">Read More</a></span></div></div></div>';
							}

							});
							if ($(this).find('footer').find('button').find('link').text() != ""){
								bubbleHTML += '<div class="head_wrapper"><div class=""><a class="links" href="' + linkPrefix + $(this).find('footer').find('button').find('link').text() + '">' + $(this).find('footer').find("button").find('text').text() + '</a></div></div>';
							}
							bubbleHTML += '<div class="podfooter"></div></div></div></div>';
						}//standard

					//type A bubble
					if ($(this).attr('bubbleType') == "specialA"){
						bubbleHTML += '<div class="heroMenuHover"><div class="podFade"><div id="specialA" class="pod282">';
						bubbleHTML += '<div class="title"><h1>'+ $(this).find('title').text() + '</h1></div>';
						bubbleHTML += '<div class="content"><p class="offer_title">' + $(this).find('specialOffer').attr('offerTitle') + '</p>';
						bubbleHTML += '<p class="offer_details">' + $(this).find('specialOffer').text() + '</p>';
						bubbleHTML += '<div class="deal_button"><a href="' + linkPrefix +  $(this).find('specialOffer').attr('buttonLink') + '"><img src="'+ pathPrefix +'images/site/btn_getYourGreatDeal.png" alt="Get Your Great Deal" /></a></div>'
						bubbleHTML += '</div>';
						bubbleHTML += '<div class="podfooter"><span class="component_button"><a href="' + linkPrefix + $(this).find('footer').find('button').find('link').text() + '"><span>';
						bubbleHTML += $(this).find('footer').find("button").find('text').text() + '</span></a></span></div></div></div></div>';
					}//type A
				});
				var rimage = $(this).find("image").text();
				var imageLink = $(this).find("imageLink").text();
				rotatorHTML = '<li><a href="' + linkPrefix + imageLink + '"><img src="' + imagePath + rimage + '" height="429" width="950"/></a>'+ bubbleHTML +'</li>';
				$(targetDiv + " ul").append(rotatorHTML);

				//if we've reached the end of the xml, start the carousel
				if (i == $('rotator',xml).length - 1) {

					var pod282_open = $(targetDiv + " .pod282_open").size();
						if (pod282_open !=0) {
							$(targetDiv + ' .pod282_open').css({'visibility':'visible'});
							$(targetDiv + ' .pod282_open').accordion({
								header: '.heading',
								selectedClass: 'open',
								event: 'click',
								active: 0,
								collapsible: false
							});
						}

					var pod282_closed = $(targetDiv + " .pod282_closed").size();
						if (pod282_closed !=0) {
							$(targetDiv + ' .pod282_closed').css({'visibility':'visible'});
							$(targetDiv + ' .pod282_closed').accordion({
								header: '.heading',
								selectedClass: 'open',
								event: 'click',
								active: false,
								collapsible: true
							});
						}

					$('.handrail').hover(function() {
						$('.heroMenuHover').hide();
					},
					function () {
						$('.heroMenuHover').fadeIn();
					});
				}
			});
		}
	});
}; // end create_jsRotator_noRotator

function create_menuHover() {
	//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].hover(function() {
			queueFlush();
			this.className += " " + cssClass;
		},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, "");
		}
	}
} // end create_menuHover

//-----------------------------------------------------------------------------------
//3.0 delete_
//-----------------------------------------------------------------------------------


//-----------------------------------------------------------------------------------
//4.0 format_
//
//accepts parameter
//returns same variable formatted
//-----------------------------------------------------------------------------------

function format_jsRotator(rotatorData,imagePath,rotate) {

	var rotatorHTML = "<ul>";
	var bubbleHTML = "";
	for (x in rotatorData){
		//the window sticker
		if (rotatorData[x].bubbleType == "standard" && rotatorData[x].bubbleDisplay == "true"){
			if (rotatorData[x].fullyClosed == "false"){
			bubbleHTML = '<div class="heroMenuHover"><div class="podFade"><div class="component pod282 pod282_open" style="left:626px; top:26px;">';
			} else {
			bubbleHTML = '<div class="heroMenuHover"><div class="podFade"><div class="component pod282 pod282_closed" style="left:626px; top:26px;">';
			} // end fullyClosed
			bubbleHTML +=  '<div class="top"></div><div class="title"><h1>'+ rotatorData[x].windowStickerTitle + '</h1></div><div class="hr"></div>';
			//each menu Item
			for (a in rotatorData[x].menuItems){
				if(rotatorData[x].menuItems[a].readMore == ""){
					bubbleHTML += '<div class="head_wrapper"><div class="heading"><a class="links" href="#">' + rotatorData[x].menuItems[a].header + '</a></div>';
					bubbleHTML += '<div class="content"><p><span class="nolink_accordion_content_title">' + rotatorData[x].menuItems[a].header + '</span><br />';
					bubbleHTML += rotatorData[x].menuItems[a].text + '</p>';
				} else {
					bubbleHTML += '<div class="head_wrapper"><div class="heading"><a class="links" href="#">' + rotatorData[x].menuItems[a].header + '</a></div>';
					bubbleHTML += '<div class="content"><p><a href="' + linkPrefix + rotatorData[x].menuItems[a].readMore + '">' + rotatorData[x].menuItems[a].header + '</a><br />';
					bubbleHTML += rotatorData[x].menuItems[a].text + '</p>';
					bubbleHTML += '<div class="readmore_button_container"><span><a class="read_more" href="' + linkPrefix + rotatorData[x].menuItems[a].readMore + '">Read More</a></span></div>';
			}

				//Image Gallery Link?
				if (rotatorData[x].menuItems[a].imageGallery != "" || rotatorData[x].menuItems[a].videoGallery != ""){
					bubbleHTML += '<div class="galleryLinkWrapper">';
					if (rotatorData[x].menuItems[a].imageGallery != ""){
						bubbleHTML += '<a id="'+rotatorData[x].menuItems[a].imageGallery+'" class="mediaPlayerStart" href="#" >View Photos</a>';
					}
					//Video Gallery Link?
					if (rotatorData[x].menuItems[a].videoGallery != ""){
						bubbleHTML += '<a id="'+rotatorData[x].menuItems[a].videoGallery+'" class="mediaPlayerStart" href="#" >View Videos</a>';
					}
					bubbleHTML += '</div>';
				}

				bubbleHTML += '</div></div>';
			}//end menuItems for

			//windowSticker button
			if (rotatorData[x].footerButtonLink != "" && rotatorData[x].footerDisplay == "true"){ //if there isnt a link defined, dont show the button
				bubbleHTML += '<div class="head_wrapper"><div class=""><a class="links" href="' + linkPrefix + rotatorData[x].footerButtonLink + '">' + rotatorData[x].footerButtonText + '</a></div></div>';
			} //end if footerbutton link exists


			bubbleHTML += '<div class="podfooter"></div>';
			bubbleHTML += '</div></div></div>';//closing tags
		}//end standard window sticker

		//Used on the motor trend page
		if (rotatorData[x].bubbleType == "bubbleB" && rotatorData[x].bubbleDisplay == "true"){
			bubbleHTML = '<div class="heroMenuHover"><div class="podFade"><div class="component pod282 pod282_closed bubbleB" style="left:626px; top:26px;">';
			bubbleHTML += '<div class="top"></div>';
			bubbleHTML += '<div class="title"><h1>'+ rotatorData[x].windowStickerTitle + '</h1></div>';
			bubbleHTML += '<div class="hr"></div>';
			for (a in rotatorData[x].menuItems){
				bubbleHTML += '<div class="head_wrapper">';

				//check for inlineImage
				if(rotatorData[x].menuItems[a].inlineImage != ""){
					bubbleHTML += '<div class="content" style="height:200px">';
					bubbleHTML += '<img src="'+ imagePath + rotatorData[x].menuItems[a].inlineImage+'" height="" width="" alt="'+rotatorData[x].menuItems[a].header+'" />';
				} else {
					bubbleHTML += '<div class="content" style="height:70px">';
				}
				bubbleHTML += '<p><span class="nolink_accordion_content_title bubbleB">' + rotatorData[x].menuItems[a].header + '</span><br />';
				bubbleHTML += rotatorData[x].menuItems[a].text + '</p>';
				//Image Gallery Link?
				if (rotatorData[x].menuItems[a].imageGallery != "" || rotatorData[x].menuItems[a].videoGallery != ""){
					bubbleHTML += '<div class="galleryLinkWrapper">';
					if (rotatorData[x].menuItems[a].imageGallery != ""){
						bubbleHTML += '<a id="'+rotatorData[x].menuItems[a].imageGallery+'" class="mediaPlayerStart" href="#" >View Photos</a>';
					}
					//Video Gallery Link?
					if (rotatorData[x].menuItems[a].videoGallery != ""){
						bubbleHTML += '<a id="'+rotatorData[x].menuItems[a].videoGallery+'" class="mediaPlayerStart" href="#" >View Videos</a>';
					}
					bubbleHTML += '</div>';
				}


				bubbleHTML += "</div></div>"; //content and head_wrapper
			} //end menuItems for loop
			bubbleHTML += '<div class="podfooter"></div>';
			bubbleHTML += "</div></div></div>";
		}

		if (rotatorData[x].bubbleType == "bubbleC" && rotatorData[x].bubbleDisplay == "true"){
			bubbleHTML = '<div class="heroMenuHover"><div class="podFade"><div class="component pod282 pod282_open bubbleC" style="left:626px; top:26px;">';

			//windowSticker button
			if (rotatorData[x].footerButtonLink != "" && rotatorData[x].footerDisplay == "true"){ //if there isnt a link defined, dont show the button
				bubbleHTML += '<div class="button"><span class="blue"><a class="blue" href="' + linkPrefix + rotatorData[x].footerButtonLink + '">' + rotatorData[x].footerButtonText + '</a></span><div class="clear"></div></div>';
			} //end if footerbutton link exists


			bubbleHTML += '</div></div></div>';//closing tags  heroMenuHover .podfade .component, etc
		}//end bubbleC window sticker

		//the main rotator image and its click-ability
		var theImg = '<img src="'+imagePath + rotatorData[x].rimage +'" height="429px" width="950px" alt="'+rotatorData[x].rimage+'" />';
		if (rotatorData[x].clickableImage == "true"){
			rotatorHTML += '<li><a href="' + linkPrefix + rotatorData[x].imageLink + '">' + theImg + '</a>'+bubbleHTML+'</li>';
		} else {
			rotatorHTML += "<li>" + theImg + bubbleHTML + "</li>";
		}

		bubbleHTML = "";

	}//end for x in rotatorData


	rotatorHTML += "</ul>";
	$("#flash_content950 .rotator").empty().html(rotatorHTML);


	if(rotate == "true"){
	 $(".rotator").jCarouselLite({
			btnNext: ".next",
			btnPrev: ".prev",
			speed: 350,
			visible: 1
		});
	} else {
		$(".rotator").css("margin-left", "0px");
	}

		var pod282_open = $(".rotator" + " .pod282_open").size();
			if (pod282_open !=0) {
				$(".rotator" + ' .pod282_open').css({'visibility':'visible'});
				$(".rotator" + ' .pod282_open').accordion({
					header: '.heading',
					selectedClass: 'open',
					event: 'click',
					active: 0,
					collapsible: false
				});
			}

		var pod282_closed = $(".rotator" + " .pod282_closed").size();
			if (pod282_closed !=0) {
				$(".rotator" + ' .pod282_closed').css({'visibility':'visible'});
				$(".rotator" + ' .pod282_closed').accordion({
					header: '.heading',
					selectedClass: 'open',
					event: 'click',
					active: false,
					collapsible: true
				});
			}

		$('.handrail').hover(function() {
			$('.heroMenuHover').hide();
		}, function () {
			$('.heroMenuHover').fadeIn();
		});

}



function format_stripeTable() {
	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');
	$('tr').removeClass('odd');		//remove all striping
	$('#feature_spec_wrapper tr:even').addClass('odd');
	$('.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)
	});
}


//-----------------------------------------------------------------------------------
//5.0 get_
//-----------------------------------------------------------------------------------

function get_dealers(searchString) {
	var mapMarkersUrl = linkPrefix + "tools/maps/dealer/getmapmarkers/";
	var csRegVal = /^\s*([a-zA-Z]{3,}\s*)+[,|\/]\s*([a-zA-Z]{2,})\s*$/;
	var csRegex = new RegExp(csRegVal);

	if (searchString.match(csRegex)) {
		var searchArray = searchString.split(/,|\//);
		mapMarkersUrl += "city/"+encodeURI(searchArray[0])+"/state/"+searchArray[1];
	}
	else {
		mapMarkersUrl += searchString;
	}
	var dealers = $.ajax({
		url: mapMarkersUrl,
		dataType: 'xml',
		async: false,
		cache: false
	});
	return dealers;
}

function get_jsRotatorData(xmlFilePath,xmlFile,imagePath) {
	//create array of elements
	var rotatorObject = new Object();
	var rotatorList = new Object();
	var menuItems = new Object();
	var rotate;
	$.ajax({
		type: "GET",
		url: '' + xmlFilePath + xmlFile,
		dataType: "xml",
		success: function(xml) {
		// Run the function for tags in the XML file
			$('doc', xml).each(function(i) {
				rotate = $(this).find("rotate").text();
			});
			$('rotator',xml).each(function(i) {

				var rotatorList = new Object();
				 rotatorList["list"] = i;
				 rotatorList["rimage"] = $(this).find("image").text();
				 rotatorList["imageLink"] = $(this).find("imageLink").text();
				 rotatorList["clickableImage"] = $(this).find("imageLink").attr("clickable");
				 rotatorList["bubbleType"] = $(this).find('bubble').attr('bubbleType');
				 rotatorList["fullyClosed"] = $(this).find('bubble').attr('fully_closed');
				 rotatorList["bubbleDisplay"] = $(this).find('bubble').attr('display');
				 rotatorList["windowStickerTitle"] = $(this).find("title").text();
				 rotatorList["menuItems"] = [];

				 $(this).find('menuItem').each(function(a) {
				   var menuItems = new Object();
					menuItems["inlineImage"] = $(this).find('inlineImage').text();
					menuItems["header"] = $(this).find('header').text();
					menuItems["text"] = $(this).find('text').text();
					menuItems["readMore"] = $(this).find('read_more').text();
					menuItems["imageGallery"] = $(this).find('imageGalleryLink').text();
					menuItems["videoGallery"] = $(this).find('videoGalleryLink').text();
					//push Menu Items Array
					rotatorList["menuItems"].push(menuItems);
				});//menuItem each
				rotatorList["footerDisplay"] = $(this).find('footer').attr('display');
				rotatorList["footerButtonDisplay"] = $(this).find('footer').find('button').attr('display');
				rotatorList["footerButtonText"] = $(this).find('footer').find('button').find('text').text();
				rotatorList["footerButtonLink"] = $(this).find('footer').find('button').find('link').text();
				//push to Rotator List Array to the full Rotator Object
				rotatorObject[i] = rotatorList;
			});//rotator each
		//	console.log(rotate);
			format_jsRotator(rotatorObject,imagePath,rotate);
		}//end success
	});//end ajax
}//end function

//-----------------------------------------------------------------------------------
//6.0 instantiate_
//
// functions called from above document.ready that RUN when the DOM is ready.
//-----------------------------------------------------------------------------------

function instantiate_accordions() {
	if (!selected_one){
		var selected_one = 0;
	} else {
	var selected_one = selected_one;
	}
	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',
			active: selected_one
		});
	}
} // end instantiate_accordions

function instantiate_defaultText(element) {
	$(element).each(function() {
		if ($(this).val() != $(this)[0].defaultValue) {
			if ($(this).val() == "") {
				$(this).val($(this)[0].defaultValue);
			}
			else {
				// The current value (likely what the user entered before a refresh) isn't the default value, so don't format it as such
				$(this).css("text-align", "left");
			}
		}
	});
} // end instantiate_defaultText()

function instantiate_featuresTabs() {
	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();
			}
		});
		format_stripeTable();
	}
}

function instantiate_findDealerMap() {
	var init = $('#findDealerMap').size();
	if (init!=0) {
		begin_findDealerMap();
	}
} // end instantiate_findDealerMap()

function instantiate_findDealerResult() {
	var init = $('#find_dealer_result').size();
	if (init != 0) {
		// set the variables
		var dealerId;
		var dealerName;
		var dealerAddress;
		var dealerCity;
		var dealerState;
		var dealerZip;
		var dealerPhone;
		var dealerLink;
		var dealerDistance;
		var inventoryUrl = "";

		// get the dealer info
		// check for the cookie
		var myDealerInfo = $.cookie('myDealerInfo');

		if (myDealerInfo) {
			// build the drop-down from the cookie
			var myDealerInfoArray = myDealerInfo.split("~");

			dealerId = myDealerInfoArray[0];
			dealerName = myDealerInfoArray[1];
			dealerAddress = myDealerInfoArray[2];
			dealerCity = myDealerInfoArray[3];
			dealerState = myDealerInfoArray[4];
			dealerZip = myDealerInfoArray[5];
			dealerPhone = myDealerInfoArray[6];
			dealerLink = myDealerInfoArray[7];
			dealerDistance = myDealerInfoArray[8];
		}
		else {
			var dealerInfo = get_dealers(dealerSearchString);

			$(dealerInfo.responseXML).find("marker").each(function(index, thisElement) {
				//alert("index: "+index+"\ndistance: "+distance+"\nsearchRadius: "+searchRadius);
				if (index == 0) {
					// set the variables
					dealerId = $(thisElement).attr("id");
					dealerName = $(thisElement).attr("name");
					dealerAddress = $(thisElement).attr("street");
					dealerCity = $(thisElement).attr("city");
					dealerState = $(thisElement).attr("state");
					dealerZip = $(thisElement).attr("zipcode");
					dealerPhone = $(thisElement).attr("phone");
					dealerLink = $(thisElement).attr("link");
					dealerDistance = $(thisElement).attr("distance");

					// create a cookie and save the dealer's info to it
					var saveDealerInfo = dealerId+"~"+dealerName+"~"+dealerAddress+"~"+dealerCity+"~"+dealerState+"~"+dealerZip+"~"+dealerPhone+"~"+dealerLink+"~"+dealerDistance;
					$.cookie("myDealerInfo", saveDealerInfo, { path: linkPrefix });

				}
			});
		}

		if (dealerName){
     		document.getElementById("find_dealer").className="hiddenFindDealer";
     	}else{
		    if(document.getElementById("find_dealer_result")){
		    	document.getElementById("find_dealer_result").className="hiddenFindDealer";
		    	document.getElementById("find_dealer").className="";
		    }else{
		       document.getElementById("find_dealer_result_preferred").className="hiddenFindDealer";
		       document.getElementById("find_dealer").className="";
		    }
		}

		// build the drop-down
		var dealerNameLink = "<a target='_blank' href='"+dealerLink+"'>"+dealerName+"</a>";

		$('span.dealer_name').empty().append(dealerNameLink);
		$('span.dealer_address').empty().append(dealerAddress);
		$('span.dealer_cityStateZip').empty().append(dealerCity+", "+dealerState+" "+dealerZip);
		$('span.dealer_phone').empty().append(dealerPhone);
		//$('span.dealer_distance').empty().append(dealerDistance);
		$('span a.dealerLink').attr("href", dealerLink);

		if (is_sneDealer(dealerId)){
			inventoryUrl = "/new-inventory.asp";
			quickQuoteUrl = "";
			applyNowUrl = "";
			$('span a.dealerSpecialOffers').hide();
		}
		else {
			inventoryUrl = "/link?program=soa&page=NEW_INVENTORY";
			quickQuoteUrl = "/link?program=soa&page=FINANCE_CENTER";
			applyNowUrl = "/link?program=soa&page=FINANCE_FORM";
			specialOffersUrl = "/link?program=soa&page=SPECIAL_OFFERS";
			$('span a.dealerSpecialOffers').attr("href", dealerLink+specialOffersUrl);
		}

		$('span a.dealerInventoryLink').attr("href", dealerLink+inventoryUrl);
	}
} // end instantiate_findDealerResult

function instantiate_handrail() {
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };

		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;

			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();

			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);

		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass		: 'sf-breadcrumb',
		menuClass	: 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass	: 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 0,
		animation	: {opacity:'show'},
		speed		: 800,
		autoArrows	: false,
		dropShadows : false,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});
	$('ul.sf-menu').superfish();
} // end instantiate_handrail

function instantiate_lazyload() {
	var Init = $(".specialOffer_checkboxes").size();
	//lazy load does weird things on the special offers page. Since it doesnt know that the items have come above the fold.
	if (Init == 0){
		$("img").lazyload();
	}
} // end instantiate_lazyload

function instantiate_omniture() {
	$('.dealerlink').livequery('click', function() {
		// get the dealer info from the element title
		var dealerInfo = $(this).attr("title");

		// send the information to omniture
		DL(dealerInfo);
	});

	$('.inventoryLink').livequery('click', function() {
		// get the dealer info from the element title
		var dealerInfo = $(this).attr("title");

		// send the infromation to omniture
		VI(dealerInfo);
	});

	$('.partner_link').click(function() {
		var linkname = $(this).text();
		var s = s_gi(s_account);
		s.tl(this,'o','my-subaru:partner_link:'+linkname);
	});

	$('.schedule_service_link').click(function () {
		var s = s_gi(s_account);
		s.linkTrackEvents = "event29";
		s.events = "event29";
		s.tl(this, 'o', 'my-subaru:schedule_service_appointment');
	});

	// 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);
	});
}

function instantiate_pngFix(document){
	$(document).pngFix();

}

function instantiate_rotator() {
	//the variables
	var sinceLast = 0;
	var heroTimer = 4000;
	var heroHover = false;
	var timingArray = new Array();
	var curAdj = 1;

	//this is called from the rotator

	function makeHandrailHover(){
		var pod282_open = $("#detergent950 .rotator" + " .pod282_open").size();
			if (pod282_open !=0) {
				$("#detergent950 .rotator" + ' .pod282_open').css({'visibility':'visible'});
				$("#detergent950 .rotator" + ' .pod282_open').accordion({
					header: '.heading',
					selectedClass: 'open',
					event: 'click',
					active: 0,
					collapsible: false
				});
			}

		var pod282_closed = $("#detergent950 .rotator" + " .pod282_closed").size();
			if (pod282_closed !=0) {
				$("#detergent950 .rotator" + ' .pod282_closed').css({'visibility':'visible'});
				$("#detergent950 .rotator" + ' .pod282_closed').accordion({
					header: '.heading',
					selectedClass: 'open',
					event: 'click',
					active: false,
					collapsible: true
				});
			}

		$('#detergent950 .handrail').hover(function() {
			$('#detergent950 .heroMenuHover').fadeOut(100);
		},
		function () {
			$('#detergent950 .heroMenuHover').fadeIn(300);
		});
	}
} // end instantiate_rotator

function instantiate_specialOffersPage() {
	var init = $(".specialOffer_checkboxes").size();
	if (init){
		//you have to delete the special programs from the main full_search because the component is wrong
		//refactor this to use an array of "safe" words, and then delete everything but those words.
		//for now we are manually deleting certain special offers.
		$(".no_programs .Graduate, .no_programs .Brake, .no_programs .Inspection, .no_programs .Cabin").remove();

		//Creating a different component just for the college special is unreasonable. Let's just delete the bits
		//that we dont want.
		$(".specialOffers_default .special_programs").each(function(){
				var superSpecialOffer = $(this).find("h2 a").text();
			if (superSpecialOffer == "College Graduate Program" ){
		   $(this).find("h2").remove();
		   $(this).find(".specialOffersLinkWrapper").remove();
		   $(this).find("p.full_title").css("padding-top", "0px");

		}

		}); //end - each specialOffers_default .special_programs
		$(".Special-Programs .special_programs").each(function(){
			var superSpecialOffer = $(this).find("h2 a").text();
		if (superSpecialOffer == "College Graduate Program" ){
		   $(this).find("h2").remove();
		   $(this).find(".specialOffersLinkWrapper").remove();
		   $(this).find("p.full_title").css("padding-top", "0px");

		}
		}); // end each .special-programs .special_programs
		//hide all "other" searches
		$(".Purchase-Offers, .Financing, .Lease-Offers").hide();
		$(".full_search").addClass("shown_search");
		var checkedBoxes = 0;
		$('.specialOffer_checkboxes input').each(function(){
			if (defaultCheckbox == "all"){
				$(this).attr('checked', false);
			} else {
				if ($(this).attr("value") == defaultCheckbox){
					$(this).attr('checked', true);
				}
			}

		});

		$(".full_search").show();
		$(".specialOffers .specialOfferItem").each(function(i){
			if ($(this).hasClass("WRX")){
				$(this).removeClass("Impreza");
			}
		});
				var checkedVehicleBoxes = 0;
				$(".specialOffers").hide();
				$(".specialOffers").removeClass("shown_search");
				$('.specialOffer_checkboxes input:not(:checked)').each(function(){
						var wrapperName = $(this).attr("name");
						var offerName = $(this).attr("value");
		//				$("."+wrapperName).show();
						var a = "."+offerName;

						$(a).addClass("hide");

					listen_specialOffersCountShown();
				});
				$('.specialOffer_checkboxes input:checked').each(function(){
						var wrapperName = $(this).attr("name");
						var offerName = $(this).attr("value");
						$("."+wrapperName).show();
						$("."+wrapperName).addClass("shown_search");
						if(wrapperName!="full_search"){
							$(".full_search").hide();
							$(".full_search").removeClass("shown_search");

						} else {
							checkedVehicleBoxes++;
						}
						var a = "."+offerName;

						$(a).removeClass("hide");

					checkedBoxes++;
					listen_specialOffersCountShown();
				});
				if (checkedBoxes == 0){

					//hide all "other" searches
					$(".Customer-Cash, .Cash-Back, .Financing, .Lease-Offers").hide();
					$(".full_search").show();
					$(".full_search").addClass("shown_search");
					$(".specialOfferItem").removeClass("hide");
					listen_specialOffersCountShown();

				}

				if (checkedVehicleBoxes == 0){

					$(".specialOfferItem").removeClass("hide");
					listen_specialOffersCountShown();

				} else {
					$(".specialOffers_default").hide();
					$(".specialOffers_default .specialOfferItem").addClass("hide");
					listen_specialOffersCountShown();
				}

		listen_specialOffersHideShowDetailsLinks();
		listen_specialOffersChangeCheckboxes();
		listen_specialOffersCountShown();
		listen_specialOffersOverride();


	}
}

function instantiate_specialOffersPage_MySubaru(){
	var init = $(".mysub-specialOffers").size();
	if (init){
			$(".specialOffers .specialOfferItem").each(function(){
				var superSpecialOffer = $(this).find("h2 a").text();
		if (superSpecialOffer == "College Graduate Program" || superSpecialOffer == "Free Vehicle Inspection" || superSpecialOffer == "Genuine Subaru Cabin Air Filter" ){
			   $(this).find("h2").remove();
			   $(this).find(".specialOffersLinkWrapper").remove();
			   $(this).find(".msrp").remove();
			   $(this).find("p.toggle_close").remove();
			   $(this).find("p.full_title").css("padding-top", "0px");

			}

			}); //end - each .specialOffers .specialOffersItem
		listen_specialOffersHideShowDetailsLinks();
	}
}

function instantiate_vehicleLandingPages() {
	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"));
	}

	var init = $(".close").size();
	if (init != 0) {
		var current;
		$(".model_intro_a .popup_window	 ").css({display: "none"});
		$(".model_intro_a .close").hover(function() {
			//hide the big window
			$(".model_intro_a .popup_window	 ").fadeOut(300);
			//undue the hover class on the li tag
			$(".model_intro_a .trims li").removeClass("hover");
			$('.model_intro_a div').remove('#arrow_pointer');
		},function() {});

		$(".model_intro_a .trims li").hover(function() {

			if ($(this).hasClass('hover')) {
				return false;
			} else {
				var layer = $(this).attr('class');
				$(".model_intro_a .trims li").removeClass("hover");
				$('.model_intro_a div').remove('#arrow_pointer');
				$("." + layer).addClass("hover");
				$(".model_intro_a .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;
		});
	}

	var component_3e = $(".component_3e").size();
	if (component_3e != 0) {
		// preload images
		var img = ['button_brochure.gif', 'button_review.gif', 'button_video.gif', 'button_brochure_over.gif', 'button_review_over.gif', 'button_video_over.gif'];
		$(img).each(function () {
			var i = new Image();
			i.src = pathPrefix+'images/site/' + this;
		});
	}

} // end instantiate_vehicleLandingPages


//-----------------------------------------------------------------------------------
//7.0 is_
//
// accepts paramater(s) to test
// returns bool
//-----------------------------------------------------------------------------------

function is_sneDealer(dealerid) {
	if (dealerid === undefined) {dealerid="0";}
	var region_code = dealerid.slice(0,3);

	if (region_code == "010") {
		return true;
	}
	else {
		return false;
	}
} // end is_sneDealer

//-----------------------------------------------------------------------------------
//8.0 listen_
//
// functions called from above document.ready that wait.
// These are for .click() and .hover() functions (excluding form submit buttons)
//-----------------------------------------------------------------------------------

function listen_defaultText(element) {
	$(element).focus(function() {
		if ($(this).val() == $(this)[0].defaultValue) {
			$(this).val("");
			//$(this).removeClass("defaultText");
			$(this).css("text-align", "left");
		}
	}).blur(function() {
		if ($(this).val() == "") {
			//$(this).addClass("defaultText");
			$(this).css("text-align", "center");
			$(this).val($(this)[0].defaultValue);
		}
	});
} // end listen_defaultText

function listen_dropDowns(element) {
	//	$("#header .bottom_menus li ").bgiframe();
	//	$("#header .global_button ").bgiframe();

	$(".no_drop", element).each(function() {
		$(this).hover(function() {
			$(".drop_down li div").hide();
			$(this).addClass("deep_hover");
		},function() {
			$("li").removeClass("deep_hover");
		});
	});

	$(".j_drop", element).each(function() {
		var div = this;
		$(this).parent().hover(function() {
			//top level nav elements immediately hide the drop nav
			if ($(this).parent().attr("class") == "bottom_menus") {
				$(".drop_down").hide();
				$(".drop_down .drop_down").hide();//a weird IE thing that happens where it just closes the first one.
			}
			if ($(this).attr("class") == "c_drop") {
				$(".drop_down li div").hide();
				$(this).addClass("deep_hover");
			}
			$(div).stop(true).show();
		},function() {
			$("li").removeClass("deep_hover");
			$(div).delay(400, function() {
				$(this).hide();
			});
		});

		$(this).children().children().hover(function() { //not the UL one more down to the li
			$(this).addClass("deep_hover");
		},function() {
			$(this).removeClass("deep_hover");
		});

		listen_dropDowns($("ul li", this)); // Recursion!
	});
} // end listen_dropDowns

function listen_findDealerBody() {
	$('#form_find_dealer_body input#dealerZip_body').keypress(function(e){
		if (e.which == 13) {
			e.preventDefault();
			var inputValue = $(this).val();
			validate_findDealer("form_find_dealer_body", inputValue, "City/State or Zip");
		}
	});
	$('#form_find_dealer_body input.submit_findDealer_body').click(function(e){
		e.preventDefault();
		var inputValue = $('#form_find_dealer_body input#dealerZip_body').val();
		validate_findDealer("form_find_dealer_body", inputValue);
	});
}

function listen_findDealerHeader() {
	$('#form_find_dealer_header input#dealerZip_header').keypress(function(e){
		if (e.which == 13) {
			e.preventDefault();
			var inputValue = $(this).val();
			validate_findDealer("form_find_dealer_header", inputValue, "City/State or Zip");
		}
	});
	$('#form_find_dealer_header input.submit_findDealer_header').click(function(e){
		e.preventDefault();
		var inputValue = $('#form_find_dealer_header input#dealerZip_header').val();
		validate_findDealer("form_find_dealer_header", inputValue);
	});
} // end listen_findDealerHeader

function listen_findDealerModal() {
	$('#form_modalFindDealer input#modalZip').keypress(function(e){
		if (e.which == 13) {
			e.preventDefault();
			var inputValue = $(this).val();
			validate_findDealer("form_modalFindDealer", inputValue, "City/State or Zip");
		}
	});
	$('#form_modalFindDealer input.submit_modalFindDealer').click(function(e){
		e.preventDefault();
		var inputValue = $('#form_modalFindDealer input#modalZip').val();
		validate_findDealer("form_modalFindDealer", inputValue);
	});
} // end listen_findDealerModal()

function listen_findDealerSPT() {
	$('#form_findDealer3 input#dealerZip3').keypress(function(e){
		if (e.which == 13) {
			e.preventDefault();
			var inputValue = $(this).val();
			validate_findDealer("form_findDealer3", inputValue, "City/State or Zip");
		}
	});
	$('#form_findDealer3 input.submit_findDealer').click(function(e){
		e.preventDefault();
		var inputValue = $('#form_findDealer3 input#dealerZip3').val();
		validate_findDealer("form_findDealer3", inputValue);
	});
} // end listen_findDealerSPT()

function listen_findDealerWindowSticker() {
	$('#form_find_dealer_window_sticker input#dealerZip_ws').keypress(function(e){
		if (e.which == 13) {
			e.preventDefault();
			var inputValue = $(this).val();
			validate_findDealer("form_find_dealer_window_sticker", inputValue, "Enter Zip");
		}
	});
	$('#form_find_dealer_window_sticker input.submit_findDealer_window_sticker').click(function(e){
		e.preventDefault();
		var inputValue = $('#form_find_dealer_window_sticker input#dealerZip_ws').val();
		validate_findDealer("form_find_dealer_window_sticker", inputValue);
	});
}

function listen_hoverClass() {
	$(".global_button").hover(function () {
		$(this).addClass("global_hover")
	}, function () {
		$(this).removeClass("global_hover")
	});
} // end listen_hoverClass

function listen_specialOffersChangeCheckboxes() {
	$(".specialOffer_checkboxes .checkbox").click(function(){
		var checkedBoxes = 0;
		var checkedVehicleBoxes = 0;
		$(".specialOffers").hide();
		$(".specialOffers").removeClass("shown_search");
		$('.specialOffer_checkboxes input:not(:checked)').each(function(){
				var wrapperName = $(this).attr("name");
				var offerName = $(this).attr("value");
//				$("."+wrapperName).show();
				var a = "."+offerName;

				$(a).addClass("hide");

			listen_specialOffersCountShown();
		});
		$('.specialOffer_checkboxes input:checked').each(function(){
				var wrapperName = $(this).attr("name");
				var offerName = $(this).attr("value");
				$("."+wrapperName).show();
				$("."+wrapperName).addClass("shown_search");
				if(wrapperName!="full_search"){
					$(".full_search").hide();
					$(".full_search").removeClass("shown_search");

				} else {
					checkedVehicleBoxes++;
				}
				var a = "."+offerName;

				$(a).removeClass("hide");

			checkedBoxes++;
			listen_specialOffersCountShown();
		});
		if (checkedBoxes == 0){

			//hide all "other" searches
			$(".Customer-Cash, .Cash-Back, .Financing, .Lease-Offers").hide();
			$(".full_search").show();
			$(".full_search").addClass("shown_search");
			$(".specialOfferItem").removeClass("hide");
			listen_specialOffersCountShown();

		}

		if (checkedVehicleBoxes == 0){

			$(".specialOfferItem").removeClass("hide");
			listen_specialOffersCountShown();

		} else {
			$(".specialOffers_default").hide();
			$(".specialOffers_default .specialOfferItem").addClass("hide");
			listen_specialOffersCountShown();
		}

//		listen_specialOffersCountShown();

	});


}

function listen_specialOffersCountShown() {
	var shown = 0;
	$(".shown_search .specialOfferItem").each(function(total){
		if (!$(this).hasClass("hide")){
			shown++;
		}
	});
	$(".shownoftotal .shown").text(shown);
	var specialOffersErrorMessage = $(".specialOffers_head p").hasClass("specialOffersErrorMessage");
	if (shown == 0 && !$(".specialOffers_head p").hasClass("specialOffersErrorMessage")){
		var errorHTML = '<p class="specialOffersErrorMessage">Sorry, there are no offers for this search criteria.</p>';
		$(".specialOffers_head .shownoftotal").append(errorHTML);
	}	else {
		$(".specialOffersErrorMessage").remove();

	}

	$(".full_search .specialOfferItem").each(function(total){
		$(".shownoftotal .total").text(total+1);
	});
}

function listen_specialOffersHideShowDetailsLinks() {
	//$("p.toggle_close a .open").hide();
	$(".toggle_close span").click(
		function(){
		var a = $(this).attr("class");
		if (a == "hideDetails"){
			$(this).hide();
			$(this).next().show();
			$(this).parent().parent().next().hide();
		} else {
			$(this).prev().show();
			$(this).hide();
			$(this).parent().parent().next().show();

		}
		return false;
		}
	);

}

function listen_specialOffersOverride(){
	var overrider = false;
	var overrider_a = false;
	var overrider_b = false;
	var overrider_c = false;
	var overrider_d = false;
	var overrider_e = false;
	var overrider_f = false;

	$('.specialOffers div').each(function(){
		if ($(this).hasClass('overrider')){
		overrider = true;
		}
		if ($(this).hasClass('overrider_a' )){
		overrider_a = true;
		}
		if ($(this).hasClass('overrider_b')){
		overrider_b = true;
		}
		if ($(this).hasClass('overrider_c')){
		overrider_c = true;
		}
		if ($(this).hasClass('overrider_d')){
		overrider_d = true;
		}
		if ($(this).hasClass('overrider_e')){
		overrider_e = true;
		}
		if ($(this).hasClass('overrider_f')){
		overrider_f = true;
		}
	});

	if (overrider || overrider_a || overrider_b || overrider_c || overrider_d || overrider_e || overrider_f){
		$('.specialOffers div').each(function(){
			if (overrider){
				if ($(this).hasClass('overridden')){
					$(this).hide();
				}
			}
			if (overrider_a){
				if ($(this).hasClass('overridden_a')){
					$(this).hide();
				}
			}
			if (overrider_b){
				if ($(this).hasClass('overridden_b')){
					$(this).hide();
				}
			}
			if (overrider_c){
				if ($(this).hasClass('overridden_c')){
					$(this).hide();
				}
			}
			if (overrider_d){
				if ($(this).hasClass('overridden_d')){
					$(this).hide();
				}
			}
			if (overrider_e){
				if ($(this).hasClass('overridden_e')){
					$(this).hide();
				}
			}
			if (overrider_f){
				if ($(this).hasClass('overridden_f')){
					$(this).hide();
				}
			}
		});
	}

}

function listen_modalClose() {
	$('a.closeModal').livequery('click', function() {
		$.modal.close();
	});

	$('#modalOverlay').css({height:($(document).height().toString() + "px"), overflow:"hidden"});

}

function listen_twoColumn(){
	//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');
		});
	}
}
//-----------------------------------------------------------------------------------
//9.0 submit_
//
// functions that submit forms based on a button .click()
//-----------------------------------------------------------------------------------


//-----------------------------------------------------------------------------------
//10.0 update_
//-----------------------------------------------------------------------------------

function update_myDealer(dealertype,dealerid,targeturl,vehicle) {
	var targetForm = '#set_dealer_' + dealertype;
	var formAction = "";
	if (dealertype == "preferred") {
		formAction = linkPrefix+'tools/maps/user/setpreferreddealer';
	}
	else if (dealertype == "service") {
		formAction = linkPrefix+'tools/maps/vehicle/setservicedealer';
	}
	//var currentAction = $(targetForm).attr("action");
	//var formAction = secureUrl+currentAction;
	$(targetForm + ' input[name=targetUrl]').val(targeturl);
	$(targetForm + ' input[name='+dealertype+'DealerId]').val(dealerid);
	$(targetForm).attr('action', formAction);
	if (!vehicle) {}
	else {$(targetForm + ' input[name=vehicleId]').val(vehicle);}

	//$(targetForm).serialize();
	//$(targetForm).submit();
	var formData = $(targetForm).serialize();
	var formUrl = $(targetForm).attr("action");
	//	/tools/gtp/vehicle/sendgtpinformation
	newTarget = targeturl.substr(1);
	//var redirectURL = linkPrefix+'my-subaru/my-account/index.html';
	var redirectURL = targeturl;
	$.ajax({
		type: "post",
		url: formAction,
		data: formData,
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			window.location.assign(redirectURL);
		},
		success: function(data, textStatus) {
			window.location.assign(redirectURL);
		}
	});
}

//-----------------------------------------------------------------------------------
//11.0 validate_
//-----------------------------------------------------------------------------------

function validate_findDealer(formId, inputValue, helpText) {
	if (helpText === undefined) {
		helpText = "City/State or Zip";
	}
	// city/state regular expression
	var csRegVal = /^\s*([a-zA-Z]{3,}\s*)+[,|\/]\s*([a-zA-Z]{2,})\s*$/;
	var csRegex = new RegExp(csRegVal);

	var opt = "";
	// check for all possible optional parameters
	var params		= window.location.search; // parameters in the url
	var mo			= $('#'+formId + ' input[name=modalOptions]').val(); // modal options appended to the redirectURL
	var ov			= $('#'+formId + ' input[name=optionalParameter]').val(); // optionalParameter={ov}
	var mOptions	= (mo === undefined) ? "" : mo;
	var optValue	= (ov === undefined) ? "" : ov;

	if (params.length > 0) {
		opt += params; // includes "?" at start of string
		if (mOptions.length > 0) {
			opt += "&"+mOptions;
		}
		if (optValue.length != 0) {
			opt += "&optionalParameter="+optValue;
		}
	}
	else if (params.length == 0) {
		if (mOptions.length > 0) {
			opt += "?"+mOptions;
			if (optValue.length != 0) {
				opt += "&optionalParameter="+optValue;
			}
		}
		else if (mOptions.length == 0) {
			if (optValue.length != 0) {
				opt += "?optionalParameter="+optValue;
			}
		}
	}

	var redirectURL = "";
	if (secureServer.length > 0) {
		redirectURL = linkPrefix+'tools/maps/dealer/find/';
	}

	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;
			$('#'+formId + ' input[name=zipcode]').val(newInputValue);

			// submit the form
			$.cookie("myDealerInfo", null, { path: linkPrefix });
			if (redirectURL.length > 0){
				redirectURL += newInputValue + opt;
				window.location.assign(redirectURL);
			}
			else {
				$('#'+formId).submit();
			}
		}
		else {
			$('#'+formId + ' input[name=zipcode]').val(helpText);
		}
	}
	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
			$.cookie("myDealerInfo", null, { path: linkPrefix });
			if (redirectURL.length > 0){
				redirectURL += isZip + opt;
				window.location.assign(redirectURL);
			}
			else {
				$('#'+formId).submit();
			}
		}
		else if (isZip.length == 0 && inputValue.length > 1) {
			// 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
				$('#'+formId + ' input[name=zipcode]').val(inputMatchesState);

				// submit the form
				$.cookie("myDealerInfo", null, { path: linkPrefix });
				if (redirectURL.length > 0){
					redirectURL += inputMatchesState + opt;
					window.location.assign(redirectURL);
				}
				else {
					$('#'+formId).submit();
				}
			}
			else {
				$('#'+formId + ' input[name=zipcode]').val(helpText);
			}
		}
	}
} // end validate_findDealer

function validate_findDealerChinese(formId, inputValue, helpText) {
	if (helpText === undefined) {
		helpText = "City/State or Zip";
	}
	// city/state regular expression
	var csRegVal = /^\s*([a-zA-Z]{3,}\s*)+[,|\/]\s*([a-zA-Z]{2,})\s*$/;
	var csRegex = new RegExp(csRegVal);

	var opt = "";
	// check for all possible optional parameters
	var params		= window.location.search; // parameters in the url
	var mo			= $('#'+formId + ' input[name=modalOptions]').val(); // modal options appended to the redirectURL
	var ov			= $('#'+formId + ' input[name=optionalParameter]').val(); // optionalParameter={ov}
	var mOptions	= (mo === undefined) ? "" : mo;
	var optValue	= (ov === undefined) ? "" : ov;

	if (params.length > 0) {
		opt += params; // includes "?" at start of string
		if (mOptions.length > 0) {
			opt += "&"+mOptions;
		}
		if (optValue.length != 0) {
			opt += "&optionalParameter="+optValue;
		}
	}
	else if (params.length == 0) {
		if (mOptions.length > 0) {
			opt += "?"+mOptions;
			if (optValue.length != 0) {
				opt += "&optionalParameter="+optValue;
			}
		}
		else if (mOptions.length == 0) {
			if (optValue.length != 0) {
				opt += "?optionalParameter="+optValue;
			}
		}
	}

	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;
			$('#'+formId + ' input[name=zipcode]').val(newInputValue);
		}
		else {
			$('#'+formId + ' input[name=zipcode]').val(helpText);
		}
	}
	else {
		// determine if a 5-digit zipcode was submitted
		var isZip = inputValue.replace(/[^\d]/g, "").substr(0,5);
		$('#'+formId + ' input[name=zipcode]').val(isZip);

		if (isZip.length == 0 && inputValue.length > 1) {
			// 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
				$('#'+formId + ' input[name=zipcode]').val(inputMatchesState);			}
			else {
				$('#'+formId + ' input[name=zipcode]').val(helpText);
			}
		}
	}
} // end validate_findDealer


//-----------------------------------------------------------------------------------
//12.0 validation_objects
//-----------------------------------------------------------------------------------

var usStates = [
	{stateAbbrev: "AL", stateName: "Alabama", stateCapital: "Montgomery"},
	{stateAbbrev: "AK", stateName: "Alaska", stateCapital: "Juneau"},
	{stateAbbrev: "AZ", stateName: "Arizona", stateCapital: "Phoenix"},
	{stateAbbrev: "AR", stateName: "Arkansas", stateCapital: "Little Rock"},
	{stateAbbrev: "CA", stateName: "California", stateCapital: "Sacramento"},
	{stateAbbrev: "CO", stateName: "Colorado", stateCapital: "Denver"},
	{stateAbbrev: "CT", stateName: "Connecticut", stateCapital: "Hartford"},
	{stateAbbrev: "DE", stateName: "Delaware", stateCapital: "Dover"},
	{stateAbbrev: "DC", stateName: "District of Columbia"},
	{stateAbbrev: "FL", stateName: "Florida", stateCapital: "Tallahassee"},
	{stateAbbrev: "GA", stateName: "Georgia", stateCapital: "Atlanta"},
	{stateAbbrev: "HI", stateName: "Hawaii", stateCapital: "Honolulu"},
	{stateAbbrev: "ID", stateName: "Idaho", stateCapital: "Boise"},
	{stateAbbrev: "IL", stateName: "Illinois", stateCapital: "Springfield"},
	{stateAbbrev: "IN", stateName: "Indiana", stateCapital: "Indianapolis"},
	{stateAbbrev: "IA", stateName: "Iowa", stateCapital: "Des Moines"},
	{stateAbbrev: "KS", stateName: "Kansas", stateCapital: "Topeka"},
	{stateAbbrev: "KY", stateName: "Kentucky", stateCapital: "Frankfort"},
	{stateAbbrev: "LA", stateName: "Louisiana", stateCapital: "Baton Rouge"},
	{stateAbbrev: "ME", stateName: "Maine", stateCapital: "Augusta"},
	{stateAbbrev: "MD", stateName: "Maryland", stateCapital: "Annapolis"},
	{stateAbbrev: "MA", stateName: "Massachusetts", stateCapital: "Boston"},
	{stateAbbrev: "MI", stateName: "Michigan", stateCapital: "Lansing"},
	{stateAbbrev: "MN", stateName: "Minnesota", stateCapital: "Minneapolis"},
	{stateAbbrev: "MS", stateName: "Mississippi", stateCapital: "Jackson"},
	{stateAbbrev: "MO", stateName: "Missouri", stateCapital: "Jefferson City"},
	{stateAbbrev: "MT", stateName: "Montana", stateCapital: "Helena"},
	{stateAbbrev: "NE", stateName: "Nebraska", stateCapital: "Lincoln"},
	{stateAbbrev: "NV", stateName: "Nevada", stateCapital: "Carson City"},
	{stateAbbrev: "NH", stateName: "New Hampshire", stateCapital: "Concord"},
	{stateAbbrev: "NJ", stateName: "New Jersey", stateCapital: "Trenton"},
	{stateAbbrev: "NM", stateName: "New Mexico", stateCapital: "Sante Fe"},
	{stateAbbrev: "NY", stateName: "New York", stateCapital: "Albany"},
	{stateAbbrev: "NC", stateName: "North Carolina", stateCapital: "Raleigh"},
	{stateAbbrev: "ND", stateName: "North Dakota", stateCapital: "Bismarck"},
	{stateAbbrev: "OH", stateName: "Ohio", stateCapital: "Columbus"},
	{stateAbbrev: "OK", stateName: "Oklahoma", stateCapital: "Oklahoma City"},
	{stateAbbrev: "OR", stateName: "Oregon", stateCapital: "Salem"},
	{stateAbbrev: "PA", stateName: "Pennsylvania", stateCapital: "Harrisburg"},
	{stateAbbrev: "RI", stateName: "Rhode Island", stateCapital: "Providence"},
	{stateAbbrev: "SC", stateName: "South Carolina", stateCapital: "Columbia"},
	{stateAbbrev: "SD", stateName: "South Dakota", stateCapital: "Pierre"},
	{stateAbbrev: "TN", stateName: "Tennessee", stateCapital: "Nashville"},
	{stateAbbrev: "TX", stateName: "Texas", stateCapital: "Austin"},
	{stateAbbrev: "UT", stateName: "Utah", stateCapital: "Salt Lake City"},
	{stateAbbrev: "VT", stateName: "Vermont", stateCapital: "Montpelier"},
	{stateAbbrev: "VA", stateName: "Virginia", stateCapital: "Richmond"},
	{stateAbbrev: "WA", stateName: "Washington", stateCapital: "Olympia"},
	{stateAbbrev: "WV", stateName: "West Virginia", stateCapital: "Charleston"},
	{stateAbbrev: "WI", stateName: "Wisconsin", stateCapital: "Madison"},
	{stateAbbrev: "WY", stateName: "Wyoming", stateCapital: "Cheyenne"}
];

//-----------------------------------------------------------------------------------
//13.0 flash interaction
// Do Not change these function names. They are called from ActionScript
//-----------------------------------------------------------------------------------

//
// Opens a modal print summary dialog and populates the dialog
// with data in the specified properties map.
//
function openPrintSummaryModal(properties) {
	var raqLink = linkPrefix+"shopping-tools/get-quote.html?model="+properties.model+"&trim="+properties.trim+"&year="+properties.year;
	var satdLink = linkPrefix+"shopping-tools/schedule-test-drive.html?model="+properties.model+"&trim="+properties.trim+"&year="+properties.year;

	// 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});

	$('.getAQuote_link').attr("href", raqLink);
	$('.scheduleTestDrive_link').attr("href", satdLink);

	// 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();
}
