//--------------------------------------------------------------
//	website:	subaru.com
//	type:		All functions excluding homepage
//	desc:		requires jQuery 1.2.6
//	Date:		10.31.09
//-----------------------------------------------------------
//
//	0.0 Global Variables
//	1.0 Instantiate - $(function() {}
//	2.0 create_
//	3.0 delete_
//	4.0 format_
//	5.0 get_
//	6.0 instantiate_
//	7.0 is_
//	8.0 submit_
//	9.0 update_
//	10.0 validate_
//
//----------------------------------------------------------------

//-----------------------------------------------------------------------------------
//0.0 Global variables
//-----------------------------------------------------------------------------------

var serviceRecordCounter = 0;
var minDate = new Date(1995, 1 - 1, 1);
var maxDate = new Date(2012, 1 - 1, 1);


//-----------------------------------------------------------------------------------
//1.0 Instantiate - $(function() {}
//-----------------------------------------------------------------------------------


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

	//Fix anchor to put '#' in url
	fixAnchors();

	// instantiate_
	instantiate_bluetoothCompatibility();
	instantiate_dearSubaruCharacterCounter();
	//forms
	instantiate_formAccountCreation();
	instantiate_formAddServiceRecord();
	instantiate_formAddVehicle();
	instantiate_formContactUs();
	instantiate_formDearSubaru();
	instantiate_formForgotEmail();
	instantiate_formForgotPassword();
	instantiate_formGetGtpInfo();
	instantiate_formGtpRedemtion();
	instantiate_formMySubaruLogin();
	instantiate_formPayments();
	instantiate_formPopup282();
	instantiate_formPopup590();
	instantiate_formRedirectedAccountCreation();
	instantiate_formReservationSti();
	instantiate_formRequestBrochure();
	instantiate_formViewBrochure();
	instantiate_formRequestQuote();
	instantiate_formScheduleTestDrive();
	instantiate_formSignUpForUpdates();
	instantiate_formSuggestLink();
	instantiate_formUpdateContactInfo();
	instantiate_formUpdateLogin();
	instantiate_formUpdateVehicle();
	instantiate_formFindDealerChinese();
	instantiate_mySubaruIndexPage();
	instantiate_mySubaruDealerPage();
	instantiate_mySubaruGtp();
	instantiate_mySubaruProfile();
	instantiate_ownerEvents();
	instantiate_rolldownItems();
	instantiate_thankYouRaqSatd();
	instantiate_vehicleMaintenanceTabs();
	instantiate_vehicleServiceHistory();


	// listen_
	listen_changeDealer();
	listen_changeOwnerEventsLink();
	listen_clueTips();
	listen_clueTipsGtp();
	listen_deleteVehicle();
	listen_formClose();
	listen_formClosePopup();
	listen_formOpen();
	listen_formReOpen();
	listen_formUpdateServiceRecord();
	listen_gtpDisclaimerSymbol();
	listen_gtpModal();
	listen_gtpPrintModalClose();
	listen_gtpShowForm();
	listen_gtpSubmit();
	listen_specials();


}); //end of document.ready

//-----------------------------------------------------------------------------------
//2.0 create_
//-----------------------------------------------------------------------------------

function fixAnchors(){

	$("a[href=#]").bind("click", function(e){
		e.preventDefault();
	});
	$("a.closeModal img").bind("click", function(e){
		e.preventDefault();
	});
}

function create_blueToothAccessoryOptions(optionCode){
	var btAccessories = $.ajax({
		url: pathPrefix+'conf/bluetooth.xml',
		async: false,
		cache: false
	});
	var optionArray = optionCode.split("|");
	var options = '<option value="noSelection">Select an Option Package</option>';
	$(btAccessories.responseXML).find("options option").each(function() {
		var accessoryId = $(this).attr("id");
		var accessoryName = $(this).attr("optionName");
		$(optionArray).each(function(index, thisElement){
			if (thisElement == accessoryId) {
				options += "<option value='"+accessoryId+"'>"+accessoryName+"</option>";
			}
		});
	});
	return options;
} // end create_blueToothAccessoryOptions

function create_blueToothCarrierOptions(optionCode) {
	var carriers = "";
	var options = '<option value="noSelection">Select a Carrier</option>';
	if (optionCode == 2) {
		carriers = $.ajax({
			url: linkPrefix+'bluetooth/getcarriers.taf?region=us',
			async: false,
			cache: false
		});
		$(carriers.responseXML).find("carrier").each(function() {
			var carrierId = $(this).attr("id");
			var carrierName = $(this).text();
			options += "<option value='"+carrierId+"'>"+carrierName+"</option>";
		});
	}
	else {
		carriers = $.ajax({
			url: pathPrefix+'conf/bluetooth.xml',
			async: false,
			cache: false
		});
		$(carriers.responseXML).find("types type[id="+optionCode+"] carrier").each(function() {
			var carrierId = $(this).attr("carrierId");
			var carrierName = $(carriers.responseXML).find("carriers carrier[id="+carrierId+"]").attr("carrierName");
			options += "<option value='"+carrierId+"'>"+carrierName+"</option>";
		});
	}
	return options;
} // end create_blueToothCarrierOptions

function create_blueToothManufacturerOptions(optionCode, carrierId) {
	var manufacturers = "";
	var options = '<option value="noSelection">Select a Manufacturer</option>';
	if (optionCode == 2) {
		manufacturers = $.ajax({
			url: linkPrefix+'bluetooth/getmanus.taf?region=us&carrier='+carrierId,
			async: false,
			cache: false
		});
		$(manufacturers.responseXML).find("manufacturer").each(function() {
			var manId = $(this).attr("id");
			var manName = $(this).text();
			options += "<option value='"+manId+"'>"+manName+"</option>";
		});
	}
	else {
		manufacturers = $.ajax({
			url: pathPrefix+'conf/bluetooth.xml',
			async: false,
			cache: false
		});
		$(manufacturers.responseXML).find("types type[id="+optionCode+"] carrier[carrierId="+carrierId+"] manufacturer").each(function() {
			var manId = $(this).attr("manId");
			var manName = $(manufacturers.responseXML).find("manufacturers manufacturer[id="+manId+"]").attr("name");
			options += "<option value='"+manId+"'>"+manName+"</option>";
		});
	}
	return options;
} // end create_blueToothManufacturerOptions

function create_blueToothModelOptions(modelYear) {
	var models = $.ajax({
		url: pathPrefix+'conf/bluetooth.xml',
		async: false,
		cache: false
	});
	var options = '<option value="noSelection">Select a Model</option>';
	$(models.responseXML).find("modelYears year[id="+modelYear+"] model").each(function() {
		var modelName = $(this).attr("name");
		var btOptions = $(this).attr("options");
		options += "<option value='"+btOptions+"'>"+modelName+"</option>";
	});
	return options;
} // end create_blueToothModelOptions

function create_blueToothPhoneOptions(optionCode, carrierId, manId) {
	var phones = "";
	var options = '<option value="noSelection">Select a Phone</option>';
	if (optionCode == 2) {
		phones = $.ajax({
			url: linkPrefix+'bluetooth/find.taf?region=us&carrier='+carrierId+'&manufacturer='+manId,
			async: false,
			cache: false
		});

		$(phones.responseXML).find("phones phone").each(function() {
			var phoneId = $(this).attr("id");
			var phoneName = $(this).find("phonename").text();
			var phoneManufacturer = $(this).find("manufacturer").text();
			var phoneImage = $(this).find("imageurl").text();
			options += "<option value='"+phoneId+"'>"+phoneName+"</option>";
		});
	}
	else {
		phones = $.ajax({
			url: pathPrefix+'conf/bluetooth.xml',
			async: false,
			cache: false
		});
		$(phones.responseXML).find("types type[id="+optionCode+"] carrier[carrierId="+carrierId+"] manufacturer[manId="+manId+"] phone").each(function() {
			var phoneId = $(this).attr("phoneId");
			var phoneName = $(phones.responseXML).find("manufacturers manufacturer[id="+manId+"] phone[id="+phoneId+"]").attr("name");
			if (phoneName.length > 0) {
				options += "<option value='"+phoneId+"'>"+phoneName+"</option>";
			}
		});
	}
	return options;
} // end create_blueToothPhoneOptions

function create_brochuresOptions(year) {
	if (year == undefined) { year = 'none'; }
	var brochures = get_brochureInfo();
	var options = "<option value='noSelection' selected='selected'>Select Brochure</option>";
	$(brochures.responseXML).find("brochure[year="+year+"]").each(function() {
		$(this).find("model").each(function() {
			var mid = $(this).attr("id");
			options += "<option value='"+mid+"'>"+mid+"</option>";
		})
	});
	return options
} // end create_brochuresOptions

function create_viewBrochureOptions() {
	year = '2010';
	var brochures = get_brochureInfo();
	var options = "<option value='noSelection' selected='selected'>Select Brochure</option>";
	$(brochures.responseXML).find("brochure[year="+year+"]").each(function() {
		$(this).find("model").each(function() {
			if ($(this).attr("flipbook") != '') {
				var mid = $(this).attr("flipbookid");
				var fblink = $(this).attr("flipbook");
				options += "<option value='" + fblink + "'>" + mid + "</option>";
			}
		})
	});
	return options
} // end create_viewBrochureOptions

function create_daysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this;
}

function create_dealerRadioGroup(zip, searchRadius) {
   // alert ("creando botones");
	// get the dealer information
	var dealers = get_dealerInfo(zip);

	// build the dealer list
	var dealerList = '';
	var dealerInfo = '';
	var countDealers=0;
	$(dealers.responseXML).find("marker").each(function(index, thisElement) {
		var distance = parseFloat($(thisElement).attr("distance"));
		//alert("index: "+index+"\ndistance: "+distance+"\nsearchRadius: "+searchRadius);
		if (index < 6 && (distance <= searchRadius)) {
			// set the variables
			countDealers++;
			var markerID = $(thisElement).attr("id");
			var dealerName = $(thisElement).attr("name");
			var dealerAddress = $(thisElement).attr("street");
			var dealerCity = $(thisElement).attr("city");
			var dealerState = $(thisElement).attr("state");
			var dealerZip = $(thisElement).attr("zipcode");
			var dealerPhone = $(thisElement).attr("phone");
			var dealerLink = $(thisElement).attr("link");
			var lat = $(thisElement).attr("lat");
			var lng = $(thisElement).attr("lng");

			dealerList += "\n\t<li>";

			if (index == 0) {
				dealerList += "<input title=\"" + dealerName + "~" + dealerAddress + "~" + dealerCity + "~" + dealerState + "~" + dealerZip + "~" + dealerPhone + "~" + distance + "\" type=\"radio\" name=\"dealer\" value=\"" + markerID + "\" checked=checked />";
				dealerList += "\n\t<div id='dealerInfo' class='dealerInformation'> </div>";

				dealerInfo = "\n<p class=\"dealerName\">" + dealerName + "<span class=\"distance\"> (" + distance + " Miles)</span></p>";
				dealerInfo += "\n<p class=\"dealerAddress\">" + dealerAddress + "</p>";
				dealerInfo += "\n<p class=\"dealerAddress\">" + dealerCity + ", " + dealerState + " " + dealerZip + "</p>";
				dealerInfo += "\n<p class=\"dealerAddress\">" + dealerPhone + "</p>";

				dealerList += "<p class=\"hide\">" + dealerName + " (" + distance + " Miles)</p><div class=\"clear\"></div></li>";
			}
			else {
				dealerList += "<input title=\"" + dealerName + "~" + dealerAddress + "~" + dealerCity + "~" + dealerState + "~" + dealerZip + "~" + dealerPhone + "~" + distance + "\" type=\"radio\" name=\"dealer\" value=\"" + markerID + "\" />";

				dealerList += "<p>" + dealerName + " (" + distance + " Miles)</p><div class=\"clear\"></div></li>";
			}
		}

	});

	if (dealerList.length == 0) {
		dealerList += "\n\t<li><p>No dealers are located within your search radius of " + searchRadius + " miles.</p><div class=\"clear\"></div></li>";
		dealerList += "\n\t<li><p>Please try expanding your search radius.</p><div class=\"clear\"></div></li>";
	}

	$('#dynamicDealerList').empty().append(dealerList);
	$(".dealerGroup").show();
	$('#dealerInfo').empty().append(dealerInfo);

	return dealerList;
} // end create_dealerRadioGroup

function create_distanceOptions() {
	var miles = distanceFrom;
	var options = "";

	$(miles).each(function() {
		var mileMarker = this;
		options += "\n<option value='"+mileMarker+"'>"+mileMarker+" miles</option>";
	});

	return options;
} // end create_distanceOptions

function create_errorMessage(inputId, message) {
	$("#error_"+inputId+", div.errorClear").remove();
	$(this).errorMessage({
		containerId: inputId,
		messageMain: message
	});
}

function create_eventsCalendar282(size, type) {
	//flush the page html for hidden elements and list view
	$("div.event_list").html('<div class="thismonth"></div><div class="recurring"></div>');
	$(".load_events").html('');

	var regionTag = "";
	if (visitorRegionTag == "" || visitorRegionTag == "null"){
		regionTag = ownerRegionTag;
	} else {
		regionTag = "region_" + visitorRegionTag;
	}

	var zipCode = "";
	if (visitorZip == "" || visitorZip == "null"){
		zipCode = ownerZip;
	} else {
		zipCode = visitorZip;
	}
	$("span.eventsZip").empty().append(zipCode);
	//variables
	var monthIndex = 0;
	var k = 0;
	var eventsNumber = 0;
	var smallEventsList = [];
	if (size == "282"){

	//	while (smallEventsList.length < 3){
			var xmlFile = 'events.html?month=';
			var xmlFilePath = linkPrefix + 'my-subaru/event-calendar/xml/';
			var allEvents = {};
			var allEventTitles = {};
			var singleEventsList = [];
			var recurringEventsList = [];

			var eventsNumber = 0;
			monthIndex += 1;
			//dates are zero indexed for this call, the rest are literal.
			var userNow = new Date();
			var startMonth = userNow.getMonth() + monthIndex;
			var startYear = userNow.getFullYear();
			var monthsSpan = 6;
			var currentMonth = startMonth;
			var currentYear = startYear;
			var startDateObj = new Date(currentMonth+ '/01/'+currentYear);
			var currentDateObj = new Date(startDateObj);
			xmlFile = 'events.html?month=' + currentDateObj.getMonthName().toLowerCase();
		//	xmlFile +='&regiontag=' + regionTag;
			var eventXmlUrl = xmlFilePath + xmlFile;


			var owner_events = get_ownerEvents(eventXmlUrl);
			$(owner_events.responseXML).find("event").each(function(i, xml) {
				var allDates = [];
				var startDate;
				var endDate;
				var currDate = new Date();
				var recurType;

				startDate = new Date($(this).attr('start-date'));
				endDate = new Date($(this).attr('end-date'));

				//prep the list-view html
				var imagelink = $(this).find('imagelink').text().replace('{$PATHPREFIX}',pathPrefix);
				var sitelink = $(this).find('url').text();
					if (imagelink == pathPrefix){
						imagelink += 'images/site/default/default_event_W.jpg';
					}
				var listDate = '<a name="'+ parseFloat(startDate.asString("mmdd") + endDate.asString("mmdd")) + '"></a>';
				var htmltxt =  '<div class="component comp590 my_2a" id="list_event'+k+'"><img alt="" src="'+imagelink+'"/>' + '<div class="content">' + '<p class="top">'+$(this).find('fulltitle').text()+'</p>' + '<p class="sig">'+$(this).find('date').text()+'</p>' + '<p>'+$(this).find('summary').text()+'</p>';
					if (sitelink.length > 0) {
						htmltxt += '<a target="_blank" href="'+sitelink+'"><span>Visit Website</span></a></div>';
					}
				htmltxt += '</div></div>';
				var htmltxt2 = '<li><span class="date">'+$(this).find('date').text()+'</span>';
					if ($(this).find('url').text().length > 0) {
						htmltxt2 += '<a href="'+$(this).find('url').text()+'"><b>'+$(this).find('fulltitle').text()+'</b></a>';
					} else {
						htmltxt2 += '<b>'+$(this).find('fulltitle').text()+'</b>';
					}
				htmltxt2 += '<span class="location">'+$(this).find('location').text()+'</span></li>';
				if (endDate >= currDate){
					if ($(this).attr('recurrence').length == 0) {
						singleEventsList.push(listDate + htmltxt);
						smallEventsList.push(listDate + htmltxt2);
						eventsNumber++;
					}
					else {
						recurringEventsList.push(htmltxt);
						smallEventsList.push(listDate + htmltxt2);
						eventsNumber++;
					}
				}

				//eventIDs++;
				k++;
				if (k == $('event',xml).length) {

				}
			});
			//list view sort and display
			//draws the calendar at the last XML node
			singleEventsList.sort();
			recurringEventsList.sort();
			$("div.event_list .thismonth").html('');
			$("div.event_list .recurring").html('');
			$("div.event_list .thismonth").append(singleEventsList[0]);
			$("div.event_list .recurring").append(recurringEventsList[0]);

	//	} //end while
		smallEventsList.sort();
		$(".my_events .event_list").append(smallEventsList[0]);
		$(".my_events .event_list").append(smallEventsList[1]);
		$(".my_events .event_list").append(smallEventsList[2]);

	}//end if 282

	//This isnt the most efficient way to do this... we need a refactor
	if (size == "590"){
		var xmlFile = 'events.html?month=';
		var xmlFilePath = linkPrefix + 'my-subaru/event-calendar/xml/';
		var allEvents = {};
		var allEventTitles = {};
		var singleEventsList = [];
		var recurringEventsList = [];

		var eventsNumber = 0;
		monthIndex += 1;
		//dates are zero indexed for this call, the rest are literal.
		var userNow = new Date();
		var startMonth = userNow.getMonth() + monthIndex;
		var startYear = userNow.getFullYear();
		var monthsSpan = 6;
		var currentMonth = startMonth;
		var currentYear = startYear;
		var startDateObj = new Date(currentMonth+ '/01/'+currentYear);
		var currentDateObj = new Date(startDateObj);
		if (type=="visitor"){
			xmlFile = 'events-visitor.html?month=';
		} else {
			xmlFile = 'events.html?month=';
		}
		xmlFile += currentDateObj.getMonthName().toLowerCase();
//		xmlFile +='&regiontag=' + regionTag;
		var eventXmlUrl = xmlFilePath + xmlFile;


		var owner_events = get_ownerEvents(eventXmlUrl);
		$(owner_events.responseXML).find("event").each(function(i, xml) {
			var allDates = [];
			var startDate;
			var endDate;
			var currDate = new Date();
			var recurType;

			startDate = new Date($(this).attr('start-date'));
			endDate = new Date($(this).attr('end-date'));

			//prep the list-view html
			var imagelink = $(this).find('imagelink').text().replace('{$PATHPREFIX}',pathPrefix);
			var sitelink = $(this).find('url').text();
				if (imagelink == pathPrefix){
					imagelink += 'images/site/default/default_event_W.jpg';
				}
			var listDate = '<a name="'+ parseFloat(startDate.asString("mmdd") + endDate.asString("mmdd")) + '"> </a>';
			var htmltxt =  '<div class="component comp590 my_2a" id="list_event'+k+'">';
			htmltxt += '<img alt="" src="'+imagelink+'"/>';
			htmltxt += '<div class="content">';
			htmltxt += '<p class="top">'+$(this).find('fulltitle').text()+'</p>';
			htmltxt += '<p class="sig">'+$(this).find('date').text()+'</p>';
			htmltxt += '<p>'+$(this).find('summary').text()+'</p>';
				if (sitelink.length > 0) {
					htmltxt += '<a target="_blank" href="'+sitelink+'"><span>Visit Website</span></a>';
				}
			htmltxt += '</div></div>';
			var htmltxt2 = '<li><span class="date">'+$(this).find('date').text()+'</span>';
				if ($(this).find('url').text().length > 0) {
					htmltxt2 += '<a href="'+$(this).find('url').text()+'"><b>'+$(this).find('fulltitle').text()+'</b></a>';
				} else {
					htmltxt2 += '<b>'+$(this).find('fulltitle').text()+'</b>';
				}
			htmltxt2 += '<span class="location">'+$(this).find('location').text()+'</span></li>';
			if(endDate >= currDate){
				if ($(this).attr('recurrence').length == 0) {
				singleEventsList.push(listDate + htmltxt);
				smallEventsList.push(listDate + htmltxt2);
				eventsNumber++;
				} else {
				recurringEventsList.push(htmltxt);
				smallEventsList.push(listDate + htmltxt2);
				eventsNumber++;
				}
			}

			//eventIDs++;
			k++;
			if (k == $('event',xml).length) {

			}
		});
		//list view sort and display
		//draws the calendar at the last XML node
		singleEventsList.sort();
		recurringEventsList.sort();
//console.log(singleEventsList[0]);
		$(".comp590 .event_list").html('');
		$(".comp590 .event_list").append(singleEventsList[0]);
		$(".comp590 .event_list").append(recurringEventsList[0]);

	} //end if 590
}

function create_formMySubaruUpdateVehicle(vin, modelYear, modelName, trimName, optionCode) {
	if (vin === undefined || vin.length == 0) {vin = 'none';}
	if (modelYear === undefined || modelYear.length == 0) {modelYear = 'none';}
	if (modelName === undefined || modelName.length == 0) {modelName = 'none';}
	if (trimName === undefined || modelName.length == 0) {trimName = 'none';}
	if (optionCode === undefined || optionCode.length == 0) {optionCode = 'none';}
	if (vin != 'none') {
		// get the vin info
		var vinInfo = vin_lookup(vin);
		var isVin = "no";
		$(vinInfo.responseXML).find("salesInfo").each(function() {
			isVin = "yes";
			var my = $(this).find("modelYear").text();
			var mn = $(this).find("modelName").text();
			var tn = $(this).find("trimName").text();
			var mc = $(this).find("modelCode").text();
			//var oc = (optionCode != 'none') ? optionCode : tn;
			var oc = $(this).find("optionCode").text();
			var purchaseDate = $(this).find("dateSold").text();

			// populate fields
			$("input[name=modelCode]").val(mc);
			$("input[name=optionCode]").val(oc);
			$("input#purchaseDate").val(purchaseDate);
			// create the model year options
			var modelYearOptions = '<option value="'+my+'">'+my+'</option>';
			$("select#chooseYear").empty().append(modelYearOptions);
			// create the model options
			var modelOptions = '<option value="'+mn+'">'+mn+'</option>';
			$('select#chooseModel').empty().append(modelOptions);
			// create the trim options
			var trimOptions = '<option value="'+tn+'">'+tn+'</option>';
			$('select#chooseTrim').empty().append(trimOptions);
		});
		if (isVin == "no") {
			if (modelYear != "none" && modelName != "none" && trimName != "none") {
				// create model year options
				var modelYearOptions = create_modelYearOptions(modelYear);
				$('select#chooseYear').empty().append(modelYearOptions).focus();
				// creat model options
				var modelOptions = create_modelOptions(modelYear, modelName);
				$('select#chooseModel').empty().append(modelOptions);
				// create trim options
				var trimOptions = create_modelTrimOptions(modelName, modelYear, trimName);
				$('select#chooseTrim').empty().append(trimOptions);
			}
		}
	}
	else if (vin == 'none') {
		if (modelYear != "none" && modelName != "none" && trimName != "none") {
			// create model year options
			var modelYearOptions = create_modelYearOptions(modelYear);
			$('select#chooseYear').empty().append(modelYearOptions).focus();
			// create model options
			var modelOptions = create_modelOptions(modelYear, modelName);
			$('select#chooseModel').empty().append(modelOptions);
			// create trim options
			var trimOptions = create_modelTrimOptions(modelName, modelYear, trimName);
			$('select#chooseTrim').empty().append(trimOptions);
		}
	}
}

//this actually does the entire vehicle detail page
function create_mySubIndexContent(vehicles_object, sel_vehicle, type){

	//clear out all data
	$(".my_copy_title h2").empty();
	$(".my_vehicle_detail .main.title h2").empty();
	$(".my_vehicle_detail ul li span#vin").empty();
	$(".my_vehicle_detail ul li span#est_mileage").empty();
	$("span#upcoming_service").empty();
	$(".my_vehicle_detail #warranty").empty();
	//clear out old service alerts / recalls
	$(".all_service_alerts").empty();
	$(".all_recall_alerts").empty();


	if (type === undefined) {type = ""}
	if (sel_vehicle === undefined) {sel_vehicle = 0}
	var vehicles;
	if (vehicles_object == "vehicles_garaged"){
		vehicles = vehicles_garaged;
	} else {
		vehicles = vehicles_owned;
	}
	var selected_array_index = sel_vehicle;

	//build HTML with for loop
	var h2_value = "";
	var vehicleName = "";
	var vehicle_vin ="";
	var vehicle_vin_text ="";
	var schedule_service_mileage = "";
	var schedule_service_link = "";
	var gtp_link = "";
	var gtp_link_text = "";
	var owned_vehicle_image = "";
	var saved_vehicle_image = "";
	var MSRP = "";
	var buildURL = "";
	var vehicle_mileage = "";
	var completeDetailsLink = linkPrefix + "special-offers/";
	var removeVehicleLink = "";
	var updateMileageLink = "";
	var vehicle_id;
	var arrayIndex;
	var warrantyName = "";
	var warrantyReadMoreLink = linkPrefix + "my-subaru/my-account/subaru-added-security.html?warType=";

	$(vehicles).each(function(index, thisElement){
		if (index == sel_vehicle) {
			var vehicleYear = $(this).attr("YEAR");
			var yearAbbrev = vehicleYear.substr(2);
			var vehicleModel = format_capitalize($(this).attr("MODEL"), 1);
			var modelCode = $(this).attr("MODEL_CODE")
			var vehicleTrim = $(this).attr("TRIM");
			vehicle_id = $(this).attr("VEHICLE_ID");
			MSRP += $(this).attr("MSRP");
			warrantyName = $(this).attr("WARRANTY");
			warrantyReadMoreLink += warrantyName;
				if (warrantyName == "") {
					warrantyReadMoreLink += "none";
				}
			vehicleName =  $(this).attr("NAME");
			vehicle_vin = $(this).attr("VIN");
			vehicle_mileage = $(this).attr("MILEAGE");
			vehicle_mileage = format_commas(vehicle_mileage);
			var vehicle_color_code = $(this).attr("VEHICLE_COLOR_CODE");
			arrayIndex = index;
			completeDetailsLink += vehicleModel.toLowerCase();
			completeDetailsLink += ".html";
			if (vehicleName == "" || vehicleName == null ) {
				vehicleName = "";
			}
			h2_value +=	 vehicleYear + ' ' + vehicleModel + ' ' + vehicleTrim;
			if (type == "owned") {
				if (vehicleName){
					h2_value += '  <span class="nickname"> "' +vehicleName + '"</span>';
				}
				h2_value += '<a id="' + vehicle_id + '" class="remove_link open_form" rel="mysubaru_vehicle_delete_confirmation" href="#" title="Remove '+ vehicleYear + ' ' + vehicleModel +'">delete</a>';
			}
			else {
			removeVehicleLink = linkPrefix +'my-subaru/data/vehicle/configured/remove/' + vehicle_id;
				//h2_value += '<a id="delete_configured"  href="'+ linkPrefix +'my-subaru/data/vehicle/configured/remove/' + vehicle_id +'" title="Remove '+ vehicleYear + ' ' + vehicleModel +'">delete</a>';
			}

			schedule_service_link += linkPrefix +'my-subaru/my-account/maintenance-schedule.html?vid=' + arrayIndex + '&vehid=' + vehicle_id;

			// get the trim image
			saved_vehicle_image = get_modelTrimImage(yearAbbrev, vehicleModel, modelCode, type, vehicle_color_code);

			//get the build link
			buildURL = get_buildURL(vehicleYear, vehicleModel, modelCode, vehicle_id );

			//update Mileage Link
			updateMileageLink = linkPrefix + 'my-subaru/my-account/my-profile.html?vid=' + arrayIndex + '&vehid=' + vehicle_id + '&openForm=form_my_profile_update_vehicle';

		}
	})//end array_index each

	//this will populate the my_copy_title H2 value found on the page.
	var my_copy_title = $(".my_copy_title").size();
	if (my_copy_title != 0) {
		$(".my_copy_title h2").empty().prepend(h2_value);
	}

	var my_next_vehicle_detail = $(".my_next_vehicle_detail").size();

		$(".no_saved_vehicle").hide();
		$(".no_owned_vehicle").hide();
		$(".my_vehicle_detail").hide();
		$(".my_next_vehicle_detail").hide();

	if (type == "owned") {
		$(".no_saved_vehicle").hide();
		$(".no_owned_vehicle").hide();
		$(".my_vehicle_detail").hide();
		$(".my_next_vehicle_detail").hide();

		if (h2_value == ""){

			$(".my_vehicle_detail").hide();
			$(".no_owned_vehicle").show();
		}
		else {

			$(".my_vehicle_detail").show();
			$(".my_vehicle_detail .main.title h2").empty();
			$(".my_vehicle_detail .main.title h2").prepend(h2_value);

			$(".my_vehicle_detail ul li span#est_mileage").empty().prepend(vehicle_mileage);
			$(".my_vehicle_detail #owner_vehicle_image").attr("src", saved_vehicle_image);
			$("a#sched_serv_link").attr("href", schedule_service_link);
			$(".my_vehicle_detail .updateMileageLink").attr("href", updateMileageLink);

			schedule_service_mileage = get_nextServiceTitle(vehicle_id);
			$("span#upcoming_service").empty().append(schedule_service_mileage);
			$(".my_vehicle_detail #warranty").empty().prepend(warrantyName);
			$(".my_vehicle_detail #warranty_read_more_link").attr("href", warrantyReadMoreLink);

			gtp_link = linkPrefix + 'my-subaru/my-account/trade-in-program.html?vid='+arrayIndex+'&vehid='+vehicle_id;

			if (vehicle_vin != "") {
				vehicle_vin_text = vehicle_vin;

				// get GTP
				gtpInfo = get_myGtpInfo(vehicle_vin);

				$(gtpInfo.responseXML).find("priceInfo").each(function() {
					var gtpStatus = $(this).find("status").text();

					if (gtpStatus == "0") {
						var gtpValue = $(this).find("value").text();
						var gtpValue = format_currency(gtpValue);
						var gtpEndDate = $(this).find("endDate").text();

						//gtp_link_text = gtpValue+' &ndash; Guaranteed until '+gtpEndDate;
						gtp_link_text = gtpValue+' &ndash; Estimate only, please click for <a href="'+linkPrefix+'finance-center/guaranteed-trade-in-program/rules-eligibility.html">Program Rules and Eligibility</a>';
					}
					else {
						gtp_link_text = "Get Value";
					}
				});
			}
			else if (vehicle_vin == "") {
				vehicle_vin_text = '<a href="'+ linkPrefix +'my-subaru/my-account/my-profile.html?vid=' + arrayIndex + '&vehid=' + vehicle_id + '&openForm=form_my_profile_update_vehicle">Add VIN</a> ';
				gtp_link_text = "Get Value";
			}
			$('a#get_gtp_link').attr("href", gtp_link).empty().append(gtp_link_text);

		}

		$(".my_vehicle_detail ul li span#vin").empty().append(vehicle_vin_text);

		create_recallNotices(vehicle_id, arrayIndex);
		create_overdueService(vehicle_id, arrayIndex);

	}

	//My Next Vehicle
	if (type == "garaged") {


		$(".no_saved_vehicle").hide();
		$(".no_owned_vehicle").hide();
		$(".my_vehicle_detail").hide();
		$(".my_next_vehicle_detail").hide();

		if (h2_value == ""){
			$(".my_next_vehicle_detail").hide();
			$(".no_saved_vehicle").show();
		} else {

		$(".my_next_vehicle_detail .main.title h2").empty().prepend(h2_value);

		MSRP = Math.round(MSRP);
		var vehicleMSRP = "$" + MSRP + '<span>MSRP*</span>';
		$(".my_next_vehicle_detail li.msrp").empty().prepend(vehicleMSRP);

		$(".my_next_vehicle_detail #saved_vehicle_image").attr("src", saved_vehicle_image);
		$(".my_next_vehicle_detail #modify_build_button").attr("href", buildURL);
		$(".my_next_vehicle_detail .configured	a").attr("href", buildURL);

		$(".my_next_vehicle_detail #see_complete_details_link").attr("href", completeDetailsLink);
		$(".my_next_vehicle_detail #remove_vehicle_link").attr("href", removeVehicleLink);
		$(".my_next_vehicle_detail").show();
		}
	}

} // end create MySub/index content

function create_modelOptions(modelYear, myModel) {
	if (myModel === undefined) { myModel = 'none'; }
	var models = get_modelInfo(modelYear);
	var options = "<option value='noSelection'>Select a Vehicle</option>";
	$(models.responseXML).find("model").each(function() {
		var modelName = $(this).attr("modelName");
		if ((modelName.toLowerCase() == "impreza") && (modelYear > 2008)) { // seperate Impreza into two "models" - Impreza, Impreza WRX
			if (myModel.toLowerCase() == "impreza") {
				options += "<option selected='selected' value='"+modelName+"'>"+modelName+"</option>";
				options += "<option value='"+modelName+" WRX'>"+modelName+" WRX</option>";
			}
			else if (myModel.toLowerCase() == "impreza wrx") {
				options += "<option value='"+modelName+"'>"+modelName+"</option>";
				options += "<option selected='selected' value='"+modelName+" WRX'>"+modelName+" WRX</option>";
			}
			else {
				options += "<option value='"+modelName+"'>"+modelName+"</option>";
				options += "<option value='"+modelName+" WRX'>"+modelName+" WRX</option>";
			}
		}
		else if (modelName.toLowerCase() != "imprezawrx") {
			if (myModel.toLowerCase() == modelName.toLowerCase()) {
				options += "<option selected='selected' value='"+modelName+"'>"+modelName+"</option>";
			}
			else {
				options += "<option value='"+modelName+"'>"+modelName+"</option>";
			}
		}
	});
	return options;
} // end create_modelOptions

