//  <script type="text/javascript">
//  These scripts are for search4.php
//
	  // these 3 see comment in js_FormLoad
		var optNewestYearCIdx;
    var optHighPriceCIdx;
    var optHighMilesCIdx;
    var tmp1;  // used for various Taffy calls
    var tmp2; // ditto
    // milespergallon definition arrays
    //var MpgRangeVals = new Array(0,15,20,25,30,35,200);
    //var MpgRangeKeys = new Array('','0-15','16-20','21-25','26-30','31-35','35 up');
      
    var ChangeLock=false;   // used to prevent a mated change event from
                            // executing it's change event in response to
                            // the first change event changing
                            // it's mated value.
    function js_FormLoad()
    {       
    	// this set of variables maintain the "current" selected index of their
    	// respective options.  If a change event occurs and the new values
    	// are invalid, the "current" value is restored.
        //alert("showprice="+ showPrice);
	    	if(showYears) optNewestYearCIdx=document.forms['search4'].newestYear.selectedIndex;
	    	if(showPrice) optHighPriceCIdx=document.forms['search4'].highPrice.selectedIndex;
	    	if(showMiles) optHighMilesCIdx=document.forms['search4'].highMiles.selectedIndex;		  
        // reset scroll bars from last window
        document.body.scrollLeft=document.forms['search4'].windowScrollX.value;
        document.body.scrollTop=document.forms['search4'].windowScrollY.value;
        js_Chg('none');
		} //end function
		
    function js_YearChanged(WhoChanged)
    {
			// verifies that the newest year is always greater than or equal to
			// the earliest year.
			
			// skip out if this change was triggered by the other yearchange event
      if (ChangeLock) {return;}
     
			var newidx=-1;	// if a change is necessary, this will be the new index
											// but, if the change is valid, the value of -1 will
											// trigger the form submit to update the search
											
      // determine current value for earliest and newest Year
      var optNewestYear=document.forms['search4'].newestYear;
      var optEarliestYear=document.forms['search4'].earliestYear;
      if (optEarliestYear.value == "")
			{	if(optNewestYear.value == "")
      	{ // just reset text of newestyear to empty field
      		optNewestYear.options[0].text="";
      	}
      	// else any other value is ok
      }
      else	// earliest year has a value
      {	// first check if newestyear is "", if so just change it's text
				if (optNewestYear.value == "")
				{ optNewestYear.options[0].text="And Newer";
		    }
				else
				{	//both have values, make sure high is greater than low
        	var earlyyear = parseInt(optEarliestYear.value);
        	var newyear=parseInt(optNewestYear.value);
        	var newyearprev=optNewestYear.options[optNewestYearCIdx].value;
        	if (newyearprev == "") 
					{	newyearprev="0"; }  // catch the default entry
        	newyearprev=parseInt(newyearprev);

        	if (newyear < earlyyear)
        	{	        		
						// if previous high was the default restore it
						if(optNewestYearCIdx == 0)
						{	newidx=0;
							optNewestYear.options[0].text="And Newer";
						}
						else
						{	//now check if previous value is still valid
							if (newyearprev >= earlyyear)
		        	{	// prev value is still valid, so restore it
		        	  newidx=optNewestYearCIdx;
							}
							else
							{ // change newyear to same as earlyyear
			          newidx=optEarliestYear.selectedIndex;
			        }
		        }
		      	ChangeLock=true;
						optNewestYear.selectedIndex=newidx;
			    	ChangeLock=false;
		      }
		    }
      }
      //reset "currentindex" for newest year
      optNewestYearCIdx=optNewestYear.selectedIndex;
      if(newidx==-1)
      {	//update
      	js_Chg(WhoChanged.name);
      }
    } // end function
    

    function js_PriceChanged(WhoChanged)
    {
     // verify that the value for highest price is > lowest price.
     // Note that the two price option arrays have the same number
     // of values, but the actual values for a given index are different
			     
      // skip out if this is a change triggered by the other Price change event
      if (ChangeLock) {return;}

			var newidx=-1;	// if a change is necessary, this will be the new index
											// but, if the change is valid, the value of -1 will
											// trigger the form submit to update the search
	
      // determine current value for lowPrice
      var optHighPrice=document.forms['search4'].highPrice;
      var optLowPrice=document.forms['search4'].lowPrice;
      if (optLowPrice.value == "")
			{ if (optHighPrice.value == "")
      	{	// reset text in case it had been overwritten(see below)
					optHighPrice.options[0].text="And Up";
     		}
     		// else any other price is ok
      }
      else	//low price has a value
			{	//if high price is empty, just change it's text
				if (optHighPrice.value=="")
				{	optHighPrice.options[0].text="And Up";
      	}
      	else
				{	//both have values, make sure high is greater than low  
	        var lprice = parseInt(optLowPrice.value);
	        var hprice=parseInt(optHighPrice.value);
	        var hpriceprev=optHighPrice.options[optHighPriceCIdx].value;
	        // change "" to 0 for prev value
	        if (hpriceprev == "") { hpriceprev="0"; }
					hpriceprev=parseInt(hpriceprev);
	
	        if (hprice <= lprice )
	        {	
	          if (optHighPriceCIdx == 0)
	          {	newidx=0;
	          	optHighPrice.options[0].text="And Up";
	          }
	          else
	          {	// use prev value if still valid
							if (lprice < hpriceprev)
							{	newidx=optHighPriceCIdx;
							}
							else
							{ // change highPrice.value to value at the same index as lowPrice
		          	newidx=optLowPrice.selectedIndex;
		          }
		        }
						ChangeLock=true;
	          optHighPrice.selectedIndex=newidx;
	          ChangeLock=false;
	        }
        }
      }
      optHighPriceCIdx=optHighPrice.selectedIndex;
      if(newidx==-1)
      {	//update
      	js_Chg(WhoChanged.name);
      }      
    } // end function


    function js_MilesChanged(WhoChanged)
    {
     // verify that the value for highest miles is > lowest miles.
     // Note that the two mileage option arrays have the same number
     // of entries, but the values for a given index are different
			
      // skip out if this is a change triggered by the other Miles change event
      if (ChangeLock) {return;}

			var newidx=-1;	// if a change is necessary, this will be the new index
											// but, if the change is valid, the value of -1 will
											// trigger the form submit to update the search
	
      // determine current values
      var optHighMiles=document.forms['search4'].highMiles;
			var optLowMiles=document.forms['search4'].lowMiles;
      if (optLowMiles.value == "")
			{	if(optHighMiles.value == "")
      	{	// Reset highmiles text in case it had been overwritten(see below)
      		optHighMiles.options[0].text="";
      	}
      	// else any setting for highmiles is ok
      }
      else	// lowmiles has a value
      {	//first check for highmiles empty, if so just change its text to "And Up"
      	if (optHighMiles.value == "")
				{
      		optHighMiles.options[0].text="And Up";
     		}
      	else	
				{	// both low and high have values, make sure high is greater than low
					var lmiles = parseInt(optLowMiles.value);
	        var hmiles=parseInt(optHighMiles.value);
	        var hmilesprev=optHighMiles.options[optHighMilesCIdx].value;
	        if(hmilesprev == "") {hmilesprev="0";}
	        hmilesprev=parseInt(hmilesprev);
	        if (hmiles <= lmiles)
	        {	
	        	if (optHighMilesCIdx == 0)
	        	{	newidx=0;
	        		optHighMiles.options[0].text="And Up";
	        	}
						else
						{	if(lmiles < hmilesprev)	// use prev value if still valid
							{	newidx=optHighMilesCIdx;
							} 
							else 
							{ // change highPrice value to value at the same index as lowPrice
		          	newidx=optLowMiles.selectedIndex;
		          }
		        }
	          ChangeLock=true;
          	optHighMiles.selectedIndex=newidx;
          	ChangeLock=false;
	        }
	      }
      }
      optHighMilesCIdx=optHighMiles.selectedIndex;
      if(newidx==-1)
      {	//update
      	js_Chg(WhoChanged.name);
      }
    } //end function
  
  	function js_RadioChanged(radiobutton)
  	{	// set $type
  		document.forms['search4'].type.value=radiobutton.value;
  		// and chg with all parameters left as is
  		js_Update(null);
 		} // end function
  
    function js_RefineSearch(WhoChanged)
		{ with (document.forms['search4'])
		  { 
        postList.value=(WhoChanged != null) ? WhoChanged.name : 'None';
        windowScrollX.value=document.body.scrollLeft;
        windowScrollY.value=document.body.scrollTop;
        js_Reload();
      }
    }
    
    function js_SetSearchCriteria(SebVal)
    { //make and model are always enabled
      var dmode='table-row'; // FireFox W3C
      try
      { document.getElementById("trMake").style.display=dmode;
      }
      catch(ex)
      { dmode='inline';  // IE
      }
      // presets that apply for both embedded and notembedded
      with (document.getElementById("trTrim").style)
      { display = (embed && showTrim) ? dmode : "none";
      }
      with (document.getElementById("trTransmission").style)
      { display = (embed && showTransmission) ? dmode : "none";
      }
      with (document.getElementById("trPrices").style)
      { display = (embed && showPrice) ? dmode : "none";
      }
      with (document.getElementById("trMiles").style)
      { display = (embed && showMiles) ? dmode : "none";
      }
      with (document.getElementById("trColor").style)
      { display = (embed && showColor) ? dmode : "none";
      }
      with (document.getElementById("trBody").style)
      { display = (embed && showBody) ? dmode : "none";
      }
      // if not embedded use dealersettings criteria
      if(!embed)
      { var searchCriteria = ((SebVal=='1') && (searchExpandedCriteria > 1)) ? searchExpandedCriteria : searchBaseCriteria;
        switch(searchCriteria)
        {	case 4:
        	  showTrim = 1;
        	  document.getElementById("trTrim").style.display=dmode;
            showTransmission = 1;
            document.getElementById("trTransmission").style.display=dmode;
        	case 3:
        		showPrice = 1;
        		document.getElementById("trPrices").style.display=dmode;
        		showMiles = 1;
        		document.getElementById("trMiles").style.display=dmode;
        	case 2:
        		showColor = 1;
        		document.getElementById("trColor").style.display=dmode;
            showBody = 1;
            document.getElementById("trBody").style.display=dmode;
        }
      }
      if(showYears)
      { document.getElementById("trYears").style.display=dmode;
      }
      else
      { document.getElementById("trYears").style.display='none';
      }
      if(showCityMPG || showHwyMPG)
      { document.getElementById("trMpg").style.display=dmode;
        with (document.getElementById("mpgCity").style)
        { display = (showCityMPG) ? "inline" : "none";
        }
        with (document.getElementById("spanMpgCity").style)
        { display = (showCityMPG) ? "inline" : "none";
        }
        with (document.getElementById("mpgHwy").style)
        { display = (showHwyMPG) ? "inline" : "none";
        }
        with (document.getElementById("spanMpgHwy").style)
        { display = (showHwyMPG) ? "inline" : "none";
        }
      }
      else
      { document.getElementById("trMpg").style.display='none';
      }
    }
    
    function js_Reload()
    { document.getElementById("TblSearch1").border = 0;
      document.getElementById("TblSearch2").style.display = "none";
      document.getElementById("TblSearchBusy").style.display = "inline";
      document.forms['search4'].submit();
    }
    
    function js_Update(WhoChanged)
		{ var chgname;
      with (document.forms['search4'])
		  { chgname=(WhoChanged != null) ? WhoChanged.name : 'None';
      }
      js_Chg(chgname);
    }
    
    function js_Abort(msg)
    { alert("JavaScript Aborting: "+msg);
      abort();
    }
    
    function js_ExpandSearch(buttoncode)
		{ js_Chg('SEB');
    }
