//--------------------------------------------------------------
//	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 global_currentYear = 2012;
var stlInProgress = false;
var facebookDealer = "";
var facebookCharity;
var facebookFirstName;

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

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

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

	// instantiate_
	instantiate_dearSubaruCharacterCounter();
	//forms	
	instantiate_formBuildGeoLocation();
	instantiate_formDearSubaru();	
	instantiate_formGetGtpInfo();
	instantiate_formGtpRedemtion();	
	instantiate_formPopup282();
	instantiate_formPopup590();	
	instantiate_formReservationSti();
	instantiate_formRallyRaces();		
	instantiate_formUpdateSignup282();	
	instantiate_formFindDealerChinese();
	instantiate_formFindDealerPromos();
	instantiate_rolldownItems();
	instantiate_tabs();
	instantiate_tabsRallyDetail();
	instantiate_tooltip();

	// listen_
	listen_changeDealer();
	listen_changeOwnerEventsLink();
	listen_clueTips();
	listen_clueTipsGtp();	
	listen_formClose();	
	listen_alertClose();
	listen_formClosePopup();
	listen_formDogEntry();
	listen_dogCounter();
	listen_formOpen();
	listen_formReOpen();	
	listen_getMoreGeezSignUp();
	listen_getMoreGeezTracking();
	listen_gtpDisclaimerSymbol();
	listen_gtpModal();
	listen_gtpPrintModalClose();
	listen_gtpShowForm();
	listen_gtpSubmit();	
	listen_soaFoundation();
	listen_specials();
	listen_soa_foundation_questionnaire();
	listen_badgeOwnershipRollover();
	listen_industry_review_awards();
}); //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_clickStreamValues(formId) {
	var s = s_gi(s_account);
	var csSourceCode	= s.prop23;
	var csReferrer		= (s.prop24.length > 0) ? s.prop24 : "NULL";
	var csKeywords		= (s.prop25.length > 0) ? s.prop25 : "NULL";
	var csRKAC			= (s.campaign.length > 0) ? s.campaign : csReferrer+"|"+csKeywords+"|NULL|NULL";
	var clickStream		= $.cookie('soa-clickstream');
	var csPath			= s.prop21+"|"+s.prop10+"|"+csSourceCode+"|"+csRKAC+"|"+clickStream;

	//console.log("clickStreamSourceCode: "+csSourceCode+", clickStreamPath: "+csPath);
	$('#'+formId+' input[name=clickStreamSourceCode]').val(csSourceCode);
	if(csPath.length > 2000){
		csPath = csPath.slice(0,2000);
	}
	$('#'+formId+' input[name=clickStreamPath]').val(csPath);
}

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_distanceOptions(defaultSearchRadius) {
	var miles = distanceFrom;
	var options = "";
	if(defaultSearchRadius === undefined ){
		defaultSearchRadius = 20;
	}
	$(miles).each(function() {
		var mileMarker = this;
		var selected = "";
		if(mileMarker == defaultSearchRadius){
			selected = "selected";
		}else{
			selected = "";
		}
		options += "\n<option value='"+mileMarker+"' "+selected+" >"+mileMarker+" miles</option>";
	});

	return options;
} // end create_distanceOptions

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 smallEventsList = [];
	if (size == "282"){

	//	while (smallEventsList.length < 3){
			var xmlFile = 'events.html?month=';
			var xmlFilePath = linkPrefix + 'my-subaru/event-calendar/xml/';
			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 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  target="_blank" 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]);

	}else if (size == "590"){ //end if 282 This isnt the most efficient way to do this... we need a refactor
		var xmlFile = 'events.html?month=';
		var xmlFilePath = linkPrefix + 'my-subaru/event-calendar/xml/';
		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 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_modelOptionsDEPRECATED(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_modelOptions(modelYear, myModel, isSecureForm) {
	var responseObj = get_modelInfoAPI(modelYear, isSecureForm);
	var options = "<option value='noSelection'>Select a Vehicle</option>";
	for(var modelit in responseObj.models)
	{
		var mm = responseObj.models[modelit];
		if (mm.name === myModel) {
			options += "<option selected='selected' value='"+mm.code+"'>"+mm.name+"</option>";
		} else {
			options += "<option value='"+mm.code+"'>"+mm.name+"</option>";
		}
	}
	return options;
} // end create_modelOptions

function create_modelTrimOptionsDEPRECATED(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_modelTrimOptions(modelName, modelYear, myTrim, isSecureForm) {
	var modelCode = "";
	
	if(modelName.length == 3){
		modelCode = modelName;
	}else{
		modelCode = get_modelCode(modelName);
	}
	
	var responseObj = get_trimInfoAPI(modelYear, modelCode, isSecureForm);
	var options = "<option value='noSelection'>Select a Model</option>";
	
	for(var trimit in responseObj.trims){
		var mt = responseObj.trims[trimit];
		if (myTrim != undefined && mt.name.toLowerCase() == myTrim.toLowerCase()) {
			options += "<option selected='selected' value='"+mt.code+"'>"+mt.name+"</option>";
		} else {
			options += "<option value='"+mt.code+"'>"+mt.name+"</option>";
		}
	}
	return options;
}


function create_modelYearOptionsDEPRECATED(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_modelYearOptions(year, flag, filterYear) {
	year = parseInt(year);
	var prevYear = global_currentYear - 1;
	filterYear = filterYear ? filterYear : prevYear;
	var responseObj = get_modelYearsAPI();
	var options = "<option value='noSelection'>Select a Year</option>";
	
	for(var yearit in responseObj.modelYears){
		var my = responseObj.modelYears[yearit];
		
		if(my.year >= filterYear){
			if (my.year == year) {
				options += "<option selected='selected' value='"+my.year+"'>"+my.year+"</option>";
			} else {
				options += "<option value='"+my.year+"'>"+my.year+"</option>";
			}
		}
	}
	return options;
} // end create_modelYearOptions

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

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 {
			 if(this != "2005" ){
			 	options += "<option	 value='"+this+"'>"+this+""+"</option>";
			 }
		}
	});
	return options;
} // end create_yearOptions

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

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_commas(nStr) {
   nStr += '';
   var x = nStr.split('.');
   var x1 = x[0];
   var 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

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

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

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

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_modelCode(modelName){
	modelName = modelName.toLowerCase();
	
	switch(modelName){
		case "forester":
			return "FOR";
		case "impreza":
			return "IMP";		
		case "impreza wrx":
			return "WRX";
		case "legacy":
			return "LEG";
		case "outback":
			return "OBK";		
		case "tribeca":
			return "TRI";
		default:
			break;
	}
}

function get_modelName(modelCode){
	modelCode = modelCode.toLowerCase();
	
	switch(modelCode){
		case "for":
			return "Forester";
		case "imp":
			return "Impreza";		
		case "wrx":
			return "Impreza-Wrx";
		case "leg":
			return "Legacy";
		case "obk":
			return "Outback";		
		case "tri":
			return "Tribeca";
		default:
			break;
	}
}

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

/**
* Get all Model's Years list from the API
* @returns Years array modelYears array
*/
function get_modelYearsAPI() {
	var urlpath = linkPrefix+"secureform/vehicledata/modelyears";
    return getInfoJSON(urlpath);
}

/**
* Get all Model's from a given year  from the API
* @param modelYear
* @returns Models array
*/
function get_modelInfoAPI(modelYear, isSecureForm) {
	var urlpath = linkPrefix+"form/vehicledata/models/"+modelYear;
	
	if(isSecure()){
		urlpath = linkPrefix+"secureform/vehicledata/models/"+modelYear;
	}
	
    return getInfoJSON(urlpath);
}

/**
* Get all Trim's from a given model/year  from the API
* @param year
* @param modelCode
* @returns Trims array
*/
function get_trimInfoAPI(year,modelCode, isSecureForm) {
	var urlpath = linkPrefix+"form/vehicledata/trims/"+year+"/"+modelCode;
	
	if(isSecure()){
		urlpath = linkPrefix+"secureform/vehicledata/trims/"+year+"/"+modelCode;
	}
		
    var trimList  = getInfoJSON(urlpath);
	var trimList2 = copyArray(trimList.trims);	
	var addedTrims = 0;
	
	for(var trim_it in trimList.trims)
	{
		var trim = trimList.trims[trim_it];

		var urlpath2 = linkPrefix+"form/vehicledata/trim/"+year+"/"+modelCode+"/"+trim.code;
		if(isSecure()){
			var urlpath2 = linkPrefix+"secureform/vehicledata/trim/"+year+"/"+modelCode+"/"+trim.code;
		}
		var trimDetail = getInfoJSON(urlpath2);
		var has5door = false;
		for(var trans_it in trimDetail.trim.transmissions)
		{
			for ( var opt_it in trimDetail.trim.transmissions[trans_it].optionPackages)
			{
				if (trimDetail.trim.transmissions[trans_it].optionPackages[opt_it].name == "5-door Option")
				{
					has5door = true;
					break;
				}
			}
			if(has5door)
			{
				break;
			}
		}
		if(has5door){
			var newname = trim.name+" 5-door";
			var _newTrim = newTrim(newname,trim.code);
			var ind2 = parseInt(trim_it)+addedTrims;
			trimList2[ind2].name += " 4-door";
			addNext(trimList2,ind2,_newTrim);
			addedTrims++;
		}
	}
	var retObj = new Object();
	retObj.trims = trimList2;
	return retObj;
}

/**
* Get a  Trim's  information detail
* @param year
* @param modelCode
* @param trimCode
* @returns Trim detail object
*/
function get_trimDetailAPI(year,modelCode,trimCode) {
	var urlpath = linkPrefix+"secureform/vehicledata/trim/"+year+"/"+modelCode+"/"+trimCode;
	return getInfoJSON(urlpath);
}

/**
* Get a  Models's  resource
* @param year
* @param modelCode
* @returns Trim detail object

HTTP URI: /form/vehicledata/model/resource/{year}/{modelcode}/{resourcetype}
Method: GET
Input MIME:
Output MIME: application/json

*/
function get_modelResource(year,modelCode,resourceType) {
	var urlpath = linkPrefix+"secureform/vehicledata/model/resource/"+year+"/"+modelCode+"/"+resourceType;
	return getInfoJSON(urlpath);
}

/**
* Get a  Trim's  resource
* @param year
* @param modelCode
* @param trimCode
* @param resourceType
* @param colorCode
* @returns Trim detail object

HTTP URI: /form/vehicledata/trim/resource/{year}/{modelcode}/{trimcode}/{resourcetype}/{colorcode}
Method: GET
Input MIME:
Output MIME: application/json

*/
function get_trimResource(year,modelCode,trimCode,resourceType,colorCode, isSecureForm) {
	var urlpath = linkPrefix+"secureform/vehicledata/trim/resource/"+year+"/"+modelCode+"/"+trimCode+"/"+resourceType;
	
	if(!isSecure()){
		urlpath = linkPrefix+"form/vehicledata/trim/resource/"+year+"/"+modelCode+"/"+trimCode+"/"+resourceType;
	}
	if(colorCode == null){
		urlpath += "/";
	}else {		
		urlpath += "/"+colorCode;
	}	
	return getInfoJSON(urlpath);
}

function addNext(list,currPosition,node){
	list.splice(currPosition+1,0,node);
}

function newTrim(name,code){
	var arr = new Object();
	arr.name = name;
	arr.code = code;
	return arr;
}

function copyArray(original){
	var newone = new Array();
	for(var it in original){
		newone[it] = original[it];
	}
	return newone;
}

/**
* Get data from the API in JSON Format
* @returns A javascript object containing response
*/
function getInfoJSON(url){	
    var response;
    $.ajax({
        async:false,
        cache:false,
        url: url,
        type: "GET",
        contentType: "application/json",
        complete: function(xhr, textStatus) {
            response = xhr;
        }
    });
    var str = response.responseText;
    var obj = JSON.parse(str);
    return obj;
}

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_msrpAPI(year,model,trim,is5door)
{
	var trimObj = get_trimDetailAPI(year,model,trim);
	var msrp5dr = 0;
	var has5door = false;
	if(is5door)
	{
		for(var trans_it in trimObj.trim.transmissions)
		{
			for ( var opt_it in trimObj.trim.transmissions[trans_it].optionPackages)
			{
				if (trimObj.trim.transmissions[trans_it].optionPackages[opt_it].name == "5-door Option")
				{
					has5door = true;
					msrp5dr = trimObj.trim.transmissions[trans_it].optionPackages[opt_it].msrp;
					break;
				}
			}
			if(has5door)
			{
				break;
			}
		}
	}
	return trimObj.trim.msrp+msrp5dr;
}

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_purchaseDate(vin){
	var vinInfo = get_vinInfo(vin, true);
	var purchaseDate = "";

	if(vinInfo.status != 500){
		$(vinInfo.responseXML).find("salesInfo").each(function() {
			purchaseDate = $(this).find("dateSold").text();
		});

		if(purchaseDate === ""){
			var currentTime = new Date();
			purchaseDate = (currentTime.getMonth() + 1) + "/" + currentTime.getDate() + "/" + currentTime.getFullYear();
		}
	}

	return purchaseDate;
}

function get_vinInfo(vin, isSecure) {
	var url = "";
	
	if(isSecure){
		url = linkPrefix+'secureform/vehicle/salesinfo/';
	}else{
		url = linkPrefix+'form/vehicle/salesinfo/';
	}
	
	var vinInfo = $.ajax({
		type: "POST",
		data: "vin="+vin,
		url: url,
		async: false,
		cache: false
	});
	return vinInfo;
}

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

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_formBuildGeoLocation() {
	var init = $('#build_modalFormRegion').size();
	if (init != 0) {
		var urlZip = $.getUrlVar('zip');
		if (urlZip.length == 5 && buildZip.length == 0) {
			$('input#build_modalZip').val(urlZip);
			submit_BuildGeoLocation("form_buildGeoLocation");
		}
		else if (buildZip.length == 0) {
			$('#nav_primary li ul').css({'display':'none'});
			$("#build_modalFormRegion").modal({
				containerId: 'modalFindDealer'
			});
			listen_modalClose();
			listen_formSubmitBuildGeoLocation();
		}
	}
}

function instantiate_formDearSubaru() {
	var init = $('#form_dear_subaru').size();
	var fieldError = 0;
	var confirmError = 0;
	var lengthError = 0;
	var emailError = 0;
	var addressError = 0;
	var cityError = 0;
	var fnError = 0;

	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#dear_subaru_zipCode').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			emailValid = validate_zipCode(inputId, inputValue);
			if (emailValid == false){
					emailError = 1;
				}else{
					emailError = 0;
				}
		});

		// Email
		$('input#myEmail').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			emailValid = validate_email(inputId, inputValue);
			if (emailValid == false){
				fieldError = 1;
			}else{
				fieldError = 0;
			}
			// confirm email re validation
			if ($('input#confirmMyEmail').val().length != 0){
				var inputId = $('input#confirmMyEmail').attr("id");
				var email1 = $(this).val();
				var email2 = $('input#confirmMyEmail').val();
				confirmMyEmailValid = validate_emailConfirm(inputId, email1, email2);
				if (confirmMyEmailValid == false){
					confirmError = 1;
				}else{
					confirmError = 0;
				}

			}
		});

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

		// Home_Address
		$('input#dear_subaru_homeAddress').blur(function() {
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home address";
			addressValid = validate_presenceOf(inputId, inputValue, message);
			if (addressValid == false){
				addressError = 1;
			}else{
				addressError = 0;
			}
		});

		// Home_City
		$('input#dear_subaru_homeCity').blur(function(){
			var inputId = $(this).attr("id");
			var inputValue = $(this).val();
			var message = "Please enter your home city";
			cityValid = validate_presenceOf(inputId, inputValue, message);
			if (cityValid == false){
				cityError = 1;
			}else{
				cityError = 0;
			}
		});

		// 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";
			nameValid = validate_presenceOf(inputId, inputValue, message);
			if (nameValid == false){
				fnError = 1;
			}else{
				fnError = 0;
			}
		});

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

		// 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');
		}).bind('keypress', function(e) {
			return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
		});

		// 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 && story.length >= 10){
				delete_errorMessage(inputId);
				message = "Please enter your story";
			}else{
				if(story.length > 750){
					message = "750 characters allowed.";
					$("#error_story, div.errorClear").remove();
					$(this).errorMessage({
						messageTop: "Limit exceeded",
						messageMain: message
					});
				}else{
				  if(story.length < 10){
					message = "Please complete your story.";
					$("#error_story, div.errorClear").remove();
					$(this).errorMessage({
					messageTop: "This field must contain 10 - 750 characters.",
					messageMain: message
					});
				  }
				}
			}
		});

		// Submit_dear_subaru
		$('#dear_subaru_modal').on('click', "#submit_dear_subaru", function(e){
			e.preventDefault();
	
			var fieldErrors = 0;
	
			// loop through each required field and check for a value
			$('#form_dear_subaru 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 <= 1 || elementValue == "noSelection") {
					fieldErrors = 1;
					// trigger an error
					$("#error_"+elementID+", div.errorClear").remove();
					$('#'+elementID).errorMessage();
				}
	
				if($('#error_story').length > 0){
					fieldErrors = 1;
				}
		});

		if (fieldError > 0 || confirmError > 0 || emailError > 0 || addressError > 0
			|| cityError > 0 || fnError > 0 || lnError > 0){
				fieldErrors = 1;
			}
		if (fieldErrors == 0) { //Terms conditions has errorCont but it is validated here.

			var isChecked = $('input[name=terms]').attr('checked');
			if (isChecked == true) {
				$('#error_terms').hide();
				// prepend my_subaru_name and my_story_title
				var sn = $('input[name=my_subaru_name]').val();
				var cc = $('textarea#story').val();
				var story = "My Subaru: "+sn+"\n\n"+cc;
				$('textarea#story').val(story);

				// submit the form
				$('#form_dear_subaru form').serialize();
				$('#form_dear_subaru form').submit();

			}
			else if (isChecked != true){
				$('#error_terms').show();
			}
		}

		return false;
		});
	}
}

