var now=new Date()
var digits = "0123456789";
var phoneNumberDelimiters = "()- ";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 10;
var xslv = "vehicles3_sp";
var xsld = "details3_sp";
var xslc = "compare3_sp";	
function isInteger(s)
{ var i;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) {return false;}
    }
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) {returnString += c;}
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function makephone(){
	document.formnameQQm.Phone.value = document.formnameQQm.textBoxPhoneArea.value+document.formnameQQm.textBoxPhonePrefix.value+document.formnameQQm.textBoxPhoneSuffix.value;
	if (document.formnameQQm.textBoxPhoneArea.value==='' && document.formnameQQm.textBoxPhonePrefix.value==='' && document.formnameQQm.textBoxPhoneSuffix.value===''){
		document.formnameQQm.Phone.value='';
	}
}

var accessoryCodes='';
function setAcc(){
	accessoryCodes='';
	for (var i=0; i<document.getElementsByName('strAcc').length; i++)
  	{
      	accessoryCodes += document.getElementsByName('strAcc')[i].value + ',';
	}
}

function get_radio_value()
{
for (var i=0; i < document.formnameQQm.pContact.length; i++)
   {
   if (document.formnameQQm.pContact[i].checked)
      {
      document.formnameQQm.preferredContact.value = document.formnameQQm.pContact[i].value;
      }
   }
}
function clearContactError(){
	$("contact_error").innerHTML="";
}
function fireTagQuickQuote(){
	var v=0;
	fireTag('93.8',{
			'<model_year>':''+$('vconfirm'+v).getAttribute('year')+'',
			'<model>':''+$('vconfirm'+v).getAttribute('model')+'',
			'<trim>':''+$('vconfirm'+v).getAttribute('trim')+'',
			'<zip>':''+$('vconfirm'+v).getAttribute('zip')+'',
			'<region>':''+$('vconfirm'+v).getAttribute('region')+'',
			'<dealer_code>':''+$('vconfirm'+v).getAttribute('dealercode')+'',
			'<dealer_name>':''+$('vconfirm'+v).getAttribute('dealername')+'',
			'<error_message>':''+$("contact_error").innerHTML+''
		});
}
function validateQuickQuote() {
	//setAcc();
	$("contact_error").innerHTML="";
	get_radio_value();
	stripNonAlphaNumeric(document.formnameQQm.firstName);
	stripNonAlphaNumeric(document.formnameQQm.lastName);
	stripNonAlphaNumeric(document.formnameQQm.comments);
	stripNonAlphaNumeric(document.formnameQQm.tradeInMakeName);
	stripNonAlphaNumeric(document.formnameQQm.tradeInModelName);
	stripNonAlphaNumeric(document.formnameQQm.tradeInTrim);
	stripNonAlphaNumeric(document.formnameQQm.tradeInEquipment);

	if (document.formnameQQm.firstName.value==='') {
		$("contact_error").innerHTML="Por favor introduce tu nombre.";
		document.formnameQQm.firstName.blur();
		document.formnameQQm.firstName.focus();
		$('firstName').addClassName('input_error');
		fireTagQuickQuote();
		return false;
	}
	if (document.formnameQQm.lastName.value===''){
		$("contact_error").innerHTML="Por favor introduce tu apellido.";
		document.formnameQQm.lastName.blur();
		document.formnameQQm.lastName.focus();
		$('lastName').addClassName('input_error');
		fireTagQuickQuote();
		return false;
	}
	if (val_zipcodeP(document.formnameQQm.textBoxZipCode.value)==='false'){
		$("contact_error").innerHTML="Por favor introduce los 5 dígitos de tu código postal.";
		document.formnameQQm.textBoxZipCode.blur();
		document.formnameQQm.textBoxZipCode.focus();
		$('textBoxZipCode').addClassName('input_error');
		fireTagQuickQuote();
		return false;
	}
	if (document.formnameQQm.emailAddress.value===''){
		$("contact_error").innerHTML="Por favor introduce una dirección válida de email.";
		document.formnameQQm.emailAddress.blur();
		document.formnameQQm.emailAddress.focus();
		$('emailAddress').addClassName('input_error');
		fireTagQuickQuote();
		return false;
	}
	if (val_email(document.formnameQQm.emailAddress.value)!==true){
		$("contact_error").innerHTML="Por favor introduce una dirección válida de email.";
		document.formnameQQm.emailAddress.blur();
		document.formnameQQm.emailAddress.focus();
		$('emailAddress').addClassName('input_error');
		fireTagQuickQuote();
		return false;
	}
	/*if (document.formnameQQm.Phone.value==='') {
		$("contact_error").innerHTML="Por favor introduce un n&uacute;mero de teléfono válido.";
		document.formnameQQm.textBoxPhoneArea.blur();
		document.formnameQQm.textBoxPhoneArea.focus();
		$('textBoxPhoneArea').addClassName('input_error');
		fireTagQuickQuote();
		return false;
	}
	if (document.formnameQQm.Phone.value.length!=10){// && checkInternationalPhone(document.formnameQQm.Phone.value)===false){
		$("contact_error").innerHTML="Por favor introduce un n&uacute;mero de teléfono válido.";
		if(document.formnameQQm.textBoxPhoneSuffix.value.length<4){
		document.formnameQQm.textBoxPhoneSuffix.blur();
		document.formnameQQm.textBoxPhoneSuffix.focus();
		$('textBoxPhoneSuffix').addClassName('input_error');
		}
		if(document.formnameQQm.textBoxPhonePrefix.value.length<3){
		document.formnameQQm.textBoxPhonePrefix.blur();
		document.formnameQQm.textBoxPhonePrefix.focus();
		$('textBoxPhonePrefix').addClassName('input_error');
		}
		if(document.formnameQQm.textBoxPhoneArea.value.length<3){
		document.formnameQQm.textBoxPhoneArea.blur();
		document.formnameQQm.textBoxPhoneArea.focus();
		$('textBoxPhoneArea').addClassName('input_error');
		}
		fireTagQuickQuote();
		return false;
	}
	if (document.formnameQQm.buyingStatus.value===''){
		$("contact_error").innerHTML="Please select a purchase horizon.";
		document.formnameQQm.bStatus.blur();
		document.formnameQQm.bStatus.focus();
		$('bStatus').addClassName('input_error');
		fireTagQuickQuote();
		return false;
	}*/
	document.formnameQQm.hiddenComments.value="";
	if (document.formnameQQm.spanish.checked===true){
	document.formnameQQm.hiddenComments.value=document.formnameQQm.hiddenComments.value+"*** Customer requested a Spanish speaking representative ***\n";
	}
	if (document.formnameQQm.schedule.checked===true){
	document.formnameQQm.hiddenComments.value=document.formnameQQm.hiddenComments.value+"*** Customer requested to schedule a Test Drive ***\n";
	}
	if (document.formnameQQm.vsa.checked===true){
	document.formnameQQm.hiddenComments.value=document.formnameQQm.hiddenComments.value+"*** Customer requested Additional Information on VSA's ***\n";
	}
	if (document.formnameQQm.tradeInEquipment.value!=="" && document.formnameQQm.tradeInPriceEstimate.value!==""){
	document.formnameQQm.hiddenComments.value=document.formnameQQm.hiddenComments.value+"*** Customer utilized KBB to estimate Trade In Value ***\n";
	var kbbString="";
	kbbString += "Trade Make : "+document.formnameQQm.tradeInMakeName.value+"\n";
	kbbString += "Trade Year : "+document.formnameQQm.tradeInYear.value+"\n";
	kbbString += "Trade Model : "+document.formnameQQm.tradeInModelName.value+"\n";
	kbbString += "Trade Trim : "+document.formnameQQm.tradeInTrim.value+"\n";
	kbbString += "Trade Mileage : "+document.formnameQQm.tradeInMileage.value+"\n";
	kbbString += "Trade Condition : "+document.formnameQQm.tradeInCondition.value+"\n";
	kbbString += "Trade KBB Estimated Value : "+document.formnameQQm.tradeInPriceEstimate.value+"\n";
	kbbString += "Trade Engine : "+document.formnameQQm.tradeInEngine.value+"\n";
	kbbString += "Trade trans : "+document.formnameQQm.tradeInTransmission.value+"\n";
	kbbString += "Trade Zip : "+document.formnameQQm.tradeInZip.value+"\n";
	kbbString += "Trade State : "+document.formnameQQm.tradeInState.value+"\n";
	//kbbString += "Trade Equip. : "+document.formnameQQm.tradeInEquipment.value+"\n";
	document.formnameQQm.hiddenComments.value=document.formnameQQm.hiddenComments.value+kbbString;
	} else if(document.formnameQQm.tradeInMakeName.value!==""){
		var kbbString="";
		kbbString += "Trade Make : "+document.formnameQQm.tradeInMakeName.value+"\n";
		kbbString += "Trade Year : "+document.formnameQQm.tradeInYear.value+"\n";
		kbbString += "Trade Model : "+document.formnameQQm.tradeInModelName.value+"\n";
		kbbString += "Trade Trim : "+document.formnameQQm.tradeInTrim.value+"\n";
		kbbString += "Trade Mileage : "+document.formnameQQm.tradeInMileage.value+"\n";
		kbbString += "Trade Condition : "+document.formnameQQm.tradeInCondition.value+"\n";
		kbbString += "Trade Estimated Value : "+document.formnameQQm.tradeInPriceEstimate.value+"\n";
		document.formnameQQm.hiddenComments.value=document.formnameQQm.hiddenComments.value+kbbString;
	}
	document.formnameQQm.hiddenComments.value=document.formnameQQm.comments.value+"\n"+document.formnameQQm.hiddenComments.value+"\n";
	//saveFormState('formnameQQm');
	getQuickQuote();
	return true;
}
function contactDealers(){
	//saveFormState('formnameQQm');
	validateQuickQuote();
}

function getContact(page){
	//$('omniPage').value=page;
	//if(TMSSite.readCookie('favList')!==null && TMSSite.readCookie('favList')!==''){
		var url = '';
		if (loc=='b'){
			url="/inventory/data/dataCommon3.asp";
		}else if (loc=='t'){
			url="/toyotaTCUV/inventory/searchV2.do";
		}else{
			url="/toyotaTCUV/inventory/searchV2.do";
        }

        var favList = TMSSite.readCookie('favList');
        var tempFavList = favList == null ? "" : favList.replace(/\|.*?@/gi, ',');
		var rand   = Math.random(9999);
		var pars   = "RequesterID="+RequesterID+
					"&rand=" + rand +
					"&action=getCompare"+
					//"&noxslt=yes"+
					"&language="+language+
					"&sdwsMethod=GetVehicles"+
					"&SecurityToken="+SecurityToken+
					//"&SZIP=90210"+//TMSSite.getZip()+
					"&SZIP="+$("SZIP").value+
					"&displayType=contactList"+
					"&page="+page+
					"&responseXsl="+xslc+
					"&SVIN="+escape(tempFavList)+page;
		//alert(pars);
		historyBookmark("getContact('"+page+"')");
		var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoading($('inventory'),'noinv'), onComplete: showContactFavorites, onError: showFailure} );
	//}else{
		//alert('no favorites for contact');
		//TMSSite.disclaimerHotlink('/includes/errors/nofavoritesatall.incl');
	//}
}