// ***************************************************************************//
    function js_Chg(ChgName)
    { var winx = document.body.scrollLeft;
      var winy = document.body.scrollTop;
      
      //winx=document.body.scrollLeft;
      //winy=document.body.scrollTop;
      var sebval=0; // default
      // setup option boxes per the search criteria
      if( searchExpandedCriteria > 1)
      { sebval = document.forms['search4'].seb.value;
        if(ChgName == 'SEB')
        { sebval = (1 ^ sebval);
          document.forms['search4'].seb.value=sebval;
        }
        if(sebval == 0)
        { document.getElementById('aSeb').innerHTML = "Advanced Search";
        }
        else
        { document.getElementById('aSeb').innerHTML = "Base Search";
        }
      }
      js_SetSearchCriteria(sebval)
        
      with(document.forms['search4'])
      { 
        // ChgName is  used to clear values as needed when a higher level
        // parameter is changed
        switch (ChgName)
        {
          case "RESET":
            // just set all search vars to ""
            if(showLocations) location.value = (location.value == "") ? 'All' : location.value;
            if(showCityMPG) mpgCity.value="";
          case "mpgCity":
            if(showHwyMPG) mpgHwy.value="";
          case "mpgHwy": 
            make.value="";
          case "make":
            model.value="";
          case "model":
            if(showBody) body.value="";
          case "body":
            if(showTrim) trim.value="";
          case "trim":
            if(showColor) color.value="";
          case "color":
            if(showYears) earliestYear.value="";
            if(showYears) newestYear.value="";
            if(showPrice) lowPrice.value="";
            if(showPrice) highPrice.value="";
            if(showMiles) lowMiles.value="";
            if(showMiles) highMiles.value="";
            if(showTransmission) tranyType.value="";
            break;
          case "earliestYear":
            if(showPrice) lowPrice.value="";
            if(showPrice) highPrice.value="";
          case "lowPrice":
          case "highPrice":
            if(showMiles) lowMiles.value="";
            if(showMiles) highMiles.value="";
          case "lowMiles":
          case "highMiles":
            if(showTransmission) tranyType.value="";
            break;
              
          default:
            break;
        }
      
      // use current values to search the taffy db for matches
        var curmpgcity = (showCityMPG) ? mpgCity.value : "";
        var curmpghwy = (showHwyMPG) ? mpgHwy.value : "";
        var curtype = type.value;
        var curmake = make.value;
        var curmodel = model.value;
        var curbody = (showBody) ? body.value : "";
        var curtrim = (showTrim) ? trim.value : "";
        var curcolor = (showColor)? color.value : "";
        var curearliestyear = (showYears) ? earliestYear.value : "";
        var curnewestyear =  (showYears) ? newestYear.value : "";
        var curlowprice = (showPrice) ? lowPrice.value : "";
        var curhighprice = (showPrice) ? highPrice.value : "";
        var curlowmiles = (showMiles) ? lowMiles.value : "";
        var curhighmiles = (showMiles) ? highMiles.value : "";
        var curtranytype = (showTransmission) ? tranyType.value : "";
        var curlocation = (showLocations) ? location.value : "";
      }
      /*
      alert("curmake="+curmake+"\n" +
            "curmodel="+curmodel+"\n" +
            "curbody="+curbody+"\n" +
            "curtrim="+curtrim+"\n" +
            "curcolor="+curcolor+"\n" +
            "curearliestyear="+curearliestyear+"\n" +
            "curnewestyear="+curnewestyear+"\n" +
            "curlowprice="+curlowprice+"\n" +
            "curhighprice="+curhighprice+"\n" +
            "curlowmiles="+curlowmiles+"\n" +
            "curhighmiles="+curhighmiles+"\n" +
            "curtranytype="+curtranytype+"\n" +
            "curlocation="+curlocation+"\n"
            );
      */    
      var qry = {};
      var vlist;
      var tmp;
      var tix;  //temp index
      var searchTitleText;
      var doqry = false;
      // first query is by type
      switch (curtype)
      { case '0':
          qry["isnew"]=0;
          doqry=true;
          searchtitletext = "Search All Used Vehicles";
          if(showButtons)document.getElementById('typerb0').checked="checked";
        break;
        case '1':
          qry["isnew"]=1;
          doqry=true;
          searchtitletext = "Search New Vehicles";
          if(showButtons)document.getElementById('typerb1').checked="checked";
        break;
        case '3':
          qry["certified"]=1;
          doqry=true;
          searchtitletext = "Search Only Certified Used Vehicles";
          if(showButtons)document.getElementById('typerb3').checked="checked";
        break;
        default:
          searchtitletext = "Search All Vehicles";
          if(showButtons)document.getElementById('typerb2').checked="checked";
        break;
      }
      if(curmake != "")   {qry["make"]=curmake; doqry=true;}
      if(curmodel != "")  {qry["model"]=curmodel; doqry=true;}
      if(curbody != "")   {qry["body"]=curbody; doqry=true;}
      if(curtrim != "")   {qry["trim"]= curtrim; doqry=true;}
      if(curcolor != "")  {qry["color"]=curcolor; doqry=true;}
      if(doqry)
      { vlist = veh.find(qry);
        qry = {};
      }
      
      if(showLocations)
      { // if All then no qry needed
        if(curlocation != 'All')
        { // filter by dealerid
          qry["dealerid"]=curlocation;
          vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist);
          qry = {};
        }
      }
      
      if(curmpgcity != "")
      { tix =parseInt(curmpgcity);
        tmp = MpgRangeVals[tix]+1;
        qry["mpgcity"]={lt:tmp};
        vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist);
        if (tix > 1)
        { tmp = MpgRangeVals[tix-1];
          qry["mpgcity"]={gt:tmp};
          vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist);
          qry = {};
        }
      }
      if(curmpghwy != "")
      { tix=parseInt(curmpghwy);
        tmp = MpgRangeVals[tix]+1;
        qry["mpghwy"]={lt:tmp};
        vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist);
        if (tix > 1)
        { tmp = MpgRangeVals[tix-1];
          qry["mpghwy"]={gt:tmp};
          vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist);
          qry = {};
        }
      }
      if(curnewestyear != "")
      { tmp = ("" + (parseInt(curnewestyear) + 1));
        qry["year"]={lt:tmp};
        vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist) ;
        qry = {};
      }
      if(curearliestyear != "")
      { tmp = (parseInt(curearliestyear) - 1);
        qry["year"]={gt:tmp};
        vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist) ;
        qry = {};
      }

      if(curhighprice != "")
      { tmp = (parseInt(curhighprice) + 1);
        qry["price"]={lessthan:tmp};
        vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist) ;
        qry = {};
      }
      if(curlowprice != "")
      { tmp = (parseInt(curlowprice) - 1);
        qry["price"]={gt:tmp};
        vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist) ;
        qry = {};
      }
      
      if(curhighmiles != "")
      { tmp = (parseInt(curhighmiles) + 1);
        qry["miles"]={lt:tmp};
        vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist) ;
        qry = {};
      }
      if(curlowmiles != "")
      { tmp = (parseInt(curlowmiles) - 1);
        qry["miles"]={gt:tmp};
        vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist) ;
        qry = {};
      }

      if(curtranytype != "")
      { qry["transmission"]=curtranytype;
        vlist = (vlist == undefined) ? veh.find(qry) : veh.find(qry,vlist) ;
      }
      
      // load raw data arrays from db query result
      var vmpgcity = new Array();
      var vmpghwy = new Array();
      var vmake = new Array();
      var vmodel = new Array();
      var vbody = new Array();
      var vtrim = new Array();
      var vcolor = new Array();
      var vyears = new Array();
      var vearliestyear = new Array();
      var vnewestyear = new Array();
      var vprices = new Array();
      var vlowprice = new Array();
      var vhighprice = new Array();
      var vmiles = new Array();
      var vlowmiles = new Array();
      var vhighmiles = new Array();
      var vtransmission = new Array();
      var vloccnts= new Array();
      
      //if locations are used, we will count vehs and certified for each location
      if(showLocations)
      { groups.forEach
        ( function (GrpCnt)
          { vloccnts[GrpCnt.grpid] = new Array( 0,0);
          }
        );
      }
     
      var vcnt=0;
      var vused=0;
      var vnew=0;
      var vcert=0;
      veh.forEach
      ( function (Lst)
        { js_Distinct(vmpgcity,Lst.mpgcity);
          js_Distinct(vmpghwy,Lst.mpghwy);
          js_Distinct(vmake,Lst.make);
          js_Distinct(vmodel,Lst.model);
          js_Distinct(vbody,Lst.body);
          js_Distinct(vtrim,Lst.trim);
          js_Distinct(vcolor,Lst.color);
          js_Distinct(vyears,Lst.year);
          js_Distinct(vprices,Lst.price);
          js_Distinct(vmiles,Lst.miles);
          js_Distinct(vtransmission,Lst.transmission);
          vcnt++;
          if(Lst.isnew == 1){vnew++;}else{vused++;}
          if(Lst.certified == 1) vcert++;
          if(showLocations)
          { vloccnts[Lst.dealerid][0]++;  // = vloccnts[Lst.dealerid][0] + 1;
            if(Lst.certified == 1) vloccnts[Lst.dealerid][1]++; // = vloccnts[Lst.dealerid][1]+1;
          }
        }
        ,vlist
      );
      
      //for a single result:
      //  -Search will link directly to "Details" instead of "Browse"
      //  -we need to grab the vehicle obj from the taffy array for later use
      var vehone;
      if(vcnt == 1)
      { vehone = veh.get()[vlist[0]];
        //alert("id=" + vehone.vehid + " " + vehone.make + " " + vehone.model + " d=" + vehone.dealerid + " type=" + vehone.isnew);
      }
					
      //if vehicle count heading is defined, enter count
      if(document.getElementById("td_vcnt") != null)
      { var cntmsg;
        switch(vcnt)
      	{	case 0: cntmsg = '  No Vehicles Found  '; break;
      		case 1: cntmsg = '  1 Vehicle Found  '; break;				
      		default: cntmsg = "  " + vcnt + " Vehicles Found  "; break;
        }
        document.getElementById("td_vcnt").innerHTML = cntmsg;
	    }
      
      //update search title, if embedded override the type defined title
      if(embed)
      { searchtitletext = "Find Your Vehicle";
      }
      document.getElementById("searchtitle").innerHTML = searchtitletext;

      // only show radio button choice if selection has vehicles of that type
      if(showButtons && vcnt == 1)
      { if(vehone.isnew ==1)
        { document.getElementById('typerb1').checked='checked';
        }
        else if(vehone.certified == 1)
        { document.getElementById('typerb3').checked='checked';
        }
        else
        { document.getElementById('typerb0').checked='checked';
        }
      }
      
      // for range options, build range lists unless only one, then insert actual values
      if(showYears)
      { if(vyears.length == 1)
        { vearliestyear[0] = vyears[0];
          vnewestyear[0] = vyears[0];
        }
        else
        { js_HiLow(vyears,vearliestyear,vnewestyear,0);
        }
      }
      if(showPrice)
      { if(vprices.length == 1)
        { vlowprice[0] = vprices[0];
          vhighprice[0] = "";
        }
        else
        { js_HiLow(vprices,vlowprice,vhighprice,5000);
        }
      }
      if(showMiles)
      { if(vmiles.length == 1)
        { vlowmiles[0] = vmiles[0];
          vhighmiles[0] = "";
        }
        else
        { js_HiLow(vmiles,vlowmiles,vhighmiles,10000);
        }
      }
      
      // regardless of selection, we always populate all makes unless either MPG is used
      if(!(showCityMPG || showHwyMPG))
      { var allmakes = new Array();
        veh.forEach
        ( function (Lst)
          { js_Distinct(allmakes,Lst.make);
          }
        );
      }
      
      // define all option objects if used
      with(document.forms['search4'])
      { var optMake=make;
        var optModel=model;
        var optmpgCity=(showCityMPG) ? mpgCity : null;
        var optmpgHwy=(showHwyMPG) ? mpgHwy : null;
        var optBody=(showBody) ? body : null;
        var optTrim=(showTrim) ? trim : null;
        var optColor=(showColor) ? color : null;
        var optEarliestYear=(showYears) ? earliestYear : null;
        var optNewestYear=(showYears) ? newestYear : null;
        var optHighPrice=(showPrice) ? highPrice : null;
        var optLowPrice=(showPrice) ? lowPrice : null;
        var optHighMiles=(showMiles) ? highMiles : null;
        var optLowMiles=(showMiles) ? lowMiles : null;
        var optTranyType = (showTransmission) ? tranyType : null;
      }
      
       // clear and repopulate the option dropdowns with the new results
      var dtxt;
      if(showCityMPG || showHwyMPG)
      { // use distinct list instead of allmakes
        dtxt = (vmake.length == 1) ? vmake[0] : "Any Make" ;
        js_AppendOptions(optMake,vmake,'S',curmake,dtxt);
      }
      else
      { js_AppendOptions(optMake,allmakes,'S',curmake,"Any Make");
      }
      js_AppendOptions(optModel,vmodel,'S',curmodel,"Any Model");
      
      if(showBody) js_AppendOptions(optBody,vbody,'S',curbody,"Any Body");
      
      if(showTrim) js_AppendOptions(optTrim,vtrim,'S',curtrim,"Any Trim");
      
      if(showColor) js_AppendOptions(optColor,vcolor,'S',curcolor,"Any Color");
      
      if(showYears)
      { js_AppendOptions(optEarliestYear,vearliestyear,'I',curearliestyear,"Any Year");
        dtxt = (curearliestyear != "") ? 'And Newer' : '';
        js_AppendOptions(optNewestYear,vnewestyear,'I',curnewestyear,dtxt);
      }
      if(showPrice)
      { js_AppendOptions(optLowPrice,vlowprice,'C',curlowprice,"Any Price");
        dtxt = (curlowprice != "") ? 'And Up' : '';
        js_AppendOptions(optHighPrice,vhighprice,'C',curhighprice,dtxt);
      }
      if(showMiles)
      { js_AppendOptions(optLowMiles,vlowmiles,'N',curlowmiles,"Any Miles");
        dtxt = (curlowmiles != "") ? 'And Up' : '';
        js_AppendOptions(optHighMiles,vhighmiles,'N',curhighmiles,dtxt);
      }
      if(showTransmission) js_AppendOptions(optTranyType,vtransmission,'S',curtranytype,"Any Transmission");

      if(showCityMPG)
      { //var cmpgs= new Array;
        cmpgs = js_MapMpgs(vmpgcity);
        js_AppendOptionsC(optmpgCity,cmpgs,0,curmpgcity);
      }
      if(showHwyMPG)
      { //var hmpgs= new Array;
        hmpgs = js_MapMpgs(vmpghwy);
        js_AppendOptionsC(optmpgHwy,hmpgs,0,curmpghwy);
      }
      
      if(showLocations)
      { var vgrp= new Array;
        vgrp[0]= new Array('All','All Locations');
        var idx=1;
        if(curlocation == 'All')
        { groups.forEach
          ( function (Grp)
            { // only show dealer if he has cars
              if(vloccnts[Grp.grpid][0] > 0)
              { vgrp[idx] = new Array( Grp.grpid,Grp.grpname);
                idx++;
              }
            }
          );
          var sortcol=1;
          var sortstart =1;
          js_Sort('asc','S',sortcol,sortstart,vgrp);
        }
        else
        { var d;
          d = groups.first({grpid:curlocation});
          var id;
          var nam;
          id=d.grpid;
          nam=d.grpname;
          vgrp[idx] = new Array(d.grpid,d.grpname);
        }
        var optLoc = document.forms['search4'].location;
        var valcol=0;
        js_AppendOptionsC(optLoc,vgrp,valcol,curlocation);
      }
      //add all options to GET list if defined
      tmp="";
      if(optMake.value != "") tmp += "&make="+escape(optMake.value);
      if(optModel.value != "") tmp += "&model="+escape(optModel.value);
      if(showBody && optBody.value != "")      tmp += "&body="+escape(optBody.value);
      if(showTrim && optTrim.value != "")      tmp += "&trim="+escape(optTrim.value);
      if(showColor && optColor.value != "") tmp += "&color="+escape(optColor.value);
      if(showCityMPG && optmpgCity.value != "") tmp += "&mpgCity="+escape(optmpgCity.value);
      if(showHwyMPG && optmpgHwy.value != "") tmp += "&mpgHwy="+escape(optmpgHwy.value);

      if(showYears)
      { if(optEarliestYear.value != "") tmp += "&earliestYear="+escape(optEarliestYear.value);
        if(optNewestYear.value != "")   tmp += "&newestYear="+escape(optNewestYear.value);
      }
      if(showPrice)
      { if(optLowPrice.value != "")   tmp += "&lowPrice="+escape(optLowPrice.value);
        if(optHighPrice.value != "")  tmp += "&highPrice="+escape(optHighPrice.value);
      }
      if(showMiles)
      { if(optLowMiles.value != "")   tmp += "&lowMiles="+escape(optLowMiles.value);
        if(optHighMiles.value != "")  tmp += "&highMiles="+escape(optHighMiles.value);
      }
      if(showTransmission && optTranyType.value != "") tmp += "&tranyType="+escape(optTranyType.value);
      if(showLocations && curlocation != "") tmp += "&location="+escape(curlocation);
      
      //Enable the link button for either details or browse or skip if vcnt <=0
      var dids = document.getElementById("d").value;
      var vtype = document.getElementById("type").value;
      var dref = document.getElementById("detailslinkref");
      var bref = document.getElementById("browselinkref");
      if(vcnt == 1)
      { 
        tmp1 = dref.href;
        tmp2 = tmp1.indexOf('?');
        dref.href = tmp1.substring(0,tmp2);
        dref.href += "?d="+dids+"&type="+vtype+"&ids="+vehone.vehid+tmp;
        dref.style.display = "inline";
        bref.style.display = "none";
      }
      else if ( vcnt > 1)
      { 
        tmp1 = bref.href;
        tmp2 = tmp1.indexOf('?');
        bref.href = tmp1.substring(0,tmp2);
        bref.href += "?d="+dids+"&type="+vtype+tmp;
        bref.style.display = "inline";
        dref.style.display = "none";
      }
      else
      { bref.style.display = "none";
        dref.style.display = "none";
      }
      document.getElementById("TblSearch2").style.display = "block";
      //restore window positions
      document.body.scrollLeft=winx;
      document.body.scrollTop=winy;
    }