function instantiate_formFindDealerChinese() {
	var init = $("#findDealer_chinese").length;
	
	if(init > 0){
		$("#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;
			}
		});
		$(".submit_findDealer").click(function (){
			showLeavingSiteWindow();
			return false;
		});
	}		
}

function instantiate_formFindDealerPromos() {
	$('#form_truelove input#zip').bind('keypress', function(e) {
		return ( e.which!=8 && e.which!=0 && e.which!=13 && (e.which<48 || e.which>57)) ? false : true ;
	});
}

function instantiate_formGetGtpInfo() {
	var init = $('#getGtpInfo').length;
	
	if (init > 0) {
		var vinInput = $('#vin');
		
		vinInput.focus(function() {
			// clear the input field
			vinInput.val("");
		}).blur(function() {
			var inputValue = jQuery.trim(vinInput.val().toUpperCase());
			if (inputValue.length == 17 ) {
				// don't do anything
			}
			else {
				vinInput.val("Enter VIN - All 17 characters");
			}
		}).keypress(function(e) {
			if (e.which == 13) {
				e.preventDefault();
				submit_gtpCalculator();
				return false;
			}
		});
		
		if($.getUrlVar("vin")){
			submit_gtpCalculator();
		}
	}
} // 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() {
			$(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').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);
		});

		// 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 == 17) {
				$("#error_"+inputID+", div.errorClear").remove();
				$(this).removeClass("errorFocus");
			}
			else {
				$(this).val("Enter VIN - All 17 characters");
				$("#error_"+inputID+", div.errorClear").remove();
				$(this).errorMessage(
				{
					messageTop: "The VIN you entered is not valid.",
					messageMain: "Please enter all 17 characters."
				});
			}
		});

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

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_formRallyRaces() {
	var init = $("#form_rally_races").size();
	if (init != 0) {
		$('#race_categories').change(function() {
			var param = $(this).val();
			var redirectURL = linkPrefix + "enthusiasts/rally/events/index.html?year="+param;
			window.location.assign(redirectURL);
		});
	}
}

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_formUpdateSignup282() {
  var init = $("#form_282_update_signup").size();
	if (init != 0) {
	  /*
  		In-line validation
  		- alphabetical by comment name
  	*/
  	// address - zip
  	$('#form_282_update_signup input#zipCode1').blur(function() {
  		var inputId = $(this).attr("id");
  		var inputValue = $(this).val();
  		validate_zipCode(inputId, inputValue);
  	});

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

  	// email_Confirm
		$('#form_282_update_signup 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
  	$('#form_282_update_signup 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
  	$('#form_282_update_signup 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);
  	});

  	$("#form_282_update_signup .submit_form_282_update_signup").click(function(e) {
  		e.preventDefault();
  		submit_formUpdateSignup282();
  		return false;
  	});
	}
}

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_tabs() {
	var init = $('#my_partner_tabs').size();
	if (init != 0) {
		window.scrollTo(0,0);
		$('#my_partner_tabs').tabs();
	}
}

function instantiate_tabsRallyDetail() {
	var init = $(".rally_tabs .tabs li").size();
	//if the features-tabs id is used on the page load the .tabs
	if (init != 0) {
		$('.rally_tabs').tabs();
	}
}

function instantiate_tooltip() {
	var init = $('.bubbleInfo').size();
	if(init != 0){
		$('.bubbleInfo').each(function () {
		    // options
		    var distance = 10;
		    var time = 250;
		    var hideDelay = 500;

		    var hideDelayTimer = null;

		    // tracker
		    var beingShown = false;
		    var shown = false;

		    var trigger = $('.trigger', this);
		    var popup = $('.popup_bubble', this).css('opacity', 0);

		    // set the mouseover and mouseout on both element
		    $([trigger.get(0), popup.get(0)]).mouseover(function () {
		      // stops the hide event if we move from the trigger to the popup element
		      if (hideDelayTimer) clearTimeout(hideDelayTimer);

		      // don't trigger the animation again if we're being shown, or already visible
		      if (beingShown || shown) {
		        return;
		      } else {
		        beingShown = true;

		        // reset position of popup box
		        popup.css({
		          top: 0,
		          left: 100,
		          display: 'block' // brings the popup back in to view
		        })

		        // (we're using chaining on the popup) now animate it's opacity and position
		        .animate({
		          top: '-=' + distance + 'px',
		          opacity: 1
		        }, time, 'swing', function() {
		          // once the animation is complete, set the tracker variables
		          beingShown = false;
		          shown = true;
		        });
		      }
		    }).mouseout(function () {
		      // reset the timer if we get fired again - avoids double animations
		      if (hideDelayTimer) clearTimeout(hideDelayTimer);

		      // store the timer so that it can be cleared in the mouseover if required
		      hideDelayTimer = setTimeout(function () {
		        hideDelayTimer = null;
		        popup.animate({
		          top: '-=' + distance + 'px',
		          opacity: 0
		        }, time, 'swing', function () {
		          // once the animate is complete, set the tracker variables
		          shown = false;
		          // hide the popup entirely after the effect (opacity alone doesn't do the job)
		          popup.css('display', 'none');
		        });
		      }, hideDelay);
		    });
		 });
	}
}


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

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

function listen_changeDealer() {
	$('body').on('click', 'a.open_changeDealer', 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-profile/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-profile/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-profile/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() {
	$('body').on('mouseover', 'a.cluetip200', function(){
		$(this).cluetip({
			cluetipClass: 'tip200',
			splitTitle: '|',
			positionBy:'fixed',
			topOffset:20,
			leftOffset:-20
		});
	});

	$('body').on('mouseover', 'a.cluetip282', function(){
		$('.cluetip282').cluetip({
		cluetipClass: 'tip282',
		cluezIndex: 3500,
		splitTitle: '|',
		sticky:'true',
		closePosition: 'title',
		closeText: '<img src="/content/images/site/icons/WindowClose_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/WindowClose_aa.gif" width="12" height="12" >',
			positionBy:'fixed',
			topOffset:20,
			leftOffset:-20
		});
	}
} // end listen_clueTipsGtp

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_alertClose() {
	$('div.closeAlert').bind('click', function() {
		var formID = $(this).attr("rel");
		$("#"+formID).hide();
	});
}

function listen_formClosePopup() {
	$('body').on('click', 'a.closePopup', 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
			$.modal.close();

			$('iframe').each(function(){
				if($(this).attr("id") != 'dog_iframe'){
					$(this).remove();
				}
			});
		}
		return false;
	});
}

function listen_dogCounter() {
	if ($('#dogCounter > ul > li').length > 0)
	{
		$.ajax({
			type: "get",
			url: linkPrefix+"form/optin/dogtested",
			error: function (XMLHttpRequest, textStatus, errorThrown) {
			//alert(textStatus);
			},
			success: function(data, textStatus) {
				if (data != null && data > 0)
				{
    				var str = '' + data;
    				while (str.length < 6) {
        				str = '0' + str;
    				}
					var index = 0;
					$('#dogCounter > ul > li').each(function() {
						var bgPos = -1 * (str.substr(index, 1) * 1) * 28;
						$(this).css('background-position', '0 ' + bgPos + 'px');
						index++;
					});
				}
			}
		});
	}
}

function listen_formDogEntry() {
	$('body').on('click', 'a.dogsModalLink, a.dogLink', function(e){
		$('#modalLoaded').attr('src', 'http://fls.doubleclick.net/activityi;src=1762894;type=dogte338;cat=dogte046;ord=1;num=1?');
	
		var axel = Math.random() + "";
		var a = axel * 10000000000000;
		$('body').prepend('<iframe src="http://fls.doubleclick.net/activityi;src=1762894;type=dogte338;cat=dogte046;ord=1;num=' + a + '?" width="1" height="1" frameborder="0"></iframe>');
	
		var callCenterId = $.getUrlVar('source');
	
		if (callCenterId.length > 0)
			$('#callCenterId').val(callCenterId);
	
		var init = $('#vme_modalDogEntry').size();
	
		if (init > 0) {
			$('#formContent').show();
			$('#thankYouContent').hide();
	
			$("#vme_modalDogEntry").modal({
				containerId: 'modalDogEntry',
				persist: true
			});
	
			$('#modalOverlay').css('display', 'none');
	
			/******Validation******/
			$('input#firstName').blur(function() {
				var inputValue = $(this).val();
				validate_presenceOf('firstNameError', inputValue, "Please enter your first name.");
				if ($('#error_firstNameError').length > 0)
					$('#firstName').addClass('errorFocus');
				else
					$('#firstName').removeClass('errorFocus');
			});
			$('input#lastName').blur(function() {
				var inputValue = $(this).val();
				validate_presenceOf('lastNameError', inputValue, "Please enter your last name.");
				if ($('#error_lastNameError').length > 0)
					$('#lastName').addClass('errorFocus');
				else
					$('#lastName').removeClass('errorFocus');
			});
			$('input#email').blur(function() {
				var inputValue = $(this).val();
				validate_email($(this).attr("id"), inputValue);
			});
			$('input#zipCode').blur(function() {
				var inputValue = $(this).val();
				validate_zipCode('zipCode', inputValue);
				if ($('#error_zipError').length > 0)
					$('#zipCode').addClass('errorFocus');
				else
					$('#zipCode').removeClass('errorFocus');
			});
			$('input#dogName').blur(function() {
				var inputValue = $(this).val();
				validate_presenceOf('dogName', inputValue, "Please enter your dog's name.");
				if ($('#error_dogName').length > 0)
					$('#dogName').addClass('errorFocus');
				else
					$('#dogName').removeClass('errorFocus');
			});
		}
	});
}

function listen_formGetMoreGeezSignUp() {
	/*
		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);
	});

	// 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_get_more_geez").click(function(e){		
		var s = s_gi(s_account);
		s.tl(this,'o','get_more_gs~sign_up_complete');
		e.preventDefault();
		submit_getMoreGeezSignUp();
		return false;
	});
}

function listen_formOpen() {

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

		var server_error = $.getUrlVars()["failedlogin"];
		
		if(server_error == 'true'){
			$('#form_login .server_error_'+$.getUrlVars()["loginmethod"]).hide();
		}

		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':'44px'});
		}

		if (formID == 'form_my_profile_update_contact' && $(this).hasClass("move")){
			$("#"+formID).css({'top':'200px','left':'161px'});
		}

		if (formID == 'form_my_profile_update_contact'){
			$('#form_my_profile_update_contact img.ajax-spinner').hide();
		}

		$("#"+formID+" .body .close_button a.closePopup").click(function() {
  				$("#"+formID).css({display:"none"});
						if (formID == 'oil_chart1'){
					$("#modalOverlay").css({display:"none"});	
				}
		});

		
		if (formID == 'oil_chart1'){

		   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: "oil_modal"});
		   $('#modalOverlay').css({display: "block", height:($(document).height().toString() + "px"), overflow:"hidden"});
		   $("#"+formID + " a").attr('href',url);

		   var windowWidth = Math.round(($(document).width() - $("#"+formID).width())/2);
		   var windowHeight = Math.round(($(window).height() - $("#"+formID).height())/2);
		   $("#"+formID).css({'left': windowWidth.toString()+'px', 'top': windowHeight.toString()+'px'});
		   
		   if ($.browser.msie && $.browser.version.substr(0, 1) < 7){
			$("#oil_modal").css({top:"0px", left: "0px", position: "absolute"});
			$("#"+formID).css({top:"200px", left: windowWidth, position: "relative"});
			scroll(0,0);
		   }else{}
		}

		/* SOA Foundation Questionnaire BEGIN */

		// soa_foundation_questionnaireq1
		if (formID == 'soa_foundation_questionnaireq1'){

			$('.soa_foundation_questionnaire .body .showForm ul li input:radio').attr('checked', false);
			$('.soa_foundation_questionnaire .body .showForm ul li input').attr("disabled", false);
			$('.soa_foundation_questionnaire .body .showForm ul li .msgYes').hide();
			$('.soa_foundation_questionnaire .body .showForm ul li .msgNo').hide();

			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 + " a").attr('href',url);

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

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


		/* SOA Foundation Questionnaire END */


		/*SOA Foundation recent grants*/
		if (formID == 'foundation_recent_grants1' || formID == 'foundation_recent_grants2'){

			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 + " a").attr('href',url);

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

			
			$("#"+formID).css({top:"20%", left: windowWidth, position: "fixed"});
		}

		/*END SOA Foundation recent grants*/


		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;

			$("#"+formID).css({top:"50%", left: windowWidth, position: "fixed"});
		}

		if (formID == 'dog_park'){
			var url = $(this).attr('href');

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

			$('.frame_content > div').html("<iframe id='dog_iframe' src='http://ngcresources.nationalgeographic.com/dog-park-locator/' norezise='noresize' frameborder='0' border='0' cellspacing='0' scrolling='no' width='945' marginwidth='0' marginheight='0' height='680' allowtransparency='true'>");

			scroll(0,200);
		}

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

function listen_formShareTheLove() {
	var callCenterId = $.getUrlVar('source');

	if (callCenterId.length > 0)
		$('#callCenterId').val(callCenterId);

	var init = $('#vme_modalShareTheLove').size();
	if (init != 0) {
		$("#vme_modalShareTheLove").modal({
			containerId: 'modalShareTheLove',
			persist: true
		});

		$('#stepOne').removeClass('hide');
		$('#stepTwo').addClass('hide');
		$('#stepThree').addClass('hide');
		$('#shareStepOne').addClass('hide');
		$('#shareStepTwo').addClass('hide');

		$('#modalOverlay').css('display', 'none');

    	$('img.close').click(function() { $.modal.close(); });
    	$('img.closeFull').click(function(){ 
			$.modal.close(); 
			var s=s_gi(s_account); s.linkTrackVars='None'; s.linkTrackEvents='None'; s.tl(this,'o','share_the_love_2011:learn_more:select_your_charity_register_submit_close'); 
		});
    	$('.continue').click(function(){ listen_formShareTheLoveStepTwo(); });
    	$('.back').click(function(){ 	
			$('#stepTwo').addClass('hide'); $('#stepOne').removeClass('hide'); 
			var s=s_gi(s_account); s.linkTrackVars='prop17'; s.linkTrackEvents='None'; s.prop17="share_the_love_2011:register:select_your_charity_step_2"; s.tl(this,'o','share_the_love_2011:learn_more:select_your_charity_register_back_to_step2');
		});
    	$('input.submit_modalShareTheLove').click(function(e){
        	e.preventDefault();
        	listen_formShareTheLoveStepThree();
    	});
		$('.share').click(function() { listen_formShareTheLoveShareStepOne(); });
		$('#vme_modalShareTheLove input:text').focus(function() {
			$(this).css('color', '#000');
		});
		$('.submit_findDealer_modal1').click(function(e){
			e.preventDefault();
			listen_formShareTheLoveShareStepTwo($('#shareStepOne #dealerZip_body').val());			
		});
		
		$('#shareFacebookLink').click(function() {listen_formShareTheLoveShareStepThree()});
		
		$('.submit_findDealer_modal2').click(function (e){
			e.preventDefault();
			create_dealerRadioGroup($('#shareStepTwo #dealerZip_body').val(), 100, true); 
			setDealerValue();
		});
		
		$('#shareStepOne #dealerZip_body').keypress(function(e) {
			if (e.keyCode == 13) {
				e.preventDefault();
				listen_formShareTheLoveShareStepTwo($('#shareStepOne #dealerZip_body').val());
			}
		});
		
		$('#shareStepTwo #dealerZip_body').keypress(function(e) {
			if (e.keyCode == 13) {
				e.preventDefault();
				create_dealerRadioGroup($('#shareStepTwo #dealerZip_body').val(), 100, true); 
				setDealerValue();
			}
		});
		
		$('.dealerGroup').on('click', "input[name=dealer]",  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>";
				facebookDealer = dealer[0];
				$('#dynamicDealerList li p').show();
				$(this).next().hide();
				$('#dealerInfo').insertAfter(this);
				$('#dealerInfo').empty().append(dealerInfo);
				
				updateFacebookDealer();
			}
		});

		$('.gtp_cluetip200').cluetip({
			cluetipClass: 'tip200 stlTip',
			splitTitle: '|',
			positionBy:'fixed',
			topOffset:20,
			leftOffset:-20
		});

		/******Validation******/
		$('input#phoneSTL').blur(function () {
			var inputValue = $(this).val();
			var inputId = $(this).attr("id");
			if(inputValue != "Phone (optional)"){
				validate_phoneNumber(inputId, inputValue);
			} else {
				$("#error_"+inputId+", div.errorClear").remove();
				$("#"+inputId).removeClass("errorFocus");
			}
		});
		
		$('input#email').blur(function() {
			var inputValue = $(this).val();
			validate_email($(this).attr("id"), inputValue);
		});
		$('input#email2').blur(function() {
			$('#error_email2').remove();
			if ($('input#email').val() != $('input#email2').val()){
				$(this).errorMessage(
				{
					containerId: 'email2',
					messageTop: "Your email must match.",
					messageMain: "Please make sure your email matches the confirm email"
				});
				$('#email2').addClass('errorFocus');
			}
		});
		$('input#firstName').blur(function() {
			var inputValue = $(this).val() == 'First Name' ? '' : $(this).val();
			validate_presenceOf('firstNameError', inputValue, "Please enter your first name.");
			if ($('#error_firstNameError').length > 0)
				$('#firstName').addClass('errorFocus');
			else
				$('#firstName').removeClass('errorFocus');
		});
		$('input#lastName').blur(function() {
			var inputValue = $(this).val() == 'Last Name' ? '' : $(this).val();
			validate_presenceOf('lastNameError', inputValue, "Please enter your last name.");
			if ($('#error_lastNameError').length > 0)
				$('#lastName').addClass('errorFocus');
			else
				$('#lastName').removeClass('errorFocus');
		});
		$('input#address').blur(function() {
			var inputValue = $(this).val() == 'Street Address' ? '' : $(this).val();
			validate_presenceOf($(this).attr("id"), inputValue, "Please enter your street address.");
		});
		$('input#city').blur(function() {
			var inputValue = $(this).val() == 'City' ? '' : $(this).val();
			validate_presenceOf('cityError', inputValue, "Please enter your city.");
			if ($('#error_cityError').length > 0)
				$('#city').addClass('errorFocus');
			else
				$('#city').removeClass('errorFocus');
		});
		$('select#stateCode').blur(function() {
			var selectOption = $(this).val() == '--' ? '' : $(this).val();
			validate_presenceOf('stateError', selectOption, "Please select your state.");
		}).change(function() {
			var selectOption = $(this).val() == '--' ? '' : $(this).val();
			validate_presenceOf('stateError', selectOption, "Please select your state.");
		});
		$('input#zipCode').blur(function() {
			var inputValue = $(this).val() == 'Zip Code' ? '' : $(this).val();
			validate_zipCode('zipError', inputValue);
			if ($('#error_zipError').length > 0)
				$('#zipCode').addClass('errorFocus');
			else
				$('#zipCode').removeClass('errorFocus');
		});
		$('input#dealerZip_body').blur(function() {
			var inputValue = $(this).val() == 'Zip Code' ? '' : $(this).val();
			validate_zipCode('zipErrorDealer', inputValue);
			if ($('#error_zipError').length > 0)
				$('#dealerZip_body').addClass('errorFocus');
			else
				$('#dealerZip_body').removeClass('errorFocus');
		});
		$('input#newVIN').blur(function() {
			var vin = jQuery.trim($('input#newVIN').val().toUpperCase());
			$('#error_vinError').remove();
			if(vin.length < 17 && vin != 'VIN'){
				$(this).errorMessage(
				{
					containerId: 'vinError',
					messageTop: "The VIN you entered is not valid.",
					messageMain: "Please re-enter all 17 characters"
				});
				$('#newVIN').addClass('errorFocus');
			}
			else if (vin == 'VIN') {
				validate_presenceOf('vinError', '', "Please enter your vehicle's VIN.");
			} else {
				if (validate_vin(vin)) {
					delete_errorMessage('vinError');
					$('#newVIN').removeClass('errorFocus');
				} else {
					$(this).errorMessage(
					{
						containerId: 'vinError',
						messageTop: "The VIN you entered is not valid.",
						messageMain: "Please re-enter all 17 characters correctly"
					});
					$('#newVIN').addClass('errorFocus');
				}
			}
		});

		listen_findDealerModal();
	}
}