function contactDealer(page,v,d){
		//$('omniPage').value=page;
		var url = '';
		if (loc=='b'){
			url="/inventory/data/dataCommon3.asp";
		}else if (loc=='t'){
			url="/toyotaTCUV/displayVehicleCompare.do";
		}else{
			url="/toyotaTCUV/displayVehicleCompare.do";
		}
	    //var tempFavList = TMSSite.readCookie('favList').replace(/\|.*?@/gi,',');
		var rand   = Math.random(9999);
		var pars   = "RequesterID="+RequesterID+
					"&rand=" + rand +
					"&action=getCompare"+
					//"&noxslt=yes"+
					"&language="+language+
					"&SZIP="+$("SZIP").value+
					"&displayType=contactList"+
					"&SVIN="+v;
		//alert(pars);
		var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoading($('inventory'),'noinv'), onComplete: showContact, onError: showFailure} );
}

function getGallery(p17) {
	var url = '';
	if (loc=='b'){
		url="/inventory/data/dataCommon3.asp";
	}else if (loc=='t'){
		url="/toyotaTCUV/inventory/searchV2.do";
	}else{
		url="/toyotaTCUV/inventory/searchV2.do";
	}
	var rand   = Math.random(9999);
	
	var pars   = "RequesterID="+RequesterID+
				"&rand=" + rand +
				"&language="+language+
				"&sdwsMethod=GetVehicles"+
				"&SecurityToken="+SecurityToken+
				"&displayType=gallery"+
				"&action=getDetails"+
				"&responseXsl=details3_sp"+
				"&SVIN="+p17;
				historyBookmark("getGallery('"+p17+"')");
			var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoading($('inventory')), onComplete: showGallery} );
			//var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: showGallery} );
}



function showGallery (OriginalRequest){
	showMask();
	$("overlay_gallery").innerHTML=OriginalRequest.responseText;
	posY = getScreenCenterY();
	posX = getScreenCenterX();
	//X = 228;//$("inventory").cumulativeOffset().left
	//Y = posY-($('inv_gallery').getHeight()/2).round();
	Y = posY-330;
	if(Y<40){Y=40};
	$('overlay_gallery').style.cssText = "position:absolute;top:"+Y+"px;"//left:"+X+"px;";

	$('overlay_calculator').hide();
	$('overlay_compare').hide();
	$('overlay_contact').hide();
	//$('overlay_details').hide();
	//setTimeout('hideLoading($("overlay_gallery"));',500);
	$('overlay_gallery').show();
	setTimeout('hideLoading($("inventory"));',500);
}

function hideGallery(){
	$('overlay_gallery').hide();
	if($('overlay_compare').innerHTML!==''){$('overlay_compare').show();}else{hideMask();}
	
}

function getDetails(vin){
	var url = '';
	if (loc=='b'){
		url="/inventory/data/dataCommon3.asp";
	}else if (loc=='t'){
		url="/toyotaTCUV/inventory/searchV2.do";
	}else{
		url="/toyotaTCUV/inventory/searchV2.do";
	}
	var rand   = Math.random(9999);
	
	var pars   = "RequesterID="+RequesterID+
				"&rand=" + rand +
				//"&noxslt=yes"+
				"&sdwsMethod=GetVehicles"+
				"&SecurityToken="+SecurityToken+
				"&language="+language+
				"&SourceId="+SourceId+
				"&displayType=details"+
				"&action=getDetails"+
				"&responseXsl="+xsld+
				"&SZIP="+$("SZIP").value+
				"&today="+now.getDate()+
				"&SVIN="+vin;
	//alert(pars);
	//var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoading('content','overlay_details'), onComplete: showDetails} );
	historyBookmark("getDetails('"+vin+"')");
	//var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: showDetails} );
	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoading($('inventory')), onComplete: showDetails} );
}

function showDetails (OriginalRequest) {
	$("overlay_content").innerHTML=OriginalRequest.responseText;
	$('overlay_calculator').hide();
	$('overlay_compare').hide();
	$('overlay_contact').hide();
	posY = getScreenCenterY();
	Y = posY-(($('overlay_content').getHeight()/2).round());
	if(Y<72){Y=72}
	$('overlay_content').style.cssText = "position:absolute;top:"+Y+"px;";

	//hidePrint();
	//$('inventory').hide();
	$('overlay_content').show();
	setTimeout('hideLoading($("inventory"));',500);
	showMask();
	getLocalSpecials('modelId',$("specialZipCode").value,'',$("specialModelCode").value,$("specialYear").value,'specialsDetails','SHORT');
	//popDropIn();
}


function hideDetails() {
	
	$('overlay_content').hide();
	$('overlay_content').innerHTML='';
	//$('inventory').show();
	hideMask();
}

function showContact(OriginalRequest){
	//showMask();
	$('overlay_calculator').hide();
	$('overlay_compare').hide();
	$('overlay_details').hide();
	$("overlay_contact").innerHTML=OriginalRequest.responseText;	
		$('overlay_contact').show();
		setTimeout('hideLoading($("inventory"));',500);
	//setFormState('formnameQQm');
	if ($('v1') && !$('v2')){
		$('v1').checked = true;			  
	}
	if (document.formnameQQm.firstName){
		document.formnameQQm.firstName.blur();
		document.formnameQQm.firstName.focus();
	}
			for(var i = 1; i <= 5; i++) {

                var v = $("v" + i);
                if(v !== null ){
				}
            }
	
	//hideLoading($("overlay_contact"));
	
}
	
	
function showContactFavorites(OriginalRequest){
	showMask();
	$('overlay_calculator').hide();
	$('overlay_compare').hide();
	$('overlay_content').hide();
	$("overlay_contact").innerHTML=OriginalRequest.responseText;
	showMask();
	posY = getScreenCenterY();
	Y = posY-(($('overlay_contact').getHeight()/2).round());
	Y = posY-330;
	if (Y<30){Y=30}
	$('overlay_contact').style.cssText = "position:absolute;top:"+Y+"px;";

	$('overlay_contact').show();
		setTimeout('hideLoading($("inventory"));',500);
	//setFormState('formnameQQm');
	//if ($('v1') && !$('v2')){
	//	$('v1').checked = true;			  
	//}
	if (document.formnameQQm.firstName){
		document.formnameQQm.firstName.blur();
		document.formnameQQm.firstName.focus();
	}		
}
function hideContact(){
	
	
	$('overlay_contact').hide();
	$('overlay_contact').innerHTML='';
	if($('overlay_content').innerHTML!==''){$('overlay_content').show();}else if(
	$('overlay_compare').innerHTML!==''){$('overlay_compare').show();} else {hideMask();}

	//$('results').show();
}

function showRefine(){
	$('overlay_refine').style.display='none';
	$('overlay_compare').hide();
	$('overlay_contact').hide();
	$('overlay_details').hide();
	$('overlay_refine').show();
}

function showCalculator() {
   // historyBookmark("showCalculator()");
	$('mask').style.zIndex=2;
	showMask();
	posY = getScreenCenterY();
	posX = getScreenCenterX();
	X = 120;//$("inventory").cumulativeOffset().left
	Y = posY-($('overlay_calculator').getHeight()/2).round();
	if(Y<72){Y=72}
	$('overlay_calculator').style.cssText = "position:absolute;top:"+Y+"px;left:"+X+"px;";

	//showMask('overlay_content');
	//$('overlay_details').hide();
	$('overlay_calculator').show();
	if($('price').value!=='' &&  $('price').value!== null){
		checkprice();
	}
	pageAction = "385";
	pixel();
}
function showCalculatord() {
    //historyBookmark("showCalculator()");
	//showMask();
	posY = getScreenCenterY();
	//posX = getScreenCenterX();
	//X = 0;//$("inventory").cumulativeOffset().left
	Y = posY-($('overlay_calculator').getHeight()/2).round();
	$('overlay_calculator').style.cssText = "position:absolute;top:"+Y+"px;";

	$('mask').style.zIndex=2;
	$('overlay_calculator').show();
	if($('price').value!=='' &&  $('price').value!== null){
		checkprice();
	}
	pageAction = "385";
	pixel();
}
function hideCalculatord(){
	if($('overlay_content').visible()==false){hideMask();}
	//hideMask('content_body_inv');
	$('overlay_calculatord').hide();
	$('mask').style.zIndex=1;
}
function hideCalculator(){
	if($('overlay_content').visible()==false){hideMask();}
	$('mask').style.zIndex=1;
	//hideMask('content_body_inv');
	$('overlay_calculator').hide();
}
function showMask(){
	//$('mask').style.height=document.body.parentNode.scrollHeight +'px';
	//$('mask').style.width=document.body.parentNode.scrollWidth +'px';
	/*
	$('mask').style.height=$('inventory').scrollHeight +'px';
	$('mask').style.width=$('inventory').scrollWidth +'px';
	if(Prototype.Browser.IE6 || Prototype.Browser.IE){
		$('mask').style.opacity='60';
	}*/
	//if($('results') && Prototype.Browser.IE6){
	//	document.vehicles.SortField.style.display='none';//$('vehicles').hide();
	//	document.vehicles.SortOrder.style.display='none';
	//}
	$('mask').show();
}
function hideMask(){
	//$('vehicles').show();
	if($('results_table') && Prototype.Browser.IE6){
		document.vehicles.SortField.style.display='inline';
	}
	$('mask').hide();
	
	//$("results_container").style.height='575px'
	
}
function getQuickQuote() {
	var vinString ="";
		var url = "";
			if (loc=='b'){
				url="/inventory/data/dataCommon3.asp";
			}else if (loc=='t'){
				url="/toyotaTCUV/submitLead.do";
				//url="/toyotaTCUV/salesLead/submitLeadXml.do"
			}else{
				url="/toyotaTCUV/submitLead.do";
				//url="/toyotaTCUV/salesLead/submitLeadXml.do"
			}
			
			var bChecked = false;
			var tv = 0;
			var cc = 0;
			for(var j = 0; j <= 15; j++){
				var x = $("v" + j);
                if(x !== null  && x.checked){
					tv++;
				}
			}
			for(var i = 0; i <= 15; i++) {
				var pars = "";
				var rand = Math.random(9999);
				pars = "RequesterID="+RequesterID+
				"&rand=" + rand +
				"&displayType="+
				"&action=getInquiry"+
				"&language="+language+
				"&zip="+escape(document.formnameQQm.textBoxZipCode.value)+
				"&firstName="+escape(document.formnameQQm.firstName.value)+
				"&lastName="+escape(document.formnameQQm.lastName.value)+
				"&address="+escape(document.formnameQQm.address.value)+
				"&city="+escape(document.formnameQQm.city.value)+
				"&state="+escape(document.formnameQQm.state.value)+
				"&phone="+escape(document.formnameQQm.Phone.value)+
				"&emailAddress="+document.formnameQQm.emailAddress.value+
				"&preferredContact="+escape(document.formnameQQm.preferredContact.value)+
				"&purchaseHorizon="+document.formnameQQm.buyingStatus.value+
				"&campaignCode=TWUU00390000";
                var v = $("v" + i);
                if(v !== null  && v.checked){
					cc++
                    bChecked = true;
                    pars = pars + "&" + v.value + "&comments="+document.formnameQQm.hiddenComments.value.strip();
					
					//alert(pars)
					//alert(encodeURI(pars))
					//alert(encodeURIComponent(pars))
					pars = encodeURI(pars)
                   //alert(v.value);// 
				   eval("var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoading($('inventory'),'noinv'), onComplete: function(request) {quickQuoteComplete(request.responseText,"+i+","+tv+","+cc+");}});");
				
				}
            }
            if(!bChecked){
				$("contact_error").innerHTML="<b class='title'>Please select at least one vehicle";
				return false
            }
			fireTag('93.7',{
				'<model_year>':''+$('vconfirm0').getAttribute('year')+'',
				'<model>':''+$('vconfirm0').getAttribute('model')+'',
				'<trim>':''+$('vconfirm0').getAttribute('trim')+'',
				'<zip>':''+$('vconfirm0').getAttribute('zip')+'',
				'<region>':''+$('vconfirm0').getAttribute('region')+'',
				'<dealer_code>':''+$('vconfirm0').getAttribute('dealercode')+'',
				'<dealer_name>':''+$('vconfirm0').getAttribute('dealername')+''
			});

}