function create_modelTrimOptions(modelName, modelYear, myTrim) {
	if (myTrim === undefined) { myTrim = 'none';}
	mn = (modelName.toLowerCase() == "impreza" || modelName.toLowerCase() == "impreza wrx") ? "Impreza" : format_capitalize(modelName.toLowerCase());
	var trims = get_modelInfo(modelYear);
	var options = "<option value='noSelection'>Select a Model</option>";
	$(trims.responseXML).find("model[modelName="+mn+"] trim").each(function() {
		var trimName = $(this).attr("trimName");
		if (mn == "Impreza" && modelYear > 2008) {
			// determine the Impreza trims to use
			var wrxFlag = $(this).attr("wrx");
			if (modelName.toLowerCase() == "impreza") {
				if (wrxFlag == 0) {
					if (myTrim.toLowerCase() == trimName.toLowerCase()) {
						options += "<option selected='selected' value='"+trimName+"'>"+trimName+"</option>";
					}
					else {
						options += "<option value='"+trimName+"'>"+trimName+"</option>";
					}
				}
			}
			else {
				if (wrxFlag == 1) {
					if (myTrim.toLowerCase() == trimName.toLowerCase()) {
						options += "<option selected='selected' value='"+trimName+"'>"+trimName+"</option>";
					}
					else {
						options += "<option value='"+trimName+"'>"+trimName+"</option>";
					}
				}
			}
		}
		else {
			if (myTrim.toLowerCase() == trimName.toLowerCase()) {
				options += "<option selected='selected' value='"+trimName+"'>"+trimName+"</option>";
			}
			else {
				options += "<option value='"+trimName+"'>"+trimName+"</option>";
			}
		}
	});
	return options;
}

function create_modelYearOptions(year, flag) {
	var modelYears = get_modelYears();
	if (year === undefined) { year = 'none'; }
	if (flag === undefined) { flag = 0; }
	var nodeQuery = (flag == 1) ? "modelYear[activeFlag="+flag+"]" : "modelYear";
	var options = "<option value='noSelection'>Select a Year</option>";
	$(modelYears.responseXML).find(nodeQuery).each(function() {
		var my = $(this).attr("year");
		var myAb = $(this).attr("yearAbbrev");
		var af = $(this).attr("activeFlag");
		if (my == year) {
			options += "<option selected='selected' value='"+my+"'>"+my+"</option>";
		} else {
			options += "<option value='"+my+"'>"+my+"</option>";
		}
	});
	return options;
} // end create_modelYearOptions

function create_overdueService(veh_id, array_index) {
	$(".all_service_alerts").empty();
	var html = "";
	var html_upcoming = "";
	var html_overdue = "";
	var count = 0;
	var thisEstimatedMileage = estimatedMileage;

	// get the Dealer's maintenance schedule
	var ms_dealer = get_maintenanceScheduleDealer(veh_id);
	var countUpcoming = $(ms_dealer.responseXML).find("maintenanceRecord[completed=false][overdue=false]").size();

	if (countUpcoming > 0) {
		// Check upcoming Service Reminders
		$(ms_dealer.responseXML).find("maintenanceRecord[completed=false][overdue=false]").each(function(index, thisElement) {
			if (index == 0) {
				thisEstimatedMileage = vehicles_owned[array_index].MILEAGE;

				var upcomingMileage = $(this).find("mileage").text();
				var mileageDiff = upcomingMileage - thisEstimatedMileage;
				if (mileageDiff < 1001) {
					var title = $(this).find("title").text();
					var mileage = format_commas(upcomingMileage);
					var description = $(this).find("description").text();
					html_upcoming +=
					html_upcoming += '<div class="service_alert'+ count +' service_alert reminder_alert">';
					html_upcoming += '<div class="top"></div>';
					html_upcoming += '<div class="body">';
					html_upcoming += '<h3>Upcoming Maintenance Reminder: It is almost time for your ' + mileage +' mile service</h3><div class="alert"></div>';
					html_upcoming += '<div class="close_button" rel="'+ vehicle_id +'" ><img class="dealer" rel="'+ count +'" src="'+ pathPrefix + 'images/site/icons/Window Close br.gif" alt="close" /></div>';
					html_upcoming += '<div class="clear"> </div>';
					html_upcoming += '<p>To keep your vehicle running at its best and ensure the continued safe operation of your Subaru, we strongly advise you to have your service performed at the mileage/time intervals indicated. <a href="'+ linkPrefix +'my-subaru/my-account/maintenance-schedule.html?vid='+ array_index +'&vehid='+ vehicle_id +'" class="viewAlertsLink">View Maintenance Schedule</a></p>';
					html_upcoming += '</div><!--body-->';
					html_upcoming += '<div class="bottom"></div>';
					html_upcoming += '</div>';
				}
			}
		});
	}

	// get the most recent "overdue" service
	var countOverdue_dealer = $(ms_dealer.responseXML).find("maintenanceRecord[overdue=true]").size();
	if (countOverdue_dealer > 0) {
		$(ms_dealer.responseXML).find("maintenanceRecord[overdue=true]").each(function(index, thisElement) {
			if (index == (countOverdue_dealer - 1)) {
				var title = $(this).find("title").text();
				var mileage = $(this).find("mileage").text();
					mileage = format_commas(mileage);
				var description = $(this).find("description").text();
				html_overdue += '<div class="service_alert'+ count +' service_alert reminder_alert">';
				html_overdue += '<div class="top"></div>';
				html_overdue += '<div class="body">';
				html_overdue += '<h3>Maintenance Reminder: Your ' + mileage +' mile service is past due</h3><div class="alert"></div>';
				html_overdue += '<div class="close_button" rel="'+ vehicle_id +'" ><img class="dealer" rel="'+ count +'" src="'+ pathPrefix + 'images/site/icons/Window Close br.gif" alt="close" /></div>';
				html_overdue += '<div class="clear"> </div>';
				html_overdue += '<p>To keep your vehicle running at its best, and ensure the continued safe operation of your Subaru, we strongly advise you to have your service performed at the mileage/time intervals indicated. <a href="'+ linkPrefix +'my-subaru/my-account/maintenance-schedule.html?vid='+ array_index +'&vehid='+ vehicle_id +'" class="viewAlertsLink">View Maintenance Schedule</a></p>';
				html_overdue += '</div><!--body-->';
				html_overdue += '<div class="bottom"></div>';
				html_overdue += '</div>';
			}
		});
	}
	else {
		// try the manufacturer schedule
		var ms_manufacturer = get_maintenanceScheduleManufacturer(veh_id);
		var countOverdue_manufacturer = $(ms_manufacturer.responseXML).find("maintenanceRecord[overdue=true]").size();
		if (countOverdue_manufacturer > 0) {
			$(ms_manufacturer.responseXML).find("maintenanceRecord[overdue=true]").each(function(index, thisElement) {
				if (index == (countOverdue_manufacturer - 1)) {
					var title = $(this).find("title").text();
					var mileage = $(this).find("mileage").text();
						mileage = format_commas(mileage);
					var description = $(this).find("description").text();
					html_overdue += '<div class="service_alert'+ count +' service_alert reminder_alert">';
					html_overdue += '<div class="top"></div>';
					html_overdue += '<div class="body">';
					html_overdue += '<h3>Maintenance Reminder: Your ' + mileage +' mile service is past due</h3><div class="alert"></div>';
					html_overdue += '<div class="close_button" rel="'+ vehicle_id +'" ><img class="dealer" rel="'+ count +'" src="'+ pathPrefix + 'images/site/icons/Window Close br.gif" alt="close" /></div>';
					html_overdue += '<div class="clear"> </div>';
					html_overdue += '<p>To keep your vehicle running at its best, and ensure the continued safe operation of your Subaru, we strongly advise you to have your service performed at the mileage/time intervals indicated. <a href="'+ linkPrefix +'my-subaru/my-account/maintenance-schedule.html?vid='+ array_index +'&vehid='+ vehicle_id +'" class="viewAlertsLink">View Maintenance Schedule</a></p>';
					html_overdue += '</div><!--body-->';
					html_overdue += '<div class="bottom"></div>';
					html_overdue += '</div>';
				}
			});
		}
	}

	html += html_upcoming + html_overdue;

	$(".all_service_alerts").append(html);
}// end create overdue service function

function create_recallNotices(veh_id, array_index) {

	$(".all_recall_alerts").empty();
	var count = 0;
	var overdue_recall_alerts = get_recallDetail(veh_id);
	$(overdue_recall_alerts.responseXML).find("recall").each(function(index, thisElement) {
		//var show_notice = $(thisElement).attr("show");
		var dateComplete = $(thisElement).children("recallcompletedate")[0].textContent;
		if (dateComplete == undefined) {
			dateComplete = ($(thisElement).children("recallcompletedate"))[0].text;
		}
		var show_notice = (dateComplete==null || dateComplete=="" || dateComplete == undefined);
		if (show_notice != false) {
			var title = $(this).find("recallTile").text();
			var description = $(this).find("recallDescription").text();
			var alertType = $(this).find("recallCampaignType").text();
			var programTitle = "Recall Notice";
			var programClass = "recall_alert";
			if (alertType == "R") {
				programTitle = "Recall Notice";
				programClass = "recall_alert";
			}
			else if (alertType == "C") {
				programTitle = "Service Alert";
				programClass = "new_service_alert";
			}
			var html = '<div class="service_alert'+ count +' service_alert '+programClass+'">';
			html += '<div class="top"></div>';
			html += '<div class="body">';
			html += '<h3>'+programTitle+': ' + title +'</h3><div class="alert"></div>';
			html += '<div class="close_button" rel="'+vehicle_id+'" ><img class="recall" rel="'+index+'" src="'+ pathPrefix + 'images/site/icons/Window Close br.gif" alt="close" /></div>';
			html += '<div class="clear"> </div>';
			html += '<p>' + description + '</p>';
			html += '<p><a href="'+ linkPrefix +'my-subaru/my-account/recall-service-program.html?vid='+ array_index +'&vehid='+ vehicle_id +'" class="viewAlertsLink">View Recalls</a></p>';
			html += '</div><!--body-->';
			html += '<div class="bottom"></div>';
			html += '</div><!--recall alert component-->';

			//write out after each iteration
			$(".all_recall_alerts").append(html);
			count ++;
		}
	}); // end each
	if (count != 0) {
		$(".service_recall").show();
	}
}// end get overdue recalls

function create_serviceReasonOptions(vehicleId, reasonId) {
	if (reasonId === undefined) { reasonId = 'none'; }
	// get dealer maintenance schedule
	var msDealer = get_maintenanceScheduleDealer(vehicleId);

	var options = "<option value='noSelection'>Select a Service Reason</option>";
	if (reasonId.toLowerCase() == "p") {
		options += '<option value="p" selected="selected">Repair</option>';
	}
	else {
		options += '<option value="p">Repair</option>';
	}
	if (reasonId.toLowerCase() == "o") {
		options += '<option value="o" selected="selected">Other</option>';
	}
	else {
		options += '<option value="o">Other</option>';
	}
	var msDealerSize = $(msDealer.responseXML).find("maintenanceRecord").size();
	if (msDealerSize > 0) {
		$(msDealer.responseXML).find("maintenanceRecord").each(function() {
			var oValue = $(this).find("mileage").text();
			var oText = $(this).find("title").text();
			// possibly consider formating the text
			   // call format function here
			if (reasonId == oValue) {
				options += '<option value="'+oValue+'" selected="selected">'+oText+'</option>';
			}
			else {
				options += '<option value="'+oValue+'">'+oText+'</option>';
			}
		});
	}
	else {
		var msManufacturer = get_maintenanceScheduleManufacturer(vehicleId);
		$(msManufacturer.responseXML).find("maintenanceRecord").each(function() {
			var oValue = $(this).find("mileage").text();
			var oText = $(this).find("title").text();
			// possibly consider formating the text
			   // call format function here
			if (reasonId == oValue) {
				options += '<option value="'+oValue+'" selected="selected">'+oText+'</option>';
			}
			else {
				options += '<option value="'+oValue+'">'+oText+'</option>';
			}
		});
	}
	return options
}

function create_similarModels(modelYear, modelName, modelTrim) {
	var similarModels = "";
	mn = (modelName.toLowerCase() == "impreza" || modelName.toLowerCase() == "impreza wrx") ? "Impreza" : format_capitalize(modelName.toLowerCase());
	var modelInfo = get_modelInfo(modelYear);
	$(modelInfo.responseXML).find("model[modelName="+mn+"] trim").each(function() {
		var tn;
		var trimName = $(this).attr("trimName");
		var buildUrl = $(this).attr("buildURL");
		var landingLink = linkPrefix+"vehicles/"+buildUrl+"index.html";
		if (mn == "Impreza" && modelYear > 2008) {
			var wrxFlag = $(this).attr("wrx");
			if (modelName.toLowerCase() == "impreza") {
				if (wrxFlag == 0 && modelTrim.toLowerCase() != trimName.toLowerCase()) {
					tn = trimName.replace(".", "").replace(" ", "-");
					msrp = $(this).attr("msrp");
					//landingLink += mn.toLowerCase()+"/"+tn.toLowerCase()+"/index.html";
					similarModels += "<div class='blue margin-top text12'><a href='"+landingLink+"' title='"+modelYear+" "+mn+" "+trimName+"'>"+modelYear+" "+mn+" "+trimName+"</a></div>";
					similarModels += "<div class='margin-top text12'>Starting at $"+msrp+"</div><br />";
				}
			}
			else {
				if (wrxFlag == 1 && modelTrim.toLowerCase() != trimName.toLowerCase()) {
					tn = trimName.replace(".", "").replace(" ", "-").replace("WRX-", "");
					msrp = $(this).attr("msrp");
					//landingLink += mn.toLowerCase()+"-wrx/"+tn.toLowerCase()+"/index.html";
					similarModels += "<div class='blue margin-top text12'><a href='"+landingLink+"' title='"+modelYear+" "+mn+" "+trimName+"'>"+modelYear+" "+mn+" "+trimName+"</a></div>";
					similarModels += "<div class='margin-top text12'>Starting at $"+msrp+"</div><br />";
				}
			}
		}
		else if (mn == "Forester" && modelYear > 2008) {
			if (modelTrim.toLowerCase() != trimName.toLowerCase()) {
				tn = trimName.replace(".", "").replace(" ", "").replace("Premium", "p").replace("Limited", "l");
				msrp = $(this).attr("msrp");
				//landingLink += mn.toLowerCase()+"/"+tn.toLowerCase()+"/index.html";
				similarModels += "<div class='blue margin-top text12'><a href='"+landingLink+"' title='"+modelYear+" "+mn+" "+trimName+"'>"+modelYear+" "+mn+" "+trimName+"</a></div>";
				similarModels += "<div class='margin-top text12'>Starting at $"+msrp+"</div><br />";
			}
		}
		else {
			if (modelTrim.toLowerCase() != trimName.toLowerCase()) {
				tn = trimName.replace(".", "").replace(" ", "-");
				msrp = $(this).attr("msrp");
				//landingLink += mn.toLowerCase()+"/"+tn.toLowerCase()+"/index.html";
				similarModels += "<div class='blue margin-top text12'><a href='"+landingLink+"' title='"+modelYear+" "+mn+" "+trimName+"'>"+modelYear+" "+mn+" "+trimName+"</a></div>";
				similarModels += "<div class='margin-top text12'>Starting at $"+msrp+"</div><br />";
			}
		}
	});
	return similarModels;
}

function create_stateOptions(myState, defaultText) {
	if (myState === undefined) { myState = ''; }
	if (defaultText === undefined) { defaultText = "Select a State"; }
	var createStates = usStates;
	var options = "<option value=''>" + defaultText + "</option>";
	$(createStates).each(function() {
		var sAbbrev = this.stateAbbrev;
		var sName = this.stateName;
		if (sAbbrev == myState) {
			options += "<option selected='selected' value='"+sAbbrev+"'>"+sName+"</option>";
		} else {
			options += "<option value='"+sAbbrev+"'>"+sName+"</option>";
		}
	});
	return options;
} // end create_stateOptions

function create_subjectOptions(subject) {
	var so = "<option value=\"noSelection\">Select Subject / Category</option>";
		so += "<option value=\"Advertising/Promotions\">Advertising/Promotions</option>";
	/* removed per FB 2614
	if (subject == "brochure"){
		so += "<option selected=\"SELECTED\" value=\"Brochure Request\">Brochure Request</option>";
	}
	else {
		so += "<option value=\"Brochure Request\">Brochure Request</option>";
	}
	*/
		so += "<option value=\"Dealer Relations\">Dealer Relations</option>";
		so += "<option value=\"Drive/Drive Performance Magazine\">Drive/Drive Performance Magazine</option>";
	if (subject == "fleet"){
		so += '<option selected="SELECTED" value="Fleet Account">Fleet Account</option>';
	}
	else {
		so += '<option value="Fleet Account">Fleet Account</option>';
	}
		so += '<option value="General Inquiries">General Inquiries</option>';
		so += '<option value="My.Subaru Website Issues">My.Subaru Website Issues</option>';
	//	if (subject == "owners"){
	//			so += '<option selected="SELECTED" value="Owners Story">Owner\'s Story</option>';
	//	} else {
	//		so += '<option value="Owners Story">Owner\'s Story</option>';
	//	}
		so += '<option value="Parts/Accessories Related">Parts/Accessories Related</option>';
		so += '<option value="Performance/Rally Questions">Performance/Rally Questions</option>';
		so += '<option value="Product Information">Product Information</option>';
		so += '<option value="Product Recommendations">Product Recommendations</option>';
		so += '<option value="Service Related">Service Related</option>';
		so += '<option value="Subaru Insider">Subaru Insider</option>';
		so += '<option value="Subaru iPod Interface">Subaru iPod Interface</option>';
		so += '<option value="Update address in official Subaru database">Update address in official Subaru database</option>';
		so += '<option value="Vehicle Problem">Vehicle Problem</option><option value="Website Issues">Website Issues</option>';

	return so;
} // end create_subjectOptions

//read in all the saved vehicles and create the lis for all
function create_tertiaryTabsAccordionGaraged(vehicles_object, dealerURL) {
	var vehicles = vehicles_object;
	var dealerURL = dealerURL;

	//build HTML with for loop
	var inventoryLink = dealerURL;
	if (is_SNEDealer(dealerCode)){
	}else{
		inventoryLink += "/link?program=soa&page=NEW_INVENTORY";
	}

	var tert = "";
	$(vehicles).each(function(index, thisElement){
		var vehicleYear = $(this).attr("YEAR");
		var vehicleModel = format_capitalize($(this).attr("MODEL"), 2);
		var vehicleTrim = $(this).attr("TRIM");
		var vehicle_vin = $(this).attr("VIN");
		var arrayIndex = index;

		tert += "<div><!--open-->";
		tert += '<div class="acc_head" id="'+ arrayIndex +'"><a href="#" class="links selected" id="'+ arrayIndex +'" >' + vehicleYear + ' ' + vehicleModel + ' ' + vehicleTrim + '</a></div>';
		tert += '<div class="acc_content"><p>';
		tert += '<span class=" "><a href="'+ linkPrefix +'finance-center/payments-financing.html">Estimate Payments</a></span>';
		tert += '<span class="inventoryLink"><a href="'+ inventoryLink +'" target="_blank">View Inventory</a></span>';
		tert += '<span class=" "><a href="'+ linkPrefix +'tools/compare-vehicles.html" >Compare</a></span>';
		tert += '<span class=" "><a href="'+ linkPrefix +'special-offers/index.html">Get Special Offers</a></span>';
		tert += '<span class=" "><a href="'+ linkPrefix +'shopping-tools/get-brochure.html" >Download Brochure</a></span>';
	//	tert += '<span class=" "><a href="'+ linkPrefix +'#" >Parts and Accessories</a></span>';
		tert += "</p></div><!--acc_content--></div><!--open-->";
	});//end of for loop

	return tert;
} // end of create tabbed tertiary accordion (garaged vehicles)

//read in all the saved vehicles and create the lis for all
function create_tertiaryTabsAccordionOwned(vehicles_object, dealerCode, tertiaryID, sel_vehicle, dealerURL) {
	var dealerCode = dealerCode;
	var vehicles = vehicles_object;
	var tertiary_id = tertiaryID;
	var selected_array_index = sel_vehicle;
	var dealerURL = dealerURL;

	//massage the dealerCode
	//	var a = dealerCode.substring(0,3);
	//	var b = dealerCode.substring(3,6);
	//	var dealerCode = a + "-" + b;

		function bold_the_link(arrayIndex, tertiaryId, sel_array_ind, sel_tert_id){
			var array_index = arrayIndex;
			var tertiary_id = tertiaryId;
			var sel_array_ind = sel_array_ind;
			var sel_tert_id = sel_tert_id;

			if ((array_index == sel_array_ind) && (tertiary_id == sel_tert_id)){
				var a = "selected";
			} else {
				var a = " ";
			}
			return a;
		 }

//build HTML with for loop
	var tert = "";
	$(vehicles).each(function(index, theElement){
		var vehicleYear = $(this).attr("YEAR");
		var vehicleModel = format_capitalize($(this).attr("MODEL"), 3);
		var vehicleTrim = $(this).attr("TRIM");
		var vehicle_vin = $(this).attr("VIN");
		var vehicle_id = $(this).attr("VEHICLE_ID");
		var arrayIndex = index;

		tert += "<div><!--open-->";
		tert += '<div class="acc_head" id="'+ arrayIndex +'"><a id="'+ arrayIndex +'" href="#" class="links" >' + vehicleYear + ' ' + vehicleModel + ' ' + vehicleTrim + '</a></div>';
		tert += '<div class="acc_content"><p>';
		tert += '<span class=" '+ bold_the_link(arrayIndex, 1, selected_array_index, tertiary_id) +' "><a href="'+ linkPrefix +'my-subaru/my-account/maintenance-schedule.html?vid=' + arrayIndex + '&vehid=' + vehicle_id +'">Schedule Service Appointment</a></span>';
		tert += '<span class=" '+ bold_the_link(arrayIndex, 2, selected_array_index, tertiary_id) +' "><a href="'+ linkPrefix +'my-subaru/my-account/maintenance-schedule.html?vid=' + arrayIndex + '&vehid=' + vehicle_id +'">Maintenance Schedule</a></span>';
		tert += '<span class=" '+ bold_the_link(arrayIndex, 3, selected_array_index, tertiary_id) +' "><a href="'+ linkPrefix +'my-subaru/my-account/service-history.html?vid=' + arrayIndex + '&vehid=' + vehicle_id +'">Service History</a></span>';
		tert += '<span class=" '+ bold_the_link(arrayIndex, 4, selected_array_index, tertiary_id) +' "><a href="'+ linkPrefix +'my-subaru/my-account/service-coupon.html?vid=' + arrayIndex + '&vin='+ vehicle_vin + '&dealer_code=' + dealerCode + '&dlr_site=N">Service Coupons</a></span>';
		tert += '<span class=" '+ bold_the_link(arrayIndex, 5, selected_array_index, tertiary_id) +' "><a href="'+ linkPrefix +'my-subaru/my-account/recall-service-program.html?vid=' + arrayIndex + '&vehid=' + vehicle_id +'">Recall and Service Program</a></span>';
		tert += '<span class=" '+ bold_the_link(arrayIndex, 10, selected_array_index, tertiary_id) +' "><a href="'+ linkPrefix +'my-subaru/my-account/trade-in-program.html?vid=' + arrayIndex + '&vehid=' + vehicle_id +'">Guaranteed Trade&ndash;In Program</a></span>';
		tert += '<span class=" '+ bold_the_link(arrayIndex, 6, selected_array_index, tertiary_id) +' "><a href="'+ linkPrefix +'my-subaru/my-account/parts-and-accessories.html?vid=' + arrayIndex + '&year=' + vehicleYear + '&model=' + vehicleModel +'&trim='+ vehicleTrim +'">Parts and Accessories</a></span>';
		tert += '<span class=" '+ bold_the_link(arrayIndex, 7, selected_array_index, tertiary_id) +' "><a href="'+ linkPrefix +'my-subaru/my-account/immobilizer-code.html?vid=' + arrayIndex + '&vehid=' + vehicle_id +'">Immobilizer Code</a></span>';
		tert += '<span class=" '+ bold_the_link(arrayIndex, 8, selected_array_index, tertiary_id) +' "><a href="'+ linkPrefix +'my-subaru/my-account/manuals-downloads.html?vid=' + arrayIndex + '&year=' + vehicleYear + '&model=' + vehicleModel +'&trim='+ vehicleTrim +'">Owners Manual and Downloads</a></span>';
		tert += '<span class=" '+ bold_the_link(arrayIndex, 9, selected_array_index, tertiary_id) +' "><a href="'+ linkPrefix +'my-subaru/my-account/warranty-guide.html?vid=' + arrayIndex + '">Warranty Guide</a></span>';
		tert += "</p></div><!--acc_content--></div><!--open-->";
	});//end of for loop
return tert;
} // end of create tertiary accordian (owned)

//create the ACTUAL accordions
function create_tertiaryTabsAccordions(selected_one, vehicles_owned, vehicles_garaged, typeOverride) {

	if (selected_one === undefined) {
		var selected_one = 0
	}
	else {
		var selected_one = selected_one;
	}

	if (typeOverride != ""){
		var selected_one_owned = 0;
	}
	else {
		var selected_one_owned = selected_one;
	}

	var vehicles_owned = vehicles_owned;
	var vehicles_garaged = vehicles_garaged;

	//This is for the accordian pod. If it appears on the page, make it work...
	var accordion = $(".accordion").size();
	if (accordion !=0) {
		$('.accordion').css({visibility: "visible"});
		$('.accordion').accordion({
			header: '.acc_head',
			selectedClass: 'showing_this',
			event: 'click',
			active: selected_one_owned
		}).bind("accordionchange", function(event, ui) {
				//window.stop();
				var vehicles = "vehicles_owned";
				var isbolded = $("span.selected").size();
				if (isbolded == 0) {
					var type = "owned";
					update_currentlyViewedVehicle(type, ui.newHeader.attr("id"));
					update_accessoriesAccordion(ui.newHeader.attr("id"), "owned");
					if (is_onIndexPage()){
						create_mySubIndexContent(vehicles, ui.newHeader.attr("id"), type);
					}
				}
				else {
					return false;
				}
		});
	}

	var accordion_garaged = $(".accordion_garaged").size();
	if (accordion_garaged !=0) {
		$('.accordion_garaged').css({visibility: "visible"});
		$('.accordion_garaged').accordion({
			header: '.acc_head',
			selectedClass: 'showing_this',
			event: 'click',
			active: selected_one
		}).bind("accordionchange", function(event, ui) {
				var vehicles = "vehicles_garaged";
				var isbolded = $("span.selected").size();
				if (isbolded == 0) {
					var type = "garaged";
					update_currentlyViewedVehicle(type, ui.newHeader.attr("id"));
					update_accessoriesAccordion(ui.newHeader.attr("id"), "garaged");
					if (is_onIndexPage()){
						create_mySubIndexContent(vehicles, ui.newHeader.attr("id"), type);
					}
				}
				else {
					return false;
				}
		});
	}

	$('#my-vehicles-tab .showing_this a.links').livequery('click', function(event) {
	   var theId = $(this).attr("id");
	   var newPage = linkPrefix + "my-subaru/my-account/index.html?vid="+ theId;
	   window.location = newPage;
	   return false;
	});

	var type="owned";
	var sel_vehicle = 0;
	var vehicles_object = vehicles_owned;
}

//create tertiary_tabs on MySubaru index page.
function create_tertiaryTabs(vehicles_owned, vehicles_garaged, sel_veh, selectedTab) {
	//double check that the tabs really need to be created.
	var tertiary_tabs = $("#nav_ms_tertiary-tabs").size();
	if (tertiary_tabs != 0) {
		var vehicles = "vehicles_owned";
		var selected_one = sel_veh;
		var selected_tab = 0;

		if (selectedTab == "garaged") {
			selected_tab = 1;
			vehicles = "vehicles_garaged";
			selected_one = sel_veh;

			if (vehicles_owned == 0) {
				selected_tab = 1;
			}
		}

		$('#nav_ms_tertiary-tabs').tabs( { selected:  selected_tab } ).bind("tabsselect", function(event, ui) {

			if (ui.panel.id == "my-vehicles-tab"){
				type = "owned";
				vehicles = "vehicles_owned";
				selected_one = $("#my-vehicles-tab").find(".showing_this a").attr("id");
			}
			else {
				type = "garaged";
				vehicles = "vehicles_garaged";
				selected_one = $("#my-next-tab").find(".showing_this a").attr("id");							
			}

			if (is_onIndexPage()){
				//this has to be in here twice since we are using the bind() function.
				create_mySubIndexContent(vehicles, selected_one, type);
				update_accessoriesAccordion(selected_one, type);
			}
		});
		//this has to be in here twice since we are using the bind() function.
		if (is_onIndexPage()){
			create_mySubIndexContent(vehicles, selected_one, type);
		}
	}//end if
}//end tertiary_tabs function

function create_yearOptions(year) {
	if (year === undefined) { year = 'none'; }
	var createYears = years;
	var options = "<option value='noSelection'>Select a Year</option>";
	$(createYears).each(function() {
		if(this==year) {
			options += "<option selected='selected' value='"+this+"'>"+this+"</option>";
		}
		else {
			options += "<option	 value='"+this+"'>"+this+"</option>";
		}
	});
	return options;
} // end create_yearOptions


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

function delete_errorMessage(inputId) {
	$("#error_"+inputId+", div.errorClear").remove();
	$("#"+inputId).removeClass("errorFocus");
}

function delete_serviceRecord(formId) {
	var formData = $('#'+formId).serialize();
	var redirectURL = window.location.pathname + window.location.search;
	$.ajax({
		type: "post",
		url: linkPrefix+"my-subaru/data/maintenance/remmoveservicerecord",
		data: formData,
		async: false,
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			window.location.assign(redirectURL);
		},
		success: function(data, textStatus) {
			// Set the Omniture Variables
			var s = s_gi(s_account);
			s.linkTrackEvents="event28";
			s.events = "event28";
			s.tl(this,'o','my-subaru:delete_record');

			window.location.assign(redirectURL);
		}
	});
}


//-----------------------------------------------------------------------------------
//4.0 format_
//-----------------------------------------------------------------------------------

function format_capitalize(incomingString, fromWhere){
	//extract the first letter of str
	var letter = incomingString.substr(0,1);
	//return letter capitalised concatonated with str minus it's first letter
	var str = incomingString.toLowerCase();
	return letter.toUpperCase() + str.substr(1);
} // end format_capitalize

function format_clean(num) {
	 var sVal='';
	 var nVal = num.length;
	 var sChar='';

   try
   {
	  for(c=0;c<nVal;c++){
		 sChar = num.charAt(c);
		 nChar = sChar.charCodeAt(0);

		 if ((nChar >=48) && (nChar <=57)){
			 if(c!=0 || nChar != 48){
				 sVal += num.charAt(c);
			 }
		 }
	  }
   }catch (exception) {}
	return sVal;
}

function format_commas(nStr) {
   nStr += '';
   x = nStr.split('.');
   x1 = x[0];
   x2 = x.length > 1 ? '.' + x[1] : '';
   var rgx = /(\d+)(\d{3})/;
   while (rgx.test(x1)) {
	 x1 = x1.replace(rgx, '$1' + ',' + '$2');
   }
   return x1 + x2;
} // end format_commas

function format_currency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
} // end format_currency

function format_emptyNumber(decimalDelimiter,decimalPlaces) {
	var preDecimal = '0';
	var postDecimal = '';

	for(i=0;i<decimalPlaces;i++)
	{
	  if (i==0) { postDecimal += decimalDelimiter; }
	  postDecimal += '0';
	}
   return preDecimal + postDecimal;
}

function format_gtpDate(gtpDate) {
	var dateArray = gtpDate.split("/");
	var month = get_monthName(dateArray[0]);
	var gtpDate = month+" "+dateArray[1]+", "+dateArray[2];
	return gtpDate;
} // end format_gtpDate

function format_number(num,countryCode,decimalPlaces) {

  var minus='';
  var comma='';
  var dec='';
  var preDecimal='';
  var postDecimal='';

  try{

	decimalPlaces = parseInt(decimalPlaces);
	comma = get_commaDelimiter(countryCode);
	dec = get_decimalDelimiter(countryCode);

	if (decimalPlaces < 1) { dec = ''; }
	if (num.lastIndexOf("-") == 0) { minus='-'; }

	preDecimal = format_clean(num);

	// preDecimal doesn't contain a number at all.
	// Return formatted zero representation.

	if (preDecimal.length < 1){
	   return minus + format_emptyNumber(dec,decimalPlaces);
	}

	// preDecimal is 0 or a series of 0's.
	// Return formatted zero representation.

	if (parseInt(preDecimal) < 1){
	   return minus + format_emptyNumber(dec,decimalPlaces);
	}

	// predecimal has no numbers to the left.
	// Return formatted zero representation.

	if (preDecimal.length == decimalPlaces){
	  return minus + '0' + dec + preDecimal;
	}

	// predecimal has fewer characters than the
	// specified number of decimal places.
	// Return formatted leading zero representation.

	if (preDecimal.length < decimalPlaces){
	   if (decimalPlaces == 2)
	   {
		return minus + format_emptyNumber(dec,decimalPlaces - 1) + preDecimal;
	   }
	   return minus + format_emptyNumber(dec,decimalPlaces - 2) + preDecimal;
	}

	// predecimal contains enough characters to
	// qualify to need decimal points rendered.
	// Parse out the pre and post decimal values
	// for future formatting.

	if (preDecimal.length > decimalPlaces){
	  postDecimal = dec + preDecimal.substring(preDecimal.length - decimalPlaces,
											   preDecimal.length);
	  preDecimal = preDecimal.substring(0,preDecimal.length - decimalPlaces);
	}

	// Place comma oriented delimiter every 3 characters
	// against the numeric representation of the "left" side
	// of the decimal representation.  When finished, return
	// both the left side comma formatted value together with
	// the right side decimal formatted value.

	var regex  = new RegExp('(-?[0-9]+)([0-9]{3})');

	while(regex.test(preDecimal)){
	   preDecimal = preDecimal.replace(regex, '$1' + comma + '$2');
	}

  }catch (exception) {}
  return minus + preDecimal + postDecimal;
}

function format_stripSlash(str) {
	var firstChar = str.substr(0,1);
	if (firstChar == "/") {
		str = str.substr(1);
	}
	return str;
}


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

function get_accBrochure(vehicleYear, myModel, myTrim){
	// remove whitespace
	var accBrochure = pathPrefix + "downloads/pdf/accbrochures/";
	var vehicleYear = jQuery.trim(vehicleYear);
	var yearAbbrev = vehicleYear.substr(2);
	myModel = jQuery.trim(myModel).toLowerCase();
	myModel = format_capitalize(myModel, 7);
	myTrim = jQuery.trim(myTrim).toLowerCase();
	myTrim = format_capitalize(myTrim, 8);

	var accbrochures = $.ajax({
		url: pathPrefix+'vehicles/my'+yearAbbrev+'/models.xml',
		async: false,
		cache: false
	});
	var regex = /.*WRX.*/;
	var found = true;
	$(accbrochures.responseXML).find("model[modelName="+myModel+"]").each(function() {
		var acc = $(this).attr("accBrochure");
		var accWRX = $(this).attr("accBrochureWRX");
		if (accWRX === undefined) {
			accWRX = acc;
		}


				if (myTrim.match(regex)) {
					accBrochure += accWRX;
				}
				 else {
					accBrochure += acc;
				}

				if(accWRX===undefined && acc ===undefined)
				{
					found=false;
				}


	}); //end each modelname
	return accBrochure;

}