function listen_formShareTheLoveStepTwo() {
	$('.req').blur();
	if ($('.errorCont').length == 0) {
		$('#stepOne').addClass('hide');
		$('#stepTwo').removeClass('hide');
		var s=s_gi(s_account); s.linkTrackVars='prop17'; s.linkTrackEvents='None'; s.prop17="share_the_love_2011:register:select_your_charity_step_2"; s.tl(this,'o','share_the_love_2011:learn_more:select_your_charity_register_step2');
		$('input.chk_donate').attr('checked', false);
		facebookFirstName = $('#firstName').val();
	}
}

function listen_formShareTheLoveStepThree() {	
	if ($('input.chk_donate:checked').length == 0) {
		validate_presenceOf('donationError', '', "Please select between one and five charities to donate to.");
	} else {
		$('#error_donationError').remove();

		//Setup the donated values
		$('input.donation').val(0);
		var donatedValue = Math.round(250 / $('input.chk_donate:checked').length * 100) / 100;
		$('input.chk_donate:checked').each(function() {
			var valueContainerId = $(this).attr("id").replace('chk_', '');
			$('#' + valueContainerId).val(donatedValue);
			
		});
		
		facebookCharity = "";
		
		var facebookArray = [];
		
		if($('#chk_amf').is(':checked')){
			facebookArray.push("American Forests");
		}
		
		if($('#chk_asp').is(':checked')){
			facebookArray.push("ASPCA");
		}
		
		if($('#chk_maw').is(':checked')){
			facebookArray.push("Make-A-Wish Foundation");
		}
		
		if($('#chk_mow').is(':checked')){
			facebookArray.push("Meals On Wheels");
		}
		
		if($('#chk_sol').is(':checked')){
			facebookArray.push("Special Olympics");
		}
		
		if(facebookArray.length == 1){
			facebookCharity = facebookArray[0];	
		} else if(facebookArray.length == 2) {
			facebookCharity = facebookArray[0] + " and " +	facebookArray[1];
		} else {
			for(var i=0; i<facebookArray.length; i++){
				if(i == 0){
					facebookCharity = facebookArray[i];
				} else if(i != (facebookArray.length - 1)) {
					facebookCharity += ", "+facebookArray[i];
				} else {
					facebookCharity += " and "+facebookArray[i];
				}
			}
		}
		
		if ($('input.chk_donate:checked').length == 1) {
			$('#charityCopy').text('Your $250 donation will be distributed to the following charity:');
		} else {
			$('#charityCopy').text('Your $250 donation will be evenly distributed to the following charities:');
		}
		
		if($('input#phoneSTL').val() == 'Phone (optional)'){
			$('#homePhone').val("");
		} else {
			$('#homePhone').val($('input#phoneSTL').val());
		}
		
		var formData = $('#form_modalShareTheLove').serialize();
		var formUrl = $('#form_modalShareTheLove').attr("action");
		
		var charitiesTracking;
		
		for(var j=0; j <facebookArray.length; j++){
			charitiesTracking += facebookArray[j]+',';	
		}
		
		//Tracking
		var s=s_gi(s_account); 
		s.linkTrackVars='prop17,eVar15,events'; 
		s.linkTrackEvents='event36'; 
		s.prop17="share_the_love_2011:register:select_your_charity_step_3_submit"; 
		s.eVar15=charitiesTracking;
		s.events="event36";
		s.tl(this,'o','share_the_love_2011:learn_more:select_your_charity_register_step3_submit');

		if (stlInProgress)
			return;

		stlInProgress = true;

		$.ajax({
			type: "post",
			url: linkPrefix+"secureform/optin/sharethelove",
			data: formData,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('#stepTwo').addClass('hide');
				$('#error').removeClass('hide');
				stlInProgress = false;
			},
			success: function(data, textStatus) {
				$('.chosenCharity').addClass('hide');
				$('#stepTwo').addClass('hide');
				$('#stepThree').removeClass('hide');
				$('input.chk_donate:checked').each(function() {
					var divId = 'img_' + $(this).attr("id").replace('chk_', '');
					$('#' + divId).removeClass('hide');
				});
				stlInProgress = false;
			}
		});
	}
}