function quickQuoteComplete(responseText,v,tv,cc){
	if (responseText.indexOf('error')<0){
		fireTag('84.19',{
			'<model_year>':''+$('vconfirm'+v).getAttribute('year')+'',
			'<model>':''+$('vconfirm'+v).getAttribute('model')+'',
			'<zip>':''+document.formnameQQm.textBoxZipCode.value+'',
			'<region>':''+$('vconfirm'+v).getAttribute('region')+'',
			'<dealer_code>':''+$('vconfirm'+v).getAttribute('dealercode')+'',
			'<dealer_name>':''+$('vconfirm'+v).getAttribute('dealername')+'',
			'<trim>':''+$('vconfirm'+v).getAttribute('trim')+''
		});
		TMSSite.doubleClick('EL');
		//TMSSite.doubleClick('TFL');
		//TMSSite.doubleClick('NTL');
		pageAction = "667";
		pixel();
		//sendTCAATag(TMSSite.readCookie('JSESSIONID_TOYOTA_TCUV'));
		if(v>0){
			$('vv'+v).innerHTML="<img src='/img/content/icon_check.gif'/>";
			//$('vconfirm'+v).innerHTML="<img src='/img/content/icon_check.gif'/>";
		}
		if (cc==tv){allQuoteComplete(tv);}
	}else{
			//alert('oops ='+v);
		$('contact_error').innerHTML="Sorry! An error occured. Please try again later.";
		$('contact_error').style.color="red";
		$('vv'+v).innerHTML="<img src='/img/content/icon_x.gif'/>";
		$('formnameQQm').disable();
		//hideLoading($('inventory'));
	}
	
}
function allQuoteComplete(tv){
	$('chooseVehicle').innerHTML='<br /><br />';
	$('contactTitleContact').innerHTML="!Gracias! Te contactáremos pronto.";
	$('contactTitleContact').style.color="yellow";
		$('firstNameResponse').innerHTML = document.formnameQQm.firstName.value;
		$('lastNameResponse').innerHTML = document.formnameQQm.lastName.value;
		$('addressResponse').innerHTML = document.formnameQQm.address.value;
		$('cityResponse').innerHTML = document.formnameQQm.city.value;
		$('stateResponse').innerHTML = document.formnameQQm.state.value;
		$('emailAddressResponse').innerHTML = document.formnameQQm.emailAddress.value;
		$('pContactResponse').innerHTML = document.formnameQQm.preferredContact.value;
		$('phoneResponse').innerHTML = document.formnameQQm.Phone.value;
		$('textBoxZipCodeResponse').innerHTML = document.formnameQQm.textBoxZipCode.value;
		if (document.formnameQQm.comments.value !==''){$('commentsResponse').innerHTML = 'Commentos: '+document.formnameQQm.comments.value;}
		if (document.formnameQQm.spanish.checked===true){$('spanishResponse').innerHTML ='Prefiero contactarme con un concesionario hispanohablantePrefiero contactarme con un concesionario hispanohablante';}
		if (document.formnameQQm.schedule.checked===true){$('scheduleResponse').innerHTML ='El cliente ha requerido una cita para prueba de manejo';}
		if (document.formnameQQm.vsa.checked===true){$('vsaResponse').innerHTML ='I would like additional information about Vehicle Service Agreements : Yes';}
	$('contact_info').hide();
	$('send').hide();
	$('contact_info_response').show();
	$('tradein_layer').hide();
	if(document.formnameQQm.kbbComplete.value=='yes' || document.formnameQQm.tradeInMakeName.value!=''){
		$('tradeInMakeNameResponse').innerHTML = document.formnameQQm.tradeInMakeName.value;
		$('tradeInModelNameResponse').innerHTML = document.formnameQQm.tradeInModelName.value;
		$('tradeInYearResponse').innerHTML = document.formnameQQm.tradeInYear.value;
		$('tradeInTrimResponse').innerHTML = document.formnameQQm.tradeInTrim.value;
		$('tradeInMileageResponse').innerHTML = document.formnameQQm.tradeInMileage.value;
		$('tradeInConditionResponse').innerHTML = document.formnameQQm.tradeInCondition.value;
		if(document.formnameQQm.tradeInPriceEstimate.value!==''){
			$('tradeInPriceEstimateResponse').innerHTML = '$ '+CommaFormatted(document.formnameQQm.tradeInPriceEstimate.value);
		}else{
			$('tradeInPriceEstimateResponse').innerHTML = '';
		}
		$('tradein_layer_response').show();
	}

	setTimeout('hideLoading($("overlay_contact"));',250);
}
function clearError(){
	$("intro_error").hide();
	$("intro_error").innerHTML="";
}

function saveSearch(){
	stripNonAlphaNumeric($('ss_first_name'));
	stripNonAlphaNumeric($('ss_last_name'));
	stripNonAlphaNumeric($('ss_full_name'));
	if ($('ss_first_name').value ===''){
		$("intro_error").innerHTML="<b class='title'>Por favor introduce tu nombre</b><br />&nbsp;<br />&nbsp;<br />";
		$("intro_error").show();
		$('ss_first_name').blur();
		$('ss_first_name').focus();
		return false;
		}
	if ($('ss_last_name').value ===''){
		$("intro_error").innerHTML="<b class='title'>Por favor introduce tu apellidoe</b><br />&nbsp;<br />&nbsp;<br />";
		$("intro_error").show();
		$('ss_last_name').blur();
		$('ss_last_name').focus();
		return false;
		}
	if (val_email($('ss_email_address').value)!==true){
		$("intro_error").innerHTML="<b class='title'>Por favor introduce una direcci363n v341lida de e-mail</b><br />&nbsp;<br />&nbsp;<br />";
		$("intro_error").show();
		$('ss_email_address').blur();
		$('ss_email_address').focus();
		return false;
		}
		$('ss_full_name').value = ($('ss_first_name').value+' '+$('ss_last_name').value);
		var lifespan= Form.getInputs('saved_search','radio','SavedSearchLife').find(function(radio) { return radio.checked; }).value;
		var url;
		if (loc=='b'){
			url="/inventory/data/dataCommon3.asp";
		}else if (loc=='t'){
			url="/toyotaTCUV/inventory/searchV2.do";
		}else{
			url="/toyotaTCUV/inventory/searchV2.do";
		}
			var rand = Math.random(9999);
			var pars = "RequesterID="+RequesterID+
					"&rand=" + rand +
					//"&noxslt=yes"+
					"&language="+language+
					"&displayType=Vehicles"+
					"&action=getVehicles"+
					"&sdwsMethod=GetVehicles"+
					"&SecurityToken="+SecurityToken+
					"&SourceId="+SourceId+
					"&SearchSourceId="+SourceId+
					"&SavedSearchLife="+lifespan+
					//"&SModel="+escape($("SModel").value.substring(0,$("SModel").value.length-1))+
					"&SModel="+escape($F("SModel"))+
					"&SZIP="+$('SZIP').value+
					"&SRadius="+$('SRadius').value+
					"&SYearMin="+$('SYearMin').value+
					"&SYearMax="+$('SYearMax').value+
					"&SPriceMin="+$('SPriceMin').value+
					"&SPriceMax="+$('SPriceMax').value+
					"&SMilesMin="+$('SMilesMin').value+
					"&SMilesMax="+$('SMilesMax').value+
					"&SearchName="+$('ss_full_name').value+
					//"&SavedSearch="+TMSSite.readCookie('SaveSearch')+
					"&SortField=listdate"+
					"&SortOrder=des"+
					"&responseXsl="+xslv+
					"&SearchEmail="+$('ss_email_address').value;
					//longAlert(pars);

			var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoading($('inventory')), onComplete: saveSearchComplete} );
}

function saveSearchComplete (OriginalRequest) {
	$('overlay_details').hide();
	$('overlay_contact').hide();
	$('overlay_calculator').hide();
	$("overlay_compare").hide();
	$("results").innerHTML=OriginalRequest.responseText;
	$("results").show();
	setTimeout('hideLoading($("results"));',500);
	fireTag('84.26',{'<zip>':''+$('SZIP').value});
}

function val_email(item) {
	var str = item;	
	var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
	var valid = true;
	if (re.test(str) === false) {
		valid = false;
	}
	return valid;
}

function val_alpha(item) {
   var digits = "abcdefghijklmnopqrstuvxyz-";
   var valid = "true";
   var temp;
   for (var i=0; i < item.length; i++) {
      temp = "" + item.substring(i, i+1);
      if (digits.indexOf(temp) == "-1") {valid = "false";};
   }
   return valid;
}

function val_number(item) {
   var digits = "0123456789-";
   var valid = "true";
   var temp;
   for (var i=0; i < item.length; i++) {
      temp = "" + item.substring(i, i+1);
      if (digits.indexOf(temp) == "-1") {valid = "false";};
   }
   return valid;
}

function goMap(page,d,vin,z,m,y,t,dn,r){
		TMSSite.doubleClick("TQ");
		//TMSSite.doubleClick("TFQ");
		//TMSSite.doubleClick("NTQ");
		window.open('/dealers/map.html?zipx='+z+'&model='+m+'&year='+y+'&trim='+t+'&dealercode='+d+'&dealername='+dn+'&region='+r+'&searchParams={"dl_current_view":+"map",+"dealerCode":+"'+d+'"}','Map','menubar=no,location=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,top=0,width=1000,height=600');

}
var galleryViewTemp='';
var galleryViewThumbTemp='';
function viewThumb(m,d,v,l,p,y,t,z,my,r,dn){
	$(m).src=l;
	if(galleryViewTemp.indexOf(v+'_'+p)<0){
		fireTag('90.1',{'<model_year>':''+y+'','<trim>':''+t+'','<zip>':''+z+'','<model>':''+my+'','<region>':''+r+'','<dealer_code>':''+d+'','<dealer_name>':''+dn+''});
	}
	galleryViewTemp+=v+'_'+p
}
function viewThumbdetails(m,d,v,l,p,y,t,z,my,r,dn){
	$(m).src=l;
	if(galleryViewThumbTemp.indexOf(v+'_'+p)<0){
		fireTag('93.4',{'<model_year>':''+y+'','<trim>':''+t+'','<zip>':''+z+'','<model>':''+my+'','<region>':''+r+'','<dealer_code>':''+d+'','<dealer_name>':''+dn+''});
	}
	galleryViewThumbTemp+=v+'_'+p

}