function get_blueToothPhoneImageUrl(carrierId, phoneId) {
	var imageurl = pathPrefix; // default image should go here
	var phoneMatrix = $.ajax({
		url: linkPrefix+'bluetooth/matrix.taf?phoneid='+phoneId+'&carrierid='+carrierId+'&region=us',
		async: false,
		cache: false
	});
	$(phoneMatrix.responseXML).find("matrix phonedetails").each(function() {
		var newImageUrl = $(this).find("imageurl").text();
		if (newImageUrl === undefined) {newImageUrl = "";}
		if (newImageUrl.length > 0) {
			imageurl = newImageUrl;
		}
	});
	return imageurl;
} // end get_blueToothPhoneImageUrl

function get_blueToothPhoneInfo(optionCode, carrierId, manId, phoneId) {
	var phoneMatrix = "";
	var phoneInfo = '{';
	if (optionCode == 2) {
		phoneMatrix = $.ajax({
			url: linkPrefix+'bluetooth/matrix.taf?phoneid='+phoneId+'&carrierid='+carrierId+'&region=us',
			async: false,
			cache: false
		});
		$(phoneMatrix.responseXML).find("matrix").each(function() {
			var manufacturer = $(this).find("phonedetails manufacturer").text();
			var phonename = $(this).find("phonedetails phonename").text();
			var carrier = $(this).find("phonedetails carrier").text();
			var imageurl = $(this).find("phonedetails imageurl").text();

			phoneInfo += '"pName": "'+phonename+'", "pManufacturer": "'+manufacturer+'", "pImageUrl": "'+imageurl+'", "features": [';

				var phonepairing = ($(this).find("basicfeatures phonepairing").text() == 1) ? "Supported" : "Unsupported";
				var handsfreedialing = ($(this).find("basicfeatures handsfreedialing").text() == 1) ? "Supported" : "Unsupported";
				var incomingcall = ($(this).find("basicfeatures incomingcall").text() == 1) ? "Supported" : "Unsupported";
				var calltransfer = ($(this).find("basicfeatures calltransfer").text() == 1) ? "Supported" : "Unsupported";
				var callhangup = ($(this).find("basicfeatures callhangup").text() == 1) ? "Supported" : "Unsupported";
				var callwaiting = ($(this).find("advancedfeatures callwaiting").text() == 1) ? "Supported" : "Unsupported";
				var manualringtones = ($(this).find("advancedfeatures manualringtones").text() == 1) ? "Supported" : "Unsupported";
				var importcontact = ($(this).find("advancedfeatures importcontact").text() == 1) ? "Supported" : "Unsupported";

				phoneInfo += '{"featureName": "Phone Pairing", "data": "'+phonepairing+'", "tip": "Head Unit displays Bluetooth connection established message.	 Handset is added to the Device List."},';
				phoneInfo += '{"featureName": "Hands Free Dialing", "data": "'+handsfreedialing+'", "tip": "Call received by the phone number that was dialed.	Voice can be heard on vehicle speaker."},';
				phoneInfo += '{"featureName": "Incoming Call", "data": "'+incomingcall+'", "tip": "Caller\'s voice can be heard through the vehicle speaker. Receiver\'s voice can be heard by caller."},';
				phoneInfo += '{"featureName": "Transfer to Phone*", "data": "'+calltransfer+'", "tip": "Call is maintained on handset when vehicle key is turned off.  Bluetooth connection is re-established when vehicle key is turned back on."},';
				phoneInfo += '{"featureName": "Call Hangup", "data": "'+callhangup+'", "tip": "Call is ended. Line has been disconnected message displayed on Head Unit."},';
				phoneInfo += '{"featureName": "Call Waiting", "data": "'+callwaiting+'", "tip": "*Phone handset must have hold function.  Call is placed on hold.  Call hold window is shown on display."},';
				phoneInfo += '{"featureName": "Touch Tones", "data": "'+manualringtones+'", "tip": "Ability to send tones such as # or * through the BlueConnect system in order to navigate through automated menu systems common to toll-free numbers."},';
				phoneInfo += '{"featureName": "Import Contacts", "data": "'+importcontact+'", "tip": "Contacts added to Head Unit phone book. Call able to be placed from phonebook entry."}';

			phoneInfo += ']';
		});
	}
	else {
		phoneMatrix = $.ajax({
			url: pathPrefix+'conf/bluetooth.xml',
			async: false,
			cache: false
		});
		var manufacturer = $(phoneMatrix.responseXML).find("manufacturers manufacturer[id="+manId+"]").attr("name");
		var phonename = $(phoneMatrix.responseXML).find("manufacturers manufacturer[id="+manId+"] phone[id="+phoneId+"]").attr("name");
		var carrier = $(phoneMatrix.responseXML).find("carriers carrier[id="+carrierId+"]").attr("carrierName");
		var imageurl = get_blueToothPhoneImageUrl(carrierId, phoneId);

		phoneInfo += '"pName": "'+phonename+'", "pManufacturer": "'+manufacturer+'", "pImageUrl": "'+imageurl+'", "features": [';

		$(phoneMatrix.responseXML).find("types type[id="+optionCode+"] carrier[carrierId="+carrierId+"] manufacturer[manId="+manId+"] phone[phoneId="+phoneId+"] feature").each(function(index, thisElement) {
			var f_id = $(this).attr("id");
			var f_name = $(phoneMatrix.responseXML).find("features feature[id="+f_id+"]").attr("name");
			var f_tip = $(phoneMatrix.responseXML).find("features feature[id="+f_id+"]").text();
			var f_status = $(this).attr("status");

			phoneInfo += '{"featureName": "'+f_name+'", "data": "'+f_status+'", "tip": "'+f_tip+'"}';
			if (index != 8) {
				phoneInfo += ", ";
			}
		});

		phoneInfo += ']';
	}
	phoneInfo += "}";
	return phoneInfo;
} // end get_blueToothPhoneInfo

function get_blueToothTypeName(optionId){
	var typeName = "";
	var types = $.ajax({
		url: pathPrefix+'conf/bluetooth.xml',
		async: false,
		cache: false
	});
	$(types.responseXML).find("options option").each(function() {
		var accessoryId = $(this).attr("id");
		if (accessoryId == optionId) {
			var accessoryName = $(this).attr("name");
			typeName = accessoryName;
		}
	});
	return typeName;
} // end get_blueToothTypeName

function get_brochureInfo() {
	var brochures = $.ajax({
		url: pathPrefix+'vehicles/brochures.xml',
		async: false
	});
	return brochures;
} // end get_brochureInfo()

function get_buildURL(vehicleYear, myModel, modelCode, vehicle_id){
	// remove whitespace
	var buildURL = linkPrefix + "vehicles/";
	var myModel = myModel.toUpperCase();
	var vehicleYear = jQuery.trim(vehicleYear);
	var yearAbbrev = vehicleYear.substr(2);
	myModel = jQuery.trim(myModel).toUpperCase();
	var buildURLS = $.ajax({
		url: pathPrefix+'vehicles/my'+yearAbbrev+'/models.xml',
		async: false,
		cache: false
	});

	$(buildURLS.responseXML).find("model[modelName="+myModel+"]").each(function() {
		$(this).find("trim").each(function() {
			var mc = $(this).attr("modelCode");
			if (modelCode.toLowerCase() == mc.toLowerCase()) {
				buildURL += $(this).attr("buildURL");
			}//end if modelCode = mc


		})//end each trim

	})//end each modelname

	buildURL += "build.html?vehicleId="+ vehicle_id;
	return buildURL;

}

function get_dealerInfo(zip){
	var dealers = $.ajax({
		url: linkPrefix + "shopping-tools/data/dealer/getmapmarkers/" + zip,
		dataType: 'xml',
		async: false
	});
	return dealers;
} // end get_dealerInfo

//Get the decimal delimiter according to the received code.
function get_decimalDelimiter(countryCode) {
	switch (countryCode) {
		case 3:
			return '#';
		case 2:
			return ',';
		default:
			return '.';
	}
}

function get_cityStateZipInfo(inputValue, type) {
	type = (type == undefined) ? "city" : type;
	inputValue = inputValue.replace(" ", "+");
	var cszService = "GetInfoByCity?USCity=";
	if (type == "state") {
		cszService = "GetInfoByState?USState=";
	}
	var cszUrl = linkPrefix+"uszip/"+cszService+inputValue;
	var cszInfo = $.ajax({
		url: cszUrl,
		type: "GET",
		dataType: 'xml',
		async: false
	});
	return cszInfo;
}

//Get the comma delimiter according to the received code.
function get_commaDelimiter(countryCode) {

  switch (countryCode)
  {
	case 3:
		   return '*';
	case 2:
		   return ',';
	default:
		   return ',';
  }

}

function get_formatedDate() { // returns Current Long date (eg. Tuesday, 11/10/2009 1:21 PM)
	var date;
	var dayName=new Array(7)
	dayName[0]="Sunday";
	dayName[1]="Monday";
	dayName[2]="Tuesday";
	dayName[3]="Wednesday";
	dayName[4]="Thursday";
	dayName[5]="Friday";
	dayName[6]="Saturday";
	var today=new Date(); // Initialize Date in raw form
	var day = today.getDay(); // Get the day in number form (0,1,2,3,etc.)
	var curr_date = today.getDate();
	var curr_month = today.getMonth();
	var curr_year = today.getFullYear();
	var curr_hour = today.getHours();
	var curr_min = today.getMinutes();
	if (curr_min < 10) {
		curr_min = "0" + curr_min;
	}
	var a_p = "";

	if (curr_hour < 12) {
		a_p = "AM";
	}
	else {
		a_p = "PM";
	}

	if (curr_hour == 0) {
		curr_hour = 12;
	}
	if (curr_hour > 12) {
		curr_hour = curr_hour - 12;
	}
	date = dayName[day] + ",   " + (curr_month+1)+"/"+curr_date+"/"+curr_year+" "+curr_hour + ":" + curr_min + " " + a_p;
	return date;
}

function get_gtpInfo(vin) {
	var formUrl = linkPrefix+'tools/gtp/vehicle/gtpinfoxml/'+vin;
	gtpInfo = $.ajax({
		url: formUrl,
		async: false,
		cache: false
	});
	return gtpInfo;
} // end get_gtpInfo

function get_myGtpInfo(id, type) {
	if (type === undefined) {type = 'vin';}
	var gtpInfo = "noGTP";
	var gtpVin = id;
	if (type == "vehicleId") {
		$(vehicles_owned).each(function() {
			var vehicleId = $(this).attr("VEHICLE_ID");
			if (id == vehicleId) {
				gtpVin = $(this).attr("VIN");
			}
		});
	}
	if (gtpVin.length > 0) {
		var formUrl = linkPrefix+'shopping-tools/data/vehicle/gtpinfoxml/'+gtpVin;
		gtpInfo = $.ajax({
			url: formUrl,
			async: false,
			cache: false
		});
	}
	return gtpInfo;
}

function get_maintenanceScheduleDealer(vehicleId) {
	ms_dealer = $.ajax({
		url: linkPrefix+'my-subaru/data/vehicle/maintenance/dealer/'+vehicleId,
		async: false,
		cache: false
	});
	return ms_dealer;
}

function get_maintenanceScheduleManufacturer(vehicleId) {
	ms_manufacturer = $.ajax({
		url: linkPrefix+'my-subaru/data/vehicle/maintenance/manufacturer/'+vehicleId,
		async: false,
		cache: false
	});
	return ms_manufacturer;
}

function get_modelDetailPath(modelYear, modelName, modelTrim) {
	var path = linkPrefix+"vehicles/";
	var modelDir = modelName.toLowerCase().replace(" ", "-");
	/*
	var trimDir = modelTrim.toLowerCase().replace(".", "").replace(" ", "-").replace("wrx-", "");
	if (modelName == "Forester") {
		trimDir = trimDir.replace("premium", "p").replace("limited", "l").replace("-","");
	}
	path += modelDir+"/"+trimDir+"/index.html";
	*/
	path += modelDir+"/index.html";
	return path;
}

function get_modelInfo(modelYear) {
	var yearAbbrev = modelYear.substr(2);
	var models;
	$.ajax({
		async: false,
		url: pathPrefix+'vehicles/my'+yearAbbrev+'/models.xml',
		complete: function(xhr, textStatus) {
			models = xhr;
		}
	});
	return models;
} // end get_modelInfo

function get_modelOptionCodes(modelYear, modelName, myTrim) {
	var mc;
	var trims = get_modelInfo(modelYear);
	modelName = (modelName.toLowerCase() == "impreza" || modelName.toLowerCase() == "impreza wrx") ? "Impreza" : format_capitalize(modelName.toLowerCase());
	$(trims.responseXML).find("model[modelName="+modelName+"] trim").each(function() {
		var trimName = $(this).attr("trimName");
		if (myTrim.toLowerCase() == trimName.toLowerCase()) {
			var modelCode = $(this).attr("modelCode").split(" | ");
			var optionCode = "0";
			if (modelYear > 2009) {
				optionCode = $(this).attr("optionCode").split(" | ");
			}
			mc = modelCode[0]+" | "+optionCode[0];
		}
	});
	return mc;
}

function get_modelTrimImage(yearAbbrev, myModel, modelCode, vehicleType, colorCode) {
	var defaultImage = "";
	var image = "";
	yearAbbrev = jQuery.trim(yearAbbrev);
	myModel = jQuery.trim(format_capitalize(myModel.toLowerCase()));
	if (vehicleType === undefined) {vehicleType = 'garaged';}
	if (colorCode === undefined) {colorCode = 'none';}
	var trims = $.ajax({
		url: pathPrefix+'vehicles/my'+yearAbbrev+'/models.xml',
		async: false,
		cache: false
	});

	var imagePath = "";
	$(trims.responseXML).find("model[modelName="+myModel+"]").each(function() {
		defaultImage = $(this).attr("defaultImage");
		$(this).find("trim").each(function() {
			if (vehicleType == "owned") {
				image = $(this).attr("ownedImage");
			}
			else if (vehicleType == "garaged") {
				image = $(this).attr("storedImage");
			}
			if (image === undefined || image == "") {
				image = defaultImage;
			}
			var mcArray = $(this).attr("modelCode").split(" | ");
			for (i=0; i<mcArray.length; i++){
				var mc = mcArray[i];
				if (modelCode.toLowerCase() == mc.toLowerCase()) {
					if (colorCode != 'none') {
						imagePath = pathPrefix+image+colorCode+".png";
					}
					else {
						imagePath = pathPrefix+image;
					}
				}
			}
		});
	});
	if (imagePath.length == 0) {
		imagePath = pathPrefix+defaultImage;
	}
	return imagePath;
}

function get_modelYears() {
	var modelYears;
	$.ajax({
		async: false,
		cache: false,
		url: pathPrefix+'vehicles/model_years.xml',
		complete: function(xhr, textStatus) {
			modelYears = xhr;
		}
	});
	return modelYears;
}

function get_monthName(monthIdentifier) {
	var monthsObject = months;
	var monthName = "";
	if (monthIdentifier === undefined) {monthIdentifier == 0}
	// determine if monthIdentifier is a number or an abbreviation
	var monthDigit = monthIdentifier.replace(/[^\d]/g, "");

	if (monthDigit.length > 0) {
		$(monthsObject).each(function() {
			var mNumber = this.monthNumber;
			if (monthIdentifier == mNumber) {
				monthName = this.monthName;
			}
		});
	}
	else {
		$(monthsObject).each(function() {
			var mAbbrev = this.monthAbbrev;
			if (monthIdentifier == mNumber) {
				monthName = this.monthName;
			}
		});
	}
	return monthName;
}

function get_msrp(year, model, trim) {
	var msrp = "";
	model = format_capitalize(model.toLowerCase());
	var modelInfo = get_modelInfo(year);
	$(modelInfo.responseXML).find("model[modelName="+model+"] trim[trimName="+trim+"]").each(function(){
		msrp = $(this).attr("msrp");
	});
	return msrp;
} // ent get_msrp

function get_nextServiceTitle(veh_id) {
	var ms_title = "";
	var ms = get_maintenanceScheduleDealer(veh_id);
	$(ms.responseXML).find("maintenanceRecord[completed=false][overdue=false]").each(function(index, thisElement){
		if (index < 1) {
			var serviceTitle = $(this).find("title").text();
			var stArray = serviceTitle.split("miles");
			var serviceMileage = $(this).find("mileage").text();
				serviceMileage = format_commas(serviceMileage);
			ms_title = serviceMileage+" miles "+stArray[1];
		}
	});
	return ms_title;
}

function get_ownerEvents(eventXmlUrl) {
	var owner_events = "";
	owner_events = $.ajax({
		type: "GET",
		url: eventXmlUrl,
		dataType: "xml",
		async: false,
		cache: false
	});
	return owner_events;

}

function get_pageScroll() {
	var ScrollTop = document.body.scrollTop;
	if (ScrollTop == 0) {
		if (window.pageYOffset) ScrollTop = window.pageYOffset;
		else ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
	}
	return ScrollTop;
}

function get_purchaseDate(vin){
	var vinInfo = get_vinInfo(vin);	
	var purchaseDate = "";
	
	$(vinInfo.responseXML).find("salesInfo").each(function() {		
		purchaseDate = $(this).find("dateSold").text();
	});
		
	return purchaseDate;	
}

function get_recallDetail(vid) {
	var recall_detail = "";
	recall_detail = $.ajax({
		url: linkPrefix+'my-subaru/data/vehicle/recalls/'+vid,
		async: false,
		cache: false
	});
	return recall_detail;
}

function get_serviceHistory(vehicle_id) {
	var service_history = "";
	service_history = $.ajax({
		url: linkPrefix+'my-subaru/data/vehicle/servicehistory/'+vehicle_id,
		async: false,
		cache: false
	});
	return service_history;
}

function get_serviceRecordReason(vehicleId, reasonId) {
	var srDesc = "";
	if (reasonId === undefined) { reasonId = 'none'; }
	if (reasonId.toLowerCase() == "p") {
		srDesc = "Repair";
	}
	else if (reasonId.toLowerCase() == "o") {
		srDesc = "Other";
	}
	else if (reasonId.toLowerCase() == "r") {
		srDesc = "Recall Campaign";
	}
	// get dealer maintenance schedule
	var msDealer = get_maintenanceScheduleDealer(vehicleId);
	var msDealerSize = $(msDealer.responseXML).find("maintenanceRecord").size();
	if (msDealerSize > 0) {
		$(msDealer.responseXML).find("maintenanceRecord").each(function() {
			var oValue = $(this).find("mileage").text();
			if (reasonId == oValue) {
				var reasonMileage = format_commas(oValue);
				var oText = $(this).find("title").text();
				var otArray = oText.split("miles");
				srDesc = reasonMileage+" miles "+otArray[1];
			}
		});
	}
	else {
		var msManufacturer = get_maintenanceScheduleManufacturer(vehicleId);
		$(msManufacturer.responseXML).find("maintenanceRecord").each(function() {
			var oValue = $(this).find("mileage").text();
			if (reasonId == oValue) {
				var reasonMileage = format_commas(oValue);
				var oText = $(this).find("title").text();
				var otArray = oText.split("miles");
				srDesc = reasonMileage+" miles "+otArray[1];
			}
		});
	}
	return srDesc;
}

function get_vinInfo(vin) {
	var vinInfo = $.ajax({
		type: "POST",
		data: "vin="+vin,
		url: linkPrefix+'my-subaru/data/vehicle/salesinfo/',
		async: false,
		cache: false
	});
	return vinInfo;
}

function get_zipCodeFromCityState(inputValue) {
	var zipcode = "";
	var inputArray = inputValue.split(/,|\//);
	var inputCity = jQuery.trim(inputArray[0]);
	var inputState = jQuery.trim(inputArray[1]);
	var cszInfo = get_cityStateZipInfo(inputCity, "city");
	$(cszInfo.responseXML).find("Table").each(function() {
		var rState = $(this).find("STATE").text();
		if (rState.toUpperCase() == inputState.toUpperCase() && zipcode.length == 0) {
			zipcode = $(this).find("ZIP").text();
		}
	});
	return zipcode;
}

function get_UrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

//-----------------------------------------------------------------------------------
//6.0 instantiate_
//-----------------------------------------------------------------------------------

function instantiate_bluetoothCompatibility() {
	var init = $('.bluetooth_compatibility').size();
	if (init != 0) {
		// Model_Year
		$('select[name=bt_year]').change(function(){
			var selectValue = $(this).val();
			if (selectValue != "noSelection") {
				var modelOptions = create_blueToothModelOptions(selectValue);
				$('select[name=bt_model]').empty().append(modelOptions);
				// empty all following select boxes
				$('select[name=bt_accessory], select[name=bt_carrier], select[name=bt_manufacturer]').empty();
			}
			else{
				// empty all following select boxes
				$('select[name=bt_accessory], select[name=bt_carrier], select[name=bt_manufacturer]').empty();
			}
		});

		// Model
		$('select[name=bt_model]').change(function(){
			var selectValue = $(this).val();
			if (selectValue != "noSelection") {
				var btAccessoryOptions = create_blueToothAccessoryOptions(selectValue);
				$('select[name=bt_accessory]').empty().append(btAccessoryOptions);

				// empty all following select boxes
				$('select[name=bt_carrier], select[name=bt_manufacturer]').empty();
			}
			else {
				// empty all following select boxes
				$('select[name=bt_carrier], select[name=bt_manufacturer]').empty();
			}
		});

		// Bluetooth Accessory
		$('select[name=bt_accessory]').change(function(){
			var selectValue = $(this).val();
			if (selectValue != "noSelection") {
				var carrierOptions = create_blueToothCarrierOptions(selectValue);
				$('select[name=bt_carrier]').empty().append(carrierOptions);

				// empty all following select boxes
				$('select[name=bt_manufacturer]').empty();
			}
			else {
				// empty all following select boxes
				$('select[name=bt_manufacturer]').empty();
			}
		});

		// Carrier
		$('select[name=bt_carrier]').change(function(){
			var selectValue = $(this).val();
			var optionId = $('select[name=bt_accessory]').val();
			if (selectValue != "noSelection") {
				var manufacturerOptions = create_blueToothManufacturerOptions(optionId, selectValue);
				$('select[name=bt_manufacturer]').empty().append(manufacturerOptions);
			}

		});

		// Manufacturer
		$('select[name=bt_manufacturer]').change(function(){
			var selectValue = $(this).val();
			if (selectValue != "noSelection") {
				// show the next button
				$('#bt_next').show("slow");
			}
			else {
				$('#bt_next').hide("slow");
			}

		});

		// phone
		$('select[name=bt_phone]').change(function(){
			var selectValue = $(this).val();
			var carrierId = $('select[name=bt_carrier]').val();
			var manId = $('select[name=bt_manufacturer]').val();
			var optionId = $('select[name=bt_accessory]').val();
			if (selectValue != "noSelection") {
				var phoneInfo = JSON.parse(get_blueToothPhoneInfo(optionId, carrierId, manId, selectValue));
				var phoneName = phoneInfo.pName;
				var phoneManufacturer = phoneInfo.pManufacturer;
				var phoneImageUrl = phoneInfo.pImageUrl;
				var phoneImage = '<img src="'+phoneImageUrl+'" alt="'+phoneName+'" />';
				var phoneTitle = phoneName+" by "+phoneManufacturer;
				$('.phone_image').empty().append(phoneImage);
				$('.bt_phone_name').empty().append(phoneTitle);

				// create the features table
				var html = "\n<table>";
					html += "\n\t<tr>";
					html += "\n\t\t<th>Features:</th>";
					html += "\n\t\t<th>Status</th>";
					html += "\n\t</tr>";

				$(phoneInfo.features).each(function() {
					var f_name = this.featureName;
					var f_data = this.data;
					var f_tip = this.tip;
					var feature = "";
					if (f_tip.length > 0) {
						feature = '<a class="cluetip200" title="'+f_name+':|'+f_tip+'" href="#">'+f_name+'</a>';
					}
					else {
						feature = f_name;
					}
					html += "\n\t<tr>";
					html += "\n\t\t<td>"+feature+"</td>";
					html += "\n\t\t<td>"+f_data+"</td>";
					html += "\n\t</tr>";
				});
				html += "\n</table>";

				$('.phone_features .bt_table').empty().append(html);
				$('#bt_startover').show("slow");
				// listen for any cluetips
				listen_clueTips();
			}
			else {
				$('#bt_startover').hide("slow");
			}
		});

		// Button Interaction
		$('#reset_bluetooth_compatibility').click(function(e) {
			e.preventDefault();
			// reload the page
			var redirectURL = window.location.pathname + window.location.search;
			window.location.assign(redirectURL);
			return false;
		});

		$('#submit_bluetooth_compatibility').click(function(e) {
			e.preventDefault();
			// get the optionType name
			var optionId = $('select[name=bt_accessory]').val();
			var bt_typeName = get_blueToothTypeName(optionId);
			$('.bt_type').empty().append(bt_typeName);
			// get the phone options
			var carrierId = $('select[name=bt_carrier]').val();
			var manId = $('select[name=bt_manufacturer]').val();
			var phoneOptions = create_blueToothPhoneOptions(optionId, carrierId, manId);
			$('select[name=bt_phone]').empty().append(phoneOptions);

			$('.showForm').hide();
			$('.showResult').fadeIn("slow");

			return false;
		});

	}
} // end instantiate_bluetoothCompatibility

function instantiate_dearSubaruCharacterCounter(){
	var init = $('#story').size();
	if (init != 0) {
		$("#story").apTextCounter({
			maxCharacters: 750,
			direction: "up",
			tracker: "#count",
			trackerTemplate: "(Character max 750. Current count: %s)"
		});
	}
}

function instantiate_formAccountCreation() {
	var init = $('#form_account_creation').size();
	if (init != 0) {
		// "Accordion" Interaction
			// by default, hide appropriate elements
			$("dd:not(:first)").hide();
			$("dt:not(:first)").hide();

		$("dt").click(function() {
			var thisTitle = $(this).attr("id");
			var activeTitle = $('dt.active').attr("id");

			if (thisTitle == activeTitle || activeTitle == "account_preferences") {
				// do nothing, they clicked on the same title OR they are trying to skip ahead
			}
			else if (thisTitle == "account_preferences" && (activeTitle == "account_contact_info" || activeTitle == "account_vehicle_info")) {
				$('dt#'+activeTitle).removeClass("active");
				$('dd:visible').slideUp("slow");
				$('dt#account_preferences').addClass("active");
				$('dd#owner_preferences').slideDown("slow");
			}
			else if (thisTitle == "account_contact_info" && activeTitle == "account_vehicle_info") {
				$('dt#account_contact_info').removeClass("active");
				$('dd:visible').slideUp("slow");
				$('dt#account_vehicle_info').addClass("active");
				$('dd#owner_vehicle_info').slideDown("slow");
			}
		});

		// Current_Owner_Identify
		$("input[name=currentOwner]").click(function() {
			// determine if the box is checked
			var isChecked = $(this).attr('checked');

			if (isChecked == true) {
				$("dd:first").hide();
				$("dd#owner_preferences").show();
				$("dt").show();
			}
			else if (isChecked == false) {
				$("dt").hide();
				$("dd").hide();
				$("dt:first").show();
				$("dd:first").show();
			}
		});

		// Date_Picker_Show

		$("#purchaseDate").datepicker({
			showOn: 'button',
			buttonImage: '/content/images/site/icons/calendar.gif',
			buttonImageOnly: true,
			changeYear: true,
			minDate: minDate,
			maxDate: maxDate
		});
		$("#purchaseDate").addClass("maskedDate");

		// create model year options
		var modelYearOptions = create_modelYearOptions();
		$('select#chooseYear').empty().append(modelYearOptions);

		// create state options
		var stateOptions = create_stateOptions(my_profile_home_state);
		$('#owner_homeState').empty().append(stateOptions);

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// Address_Zip
		$('input#zipCode2, input#owner_zipCode2').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_zipCode(inputId, inputValue);
		});

		// Date
		$('input#purchaseDate').change(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			var isDate = validate_date(inputValue, $(this));

			if (isDate != "true") {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: isDate
				});
			}
			else if (isDate == "true") {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});
		$('input#purchaseDate').blur(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			if (inputValue.length > 0) {
				var isDate = validate_date(inputValue, $(this));

				if (isDate != "true") {
					$("#error_"+inputId+", div.errorClear").remove();
					$(this).errorMessage(
					{
						messageMain: isDate
					});
				}
				else if (isDate == "true") {
					$("#error_"+inputId+", div.errorClear").remove();
					$(this).removeClass("errorFocus");
				}
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter a valid date (mm/dd/yyyy)."
				});
			}
		});

		// Email
		$('input#myEmail, input#ownerEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_email(inputId, inputValue);
		});

		// Email_Confirm
		$('input#confirmMyEmail, input#confirmOwnerEmail').blur(function() {
			var inputId = $(this).attr("id");
			var email1 = $('input#myEmail').val();
			if (inputId == "confirmOwnerEmail") {
				email1 = $('input#ownerEmail').val();
			}
			var email2 = $(this).val();
			validate_emailConfirm(inputId, email1, email2);
		});

		// Model
		$('select#chooseModel').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_model(inputId, selectOption);
		}).change(function(){
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var year = $("select#chooseYear").val();
			validate_model(inputId, selectOption, year);
		});

		// Model_Trim
		$('select#chooseTrim').blur(function()	{
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelTrim(inputId, selectOption);

		}).change(function(){
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelTrim(inputId, selectOption);
		});

		// Model_Year
		/*$('select#chooseYear').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelYear(inputId, selectOption);
		}).change(function(){
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelYear(inputId, selectOption);
		});*/

		// Model_Year
		$('select#chooseYear').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var validYear = validate_modelYear(inputId, selectOption, "none");
			var vinValue = $('input#vin').val();
			if (validYear && vinValue.length == 0) {
				var modelOptions = create_modelOptions(selectOption);
				$('select#chooseModel').empty().append(modelOptions);
			}
		}).change(function(){
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var validYear = validate_modelYear(inputId, selectOption, "none");
			var vinValue = $('input#vin').val();
			if (validYear && vinValue.length == 0) {
				var modelOptions = create_modelOptions(selectOption);
				$('select#chooseModel').empty().append(modelOptions);
			}
		});

		// Name_First
		$('input#fn, input#owner_fn').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your first name";
			validate_presenceOf(inputId, inputValue, message);
		});

		// Name_Last
		$('input#ln, input#owner_ln').blur(function(){
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your last name";
			validate_presenceOf(inputId, inputValue, message);
		});

		// Password
		$('input#password, input#ownerPassword').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_password(inputId, inputValue);
		});

		// Password_Confirm_Account_Creation
		$('input#confirmPassword, input#confirmOwnerPassword').blur(function() {
			var inputId = $(this).attr("id");
			var pw1 = $('input#'+inputId).val();
			var pw2 = $(this).val();
			validate_passwordConfirm(inputId, pw1, pw2);
		});

		// Phone_Home
		$("input#owner_homePhone, input#owner_workPhone").blur(function() {
			// proceed with validation
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_phoneNumber(inputId, inputValue);
		}).focus(function(){
			$(this).val($(this).val().replace(/[-]/gi,"")).attr('maxlength', '10');
		});

		// Vehicle Identification Number (VIN)
		$('input#vin').blur(function() {
			var vin = jQuery.trim($(this).val().toUpperCase());
			validate_vin(vin);
		});

		// Submit_Non_Owner_Account_Creation
		$('#submit_non_owner_account_creation').click(function(e) {
			e.preventDefault();
			submit_nonOwnerAccountCreation();
			return false;
		});

		// Validate_Step_1
		$('#validate_step1').click(function() {
			$("#error_privacyPolicy, div.errorClear").remove();
			$(this).removeClass("errorFocus");

			// check for obvious errors
			var fieldErrors = $('dd#owner_preferences').find("div.errorCont").length;

			// loop through each required field and check for a value
			$('dd#owner_preferences').find("p.required").each(function(index, thisElement) {
				var elementID = $(thisElement).children("eq(0)").attr("id");
				var elementValue = $(thisElement).children("eq(0)").val();
				var elementLength = parseFloat(elementValue.length);
				if (elementLength == 0 || elementValue == "noSelection") {
					// set fieldErrors to 1
					fieldErrors = 1;

					// trigger an error
					$("#error_"+elementID+", div.errorClear").remove();
					$('#'+elementID).errorMessage();
				}
			});

			if (fieldErrors == 0) {
				$('dt#account_preferences').removeClass("active");
				$('dd#owner_preferences').slideUp("slow");
				$('dt#account_contact_info').addClass("active");
				$('dd#owner_contact_info').slideDown("slow");
			}
			return false;
		});

		// Validate_Step_2
		$('#validate_step2').click(function() {
			// check for obvious errors
			var fieldErrors = $('dd#owner_contact_info').find("div.errorCont").length;

			// loop through each required field and check for a value
			$('dd#owner_contact_info').find("p.required").each(function(index, thisElement) {
				var elementID = $(thisElement).children("eq(0)").attr("id");
				var elementValue = $(thisElement).children("eq(0)").val();
				var elementLength = parseFloat(elementValue.length);
				if (elementLength == 0 || elementValue == "noSelection") {
					// set fieldErrors to 1
					fieldErrors = 1;

					// trigger an error
					$("#error_"+elementID+", div.errorClear").remove();
					$('#'+elementID).errorMessage();
				}
			});

			if (fieldErrors == 0) {
			/*	// get preferred dealer
				var inputValue = $('#owner_zipCode2').val();
				// get the dealer information
				var dealers = $.ajax({
					url: linkPrefix + "shopping-tools/data/dealer/getmapmarkers/"+inputValue,
					dataType: 'xml',
					async: false,
					cache: false
				});

				// build the dealer information
				var dealerInfo = '\n<label>My Preferred Dealer</label>';
				$(dealers.responseXML).find("marker").each(function(index, thisElement) {
					//alert("index: "+index+"\ndistance: "+distance+"\nsearchRadius: "+searchRadius);
					if (index == 0) {
						// set the variables
						var markerID = $(thisElement).attr("id");
						var dealerName = $(thisElement).attr("name");
						var dealerAddress = $(thisElement).attr("street");
						var dealerCity = $(thisElement).attr("city");
						var dealerState = $(thisElement).attr("state");
						var dealerZip = $(thisElement).attr("zipcode");
						var dealerPhone = $(thisElement).attr("phone");
						var dealerLink = $(thisElement).attr("link");
						var lat = $(thisElement).attr("lat");
						var lng = $(thisElement).attr("lng");

						dealerInfo += '<p class="inputCont dealer_title"><a target="_blank" href="'+dealerLink+'" title="'+dealerName+'">'+dealerName+'</a></p>';
						dealerInfo += '<p class="inputCont dealer_address">'+dealerAddress+'<br />'+dealerCity+', '+dealerState+' '+dealerZip+' <br /> '+dealerPhone+'</p>';
					}
				});

				$('#preferredDealerCont').empty().append(dealerInfo);
			*/

				$('dt#account_contact_info').removeClass("active");
				$('dd#owner_contact_info').slideUp("slow");
				$('dt#account_vehicle_info').addClass("active");
				$('dd#owner_vehicle_info').slideDown("slow");
			}
			return false;
		});

		// Validate_Step_3
		$('#validate_step3').click(function() {
			// hide the buton
			$('#button_submitOwnerAccountCreation').hide();

			// check for obvious errors
			var fieldErrors = $('dd#owner_vehicle_info').find("div.errorCont").length;

			// loop through each required field and check for a value
			$('dd#owner_vehicle_info').find("p.required").each(function(index, thisElement) {
				var elementID = $(thisElement).children("eq(0)").attr("id");
				var elementValue = $(thisElement).children("eq(0)").val();
				var elementLength = parseFloat(elementValue.length);
				if (elementLength == 0 || elementValue == "noSelection" || elementValue == "") {
					// set fieldErrors to 1
					fieldErrors = 1;

					// trigger an error
					$("#error_"+elementID+", div.errorClear").remove();
					$('#'+elementID).errorMessage();

					// show the button
					$('#button_submitOwnerAccountCreation').show();
				}
			});

			if (fieldErrors == 0) {
				// remove the "non-owner" portions of the form
				$("dd#nonOwner_preferences").remove();

				// if a VIN was NOT entered...
				var vin = $('input#vin').val();
				if (vin.length == 0) {
					// get the modelCode & optionCode
					var modelYear = $('select#chooseYear').val();
					var mn = $('select#chooseModel').val();
					var tn = $('select#chooseTrim option:selected').text();
					var moCodes = get_modelOptionCodes(modelYear, mn, tn);
					var mcArray = moCodes.split(" | ");

					$('input#modelCode').val(mcArray[0]);
					$('input#optionCode').val(mcArray[1]);
				}

				// Set the Omniture Variables
				s=s_gi(s_account);
				s.linkTrackVars="eVar1,eVar18,eVar19,eVar20,eVar21,prop29,prop30,prop31, prop33,zip,state,events";
				s.linkTrackEvents="event27";
				s.eVar1 = $('#chooseModel').val(); // model input field
				s.eVar18 = $('input[name=homeZip]').val();
				s.eVar19 = $('input[name=homeState]').val();
				s.eVar20 = "owner";
				s.eVar21 = $('#ownerEmail').val();
				s.prop29 = $('input[name=homeZip]').val();
				s.prop30 = $('input[name=homeState]').val();
				s.prop31 = "owner";
				s.prop33 = $('#ownerEmail').val();
				s.zip = $('input[name=homeZip]').val();
				s.state = $('input[name=homeState]').val();
				s.events = "event27";
				s.tl(this,'o','my-subaru:complete registration');

				// submit the form
				$('#form_account_registration').submit();
			}
			return false;
		});
	}
}