function listen_formShareTheLoveShareStepOne() {
	var s=s_gi(s_account); 
	s.linkTrackVars='prop17'; 
	s.linkTrackEvents='None'; 
	s.prop17="share_the_love_2011:share:select_your_dealer_step_1";
	s.tl(this,'o','share_the_love_2011:share:where_did_you_buy_your_subaru_step_1');
	
	$('#stepThree').addClass('hide');
	$('#shareStepOne').removeClass('hide');
}

function listen_formShareTheLoveShareStepTwo(zipValue) {
	if ($('.errorCont').length == 0) {
		var s=s_gi(s_account); 
		s.linkTrackVars='prop17'; 
		s.linkTrackEvents='None'; 
		s.prop17="share_the_love_2011:share:select_your_dealer_step_2";
		s.tl(this,'o','share_the_love_2011:share:where_did_you_buy_your_subaru_step_2');
		$('#shareStepOne').addClass('hide');
		$('#shareStepTwo').removeClass('hide');
		$('#shareStepTwo #dealerZip_body').val(zipValue);
		create_dealerRadioGroup(zipValue, 100, true);
		setDealerValue();
	}
}

function listen_formShareTheLoveShareStepThree() {
	var s=s_gi(s_account); 
	s.linkTrackVars='prop17'; 
	s.linkTrackEvents='None'; 
	s.prop17="share_the_love_2011:share:select_your_dealer_step_3";
	s.tl(this,'o','share_the_love_2011:share:select_your_dealer_step_3');
	$.modal.close();
}