function showHelp() {
    historyBookmark("showHelp()");
	showMask();
	//$('overlay_calculator').style.display='none';
	//$('overlay_compare').hide();
	//$('overlay_contact').hide();
	
	//$('content_body_inv').hide();
	$('overlay_help').style.display='block';
}
function hideHelp() {
	hideMask();
	$('overlay_help').hide();
	//$('content_body_inv').show();
}

function xgetOrderBy(s,t) {
	//SearchRecStart=1;
	$("SortField").value = s;
	$("SortOrder").value = t;
	if (s == 'createddate' && $("SortOrder").value==='' ){
		$("SortOrder").value = 'des';
	}
	//saveFormState('vsearch');
	getVehicles();
}
function getOrderBy(s, t) {
	$("SortField").value = s;
	$("SortOrder").value = t;
	//fireTag('84.12',{'<zip>':''+$('SZIP').value});
	//fireTag('84.12',{'<zip>':''+$('SZIP').value+'','<region>':''});
    do_sort(s, t == "des" ? true : false);
    return;

	//saveFormState('vsearch');
	getVehicles();
}
// sorting
var sort_comp = function (field, reverse, primer) {
    reverse = (reverse) ? -1 : 1;
    return function (a, b) {
        a = a[field];
        b = b[field];

        if (typeof (primer) != 'undefined') {
            a = primer(a);
            b = primer(b);
        }

        if (a < b) return reverse * -1;
        if (a > b) return reverse * 1;
        return 0;
    }
}

function do_sort(field, reverse) {
    var wrapper = document.getElementById("wrapper");

    // load html into JSON array
    var sort_data = [];
    for (var i = 2; i < wrapper.childNodes.length; i++) {
        var v = wrapper.childNodes[i];
        if (v.id) {
            var o = $(v.id);
            sort_data.push({ Distance: o.getAttribute('distance'), Price: o.getAttribute('price'), Mileage: o.getAttribute('mileage'), Model: o.getAttribute('model'), Year: o.getAttribute('year'), CreatedDate: o.getAttribute('date'), Element: v });
        }
    }

    // sort JSON array
    switch (field) {
        case "distance":
            sort_data.sort(sort_comp('Distance', reverse, parseInt));
            break;
        case "price":
            sort_data.sort(sort_comp('Price', reverse, parseFloat));
            break;
        case "miles":
            sort_data.sort(sort_comp('Mileage', reverse, parseInt));
            break;
        case "model":
            sort_data.sort(sort_comp('Model', reverse));
		    break;
		case "year":
		    sort_data.sort(sort_comp('Year', reverse, parseInt));
		    break;
		case "listdate":
		    sort_data.sort(sort_comp('CreatedDate', reverse));
		    break;
    }

    // reorder elements
    for (var i = 0; i < sort_data.length; i++) {
        wrapper.appendChild(wrapper.removeChild(sort_data[i].Element));
    }
}

var filterAttr = [];
function filter_old(item, value) {
    // add or remove item from filter list
	if($('wrapper')){
    var p = -1, inc = 1, toggleCnt = 0;
    for (var i = 0; i < filterAttr.length; i++)
        if (filterAttr[i].item === item && filterAttr[i].value === value) p = i;
    if (p > -1) filterAttr.remove(p); else { filterAttr.push({ "item": item, "value": value }); inc = -1; }
       // toggle appropriate items
    $$(".listing1a,.listing1b,.listing2a,.listing2b,.listing3a,.listing3b").each(function(el) {
        var b = true;
        for (var i = 0; i < filterAttr.length; i++)
		if (el.getAttribute(filterAttr[i].item) === filterAttr[i].value && (filterAttr[i].item !== item || filterAttr[i].value !== value)) b = false;
        if (b && el.getAttribute(item) === value) {
            el.toggle();
            toggleCnt += inc;
        }
    });

    var oVehicleCount = $("filterCount");
    var cnt = parseInt(oVehicleCount.getAttribute("count"), 10) + toggleCnt;
    oVehicleCount.setAttribute("count", cnt);
    oVehicleCount.innerHTML = cnt;
	}

}
function filter(item, value, bSet) {
    // search models
    var e = document.getElementsByName("SearchModels");
    var sm = "";
    for (var i = 0; i < e.length; i++) if (e[i].checked) sm += (sm.length > 0 ? "," : "") + e[i].value;
    $("SModel").value = sm;
    sm = sm.split(",");
    // add or remove item from filter list
    if ($("wrapper")) {
        var p = -1, inc = 1, toggleCnt = 0;
        if (!bSet) {
            for (var i = 0; i < filterAttr.length; i++)
                if (filterAttr[i].item === item && filterAttr[i].value === value) p = i;
            if (p > -1) filterAttr.remove(p); else { filterAttr.push({ "item": item, "value": value }); inc = -1; }
        }
        
        // toggle appropriate items
        $("wrapper").childElements().each(function(el) {
            if (el.id.length == 17) {
                var b = true;
                for (var i = 0; i < filterAttr.length; i++) {
                    switch (filterAttr[i].item) {
                        case "SearchModels":
                            var model = el.getAttribute("model");
                            var bSearchModels = false;
                            for (var j = 0; j < sm.length; j++) if (model == sm[j]) bSearchModels = true;
                            if (bSearchModels == false) b = false;
                            break;
                        default:
                            if (el.getAttribute(filterAttr[i].item) == filterAttr[i].value) b = false;
                            break;
                    }
                }
                //if (b && !el.visible()) { el.show(); toggleCnt += 1; }
                //if (!b && el.visible()) { el.hide(); toggleCnt += -1; }
                if (b && !el.visible() && el.readAttribute("isvis") != "yes") { el.setAttribute("isvis", "yes"); el.appear({ duration: 0.8 }); toggleCnt += 1; }
                if (!b && el.visible() && el.readAttribute("isvis") != "no") { el.setAttribute("isvis", "no"); el.fade({ duration: 0.8 }); toggleCnt += -1; }
            }
        });
     
        var oVehicleCount = $("filterCount");
        var cnt = parseInt(oVehicleCount.getAttribute("count"), 10) + toggleCnt;
        oVehicleCount.setAttribute("count", cnt);
        oVehicleCount.innerHTML = cnt;
    }
}	
var modelCount = 0;
function setModels(){
	var e = document.getElementsByName("SearchModels");
    var sm = "";
	modelCount = 0;
    for (var i = 0; i < e.length; i++) if (e[i].checked) sm += (sm.length > 0 ? "," : "") + e[i].value;
    $("SModel").value = sm;
    sm = sm.split(",");
	var f = document.getElementsByName("SearchModels");
	var ss = ""
    for (var i = 0; i < f.length; i++) {
		if (f[i].checked && ss.indexOf(f[i].getAttribute('segment'))<0){
			if (ss.length > 0 ){
				ss += ","+f[i].getAttribute('segment');
			}else{
				ss += f[i].getAttribute('segment');
			}
		}
	}
   ss = ss.split(",");
	$("SearchSegment").value = ss;
}

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

function encode(x) {
	var obj = x;
	var unencoded = obj.value;
	obj.value = escape(unencoded);
}
function decode(x) {
	var obj = x;
	var encoded = obj.value;
	obj.value = unescape(encoded.replace(/\+/g,  " "));
}
function setRadius(rr){
	if(rr===null || rr===''){rr=25;}
		rr=Math.round(rr);
		if(rr==10){
		radiusCookieValue=1;
		} else if (rr==25) {
		radiusCookieValue=2;
		} else if (rr==50) {
		radiusCookieValue=3;
		} else if (rr==100) {
		radiusCookieValue=4;
		} else if (rr==250) {
		radiusCookieValue=5;
		} else if (rr===0) {
		radiusCookieValue=6;
		} else {
		radiusCookieValue=2;
		}
		if(rr==0){
			$('SearchRadiusLabel').innerHTML='Ilimitado';
			$('selectedRadius').innerHTML='Ilimitado';
			$('handleRadius-2-img').title='Ilimitado';
			sliderRadius.setValue(6,1);
		}else{
			$('SearchRadiusLabel').innerHTML=rr + ' millas';
			$('selectedRadius').innerHTML=rr + ' millas';
			$('handleRadius-2-img').title=rr;
			sliderRadius.setValue(radiusCookieValue,1);
			
		}
	$('SRadius').value=rr;
}
function nextPage(){
	var page=parseInt($("pagenum").value);
	$$('#results_table tr[page='+(page)+']').invoke('hide');
	$$('#results_table tr[page='+(page+1)+']').invoke('show');
	$("pagenum").value= parseInt($("pagenum").value)+1;
	var pfrom=$("pfrom").innerHTML=(page*perpage)+1;
	var pto=$("pto").innerHTML=(page*perpage)+perpage;
	if(pto>=parseInt($("totalRecords").value)){
		$A($("results_table").getElementsByClassName("pager_next")).invoke('hide');
	}else{
		$A($("results_table").getElementsByClassName("pager_next")).invoke('show');
	}
	if(pfrom>=5){
		$A($("results_table").getElementsByClassName("pager_prev")).invoke('show');
	}
	if((parseInt($("totalFetched").value) < parseInt($("totalRecords").value)) && (parseInt(($("totalFetched").value)-pto)<=5)){
	addVehicles();
	}
}
function prevPage(){
	var page=parseInt($("pagenum").value);
	$$('#results_table tr[page='+(page)+']').invoke('hide');
	$$('#results_table tr[page='+(page-1)+']').invoke('show');
	$("pagenum").value= parseInt($("pagenum").value)-1;
	var pfrom=$("pfrom").innerHTML=(page*perpage)-perpage-4;
	var pto=$("pto").innerHTML=(page*perpage)-perpage;
	if(pto>=parseInt($("totalRecords").value)){
		$A($("results_table").getElementsByClassName("pager_next")).invoke('hide');
	}else{
		$A($("results_table").getElementsByClassName("pager_next")).invoke('show');
	}
	if(pfrom<=5){
		$A($("results_table").getElementsByClassName("pager_prev")).invoke('hide');
	}
}

function buildSearchModel(model){
$('SModel').value="";
$('SModelCode').value="";
	$A($("vsearch").getElementsByClassName("radio")).each(function(element){
		if(element.checked===true){
			$('SModel').value=$('SModel').value+element.value+",";
			if(element.getAttribute('modelcodes')!==null && element.getAttribute('modelcodes')!==''){
				//$('SModelCode').value=$('SModelCode').value+element.getAttribute('modelcodes')+",";
			}
		}
	});
	//$('SModelCode').value=$("SModelCode").value.substring(0,$("SModelCode").value.length-1)
	if($('SModel').value!==""){
		getVehicles();
	} else{
	$('results').innerHTML="";
	$('specialsResults').innerHTML="";
	}
}