//**************************************************************************//   
    function js_Distinct(DArray,NewVal)
    { if(NewVal == "")return;
      if(DArray.length <= 0)
      { DArray[0]=NewVal;
      }
      else
      { fnd=false;
        for( var j =0; j<DArray.length;j++)
        { if (DArray[j] == NewVal)
          { fnd=true;
            break;
          }
        }
        if(!fnd) DArray.push(NewVal);
      }
    }
    
    function js_HiLow(NewVals,ALow,AHigh,Range)
    { 
      var fnd;

      if(Range == 0)
      { // 1:1 setup
        for( var j=0; j<NewVals.length;j++)
        { fnd=false;
          for(k=0; k<ALow.length;k++)
          { if (ALow[k] == NewVals[j])
            { fnd=true;
              break;
            }
          }
          if(!fnd)
          { ALow.push(NewVals[j]);
            AHigh.push(NewVals[j]);
          }
        }
      }
      else
      { // entries have a Range offset
        // first find low range for the newval
        for( var j=0; j<NewVals.length;j++)
        { var tnew = (Math.floor(NewVals[j]/Range))* Range;
          fnd=false;
          for(k=0; k<ALow.length;k++)
          { if (ALow[k] == tnew)
            { fnd=true;
              break;
            }
          }
          if(!fnd)
          { ALow.push(tnew);
            AHigh.push(tnew+Range);
          }
        }
      }
    }
        
    function js_ClrOpt(Opt)
    { // clears an option select
      // Opt is the document object
      cnt1 = Opt.length;
      //alert('cnt1=' + cnt1);
      for (var i = cnt1-1; i >= 0; i--)
      { Opt.remove( Opt.length-1);
      }
      //cnt2 = modelobj.length; alert('cnt2=' + cnt2);
    }
    
    function js_MapMpgs(Mpgs)
    { function nc(a,b) { return (a-b);}
      Mpgs.sort(nc);
var m="";
for (var i=0;i<Mpgs.length;i++)
{ m += i+"="+Mpgs[i]+"\n"}
//alert(m);    

      rval = new Array();
      rval[0]= new Array('','Any');
      var tmpidx=0;
      var cidx="";
      var mpgslen = Mpgs.length;
      var last = false;
      for( var j=1; j<MpgRangeVals.length;j++)
      { var def = false;
        for(k=tmpidx; k<mpgslen;k++)
        { //alert("j="+j+", valj="+MpgRangeVals[j]+", def="+def+", k="+k+", Mpgsk="+Mpgs[k]);
          if (Mpgs[k] <= MpgRangeVals[j])
          { if(!def)
            { rval[rval.length]= new Array(j,MpgRangeKeys[j]);
              def=true;
            }
            tmpidx=k+1; // trap for last element
          }
          else
          { tmpidx=k;
            break;
          }
        }
      }
      return rval;
    }
      
    function js_Sort(Order,DType,SortCol,StartIndex,Arr)
    { // Order is 'asc' or 'dsc'
      // DType is "N" for Numeric, "S" for String
      // SortCol is column to use for sorting, ie 0 or 1
      // StartIndex is 0 or 1 for starting point to sort
      // Arr is array to be sorted
      function Swap(m,n)
      { var t = Arr[m];
        Arr[m] = Arr[n];
        Arr[n] = t;
        /*
        var t0 = Arr[m][0];
        var t1 = Arr[m][1];
        Arr[m][0] = Arr[n][0];
        Arr[m][1] = Arr[n][1];
        Arr[n][0]=t0;
        Arr[n][1]=t1;
        */
      }
      var vlen = Arr.length;
      if((vlen - StartIndex) > 1)
      { // sort according to first index with a simple bubble sort
        for( var i=StartIndex; i<vlen-1; i++)
        { for (j=i+1;j<vlen;j++)
          { var k = i;
            var l = j;
            if(Order == 'dsc')
            { k=j;
              l=i;
            }
            if(DType=='N')
            { // numeric sort
              if(Arr[l][SortCol] < Arr[k][SortCol]) Swap(k,l);
            }
            else
            { // default string
              var lck = Arr[k][SortCol];
              var lcl = Arr[l][SortCol];
              lck = lck.toLowerCase();
              lcl = lcl.toLowerCase();
              if( lcl < lck ) Swap(k,l);
            }
          }
        }
      }
      return Arr;
    }
    
    function js_AppendOptions(OptObj,Values,ValuesType,SelectValue,DefaultCaption)
    { //add options where the value and caption are the same data but the caption
      // is reformatted if it's a number
      js_ClrOpt(OptObj);
      var vlen = Values.length;
      function cmps(a,b)
      { //alert("a= " + a + ", b= " + b);
        if(a>b) return 1;
        if(a<b) return -1;
        return 0;
      }
      function cmpn(a,b) { return (a-b);}
      if(vlen>1)
      {
        if(ValuesType == 'N' || ValuesType == 'I' || ValuesType == 'C')
        { Values.sort(cmpn);
        }
        else
        { Values.sort(cmps);
        }
      }
      
      // default entry
      js_AppendOption(OptObj,"",DefaultCaption,SelectValue);
      
      //load rest of options, if only 1 then make it selected
      for(i=0;i<vlen;i++)
      { if(ValuesType=='S' && Values[i]=="") continue;
        var vdat=Values[i];
        var val;
        var txt;
        var selval;
        switch (ValuesType)
        { case 'N':
            val=vdat.toString();
            txt = js_AddCommas(val);
            selval=SelectValue.toString();
          break;
          case 'C':
            val=vdat.toString();
            selval=SelectValue.toString();
            if(vdat == "0" || vdat == "")
            { txt = vdat;
            }
            else
            { txt = '$' + js_AddCommas(val);
            }
          break;
          case 'I':
            val=vdat.toString();
            txt = val;
            selval=SelectValue.toString();
          break;
          default:
            val = vdat;
            txt = val;
            selval=SelectValue;
          break;
        }
        js_AppendOption(OptObj,val,txt,selval,vlen);
      }
    }
    
    function js_AppendOptionsC(OptObj,Values,ValIndex,SelectValue)
    { // Values and Captions are in a two dim array Values
      // ValIndex is 0 or 1 for the column that contains the Value,
      // the other contains the Caption
      js_ClrOpt(OptObj);
      vlen = Values.length;
      //load options, if only 1 then make it selected
      for(i=0;i<vlen;i++)
      { var val;
        var txt;
        val=Values[i][ValIndex];
        txt=Values[i][ValIndex ^ 1];
//alert(" append 878: val=~" + val + "~ txt=~" + txt + "~ SelVal= ~" + SelectValue+"~");
        js_AppendOption(OptObj,val,txt,SelectValue,vlen);
      }
    }
    
    function js_AppendOption(SelObj,OptValue,OptText,SelText,OptCnt)
    {
      var y = document.createElement('option');
      y.value = OptValue;
      y.text = OptText;
      if(OptValue == SelText || OptCnt == 1) y.selected=true;
      try
      { SelObj.add(y,null); // standards compliant
      }
      catch(ex)
      { // IE only
        SelObj.add(y);
      }
    }
      
    function js_AddCommas(nStr)
    {
    	nStr += '';
    	x = nStr.split('.');
    	x1 = x[0];
    	x2 = x.length > 1 ? '.' + x[1] : '';
    	var rgx = /(\d+)(\d{3})/;
    	while (rgx.test(x1)) {
    		x1 = x1.replace(rgx, '$1' + ',' + '$2');
    	}
    	return x1 + x2;
    }