function setDealerValue() {
	var dealer = $('input[name=dealer]').attr("title").split("~");
	facebookDealer = dealer[0];
	updateFacebookDealer();
}

function updateFacebookDealer() {
	var currentServerURL = secureServer;
	var normalServerURL = currentServerURL.replace('https', 'http');
	facebookCopy = 'http://www.facebook.com/sharer.php?s=100&p[title]=Subaru "Share the Love" event&p[url]='+ currentServerURL +'/my-subaru/share-the-love.html&p[images][0]='+ normalServerURL +'/content/images/site/modal_stl_facebook_share.jpg&p[summary]='+ facebookFirstName +' just purchased or leased a new Subaru from '+ facebookDealer +' and donated $250 to these charities: '+ facebookCharity +'. Learn more about the Subaru "Share the Love" event at subaru.com/share.';
	$("#shareFacebookLink").prop("href", facebookCopy);
}
updateFacebookDealer();
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", "chineseDealerSubmit", inputValue, defValue);	

	if ($(".errorCont").length > 0){
		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: "42%", position: "fixed"});
	}

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

function listen_formReOpen() {
	$('body').on('click', 'a.reOpen_form', 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_formSubmitBuildGeoLocation() {
	var zipSearch = $('#form_buildGeoLocation input.submit_formBuildGeoLocation');
	$('input#build_modalZip').keypress(function(e) {
		if(e.which == 13) {
			e.preventDefault();
			zipSearch.click();
		}
	});
	zipSearch.click(function(e) {
		e.preventDefault();
		var inputValue = $('input#build_modalZip').val().replace(/[^\d]/g, "").substr(0, 5);
		if(inputValue.length == 5 && validate.isValidZipCode(inputValue)) {
			$('input#build_modalZip').val(inputValue);
			submit_BuildGeoLocation("form_buildGeoLocation");
		} else {
			$('input#build_modalZip').val("Enter ZIP Code");
			$("#error_build_modalZip, div.errorClear").remove();
			$('#form_buildGeoLocation #build_modalZip').errorMessage({
				messageTop : "ZIP Code",
				messageMain : "The info entered is not a valid Zip Code"
			});
		}
	});
}


function listen_getMoreGeezSignUp(){
	var init = $('.getmoregs_scoop').size();
	if(init!=0){
		var registerVar = $.getUrlVar('register');
		if (registerVar == "true"){
			$('.modal_geez_sign_up').modal({
				containerId: 'moreGeezSignUp',
				persist: true
			});
			var fullHeight = $(document).height();
			$('#modalOverlay').css({'top':'0px','height': fullHeight, 'overflow':'hidden'});
			$('#moreGeezSignUp').css({'top':'30px', 'left':'50%', 'margin-left':'-141px'});

			listen_formGetMoreGeezSignUp();
		}

		$('#get_more_geez_sign_up').click(function(){
			$('.modal_geez_sign_up').modal({
				containerId: 'moreGeezSignUp',
				persist: true
			});
			var s = s_gi(s_account);
			s.tl(this,'o','get_more_gs~sign_up_now');
			var fullHeight = $(document).height();
			$('#modalOverlay').css({'top':'0px','height': fullHeight, 'overflow':'hidden'});
			$('#moreGeezSignUp').css({'top':'533px', 'left':'50%', 'margin-left':'-141px'});
 
			listen_formGetMoreGeezSignUp();
		});

		$('#form_more_geez_sign_up .close_button_moreGeez').click(function(e){
			$('#form_more_geez_sign_up .showMessage').empty().slideUp('slow');
			$('#form_more_geez_sign_up .showForm').slideDown("slow");

			$.modal.close();
		});
	}

	$("a.button_test_video").click(function(){
		listen_getMoreGeezButtonHighlighting("watch_videos");
	});
	$("a.button_test_card").click(function(){
		listen_getMoreGeezButtonHighlighting("send_g_cards");
	});
	$("a.button_test_face").click(function(){
		listen_getMoreGeezButtonHighlighting("gs_your_face");
	});
	$("a.button_test_none").click(function(){
		listen_getMoreGeezButtonHighlighting();
	});
}

function listen_getMoreGeezButtonHighlighting(buttonToHighlight){
	//implementation:

	$("#get_more_geez .secondary_nav li").each(function(){
		$(this).removeClass("selected");
		if ($(this).attr("id") == buttonToHighlight){
			$(this).addClass("selected")
		}
	});
}

function listen_getMoreGeezTracking(){

	$(".get_more_gs-tabs #get_more_gs-tabs a#tab1").click(function(){
		var s = s_gi(s_account);
		s.tl(this,"o","get_more_gs-wrx");
	});

	$(".get_more_gs-tabs #get_more_gs-tabs a#tab2").click(function(){
		var s = s_gi(s_account);
		s.tl(this,"o","get_more_gs-wrx_sti");
	});
}

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').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() {
		$(this).val(jQuery.trim($(this).val()));
		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() {
		$(this).val(jQuery.trim($(this).val()));
		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() {
		$(this).val(jQuery.trim($(this).val()));
		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() {
		$(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').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);
	});

	$("#submit_print_my_gtp").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();
		$('#defaultGtpMessage').show();
		$('#getGtpInfo').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

// soa partnership questionaire iframe popup
function listen_soaFoundation() {
	$('#soaFoundation').click(function () {
		$("#vme_modalSOAFoundation").modal({
			containerId: 'modalSOAFoundation',
			persist: true
		});

		$('#modalOverlay').css('display', 'none');

		$('#closeGizmo').click(function(){
			$.modal.close();
		});
	});
}

function listen_soa_foundation_questionnaire(){

	$('body').on('click', '.soa_foundation_questionnaire .body .showForm ul li input.response', function(e){

		var response = $('.soa_foundation_questionnaire .body .showForm ul li input:radio:checked').val();
		var popUpID = $(this).parent().parent().parent().parent().parent().attr("id");;
		var formID = popUpID;


		if (popUpID == "soa_foundation_questionnaireq1") {

			$('.soa_foundation_questionnaire').on('click', '.body .showForm ul li .msgNo a', function(e){
				window.location.assign("#guidelines");
			});

			if (response == "true"){

				$("#soa_foundation_questionnaireq1").hide();
				formID ="soa_foundation_questionnaireq2"
				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();
				});

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

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

			}else{
				$('#soa_foundation_questionnaireq1 .body .showForm ul li input').attr("disabled", true);
				$('#soa_foundation_questionnaireq1 .msgNo').show();
			}


		}

		if (popUpID == "soa_foundation_questionnaireq2") {

			if (response == "false"){

				$("#soa_foundation_questionnaireq2").hide();
				formID ="soa_foundation_questionnaireq3"
				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();
				});

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

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

			}else{
				$('#soa_foundation_questionnaireq2 .body .showForm ul li input').attr("disabled", true);
				$('#soa_foundation_questionnaireq2 .body .showForm ul li .msgYes').show();
				setTimeout('window.location.assign(linkPrefix+"company/soa-foundation/index.html");',5000);
			}


		}

		if (popUpID == "soa_foundation_questionnaireq3") {

			if (response == "true"){

				$("#soa_foundation_questionnaireq3").hide();
				formID ="soa_foundation_questionnaireq4"
				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();
				});

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

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

			}else{
				$('#soa_foundation_questionnaireq3 .body .showForm ul li input').attr("disabled", true);
				$('#soa_foundation_questionnaireq3 .body .showForm ul li .msgNo').show();
				setTimeout('window.location.assign(linkPrefix+"company/soa-foundation/index.html");',5000);
			}


		}

		if (popUpID == "soa_foundation_questionnaireq4") {

			if (response == "false"){

				$("#soa_foundation_questionnaireq4").hide();
				formID ="soa_foundation_questionnaireq5"
				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();
				});

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

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

			}else{
				$('#soa_foundation_questionnaireq4 .body .showForm ul li input').attr("disabled", true);
				$('#soa_foundation_questionnaireq4 .body .showForm ul li .msgYes').show();
				setTimeout('window.location.assign(linkPrefix+"company/soa-foundation/index.html");',5000);
			}


		}

		if (popUpID == "soa_foundation_questionnaireq5") {

			if (response == "true"){

				$("#soa_foundation_questionnaireq5").hide();
				formID ="soa_foundation_questionnaireq6"
				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();
				});

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

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

			}else{
				$('#soa_foundation_questionnaireq5 .body .showForm ul li input').attr("disabled", true);
				$('#soa_foundation_questionnaireq5 .body .showForm ul li .msgNo').show();
				setTimeout('window.location.assign(linkPrefix+"company/soa-foundation/index.html");',5000);
			}


		}

		if (popUpID == "soa_foundation_questionnaireq6") {

			if (response == "true"){
				$('#soa_foundation_questionnaireq6 .body .showForm ul li input').attr("disabled", true);
				$('#soa_foundation_questionnaireq6 .body .showForm ul li .msgYes').show();
			}else{
				$('#soa_foundation_questionnaireq6 .body .showForm ul li input').attr("disabled", true);
				$('#soa_foundation_questionnaireq6 .body .showForm ul li .msgNo').show();
				setTimeout('window.location.assign(linkPrefix+"company/soa-foundation/index.html");',5000);
			}


		}
	$("#"+formID+" .body .close_button a.closePopup").click(function() {
  				$("#"+formID).css({display:"none", position:"fixed"});
		});

	});
}

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