function emptyModels(){
	$A($("vsearch").getElementsByClassName("radio")).each(function(element){
	element.checked=false;
	});
	$('SModel').value="";
}

function getSelectedValues(select) {
  var r = new Array();
  //alert($("vsearch").getElementsByClassName('radio').length);
  for (var i = 1; i < $A($("vsearch").getElementsByClassName('radio')).length; i++);
    if ($("vsearch").getElementsByClassName('radio')[i].selected){
      r[r.length] = $A($("vsearch").getElementsByClassName('radio'))[i].value;
	}
  return escape(r);
}

function selectVehicles() {
	emptyModels();
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("avalon")>=0){specialsSeriesId='35';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("camry")>=0){specialsSeriesId='25';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("solara")>=0){specialsSeriesId='27';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("corolla")>=0){specialsSeriesId='18';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("celica")>=0){specialsSeriesId='21';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("echo")>=0){specialsSeriesId='';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("matrix")>=0){specialsSeriesId='19';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("venza")>=0){specialsSeriesId='28';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("yaris")>=0){specialsSeriesId='14';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("mr2")>=0){specialsSeriesId='32';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("4runner")>=0){specialsSeriesId='86';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("fj")>=0){specialsSeriesId='47';$('SModel').value='fj cruiser,';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("land cruiser")>=0){specialsSeriesId='61';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("highlander")>=0){specialsSeriesId='69';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("rav4")>=0){specialsSeriesId='44';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("sequoia")>=0){specialsSeriesId='79';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("sienna")>=0){specialsSeriesId='53';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("tacoma")>=0){specialsSeriesId='71';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("tundra")>=0){specialsSeriesId='82';}
	if (getQueryVariable("SearchModel").toLowerCase().indexOf("prius")>=0){specialsSeriesId='12';}
	if (($("VehicleCategory").value==='' || $("VehicleCategory").value===null) && getQueryVariable("SearchModel")!==null ){
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("avalon")>=0){$("VehicleCategory").value=1;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("camry")>=0){$("VehicleCategory").value=1;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("solara")>=0){$("VehicleCategory").value=1;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("corolla")>=0){$("VehicleCategory").value=1;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("celica")>=0){$("VehicleCategory").value=1;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("echo")>=0){$("VehicleCategory").value=1;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("matrix")>=0){$("VehicleCategory").value=1;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("yaris")>=0){$("VehicleCategory").value=1;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("mr2")>=0){$("VehicleCategory").value=1;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("4runner")>=0){$("VehicleCategory").value=2;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("fj")>=0){$("VehicleCategory").value=2;$('SModel').value='fj cruiser,';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("land cruiser")>=0){$("VehicleCategory").value=2;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("highlander")>=0){$("VehicleCategory").value=2;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("rav4")>=0){$("VehicleCategory").value=2;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("sequoia")>=0){$("VehicleCategory").value=2;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("sienna")>=0){$("VehicleCategory").value=2;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("tacoma")>=0){$("VehicleCategory").value=3;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("tundra")>=0){$("VehicleCategory").value=3;}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("prius")>=0){$("VehicleCategory").value=4;}
		//alert($("VehicleCategory").value);
	}
	if ($("VehicleCategory").value!=='' && $("VehicleCategory").value!=null){
		for (var i = 1; i < 5; i++){
		if ($("VehicleCategory").value==i){
			//$("searchmodels").style.visibility='visible';
			//$("searchparams").style.visibility='visible';
		$("sv_"+i).style.display = "block";
		$("v_"+i).style.display = "block";
			
		}
		else{
		$("sv_"+i).style.display = "none";
		$("v_"+i).style.display = "none";
		}
	}
	//setSliderYears();
//	$('searchstep2').show();
//	$('searchstep1').hide();
if($("SearchByDealerCode").value!==""){
	$('searchstep1').hide();
	$("category").hide();
	$("searchdealer2").show();
	}else{
	$("selectedZip").innerHTML=$("SZIP").value;
	$('category').show();
	$('searchstep1').hide();
	}

	
	}
}
function updateSpecial(el,seriesId){
	if (el.checked==true){
		if (seriesId!==specialsSeriesId){
			specialsSeriesId=seriesId;
			getLocalSpecials('seriesId',$("SZIP").value,specialsSeriesId,'','','specialsResults','LONG');
		}
	}
}
function goKbb(){
	environment="http://"+location.host;
	//staging
	//window.open('http://kbb2000.kbb.com/kb/ki.dll/kw.kc.uy?toyo;;&amp;;t&amp;21&amp;&amp;http://devcpd3.toyotacertified.com/kbb/kbb.jsp','Kelley_Blue_Book','width=525,height=750,toolbar=0,scrollbars=1,location=0,menubar=0,resizable=1,top=10,left=10');
	//production
	//window.open('http://cm.syndication.kbb.com/kb/ki.dll/kw.kc.uy?toyo;;&amp;;t&amp;21&amp;&amp;'+environment+'/toyotaTCUV/kbb.jsp','Kelley_Blue_Book','width=525,height=750,toolbar=0,scrollbars=1,location=0,menubar=0,resizable=1,top=10,left=10');
	window.open('http://sdcm.syndication.kbb.com/UsedCar/UCIndex/TOYO/UsedCar/TradeIn?PassBackUrl='+environment+'/toyotaTCUV/kbb.jsp','Kelley_Blue_Book','width=525,height=750,toolbar=0,scrollbars=1,location=0,menubar=0,resizable=1,top=10,left=10');
}

function getFavorites(){
	if(TMSSite.readCookie('favList')!=null && TMSSite.readCookie('favList')!=''){
		var url = '';
		if (loc=='b'){
			url="/inventory/data/dataCommon3.asp";
		}else if (loc=='t'){
			url="/toyotaTCUV/inventory/searchV2.do";
		}else{
			url="/toyotaTCUV/inventory/searchV2.do";
		}
		var tempFavList = TMSSite.readCookie('favList').replace(/\|.*?@/gi,',');
		var rand   = Math.random(9999);
		var pars   = "RequesterID="+RequesterID+
					"&rand=" + rand +
					"&action=getFavorites"+
					//"&noxslt=yes"+
					"&sdwsMethod=GetVehicles"+
					"&SecurityToken="+SecurityToken+
					"&language="+language+
					"&displayType=favList"+
					"&SVIN="+escape(tempFavList.substring(0,tempFavList.length-1));
		//alert(pars);
		var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoading($('sidebar')), onComplete: showFavorites, onError: showFailure} );
	}else{
		$("fav_list").innerHTML="";
		favCount=0;
		$("favcountdisplay").innerHTML=favCount;
	}
}

function showFavorites (OriginalRequest) {
	var htm=OriginalRequest.responseText;
	if(htm.indexOf('se ha producido un error en el sistema al procesar')>0){
		//omniBackEndError('getFavorites');
		$("fav_list").innerHTML='';
		hideLoading($("fav_list"));
		return false;
    }
    var favList = TMSSite.readCookie('favList');
	var aFavList = favList == null ? null : favList.split("@");
	if(htm.indexOf('error')<0){
		if (aFavList.length>0 && aFavList != null){
			for(var i=0; i<aFavList.length-1; i++){
				var aVin = aFavList[i].split("|");
				if(OriginalRequest.responseText.indexOf(aVin[0]) < 0) {
					htm+="<div id='fav_item_"+aVin[0]+"' class='favorite_sold' onmouseover=\"this.style.backgroundColor='#e5ecf1'\"; onmouseout=\"this.style.backgroundColor='#ffffff'\"; >";
					htm+="<div class='clear'></div>";
					htm+="<div class='listing_sold' id='fav_listing_"+aVin[0]+"'><b>"+aVin[1]+" "+aVin[2]+"</b><br />";
					htm+="<b>"+aVin[3]+"</b><br />";
					htm+=aVin[4]+" millas<br />";
					htm+="<a href='javascript:void(null);' onclick='deleteFavItem(\""+aVin[0]+"\");'>Eliminar</a><br />";
					htm+="</div>";
					htm+="<div class=\"clear\"></div>";
					htm+="</div>";
				}
			}
		}
		$("fav_list").innerHTML=htm;
		$("favcountdisplay").innerHTML=favCount;
	} else {
		//$("fav_list").innerHTML=htm;
		$("fav_list").innerHTML="";
	}
	setTimeout('hideLoading($("fav_list"));',500);
}
 function favIt(vin){
	 if($('favid-'+vin).checked){
		 addFavItem(vin)
	 }else{
		 deleteFavItem(vin)
	 }
 }
 function addFavItem(vin){
	 if((favCount<10) || (favCount==null)){
		 if(favList.indexOf(vin)<0){
			favList+=vin+',';
			favCount++;
			$(vin).addClassName('_fav');
				var vinStr = vin + "|" + $(vin).getAttribute('year') + "|" + $(vin).getAttribute('model') + "|" + $(vin).getAttribute('price') + "|" + $(vin).getAttribute('mileage');
				if(TMSSite.readCookie('favList')!=null){
					TMSSite.createCookie('favList',TMSSite.readCookie('favList')+vinStr+'@',30);
					TMSSite.createCookie('favCount',favCount,30);
					$("favcountdisplay").innerHTML=favCount;
				}else{
					TMSSite.createCookie('favList',vinStr+'@',30);
					TMSSite.createCookie('favCount',favCount,30);
					$("favcountdisplay").innerHTML=favCount;
				}
				//omniResultsAddFavorites($(vin).getAttribute('dealerCode'),vin)
				if (TMSSite.readCookie('favAlert')!=='n'){
					$('inventory_alert').show();	
				}
			}
	}else{
		setTimeout("TMSSite.disclaimerHotlink('/includes/errors/maxfavorites.incl');",500);
		$('favid-'+vin).checked=false;
	}
}

function deleteFavItem(vin){
	var regEx = new RegExp(vin+'.*?@', 'gi') ;
	TMSSite.createCookie('favList',TMSSite.readCookie('favList').replace(regEx,''),30);
	favList=favList.replace(vin+',','');
	//$("fav_item_"+vin).remove();
	favCount--;
	$(vin).removeClassName('_fav');
	TMSSite.createCookie('favCount',favCount,30);
	$("favcountdisplay").innerHTML=favCount;
	if($('favid-'+vin)){
		$('favid-'+vin).checked=false;
	}
}
function deleteAllFavItems(){
	$("favcountdisplay").innerHTML=favCount;
	//$A($('results').getElementsByClassName("favitem")).each(function(el){
		$$('#results input').each(function(el){
			el.checked=false;
	   });
	   $$('#results div').each(function(el){
			el.checked=false;
	   });
	    $("wrapper").childElements().each(function(el) {
            if (el.id.length == 17) {
				el.removeClassName('_fav');
			}
		});
	TMSSite.createCookie('favList','',30);
	TMSSite.createCookie('favCount','0',30);
	favList='';
	favCount=0;
	$("favcountdisplay").innerHTML=favCount;
}

function delFavCookies(){
	TMSSite.createCookie('favCount','',-1);
	TMSSite.createCookie('favList','',-1);
	favList='';
	favCount=0;
}