function instantiate_formAddServiceRecord() {
	var init = $('#form_add_service_record').size();
	if (init != 0) {
		// date picker

		var currentTime = new Date()
		var currentDate = new Date(currentTime.getFullYear(), currentTime.getMonth(), currentTime.getDate());

		$("#serviceDate").datepicker({
			showOn: 'button',
			buttonImage: '/content/images/site/icons/calendar.gif',
			buttonImageOnly: true,
			changeYear: true,
			minDate: minDate,
			maxDate: currentDate
		});

		$("#serviceDate").addClass("maskedDate");

		// create service reasons options
		var sr = create_serviceReasonOptions(vehicle_id);
		$('select#serviceReason').empty().append(sr);

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// Date
		$('input#serviceDate').change(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			var isDate = validate_date(inputValue);

			if (isDate != "true") {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: isDate
				});
			}
			else if (isDate == "true") {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});
		$('input#serviceDate').blur(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");

			if (inputValue.length > 0) {
				var isDate = validate_date(inputValue);

				if (isDate != "true") {
					$("#error_"+inputId+", div.errorClear").remove();
					$(this).errorMessage(
					{
						messageMain: isDate
					});
				}
				else if (isDate == "true") {

					var testDate = new Date(inputValue);
					var currentDate = new Date(currentTime.getFullYear(), currentTime.getMonth(), currentTime.getDate());
					var msg ="The date should be between " + (minDate.getMonth()+1) + "/" + minDate.getDate() + "/" + minDate.getFullYear() + " and " + (currentDate.getMonth() +1) + "/" + (currentDate.getDate()) + "/" + currentDate.getFullYear();

					if (testDate > currentDate){
						$("#error_"+inputId+", div.errorClear").remove();
						$(this).errorMessage(
						{
							messageMain: msg
						});
					}else{
						$("#error_"+inputId+", div.errorClear").remove();
						$(this).removeClass("errorFocus");
					}

				}
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter a valid date (mm/dd/yyyy)."
				});
			}
		});

		// Description
		$('input#serviceDescription').blur(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id")
			if (inputValue.length == 0) {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter service description."
				});
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		// Mileage
		$('input#visibleServiceMileage').focus(function(){
			$(this).val($(this).val().replace(/[,]/gi,"")).attr('maxlength', '7');
		}).bind('keypress', function(e) {
			return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
		}).blur(function() {
			$(this).attr('maxlength', '9');
			this.value=format_number(this.value,1,0);
			var inputValue = $(this).val();

			var inputId = $(this).attr("id");
			var inputDigits = inputValue.replace(/[^\d]/g, "");

			if (inputDigits.length == 0 || inputValue == 0) {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter the current mileage."
				});
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		// Provider
		$('input#serviceProvider').blur(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id")
			if (inputValue.length == 0) {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter the service provider."
				});
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		// Reason
		$('select#serviceReason').blur(function() {
			var selectOption = $(this).val();
			var selectId = $(this).attr("id");
			if (selectOption == "noSelection")
			{
				$("#error_"+selectId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please select a reason for service."
				});
			}
		}).change(function(){
			var selectOption = $(this).val();
			var selectId = $(this).attr("id");
			if (selectOption != "noSelection") {
				$("#error_"+selectId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		// submit_add_service_record
		$('#submit_add_service_record').click(function() {
			submit_addServiceRecord("form_add_service_record");
			return false;
		});
	}
}

function instantiate_formAddVehicle() {
	var init = $('#form_add_vehicle').size();
	if (init != 0) {
		// get vin value
		var vinValue = $('input#vin').val();

		if (vinValue.length == 0) {
			// enable the date picker
			$("#purchaseDate").datepicker({
			showOn: 'button',
			buttonImage: '/content/images/site/icons/calendar.gif',
			buttonImageOnly: true,
			changeYear: true,
			minDate: minDate,
			maxDate: maxDate
		});

		$("#purchaseDate").addClass("maskedDate");

			// create model year options
			var modelYearOptions = create_modelYearOptions();
			$('select#chooseYear').empty().append(modelYearOptions);
		}

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// Date
		$('input#purchaseDate').change(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			var isDate = validate_date(inputValue, $(this));

			if (isDate != "true") {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: isDate
				});
			}
			else if (isDate == "true") {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});
		$('input#purchaseDate').blur(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			if (inputValue.length > 0) {
				var isDate = validate_date(inputValue, $(this));

				if (isDate != "true") {
					$("#error_"+inputId+", div.errorClear").remove();
					$(this).errorMessage(
					{
						messageMain: isDate
					});
				}
				else if (isDate == "true") {
					$("#error_"+inputId+", div.errorClear").remove();
					$(this).removeClass("errorFocus");
				}
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter a valid date (mm/dd/yyyy)."
				});
			}
		});

		// Mileage
		$('input#currentMileage').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_mileage(inputId, inputValue);
		});

		// Model
		$('select#chooseModel').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var year = $("select#chooseYear").val();
			var validModel = validate_model(inputId, selectOption, year, "none");
				vinValue = $('input#vin').val();
			if (validModel == "yes" && vinValue.length == 0) {
				var trimOptions = create_modelTrimOptions(selectOption, year);
				$('select#chooseTrim').empty().append(trimOptions);
			}

		}).change(function(){
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var year = $("select#chooseYear").val();
			var validModel = validate_model(inputId, selectOption, year, "none");
				vinValue = $('input#vin').val();
			if (validModel == "yes" && vinValue.length == 0) {
				var trimOptions = create_modelTrimOptions(selectOption, year);
				$('select#chooseTrim').empty().append(trimOptions);
			}
		});

		// Model_Trim
		$('select#chooseTrim').blur(function()	{
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelTrim(inputId, selectOption);

		}).change(function(){
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelTrim(inputId, selectOption);
		});

		// Model_Year
		$('select#chooseYear').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var validYear = validate_modelYear(inputId, selectOption, "none");
				vinValue = $('input#vin').val();
			if (validYear == "yes" && vinValue.length == 0) {
				var modelOptions = create_modelOptions(selectOption);
				$('select#chooseModel').empty().append(modelOptions);
			}
		}).change(function(){
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var validYear = validate_modelYear(inputId, selectOption, "none");
				vinValue = $('input#vin').val();
			if (validYear == "yes" && vinValue.length == 0) {
				var modelOptions = create_modelOptions(selectOption);
				$('select#chooseModel').empty().append(modelOptions);
			}
		});

		// Vehicle Identification Number (VIN)
		$('input#vin').blur(function() {
			var vin = jQuery.trim($(this).val().toUpperCase());
			var validVin = validate_vin(vin);
			if (validVin) {
				vinValue = vin;
				$("#purchaseDate").datepicker('destroy');
			}
			else {
				vinValue = "";
				$("#purchaseDate").datepicker({
					showOn: 'button',
					buttonImage: '/content/images/site/icons/calendar.gif',
					buttonImageOnly: true,
					changeYear: true,
					minDate: minDate,
					maxDate: maxDate
				});

				$("#purchaseDate").addClass("maskedDate");
			}
		});

		// Vehicle Name
		$('input#name').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_vehicleName(inputId, inputValue);
		});

		// Submit_Add_Vehicle
		$('#submit_add_vehicle').click(function(e) {
			e.preventDefault();
			submit_addVehicle();
			return false;
		});
	}
}

function instantiate_formContactUs() {
	var init = $('#form_contactUs').size();
	if (init != 0) {
		//create the subject dropdown
		var subjectOptions = create_subjectOptions(subject);
		$('select#subjectCategory').empty().append(subjectOptions);

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// address - city
		$('input#homeCity').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter the name of your city.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// address - state
		$('select#homeState').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_presenceOf(inputId, selectOption);
		}).change(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_presenceOf(inputId, selectOption);
		});

		// address - street1
		$('input#homeAddress').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home street address.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// address - zip
		$('input#zipCode2').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_zipCode(inputId, inputValue);
		});

		// category
		$('select#subjectCategory').blur(function() {
			var selectOption = $(this).val();
			if (selectOption == "noSelection")
			{
				$("#error_subjectCategory, div.errorClear").remove();
				$(this).errorMessage({
					messageMain: "Please select a Subject / Category."
				});
			}
			else if (selectOption != "noSelection")
			{
				$("#error_subjectCategory, div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		// comments
		$('textarea#customerComments').blur(function() {
			var inputLength = $(this).val().length;

			if (inputLength == "0") {
				$('#error_customerComments').remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter your comments."
				});
			}
			else if (inputLength > "0") {
				$('#error_customerComments').remove();
				$(this).removeClass("errorFocus");
			}
		});

		//email
		$('input#myEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_email(inputId, inputValue);
		});

		// name - first
		$('input#fn').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your first name.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// name - last
		$('input#ln').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your last name.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// owner
		$('input.currentOwner').click(function() {
			var thisValue = $(this).val();

			if (thisValue == "true") {
				// show the vin field
				$('#vehicleVin label').addClass("required");
				$('#vehicleVin').show();
			}
			else if (thisValue == "false") {
				// remove the vin field
				$('#vehicleVin label').removeClass("required");
				$('#vehicleVin').hide();
			}
		});

		// button interaction
		$('#submit_contactUs').click(function(e) {
			e.preventDefault();
			submit_contactUs();
			return false;
		});

		$('input.cancel').click(function() {
			$('.errorCont, div.errorClear').remove();
			$('input, select, textarea').removeClass("errorFocus");
			$('form#form_contactUs')[ 0 ].reset();
			window.scrollTo(0,0);

		});
	}
} // end instantiate_formContactUs()

function instantiate_formDearSubaru() {
	var init = $('#form_dear_subaru').size();
	if (init != 0) {
		// create state options
		var stateOptions = create_stateOptions(my_profile_home_state);
		$('#owner_homeState').empty().append(stateOptions);

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// Address_Zip
		$('input#owner_zipCode2').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_zipCode(inputId, inputValue);
		});

		// Email
		$('input#myEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_email(inputId, inputValue);
		});

		// Email_Confirm
		$('input#confirmMyEmail').blur(function() {
			var inputId = $(this).attr("id");
			var email1 = $('input#myEmail').val();
			var email2 = $(this).val();
			validate_emailConfirm(inputId, email1, email2);
		});

		// Home_Address
		$('input#owner_homeAddress').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home address";
			validate_presenceOf(inputId, inputValue, message);
		});

		// Home_City
		$('input#owner_homeCity').blur(function(){
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home city";
			validate_presenceOf(inputId, inputValue, message);
		});

		// Home_State
		$('select#owner_homeState').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_presenceOf(inputId, selectOption);
		}).change(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_presenceOf(inputId, selectOption);
		});

		// Name_First
		$('input#fn').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your first name";
			validate_presenceOf(inputId, inputValue, message);
		});

		// Name_Last
		$('input#ln').blur(function(){
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your last name";
			validate_presenceOf(inputId, inputValue, message);
		});

		// Phone_Home
		$("input#owner_homePhone").blur(function() {
			// proceed with validation
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_phoneNumber(inputId, inputValue);
		}).focus(function(){
			$(this).val($(this).val().replace(/[-]/gi,"")).attr('maxlength', '10');
		});

		// Story
		$('textarea#story').blur(function(){
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message;

			var story = new String(document.getElementById('story').value);

			if(story.length <= 750){
				delete_errorMessage(inputId);
				message = "Please enter your story"
				validate_presenceOf(inputId, inputValue, message);
			}else{
				message = "750 characters allowed.";
				$("#error_story, div.errorClear").remove();
				$(this).errorMessage({
					messageTop: "Limit exceeded",
					messageMain: message
				});
			}
		});
	}
}

function instantiate_formForgotEmail() {
	var init = $('#form_forgot_email').size();
	if (init != 0) {
		// Username

		// Password

		// Submit_forgot_email
		$('#submit_forgot_email').click(function(e) {
			e.preventDefault();
			submit_forgotEmail();
			return false;
		});
	}
}

function instantiate_formForgotPassword() {
	var init = $('#form_forgot_password').size();
	if (init != 0) {
		// Email
		$('input#fpw_email').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_email(inputId, inputValue);
		});

		// Submit_forgot_password
		$('#submit_forgot_password').click(function(e) {
			e.preventDefault();
			submit_forgotPassword();
			return false;
		});
	}
}

function instantiate_formGetGtpInfo() {
	var init = $('form#getGtpInfo').size();
	if (init != 0) {

		$('input#vin').focus(function() {
			// clear the input field
			$(this).val("");
		}).blur(function() {
			var inputValue = jQuery.trim($(this).val().toUpperCase());
			if (inputValue.length == 8 || inputValue.length == 17 ) {
				// don't do anything
			}
			else {
				$(this).val("Enter VIN - Last 8 or all 17 characters");
			}
		}).keypress(function(e) {
			if (e.which == 13) {
				e.preventDefault();
				submit_gtpCalculator();
				return false;
			}
		});
	}
} // end instantiate_formGetGtpInfo()

function instantiate_formGtpRedemtion() {
	var init = $('.gtp_redemption_form').size();
	if (init != 0) {
		var stateOptions = create_stateOptions("", "Select a State");
		$('select#owner_homeState').empty().append(stateOptions);

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// address - city
		$('input#owner_homeCity').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter the name of your city.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// address - state
		$('select#owner_homeState').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_presenceOf(inputId, selectOption);
		}).change(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_presenceOf(inputId, selectOption);
		});

		// address - street1
		$('input#owner_homeAddress').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home street address.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// address - zip
		$('input#owner_zipCode2').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_zipCode(inputId, inputValue);
		});

		//email
		$('input#myEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_email(inputId, inputValue);
		});

		// name - first
		$('input#fn').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your first name.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// name - last
		$('input#ln').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your last name.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// Vin
		$('#previousVin, #newVin').focus(function() {
			// clear the input field
			$(this).val("");
		}).blur(function() {
			var inputID = $(this).attr("id");
			var inputValue = jQuery.trim($(this).val().toUpperCase());
			if (inputValue.length == 8 || inputValue.length == 17) {
				$("#error_"+inputID+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
			else {
				$(this).val("Enter VIN - Last 8 or all 17 characters");
				$("#error_"+inputID+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageTop: "The VIN you entered is not valid.",
					messageMain: "Please enter the last 8 or all 17 characters."
				});
			}
		});

		$('#submit_gtp_redemption').click(function(e) {
			e.preventDefault();
			submit_gtpRedemption();
			return false;
		});
	}
} // end instantiate_formGtpRedemtion()

function instantiate_formMySubaruLogin() {
	var init = $('#form_login').size();
	if (init != 0) {
		/*
			In-line validation
			- alphabetical by comment name
		*/
		// Email
		$('#form_login input#myEmailLogin').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = jQuery.trim($(this).val());
			validate_email(inputId, inputValue);
		});

		// Password
		$('#form_login input#myPasswordLogin').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = jQuery.trim($(this).val());
			validate_presenceOf(inputId, inputValue);
		});

		// Submit_Login
		$('#submit_login, #submit_login_button').click(function(e) {
			$('#form_login input#myEmailLogin').blur();
			$('#form_login input#myPasswordLogin').blur();
			e.preventDefault();
			submit_login();
			return false;
		});
	}
}

function instantiate_formPayments() { // form should be refactored to allow for multiple model years
	var init = $('#form_payments').size();
	if (init != 0) {
		// form field interaction
		$('input[name=model]').click(function() {
			// create the trim drop-downs
			var mid = $(this).val();
			var trimOptions = create_modelTrimOptions(mid, "2010");
			$('select[name=chooseTrim]').empty().append(trimOptions).focus();
			$('input[name=purchasePrice]').empty();
		});

		$('select[name=chooseTrim]').change(function() {
			var modelId = $('input[name=model]:checked').val();
			var trimId = $(this).val();
			var msrp = get_msrp("2010", modelId, trimId);
			$('input[name=purchasePrice]').val(msrp);
		});

		$('input[name=purchasePrice], input[name=tradeValue], input[name=cashDown]').keyup(function(e) {
			if ((e.keyCode > 47 && e.keyCode < 58) || (e.keyCode > 95 && e.keyCode < 106) || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 110 || e.keyCode == 188 || e.keyCode == 190  || e.keyCode == 16) {
				var newValue = $(this).val();
				$(this).val(newValue);
			}
			else {
				// reset the value
				var newValue = '';
				$(this).val(newValue);
			}
		});

		$('input[name=apr]').keyup(function(e) {
			if ((e.keyCode > 47 && e.keyCode < 58) || (e.keyCode > 95 && e.keyCode < 106) || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 110 || e.keyCode == 190 || e.keyCode == 16) {
				var newValue = $(this).val();
				$(this).val(newValue);
			}
			else {
				// reset the value
				var newValue = '';
				$(this).val(newValue);
			}
		});

		// button interaction
		$('#calculatePayment').click(function() {
			// set values
			var msrp = $('input[name=purchasePrice]').val().replace(/\.[0-9]*$/, "").replace(",", "");
				msrp = (msrp == '') ? msrp = 0 : parseFloat(msrp);
			var tradeValue = $('input[name=tradeValue]').val().replace(/\.[0-9]*$/, "").replace(",", "");
				tradeValue =  (tradeValue == '')  ? tradeValue = 0 : parseFloat(tradeValue);
			var cashDown = $('input[name=cashDown]').val().replace(/\.[0-9]*$/, "").replace(",", "");
				cashDown = (cashDown == '') ? cashDown = 0 : parseFloat(cashDown);
			var totalDown = tradeValue+cashDown;
			var apr = parseFloat($('input[name=apr]').val()).toFixed(2);
				if (apr.length == 0 || apr == "NaN") {
					apr = 0
					$('input[name=apr]').val(apr);
				};
			var months = parseFloat($('input[name=loanTerm]:checked').val());
			var period = 12;

			if (totalDown > msrp) {
				alert( "The trade in value and down payment exceed the purchase price." );
				return false;
			}
			else {
				var amtLoaned = msrp-tradeValue-cashDown;
				var adjRate = apr / (period * 100);
				var payment = 0;

				if (adjRate == 0) {
					payment = amtLoaned / months;
				}
				else {
					b = Math.pow(1+adjRate, months);
					payment = ((adjRate * (amtLoaned) * b) / (b-1));
				}
				var intPayment = Math.round( payment * 100 );
				var strPayment = ""+( intPayment );
				var finalDollar = strPayment.substr( 0, strPayment.length-2 );
				var finalDecimal = strPayment.substr( strPayment.length-2, 2 );
				if (strPayment == "NaN") {
					finalDollar = "0";
					finalDecimal = "00";
				}
				var output = "$"+finalDollar+"<sup>"+finalDecimal+"</sup>";
				$('p.price').empty().append(output);
			}

			return false;
		});
	}
} // end instantiate_formPayments()

function instantiate_formPopup282() {
	var init = $(".form_popup_282").size();
	if (init != 0) {
		// preload images
		var img = ['a_282_rc_light_grey_top.png', 'a_282_rc_light_grey_bottom.png', 'a_282_light_grey_body.png'];
		$(img).each(function () {
			var i = new Image();
			i.src = pathPrefix+'images/site/' + this;
		});
	}
}

function instantiate_formPopup590() {
	var init = $(".form_popup_590").size();
	if (init != 0) {
		// preload images
		var img = ['a_590_rc_light_grey_top.png', 'a_590_rc_light_grey_bottom.png', 'a_590_light_grey_body.png'];
		$(img).each(function () {
			var i = new Image();
			i.src = pathPrefix+'images/site/' + this;
		});
	}
}

function instantiate_formRedirectedAccountCreation() {
	var init = $('#form_redirected_account_creation').size();
	if (init != 0) {

		var server_error = get_UrlVars()["failedlogin"];
		if(server_error == 'true'){
			$('#form_login .server_error').show();
		}
		else{
			$('#form_login .server_error').hide();
		}
		
		var duplicateemail = get_UrlVars()["duplicateemail"];
		if(duplicateemail == 'true'){
			$('#form_account_registration .server_error').show();
		}
		else{
			$('#form_account_registration .server_error').hide();
		}

		
		var audience = get_UrlVars()["audience"];
		if(audience == '3' && duplicateemail != 'true'){
			$('#form_redirected_account_creation #form_account_registration').hide();
			$('#form_redirected_account_creation #form_account_registration').addClass("hidden");
			$('#form_redirected_account_creation .my_subaru_login').removeClass("hidden");
			$('#form_redirected_account_creation .my_subaru_login').show();
			$('#comm_login').css("display", "none");
			$('#comm_register').css("display", "block");
		}
		else{
			$('.my_subaru_login').hide();
		}
		
		//Input Messages
		var FIRST_NAME = "First Name";
		var LAST_NAME = "Last Name";
		var EMAIL = "Email Address";
		var CONFIRM_EMAIL = "Confirm Email Address";
		var VIN = "VIN (NOT REQUIRED)";
		var VIN_MESSAGE = "VIN (Not Required)"
		var ZIP = "Zip Code";


		$('.showVinInfo').click(function(e) {
			e.preventDefault();

			if ($('p.vinInfo').hasClass("hidden")) {
				$('p.vinInfo').show("blind", {}, 500).removeClass("hidden");
			}
			else{
				$('p.vinInfo').hide("blind", {}, 500).addClass("hidden");
			}
			return false;
		});

		$('.showLogInForm').click(function(e) {
			e.preventDefault();

			if ($('#form_redirected_account_creation .my_subaru_login').hasClass("hidden")) {
				$('#form_redirected_account_creation #form_account_registration').hide("blind", {}, 1000).addClass("hidden");
				$('#form_redirected_account_creation .my_subaru_login').show("blind", {}, 1000).removeClass("hidden");
				$('#comm_login').fadeOut(1000).css("display", "none");
				$('#comm_register').fadeIn(1000).css("display", "block");
			}
			else{
				$('#form_redirected_account_creation #form_account_registration').show("blind", {}, 1000).addClass("hidden");
				$('#form_redirected_account_creation .my_subaru_login').hide("blind", {}, 1000).addClass("hidden");
				$('#comm_login').fadeIn(1000).css("display", "block");
				$('#comm_register').fadeOut(1000).css("display", "none");
			}
			return false;
		});

		$('input#password').css('display', 'none');
		$('input#confirmPassword').css('display', 'none');

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// Address_Zip
		$('input#zipCode2').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();

			if(inputValue === ""){
				$('input#zipCode2').val(ZIP);
			}else{
				validate_zipCode(inputId, inputValue);
			}
		});

		// Email
		$('input#myEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();

			if(inputValue === ""){
				$('input#myEmail').val(EMAIL);
			}else{
				validate_email(inputId, inputValue);
			}
		});

		// Email_Confirm
		$('input#confirmMyEmail').blur(function() {
			var inputId = $(this).attr("id");
			var email1 = $('input#myEmail').val();
			var email2 = $(this).val();

			if(email2 != ""){
				validate_emailConfirm(inputId, email1, email2);
			}else{
				$('input#confirmMyEmail').val(CONFIRM_EMAIL);
			}
		});

		// Name_First
		$('input#fn').blur(function() {
			var inputValue = $('input#fn').val();

			if(inputValue === "" || inputValue === FIRST_NAME){
				$('input#fn').val(FIRST_NAME);
				create_errorMessage($('input#fn').attr("id"), 'Please enter your first name');
			}else{
				delete_errorMessage($(this).attr("id"));
			}
		});

		// Name_Last
		$('input#ln').blur(function(){
			var inputValue = $('input#ln').val();

			if(inputValue === "" || inputValue === LAST_NAME){
				$('input#ln').val(LAST_NAME);
				create_errorMessage($('input#ln').attr("id"), 'Please enter your last name');
			}else{
				delete_errorMessage($(this).attr("id"));
			}
		});

		// Password
		$('input#password').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			if(inputValue === ""){
				$('input#passwordText').css('display', 'inline');
				$('input#password').css('display', 'none')
			}
			validate_password(inputId, inputValue);
		});

		// Password Text Message
		$('input#passwordText').focus(function() {
			$(this).css('display', 'none');
			$('input#password').css('display', 'inline');
			$('input#password').focus();
		});

		// Password_Confirm_Account_Creation
		$('input#confirmPassword').blur(function() {
			var inputId = $(this).attr("id");
			var pw1 = $('input#'+inputId).val();
			var pw2 = $(this).val();
			if($(this).val() === ""){
				$('input#confirmPasswordText').css('display', 'inline');
				$(this).css('display', 'none');
			}
			validate_passwordConfirm(inputId, pw1, pw2);
		});

		// Confirm Password Text Message
		$('input#confirmPasswordText').focus(function() {
			$('input#confirmPasswordText').css('display', 'none');
			$('input#confirmPassword').css('display', 'inline');
			$('input#confirmPassword').focus();
		});

		// Vehicle Identification Number (VIN)
		$('input#vin').blur(function() {
			var vin = jQuery.trim($('input#vin').val().toUpperCase());
			if(vin != "" && vin != VIN){
				var purchaseDate = get_purchaseDate(vin); 
				//If the vin is valid, then purchase date exists. 
				if(purchaseDate === ""){										
					delete_errorMessage($(this).attr("id"));
					
					$(this).errorMessage(
					{
						messageTop: "The VIN you entered is not valid.",
						messageMain: "Please re-enter the last 8 or all 17 characters, or leave this field empty"
					});
					
				}else{
					delete_errorMessage($(this).attr("id"));
					$('input#currentOwner').val("true");
					$('input#purchaseDate').val(purchaseDate);
				}
			}else{
				$('input#vin').val(VIN_MESSAGE);
				delete_errorMessage($(this).attr("id"));
			}
		});

		// Submit_Non_Owner_Account_Creation
		$('#submit_non_owner_account_creation').click(function(e) {
			e.preventDefault();
			// Validates input fields
			validate_zipCode($('input#zipCode2').attr("id"), $('input#zipCode2').val());
			validate_email($('input#myEmail').attr("id"), $('input#myEmail').val());
			validate_emailConfirm($('input#confirmMyEmail').attr("id"), $('input#myEmail').val(), $('input#confirmMyEmail').val());

			if($('input#fn').val() === FIRST_NAME){
				create_errorMessage($('input#fn').attr("id"), 'Please enter your first name');
			}

			if($('input#ln').val() === LAST_NAME){
				create_errorMessage($('input#ln').attr("id"), 'Please enter your last name');
			}

			$('input#vin').blur();

			validate_password($('input#password').attr("id"), $('input#password').val());
			validate_passwordConfirm($('input#confirmPassword').attr("id"), $('input#password').val(), $('input#confirmPassword').val());
			// Submit form
			submit_nonOwnerAccountCreation();
			$('#button_submitShopperAccountCreation').show();
			return false;
		});
	}
}

function instantiate_formReservationSti() {
	var init = $('#form_reservation_sti').size();
	if (init != 0) {
		/*
			In-line validation
			- alphabetical by comment name
		*/

		// address - zip
		$('input#zipCode2').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_zipCode(inputId, inputValue);
		});

		// comments
		$('textarea#customerComments').blur(function() {
			var inputLength = $(this).val().length;

			if (inputLength == "0") {
				$('#error_customerComments').remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter your comments."
				});
			}
			else if (inputLength > "0") {
				$('#error_customerComments').remove();
				$(this).removeClass("errorFocus");
			}
		});

		//email
		$('input#myEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_email(inputId, inputValue);
		});

		// email_Confirm
		$('input#confirmMyEmail').blur(function() {
			var inputId = $(this).attr("id");
			var email1 = $('input#myEmail').val();
			if (inputId == "confirmOwnerEmail") {
				email1 = $('input#ownerEmail').val();
			}
			var email2 = $(this).val();
			validate_emailConfirm(inputId, email1, email2);
		});

		// name - first
		$('input#fn').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your first name.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// name - last
		$('input#ln').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your last name.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// button interaction
		$('#submit_reservation_sti').click(function(e) {
			e.preventDefault();
			submit_reservationSti();
			return false;
		});

		$('input.cancel').click(function() {
			$('.errorCont, div.errorClear').remove();
			$('input, select, textarea').removeClass("errorFocus");
			$('form#form_reservation_sti')[ 0 ].reset();
			window.scrollTo(0,0);

		});

	}
}

function instantiate_formRequestBrochure() { // Why are we using private functions? -jward
	var init = $('#form_requestBrochure').size();
	if (init != 0) {
		var brochureOptions = create_brochuresOptions();
		var stateOptions = create_stateOptions("","- -");
		var yearOptions = create_yearOptions();
		$('select#downloadModel').empty().append(brochureOptions);
		$('select#homeState').empty().append(stateOptions);
		$('select#downloadYear').empty().append(yearOptions);
		$('#download_brochure, .blue_download_icon').addClass("disabledButton");

		function validateDownload(){

			var selectOption1 = $("#downloadYear").val();
			var selectOption2 = $("#downloadModel").val();

			if ((selectOption1 != "noSelection") && (selectOption2 != "noSelection")){
				$('#download_brochure').removeClass("disabledButton");
				$('.blue_download_icon').removeClass("disabledButton");
			}else{
				$('#download_brochure').addClass("disabledButton");
				$('#download_brochure').attr("href", "#");
				$('.blue_download_icon').addClass("disabledButton");
			}
		}

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// address - city
		$('input#homeCity').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter the name of your city.";
			validate_presenceOfCity(inputId, inputValue, message);
		});

		// address - state
		$('select#homeState').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_stateForm(inputId, inputValue);
		}).change(function(){
			var optionSelected = $(this)[0].selectedIndex;
			var stateOptions = create_stateOptions("","- -");
			$('select#homeState').empty().append(stateOptions);
			$(this)[0].options[optionSelected].text = $(this)[0].options[optionSelected].value;
			$(this)[0].options[optionSelected].selected = true;
		});

		// address - street1
		$('input#homeAddress').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home street address.";
			validate_presenceOfAddress(inputId, inputValue, message);
		});

		// address - street2
		$('input#homeAddress2').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home street address.";
			validate_presenceOfAddress2(inputId, inputValue, message);
		});

		// address - zip
		$('input#zipCode2').blur(function(){
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_zipCodeForm(inputId, inputValue);
		});

		// download - brochure
		$('select#downloadModel').change(function(){
			var selectOption = $(this).val();
			if ((selectOption != 'noSelection') && (selectOption.length > 0) ) {
				var year = $('select#downloadYear').val();
				var linkTitle = year+" "+selectOption;
				var imagePath = pathPrefix;
				var linkPath = pathPrefix;
				var brochures = get_brochureInfo();
				$(brochures.responseXML).find("brochure[year="+year+"] model[id="+selectOption+"]").each(function() {
					imagePath +=  $(this).attr("image");
					linkPath += $(this).attr("path");
				});

				if (imagePath.length > 0){
					if (year == 2010){
					var image = "<img src='"+imagePath+"' alt='"+selectOption+"' />";
					$('#imageBrochure').empty().append(image);
					}
					$('a#download_brochure').attr("href", linkPath).attr("title", linkTitle);
				}
				else {
					$('#imageBrochure').empty();
					$('a#download_brochure').attr("href", "#").attr("title", "");
				}
			}
			else {
				$('#imageBrochure').empty();
				$('a#download_brochure').attr("href", "#").attr("title", "");
			}
			validateDownload();
		});


		// download - year
		$('select#downloadYear').change(function() {
			$('a#download_brochure').attr("href", "#").attr("title", "");
			var selectOption = $('select#downloadYear').val();
			if (selectOption != 'noSelection' || selectOption.length > 0) {
				var brochureOptions = create_brochuresOptions(selectOption);
				$('#imageBrochure').empty();
				$('select#downloadModel').empty().append(brochureOptions);
				validateDownload();
			}
		});

		//email
		$('input#myEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_email(inputId, inputValue);
		});

		// email_Confirm
		$('input#confirmEmail').blur(function() {
			var inputId = $(this).attr("id");
			var email1 = $('input#myEmail').val();
			var email2 = $(this).val();
			validate_emailConfirm(inputId, email1, email2);
		});

		// name - first
		$('input#fn').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your first name.";
			validate_presenceOfName(inputId, inputValue, message);
		});

		// name - last
		$('input#ln').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your last name.";
			validate_presenceOfName(inputId, inputValue, message);
		});

		// phone
		$("input#homePhone").blur(function() {
			// proceed with validation
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_phoneNumber(inputId, inputValue);
		}).focus(function(){
			$(this).val($(this).val().replace(/[-]/gi,"")).attr('maxlength', '10');
		}).bind('keypress', function(e) {
			return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
		});

		// button interaction
		$('#submit_brochure').livequery('click', function(e) {
			e.preventDefault();
			submit_getBrochure();
			return false;
		});

		$('input.cancel').click(function() {
			$('.errorCont, div.errorClear').remove();
			$('input, select, textarea').removeClass("errorFocus");
			$('form#form_requestBrochure')[ 0 ].reset();
			window.scrollTo(0,0);

		});

		$("input[type='checkbox'][name='brochureType']").click(function() {
			selectedBrochuresCount($(this)[0]);
		});

		$('#download_brochure').click(function(){
			window.location.replace($(this).attr('href'));
		});

		//Helper functions
		function selectedBrochuresCount(checkbox){
			var checkboxes = document.getElementsByName("brochureType");
			var checkedCount = 0;

			$(checkboxes).each(function(){
				if(this.checked == true){
					checkedCount++;
				}
			});

			if(checkedCount >= 3){
				if(!document.getElementById("error_checkboxBrochures")){
					addWarningAmountBrochures();
				}

				if(checkbox.checked == true){
					checkedCount--;
				}
			}else{
				$("#error_checkboxBrochures, div.errorClear").remove();
				$("#checkboxBrochures").removeClass("errorFocus");
			}
		}

		function addWarningAmountBrochures(){
			var inputId = "checkboxBrochures";

			var defaults = {
				containerId: inputId,
				messageTop: "Limit exceeded",
				messageMain: "You can select up to two brochures at a time.",
				formElement: "true"
			};
			var options = jQuery.extend(defaults, options);

			var output = "<div class='errorClear' />";
			output += "<div id='error_checkboxBrochures' class='errorCont'>";
			output += "<span class='top'></span>";
			output += "<p class='bold'>"+options.messageTop+"</p>";
			output += "<p>"+options.messageMain+"</p>";
			output += "</div>";
			output += "<div class='errorClear' />";

			//apend the output AFTER the form element
			$("#"+options.containerId).append(output);
		}
	}
} // end instantiate_formRequestBrochure()