function listen_badgeOwnershipRollover(){
	if($('#badge_list').size() != 0){
		if ($.browser.msie && $.browser.version.substr(0,1)<7) {
			$('.rollover_legend').css("display", "none");
		}
		$('#badge_list li').hover(function() {
			var hPath = $(this).attr("title");
			$('#badge_image').attr("src", pathPrefix + "articles/badgeofownership/icons/" + hPath + "_lg.png");
		},function(){});
	}
}

function listen_industry_review_awards(){
	if($('#reviews_awards_model_navigation').size() != 0){

		clean_panels();
		var review_vehicle = $.getUrlVar('vehicle');

		switch(review_vehicle){
			case "impreza-wrx":
				set_vehicle_load('imprezawrx');
			break;

			case "forester":
				set_vehicle_load('forester');
			break;

			case "legacy":
				set_vehicle_load('legacy');
			break;

			case "outback":
				set_vehicle_load('outback');
			break;

			case "tribeca":
				set_vehicle_load('tribeca');
			break;

			default:
				set_vehicle_load('impreza');
		}

		$('#reviews_awards_nav li').click(function() {
			clean_panels();
			$(this).addClass('active_model');
			var panelID = $(this).attr("title") + '_reviews_awards_panel';
			$('#'+panelID+'').fadeIn("slow");
		});
	}
}