function getVehicles(){
	var url = '';
	var tempFavList = '';
	if(TMSSite.readCookie('favList')!=null){
		tempFavList = "|"+TMSSite.readCookie('favList').replace(/\|.*?@/gi,'|');
	}
	if (loc=='b'){
		url="/inventory/data/dataCommon3.asp";
	}else if (loc=='t'){
		url="/toyotaTCUV/inventory/searchV2.do";
	}else{
		url="/toyotaTCUV/inventory/searchV2.do";
	}
	var rand   = Math.random(9999);
	var pars = '';
	//if ($("SearchByDealerCode").value!==""){
	if ($("SDealer").value!==""){
		/*if($('SModel').value==''){
			selectVehicles();
			$('searchstep1').show();
		}*/
	//$('searchzip').hide();
	//$('searchdealer1').show();
			
	pars   = "RequesterID="+RequesterID+
				//"&rand=" + rand +
				//"&noxslt=yes"+
				"&sdwsMethod=GetVehicles"+
				"&SecurityToken="+SecurityToken+
				"&language="+language+
				"&displayType="+displayType+
				"&action=getVehicles"+
				"&SourceId="+SourceId+
				"&SModel="+escape($F("SModel"))+				
				"&SZIP="+$("SZIP").value+
				//"&SearchState="+$F("SearchState").value+
				//"&SRadius="+$("SRadius").value+
				"&SYearMin="+$("SYearMin").value+
				"&SYearMax="+$("SYearMax").value+
				"&SPriceMin="+$("SPriceMin").value+
				"&SPriceMax="+$("SPriceMax").value+
				"&SMilesMin="+$("SMilesMin").value+
				"&SMilesMax="+$("SMilesMax").value+
				"&SDealer="+$("SDealer").value+
				"&SortField="+$("SortField").value+
				"&SortOrder="+$("SortOrder").value+
				"&today="+now.getDate()+
				"&responseXsl="+xslv+
				//"&FavList="+escape(tempFavList.substring(0,tempFavList.length-1))+
				"&FavList="+escape(tempFavList)+
				"&FavCount="+TMSSite.readCookie('favCount');
				//"&SearchRecSample="+//$("SearchRecSample").value+
				//"&SearchRecStart=";//+$("SearchRecStart").value;
				//"&SVIN="+$("SVIN").value;
	
	}else{
	pars   = "RequesterID="+RequesterID+
				
				//"&noxslt=yes"+
				"&sdwsMethod=GetVehicles"+
				"&SecurityToken="+SecurityToken+
				"&language="+language+
				"&rand=" + rand +
				"&displayType="+displayType+
				"&action=getVehicles"+
				"&SourceId="+SourceId+
				//"&SModel="+escape($F("SModel").substring(0,$F("SModel").length-1))+
				"&SModel="+escape($F("SModel"))+
				"&SZIP="+$("SZIP").value+
				//"&SearchState="+$F("SearchState").value+
				"&SRadius="+$("SRadius").value+
				"&SYearMin="+$("SYearMin").value+
				"&SYearMax="+$("SYearMax").value+
				"&SPriceMin="+$("SPriceMin").value+
				"&SPriceMax="+$("SPriceMax").value+
				"&SMilesMin="+$("SMilesMin").value+
				"&SMilesMax="+$("SMilesMax").value+
				"&SDealer="+$("SDealer").value+
				"&SortField="+$("SortField").value+
				"&SortOrder="+$("SortOrder").value+
				"&NumRecs="+$("NumRecs").value+
				"&StartingRec="+$("StartingRec").value+
				"&responseXsl="+xslv+
				"&AlertCount="+AlertCount+
				"&AbortCount="+AbortCount+
				//"&FavList="+escape(tempFavList.substring(0,tempFavList.length-1))+
				"&FavList="+escape(tempFavList)+
				"&FavCount="+TMSSite.readCookie('favCount')+
				"&today="+(now.getMonth()+1)+now.getDate()+
				"&SVIN="+$("SVIN").value+
				"&modelCount="+modelCount+
				"&SavedSearch="+TMSSite.readCookie('SaveSearch')+
				"&SModelCode="+$("SModelCode").value;
				//"&HSD="+HSD
				//"&SearchRequiredAccessories="//$("SearchRequiredAccessories").value+
}
	//$("specialsResults").innerHTML="";
	historyBookmark("getVehicles()");
	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoading($('inventory'),'inv'), onComplete: showVehicles} );
	//var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: showVehicles} );
//omniResultsSearch();
	pageAction = "995";
	pixel();
 tempFavList = ""
}

var specialsSeriesId=""
function showVehicles (OriginalRequest) {
	/*if(OriginalRequest.responseText.indexOf('se ha producido un error en el sistema al procesar')>0){
		omniBackEndError('getVehicles');
		$("results").innerHTML=OriginalRequest.responseText;
		hideLoading($('results'));
		return false;
	}*/
	$("results").innerHTML='';
	////$("pagenum").value=1;
	///pfrom=1;
	///pto=5;
//	if ($("SModel").value!=='' || $("SDealer").value!=='' || getQueryVariable('action')!==''){
		$("results").innerHTML=OriginalRequest.responseText;
		hideLoading($('inventory'));
//	}


	if($("filterContent")){$("filter").innerHTML=$("filterContent").innerHTML;
		$("filter").show();
		$("filterContent").innerHTML='';
	} else{
		$("filter").innerHTML='';
		$("filter").hide();
	}
	if (getQueryVariable("SearchModel")!=='' && $("SModel").value==''){
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("avalon")>=0){specialsSeriesId='35';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("camry")>=0){specialsSeriesId='25';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("solara")>=0){specialsSeriesId='27';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("corolla")>=0){specialsSeriesId='18';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("celica")>=0){specialsSeriesId='21';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("echo")>=0){specialsSeriesId='';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("matrix")>=0){specialsSeriesId='19';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("venza")>=0){specialsSeriesId='28';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("yaris")>=0){specialsSeriesId='14';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("mr2")>=0){specialsSeriesId='32';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("4runner")>=0){specialsSeriesId='86';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("fj")>=0){specialsSeriesId='47';$('SModel').value='fj cruiser,';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("land cruiser")>=0){specialsSeriesId='61';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("highlander")>=0){specialsSeriesId='69';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("rav4")>=0){specialsSeriesId='44';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("sequoia")>=0){specialsSeriesId='79';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("sienna")>=0){specialsSeriesId='53';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("tacoma")>=0){specialsSeriesId='71';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("tundra")>=0){specialsSeriesId='82';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("prius")>=0){specialsSeriesId='12';}
		if (getQueryVariable("SearchModel").toLowerCase().indexOf("venza")>=0){specialsSeriesId='28';}
	}else if ($("SModel").value!=='' && specialsSeriesId==""){
		if ($("SModel").value.toLowerCase().indexOf("avalon")==0){specialsSeriesId='35';}
		if ($("SModel").value.toLowerCase().indexOf("camry")==0){specialsSeriesId='25';}
		if ($("SModel").value.toLowerCase().indexOf("solara")==0){specialsSeriesId='27';}
		if ($("SModel").value.toLowerCase().indexOf("corolla")==0){specialsSeriesId='18';}
		if ($("SModel").value.toLowerCase().indexOf("celica")==0){specialsSeriesId='21';}
		if ($("SModel").value.toLowerCase().indexOf("echo")==0){specialsSeriesId='';}
		if ($("SModel").value.toLowerCase().indexOf("matrix")==0){specialsSeriesId='19';}
		if ($("SModel").value.toLowerCase().indexOf("venza")==0){specialsSeriesId='28';}
		if ($("SModel").value.toLowerCase().indexOf("yaris")==0){specialsSeriesId='14';}
		if ($("SModel").value.toLowerCase().indexOf("mr2")==0){specialsSeriesId='32';}
		if ($("SModel").value.toLowerCase().indexOf("4runner")==0){specialsSeriesId='86';}
		if ($("SModel").value.toLowerCase().indexOf("fj")==0){specialsSeriesId='47';$('SModel').value='fj cruiser,';}
		if ($("SModel").value.toLowerCase().indexOf("land cruiser")==0){specialsSeriesId='61';}
		if ($("SModel").value.toLowerCase().indexOf("highlander")==0){specialsSeriesId='69';}
		if ($("SModel").value.toLowerCase().indexOf("rav4")==0){specialsSeriesId='44';}
		if ($("SModel").value.toLowerCase().indexOf("sequoia")==0){specialsSeriesId='79';}
		if ($("SModel").value.toLowerCase().indexOf("sienna")==0){specialsSeriesId='53';}
		if ($("SModel").value.toLowerCase().indexOf("tacoma")==0){specialsSeriesId='71';}
		if ($("SModel").value.toLowerCase().indexOf("tundra")==0){specialsSeriesId='82';}
		if ($("SModel").value.toLowerCase().indexOf("prius")==0){specialsSeriesId='12';}
		if ($("SModel").value.toLowerCase().indexOf("venza")==0){specialsSeriesId='28';}
	}else if (specialsSeriesId==""){
			specialsSeriesId="25"
	//}else{
		//specialsSeriesId="25"
	}
	getLocalSpecials('seriesId',$("SZIP").value,specialsSeriesId,'','','specialsResults','LONG');
	//if ($('SDealer').value!=''&& $('SDealer').value!=null){
	//	$('SDealer'+$('SDealer').value).checked=true;
	//}
	//filterAttr='';
	
	for (var i = 0; i < filterAttr.length; i++) {
	    var e = document.getElementsByName(filterAttr[i].item);
	    for (var j = 0; j < e.length; j++) if (e[j].value == filterAttr[i].value) {e[j].checked = (filterAttr[i].item == "SearchModels" ? true : false); filter(filterAttr[i].item, filterAttr[i].value, true); }
	}
	if ($('results')){
		$('searchbutton').src="/img/inv_b_update.png"	
	}else{
		$('searchbutton').src="/img/b_search2.png"	
	}
	historyBookmark("getVehicles()");
	fireTagInv('84.12','','','',''+$('SearchResults_Returned').value+'');
	//if($('SearchResults_Returned').value > +$("SearchRecSample").value){
	//	updateVehicles();
	//}
}

function toggleFilterLayer(a){
	 $(a+'filterlist').toggle();
	 $(a+'collapse',a+'expand').invoke('toggle'); 
}
function toggleSelectAll(v) {
    var a = document.getElementsByName(v);
    for (var i = 0; i < a.length; i++) {
        if (!a[i].checked) {
            a[i].checked = true;
        } 
    }
}
function toggleDeSelectAll(v) {
    var a = document.getElementsByName(v);
    for (var i = 0; i < a.length; i++) {
        if (a[i].checked) {
            a[i].checked = false;
        }
    }
}

function clear_all(v) {
    var a = document.getElementsByName(v);
    for (var i = 0; i < a.length; i++) {
        if (a[i].checked) {
            a[i].checked = false;
            filter(v, a[i].value, false);
        }
    }
}
function select_all(v) {
    var a = document.getElementsByName(v);
    for (var i = 0; i < a.length; i++) {
        if (!a[i].checked) {
            a[i].checked = true;
            filter(v, a[i].value, false);
        }
    }
}
function select_segment(v,s) {
    var a = document.getElementsByName(v);
    for (var i = 0; i < a.length; i++) {
		if(a[i].getAttribute('segment')==s){
				if (!a[i].checked) {
					a[i].checked = true;
					//filter(v, a[i].value, false);
					fadeAlerts();
			}
		}
    }
	setModels();
}
function clear_segment(v,s) {
    var a = document.getElementsByName(v);
    for (var i = 0; i < a.length; i++) {
		if(a[i].getAttribute('segment')==s){
				if (a[i].checked) {
					a[i].checked = false;
					//filter(v, a[i].value, false);
			}
		}
    }
	setModels();
}