function instantiate_formViewBrochure() {
	var init = $('#form_viewBrochure').size();
	if (init != 0) {
		var brochureViewOptions = create_viewBrochureOptions();
		$('select#viewModel').empty().append(brochureViewOptions);
		$('select#viewModel').change(function(){
			if($(this).val() != 'noSelection'){
				$('#view_brochure').removeClass('disabledButton');
			}
			else{
				if(! $('#view_brochure').hasClass('disabledButton')){
					$('#view_brochure').addClass('disabledButton');
				}
			}
		});
		$('#view_brochure').click(function(){
			var viewSelection = $('select#viewModel').val();
			if(viewSelection != 'noSelection'){
				window.open(viewSelection);
				return false;
			}
		});
	}
} // end instantiate_formViewBrochure()

function addErrorBrochures(topmsg,msg){ // REFACTOR to adhere to coding conventions -jward
	var inputId = "checkboxBrochures";

	var defaults = {
		containerId: inputId,
		messageTop: topmsg,
		messageMain: msg,
		formElement: "true"
	};
	var options = jQuery.extend(defaults, options);

	$("#error_checkboxBrochures, div.errorClear").remove();

	var output = "<div class='errorClear' />";
	output += "<div id='error_checkboxBrochures' class='errorCont'>";
	output += "<span class='top'></span>";
	output += "<p class='bold'>"+options.messageTop+"</p>";
	output += "<p>"+options.messageMain+"</p>";
	output += "</div>";
	output += "<div class='errorClear' />";

	//append the output AFTER the form element
	$("#"+options.containerId).append(output);
}

function instantiate_formRequestQuote() {
	var init = $('#form_requestQuote').size();
	if (init != 0) {
		// determine if this is a "pre-selected" quote request
		if (buildModel.length > 0) {
			// create year options set the pre-selected year option
			var yearOptions = create_modelYearOptions(buildYear, 1);
			//$('select#chooseYear').empty().append(buildYearOptions);

			// create pre-selected model options
			var buildModelOptions = create_modelOptions(buildYear, buildModel);
			$('select#chooseModel').empty().append(buildModelOptions);

			// create pre-selected trim options
			if (buildModel == "Impreza WRX" && (buildTrim == "STI" || buildTrim == "Premium" || buildTrim == "Limited")) {
				buildTrim = "WRX " + buildTrim;
			}

			if (buildModel == "Impreza WRX" || buildModel == "Impreza" && (buildTrim == "WRX" || buildTrim == "2.5GT" || buildTrim == "2.5i Premium"|| buildTrim == "2.5i")) {
				buildTrim = buildTrim + " 4-door";
			}

			var buildTrimOptions = create_modelTrimOptions(buildModel, buildYear, buildTrim);
			$('select#chooseTrim').empty().append(buildTrimOptions);

			// get the model info
			var buildModels = get_modelInfo(buildYear);

			// set the variables
			var mn = (buildModel.toLowerCase() == "impreza" || buildModel.toLowerCase() == "impreza wrx") ? "Impreza" : buildModel;
			var vTitle = buildModel + " " + buildTrim;
			var imagePath = pathPrefix+"images/";
			var imageDirectory = "";
			var trimImageDir = "";
			var image_b = "";
			var msrp = "";

			$(buildModels.responseXML).find("model[modelName="+mn+"]").each(function() {
				imageDirectory = $(this).attr("imageDirectory");
				$(this).find("trim[trimName="+buildTrim+"]").each(function() {
					trimImageDir = $(this).attr("trimImageDir")
					image_b = $(this).attr("trimImageB");
					msrp = $(this).attr("msrp");
				});
			});
			imagePath += imageDirectory+"/"+trimImageDir+"/"+image_b;
			var image = "<img src='" + imagePath + "' alt='" + vTitle + "' />";
			var newMSRP = "MSRP* Starting At: $" + msrp;

			// build the window sticker
			var output = "\n" + image;
				output += "\n<dl>";
				output += "\n\t<dt class='year'>"+buildYear+"</dt>";
				output += "\n\t<dt class='vTitle'>"+buildModel+"</dt>";
				output += "\n\t<dt class='msrp'>"+buildTrim+"</dt>";
				output += "\n\t\t<dd></dd>";
				output += "\n</dl>";
				output += "\n<div class='clear'></div>";

			$('#modelCont').empty().append(output).show("slow");
		}
		else {
			var yearOptions = create_modelYearOptions("", 1);
		}
		var stateOptions = create_stateOptions("", "- -");
		var distanceOptions = create_distanceOptions();
		$('select#selectRadius').append(distanceOptions);
		$('select#homeState').empty().append(stateOptions);
		$('select#chooseYear').append(yearOptions);

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// address - city
		$('input#homeCity').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter the name of your city.";
			validate_presenceOfCity(inputId, inputValue, message);
		});

		// address - state
		$('select#homeState').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_stateForm(inputId, inputValue);
		}).change(function(){
			var optionSelected = $(this)[0].selectedIndex;
			var stateOptions = create_stateOptions("","- -");
			$('select#homeState').empty().append(stateOptions);
			$(this)[0].options[optionSelected].text = $(this)[0].options[optionSelected].value;
			$(this)[0].options[optionSelected].selected = true;
		});

		// address - street
		$('input#homeAddress').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home street address.";
			validate_presenceOfAddress(inputId, inputValue, message);
		});

		// address - street
		$('input#homeAddress2').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home street address.";
			validate_presenceOfAddress2(inputId, inputValue, message);
		});

		// address - zip
		$('input#zipCode1').blur(function(){
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_zipCodeForm(inputId, inputValue);
		});

		// dealer inputs
		$('input[name=dealer]').livequery('click', function() {
			if ($(this).next().hasClass("dealerInformation") == false) {

				var dealer = $(this).attr("title").split("~");
				var dealerInfo = "\n<p class=\"dealerName\">" + dealer[0] + "<span class=\"distance\"> (" + dealer[6] + " Miles)</span></p>";
				dealerInfo += "\n<p class=\"dealerAddress\">" + dealer[1] + "</p>";
				dealerInfo += "\n<p class=\"dealerAddress\">" + dealer[2] + ", " + dealer[3] + " " + dealer[4] + "</p>";
				dealerInfo += "\n<p class=\"dealerAddress\">" + dealer[5] + "</p>";
				$('#dynamicDealerList li p').show();
				$(this).next().hide();
				$('#dealerInfo').insertAfter(this);
				$('#dealerInfo').empty().append(dealerInfo);

			}
		});


		// distance radius
		$('select#selectRadius').change(function() {
			// remove the error container if it exists
			$("#error_dynamicDealerList, div.errorClear").remove();

			var zip = $('input#zipCode1').val();
			var searchRadius = parseFloat($(this).val());

			create_dealerRadioGroup(zip, searchRadius);

		});


		// email
		$('input#myEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_email(inputId, inputValue);
		});

		// email_Confirm
		$('input#confirmMyEmail').blur(function() {
			var inputId = $(this).attr("id");
			var email1 = $('input#myEmail').val();
			if (inputId == "confirmOwnerEmail") {
				email1 = $('input#ownerEmail').val();
			}
			var email2 = $(this).val();
			validate_emailConfirm(inputId, email1, email2);
		});

		// model name
		$('select#chooseModel').blur(function() {
			var modelYear = $('select#chooseYear').val();
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_model(inputId, selectOption, modelYear);
		}).change(function() {
			var modelYear = $('select#chooseYear').val();
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_model(inputId, selectOption, modelYear);
			$('#modelCont').empty();
		});

		// model trim
		$('select#chooseTrim').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelTrim(inputId, selectOption);
		}).change(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var isValid = validate_modelTrim(inputId, selectOption);

			if (isValid == "yes") {
				// populate the "window sticker"
				var modelYear = $('select#chooseYear').val();
				var modelId = $('select#chooseModel').val();
				var trimId = selectOption;
				var trimValue = $('select#chooseTrim option:selected').text();

				// get the model info
				var models = get_modelInfo(modelYear);

				// set the variables
				var mn = (modelId.toLowerCase() == "impreza" || modelId.toLowerCase() == "impreza wrx") ? "Impreza" : modelId;
				var tn = trimId;
				if (mn == tn || tn == "WRX") {
					tn = " ";
				}
				var vTitle = mn + " " + tn;
				var imagePath = pathPrefix+"images/";
				var imageDirectory = "";
				var trimImageDir = "";
				var image_b = "";
				var msrp = "";

				$(models.responseXML).find("model[modelName="+mn+"]").each(function() {
					imageDirectory = $(this).attr("imageDirectory");
					$(this).find("trim[trimName="+trimValue+"]").each(function() {
						trimImageDir = $(this).attr("trimImageDir")
						image_b = $(this).attr("trimImageB");
						msrp = $(this).attr("msrp");
					});
				});
				imagePath += imageDirectory+"/"+trimImageDir+"/"+image_b;
				var image = "<img src='" + imagePath + "' alt='" + vTitle + "' />";
				var newMSRP = "MSRP* Starting At: $" + msrp;

				// build the window sticker
				var output = "\n" + image;
					output += "\n<dl>";
					output += "\n\t<dt class='year'>"+modelYear+"</dt>";
					output += "\n\t<dt class='vTitle'>"+mn+"</dt>";
					output += "\n\t<dt class='msrp'>"+tn+"</dt>";
					output += "\n\t\t<dd></dd>";
					output += "\n</dl>";
					output += "\n<div class='clear'></div>";

				$('#modelCont').empty().append(output).show("slow");

				$("#error_chooseTrim, div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		// model year
		$('select#chooseYear').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelYear(inputId, selectOption);
		}).change(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelYear(inputId, selectOption);
			$('#modelCont').empty();
		});

		// name - first
		$('input#fn').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your first name.";
			validate_presenceOfName(inputId, inputValue, message);
		});

		// name - last
		$('input#ln').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your last name.";
			validate_presenceOfName(inputId, inputValue, message);
		});

		// phone
		$("input#contactPhone, input#contactPhone2").blur(function() {
			// proceed with validation
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_phoneNumber(inputId, inputValue);
		}).focus(function(){
			$(this).val($(this).val().replace(/[-]/gi,"")).attr('maxlength', '10');
		}).bind('keypress', function(e) {
			return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
		});

		// button interaction
		$('#submit_requestQuote').livequery('click', function() {
			submit_requestQuote();
			return false;
		});

		$('input.cancel').click(function() {
			$('.errorCont, div.errorClear').remove();
			$('input, select, textarea').removeClass("errorFocus");
			$('form#form_requestQuote')[ 0 ].reset();
			$('#modelCont, #dynamicDealerList, #dealerInfo').empty();
		});
	}
} // end instantiate_formRequestQuote()

function instantiate_formScheduleTestDrive() {
	var init = $('#form_scheduleTestDrive').size();
	if (init != 0) {
		// determine if this is a "pre-selected" quote request
		if (buildModel.length > 0) {
			// create year options set the pre-selected year option
			var yearOptions = create_modelYearOptions(buildYear, 1);
			//$('select#chooseYear').empty().append(buildYearOptions);

			// create pre-selected model options
			var buildModelOptions = create_modelOptions(buildYear, buildModel);
			$('select#chooseModel').empty().append(buildModelOptions);

			// create pre-selected trim options
			if (buildModel == "Impreza WRX" && (buildTrim == "STI" || buildTrim == "Premium")) {
				buildTrim = "WRX " + buildTrim;
			}
			var buildTrimOptions = create_modelTrimOptions(buildModel, buildYear, buildTrim);
			$('select#chooseTrim').empty().append(buildTrimOptions);

			// get the model info
			var buildModels = get_modelInfo(buildYear);

			// set the variables
			var mn = (buildModel.toLowerCase() == "impreza" || buildModel.toLowerCase() == "impreza wrx") ? "Impreza" : buildModel;
			var vTitle = buildModel + " " + buildTrim;
			var imagePath = pathPrefix+"images/";
			var imageDirectory = "";
			var trimImageDir = "";
			var image_b = "";
			var msrp = "";

			$(buildModels.responseXML).find("model[modelName="+mn+"]").each(function() {
				imageDirectory = $(this).attr("imageDirectory");
				$(this).find("trim[trimName="+buildTrim+"]").each(function() {
					trimImageDir = $(this).attr("trimImageDir")
					image_b = $(this).attr("trimImageB");
					msrp = $(this).attr("msrp");
				});
			});
			imagePath += imageDirectory+"/"+trimImageDir+"/"+image_b;
			var image = "<img src='" + imagePath + "' alt='" + vTitle + "' />";
			var newMSRP = "MSRP* Starting At: $" + msrp;

			// build the window sticker
			var output = "\n" + image;
				output += "\n<dl>";
				output += "\n\t<dt class='year'>"+buildYear+"</dt>";
				output += "\n\t<dt class='vTitle'>"+buildModel+"</dt>";
				output += "\n\t<dt class='msrp'>"+buildTrim+"</dt>";
				output += "\n\t\t<dd></dd>";
				output += "\n</dl>";
				output += "\n<div class='clear'></div>";

			$('#modelCont').empty().append(output).show("slow");
		}
		else {
			var yearOptions = create_modelYearOptions("", 1);
		}
		var stateOptions = create_stateOptions("", "- -");
		var distanceOptions = create_distanceOptions();
		$('select#selectRadius').append(distanceOptions);
		$('select#homeState').empty().append(stateOptions);
		$('select#chooseYear').append(yearOptions);

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// address - city
		$('input#homeCity').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter the name of your city.";
			validate_presenceOfCity(inputId, inputValue, message);
		});

		// address - state
		$('select#homeState').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_stateForm(inputId, inputValue);
		}).change(function(){
			var optionSelected = $(this)[0].selectedIndex;
			var stateOptions = create_stateOptions("","- -");
			$('select#homeState').empty().append(stateOptions);
			$(this)[0].options[optionSelected].text = $(this)[0].options[optionSelected].value;
			$(this)[0].options[optionSelected].selected = true;
		});

		// address - street
		$('input#homeAddress').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home street address.";
			validate_presenceOfAddress(inputId, inputValue, message);
		});

		// address - street
		$('input#homeAddress2').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home street address.";
			validate_presenceOfAddress2(inputId, inputValue, message);
		});

		// address - zip
		$('input#zipCode1').blur(function(){
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_zipCodeForm(inputId, inputValue);
		});

		// dealer inputs
		$('input[name=dealer]').livequery('click', function() {
			if ($(this).next().hasClass("dealerInformation") == false) {

				var dealer = $(this).attr("title").split("~");
				var dealerInfo = "\n<p class=\"dealerName\">" + dealer[0] + "<span class=\"distance\"> (" + dealer[6] + " Miles)</span></p>";
				dealerInfo += "\n<p class=\"dealerAddress\">" + dealer[1] + "</p>";
				dealerInfo += "\n<p class=\"dealerAddress\">" + dealer[2] + ", " + dealer[3] + " " + dealer[4] + "</p>";
				dealerInfo += "\n<p class=\"dealerAddress\">" + dealer[5] + "</p>";
				$('#dynamicDealerList li p').show();
				$(this).next().hide();
				$('#dealerInfo').insertAfter(this);
				$('#dealerInfo').empty().append(dealerInfo);

			}
		});


		// distance radius
		$('select#selectRadius').change(function() {
			// remove the error container if it exists
			$("#error_dynamicDealerList, div.errorClear").remove();

			var zip = $('input#zipCode1').val();
			var searchRadius = parseFloat($(this).val());

			var dealerListHtml = create_dealerRadioGroup(zip, searchRadius);

			// append the dealer list
			//$('#dynamicDealerList').empty().append(dealerListHtml);
			//$(".dealerGroup").show();
		});

		// email
		$('input#myEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_email(inputId, inputValue);
		});

		// email_Confirm
		$('input#confirmMyEmail').blur(function() {
			var inputId = $(this).attr("id");
			var email1 = $('input#myEmail').val();
			if (inputId == "confirmOwnerEmail") {
				email1 = $('input#ownerEmail').val();
			}
			var email2 = $(this).val();
			validate_emailConfirm(inputId, email1, email2);
		});

		// model name
		$('select#chooseModel').blur(function() {
			var modelYear = $('select#chooseYear').val();
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_model(inputId, selectOption, modelYear);
		}).change(function() {
			var modelYear = $('select#chooseYear').val();
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_model(inputId, selectOption, modelYear);
			$('#modelCont').empty();
		});

		// model trim
		$('select#chooseTrim').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelTrim(inputId, selectOption);
		}).change(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var isValid = validate_modelTrim(inputId, selectOption);

			if (isValid == "yes") {
				// populate the "window sticker"
				var modelYear = $('select#chooseYear').val();
				var modelId = $('select#chooseModel').val();
				var trimId = selectOption;
				var trimValue = $('select#chooseTrim option:selected').text();

				// get the model info
				var models = get_modelInfo(modelYear);

				// set the variables
				var mn = (modelId.toLowerCase() == "impreza" || modelId.toLowerCase() == "impreza wrx") ? "Impreza" : modelId;
				var tn = trimId;
				if (mn == tn || tn == "WRX") {
					tn = " ";
				}
				var vTitle = mn + " " + tn;
				var imagePath = pathPrefix+"images/";
				var imageDirectory = "";
				var trimImageDir = "";
				var image_b = "";
				var msrp = "";

				$(models.responseXML).find("model[modelName="+mn+"]").each(function() {
					imageDirectory = $(this).attr("imageDirectory");
					$(this).find("trim[trimName="+trimValue+"]").each(function() {
						trimImageDir = $(this).attr("trimImageDir")
						image_b = $(this).attr("trimImageB");
						msrp = $(this).attr("msrp");
					});
				});
				imagePath += imageDirectory+"/"+trimImageDir+"/"+image_b;
				var image = "<img src='" + imagePath + "' alt='" + vTitle + "' />";
				var newMSRP = "MSRP* Starting At: $" + msrp;

				// build the window sticker
				var output = "\n" + image;
					output += "\n<dl>";
					output += "\n\t<dt class='year'>"+modelYear+"</dt>";
					output += "\n\t<dt class='vTitle'>"+mn+"</dt>";
					output += "\n\t<dt class='msrp'>"+tn+"</dt>";
					output += "\n\t\t<dd></dd>";
					output += "\n</dl>";
					output += "\n<div class='clear'></div>";

				$('#modelCont').empty().append(output).show("slow");

				$("#error_chooseTrim, div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		// model year
		$('select#chooseYear').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelYear(inputId, selectOption);
		}).change(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelYear(inputId, selectOption);
			$('#modelCont').empty();
		});

		// name - first
		$('input#fn').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your first name.";
			validate_presenceOfName(inputId, inputValue, message);
		});

		// name - last
		$('input#ln').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your last name.";
			validate_presenceOfName(inputId, inputValue, message);
		});

		// phone
		$("input#contactPhone, input#contactPhone2").blur(function() {
			// proceed with validation
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_phoneNumber(inputId, inputValue);
		}).focus(function(){
			$(this).val($(this).val().replace(/[-]/gi,"")).attr('maxlength', '10');
		}).bind('keypress', function(e) {
			return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
		});

		// button interaction
		$('#submit_scheduleTestDrive').livequery('click', function() {
			submit_scheduleTestDrive();
			return false;
		});

		$('input.cancel').click(function() {
			$('.errorCont, div.errorClear').remove();
			$('input, select, textarea').removeClass("errorFocus");
			$('form#form_scheduleTestDrive')[ 0 ].reset();
			$('#modelCont, #dynamicDealerList, #dealerInfo').empty();
		});
	}
} // end instantiate_formScheduleTestDrive()

function instantiate_formSignUpForUpdates() {
	var init = $('#form_infoSignUp').size();
	if (init != 0) {
		/*
			In-line validation
			- alphabetical by comment name
		*/

		// address - zip
		$('input#zipCode1').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_zipCode(inputId, inputValue);
		});

		//email
		$('input#myEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_email(inputId, inputValue);
		});

		// email_Confirm
		$('input#confirmMyEmail').blur(function() {
			var inputId = $(this).attr("id");
			var email1 = $('input#myEmail').val();
			if (inputId == "confirmOwnerEmail") {
				email1 = $('input#ownerEmail').val();
			}
			var email2 = $(this).val();
			validate_emailConfirm(inputId, email1, email2);
		});

		// group - current owners
		$('#currentOwner_Group').bind("mouseleave", function() {
			// verify that at least one checkbox or radio button was checked
			var isChecked = 0; // assume nothing is checked
			$('#currentOwner_Group ul.radio').find('input[type=radio]:checked').each(function() {
				isChecked = 1;
			});

			if (isChecked == 0) {
				// trigger an error
				$("#error_currentOwner_Group, div.errorClear").remove();
				$('#currentOwner_Group').errorMessage({
					messageTop: "You must check at least one",
					messageMain: "Please make a selection and resubmit"
				});
			}
			else if (isChecked == 1) {
				$('#error_currentOwner_Group, div.errorClear').remove();
				$('#currentOwner_Group').removeClass("errorFocus");
			}
		});

		// group - models
		$('#modelInterest_Group').bind("mouseleave", function() {
			// verify that at least one checkbox or radio button was checked
			var isChecked = 0; // assume nothing is checked
			$('#modelInterest_Group ul.radio').find('input[type=checkbox]:checked').each(function() {
				isChecked = 1;
			});

			if (isChecked == 0) {
				// trigger an error
				$("#error_modelInterest_Group, div.errorClear").remove();
				$('#modelInterest_Group').errorMessage({
					messageTop: "You must check at least one",
					messageMain: "Please make a selection and resubmit"
				});
			}
			else if (isChecked == 1) {
				$('#error_modelInterest_Group, div.errorClear').remove();
				$('#modelInterest_Group').removeClass("errorFocus");
			}
		});

		// group - purchase time frame
		$('#purchaseTime_Group').bind("mouseleave", function() {
			// verify that at least one checkbox or radio button was checked
			var isChecked = 0; // assume nothing is checked
			$('#purchaseTime_Group ul.radio').find('input[type=radio]:checked').each(function() {
				isChecked = 1;
			});

			if (isChecked == 0) {
				// trigger an error
				$("#error_purchaseTime_Group, div.errorClear").remove();
				$('#purchaseTime_Group').errorMessage({
					messageTop: "You must check at least one",
					messageMain: "Please make a selection and resubmit"
				});
			}
			else if (isChecked == 1) {
				$('#error_purchaseTime_Group, div.errorClear').remove();
				$('#purchaseTime_Group').removeClass("errorFocus");
			}
		});

		// name - first
		$('input#fn').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your first name.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// name - last
		$('input#ln').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your last name.";
			validate_presenceOf(inputId, inputValue, message);
		});

		// button interaction
		$('#submit_infoSignUp').livequery('click', function(e) {
			e.preventDefault();
			submit_signUpForUpdates();
			return false;
		});

		$('input.cancel').click(function() {
			$('.errorCont, div.errorClear').remove();
			$('input, select, textarea').removeClass("errorFocus");
			$('form#form_infoSignUp')[ 0 ].reset();
			window.scrollTo(0,0);
		});
	}
} // end instantiate_formSignUpForUpdates()

function instantiate_formSuggestLink() {
	var formExists = $('#form_suggest_link').size();
	if (formExists != 0 && ownerShopperLinks == 1) {
		// show the link
		$('span#suggest_owner_link').show();
	}
}

function instantiate_formUpdateContactInfo() {
	var init = $("#form_my_profile_update_contact").size();
	if (init != 0) {
		// create state options
		var stateOptions = create_stateOptions(my_profile_home_state);
		$('#owner_homeState').empty().append(stateOptions);

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// Address_Zip
		$('input#zipCode2, input#owner_zipCode2').blur(function() {
			$(this).val(jQuery.trim($(this).val()));
			//$(this).val($(this).val().trim());
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_zipCode(inputId, inputValue);
		});

		// Name_First
		$('input#fn, input#owner_fn').blur(function() {
			$(this).val(jQuery.trim($(this).val()));
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your first name";
			validate_presenceOf(inputId, inputValue, message);
		});

		// Name_Last
		$('input#ln, input#owner_ln').blur(function(){
			$(this).val(jQuery.trim($(this).val()));
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your last name";
			validate_presenceOf(inputId, inputValue, message);
		});

		$('input#homeAddress2, input#owner_homeAddress, input#owner_homeCity' ).blur(function(){
			$(this).val(jQuery.trim($(this).val()));
		});

		// Phone_Home
		$("input#owner_homePhone, input#owner_workPhone").blur(function() {
			// proceed with validation
			$(this).val(jQuery.trim($(this).val()));
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_phoneNumber(inputId, inputValue);
		}).focus(function(){
			$(this).val($(this).val().replace(/[-]/gi,"")).attr('maxlength', '10');
		});

		// Submit_My_Profile_Update_Contact
		$('#submit_my_profile_update_contact').click(function(e) {
			e.preventDefault();
			update_contactInfo("form_my_profile_update_contact");
			return false;
		});

	}
}

function instantiate_formUpdateLogin() {
	var init = $("#form_my_profile_update_login").size();
	if (init != 0) {
		// Email
		$('input#ownerEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			if (inputValue.length > 0) {
				validate_email(inputId, inputValue);
			}
		});

		// Password
		$('input#ownerNewPassword').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			if (inputValue.length > 0) {
				validate_password(inputId, inputValue);
			}
		});

		// Password_Confirm
		$('input#confirmOwnerPassword').blur(function() {
			var inputId = $(this).attr("id");
			var pw1 = $('input#'+inputId).val();
			var pw2 = $(this).val();
			validate_passwordConfirm(inputId, pw1, pw2);
		});

		// Submit_My_Profile_Update_Login
		$('#submit_my_profile_update_login').click(function(e) {
			e.preventDefault();
			update_login();
			return false;
		});
	}
}

function instantiate_formFindDealerChinese(){

	$("#findDealer_chinese").bind("keypress", function(e) {
    	if (e.keyCode == 13) {
			showLeavingSiteWindow();
    		return false;
        }
     });
	 $("#findDealer_chinese input#dealerZip2").focus(function() {
 	 	if (this.value == this.defaultValue){
       		this.value = '';
        }
     }).blur(function() {
	 	if (this.value == ''){
			this.value = this.defaultValue;
		}
	 });


}


function instantiate_formUpdateVehicle() {
	var init = $("#form_my_profile_update_vehicle").size();
	if (init != 0) {
		var vinValue = $('input#vin').val();

		if (vinValue.length == 0) {
			// enable the date picker
			$("#edit_purchaseDate").datepicker({
				showOn: 'button',
				buttonImage: '/content/images/site/icons/calendar.gif',
				buttonImageOnly: true,
				changeYear: true,
				minDate: minDate,
				maxDate: maxDate
			});

		$("#edit_purchaseDate").addClass("maskedDate");

		}

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// Date
		$('input#edit_purchaseDate').change(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			var isDate = validate_date(inputValue, $(this));

			if (isDate != "true") {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: isDate
				});
			}
			else if (isDate == "true") {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});
		$('input#edit_purchaseDate').blur(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			if (inputValue.length > 0) {
				var isDate = validate_date(inputValue, $(this));

				if (isDate != "true") {
					$("#error_"+inputId+", div.errorClear").remove();
					$(this).errorMessage(
					{
						messageMain: isDate
					});
				}
				else if (isDate == "true") {
					$("#error_"+inputId+", div.errorClear").remove();
					$(this).removeClass("errorFocus");
				}
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter a valid date (mm/dd/yyyy)."
				});
			}
		});

		// Mileage
		$('input#originalMileage').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_mileage(inputId, inputValue);
		});

		// Model
		$('select#chooseModel').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var year = $("select#chooseYear").val();
			var validModel = validate_model(inputId, selectOption, year, "none");
				vinValue = $('input#vin').val();
			if (validModel == "yes" && vinValue.length == 0) {
				var trimOptions = create_modelTrimOptions(selectOption, year);
				$('select#chooseTrim').empty().append(trimOptions);
			}

		}).change(function(){
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var year = $("select#chooseYear").val();
			var validModel = validate_model(inputId, selectOption, year, "none");
				vinValue = $('input#vin').val();
			if (validModel == "yes" && vinValue.length == 0) {
				var trimOptions = create_modelTrimOptions(selectOption, year);
				$('select#chooseTrim').empty().append(trimOptions);
			}
		});

		// Model_Trim
		$('select#chooseTrim').blur(function()	{
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelTrim(inputId, selectOption);

		}).change(function(){
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			validate_modelTrim(inputId, selectOption);
		});

		// Model_Year
		$('select#chooseYear').blur(function() {
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var validYear = validate_modelYear(inputId, selectOption, "none");
				vinValue = $('input#vin').val();
			if (validYear == "yes" && vinValue.length == 0) {
				var modelOptions = create_modelOptions(selectOption);
				$('select#chooseModel').empty().append(modelOptions);
			}
		}).change(function(){
			var inputId = $(this).attr("id");
			var selectOption = $(this).val();
			var validYear = validate_modelYear(inputId, selectOption, "none");
				vinValue = $('input#vin').val();
			if (validYear == "yes" && vinValue.length == 0) {
				var modelOptions = create_modelOptions(selectOption);
				$('select#chooseModel').empty().append(modelOptions);
			}
		});

		// Vehicle Name
		$('input#name').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			validate_vehicleName(inputId, inputValue);
		});

		// Vehicle Identification Number (VIN)
		$('input#vin').blur(function() {
			var vin = jQuery.trim($(this).val().toUpperCase());
			var validVin = validate_vin(vin);

			if (validVin) {
				// mark fields as read-only
				$("select#chooseYear, select#chooseModel, select#chooseTrim").attr("readonly", "readonly");
			}
			else {
				// mark fields as read-only
				$("select#chooseYear, select#chooseModel, select#chooseTrim").attr("readonly", "readonly");
			}
		});

		// Submit_My_Profile_Update_Vehicle
		$('#submit_my_profile_update_vehicle').click(function(e) {
			e.preventDefault();
			update_vehicleInfo();
			return false;
		});
	}
}

function instantiate_mySubaruDealerPage() {
	var my_dealer = $('.my_dealer').size();
	if (my_dealer != 0){
		update_currentlyViewedVehicle(type, vid);
	}
}

function instantiate_mySubaruGtp() {
	var init = $(".gtp_Success").size();
	if (init != 0) {
		var gtpInfoXml = get_myGtpInfo(gtp_vehicle_id, "vehicleId");
		$(gtpInfoXml.responseXML).find("priceInfo").each(function() {
			var status = $(this).find("status").text();
			if(status==0){
				var gtpValue = $(this).find("value").text();
				var gtpValueHTML = format_currency(gtpValue);
				var gtpEndDate = $(this).find("endDate").text();
				var gtpMileage = format_commas($(this).find("mileage").text());
				//var gtpEndDateHTML = '&ndash; Guaranteed Until ' + gtpEndDate + '* <a href="'+ linkPrefix +'finance-center/guaranteed-trade-in-program/rules-eligibility.html">See Applicable Restrictions</a>';
				var gtpEndDateHTML = '&ndash; Estimate only* <a href="'+ linkPrefix +'finance-center/guaranteed-trade-in-program/rules-eligibility.html">See Applicable Restrictions</a>';
				$("div.trade_in_value span.gtpMileage").append(gtpMileage);
				$("div.trade_in_value span.trade_in_value").append(gtpValueHTML);
				$("div.trade_in_value span.guaranteedUntil").append(gtpEndDateHTML);

				$("#gtpSuccess").show();
			} else if(status == 1){
				$("#gtpError1").show();
			} else if(status == 2){
				$("#gtpError2").show();
			} else if(status == 3){
				$("#gtpError3").show();
			}
		});
	}
}

function instantiate_mySubaruIndexPage() {
	var mySubaruIndexTertNav = $('#mySubaruIndexTertNav').size();
	if (mySubaruIndexTertNav != 0){
		var form_add_vehicle = $(".form_add_vehicle").size();
		if (form_add_vehicle != 0){
			type = "owned";
		}
		if (overrideType != ""){
			type = overrideType;
		}

		//load up owned LIs into the my-vehicles tab (this does not make it accordion)
		var echo_owned = create_tertiaryTabsAccordionOwned(vehicles_owned, dealerCode, tertiaryId, sel_veh, dealerURL);
		$("#my-vehicles-tab .accordion").prepend(echo_owned);

		//load up owned LIs into the my-next tab (this does not make it accordion)
		var echo_garaged = create_tertiaryTabsAccordionGaraged(vehicles_garaged, dealerURL);
		$("#my-next-tab .accordion_garaged").prepend(echo_garaged);

		//here is where it makes it accordion
		create_tertiaryTabsAccordions(sel_veh, vehicles_owned, vehicles_garaged, overrideType);

		//then we make the accordions inside tabs
		create_tertiaryTabs(vehicles_owned, vehicles_garaged, sel_veh, type);


		update_accessoriesAccordion(vid, type);

		update_currentlyViewedVehicle(type, vid);

	}
}