function clean_panels(){
	$('#reviews_awards_nav li').each(function(){
		$(this).removeClass('active_model');
	});
	$('.reviews_awards_panel').each(function(){
		$(this).hide();
	});
}

function set_vehicle_load(vehicle_name){
	$('#reviews_awards_nav li').each(function(){
		if($(this).attr("title") == vehicle_name){
			$(this).addClass('active_model');
		}
	});
	var panel_name = vehicle_name + '_reviews_awards_panel';
	$('#'+panel_name+'').show();
}

//-----------------------------------------------------------------------------------
//8.0 submit_
//-----------------------------------------------------------------------------------
function submit_BuildGeoLocation(formId) {
	var formData = $('#'+formId).serialize();
	var redirectURL = window.location.pathname + window.location.search;
	$.ajax({
		type: "post",
		url: linkPrefix+"tools/gtp/user/setvisitorzipcode",
		data: formData,
		error: function() {			
			$('input#build_modalZip').val("Enter ZIP");			
		},
		success: function() {
			window.location.assign(redirectURL);
		}
	});
}

function submit_formUpdateSignup282() {
  // check for obvious errors
	var fieldErrors = $('#form_282_update_signup').find("div.errorCont").length;
	
	// loop through each required field and check for a value
	$('#form_282_update_signup').find("input.required").each(function(index, thisElement) {
		var elementID = $(thisElement).attr("id");
		var elementValue = $(thisElement).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_282_update_signup').serialize();
		var formUrl = $('#form_282_update_signup').attr("action");

		$.ajax({
			type: "post",
			url: formUrl,
			data: formData,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('.form_update_signup .showForm').slideUp("slow");
				var errorMessage = "<p><strong>Error!</strong></p><p>There was an error processing your request, please try again.</p>";
				$('.form_update_signup  .showMessage').empty().append(errorMessage).slideDown('slow');
			},
			success: function(data, textStatus) {
				$('.form_update_signup  .showForm').slideUp("slow");
				var successMessage = "<p><strong>Consider yourself looped in!</strong></p><p>As soon as any new information about the 2013 Subaru BRZ becomes available, you'll be the first to know.</p>";
				$('.form_update_signup  .showMessage').empty().append(successMessage).slideDown('slow');
			}
		});
	}
}

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

	// loop through each required field and check for a value
	$('#form_more_geez_sign_up 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_more_geez_sign_up form').serialize();

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

		$.ajax({
			type: "post",
			url: formUrl,
			data: formData,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$('#form_more_geez_sign_up .showForm').slideUp("slow");
				var errorMessage = "<h3>Error!</h3><p>There was an error processing your request, please try again or <a class='close_button close_button_moreGeez' rel=' | refresh' >close window</a>.</p>";
				$('#form_more_geez_sign_up .showMessage').empty().append(errorMessage).slideDown('slow');
			},
			success: function(data, textStatus) {
				$('#form_more_geez_sign_up .showForm').slideUp("slow");
				var successMessage = "<h3>Thank You!</h3><p>Your request to learn more about WRX has been sent. <a class='close_button close_button_moreGeez' rel=' | refresh' >Close Window</a></p>";
				$('#form_more_geez_sign_up .showMessage').empty().append(successMessage).slideDown('slow');
			}
		});
	}


}

function submit_gtpCalculator() {
	var submitId = $('a.gtp_calculator').attr("id");
	var vin = jQuery.trim($('#vin').val().toUpperCase());
	//Remove spaces in the middle
	vin = vin.replace(/\W+/g,'');

	if (vin.length == 17) {						
		if (submitId == "submit_gtp" && !($.getUrlVar("vin") && $.getUrlVar("offercode")) ) {
			
			var s = s_gi(s_account);
            s.linkTrackVars="prop40,eVar44,events";
            s.linkTrackEvents="event35";
            s.prop40= vin;            
            s.eVar44 = vin; 
            s.events="event35";
            s.tl(this, 'o', 'guaranteed-trade-in-value:get-trade-in-value_vin_submit');
        }
		
		// 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") {
				
				$("#gtpOverview").hide();
				$("#gtpRules").show();
				$(".rolldown_container").show();				
				$("#getGtpValueNav").addClass("selected");
				$("#overviewNav").removeClass("selected");
				
				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,false);

				// 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);
				$('#printMileage').empty().append(gtpMileageFormat);
				$('#printVin').empty().append(gtpVin);
				$('#printGtpValue').empty().append(gtpCurrency);
				$('#printGtpEndDate').empty().append(gtpEndDate);

				$('.showGtpForm').hide();
				$('.gtpSuccess').show();
				$('#defaultGtpMessage').hide();
				$('#getGtpInfo').hide();
				$('#gtp_error1').hide();
				$('#gtp_error2').hide();
				$('#gtp_error3').hide();

			}
			else if (gtpStatus == "1") {
				$('#defaultGtpMessage').hide();
				$('#gtp_error1').show();
				$('#gtp_error2').hide();
				$('#gtp_error3').hide();
			}
			else if (gtpStatus == "2") {
				$('#defaultGtpMessage').hide();
				$('#gtp_error2').show();
				$('#gtp_error1').hide();
				$('#gtp_error3').hide();
			}
			else if (gtpStatus == "3") {
				$('#defaultGtpMessage').hide();
				$('#gtp_error3').show();
				$('#gtp_error1').hide();
				$('#gtp_error2').hide();
			}
		});	
	} else {
		$('input#vin').val("Enter VIN - All 17 characters");
		$('#defaultGtpMessage').hide();
		$('#gtp_error1').show();
		$('#gtp_error2').hide();
		$('#gtp_error3').hide();
	}
} // 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 - 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
				var 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 address2 = $("#form_print_gtp #homeAddress2").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
	var 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.address2").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.address2").append(address2);
	$("#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);

	// 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) {
		if(isChecked){
			// 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_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();
	}
}

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


//-----------------------------------------------------------------------------------
//10.0 validate_
//-----------------------------------------------------------------------------------

function validate_apr(inputId, inputValue) {
	var isValid = true;
	var value = jQuery.trim(inputValue.toLowerCase());
	var regVal	  = /^[[0-9]+[\.]?[0-9]+]*$/;
	var regValPor = /^[[0-9]+[\.]?[0-9]+[\%]]*$/;
	var regValPor2 = /^[[0-9]+[\%]]*$/;
	var regEx = new RegExp(regVal);
	var regExPor = new RegExp(regValPor);
	var regExPor2 = new RegExp(regValPor2);

	if (inputValue.length == 0 || inputValue == "0" ) {
		$('input[name='+inputId+']').val("0");
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}else{
		if (value.match(regEx) || inputValue.length == 1 || value.match(regExPor) || value.match(regExPor2)) {
			if(inputValue.length == 1 && inputValue == "." || inputValue == "%"){
				isValid = false;
				var topMessage = "Invalid format!";
				var mainMessage = "Please enter a valid apr";
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage({
					containerId: inputId,
					messageTop: topMessage,
					messageMain: mainMessage
				});
			}else{
				$("#error_"+inputId+", div.errorClear").remove();
				$("#"+inputId).removeClass("errorFocus");
			}
		}
		else {
			isValid = false;
			var topMessage = "Invalid format!";
			var mainMessage = "Please enter a valid apr";
			$("#error_"+inputId+", div.errorClear").remove();
			$(this).errorMessage({
				containerId: inputId,
				messageTop: topMessage,
				messageMain: mainMessage
			});
		}
	}
	return isValid;
}