function addHiddenVehicles (OriginalRequest) {
	$("totalFetched").value=parseInt($("totalFetched").value)+25;
	$("results_table_footer").insert({before: OriginalRequest.responseText});
	$A($("results_table").getElementsByClassName("vehicle_image")).each(
      function(item) {
      new Draggable(
            item.id,
            {
			   revert: true
            }
         );
      }
   );
   $A($("results_table").getElementsByClassName("pager_next")).each(function(element){
		element.show();
	});
}

function deleteCompare(vin){
	var regEx = new RegExp (vin+'.*?@', 'gi') ;
	TMSSite.createCookie('favList',TMSSite.readCookie('favList').replace(regEx,''),30);
	favList=favList.replace(vin+',','');
	//$("fav_item_"+vin).remove();
	favCount--;
	TMSSite.createCookie('favCount',favCount,30);
	$("favcountdisplay").innerHTML=favCount;
	//hideCompare();
	if($('favid-'+vin)){
		$('favid-'+vin).checked=false;
	}
	getCompare();
 }
function swapCompare(v){
var favVisible=0;
	$$('.cv_compare input').each(function(el){
		if( el.checked==true){
		favVisible++;
	}
	});
	if(favVisible<=3){
		if($('favSelector'+v).checked){
			$('cv_listing_'+v).appear({duration:0.5});
			$('cv_listing_'+v+'a').appear({duration:0.5});
			//$('fav'+v).remoClassName('cv_compare_disabled');
			}else{
			$('cv_listing_'+v).fade({duration:0.5});
			$('cv_listing_'+v+'a').fade({duration:0.5});
			//$('fav'+v).addClassName('cv_compare_disabled');
			}
	}else{
		TMSSite.disclaimerHotlink('/includes/errors/swapfavorites.incl');
	$('favSelector'+v).checked=false;
	}
}
function getCompare(){
	if(favCount>1){
		if(TMSSite.readCookie('favList')!==null && TMSSite.readCookie('favList')!==''){
			var url = '';
			if (loc=='b'){
				url="/inventory/data/dataCommon3.asp";
			}else if (loc=='t'){
				url="/toyotaTCUV/inventory/searchV2.do";
			}else{
				url="/toyotaTCUV/inventory/searchV2.do";
			}
			//omniResultsCompare();

			var tempFavList = TMSSite.readCookie('favList').replace(/\|.*?@/gi,',');
			var rand   = Math.random(9999);
			var pars   = "RequesterID="+RequesterID+
						"&rand=" + rand +
						"&action=getCompare"+
						"&sdwsMethod=GetVehicles"+
						"&SecurityToken="+SecurityToken+
						"&language="+language+
						"&SZIP="+$("SZIP").value+
						"&displayType=compareList"+
						"&today="+now.getDate()+
						"&responseXsl="+xslc+
						"&SVIN="+escape(tempFavList.substring(0,tempFavList.length-1));
			//historyBookmark("getCompare()");
			var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoading($('inventory')), onComplete: showCompare, onError: showFailure} );
		}else{
			//alert('no favorites to compare');
			TMSSite.disclaimerHotlink('/includes/errors/nofavorites.incl');
		}
	}else if (favCount==1){
		//alert('need more than one fav to compare');
		var tempFavList = TMSSite.readCookie('favList').replace(/\|.*?@/gi,',');
		getDetails(escape(tempFavList.substring(0,tempFavList.length-1)));
	} else {
		//alert('need more than one fav to compare');
		TMSSite.disclaimerHotlink('/includes/errors/nofavorites.incl');
	}
	
}
function showCompare (OriginalRequest) {
	showMask();
	$("overlay_compare").innerHTML=OriginalRequest.responseText;
	$('overlay_contact').hide();
	$('overlay_calculator').hide();
	$('overlay_gallery').hide();
	$("overlay_compare").show();
	hideLoading($("inventory"));

	var modelList="";
	$("compvehicles_bg").childElements().each(function(el) {
		if(el.getAttribute("modellist")!==null){
				   modelList+=el.getAttribute("modellist")+",";
		}
		
    });
	modelList=modelList.substring(0,modelList.length-1);
	fireTag('84.14',{'<zip>':''+$('SZIP').value+'','<model1,model2,model3>':''+modelList+''})
}
function hideCompare () {
	hideMask();
	$('overlay_compare').hide();
	$('overlay_compare').innerHTML="";
}

function showLoading (mask,type) {
	$("waitRadius").innerHTML=$('SRadius').value;
	$("waitZipCode").innerHTML=$('SZIP').value;
	var contentSize =mask.getDimensions();
	//$("search_loading").addClassName("fade");
	//var modalLoading = $('search_loading');
	Position.clone(mask, 'search_loading', {setWidth: true, setHeight: true });
	//$('search_loading').style.zIndex=1;
	$('search_loading').style.left=0;
	if (type=='inv' && type!='' && type!=null){
		$('search_loading_inv').show();
		
	}else if (type=='noinv'){
		$('search_loading_noinv').show();
	} else {
		$('search_loading_wait').show();
	}
	$("search_loading").show();
	$('loading_img').show();
	//modalLoading.show();
}

function hideLoading (content) {
	
	//if($(content).getHeight()>25){
	//	$("results").style.height=$(content).getHeight()-20+'px';
	//}
	$('loading_img').hide();
	$("search_loading").hide();
	//$(content).removeClassName("fade");
	//$(content).setStyle({visibility: "visible"});
	//$('search_loading').style.zIndex=1;
	//modalLoading.hide();
	$('search_loading_wait').hide();
	$('search_loading_inv').hide();
	$('search_loading_noinv').hide();
	
	
}

function translateRadius(rr){
	rr=Math.round(rr);
	if(rr==1){
	$('SRadius').value=10;
	} else if (rr==2) {
	$('SRadius').value=25;
	} else if (rr==3) {
	$('SRadius').value=50;
	} else if (rr==4) {
	$('SRadius').value=100;
	} else if (rr==5) {
	$('SRadius').value=250;
	} else if (rr==6) {
	$('SRadius').value=0;
	} else {
	$('SRadius').value=25;
	}
	if(rr==6){
		$('selectedRadius').innerHTML='Ilimitado';
		$('SearchRadiusLabel').innerHTML='Ilimitado';
		$('handleRadius-2-img').title='Ilimitado';
	}else{
		$('selectedRadius').innerHTML=$('SearchRadius').value + ' millas';
		$('SearchRadiusLabel').innerHTML=$('SearchRadius').value + ' millas';
		$('handleRadius-2-img').title=$('SearchRadius').value + ' millas';
	}
	//if ($('SZIP').value!=''){
//		getVehicles();
//	}
}

function kbbComplete(){
	document.formnameQQm.tradein[0].checked = true;
	document.formnameQQm.kbbComplete.value = 'yes';
	$('trade_in').value=document.formnameQQm.tradeInPriceEstimate.value;
	document.formnameQQm.tradeInYear.readOnly=true;
	document.formnameQQm.tradeInMakeName.readonly=true;
	document.formnameQQm.tradeInModelName.readonly=true;
	document.formnameQQm.tradeInTrim.disabled=true;
	document.formnameQQm.tradeInCondition.disabled=true;
	document.formnameQQm.tradeInMileage.disabled=true;
	document.formnameQQm.tradeInPriceEstimate.disabled=true;
}	
var tempYears='';
var tempMiles='';
var tempPrice='';


function setSearchModel(model){
	$('SModel').value=""
	$$("input.vehicleCheckbox").each(function(element){
		var amodel=model.split(',');
		var i=0;
		for (i=0;i<=amodel.length-1;i++){
			if(element.value.toLowerCase()==amodel[i].toLowerCase() ){//&& $('SModel').value===''){
				element.checked=true;
				$('SModel').value+=element.value+",";
				modelCount++;
			}
		
		//$('SModel').value=model;
		if ($('SModel').value==","){$('SModel').value=""};
		//if ($('SModel').value.indexOf('Camry,')!=1){$('SModel').value=$('SModel').value.replace('Camry,','Camry,Camry Hybrid,')};
		}
	});
	setModels();
}

//var bValidated = false;
function validate() {
	//fadeAlerts();
	if($("SDealer").value!=""){
		getVehicles();
		//alert('y');
		return false;
	}

	//alert('z');
	if(!isZip($("SZIP").value)){
	//alert('nozip');
	//if (!(val_zipcodeP(vsearch.SZIP.value)) ){
			//TMSSite.disclaimerHotlink("/includes/errors/invalidzip.incl");
			if($('search_alert')){$("search_alert").fade({duration:0.5});}
			$("search_alert_zip").appear({duration:0.5});
			$("SZIP").blur();
			$("SZIP").focus();
			fireTag('83.1',{'<error_message>':'Please enter a valid Zip Code','<zip>':'null'})
		return false;
		}
	else if ((Math.round(document.getElementById("SZIP").value) >=96701) && (Math.round(document.getElementById("SZIP").value) <=96898)){
			TMSSite.extlink.display('http://www.toyota-hawaii.com','Toyota Certified Used Vehicles are NOT available in Hawaii.<br/><br/>To better meet your needs, Toyota is referring you to a third party site to<br/>obtain the information you requested.');
			fireTag('83.1',{'<error_message>':'Toyota Certified Used Vehicles are NOT available in Hawaii'})
		return false;
		}	
	else if ((Math.round(document.getElementById("SZIP").value) >=601) && (Math.round(document.getElementById("SZIP").value) <=988)){			
			TMSSite.extlink.display('http://www.toyotapr.com','Toyota Certified Used Vehicles are NOT available in Puerto Rico.<br/><br/>To better meet your needs, Toyota is referring you to a third party site to<br/>obtain the information you requested.');
			fireTag('83.1',{'<error_message>':'Toyota Certified Used Vehicles are NOT available in Puerto Rico'})
		return false;
		}
	else if ($("VehicleCategory").value===""){
		//TMSSite.disclaimerHotlink("/includes/errors/inventory_category.incl");
		//return false;
		}
	// verify at least one model segment is selected
	if ($("SModel").value == "") {
	    
	    //if (bValidated) {
	        //TMSSite.disclaimerHotlink("/includes/errors/inventory_category.incl");
	        //$('type_list').addClassName('type_list_error');
			if($('search_alert')){$("search_alert").fade({duration:0.5});}
			$("search_alert_type").appear({duration:0.5});
			fireTag('83.1',{'<error_message>':'Please select a vehicle category'})

			//alert('z');
	   // }
		//alert('1');
	    //bValidated = true;
	    return false;
	}
	//$('type_list').removeClassName('type_list_error');
	//bValidated = true;
	
	if(isZip($("SZIP").value)){
		TMSSite.setZip($('SZIP').value);
	}
	//selectVehicles();
	//}
	//alert('end');
	//historyBookmark("getVehicles()");
	getVehicles();
	fireTag('82.1',{'<zip>':''+$('SZIP').value+'','<region>':'','<model>':''+$('SModel').value+'','<segment>':''+$('SearchSegment').value+'','<dealer_code>':''+$('SDealer').value+'','<dealer_name>':''+$('SearchDealerName').value+''});
	return false;
}
function fadeAlerts(){
	if($('search_alert')){$('search_alert').fade({duration:0.5});}
	$('search_alert_zip').fade({duration:0.5});
	$('search_alert_type').fade({duration:0.5});
}