function instantiate_mySubaruProfile() {
	var init = $(".my_profile").size();
	if (init != 0) {
		update_currentlyViewedVehicle(type, vid);

		var gtp_link = linkPrefix + 'my-subaru/my-account/trade-in-program.html?vid='+sel_veh+'&vehid='+vehicle_id;
		var gtpInfo = get_myGtpInfo(vehicle_id, "vehicleId");
		var gtp_link_text = "";

		if (gtpInfo.responseXML) {
			$(gtpInfo.responseXML).find("priceInfo").each(function() {
				var gtpStatus = $(this).find("status").text();

				if (gtpStatus == "0") {
					var gtpValue = $(this).find("value").text();
					var gtpValue = format_currency(gtpValue);
					var gtpEndDate = $(this).find("endDate").text();

					gtp_link_text = gtpValue+' &ndash; Estimate only, please click for Program Rules and Eligibility ';
				}
				else {
					gtp_link_text = "Get Value";
				}
			});
		}
		else {
			gtp_link_text = "Get Value";
		}

		var profile_current_mileage = $('span#profile_current_mileage').text();
			profile_current_mileage = format_commas(profile_current_mileage);
		var next_service_title = get_nextServiceTitle(vehicle_id);
		var service_title = next_service_title+" &ndash; ";
		$('a#profile_gtp_link').attr("href", gtp_link).empty().append(gtp_link_text);
		$('span#profile_current_mileage').empty().append(profile_current_mileage);
		$('span#profile_next_service').empty().append(service_title);

		if (openModalForm != "0") {
			create_formMySubaruUpdateVehicle(editVehicle_vin, editVehicle_myModelYear, editVehicle_myModel, editVehicle_myTrim, editVehicle_optionCode);
			$("#"+openModalForm).css({'top':'0px'});
			// hide any messages that may be present
			$(".showMessage").hide();
			$("#"+openModalForm+", .showForm").show();
		}
	}
}

function instantiate_ownerEvents() {
	//these function calls are to owner_events_lite.js for now
	var init = $(".my_events").size();
	var init2 = $(".events-calendar").size(); //this is the 590 component

	if (init != 0) {
		create_eventsCalendar282("282");
		var linkHref = linkPrefix + "my-subaru/my-account/owner-events.html";
		$("#ownerEvents_viewAllEvents").attr("href", linkHref);
	}
	if (init2 != 0 && ownerZip != "") {
		create_eventsCalendar282("590", "owned");
	} else if (init2 != 0 && ownerZip == "") {
		create_eventsCalendar282("590", "visitor");
	}

}

function instantiate_rolldownItems() {
	$('.rolldown_item .rolldown_top').click(function() {
		$(this).toggleClass("opened");
		$(this).next().slideToggle('slow');
		return false;
	}).next().hide();

	var vehMilCrit = $(".rolldown_container");
	$(vehMilCrit).find(".rolldown_top a").each(function(){
		if ($(this).html() == "Vehicle Mileage Criteria:"){
			$(this).parent().toggleClass("opened");
			$(this).parent().next().slideToggle('slow');
		}//end if
	});

}

function instantiate_thankYouRaqSatd() {
	var init = $('.thankYou_satd, .thankYou_raq').size();
	if (init != 0) {
		var mn = (formModelName.toLowerCase() == "impreza" || formModelName.toLowerCase() == "impreza wrx") ? "Impreza" : formModelName;
		var mbn = formModelName.toLowerCase().replace(" ", "");
		var modelInfo = get_modelInfo(formModelYear);
		var specBrochurePath	= pathPrefix+"downloads/pdf/brochures/"+formModelYear+"_"+mbn+"_specs.pdf";
		var imagePath			= pathPrefix+"images/";
		var imageDirectory		= "";
		var trimImageDir		= "";
		var image_c				= "";
		var msrp				= "$";
		$(modelInfo.responseXML).find("model[modelName="+mn+"]").each(function() {
			imageDirectory = $(this).attr("imageDirectory");
			$(this).find("trim[trimName="+formModelTrim+"]").each(function() {
				trimImageDir = $(this).attr("trimImageDir")
				image_b = $(this).attr("trimImageC");
				msrp += $(this).attr("msrp");
			});
		});
		imagePath += imageDirectory+"/"+trimImageDir+"/"+image_b;
		var image = "<img src='" + imagePath + "' alt='"+formModelYear+" "+mn+" "+formModelTrim+"' />";
		var specBrochureLink	= "<a target='_blank' href='"+specBrochurePath+"' title='"+formModelYear+" "+mn+" "+formModelTrim+" Brochure'>Download the Full Specs (PDF)</a>";

		var date = get_formatedDate();

		// append the variables to appropriate DOM elements
		$('#carImage').append(image);
		$("#carTitle").append(mn+" "+formModelTrim);
		$('#carPrice').append(msrp);
		$('#carLink').append(specBrochureLink);

		$("#date").append(date);
		$("#dealerName").append(formDealerName);
		$("#dealerAddress").append(formDealerStreet);
		$("#dealerAddress2").append(formDealerCity+", "+formDealerState+" "+formDealerZip);
		$("#dealerPhone").append("Phone: "+ formDealerPhone);
		$("#dealerDistance").append(formDealerDistance+" Miles");

		$("#userName").append(formFn+" "+formLn);
		$("#userAddress").append(formStreet);
		$("#userAddress2").append(formCity+", "+formState+" "+formZip);
		$("#userPhone").append("Phone: "+ formPhone);
		$("#userEmail").append(formEmail);

		var similarModels = create_similarModels("2010", formModelName, formModelTrim);
		$("#similarModelsTitle").append("Similar "+formModelName+" Models");
		$("#similarModels").append(similarModels);

		var modelHomePagePath = get_modelDetailPath(formModelYear, formModelName, formModelTrim);
		var modelHomePageLink = "<a href='"+modelHomePagePath+"' title='"+formModelName+" Model Home Page'>Go to the "+formModelName+" Home Page</a>"
		$("#modelHomePageLink").append(modelHomePageLink);
	}
} // end instantiate_thankYouScheduleTestDrive()

function instantiate_vehicleMaintenanceTabs() {
	var init = $("#maintenance_tabs").size();
	if (init != 0) {
		var vehicles = vehicles_owned;
		var vehicleYear = vehicles_owned[sel_veh].YEAR;
		var vehicleModel = format_capitalize(vehicles_owned[sel_veh].MODEL);
		var vehicleTrim = vehicles_owned[sel_veh].TRIM;

		// get the dealer's maintenance schedule
		var dealer_maintenance = get_maintenanceScheduleDealer(vehicle_id);
		var manufacturer_maintenance = get_maintenanceScheduleManufacturer(vehicle_id);
		var dmt = "";
		var mmt = "";

		// count the overdue service records
		var overDueDealerServiceRecords = $(dealer_maintenance.responseXML).find("maintenanceRecord[overdue=true]").size();
		var overDueManufacturerServiceRecords = $(manufacturer_maintenance.responseXML).find("maintenanceRecord[overdue=true]").size();

		// start the "div" table
		var mt = '\n<div class="table_row table_head">';
			mt += '\n\t<div class="col1"><p>Interval</p></div>';
			mt += '\n\t<div class="col2"><p>Status</p></div>';
			mt += '\n\t<div class="col3"><p>Action</p></div>';
			mt += '\n\t<div class="clear"> </div>';
			mt += '\n</div>';

		// build the dealer schedule
		$(dealer_maintenance.responseXML).find("maintenanceRecord").each(function(index, thisElement) {
			var row_class = (index%2) ? "" : "odd";
			var completed = $(this).attr("completed");
			var overdue = $(this).attr("overdue");
			var maintenanceID = $(this).find("maintenanceID").text();
			var manufacturerRecomends = $(this).find("manufacturerRecomends").text();
			var tArray = $(this).find("title").text().split("miles");
			var title = format_commas(tArray[0])+" miles "+tArray[1];
			var mileage = $(this).find("mileage").text();
				mileage = format_commas(mileage);
			var description = $(this).find("description").text();
			var descArray = description.split("|");
			var lastOverdue = '<p>Maintenance performed? <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" title="Record Service">Record this service</a> in your <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" target="_blank">Service History</a>.</p>';
				lastOverdue += '<p>You can call '+ms_dealerName+' at '+ms_dealerPhone+' or <a href="'+ms_dealerUrl+'" title="Schedule Service Appointment" target="_blank">schedule this service online</a> to set an appointment today.</p>';
			var status = "";
			var statusClass = "";
			if (completed == "true") {
				status = "Completed";
				statusClass = "";
				lastOverdue = "";
			}
			else if (completed == "false" && overdue == "false") {
				status = "Open";
				statusClass = "";
			}
			else if (completed == "false" && overdue == "true") {
				status = "Overdue"
				statusClass = "overdue";

				/*
				if (index == (overDueDealerServiceRecords-1)) {
					lastOverdue = '<p>Maintenance performed? <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" title="Record Service">Record this service</a> in your <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" target="_blank">Service History</a>.</p>';
					lastOverdue += '<p>You can call '+ms_dealerName+' at '+ms_dealerPhone+' or <a href="'+ms_dealerUrl+'" title="Schedule Service Appointment" target="_blank">schedule this service online</a> to set an appointment today.</p>';
				}
				else {
					lastOverdue = '&nbsp;';
				}
				*/
			}

			dmt += '\n<div class="table_row table_cell '+row_class+'">';
			dmt += '\n\t<div class="col1"><p><a href="#" rel="dealer_detail_'+index+'">'+title+'</a></div>';
			dmt += '\n\t<div class="col2 '+statusClass+'"><p>'+status+'</div>';
			dmt += '\n\t<div class="col3">'+lastOverdue+'</div>';
			dmt += '\n\t<div id="dealer_detail_'+index+'" class="row_detail">';
			dmt += '\n\t\t<h3>Maintenance Details</h3>';
			dmt += '\n\t\t<p class="close"><a href="#" rel="dealer_detail_'+index+'">Close</a></p>';
			dmt += '\n\t\t<p><strong>Vehicle:</strong> '+vehicleYear+' '+vehicleModel+' '+vehicleTrim+'</p>';
			dmt += '\n\t\t<p><strong>Interval:</strong> '+title+'</p>';
			if (description.length > 0) {
				dmt += '\n\t\t<table>';
				dmt += '\n\t\t\t<tr>';
				dmt += '\n\t\t\t\t<th>Action</th>';
				dmt += '\n\t\t\t\t<th>Description</th>';
				dmt += '\n\t\t\t</tr>';
				jQuery.each(descArray, function(i, val) {
					var thisRowClass = (i%2) ? "" : "odd";
					var detail = val.split(" - ");
					dmt += '\n\t\t\t<tr class="'+thisRowClass+'">';
					dmt += '\n\t\t\t\t<td>'+detail[0]+'</td>';
					dmt += '\n\t\t\t\t<td>'+detail[1]+'</td>';
					dmt += '\n\t\t\t</tr>';
				});
				dmt += '\n\t\t</table>';
			}
			dmt += '\n\t</div>';
			dmt += '\n\t<div class="clear"> </div>';
			dmt += '\n</div>';

		});

		// build the manufacturer schedule
		$(manufacturer_maintenance.responseXML).find("maintenanceRecord").each(function(index, thisElement) {
			var row_class = (index%2) ? "" : "odd";
			var completed = $(this).attr("completed");
			var overdue = $(this).attr("overdue");
			var maintenanceID = $(this).find("maintenanceID").text();
			var manufacturerRecomends = $(this).find("manufacturerRecomends").text();
			var tArray = $(this).find("title").text().split("miles");
			var title = format_commas(tArray[0])+" miles "+tArray[1];
			var mileage = $(this).find("mileage").text();
				mileage = format_commas(mileage);
			var description = $(this).find("description").text();
			var descArray = description.split(", ");
			var lastOverdue = '<p>Maintenance performed? <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" title="Record Service">Record this service</a> in your <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" target="_blank">Service History</a>.</p>';
				lastOverdue += '<p>You can call '+ms_dealerName+' at '+ms_dealerPhone+' or <a href="'+ms_dealerUrl+'" title="Schedule Service Appointment" target="_blank">schedule this service online</a> to set an appointment today.</p>';
			var status = "";
			var statusClass = "";
			if (completed == "true") {
				status = "Completed";
				statusClass = "";
				lastOverdue = "";
			}
			else if (completed == "false" && overdue == "false") {
				status = "Open";
				statusClass = "";
			}
			else if (completed == "false" && overdue == "true") {
				status = "Overdue"
				statusClass = "overdue";

				/*
				if (index == (overDueDealerServiceRecords-1)) {
					lastOverdue = '<p>Maintenance performed? <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" title="Record Service">Record this service</a> in your <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" target="_blank">Service History</a>.</p>';
					lastOverdue += '<p>You can call '+ms_dealerName+' at '+ms_dealerPhone+' or <a href="'+ms_dealerUrl+'" title="Schedule Service Appointment" target="_blank">schedule this service online</a> to set an appointment today.</p>';
				}
				else {
					lastOverdue = '&nbsp;';
				}
				*/
			}

			mmt += '\n<div class="table_row table_cell '+row_class+'">';
			mmt += '\n\t<div class="col1"><p><a href="#" rel="manufacturer_detail_'+index+'">'+title+'</a></div>';
			mmt += '\n\t<div class="col2 '+statusClass+'"><p>'+status+'</div>';
			mmt += '\n\t<div class="col3">'+lastOverdue+'</div>';
			mmt += '\n\t<div id="manufacturer_detail_'+index+'" class="row_detail">';
			mmt += '\n\t\t<h3>Maintenance Details</h3>';
			mmt += '\n\t\t<p class="close"><a href="#" rel="manufacturer_detail_'+index+'">Close</a></p>';
			mmt += '\n\t\t<p><strong>Vehicle:</strong> '+vehicleYear+' '+vehicleModel+' '+vehicleTrim+'</p>';
			mmt += '\n\t\t<p><strong>Interval:</strong> '+title+'</p>';
			if (description.length > 0) {
				mmt += '\n\t\t<table>';
				mmt += '\n\t\t\t<tr>';
				mmt += '\n\t\t\t\t<th>Action</th>';
				mmt += '\n\t\t\t\t<th>Description</th>';
				mmt += '\n\t\t\t</tr>';
				jQuery.each(descArray, function(i, val) {
					var thisRowClass = (i%2) ? "" : "odd";
					var detail = val.split(" - ");
					mmt += '\n\t\t\t<tr class="'+thisRowClass+'">';
					mmt += '\n\t\t\t\t<td>'+detail[0]+'</td>';
					mmt += '\n\t\t\t\t<td>'+detail[1]+'</td>';
					mmt += '\n\t\t\t</tr>';
				});
				mmt += '\n\t\t</table>';
			}
			mmt += '\n\t</div>';
			mmt += '\n\t<div class="clear"> </div>';
			mmt += '\n</div>';

		});

		var dealerDetail = mt+dmt;
		$('#dealer_schedule').empty().append(dealerDetail);

		var manufacturerDetail = mt+mmt;
		$('#manufacturer_schedule').empty().append(manufacturerDetail);

		$("#maintenance_tabs").tabs();

		$(".table_row .col1 a").livequery('click', function(e) {
			e.preventDefault();
			var detailId = $(this).attr("rel");
			var detailClass = $(this).attr("class");
			if (detailClass == "open") {
				$("#"+detailId).slideUp("slow");
				$(this).removeClass("open");
				$("#"+detailId+" p.close a").removeClass("open");
			}
			else {
				$("#"+detailId).slideDown("slow");
				$(this).addClass("open");
				$("#"+detailId+" p.close a").addClass("open");
			}
			return false;
		});

		// close link
		$(".row_detail a.open").livequery('click', function(e) {
			e.preventDefault();
			var detailId = $(this).attr("rel");
			$("#"+detailId).slideUp("slow");
			$(".table_row .col1 a").removeClass("open");
			$(this).removeClass("open");
			return false;
		});
	}
}

function instantiate_vehicleServiceHistory() {
	var init = $('.my_vehicle_service_history').size();
	if (init != 0) {
		var updateVinLink = linkPrefix + "my-subaru/my-account/my-profile.html?vid=" + vid;
		//append vid to links if they exist
		$(".my_vehicle_service_history p a").attr("href", updateVinLink);

		// get the service history
		var service_history = get_serviceHistory(vehicle_id);
		// start the "div" table
		var rd = '\n<div class="table_row table_head">';
			rd += '\n\t<div class="col1"><p>Description</p></div>';
			rd += '\n\t<div class="col2"><p>Provider</p></div>';
			rd += '\n\t<div class="col3"><p>Date</p></div>';
			rd += '\n\t<div class="col4"><p>Mileage</p></div>';
			rd += '\n\t<div class="col5"><p>Reason</p></div>';
			rd += '\n\t<div class="col6"><p>Source</p></div>';
			rd += '\n\t<div class="clear"> </div>';
			rd += '\n</div>';

		// build each row
		var rowCount = 0;
		$(service_history.responseXML).find("serviceRecord").each(function(index, thisElement) {
			var row_class = (index%2) ? "" : "odd";
			var serviceRecordId = $(this).find("serviceRecordId").text();
			var serviceDate = $(this).find("serviceDate").text();
			var mileage = $(this).find("mileage").text();
			var mileageFormatted = format_commas(mileage);
			var mileageInterval = $(this).find("mileageInterval").text();
			var repairOrderNumber = $(this).find("repairOrderNumber").text();
			var serviceReason = $(this).find("serviceReason").text();
			var serviceId = (serviceReason.toLowerCase() == "o" || serviceReason.toLowerCase() == "p" || serviceReason.toLowerCase() == "r")	? serviceReason : mileageInterval;
			var srDesc = get_serviceRecordReason(vehicle_id, serviceId);
			var serviceProvider = $(this).find("serviceProvider").text();
			var serviceDescCount = $(this).find("serviceDescription").size();
			var serviceDescription = "";
			if (serviceDescCount > 1) {
				$(this).find("serviceDescription").each(function(index, thisElement) {
					var sd = $(this).text();
					serviceDescription += sd;
					if (serviceDescCount != (index+1)) {
						serviceDescription += " &ndash; ";
					}
				});
			}
			else {
				serviceDescription = $(this).find("serviceDescription").text();
			}
			var srReasons = create_serviceReasonOptions(vehicle_id, serviceId);
			var dealerId = 0;
			$(this).find("dealer").each(function() {
				dealerId = $(this).find("dealerId").text();
			});
			var serviceSource = "Owner";
				if (dealerId != 0) {serviceSource = "Dealer";}
			rd += '\n<div class="table_row table_cell '+row_class+'">';
			if (serviceSource == "Owner") {
				rd += '\n\t<div class="col1"><p><a href="#" rel="detail_'+index+'">'+serviceDescription+'</a></p></div>';
			}
			else if (serviceSource == "Dealer") {
				rd += '\n\t<div class="col1"><p>'+serviceDescription+'</p></div>';
			}
			rd += '\n\t<div class="col2"><p>'+serviceProvider+'</p></div>';
			rd += '\n\t<div class="col3"><p>'+serviceDate+'</p></div>';
			rd += '\n\t<div class="col4"><p>'+mileageFormatted+'</p></div>';
			rd += '\n\t<div class="col5"><p>'+srDesc+'</p></div>'; // Reason Title
			rd += '\n\t<div class="col6"><p>'+serviceSource+'</p></div>';

			// construct the form
			if (serviceSource == "Owner") {
				rd += '\n\t<div id="detail_'+index+'" class="comp282 form_service_record row_detail">';
				rd += '\n\t\t<h3>View / Update Service Record</h3>';
				rd += '\n\t\t<form id="update_'+index+'" action="'+linkPrefix+'my-subaru/data/maintenance/updateservicerecord" method="post">';
				rd += '\n\t\t\t<input type="hidden" name="vehicleId" value="'+vehicle_id+'">';
				rd += '\n\t\t\t<input type="hidden" name="serviceRecordId" value="'+serviceRecordId+'">';
				rd += '\n\t\t\t<input type="hidden" name="repairOrderNumber" value="'+repairOrderNumber+'">';
				rd += '\n\t\t\t<p class="inputCont delete_record"><input type="checkbox" class="checkbox" name="delete_record" value="true"/><span>Delete Record</span></p>';
				rd += '\n\t\t\t<label>Description</label>';
				rd += '\n\t\t\t<p class="inputCont required"><input type="text" id="serviceDescription_'+index+'" class="serviceDescription" name="details" value="'+serviceDescription+'" maxlength="255" /></p>';
				rd += '\n\t\t\t<label>Provider</label>';
				rd += '\n\t\t\t<p class="inputCont required"><input type="text" id="serviceProvider_'+index+'" class="serviceProvider" name="providerName" value="'+serviceProvider+'" maxlength="50" /></p>';
				rd += '\n\t\t\t<label>Date (mm/dd/yyyy)</label>';
				rd += '\n\t\t\t<p class="inputCont required"><input type="text" id="serviceDate_'+index+'" class="serviceDate" name="serviceDate" value="'+serviceDate+'" maxlength="10" /></p>';
				rd += '\n\t\t\t<label>Mileage</label>';
				rd += '\n\t\t\t<p class="inputCont required"><input type="text" id="serviceMileage_'+index+'" class="serviceMileage" name="mileage" value="'+mileage+'" maxlength="7" /></p>';
				rd += '\n\t\t\t<label>Reason</label>';
				rd += '\n\t\t\t<p class="inputCont required">';
				rd += '\n\t\t\t\t<select id="serviceReason_'+index+'" class="serviceReason" name="serviceReason">'+srReasons+'</select>';
				rd += '\n\t\t\t</p>';
				//rd += '\n\t\t\t<label>Source</label>';
				//rd += '\n\t\t\t<p class="inputCont">'+serviceSource+'</p>';
				rd += '\n\t\t\t<div class="clear"> </div>';
				rd += '\n\t\t\t<div class="button">';
				rd += '\n\t\t\t\t<span class="blue"><a id="submit_'+index+'" class="submit_update_service_record blue" href="#">Update Record</a></span>';
				rd += '\n\t\t\t\t<img id="spinner_'+index+'" class="hide ajax-spinner" src="'+pathPrefix+'images/site/icons/ajax-loader-blue-white.gif" alt="loading content" />';
				rd += '\n\t\t\t\t<div class="clear"> </div>';
				rd += '\n\t\t\t</div>';
				rd += '\n\t\t\t<div class="clear"> </div>';
				rd += '\n\t\t</form>';
				rd += '\n\t\t<div class="clear"> </div>';
				rd += "\n\t</div>";
			}

			rd += '\n\t<div class="clear"> </div>';
			rd += '\n</div>';
			rowCount++;
		});

		if (rowCount == 0) {
			rd += '\n<div class="table_row table_cell odd no_content">';
			rd += '\n\t\t<p>No Service Records could be found for your vehicle. Please use the form below to add a Service Record.</p>';
			rd += '\n</div>';
		}

		// append the table
		$('.table_container').empty().append(rd);

		$(".table_row .col1 a").livequery('click', function(e) {
			e.preventDefault();
			var detailId = $(this).attr("rel");
			var detailClass = $(this).attr("class");

			if (detailClass == "open") {
				$("#"+detailId).slideUp("slow");
				$(this).removeClass("open");
			} else {
				$("#"+detailId).slideDown("slow");
				$(this).addClass("open");
			}
			return false;
		});

		// bind the listener
		listen_formUpdateServiceRecord();
	}
}


//-----------------------------------------------------------------------------------
//7.0 is_
//-----------------------------------------------------------------------------------

function is_integer(s) {
	var i;
	for (i = 0; i < s.length; i++){
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

function is_onIndexPage() {
	var indexPage = $(".my_vehicle_detail").size();
	if (indexPage != 0){
		return true;
	} else {
		return false;
	}

}

function is_SNEDealer(dealerid){
	var region_code = dealerid.slice(0,3);
	//alert(region_code);
	if (region_code == "010"){
		return true;
	}
	else {
		return false;
	}
}

//-----------------------------------------------------------------------------------
//6.0 listen_
//-----------------------------------------------------------------------------------

function listen_changeDealer() {
	$('a.open_changeDealer').livequery('click', function(e) {
		e.preventDefault();
		var paramsArray = $(this).attr("rel").split("|");
		var yOffset = get_pageScroll() + 120;
		var currentPage = window.location.pathname;
		var returnToPage = (currentPage == "/soa-alpha/my-subaru/data/user/login") ? "/soa-alpha/my-subaru/my-account/index.html" : currentPage;
		var targetForm = 'change_dealer_'+paramsArray[0];
		var targetModal = '#modalFormContainer_' + paramsArray[0];
		$("#"+targetForm+" input[name=modalOptions]").val(paramsArray[0]+'dealerzip='+paramsArray[1]+'&vehiclenum='+paramsArray[2]+'&targeturl='+returnToPage);
		$(targetModal).modal({
			containerId: 'mcFindDealer'
		});
		$('#modalOverlay').css({height:($(document).height().toString() + "px"), overflow:"hidden"});
		$('#mcFindDealer').css({'top': yOffset + 'px'});
		listen_formChangeDealerModal(targetForm);
		return false;
	});
}

function listen_changeOwnerEventsLink(){

	$('#submit_owner_events_changeZip').click(function(e) {
		e.preventDefault();

		// get the id of the form to submit
		var formId = $(this).parent().parent().parent().attr("id");
		var inputValue = $('#EventsZip').val();

		// determine if a 5-digit zipcode was submitted
		var isZip = inputValue.replace(/[^\d]/g, "").substr(0,5);

		if (isZip.length == '5') {
			// replace the zipcode so no spaces are left
			$('#EventsZip').val(isZip);
			var formData = $('#'+formId).serialize();
			$.ajax({
				type: "post",
				url: linkPrefix+"my-subaru/data/user/setvisitorzipcode",
				data: formData,
				complete: function() {
					var params = window.location.search;
					var redirectURL = linkPrefix + "my-subaru/my-account/index.html" + params;
					window.location.assign(redirectURL);
				}
			});
			}
			else if (isZip.length < '5' || isZip.length > '5') {
				var errorMessage = "Enter 5 digit Zip";
				$(this).val(errorMessage);
			}


		return false;
	});

	$('#form_changeEventsZip').submit(function(e) {
		e.preventDefault();

		// get the id of the form to submit
		var formId = $(this).attr("id");
		var inputValue = $('#EventsZip').val();

		// determine if a 5-digit zipcode was submitted
		var isZip = inputValue.replace(/[^\d]/g, "").substr(0,5);

		if (isZip.length == '5') {
			// replace the zipcode so no spaces are left
			$('#EventsZip').val(isZip);
			var formData = $('#'+formId).serialize();
			$.ajax({
				type: "post",
				url: linkPrefix+"my-subaru/data/user/setvisitorzipcode",
				data: formData,
				complete: function() {
					var params = window.location.search;
					var redirectURL = linkPrefix + "my-subaru/my-account/index.html" + params;
					window.location.assign(redirectURL);
				}
			});
			}
			else if (isZip.length < '5' || isZip.length > '5') {
				var errorMessage = "Enter 5 digit Zip";
				$(this).val(errorMessage);
			}
		return false;
	});

}

function listen_clueTips() {
	$('a.cluetip200').livequery(function() {
		$(this).cluetip({
			cluetipClass: 'tip200',
			splitTitle: '|',
			positionBy:'fixed',
			topOffset:20,
			leftOffset:-20
		});
	});

	$('.cluetip282').cluetip({
		cluetipClass: 'tip282',
		splitTitle: '|',
		sticky:'true',
		closePosition: 'title',
		closeText: '<img src="/content/images/site/icons/Window Close_aa.gif" width="12" height="12" >',
		positionBy:'fixed',
		topOffset:20,
		leftOffset:-20
	});
} // end listen_clueTips

function listen_clueTipsGtp() {
	var gtp_cluetip200 = $('.gtp_cluetip200').size();
	if(gtp_cluetip200 != 0){
		$('.gtp_cluetip200').cluetip({
			cluetipClass: 'tip200',
			splitTitle: '|',
			positionBy:'fixed',
			topOffset:20,
			leftOffset:-20
		});
	}
	var gtp_cluetip282 = $('.gtp_cluetip282').size();
	if(gtp_cluetip282 != 0){
		$('.gtp_cluetip282').cluetip({
			cluetipClass: 'tip282',
			splitTitle: '|',
			sticky:'true',
			closePosition: 'title',
			closeText: '<img src="/content/images/site/icons/Window Close_aa.gif" width="12" height="12" >',
			positionBy:'fixed',
			topOffset:20,
			leftOffset:-20
		});
	}
} // end listen_clueTipsGtp

function listen_deleteVehicle() {
	$('a.removeVehicle').livequery('click', function(e) {
		e.preventDefault();
		var vehicleId = $(this).attr("rel");
		var deleteResource = linkPrefix +'my-subaru/data/vehicle/owned/remove/' + vehicleId;
		// set the currently viewed vehicle to index zero
		update_currentlyViewedVehicle(type, 0);

		// send the delete request
		window.location.assign(deleteResource);
		return false;
	});
}

function listen_formChangeDealerModal(formId) {
	$('#'+formId+' input[name=zipcode]').keypress(function(e){
		if (e.which == 13) {
			e.preventDefault();
			var inputValue = $(this).val();
			validate_findDealer(formId, inputValue, "City/State or Zip");
		}
	});
	$('#'+formId+' input.submit_button').click(function(e){
		e.preventDefault();
		var inputValue = $('#'+formId+' input[name=zipcode]').val();
		validate_findDealer(formId, inputValue);
	});
}

function listen_formClose() {
	$('span.close').click(function() {
		var formID = $(this).attr("title");
		$("#"+formID).hide();
	});
}

function listen_formClosePopup() {
	$('.closePopup').livequery('click', function(e) {
		e.preventDefault();
		var popUpArray = $(this).attr("rel").split(" | ");
		var popUpId = popUpArray[0];
		var closeAction = popUpArray[1];
		if (closeAction == "refresh") {
			// refresh the page
			var searchParams = window.location.search;
			var regexS = /(&openForm=).*([a-zA-Z0-9])/
			var regex = new RegExp( regexS );
			var params = searchParams.replace(regex, "");
			var redirectURL = window.location.pathname + params;
			window.location.assign(redirectURL);
		}
		else if (closeAction == "close") {
			// close the form
			$('#modalOverlay').css({display: "none", height:(0 + "px")});
			$('iframe').remove();
			$("#"+popUpId).hide();
		}
		return false;
	});
}

function listen_formOpen() {

	$('a.open_form').livequery('click',function(e){

		e.preventDefault();
		var formID = $(this).attr("rel");

		if (formID == "form_my_profile_update_vehicle") {
			create_formMySubaruUpdateVehicle(editVehicle_vin, editVehicle_myModelYear, editVehicle_myModel, editVehicle_myTrim, editVehicle_optionCode);
		}
		if (formID != 'form_forgot_email' && formID != 'form_forgot_password' && formID != "form_dear_subaru" && formID != "form_owner_events_changeZip") {
			$("#"+formID).css({'top':(get_pageScroll()) + 'px'});
		}
		else {
			$("#"+formID).css({'top':'0px'});
		}
		if (formID == 'form_owner_events_changeZip'){
			$("#"+formID).css({'margin-left':'13px', 'top':'276px'});
		}

		if (formID == 'mysubaru_notification'){

			if ($(this).parent().parent().hasClass("user_logged_in")) {
				document.location = $(this).attr('href');
				return false;
			}

			var props = { top:"0", position: "absolute", visibility: "hidden", display: "block" };
			var itemWidth = 0;
			var itemHeight = 0;

			$.swap($("#"+formID)[0], props, function(){
				 itemWidth = $("."+formID).width();
				 itemHeight = $("."+formID).height();
			});

			$("#"+formID).modal({containerId: "musubaru_modal"});
			$('#modalOverlay').css({display: "block", height:($(document).height().toString() + "px"), overflow:"hidden"});

			var windowWidth = ($(document).width() - itemWidth)/2;

			if ($.browser.msie && $.browser.version.substr(0, 1) < 7){
				$("#musubaru_modal").css({top:"0px", left: "0px", position: "absolute"});
				$("#"+formID).css({top:"200px", left: windowWidth, position: "relative"});
				scroll(0,0);
			}else{
				$("#"+formID).css({top:"50%", left: windowWidth, position: "fixed"});
			}
		}

		if (formID == 'mysubaru_vehicle_delete_confirmation'){

			var vehicle = $(this).attr('id');
			$("#"+formID + " a.removeVehicle").attr('rel',vehicle);

			var props = { top:"0", position: "absolute", visibility: "hidden", display: "block" };
			var itemWidth = 0;
			var itemHeight = 0;

			$.swap($("#"+formID)[0], props, function(){
				 itemWidth = $("."+formID).width();
				 itemHeight = $("."+formID).height();
			});

			$("#"+formID).modal({containerId: "musubaru_modal"});
			$('#modalOverlay').css({display: "block", height:($(document).height().toString() + "px"), overflow:"hidden"});

			var windowWidth = ($(document).width() - itemWidth)/2;

			if ($.browser.msie && $.browser.version.substr(0, 1) < 7){
				$("#musubaru_modal").css({top:"0px", left: "0px", position: "absolute"});
				$("#"+formID).css({top:"200px", left: windowWidth, position: "relative"});
				scroll(0,0);
			}else{
				$("#"+formID).css({top:"50%", left: windowWidth, position: "fixed"});
			}
		}

		if (formID == 'chinese_to_english_notification'){

			var url = $(this).attr('href');
			var props = { top:"0", position: "absolute", visibility: "hidden", display: "block" };

			var itemWidth = 0;
			var itemHeight = 0;

			$.swap($("#"+formID)[0], props, function(){
				 itemWidth = $("."+formID).width();
				 itemHeight = $("."+formID).height();
			});

			$("#"+formID).modal({containerId: "chinese_modal"});
			$('#modalOverlay').css({display: "block", height:($(document).height().toString() + "px"), overflow:"hidden"});
			$("#"+formID + " a").attr('href',url);

			var windowWidth = ($(document).width() - itemWidth)/2;

			if ($.browser.msie && $.browser.version.substr(0, 1) < 7){
				$("#chinese_modal").css({top:"0px", left: "0px", position: "absolute"});
				$("#"+formID).css({top:"200px", left: windowWidth, position: "relative"});
				scroll(0,0);
			}else{
				$("#"+formID).css({top:"50%", left: windowWidth, position: "fixed"});
			}
		}

		// hide any messages that may be pesent
		$(".showMessage").hide();
		$("#"+formID+", .showForm").show();
		return false;
	});
}

function showLeavingSiteWindow() { // REFACTOR to adhere to coding conventions -jward

// Validation
	var inputValue = $('#findDealer_chinese input#dealerZip2').val();
	var defValue = "聯絡經銷商";

	// suppress errors if form field is non-existent or inputValue is undefined
	if (inputValue == undefined) {
	    inputValue = "";
	}

	validate_findDealerChinese("findDealer_chinese", inputValue, defValue);

	inputValue = $('#findDealer_chinese input#dealerZip2').val();

	if (inputValue == defValue){
		return false;
	}

// End Validation

	var formID = "chinese_to_english_notification"
	var url = "javascript:$('#findDealer_chinese').submit();";
	var props = { top:"0", position: "absolute", visibility: "hidden", display: "block" };

	var itemWidth = 0;
	var itemHeight = 0;

	$.swap($("#"+formID)[0], props, function(){
		 itemWidth = $("."+formID).width();
		 itemHeight = $("."+formID).height();
	});

	$("#"+formID).modal({containerId: "chinese_modal"});
	$('#modalOverlay').css({display: "block", height:($(document).height().toString() + "px"), overflow:"hidden"});
	$("#"+formID + " a").attr('href',url);

	var windowWidth = ($(document).width() - itemWidth)/2;

	if ($.browser.msie && $.browser.version.substr(0, 1) < 7){
		$("#chinese_modal").css({top:"0px", left: "0px", position: "absolute"});
		$("#"+formID).css({top:"200px", left: windowWidth, position: "relative"});
		scroll(0,0);
	}else{
		$("#"+formID).css({top:"50%", left: windowWidth, position: "fixed"});
	}

	$(".showMessage").hide();
	$("#"+formID+", .showForm").show();
}

function listen_formReOpen() {
	$('a.reOpen_form').livequery('click', function(e) {
		e.preventDefault();
		var formId = $(this).attr("rel");
		$('#'+formId+' form')[ 0 ].reset();
		$('#'+formId+' .showMessage').slideUp("slow");
		$('#'+formId+' .showForm').slideDown("slow");

		return false;
	});
}

function listen_formUpdateServiceRecord() {
	var init = $('.form_service_record').size();
	if (init != 0) {
		// date picker
		$("input.serviceDate").datepicker({
			showOn: 'button',
			buttonImage: '/content/images/site/icons/calendar.gif',
			buttonImageOnly: true,
			changeYear: true,
			minDate: minDate,
			maxDate: maxDate
		});

		$(".serviceDate").addClass("maskedDate");

		/*
			In-line validation
			- alphabetical by comment name
		*/
		// Date
		$('input.serviceDate').change(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			var isDate = validate_date(inputValue, $(this));

			if (isDate != "true") {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: isDate
				});
			}
			else if (isDate == "true") {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});
		$('input.serviceDate').blur(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			if (inputValue.length > 0) {
				var isDate = validate_date(inputValue, $(this));

				if (isDate != "true") {
					$("#error_"+inputId+", div.errorClear").remove();
					$(this).errorMessage(
					{
						messageMain: isDate
					});
				}
				else if (isDate == "true") {
					$("#error_"+inputId+", div.errorClear").remove();
					$(this).removeClass("errorFocus");
				}
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter a valid date (mm/dd/yyyy)."
				});
			}
		});

		// Description
		$('input.serviceDescription').blur(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id")
			if (inputValue.length == 0) {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter service description."
				});
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		// Mileage
		$('input.visibleServiceMileage').blur(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			var inputDigits = inputValue.replace(/[^\d]/g, "");
			if (inputDigits.length == 0) {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter the current mileage."
				});
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		// Provider
		$('input.serviceProvider').blur(function() {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id")
			if (inputValue.length == 0) {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please enter the service provider."
				});
			}
			else {
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		// Reason
		$('select.serviceReason').blur(function() {
			var selectOption = $(this).val();
			var selectId = $(this).attr("id");
			if (selectOption == "noSelection")
			{
				$("#error_"+selectId+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageMain: "Please select a reason for service."
				});
			}
		}).change(function(){
			var selectOption = $(this).val();
			var selectId = $(this).attr("id");
			if (selectOption != "noSelection") {
				$("#error_"+selectId+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
		});

		$('.submit_update_service_record').click(function(e) {
			e.preventDefault();
			if (serviceRecordCounter == 0) {
				// get the form id
				var submitId = $(this).attr("id");
				var formId = submitId.replace("submit_", "update_");
				var spinnerId = submitId.replace("submit_", "spinner_");
				var deleteRecord = $('#'+formId+' input[name=delete_record]').attr('checked');
				if (deleteRecord == true) {
					delete_serviceRecord(formId);
				}
				else {
					update_serviceRecord(formId);
				}
			}
			else if (serviceRecordCounter > 0) {
				var redirectURL = window.location.pathname + window.location.search;
				window.location.assign(redirectURL);
			}
			serviceRecordCounter = serviceRecordCounter+1;
			return false;
		});
	}
}