function validate_chooseTrim(inputId, selectOption){
	var isValid = true;
	if (selectOption.length == 0 || selectOption == "noSelection") {
		var topMessage = "This field cannot be left blank";
		var mainMessage = "Please Select a Model";
		$("#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_emailConfirm(inputId, email1, email2) {
	var isValid = true;
	if (email2 != email1) {
		isValid = false;
		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 confirmation email address.";

		$("#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_groupSelectVehicle(inputId){
	// verify that at least one checkbox or radio button was checked
	var isChecked = 0; // assume nothing is checked
	$('#'+inputId+' ul.radio').find('input[type=radio]:checked').each(function() {
		isChecked = 1;
	});

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

function validate_purchasePrice(inputId, inputValue) {
	var isValid = true;
	var value = jQuery.trim(inputValue.toLowerCase());
	var regVal	  = /^[[0-9]{1,3}[\,]?[0-9]{3}]*$/;
	var regValNum = /^[[0-9]{1,7}]*$/;
	var regEx	 = new RegExp(regVal);
	var regExNum = new RegExp(regValNum);

	if (inputValue.length == 0) {
		var topMessage = "This field cannot be left blank";
		var mainMessage = "Please enter your Purchase Price";
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageTop: topMessage,
			messageMain: mainMessage
		});
	}else{
		if (value.match(regEx) && !value.match(regExNum)) {
			$("#error_"+inputId+", div.errorClear").remove();
			$("#"+inputId).removeClass("errorFocus");
		}
		else {
		   if(value.match(regExNum)){
				$("#error_"+inputId+", div.errorClear").remove();
				$("#"+inputId).removeClass("errorFocus");
				if (inputValue.length == 7)
					inputValue = inputValue.slice(0,inputValue.length-1);

				if(inputValue.length > 3){
				 var valueStr = inputValue.split("");
				 var inputValue="";
					  for (i=0; i<valueStr.length; i++){
						if(i == (valueStr.length-3)){
							inputValue += ",";
						}
						inputValue += valueStr[i];
					 }
				  $('input[name=purchasePrice]').val(inputValue);
				}
		   }else {
				isValid = false;
				var topMessage = "Invalid format!";
				var mainMessage = "Please enter a valid Purchase Price";
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage({
					containerId: inputId,
					messageTop: topMessage,
					messageMain: mainMessage
				});
		  }
		}
	}
	return isValid;
}

function validate_model(inputId, selectOption, year, action) {
	var isValid = "no";
	if (year === undefined) {year = "";}
	if (selectOption === "noSelection" || selectOption.length === 0) {
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageMain: "Please select a vehicle"
		});
		var trimOption = '<option value="noSelection">Select a Model</option>';
		$('select#chooseTrim').empty().append(trimOption);
		$('#modelCont').empty();
	}
	else if (selectOption !== "noSelection" && selectOption.length > 0) {
		isValid = "yes";
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");

		var trimOptions = create_modelTrimOptions(selectOption, year, "", true);
		$('select#chooseTrim').empty().append(trimOptions);
		$("#error_chooseTrim, div.errorClear").remove();
		$("select#chooseTrim").removeClass("errorFocus");
	}
	return isValid;
}

function validate_modelDEPRECATED(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_modelTrimOptionsDEPRECATED(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, "", true);
			$('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, "", true);
			//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_modelYearDEPRECATED(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_modelOptionsDEPRECATED(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_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 {
			$("#error_"+inputId+", div.errorClear").remove();
			$("#"+inputId).removeClass("errorFocus");
		}
}

function validate_price(inputId, inputValue, message) {
	var isValid = true;
	var value = jQuery.trim(inputValue.toLowerCase());
	var regVal	  = /^[[0-9]{1,3}[\,]?[0-9]{3}]*$/;
	var regValNum = /^[[0-9]{1,7}]*$/;
	var regEx	 = new RegExp(regVal);
	var regExNum = new RegExp(regValNum);

	if (inputValue.length == 0 || inputValue == "0" ) {
		$('input[name='+inputId+']').val("0");
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}else{
		if (value.match(regEx) && !value.match(regExNum)) {
			$("#error_"+inputId+", div.errorClear").remove();
			$("#"+inputId).removeClass("errorFocus");
		}
		else {
		   if(value.match(regExNum)){
				$("#error_"+inputId+", div.errorClear").remove();
				$("#"+inputId).removeClass("errorFocus");
				if (inputValue.length == 7)
					inputValue = inputValue.slice(0,inputValue.length-1);

				if(inputValue.length > 3){
				 var valueStr = inputValue.split("");
				 var inputValue="";
					  for (i=0; i<valueStr.length; i++){
						if(i == (valueStr.length-3)){
							inputValue += ",";
						}
						inputValue += valueStr[i];
					 }
					 $('input[name='+inputId+']').val(inputValue);
				}
		   }else {
				isValid = false;
				var topMessage = "Invalid format!";
				var mainMessage = "Please enter a valid Purchase Price";
				$("#error_"+inputId+", div.errorClear").remove();
				$(this).errorMessage({
					containerId: inputId,
					messageTop: topMessage,
					messageMain: mainMessage
				});
		  }
		}
	}
	return isValid;
}

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 (value.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 (value.match(regEx)) {
		if (value.length < 2) {
			$("#error_"+inputId+", div.errorClear").remove();
			$(this).errorMessage({
			containerId: inputId,
			messageMain: message
		});
		}
		else {
			$("#error_"+inputId+", div.errorClear").remove();
			$("#"+inputId).removeClass("errorFocus");
			isValid = true;
		}
	}else{
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
				containerId: inputId,
				messageTop:	 "Invalid format!",
				messageMain: ""
		});
	}
}

function validate_presenceOfName(inputId, inputValue, message) {
	var value = jQuery.trim(inputValue.toLowerCase());
	var regVal = /^[a-zA-Z0-9\s'-]*$/;
	var regEx = new RegExp(regVal);
	var pat = /^\s+$/;
	var regEx2 = new RegExp(pat);

	if (value.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_purchase_date(dateString, year){
	var deliminator= "/";
	var valid_purchase_date = "true";
	var dateStringDigits = dateString.replace(/[^\d]/g, "");
	var pos1=dateString.indexOf(deliminator);
	var pos2=dateString.indexOf(deliminator,pos1+1);
	var strYear=dateString.substring(pos2+1);
	var purchase_year = parseInt(strYear);
	var model_year;

	if (year === undefined) {
		model_year = "";
	}
	else{
		model_year = parseInt(year);
	}

	if (model_year != ""){
		var result= model_year - purchase_year;
		if(result > 1){
			valid_purchase_date = "false";
		}
	}
	return valid_purchase_date;
}

function validate_vin(vin) {
	var vinMatch = "no";
	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
	if (vehicles_owned) {
		$(vehicles_owned).each(function() {
			var ownedVin = jQuery.trim($(this).attr("VIN").toUpperCase());
			if (vin == ownedVin) {
				vinMatch = "yes";
			}
		});
	}

	if (vinMatch == "no") {
		var isVin = "no";

		if(vin.length == 17){
			var vinInfo = get_vinInfo(vin, true);
			$(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="oct_link_dealer" 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_modelYearOptionsDEPRECATED();
			$('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" && vin != "") {
		$(".field_check").hide();
		$("#duplicateVin").show();
	}
	return validVin;
}
		
function validate_zipCode(inputId, inputValue) {
	var inputDigits = inputValue.replace(/[^\d]/g, "");
	var digitLength = inputDigits.length;
	var validated = false;
	var regVal = /^[0-9\s'-]*$/;
	var regEx = new RegExp(regVal);

	if (inputValue.match(regEx)) {
		if (digitLength < 5 || digitLength > 5) {
			$("#error_"+inputId+", div.errorClear").remove();
			//$("#"+inputId).val("ZIP Code");
			$(this).errorMessage({
			containerId: inputId,
			messageTop: "The zip code must contain only 5 digits",
			messageMain: "Please enter a 5 digit zip code"
		});
		validated = false;
		}else{
			$("#error_"+inputId+", div.errorClear").remove();
			$("#"+inputId).removeClass("errorFocus");
			validated = true;
		}
	}else{
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage({
				containerId: inputId,
				messageTop:	 "Invalid format!",
				messageMain: ""
		});
		isValid = false;
	}
	return validated;
}

function validate_zipCodeForm(inputId, inputValue) {
	var inputDigits = inputValue.replace(/[^\d]/g, "");
	var digitLength = inputDigits.length;
	var validated = "no";
	
	if (inputValue.length == 0) {
		$("#error_" + inputId + ", div.errorClear").remove();
		$(this).errorMessage({
			containerId: inputId,
			messageMain: 'Please enter your ZIP code'
		});
	}
	else {	
		if (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"
			});
			$(this).removeClass("errorFocus");
			$("#" + inputId).addClass("errorFocus");
			validated = "no";
		}
		else {			
			var searchRadius = parseFloat($("#selectRadius").val());
			if(searchRadius != undefined)
				var dealerListHtml = create_dealerRadioGroup(inputValue, searchRadius, true);
			
			$("#error_" + inputId + ", div.errorClear").remove();
			$("#t").removeClass("errorFocus");
			$("#" + inputId).removeClass("errorFocus");
			validated = "yes";			
		}
	}
	return validated;
}

/**
*
* Validation method to form "Tell Your Story Now" on dearsubaru/index.html
*
*/
function validate_dearSubaru_stateForm(inputId, inputValue) {
	var selectOption = inputValue;
	if (selectOption == ""){
		$("#error_"+inputId+", div.errorClear").remove();
		$(this).errorMessage(
		{
			containerId: inputId,
			messageMain: "Please select your state."
		});
		validated = false;
	}
	else if (selectOption != ""){
		$("#error_"+inputId+", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
		validated = true;
	}
	return validated;
}
/**
* End Validation Method
*/

function validate_stateForm(inputId, inputValue) {
	var selectOption = inputValue;
	if (selectOption == ""){
		$("#error_" + inputId + ", div.errorClear").remove();
		$(this).errorMessage(
		{
			containerId: inputId,
			messageMain: "Please select your state."
		});
	}
	else if (selectOption != ""){
		$("#error_" + inputId + ", div.errorClear").remove();
		$("#"+inputId).removeClass("errorFocus");
	}
}