function displayHelp(h) {
	if (h!==""){
		for (var i = 0; i < 8; i++){
			$('help'+i).style.display="none";
		}
	$('help'+h).style.display="block";
	}
}

function showEdrop(v){
	$('a2'+v).style.display='inline';
	$('a1'+v).hide();				
}
function hideEdrop(v){
	$('a2'+v).style.display='none';
	$('a1'+v).show();	
}

function showSold(){

}

function alertme(){
	//alert('failure');
}

function showFailure(){
	//alert('failure');
}

function omniResultsEstimator(page,p16,p17,p47,ev){
		pageAction = "385";
		pixel();
}

function omniResultsGoToDetails(page,p16,p17){
}
function fireTAG(tag,year,trim,zip,region,model,dealer_code,dealer_name,display,pix){
	fireTag(''+tag+'',{'<model_year>':''+year+'','<trim>':''+trim+'','<zip>':''+zip+'','<region>':''+region+'','<model>':''+model+'','<dealer_code>':''+dealer_code+'','<dealer_name>':''+dealer_name+'','<display>':''+display+'','<vehicle_photo_status>':''+pix+''});
}
function fireTAGSort(tag,zip,s){
	fireTag(''+tag+'',{'<zip>':''+zip+'','<sort>':''+s+'','<model>':''+$("SModel").value+''});
}
function fireTAGSaveSearch(tag,zip){
	fireTag(''+tag+'',{'<zip>':''+zip+''});
}
function fireTagCompare(tag,display){
	fireTag(''+tag+'',{'<zip>':''+$('SZIP').value+'','<display>':''+display+''});
}
function omniResultsx(page,p16,p17,p26,p47,ev){
		pageAction = "995";
		pixel();
}
function omniResultsSearch(){
		pageAction = "995";
		pixel();
}

function omniResultsCarfax(page,p16,p17,p47,ev){
}

function omniResultsDealerInventory(page,p16,p20){
}

function omniResultsAddFavorites(p16,p17,p47){
}

function omniResultsCompare(){
}

function omniResultsContact(page,p16,p17){
}

function omniResultsLink(page,p16,p17){
}

function omniResultsPrintPage(){
		//TMSSite.doubleClick("TPDL");
		//TMSSite.doubleClick("TFL");
		//TMSSite.doubleClick("NTL");
}


function omniResultsQuickQuote(p16,p17,strEvents){
}
function showPrint(){
	//$('legend_top').show();
}
function hidePrint(){
	//$('legend_top').hide();
}
function submitViaEnter(evt) {
	evt = (evt) ? evt : event;
	var target = (evt.target) ? evt.target : evt.srcElement;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
	if (charCode == 13 || charCode == 3){ validate(); return false; }
	return true;
}

function omniOcaLink(page,p16,p17){
}

function omniBackEndError(xCall){
}

function sendTCAATag(xSS){
	var ebSession = xSS;
	var ebRand = Math.random()+ ' ';
	ebRand = ebRand * 1000000;
	var strddm = new Image();
	strddm.src='HTTP://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&ActivityID=26097&rnd='+ ebRand + '&Session='+ebSession
}

function getPageState(action){
    var jsonData = {
        "Action" : action,
        "SModel" : $("SModel").value,
        "SZIP" : $("SZIP").value,
        "SRadius" : $("SRadius").value,
        "SYearMin" : $("SYearMin").value,
        "SYearMax" : $("SYearMax").value,
        "SPriceMin" : $("SPriceMin").value,
        "SPriceMax" : $("SPriceMax").value,
        "SMilesMin" : $("SMilesMin").value,
        "SMilesMax" : $("SMilesMax").value,
        "SDealer" : $("SDealer").value,
        "SortField" : $("SortField").value,
        "SortOrder" : $("SortOrder").value,
        "SVIN" : $("SVIN").value,
        "SModelCode" : $("SModelCode").value,
		"SModel" : $("SModel").value
    };
    return jsonData;
}

function setPageState(jsonData) {
    if (jsonData == null) jsonData = _historyDefault;
    if (jsonData != null) {
        $("SModel").value = jsonData.SModel;
        $("SZIP").value = jsonData.SZIP;
        $("SRadius").value = jsonData.SRadius;
        $("SDealer").value = jsonData.SDealer;
		$("SearchByDealerCode").value = $('SearchByDealerCode').value;
        $("SortField").value = jsonData.SortField;
        $("SortOrder").value = jsonData.SortOrder;
        $("SVIN").value = jsonData.SVIN;
        $("SModelCode").value = jsonData.SModelCode;
		$("SortField").value = jsonData.SortField;
		$("SortOrder").value = jsonData.SortOrder,
		$("SYearMin").value = jsonData.SYearMin,
		$("fSearchMinYear").value = jsonData.SYearMin,
        $("SYearMax").value = jsonData.SYearMax,
		$("fSearchMaxYear").value = jsonData.SYearMax,
        $("SPriceMin").value = jsonData.SPriceMin,
		$("fSearchMinPrice").value = jsonData.SPriceMin,
        $("SPriceMax").value = jsonData.SPriceMax,
		$("fSearchMaxPrice").value = jsonData.SPriceMax,
        $("SMilesMin").value = jsonData.SMilesMin,
		$("fSearchMinMiles").value = jsonData.SMilesMin,
        $("SMilesMax").value = jsonData.SMilesMax,
		$("fSearchMaxMiles").value = jsonData.SMilesMax;

		
        $A($("segmentcriterialist").getElementsByClassName("vehicleCheckbox")).each(function(element) {
            var a = jsonData.SModel.split(","), b = false;
            for (var i = 0; i < a.length; i++) if (element.value == a[i]) b = true;
            element.checked = b;
        });

        hideCalculator();
        hideContact();
        hideCompare();
        hideGallery();
        hideDetails();
		$('overlay_content').hide();
        showPrint();
        eval(jsonData.Action);
    }
}
function viewDealerInventory(dealercode,dealername,dealercity,dealerstate,dealerzip){
	$('SDealer').value=dealercode;
	$('SearchByDealerCode').value='y';
	$('dealerName').value=dealername
	$('dealerName1').innerHTML=unescape($('dealerName').value);
	$('dealerName2').innerHTML=unescape($('dealerName').value);
	$('dealerCity').value=dealercity;
	$('dealerCity1').innerHTML=unescape($('dealerCity').value);
	$('dealerCity2').innerHTML=unescape($('dealerCity').value);
	$('dealerState').value=dealerstate;
	$('dealerState1').innerHTML=unescape($('dealerState').value);
	$('dealerState2').innerHTML=unescape($('dealerState').value);
	$('dealerZip').value=dealerzip;
	$('dealerZip1').innerHTML=unescape($('dealerZip').value);
	$('dealerZip2').innerHTML=unescape($('dealerZip').value);
if($('SModel').value!==''){
$('category').hide();
$('searchdealer2').show();
}else{

}

getVehicles();
}
function fireTagInv(tag,year,dealername,region,results_returned){
	fireTag(''+tag+'',{
		'<zip>':''+$('SZIP').value+'',
		'<model>':''+$('SModel').value+'',
		'<segment>':''+$('SearchSegment').value+'',
		'<model_selector_price>':''+CommaFormatted($('SPriceMin').value)+' - '+CommaFormatted($('SPriceMax').value)+'',
		'<model_selector_mileage_range>':''+CommaFormatted($('SMilesMin').value)+' - '+CommaFormatted($('SMilesMax').value)+'',
		'<model_selector_year_range>':''+$('SYearMin').value+' - '+$('SYearMax').value+'',
		'<model>':''+$('SModel').value+'',
		'<model_year>':''+year+'',
		'<search_radius>':''+$('SRadius').value+'',
		'<dealer_code>':''+$('SDealer').value+'',
		'<dealer_name>':''+$('SearchDealerName').value+'',
		'<region>':''+$('SearchRegion').value+'',
		'<number_of_results_returned>':''+$('SearchCount').value+'',
		'<display>':''+$('SearchDisplay').value+'',
		'<trim>':''+$('SearchTrim').value+'',
		'<model1,model2,model3>':''+$('SearchM123').value+'',
		'<sort>':''+$('SortFieldDrop')[$('SortFieldDrop').selectedIndex].text+'',
		'<number_of_results_returned>':''+results_returned+''
	});
}
function fireTagMap(tag,zip,dealercode,dealername,model,year,trim,region){
	fireTag(''+tag+'',{
		'<zip>':''+$('SZIP').value+'',
		'<model>':''+model+'',
		'<model_year>':''+year+'',
		'<dealer_code>':''+dealercode+'',
		'<dealer_name>':''+dealername+'',
		'<trim>':''+trim+'',
		'<display>':''+$('SearchDisplay').value+'',
		'<region>':''+region+''
	});
}
function fireTagContact(tag,year,trim,zip,region,model,dealercode,dealername){
	fireTag(''+tag+'',{
		'<zip>':''+$('SZIP').value+'',
		'<model>':''+model+'',
		'<model_year>':''+year+'',
		'<dealer_code>':''+dealercode+'',
		'<dealer_name>':''+dealername+'',
		'<region>':''+region+'',
		'<trim>':''+trim+'',
		'<display>':''+$('SearchDisplay').value+''
	});
	fireTag('84.18',{
		'<zip>':''+$('SZIP').value+'',
		'<model>':''+model+'',
		'<model_year>':''+year+'',
		'<dealer_code>':''+dealercode+'',
		'<dealer_name>':''+dealername+'',
		'<region>':''+region+'',
		'<trim>':''+trim+'',
		'<display>':''+$('SearchDisplay').value+''
	});
}
function fireTagDownload(tag,zip){
	var m,y,dc,dn,r;
	if($('SModel').value!=''){m=$('SModel').value}else{m='null'}
	y='null';
	if($('SDealer').value!=''){dc=$('SDealer').value}else{dc='null'}
	if($('SearchDealerName').value!=''){dn=$('SearchDealerName').value}else{dn='null'}
	if($('SearchRegion').value!=''){r=$('SearchRegion').value}else{r='null'}
	fireTag(''+tag+'',{
	'<zip>':''+$('SZIP').value+'',
	'<model>':''+m+'',
	'<model_year>':''+y+'',
	'<dealer_code>':''+dc+'',
	'<dealer_name>':''+dn+'',
	'<region>':''+r+'',
	'<trim>':'null'
	});
}

function getScreenCenterY() {
var y = 0;
y = document.viewport.getScrollOffsets().top
+(document.viewport.getHeight()/2);
return(y.round());
}

function getScreenCenterX() {
return((document.body.clientWidth/2).round());
}