function listen_gtpDisclaimerSymbol() {
	var gtpValueCont = $('span#gtpValue').size();
	var gtpValue = $('span#gtpValue').text();
	if (gtpValueCont != 0 && gtpValue.length > 0) {
		// append the disclaimer symbol
		$('p.gtpDisclaimer').prepend('^');
	}
} // end listen_gtpDisclaimerSymbol

function listen_gtpModal() {
	$('#show_certificate').click(function(){
		$(".modal_gtp_print").modal({
			containerId: 'mcGTPCert',
			persist:true,
			onClose: listen_gtpPrintModalClose
		});
		var fullHeight = $(document).height();
		$('#modalOverlay').css({'top':'0px','height': fullHeight, 'overflow':'hidden'});
		$('#mcGTPCert').css({'top':'30px', 'left':'50%', 'margin-left':'-141px'});

		listen_gtpPrintModalForm();
		return false;
	});
} // end listen_gtpModal

function listen_gtpPrintModalClose(dialog) {
	$('.closeModal img').livequery('click', function() {
		$.modal.close();
	});
} // end listen_gtpPrintModalClose

function listen_gtpPrintModalForm() {
	var stateOptions = create_stateOptions("", "Select a State");
	$('select#owner_homeState').empty().append(stateOptions);

	/*
		In-line validation
		- alphabetical by comment name
	*/
	// address - city
	$('input#owner_homeCity').blur(function() {
		var inputId = $(this).attr("id");
		var inputValue = $(this).val();
		var message = "Please enter the name of your city.";
		validate_presenceOf(inputId, inputValue, message);
	});

	// address - state
	$('select#owner_homeState').blur(function() {
		var inputId = $(this).attr("id");
		var selectOption = $(this).val();
		validate_presenceOf(inputId, selectOption);
	}).change(function() {
		var inputId = $(this).attr("id");
		var selectOption = $(this).val();
		validate_presenceOf(inputId, selectOption);
	});

	// address - street1
	$('input#owner_homeAddress').blur(function() {
		var inputId = $(this).attr("id");
		var inputValue = $(this).val();
		var message = "Please enter your home street address.";
		validate_presenceOf(inputId, inputValue, message);
	});

	// address - zip
	$('input#owner_zipCode2').blur(function() {
		var inputId = $(this).attr("id");
		var inputValue = $(this).val();
		validate_zipCode(inputId, inputValue);
	});

	//email
	$('input#myEmail').blur(function() {
		var inputId = $(this).attr("id");
		var inputValue = $(this).val();
		validate_email(inputId, inputValue);
	});

	// name - first
	$('input#fn').blur(function() {
		var inputId = $(this).attr("id");
		var inputValue = $(this).val();
		var message = "Please enter your first name.";
		validate_presenceOf(inputId, inputValue, message);
	});

	// name - last
	$('input#ln').blur(function() {
		var inputId = $(this).attr("id");
		var inputValue = $(this).val();
		var message = "Please enter your last name.";
		validate_presenceOf(inputId, inputValue, message);
	});

	$("#submit_print_my_gtp").livequery('click', function(e) {
		e.preventDefault();
		submit_gtpPrintCertificate();
		return false;
	});
} // end listen_gtpPrintModalForm

function listen_gtpShowForm() {
	$('.gtp_showForm').click(function(e) {
		e.preventDefault();
		var errorCont = $(this).attr("rel");
		// remvove the disclaimer symbol
		var disclaimerText = $('p.gtpDisclaimer').text().replace("^", "");
		$('p.gtpDisclaimer').empty().append(disclaimerText);
		$('div#'+errorCont).hide();
		$('div.showGtpForm').show();
		return false;
	});
} // end listen_gtpShowForm()

function listen_gtpSubmit() {
	$('#submit_gtp, #submit_gtp_ajax, #submit_gtp_button, #submit_gtp_button_ajax').click(function(e) {
		e.preventDefault();
		submit_gtpCalculator();
		return false;
	});
} // end listen_gtpSubmit

function listen_specials() {
	$('#modalFormContainer .offers img, .offers_obDetergent_bottom').click(function() {
		var redirect = linkPrefix+"outback-detergent.html";
		window.location.assign(redirect);
	});
}

//-----------------------------------------------------------------------------------
//8.0 submit_
//-----------------------------------------------------------------------------------

function submit_addServiceRecord(formId) {
	// check for obvious errors
	$('#'+formId + ' input#visibleServiceMileage').blur();
	var fieldErrors = $('#'+formId).find("div.errorCont").length;

	// loop through each required field and check for a value
	$('#'+formId).find("p.required").each(function(index, thisElement) {
		var elementID = $(thisElement).children("eq(0)").attr("id");
		var elementValue = $(thisElement).children("eq(0)").val();
		var elementLength = parseFloat(elementValue.length);
		if (elementLength == 0 || elementValue == "noSelection") {
			// set fieldErrors to 1
			fieldErrors = 1;

			// trigger an error
			$("#error_"+elementID+", div.errorClear").remove();
			$('#'+elementID).errorMessage();
		}
	});

	if (fieldErrors == 0) {
		//Remove the comma from the service mileage.
		var parsedMileage = document.getElementById("visibleServiceMileage").value;
		document.getElementById("serviceMileage").value = parsedMileage.replace(/[^\d]/g, "");

		// start the spinner
		$('#'+formId+' .button img.ajax-spinner').show();
		// submit the form
		var formData = $('#'+formId).serialize();
		var redirectURL = window.location.pathname + window.location.search;
		$.ajax({
			type: "post",
			url: linkPrefix+"my-subaru/data/maintenance/addservicerecord",
			data: formData,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('#form_service_record .showForm').slideUp("slow");
				var errorMessage = "<h3>Error!</h3><p>There was an error while adding your Service Record, please try again or <a class='closePopup' rel=' | refresh' >close window</a>.</p>";
				$('#form_service_record .showMessage').empty().append(errorMessage).slideDown('slow');
			},
			success: function(data, textStatus) {
				// Set the Omniture Variables
				var s = s_gi(s_account);
				s.linkTrackEvents="event28";
				s.events = "event28";
				s.tl(this,'o','my-subaru:add_record');

				window.location.assign(redirectURL);
			}
		});
	}
}

function submit_addVehicle() {
	// check for obvious errors
	var fieldErrors = $('#form_add_vehicle').find("div.errorCont").length;

	// loop through each required field and check for a value
	$('#form_add_vehicle').find("p.required").each(function(index, thisElement) {
		var elementID = $(thisElement).children("eq(0)").attr("id");
		var elementValue = $(thisElement).children("eq(0)").val();
		var elementLength = parseFloat(elementValue.length);
		if (elementLength == 0 || elementValue == "noSelection") {
			// set fieldErrors to 1
			fieldErrors = 1;

			// trigger an error
			$("#error_"+elementID+", div.errorClear").remove();
			$('#'+elementID).errorMessage();
		}
	});

	if (fieldErrors == 0) {
		// start the spinner
		$('#form_add_vehicle .button img.ajax-spinner').show();

		// if a VIN was NOT entered...
		var vin = $('input#vin').val();
		if (vin.length == 0) {
			// get the modelCode & optionCode
			var modelYear = $('select#chooseYear').val();
			var mn = $('select#chooseModel').val();
			var tn = $('select#chooseTrim option:selected').text();
			var moCodes = get_modelOptionCodes(modelYear, mn, tn);
			var mcArray = moCodes.split(" | ");

			$('input#modelCode').val(mcArray[0]);
			$('input#optionCode').val(mcArray[1]);
		}
		else {
			$('input#vin').val(vin.toUpperCase())
		}

		// PATCH for 2010 Trims *********************
		if (modelYear > 2009 && vin.length > 0) {
			$('select#chooseTrim option:selected').val("");
		}
		// END PATCH ********************************

		// Set the Omniture Variables
		var s = s_gi(s_account);
		s.linkTrackEvents = "event33";
		s.events = "event33";
		s.tl(this, 'o', 'my-subaru:add_vehicle');

		// submit the form
		var formData = $('#form_add_vehicle').serialize();

		$.ajax({
			type: "post",
			url: linkPrefix+"my-subaru/data/vehicle/owned/add",
			data: formData,
			complete: function() {
				var redirectURL = linkPrefix+"my-subaru/my-account/index.html";
				update_currentlyViewedVehicle("owned", 0);
				window.location.assign(redirectURL);
			}
		});
	}
}

function submit_contactUs() {
	// check for obvious errors
	var fieldErrors = $('#form_contactUs').find("div.errorCont").length;

	// loop through each required field and check for a value
	$('#form_contactUs').find("label.required").each(function() {
		var elementID = $(this).next().attr("id");
		var elementValue = $(this).next().val();
		var elementLength = parseFloat(elementValue.length);
		if (elementLength == 0 || elementValue == "noSelection") {
			// set fieldErrors to 1
			fieldErrors = 1;

			// trigger an error
			$("#error_"+elementID+", div.errorClear").remove();
			$('#'+elementID).errorMessage();
		}
	});

	if (fieldErrors == 0) {
		// submit the form
		$('#form_contactUs').submit();
	}
	else {
		// scroll to the top of the page so user can view any error messages
		window.scrollTo(0,0);
	}
} // end submit_contactUs()

function submit_forgotEmail() {
	// check for obvious errors
	var fieldErrors = $('#form_forgot_email form').find("div.errorCont").length;

	if (fieldErrors == 0) {
		// submit the form
		//var formData = $('#form_forgot_email form').serialize();

		$('#form_forgot_email form').submit();
	}
}

function submit_forgotPassword() {
	// check for obvious errors
	var fieldErrors = $('#form_forgot_password').find("div.errorCont").length;

	if ($('#submit_forgot_password').hasClass('enable')) {
		if (fieldErrors == 0) {
			// start the spinner
			$('#form_forgot_password .button img.ajax-spinner').show();
			$('#submit_forgot_password').removeClass('enable');

			// submit the form
			var email = $('input#fpw_email').val();
			var formData = $('#form_forgot_password .body form').serialize();

			$.ajax({
				type: "post",
				url: linkPrefix + "my-subaru/data/user/resetpassword",
				data: formData,
				error: function(XMLHttpRequest, textStatus, errorThrown){
					$('#form_forgot_password .button img.ajax-spinner').hide();
					$('#submit_forgot_password').addClass('enable');
					$('.showForm').slideUp("slow");
					var errorMessage = "<h3>Error!</h3><p>The email address you entered (" + email + ") is not associated with a My Subaru account. </p>";
					$('.showMessage').empty().append(errorMessage).slideDown('slow');
				},
				success: function(data, textStatus){
					$('#form_forgot_password .button img.ajax-spinner').hide();
					$('#submit_forgot_password').addClass('enable');
					$('.showForm').slideUp("slow");
					var successMessage = "<h3>Success!</h3><p>Your new password has been sent to " + email + ". </p>";
					$('.showMessage').empty().append(successMessage).slideDown('slow');
				}
			});
		}
	}
}

function submit_getBrochure() {
	var brochureSelected = true;
	// check for obvious errors
	var brochureTypes = '';
	$("input[type='checkbox'][name='brochureType']").each(function() {
		if (this.checked) {
			brochureTypes += this.value+",";
		}
	});

	if(brochureTypes == '')
	{
		brochureSelected = false;
		addErrorBrochures("No brochures selected","You must select at least one brochure.");
	}

	$('#brochureType').val(brochureTypes);
	var fieldErrors = $('#form_requestBrochure').find("div.errorCont").length;

	// loop through each required field and check for a value
	$('#form_requestBrochure').find("div.formRequired").each(function(index, thisElement) {
		if (index >= 0) {
			var elementID = $(thisElement).children()[1].id;
			var elementValue = $(thisElement).children()[1].value;
			var elementLength = parseFloat(elementValue.length);
			if (elementID == "zipCode2" || elementID == "homeState") {
				if (elementLength == 0 || elementValue == "noSelection") {
					// set fieldErrors to 1
					fieldErrors = 1;

					// trigger an error
					if (elementID == "zipCode2") {
						$("#error_divErrorZip, div.errorClear").remove();
						$("#divErrorZip").addClass("zipCode2");
						$('#divErrorZip').errorMessage( {
							specialCase:"true"
						});
					}
					if (elementID == "homeState"){
						$("#error_divErrorState, div.errorClear").remove();
						$("#divErrorState").addClass("homeState");
						$('#divErrorState').errorMessage( {
							specialCase:"true"
						});
					}
					$("#getQuoteError").addClass("width263");

				}
			}
			else {
				if (elementLength == 0 || elementValue == "noSelection") {
					// set fieldErrors to 1
					fieldErrors = 1;

					// trigger an error
					$("#error_" + elementID + ", div.errorClear").remove();
					$('#' + elementID).errorMessage();
				}
			}
		}
		var idas = 9;
		idas++;
	});

	if (brochureSelected && fieldErrors == 0) {
		// Set the Omniture Variables
		s.linkTrackVars='eVar9,state,prop30,eVar19,zip,prop29,eVar18';
		s.linkTrackEvents='None';
		s.eVar9 = $('input[name=brochureType]:checked').val(); // brochure type selected radio button
		s.state = $('#homeState').val(); // state field
		s.prop30 = s.state; // state field
		s.eVar19 = s.state; // state field
		s.zip = $('#zipCode2').val(); // zip field
		s.prop29 = s.zip; // zip field
		s.eVar18 = s.zip; // zip field
		s.tl(this,'o','Request Brochure Submit');

		// submit the form
		$('#form_requestBrochure').submit();
	}
	else {
		// scroll to the top of the page so user can view any error messages
		window.scrollTo(0,0);
	}
} // end submit_getBrochure()

function submit_gtpCalculator() {
	var submitId = $('a.gtp_calculator').attr("id");
	var vin = jQuery.trim($('#vin').val().toUpperCase());
	if ((vin.length == 8 || vin.length == 17) && vin != "Enter VIN - Last 8 or all 17 characters") {
		if (submitId == "submit_gtp") {
			// Set the Omniture Variables
			s = s_gi(s_account);
			s.linkTrackVars='events';
			s.linkTrackEvents='event36';
			s.eVar12 = ""; // user email
			s.prop9 = ""; // user email
			s.events = "event36";
			s.tl(this, 'o', 'guaranteed-trade-in-value:get-trade-in-value');

			var formAction = $('#getGtpInfo').attr("action");
			var redirectURL = formAction+vin;
			window.location.assign(redirectURL);
		}
		else if (submitId == "submit_gtp_ajax") {
			// Set the Omniture Variables
			/*
			s = s_gi(s_account);
			s.linkTrackVars='events';
			s.linkTrackEvents='event36';
			s.eVar12 = ""; // user email
			s.prop9 = ""; // user email
			s.events = "event36";
			s.tl(this, 'o', 'guaranteed-trade-in-value:get-trade-in-value');
			*/
			// get the gtp info via ajax
			var gtpInfo = get_gtpInfo(vin);

			$(gtpInfo.responseXML).find("priceInfo").each(function() {
				var gtpStatus = $(this).find("status").text();
				if (gtpStatus == "0") {
					var gtpStartDate = $(this).find("startDate").text();
					var gtpEndDate = $(this).find("endDate").text();
						gtpEndDate = format_gtpDate(gtpEndDate);
					var gtpMileage = $(this).find("mileage").text();
					var gtpVin = $(this).find("vin").text();
					var gtpVehicleYear = $(this).find("modelYear").text();
					var gtpVehicleModel = $(this).find("modelName").text();
					var gtpVehicelTrim = $(this).find("trimName").text();
					var gtpValue = $(this).find("value").text();
					var gtpMileageFormat = format_commas(gtpMileage);
					var gtpCurrency = format_currency(gtpValue);

					// dealer info --> CONSIDER REFACTORING INTO A GET_ FUNCTION
					var salesDealerId = $(this).find("dealer dealerId").text();
					var salesDealerName = $(this).find("dealer dealerName").text();
					if (ddcDealerId != 0) {
						salesDealerId = ddcDealerId;
						// get the dealers name
						var formUrl = linkPrefix+'tools/maps/dealer/getmapmarkers/dealerid/'+salesDealerId;
						var dealerInfo = $.ajax({
							url: formUrl,
							async: false,
							cache: false
						});
						$(dealerInfo.responseXML).find("marker").each(function(i, thisElement) {
							salesDealerName = $(thisElement).attr("name");
						});
					}

					var dealerMessage = "Please have "+salesDealerName+" contact me about the Guaranteed Trade-In Program.";

					$('p.gtpDisclaimer').prepend('^');

					$('#gtpModelYear').empty().append(gtpVehicleYear);
					$('#gtpModelName').empty().append(gtpVehicleModel);
					$('#gtpModelTrim').empty().append(gtpVehicelTrim);
					$('#gtpMileage').empty().append(gtpMileageFormat);
					$('#gtpValue').empty().append(gtpCurrency);
					$('#gtpEndDate').empty().append(gtpEndDate);

					$('#modalModelYear').empty().append(gtpVehicleYear);
					$('#modalModelName').empty().append(gtpVehicleModel);
					$('#modalModelTrim').empty().append(gtpVehicelTrim);
					$('#modalMileage').empty().append(gtpMileageFormat);
					$('#modalGtpValue').empty().append(gtpCurrency);
					$('#modalGtpEndDate').empty().append(gtpEndDate);
					$('#modalDealerMessage').empty().append(dealerMessage);

					$('input[name=vin]').val(gtpVin);
					$('input[name=model]').val(gtpVehicleModel);
					$('input[name=modelYear]').val(gtpVehicleYear);
					$('input[name=mileage]').val(gtpMileage);
					$('input[name=tradeInPrice]').val(gtpValue);
					$('input[name=dealerId]').val(salesDealerId);

					$('#printModelYear').empty().append(gtpVehicleYear);
					$('#printModelName').empty().append(gtpVehicleModel);
					$('#printModelTrim').empty().append(gtpVehicelTrim);
					$('#printVin').empty().append(gtpVin);
					$('#printGtpValue').empty().append(gtpCurrency);
					$('#printGtpEndDate').empty().append(gtpEndDate);

					$('.showGtpForm').hide();
					$('.gtpSuccess').show();

				}
				else if (gtpStatus == "1") {
					$('.showGtpForm').hide();
					$('#gtp_error1').show();
				}
				else if (gtpStatus == "2") {
					$('.showGtpForm').hide();
					$('#gtp_error2').show();
				}
				else if (gtpStatus == "3") {
					$('.showGtpForm').hide();
					$('#gtp_error3').show();
				}
			});
		}

	}
	else {
		$('input#vin').val("Enter VIN - Last 8 or all 17 characters");
	}
} // end submit_gtpCalculator()

function submit_gtpRedemption() {
	// check for obvious errors
	var fieldErrors = $('.gtp_redemption_form form').find("div.errorCont").length;

	// loop through each required field and check for a value
	$('.gtp_redemption_form form').find("p.required").each(function(index, thisElement) {
		var elementID = $(thisElement).children("eq(0)").attr("id");
		var elementValue = $(thisElement).children("eq(0)").val();
		var elementLength = parseFloat(elementValue.length);
		if (elementLength == 0 || elementValue == "noSelection" || elementValue == "Enter VIN - Last 8 or all 17 characters") {
			// set fieldErrors to 1
			fieldErrors = 1;

			// trigger an error
			$("#error_"+elementID+", div.errorClear").remove();
			$('#'+elementID).errorMessage();
		}
	});

	if (fieldErrors == 0) {
		// get the dealer information
		var zipCode = $('#owner_zipCode2').val();
		var dealers = $.ajax({
			url: linkPrefix + "tools/maps/dealer/getmapmarkers/"+zipCode,
			dataType: 'xml',
			async: false,
			cache: false
		});

		var dealerId = "";
		$(dealers.responseXML).find("marker").each(function(index, thisElement) {
			var distance = parseFloat($(thisElement).attr("distance"));
			if (index == 0) {
				// set the variables
				var dealerID = $(thisElement).attr("id");
				var dealerName = $(thisElement).attr("name");
			}

		});

		// set the dealerId
		$('input#dealerId').val(dealerId);

		// submit the form
		var formData = $('.gtp_redemption_form form').serialize();
		// submit the form
		//$('#gtp_redemption_form form').submit();

		var formUrl = $('.gtp_redemption_form form').attr("action");

		$.ajax({
			type: "post",
			url: formUrl,
			data: formData,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				var errorMessage = "<h3>Error!</h3><p>We could not process your request at this time.</p>";
				$('.showMessage').empty().append(errorMessage).slideDown('slow');
			},
			success: function(data, textStatus) {
				// Set the Omniture Variables
				s = s_gi(s_account);
				s.linkTrackVars='eVar12,prop9,events';
				s.linkTrackEvents='event37';
				s.eVar12 = $('input#myEmail').val(); // user email
				s.prop9 = $('input#myEmail').val(); // user email
				s.events = "event37";
				s.tl(this, 'o', 'guaranteed-trade-in-value:print trade-in value certificate');

				var redirectURL = linkPrefix+'finance-center/guaranteed-trade-in-program/thank-you.html';
				window.location.assign(redirectURL);
			}
		});
	}
} // end submit_gtpRedemption()

function submit_gtpPrintCertificate() {
	var isChecked = $('input[name=gtp_dealerContact]').attr('checked');
	var firstName = $("#form_print_gtp #fn").val();
	var lastName = $("#form_print_gtp #ln").val();
	var address = $("#form_print_gtp #owner_homeAddress").val();
	var city = $("#form_print_gtp #owner_homeCity").val();
	var state = $("#form_print_gtp #owner_homeState").val();
	var zip = $("#form_print_gtp #owner_zipCode2").val();
	var email = $("#form_print_gtp #owner_emailAddress").val();
/*
//This throws an error on dealer pages.
	// Set the Omniture Variables
	s = s_gi(s_account);
	s.linkTrackVars='eVar12,prop9,events';
	s.linkTrackEvents='event37';
	s.eVar12 = email; // user email
	s.prop9 = email; // user email
	s.events = "event37";
	s.tl(this, 'o', 'guaranteed-trade-in-value:print trade-in value certificate');
*/
	$("#gtp_print_component span.firstName").empty();
	$("#gtp_print_component span.lastName").empty();
	$("#gtp_print_component span.address").empty();
	$("#gtp_print_component span.city").empty();
	$("#gtp_print_component span.state").empty();
	$("#gtp_print_component span.zip").empty();
	$("#gtp_print_component span.email").empty();

	$("#gtp_print_component span.firstName").append(firstName);
	$("#gtp_print_component span.lastName").append(lastName);
	$("#gtp_print_component span.address").append(address);
	$("#gtp_print_component span.city").append(city);
	$("#gtp_print_component span.state").append(state);
	$("#gtp_print_component span.zip").append(zip);
	$("#gtp_print_component span.email").append(email);

	if (isChecked == true) {
		//submit the data
		// check for obvious errors
		var fieldErrors = $('#form_print_gtp form').find("div.errorCont").length;

		// loop through each required field and check for a value
		$('#form_print_gtp form').find("p.required").each(function(index, thisElement) {
			var elementID = $(thisElement).children("eq(0)").attr("id");
			var elementValue = $(thisElement).children("eq(0)").val();
			var elementLength = parseFloat(elementValue.length);
			if (elementLength == 0 || elementValue == "noSelection") {
				// set fieldErrors to 1
				fieldErrors = 1;

				// trigger an error
				$("#error_"+elementID+", div.errorClear").remove();
				$('#'+elementID).errorMessage();
			}
		});

		if (fieldErrors == 0) {
			// submit the form
			var formData = $('#form_print_gtp form').serialize();

			var formUrl = $('#form_print_gtp form').attr("action");

			$.ajax({
				type: "post",
				url: formUrl,
				data: formData,
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					var errorMessage = "<h3>Error!</h3><p>We could not process your request at this time.</p>";
				},
				success: function(data, textStatus) {
					//close print modal
					$.modal.close();

					// print the coupon
					window.print();

					window.setTimeout(function() {
						$("#gtp_thankyou_modal").modal({containerId: 'mcGTPCert'});
						var fullHeight = $(document).height();
						$('#modalOverlay').css({'top':'0px','height': fullHeight, 'overflow':'hidden'});
						$('#mcGTPCert').css({'top':'30px', 'left':'50%', 'margin-left':'-141px'});
						window.scrollTo(0,0);
						window.setTimeout(function() {
							window.location.href = window.location.href;
						}, 600);
					}, 1500);

				}
			});
		}
	}
	else {
		//close print modal
		$.modal.close();

		// just print the coupon
		window.print();

			window.setTimeout(function() {
			//refresh the page.
			//this is because there are errors in IE when trying to print the modal for the 2nd time
			window.location.href = window.location.href;
			}, 1500);

	}
} // end submit_gtpPrintCertificate

function submit_login() {
	// check for obvious errors
	var fieldErrors = $('#form_login').find("div.errorCont").length;

	if (fieldErrors == 0) {
		// trim spaces
		var trim_email = jQuery.trim($('#myEmailLogin').val());
		var trim_pw = jQuery.trim($('#myPasswordLogin').val());
		$('#myEmailLogin').val(trim_email);
		$('#myPasswordLogin').val(trim_pw);

		// Set the Omniture Variables
		s=s_gi(s_account);
		s.linkTrackVars='eVar21,eVar22,prop32,prop33,events';
		s.linkTrackEvents='event3';
		s.eVar21 = $('#myEmailLogin').val(); // user email
		s.eVar22 = ""; // Login / LoginError
		s.eVar32 = ""; // Login / LoginError
		s.prop33 = $('#myEmailLogin').val(); // user email
		s.events = "event3";
		s.tl(this, 'o', 'my-subaru:log-in_attempt');

		// submit the form
		$('#form_login').submit();
	}
	else {
		// scroll to the top of the page so user can view any error messages
		window.scrollTo(0,0);
	}
}

function submit_nonOwnerAccountCreation() {
	// hide the button
	$('#button_submitShopperAccountCreation').hide();

	// check for obvious errors
	var fieldErrors = $('#form_account_registration').find("div.errorCont").length;

	// loop through each required field and check for a value
	$('dd#nonOwner_preferences').find("p.required").each(function(index, thisElement) {
		var elementID = $(thisElement).children("eq(0)").attr("id");
		var elementValue = $(thisElement).children("eq(0)").val();
		var elementLength = parseFloat(elementValue.length);
		if (elementLength == 0 || elementValue == "noSelection") {
			// set fieldErrors to 1
			fieldErrors = 1;

			// trigger an error
			$("#error_"+elementID+", div.errorClear").remove();
			$('#'+elementID).errorMessage();

			// show the button
			$('#button_submitShopperAccountCreation').show();
		}
	});

	if (fieldErrors == 0) {
		// remove the "owner-specifc" portions of the form
		$("dd#owner_preferences, dd#owner_contact_info, dd#owner_vehicle_info").remove();

		// submit the form
		$('#form_account_registration').submit();
	}
}

function submit_reservationSti() {
	// check for obvious errors
	var fieldErrors = $('#form_reservation_sti').find("div.errorCont").length;

	// loop through each required field and check for a value
	$('#form_reservation_sti form').find("p.required").each(function(index, thisElement) {
		var elementID = $(thisElement).children("eq(0)").attr("id");
		var elementValue = $(thisElement).children("eq(0)").val();
		var elementLength = parseFloat(elementValue.length);
		if (elementLength == 0 || elementValue == "noSelection") {
			// set fieldErrors to 1
			fieldErrors = 1;

			// trigger an error
			$("#error_"+elementID+", div.errorClear").remove();
			$('#'+elementID).errorMessage();
		}
	});

	if (fieldErrors == 0) {
		// submit the form
		$('#form_reservation_sti form').submit();
	}
}

function submit_requestQuote() {
	// check for obvious errors
	var fieldErrors = $('#form_requestQuote').find("div.errorCont").length;

	// loop through each required field and check for a value
	$('#form_requestQuote').find("div.formRequired").each(function(index, thisElement) {
		if (index >= 0) {
			var elementID = $(thisElement).children()[1].id;
			var elementValue = $(thisElement).children()[1].value;
			var elementLength = parseFloat(elementValue.length);
			if (elementID == "zipCode1" || elementID == "homeState") {
				if (elementLength == 0 || elementValue == "noSelection") {
					// set fieldErrors to 1
					fieldErrors = 1;

					// trigger an error
					if (elementID == "zipCode1") {
						$("#error_divErrorZip, div.errorClear").remove();
						$("#divErrorZip").addClass("zipCode1");
						$('#divErrorZip').errorMessage( {
							specialCase:"true"
						});
					}
					if (elementID == "homeState"){
						$("#error_divErrorState, div.errorClear").remove();
						$("#divErrorState").addClass("homeState");
						$('#divErrorState').errorMessage( {
							specialCase:"true"
						});
					}
					$("#getQuoteError").addClass("width263");

				}
			}
			else {
				if (elementLength == 0 || elementValue == "noSelection") {
					// set fieldErrors to 1
					fieldErrors = 1;

					// trigger an error
					$("#error_" + elementID + ", div.errorClear").remove();
					$('#' + elementID).errorMessage();
				}
			}
		}
	});

	if (fieldErrors == 0) {
		// verify that a Dealer was selected
		var isChecked = 0; // assume nothing is checked
		$('#dynamicDealerList').find('input:checked').each(function() {
			isChecked = 1;
		});

		if (isChecked == 0) {
			// trigger an error
			$("#error_dynamicDealerList, div.errorClear").remove();
			$('#dynamicDealerList').errorMessage(
			{
				messageTop: "You forgot to select a Dealer",
				messageMain: "Please make a selection and resubmit",
				formElement: "false"
			});
		}
		else if (isChecked == 1) {
			// submit the form after the Floodlight Tag was submitted
			$('#form_requestQuote').submit();
		}
	}
	else {
		// scroll to the top of the page so user can view any error messages
		window.scrollTo(0, 0);
	}
} // end submit_requestQuote

function submit_scheduleTestDrive() {
	// check for obvious errors
	var fieldErrors = $('#form_scheduleTestDrive').find("div.errorCont").length;

	// loop through each required field and check for a value
	$('#form_scheduleTestDrive').find("div.formRequired").each(function(index, thisElement) {
		if (index >= 0) {
			var elementID = $(thisElement).children()[1].id;
			var elementValue = $(thisElement).children()[1].value;
			var elementLength = parseFloat(elementValue.length);
			if (elementID == "zipCode1" || elementID == "homeState") {
				if (elementLength == 0 || elementValue == "noSelection") {
					// set fieldErrors to 1
					fieldErrors = 1;

					// trigger an error
					if (elementID == "zipCode1") {
						$("#error_divErrorZip, div.errorClear").remove();
						$("#divErrorZip").addClass("zipCode1");
						$('#divErrorZip').errorMessage( {
							specialCase:"true"
						});
					}
					if (elementID == "homeState"){
						$("#error_divErrorState, div.errorClear").remove();
						$("#divErrorState").addClass("homeState");
						$('#divErrorState').errorMessage( {
							specialCase:"true"
						});
					}
					$("#getQuoteError").addClass("width263");

				}
			}
			else {
				if (elementLength == 0 || elementValue == "noSelection") {
					// set fieldErrors to 1
					fieldErrors = 1;

					// trigger an error
					$("#error_" + elementID + ", div.errorClear").remove();
					$('#' + elementID).errorMessage();
				}
			}
		}
	});

	if (fieldErrors == 0) {
		// verify that a Dealer was selected
		var isChecked = 0; // assume nothing is checked
		$('#dynamicDealerList').find('input:checked').each(function() {
			isChecked = 1;
		});

		if (isChecked == 0) {
			// trigger an error
			$("#error_dynamicDealerList, div.errorClear").remove();
			$('#dynamicDealerList').errorMessage(
				{
					messageTop: "You forgot to select a Dealer",
					messageMain: "Please make a selection and resubmit",
					formElement: "false"
				});
		}
		else if (isChecked == 1) {
			// fire the "DoubleClick Floodlight Tag"
			var axel = Math.random() + "";
			var a = axel * 10000000000000;
			var floodLight = '<iframe src="https://fls.doubleclick.net/activityi;src=1762894;type=subar882;cat=reque373;ord=' + a + '?" width="1" height="1" frameborder="0"></iframe>'
			$("body").append(floodLight);
			// Set the Omniture Variables
			s.linkTrackVars='eVar1,eVar2,state,prop30,eVar19,zip,prop29,eVar18';
			s.linkTrackEvents='None';
			s.eVar1 = $('#chooseModel').val(); // model input field
			s.eVar2 = $('#chooseModel').val() + ':' + $('#chooseTrim').val(); // model:trim input field
			s.state = $('#homeState').val(); // state field
			s.prop30 = s.state; // state field
			s.eVar19 = s.state; // state field
			s.zip = $('#zipCode1').val(); // zip field
			s.prop29 = s.zip; // zip field
			s.eVar18 = s.zip; // zip field
			s.eVar10 = $("#dynamicDealerList li input[name='dealer']").val(); // selected dealer
			s.tl(this,'o','Schedule Test Drive Submit');

			// submit the form
			$('#form_scheduleTestDrive').submit();
		}
	}
	else {
		// scroll to the top of the page so user can view any error messages
		window.scrollTo(0,0);
	}
	return false;
} // end submit_scheduleTestDrive

function submit_signUpForUpdates() {
	// check for obvious errors
	var fieldErrors = $('#form_infoSignUp').find("div.errorCont").length;

	// loop through each required field and check for a value
	$('#form_infoSignUp').find("label.required, label.required_bottom").each(function() {
		// get the class of the next element
		var elementClass = $(this).next().attr("class");

		if (elementClass == "inputGroup") {
			// get the id of this element
			var containerId = $(this).next().attr("id");
			// validate for radio buttons or checkboxes
			var isChecked = 0; // assume nothing is checked
			$('#'+containerId+' ul.radio').find('input:checked').each(function() {
				isChecked = 1;
			});

			if (isChecked == 0) {
				fieldErrors = 1;
				// trigger an error
				$("#error_"+containerId+", div.errorClear").remove();
				$('#'+containerId).errorMessage({
					messageTop: "You must check at least one",
					messageMain: "Please make a selection and resubmit"
				});
			}
		}
		else {
			var elementID = $(this).next().attr("id");
			var elementValue = $(this).next().val();
			var elementLength = parseFloat(elementValue.length);
			if (elementLength == 0 || elementValue == "noSelection") {
				// set fieldErrors to 1
				fieldErrors = 1;

				// trigger an error
				$("#error_"+elementID+", div.errorClear").remove();
				$('#'+elementID).errorMessage();
			}
		}

	});

	if (fieldErrors == 0 && ($('input[name=firstName]').val()!="") ) {
		// verify the privacy policy checkbox is checked
		var checkedTerms = $('input[name=terms]').is(':checked');

		if (checkedTerms) {
			// Set the Omniture Variables
			s.linkTrackVars='eVar1,zip,prop29,eVar18';
			s.linkTrackEvents='None';
			s.eVar1 = $('input[name=modelInterest]:checked').val(); // model input field
			s.zip = $('#zipCode1').val(); // zip field
			s.prop29 = s.zip; // zip field
			s.eVar18 = s.zip; // zip field
			s.tl(this,'o','Sign Up For Updates Submit');

			// submit the form
			$('#form_infoSignUp').submit();
		}
		else {
			alert("You must acknowledge your agreement with the Privacy Policy.");
		}
	}
	else {
		// scroll to the top of the page so user can view any error messages
		window.scrollTo(0,0);
	}
} // end submit_signUpForUpdates()

//-----------------------------------------------------------------------------------
//9.0 update_
//-----------------------------------------------------------------------------------

function update_accessoriesAccordion(selectedIndex, whichTab){
	$('.dynamic_accordion').hide();
	var vehicles;
	if (whichTab == "owned"){
		vehicles = vehicles_owned;
	} else {
		vehicles = vehicles_garaged;
	}

	if($(vehicles).size() > 0){
		var vehicleYear = vehicles[selectedIndex].YEAR;
		var vehicleModel = vehicles[selectedIndex].MODEL;
		var modelCode = vehicles[selectedIndex].MODEL_CODE;
		var vehicle_id = vehicles[selectedIndex].VEHICLE_ID;
		var vehicleTrim = vehicles[selectedIndex].TRIM;

		switch (vehicleModel) {
			case "IMPREZA":
				$('#Impreza_accordion').show();
				$('#Specials_accordion').hide();
				break;
			case "LEGACY":
				$('#Legacy_accordion').show();
				$('#Specials_accordion').hide();
				break;
			case "OUTBACK":
				$('#Outback_accordion').show();
				$('#Specials_accordion').hide();
				break;
			case "FORESTER":
				$('#Forester_accordion').show();
				$('#Specials_accordion').hide();
				break;
			case"TRIBECA":
				$('#Tribeca_accordion').show();
				$('#Specials_accordion').hide();
				break;
			default:
				$('#Specials_accordion').show();
		}

		//vehicleModel = format_capitalize(vehicleModel, 4);

		var read_more_link = get_accBrochure(vehicleYear, vehicleModel, vehicleTrim);
		if (read_more_link == "/content/downloads/pdf/accbrochures/undefined"){
			$('.dynamic_accordion p span').remove();
		}
		else {
		    $('.dynamic_accordion a.read_more').attr("href", read_more_link);
		}
	}

}

function update_contactInfo(formId) {
	// check for obvious errors
	var fieldErrors = $('#form_my_profile_update_contact').find("div.errorCont").length;

	$('#'+formId).find("p.required").each(function(index, thisElement) {
		var elementID = $(thisElement).children("eq(0)").attr("id");
		var elementValue = $(thisElement).children("eq(0)").val();
		var elementLength = parseFloat(elementValue.length);
		if (elementLength == 0 || elementValue == "noSelection") {
			// set fieldErrors to 1
			fieldErrors = 1;

			// trigger an error
			$("#error_"+elementID+", div.errorClear").remove();
			$('#'+elementID).errorMessage();
		}
	});


	if (fieldErrors == 0) {
		// start the spinner
		$('#form_my_profile_update_contact .button img.ajax-spinner').show();

		// change the close action
		$('#form_my_profile_update_contact span a.closePopup').attr("rel", " | refresh");

		// submit the form
		var formData = $('#form_my_profile_update_contact form').serialize();

		$.ajax({
			type: "post",
			url: linkPrefix+"my-subaru/data/user/updatecontactinformation",
			data: formData,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('#form_my_profile_update_contact .showForm').slideUp("slow");
				var errorMessage = "<h3>Error!</h3><p>There was an error updating your account, please try again or <a class='closePopup' rel=' | refresh' >close window</a>.</p>";
				$('#form_my_profile_update_contact .showMessage').empty().append(errorMessage).slideDown('slow');
			},
			success: function(data, textStatus) {
				$('#form_my_profile_update_contact .showForm').slideUp("slow");
				var successMessage = "<h3>Thank You!</h3><p>Your vehicle information has been updated. <a class='closePopup' rel=' | refresh' >Close Window</a></p>";
				$('#form_my_profile_update_contact .showMessage').empty().append(successMessage).slideDown('slow');
			}
		});
	}
}

function update_currentlyViewedVehicle(ownedGaraged, vid){
	var URLToPost;
	if (ownedGaraged == "owned"){
		URLToPost = linkPrefix + "my-subaru/data/vehicle/setselectedownedvehicle";

	} else {
		URLToPost = linkPrefix + "my-subaru/data/vehicle/setselectedgaragedvehicle";

	}

	URLToPost += "/" + vid;
	$.ajax({
		type: "GET",
		url: URLToPost,
		async: true,
		cache: false
	});

}

function update_login() {
	// check for obvious errors
	var fieldErrors = $('#form_my_profile_update_login form').find("div.errorCont").length;
	var currentPw = $('#form_my_profile_update_login input#ownerPassword').val();

	if (currentPw.length == 0) {
		fieldErrors = 1;
		// trigger an error
		$("#error_ownerPassword, div.errorClear").remove();
		$('#ownerPassword').errorMessage();
	}

	if (fieldErrors == 0) {
		// start the spinner
		$('#form_my_profile_update_login .button img.ajax-spinner').show();

		// change the close action
		$('#form_my_profile_update_login span a.closePopup').attr("rel", "form_my_profile_update_login | refresh");

		// submit the form
		var formData = $('#form_my_profile_update_login form').serialize();
		var message = "";
		$.ajax({
			type: "post",
			url: linkPrefix+"my-subaru/data/user/updatecredentials",
			data: formData,
			complete: function(xhr) {
				$('#form_my_profile_update_login .button img.ajax-spinner').hide();

				var status = xhr.status;

				if (status == 200) {
					$('#form_my_profile_update_login .showForm').slideUp("slow");
					var message = "<h3>Success!</h3><p>Your Login has successfully been updated. <a class='closePopup' rel='form_my_profile_update_login | refresh' >Close Window</a></p>";
					$('#form_my_profile_update_login .showMessage').empty().append(message).slideDown('slow');
				}
				else if (status == 304) {
					$('#form_my_profile_update_login .showForm').slideUp("slow");
					var message = "<h3>Error!</h3><p>The email you entered is already in use. Please <a class='reOpen_form' rel='form_my_profile_update_login' href='#'>try again</a> or <a class='closePopup' rel='form_my_profile_update_login | refresh' >close window</a>.</p>";
					$('#form_my_profile_update_login .showMessage').empty().append(message).slideDown('slow');
				}

			}
		});
	}
}

function update_serviceRecord(formId) {
	// check for obvious errors
	var fieldErrors = $('#'+formId).find("div.errorCont").length;

	// loop through each required field and check for a value
	$('#'+formId).find("p.required").each(function(index, thisElement) {
		var elementID = $(thisElement).children("eq(0)").attr("id");
		var elementValue = $(thisElement).children("eq(0)").val();
		var elementLength = parseFloat(elementValue.length);
		if (elementLength == 0 || elementValue == "noSelection") {
			// set fieldErrors to 1
			fieldErrors = 1;

			// trigger an error
			$("#error_"+elementID+", div.errorClear").remove();
			$('#'+elementID).errorMessage();
		}
	});

	if (fieldErrors == 0) {
		// start the spinner
		$('#'+formId+' .button img.ajax-spinner').show();

		// submit the form
		var formData = $('#'+formId).serialize();
		var redirectURL = window.location.pathname + window.location.search;
		$.ajax({
			type: "post",
			url: linkPrefix+"my-subaru/data/maintenance/updateservicerecord",
			data: formData,
			async: false,
			complete: function() {
				// Set the Omniture Variables
				/*
				var s = s_gi(s_account);
				s.linkTrackEvents="event28";
				s.events = "event28";
				s.tl(this,'o','my-subaru:update_record');
				*/
				window.location.assign(redirectURL);
			}
		});
	}
}

/*function update_vehicleDetail(){
	var noSavedVehicle = $(".no_saved_vehicle");
	var noOwnedVehicle = $(".no_owned_vehicle");
	var myVehicleDetail = $(".my_vehicle_detail");
	var myNextVehicleDetail = $(".my_next_vehicle_detail");
	
	$(".two_thirds").empty();
	$(".two_thirds").prepend(noSavedVehicle);
	$(".two_thirds").prepend(noOwnedVehicle);
	$(".two_thirds").prepend(myVehicleDetail);
	$(".two_thirds").prepend(myNextVehicleDetail);
}*/

function update_vehicleInfo() {
	// check for obvious errors
	var fieldErrors = $('#form_my_profile_update_vehicle form').find("div.errorCont").length;
	var old_value = $("#prev_mileage").val();
	var new_value = $("#originalMileage").val().replace(/[^\d]/g, "");
	var confirmMileOverTitle =	"You have entered a mileage that is 1,000 miles over your current mileage.";
	var confirmMileUnderTitle =	 "You have entered a mileage that is 1,000 miles under your current mileage.";
	var confirmMileBody = " Are you sure you want to save this change?	 If not, please select Cancel and try again.";
	var correctMileage=true;
	if(new_value-old_value>1000)
	{
		correctMileage=confirm(confirmMileOverTitle+confirmMileBody);
	}
	else if(new_value-old_value<-1000)
	{
		correctMileage=confirm(confirmMileUnderTitle+confirmMileBody);
	}

	// loop through each required field and check for a value
	$('#form_my_profile_update_vehicle').find("p.required").each(function(index, thisElement) {
		var elementID = $(thisElement).children("eq(0)").attr("id");
		var elementValue = $(thisElement).children("eq(0)").val();
		var elementText = $(thisElement).children("eq(0)").text();
		var elementLength = parseFloat(elementValue.length) + parseFloat(elementText.length);
		if (elementLength == 0 || elementValue == "noSelection") {
			// set fieldErrors to 1
			fieldErrors = 1;

			// trigger an error
			$("#error_"+elementID+", div.errorClear").remove();
			$('#'+elementID).errorMessage();
		}
	});

	if (fieldErrors == 0 && correctMileage) {
		// start the spinner
		$('#form_my_profile_update_vehicle .button img.ajax-spinner').show();

		// if a VIN was NOT entered...
		var vin = $('input#vin').val();
		if (vin.length == 0) {
			// get the modelCode & optionCode
			var modelYear = $('select#chooseYear').val();
			var mn = $('select#chooseModel').val();
			var tn = $('select#chooseTrim option:selected').text();
			var moCodes = get_modelOptionCodes(modelYear, mn, tn);
			var mcArray = moCodes.split(" | ");

			$('input#modelCode').val(mcArray[0]);
			$('input#optionCode').val(mcArray[1]);
		}
		else {
			$('input#vin').val(vin.toUpperCase())
		}

		// PATCH for 2010 Trims *********************
		if (modelYear > 2009 && vin.length > 0) {
			$('select#chooseTrim option:selected').val("");
		}
		// END PATCH ********************************

		// change the close action
		$('#form_my_profile_update_vehicle span a.closePopup').attr("rel", " | refresh");

		$("#originalMileage").val(new_value);

		// submit the form
		var formData = $('#form_my_profile_update_vehicle form').serialize();

		$.ajax({
			type: "post",
			url: linkPrefix+"my-subaru/data/vehicle/owned/update",
			data: formData,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('#form_my_profile_update_vehicle .showForm').slideUp("slow");
				var errorMessage = "<h3>Error!</h3><p>There was an error updating your account, please try again or <a class='closePopup' rel=' | refresh' >close window</a>.</p>";
				$('#form_my_profile_update_vehicle .showMessage').empty().append(errorMessage).slideDown('slow');
			},
			success: function(data, textStatus) {
				$('#form_my_profile_update_vehicle .showForm').slideUp("slow");
				var successMessage = "<h3>Thank You!</h3><p>Your vehicle information has been updated. <a class='closePopup' rel=' | refresh' >Close Window</a></p>";
				$('#form_my_profile_update_vehicle .showMessage').empty().append(successMessage).slideDown('slow');
			}
		});
	}
}



//-----------------------------------------------------------------------------------
//10.0 validate_
//-----------------------------------------------------------------------------------

function validate_date(dateString) {
	// Declaring valid date character, minimum year and maximum year
	var deliminator= "/";

	var message = "true";
	var dateStringDigits = dateString.replace(/[^\d]/g, "");
	var daysInMonth = create_daysArray(12);
	var pos1=dateString.indexOf(deliminator);
	var pos2=dateString.indexOf(deliminator,pos1+1);
	var strMonth=dateString.substring(0,pos1);
	var strDay=dateString.substring(pos1+1,pos2);
	var strYear=dateString.substring(pos2+1);
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) {
		strDay=strDay.substring(1);
	}
	if (strMonth.charAt(0)=="0" && strMonth.length>1) {
		strMonth=strMonth.substring(1);
	}
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	var month = parseInt(strMonth);
	var day = parseInt(strDay);
	var year = parseInt(strYr);

	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		message = "Please enter the date in the correct format.";
	}
	if (strMonth.length<1 || month<1 || month>12){
		message = "Please enter a valid month.";
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>validate_daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		message = "Please enter a valid day.";
	}
	if (strYear.length != 4 || year==0){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		message = "Please enter a valid 4 digit year.";
	}
	if (dateString.indexOf(deliminator,pos2+1)!=-1 || is_integer(dateStringDigits)==false){
		//alert("Please enter a valid date")
		message = "Please enter a valid date.";
	}
	if ((year < minDate.getFullYear()) || (year > maxDate.getFullYear())) {
		message = "Please enter a valid year."
	}
	return message;
}

function validate_daysInFebruary(year) {
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function validate_email(inputId, inputValue) {
	var isValid = "no";
	var value = jQuery.trim(inputValue.toUpperCase());
	var regEx = new RegExp("^[A-Z0-9._+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$");

	if (value.match(regEx)) {
		isValid = "yes";
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}
	else {
		if (inputValue.length == 0) {
			var topMessage = "This field cannot be left blank";
			var mainMessage = "Please enter your email address";
		}
		else {
			var topMessage = "The email you entered is not valid";
			var mainMessage = "Please enter a valid email address";
		}
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageTop: topMessage,
			messageMain: mainMessage
		});
	}
}

function validate_emailConfirm(inputId, email1, email2) {
	if (email2 != email1) {
		var topMessage = "The email addresses you entered do NOT match!";
		var mainMessage = "Please re-enter your email address.";

		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage(
		{
			containerId: inputId,
			messageTop: topMessage,
			messageMain: mainMessage
		});
	}
	else if (email2.length == 0) {
		var topMessage = "You forgot to enter an email address!";
		var mainMessage = "Please enter your email address.";

		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage(
		{
			containerId: inputId,
			messageTop: topMessage,
			messageMain: mainMessage
		});
	}
	else {
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}
}

function validate_mileage(inputId, inputValue) {
	var inputDigits = inputValue.replace(/[^\d]/g, "");
	if(inputValue >= 900000) {
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
		$(this).errorMessage(
		{
				containerId: inputId,
				messageTop: "You have entered a mileage over 900,000 miles",
				messageMain: "We're sorry, but the mileage you entered is not valid.  Please review and try again."
		});
	}
	else {
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
		if (inputDigits.length == 0) {
			$("#"+inputId).val("0");
		}
	}
}

function validate_model(inputId, selectOption, year, action) {
	var isValid = "no";
	if (year === undefined) {year = "";}
	if (action === undefined) {action = "pop";}
	if ((selectOption == "noSelection" || selectOption.length == 0) && year.length != 4) {
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageMain: "Please select a vehicle"
		});

		if (action == "none") {
			var trimOption = '<option value="noSelection">Select a Model</option>';
			$('select#chooseTrim').empty().append(trimOption);
			$('#modelCont').empty();
		}
		if (action == "pop") {
			var trimOptions = "<option value='noSelection'>Select a Vehicle</option>";
			$('select#'+inputId).empty().append(trimOptions);
			$("#error_chooseTrim, div.errorClear").remove();
			$("select#chooseTrim").removeClass("errorFocus");

			var trimOption = '<option value="noSelection">Select a Model</option>';
			$('select#chooseTrim').empty().append(trimOption);

			$('#modelCont').empty();
		}
	}
	else if ((selectOption == "noSelection" || selectOption.length == 0) && year.length == 4) {
		isValid = "yes";
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageMain: "Please select a vehicle"
		});

		if (action == "pop") {
			var trimOptions = create_modelTrimOptions(selectOption, year);
			$('select#chooseTrim').empty().append(trimOptions);
			$("#error_chooseTrim, div.errorClear").remove();
			$("select#chooseTrim").removeClass("errorFocus");
		}
	}
	else if ((selectOption != "noSelection" && selectOption.length > 0) && year.length == 4) {
		isValid = "yes";
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");

		if (action == "pop") {
			var trimOptions = create_modelTrimOptions(selectOption, year);
			$('select#chooseTrim').empty().append(trimOptions);
			$("#error_chooseTrim, div.errorClear").remove();
			$("select#chooseTrim").removeClass("errorFocus");
		}
	}
	return isValid;
}

function validate_modelTrim(inputId, selectOption) {
	var isValid = "no";
	if (selectOption == "noSelection" || selectOption.length == 0) {
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageMain: "Please select a model"
		});
	}
	else {
		isValid = "yes";
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}
	return isValid;
}

function validate_modelYear(inputId, selectOption, action) {
	var isValid = "no";
	if (action === undefined) {action = "pop";}
	if (selectOption == "noSelection" || selectOption.length == 0) {
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageMain: "Please Select a Year"
		});
		if (action == "pop") {
			var options = "<option value='noSelection'>Select a Vehicle</option>";
			$('select#chooseModel').empty().append(options);
			var trimOptions = "<option value='noSelection'>Select a Model</option>";
			$('select#chooseTrim').empty().append(trimOptions);
			$("#error_chooseModel, #error_chooseTrim, div.errorClear").remove();
			$("select#chooseModel, select#chooseTrim").removeClass("errorFocus");
		}
	}
	else if (selectOption.length == 4) {
		isValid = "yes";
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");

		if (action == "pop") {
			var modelOptions = create_modelOptions(selectOption);
			//alert(modelOptions);
			$('select#chooseModel').empty().append(modelOptions);

			var trimOptions = "<option value='noSelection'>Select a Model</option>";
			$('select#chooseTrim').empty().append(trimOptions);
			$("#error_chooseModel, #error_chooseTrim, div.errorClear").remove();
			$("select#chooseModel, select#chooseTrim").removeClass("errorFocus");
		}
	}
	return isValid;
}

function validate_password(inputId, inputValue) {
	var isValid = "no";
	// 6 characters and be only letters, numbers, or ".", "@", "-" or "_" (no other special characters
	//var pwPattern = /^*([a-zA-Z0-9-@_,\.]*){6,26}$/;
	var pwPattern = /^(.*[A-Za-z0-9-@_,\.])$/;
	var pwRegex = new RegExp(pwPattern);

	if (inputValue.match(pwRegex) && inputValue.length > 5) {
		isValid = "yes";
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}
	else {
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage(
		{
			containerId: inputId,
			messageTop: "Invalid Password!",
			messageMain: 'Password must be at least 6 characters long and contain only letters, numbers, ".", "@", "-", or "_"'
		});
	}
}

function validate_passwordConfirm(inputId, pw1, pw2) {
	if (pw2 != pw1)
	{
		var topMessage = "The passwords you entered do NOT match!";
		var mainMessage = "Please re-enter your password.";

		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage(
		{
			containerId: inputId,
			messageTop: topMessage,
			messageMain: mainMessage
		});
	}
	else if (pw2.length == 0) {
		var topMessage = "You forgot to confirm your password!";
		var mainMessage = "Please re-enter your password.";

		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage(
		{
			containerId: inputId,
			messageTop: topMessage,
			messageMain: mainMessage
		});
	}
	else
	{
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}
}

function validate_phoneNumber(inputId, inputValue) {
	if (inputValue.length > 0) {
		// validate the field
		var inputDigits = inputValue.replace(/[^\d]/g, "");
		var areaCode = inputDigits.substr(0,3);
		var phonePrefix = inputDigits.substr(3,3);
		var lineNumber = inputDigits.substr(6,4);
		var digitLength = inputDigits.length;
		if (digitLength < 10 || digitLength > 10)
		{
			var topMessage = "The phone number you entered is not valid";
			var mainMessage = "Please enter a valid, 10 digit phone number";

			$("#error_"+inputId+", div.errorClear").remove();
			$(this).errorMessage(
			{
				containerId: inputId,
				messageTop: topMessage,
				messageMain: mainMessage
			});
		}
		else {
			$("#error_"+inputId+", div.errorClear").remove();
			$("#"+inputId).removeClass("errorFocus");
			// re-format the phone number
			var formatedNumber = areaCode+"-"+phonePrefix+"-"+lineNumber;
			$("#"+inputId).attr('maxlength', '12');
			$("#"+inputId).val(formatedNumber);
		}
	}
	else
		if (inputValue.length == 0){
		    var topMessage = "This field cannot be left blank";
			var mainMessage = "Please enter a valid, 10 digit phone number";

			$("#error_"+inputId+", div.errorClear").remove();
			$(this).errorMessage(
				{
					containerId: inputId,
					messageTop: topMessage,
					messageMain: mainMessage
			});
	   }
	   else {
		     $("#error_"+inputId+", div.errorClear").remove();
		     $("#"+inputId).removeClass("errorFocus");
	  }
}

function validate_presenceOf(inputId, inputValue, message) {
	if (inputValue.length < 2) {
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageMain: message
		});
	}
	else {
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}
}

function validate_presenceOfName(inputId, inputValue, message) {
	var value = jQuery.trim(inputValue.toLowerCase());
	var regVal = /^[a-zA-Z0-9\s'-]*$/;
	var regEx = new RegExp(regVal);

	if (inputValue.length < 2) {
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageMain: message
		});
	}
	else {
		if (value.match(regEx)) {
			$("#error_"+inputId+", div.errorClear").remove();
			$("#"+inputId).removeClass("errorFocus");
		}
		else {
				isValid = false;
				var topMessage = "Invalid format!";
				var mainMessage = "";
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage({
					containerId: inputId,
					messageTop: topMessage,
					messageMain: mainMessage
				});
		}
	}
}

function validate_presenceOfAddress(inputId, inputValue, message) {
	var value = jQuery.trim(inputValue.toLowerCase());
	var regVal = /^[a-zA-Z0-9-#,'-',/\s'-]*$/;
	var regEx = new RegExp(regVal);

	if (inputValue.length < 2) {
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageMain: message
		});
	}
	else {
		if (value.match(regEx)) {
			$("#error_"+inputId+", div.errorClear").remove();
			$("#"+inputId).removeClass("errorFocus");
		}
		else {
				isValid = false;
				var topMessage = "Invalid format!";
				var mainMessage = "";
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage({
					containerId: inputId,
					messageTop: topMessage,
					messageMain: mainMessage
				});
		}
	}
}

function validate_presenceOfAddress2(inputId, inputValue, message) {
	var value = jQuery.trim(inputValue.toLowerCase());
	var regVal = /^[a-zA-Z0-9-#,'-',/\s'-]*$/;
	var regEx = new RegExp(regVal);


	if (value.match(regEx)) {
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}
	else {
		isValid = false;
		var topMessage = "Invalid format!";
		var mainMessage = "";
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageTop: topMessage,
			messageMain: mainMessage
		});
	}
}

function validate_presenceOfCity(inputId, inputValue, message) {
	var value = jQuery.trim(inputValue.toLowerCase());
	var regVal = /^[a-zA-Z0-9-#,'-',/\s'-]*$/;
	var regEx = new RegExp(regVal);

	if (inputValue.length < 2) {
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageMain: message
		});
	}
	else {
		if (value.match(regEx)) {
			$("#error_"+inputId+", div.errorClear").remove();
			$("#"+inputId).removeClass("errorFocus");
		}
		else {
				isValid = false;
				var topMessage = "Invalid format!";
				var mainMessage = "";
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage({
					containerId: inputId,
					messageTop: topMessage,
					messageMain: mainMessage
				});
		}
	}
}

function validate_vehicleName(inputId, inputValue) {
	var isValid = true;
	if (inputValue.length > 0) {
		var value = jQuery.trim(inputValue.toLowerCase());
		var regVal = /^[a-zA-Z0-9\s'-]*$/;
		var regEx = new RegExp(regVal);
		if (value.match(regEx)) {
			$("#error_"+inputId+", div.errorClear").remove();
			$("#"+inputId).removeClass("errorFocus");
		}
		else {
			isValid = false;
			var topMessage = "Invalid format!";
			var mainMessage = "Please enter a vehicle name containing only letters, numbers, and hyphens";
			$("#error_"+inputId+", div.errorClear").remove();
			$(this).errorMessage({
				containerId: inputId,
				messageTop: topMessage,
				messageMain: mainMessage
			});
		}
	}
	else {
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}
	return isValid;
}

function validate_vin(vin) {
	var validVin = false;
	// hide error message if it exists
	$(".vin_errorCont").hide();
	// start the spinner
	$(".field_check").show();

	// check the VIN to make sure it's not a duplicate
	var vinMatch = "no";
	$(vehicles_owned).each(function() {
		var ownedVin = jQuery.trim($(this).attr("VIN").toUpperCase());
		if (vin == ownedVin) {
			vinMatch = "yes";
		}
	});

	if (vinMatch == "no") {
		var vinInfo = get_vinInfo(vin);
		var isVin = "no";
		$(vinInfo.responseXML).find("salesInfo").each(function() {
			isVin = "yes";
			validVin = true;

			var my = $(this).find("modelYear").text();
			var mn = $(this).find("modelName").text();
			var tn = $(this).find("trimName").text();
			var mc = $(this).find("modelCode").text();
			var oc = $(this).find("optionCode").text();
			var purchaseDate = $(this).find("dateSold").text();

			// remove error messages
			$("#error_chooseYear, #error_chooseModel, #error_chooseTrim, div.errorClear").remove();
			$("select#chooseYear, select#chooseModel, select#chooseTrim").removeClass("errorFocus");

			// populate fields
			$("input#purchaseDate, input#edit_purchaseDate").val(purchaseDate);
			// create the model year options
			var modelYearOptions = '<option value="'+my+'">'+my+'</option>';
			$("select#chooseYear").empty().append(modelYearOptions);
			// create the model options
			var modelOptions = '<option value="'+mn+'">'+mn+'</option>';
			$('select#chooseModel').empty().append(modelOptions);
			// create the trim options
			var trimOptions = '<option value="'+tn+'">'+tn+'</option>';
			$('select#chooseTrim').empty().append(trimOptions);

			// populate modelCode and optionCode
			$('input#modelCode').val(mc);
			$('input#optionCode').val(oc);

			$(".field_check, .vin_errorCont").hide();

			// build the dealer information
			var dealerInfo = '\n<label>My Preferred Dealer</label>';
			var markerID = $(this).find("id").text();
			var dealerName = $(this).find("name").text();
			var dealerAddress = $(this).find("address1").text();
			var dealerCity = $(this).find("city").text();
			var dealerState = $(this).find("state").text();
			var dealerZip = $(this).find("zip").text();
			var dealerPhone = $(this).find("phone").text();
			var dealerLink = $(this).find("url").text();


			dealerInfo += '<p class="inputCont dealer_title"><a class="inventoryLink" target="_blank" href="'+dealerLink+'" title="'+dealerName+'">'+dealerName+'</a></p>';
			dealerInfo += '<p class="inputCont dealer_address">'+dealerAddress+'<br />'+dealerCity+', '+dealerState+' '+dealerZip+' <br /> '+dealerPhone+'</p>';

			$('#preferredDealerCont').empty().append(dealerInfo);
		});


	//****************************************

		if (isVin == "no") {
			// create the model year options
			var modelYearOptions = create_modelYearOptions();
			$('select#chooseYear').empty().append(modelYearOptions).focus();
			// reset model options and trim options
			var modelOptions = '<option value="noSelection">Select a Model</option>';
			$('select#chooseModel').empty().append(modelOptions);
			var trimOption = '<option value="noSelection">Select a Trim</option>';
			$('select#chooseTrim').empty().append(trimOption);
			$(".field_check").hide();
			$("#notValidVin").show();
		}
	}
	else if (vinMatch == "yes") {
		$(".field_check").hide();
		$("#duplicateVin").show();
	}
	return validVin;
}

function validate_zipCode(inputId, inputValue) {
	var inputDigits = inputValue.replace(/[^\d]/g, "");
	var digitLength = inputDigits.length;
	var validated = "no";

	if (digitLength < 5 || digitLength > 5) {
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage(
		{
			containerId: inputId,
			messageTop: "The zip code must contain only 5 digits",
			messageMain: "Please enter a 5 digit zip code"
		});
		validated = "no";
	}
	else {
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
		validated = "yes";
	}
	return validated;
}

function validate_zipCodeForm(inputId, inputValue) {
	var inputDigits = inputValue.replace(/[^\d]/g, "");
	var digitLength = inputDigits.length;
	var validated = "no";

	if (digitLength < 5 || digitLength > 5) {
		$("#error_divErrorZip, div.errorClear").remove();
		$('#divErrorZip').errorMessage(
		{
			messageTop: "The zip code must contain only 5 digits",
			messageMain: "Please enter a 5 digit zip code"
		});
		$("#divErrorZip").removeClass("errorFocus");
		$("#"+inputId).addClass("errorFocus");
		validated = "no";
	}
	else {
		var zip = $('input#zipCode1').val();
		var searchRadius = parseFloat($("#selectRadius").val());
		var dealerListHtml = create_dealerRadioGroup(zip, searchRadius);

		$("#error_divErrorZip, div.errorClear").remove();
		$("#divErrorZip").removeClass("errorFocus");
		$("#"+inputId).removeClass("errorFocus");
		validated = "yes";
	}
	return validated;
}

function validate_stateForm(inputId, inputValue) {
	var selectOption = inputValue;
	if (selectOption == ""){
		$("#error_divErrorState, div.errorClear").remove();
		$('#divErrorState').errorMessage(
		{
			messageMain: "Please select your state."
		});
		$("#divErrorState").removeClass("errorFocus");
	}
	else if (selectOption != ""){
		$("#error_divErrorState, div.errorClear").remove();
		$("#divErrorState").removeClass("errorFocus");
		$("#"+inputId).removeClass("errorFocus");
	}
}

