function getParameters(url)
{
    var params = new Array("y","m","d","c","ca","cc1","cc2","cc3","mi","o","ot","ml","v","r","av","rv","yt","vt","s","vi","t","cp","aid","iid","a","as","at","ap","z","da","e","nx","np","m2","m3","m4","d2","d3","d4","y2","y3","y4","c2","c3","c4","yt2","yt3","yt4","vt2","vt3","vt4","s2","s3","s4","dx","bg","rn","mpg");
    var newUrl = '';
    
    newUrl = url + BuildQueryString(params);  
        
    if (ltxFlag)            
        NADA.Service.LinkTracker.TrackingService(LIParameter, newUrl);                  
    
    return newUrl;
}

function ReplaceQueryStringParamsValue(querystring, paramsValue) {
    params = paramsValue.split('|');
    for (i = 0; i < params.length; i++) {
        querystring = querystring.replace(querystring.substr(querystring.indexOf(params[i] + "=", 0), (querystring.indexOf("&", querystring.indexOf(params[i] + "=", 0)) - querystring.indexOf(params[i] + "=", 0))), ReplaceQueryStringParam(params[i], eval("document.forms[0]." + params[i] + ".value")));
    }
    return querystring;
}

function ReplaceQueryStringParam(name, value) {
    var param = "";
    if (value != null & value != '') {
        param = name + '=' + value;
    }
    return param;
}

function BuildParamArray(prms,prmIds)
{
    var paramArray = new Array();
    var index = 0;
            
    for(i = 0; i < prms.length; i++)
    {
        index = AddParamToArray(paramArray,prmIds[i], prms[i], eval("document.forms[0]." + prms[i] + ".value"), index);
    }
        
    return paramArray;
}

function BuildQueryString(params)
{
    var querystring = "";
    
    for(i = 0; i < params.length; i++)
    {
        querystring += BuildQueryStringParam(   params[i], eval("document.forms[0]." + params[i] + ".value")); 
    }
    return querystring;
}

/*  validation functions*/

function validZip(value){	
	var zipexp = /^\d{5}$|^\d{5}[\-\s]?\d{4}$/	
	return zipexp.test(value)
}


/*Image functions */

function swapImage(imgName, imgPath){
    if (document.images) {
        document.getElementById(imgName).src = imgPath;
    }
}

function ImageLoadFailed(theParent,imgHeight,imgWidth) {
	var isIE=document.all;
	if(isIE)	
		window.event.srcElement.style.display = "None";
		
	document.getElementById(theParent).style.cssText = "border:1px solid #999999;height:" + imgHeight + "px;width:" + imgWidth + "px;background-color:#E3E8EF;text-align:center;";
	document.getElementById(theParent).innerHTML = "<div style='height:24px;margin-top:" + (imgHeight/2-12) +"px'><b>Photo not available</b></div>";
}
function ImageLinkLoadFailed(theParent,imgHeight,imgWidth) {
	var isIE=document.all;
	if(isIE)
		window.event.srcElement.style.display = "None";
		
	document.getElementById(theParent).style.cssText = "padding-bottom:6px;cursor:pointer;border:1px solid #999999;height:" + imgHeight + ";width:" + imgWidth + ";background-color:#E3E8EF;vertical-align: middle;text-align:center;";
	document.getElementById(theParent).innerHTML = "<br><b>Photo not available</b>";
	
}
function HideOnImageLoadFail()
{
	var isIE=document.all;
	if(isIE)	
		window.event.srcElement.style.display = "None";	
}
function calculateAfford(){
		
		var rate = document.forms[0].InterestRate.options[document.forms[0].InterestRate.selectedIndex].value/100/12;
		var nPer = document.forms[0].LoanTerm.options[document.forms[0].LoanTerm.selectedIndex].value;
		var pmt = Math.round(document.forms[0].Monthly_Payment.value);
		var amt = pmt * (1-Math.pow(1/(1+rate), nPer)) / rate;
		var dnPmt = Math.round(document.forms[0].Down_Payment.value);
		if (dnPmt=="") dnPmt = 0;
		var totalCost = amt + dnPmt;
		
		document.forms[0].Afford_Amount.value = Math.abs((Math.round(totalCost*100)/100));
		
}

/* FLASH DETECTION */
var WM_startTagFix = '<\/';

var msie_windows = 0;

if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)){
  msie_windows = 1;
  document.writeln('<script language="VBscript">');
  document.writeln('Dim WM_detect_through_vb');
  document.writeln('WM_detect_through_vb = 0');
  document.writeln('If ScriptEngineMajorVersion >= 2 then');
  document.writeln('  WM_detect_through_vb = 1');
  document.writeln('End If');
  document.writeln('Function WM_activeXDetect(activeXname)');
  document.writeln('  on error resume next');
  document.writeln('  If ScriptEngineMajorVersion >= 2 then');
  document.writeln('     WM_activeXDetect = False');
  document.writeln('     WM_activeXDetect = IsObject(CreateObject(activeXname))');
  document.writeln('     If (err) then');
  document.writeln('        WM_activeXDetect = False');
  document.writeln('     End If');
  document.writeln('   Else');
  document.writeln('     WM_activeXDetect = False');
  document.writeln('   End If');
  document.writeln('End Function');
  document.writeln(WM_startTagFix+'script>');
}

function WM_pluginDetect(plugindescription, pluginxtension, pluginmime, activeXname){
  var i,plugin_undetectable=0,detected=0, daPlugin=new Object();
  
  if (msie_windows && WM_detect_through_vb){
      plugin_undetectable = 0;
  } 
  
  else {
      plugin_undetectable = 1;
  }  
  
  if(navigator.plugins) {
      numPlugins = navigator.plugins.length;
      if (numPlugins > 1) {
	  if (navigator.mimeTypes && navigator.mimeTypes[pluginmime] && navigator.mimeTypes[pluginmime].enabledPlugin && (navigator.mimeTypes[pluginmime].suffixes.indexOf(pluginxtension) != -1)) { // seems like we have it, let's just make sure and check the version (if specified)
	      if ((navigator.appName == 'Netscape') && (navigator.appVersion.indexOf('4.0') != -1)) { // stupid, stupid Netscape can't handle the references to navigator.plugins by number, sooo...
		  for(i in navigator.plugins) {
		      if ((navigator.plugins[i].description.indexOf(plugindescription) != -1) || (i.indexOf(plugindescription) != -1)) { // some versions of quicktime have no description. feh!
			  detected=1;
			  break;
		      }
		  }
	      } else {
		  for (i = 0; i < numPlugins; i++) {
		      daPlugin = navigator.plugins[i];
		      if ((daPlugin.description.indexOf(plugindescription) != -1) || (daPlugin.name.indexOf(plugindescription) != -1)) {
			  detected=1;
			  break;
		      }
		  }
	      }	      // Mac weirdness
      if (navigator.mimeTypes[pluginmime] == null) {
		  detected = 0;
	      }
	  }
	  return detected;
      } 
	  
	  else if((msie_windows == 1) && !plugin_undetectable){
	  return WM_activeXDetect(activeXname);
      } 
	  
	  else { 		
	  return 0;
      }
  } 
  
  else {
      return 0;
  }
}

var isItThere  = WM_pluginDetect('Flash', 'swf', 'application/x-shockwave-flash', 'ShockwaveFlash.ShockwaveFlash');

function number_check(value) 
{ 
	return ( 1 - (value%2) ) 
}

function moveAdHeader() {

    var adWidth = 0;
    var isMove = false;
    var divs = document.getElementsByTagName("div");
    var divAdTitle = null;
    var divAdBox = null;
    var divC;
    var parentDivWidth = 0;
    var divsCount = divs.length;
    makeShoppingWidgetTitle(divs, divsCount);
    if (document.getElementById("hdnIsPostBack").value == "1_25_0_5602") 
        moveAdBox39RVHomePage();
    for (var i = 0; i < divsCount; i++) 
    {
        divC = divs[i];
        if (divC.className == "AdBoxTitle")
        {
		    divAdTitle = divC;
            if (divAdTitle.nextSibling.className == "AdBox" || divAdTitle.nextSibling.className == "Ad")
            {
                if (divAdBox == null) 
                {
                    divAdBox = divAdTitle.nextSibling;   
                }
                else
                {
			        parentDivWidth = divAdBox.style.width;
			        parentDivWidth = Number(parentDivWidth.replace("px",""));
    			    divAdBox = divAdTitle.nextSibling;
			        if ((divAdBox.style.width == "160px")  
				        && (parentDivWidth == 300)) 
			        {
				        divAdTitle.nextSibling.style.width = divAdBox.style.width;
				        divAdTitle.style.position = "relative";
				        divAdTitle.style.left= "140px";
			        }
			    }
			    
            }
           
        }
    }
}

function makeShoppingWidgetTitle(pageDivs, divsCount)
{
    var divWTitle = null;
    var divW = null;
    var isAd40Exists = false;
     
    for (var i = 0; i < divsCount; i++) 
    {
        divWTitle = pageDivs[i]; 
        if (divWTitle.className == "AdBoxWidget" || divWTitle.className == "AdBoxTitle")
        {
            if (divWTitle.nextSibling != null)
            {
                divW = divWTitle.nextSibling;
                if (divW.id == "ad40")
                {
                    divWTitle.className = "AdBoxTitle";
                    isAd40Exists = true;
                }
                else if (divW.id == "ad15" && isAd40Exists)
                {
                    divWTitle.className = "";
                    divW.style.marginTop = "5px";
                }
            }
            
        }
    }
}

function moveAdBox39RVHomePage()
{
    var divPnlAd = null;
    var divAd39 = document.getElementById("ad39");
    if (divAd39 != null)
    {
        divPnlAd = divAd39.parentNode;
        divPnlAd.style.marginTop = "-15px";
        divPnlAd.style.position = "relative";
        divPnlAd.style.zIndex = "10";
    }
}
// custom objects
function ArrayLookup(array, name)
{
    for (var i = 0; i < array.length; i++)
    {
        if (array[i].name == name)
            return array[i].value;
    }
    return null;
}

function AddParamToArray(arrayObj, id, name, value, index)
{
    if (value != null && value != '' && value != 'null')
    {
        var paramObj = new ParamObject(id, name, value);
        arrayObj[index] = paramObj;
        index++;
    }
    return index;
}

function BuildQueryStringParam(name, value)
{
    var param = "";
    if(value != null & value != '')
    {
        param = '&' + name + '=' + value;
    }
    return param;
}

function ParamObject(id, name, value)
{
    this.id = id;
    this.name = name;
    this.value = value;
}
function ConvertToExternal(url,paramArray)
{
    var virtualFolders = "";        
        
    var make = ArrayLookup(paramArray,"m");
    if (make != null && make != '')
    {
        var makeDisplay = ArrayLookup(makesArray, make);
        virtualFolders = AddVirtualFolder(virtualFolders, makeDisplay);        
    }
    
    var year = ArrayLookup(paramArray,"y");
    if (year != null && year != '')
        virtualFolders = AddVirtualFolder(virtualFolders, year);    
        
    var model = ArrayLookup(paramArray,"d");
    if (model != null && model != '')
    {
        var modelDisplay = ArrayLookup(modelsArray, model);
        virtualFolders = AddVirtualFolder(virtualFolders, modelDisplay);        
    } 
        
    var category = ArrayLookup(paramArray,"c");
    if (category != null && category != '')
    {
        var categoryDisplay = ArrayLookup(categoryArray, category);
        virtualFolders = AddVirtualFolder(virtualFolders, categoryDisplay);        
    }
        
    if (virtualFolders != null && virtualFolders != '')
        virtualFolders += "/";    
            
    var pageParameters = GetPageParameters(paramArray);
    
    url = url.replace("<@virtualpath@>",virtualFolders+pageParameters);
    
    return url;
}

function AddVirtualFolder(virtualFolders, value)
{
    if (value != null && value != '')
    {
        if (virtualFolders != null && virtualFolders != '')
            virtualFolders += "/";
            
        virtualFolders += value;
    }       
    return virtualFolders;
}

function GetPageParameters(paramArray)
{
    var paramValues = new Array(paramArray.length-1);
    var paramId = new Array(paramArray.length-1);
    
    for(i = 0; i < paramArray.length; i++)
    {
        paramValues[i] = paramArray[i].value;        
        var temp = paramArray[i].id;
        if (temp.length == 1)
            temp = "0" + temp;
        paramId[i] = temp;        
    }
    var paramValueSect = paramValues.join("_");
    if (paramValueSect != null && paramValueSect != '')
        paramValueSect += "_";
    var parmIdSect = paramId.join("");
    return paramValueSect + parmIdSect;
}


function OpenWindow(url)
{
	winW = 480;
	winH = 280;
	winX = screen.availWidth/2 - winW/2;
	winY = screen.availHeight/2 - winH/2;
		
	var custWin = window.open(url,'ExplanationWin','top=' + winY + ', left=' + winX + ',width=' + winW + ',height=' + winH + ',resizable=1,scrollbars=1');	

}

// functions for rating pages
function GetRateScaleData(args)
    { 
        var context = ""; 
        showRateScale(args, context);
    }
    function ReceiveCurrentRating(arg, context)
    { 
        document.getElementById("hdnRates").value = arg;
        showCurrentRates();
    }
    
    function showCurrentRates()
    {
        var rates = document.getElementById("hdnRates");
        ratesText = rates.value;
        var aryRates = ratesText.split("|");
        var tbl = document.getElementById("tblRatings");
        var tblRatings = tbl.getElementsByTagName("table");
        var iRateNmb = 0;
        var lblID = "";
        var t = "";
        var lblRates = null;
        
        if (tblRatings != null)
        {
            lblRates = tblRatings[0].getElementsByTagName("span");
            
            for (var intI = 0; intI < lblRates.length; intI++) 
            {
                lblID = lblRates[intI].id;
                if (lblID.indexOf("lblRateScale") >=0)
                {
                    t = aryRates[iRateNmb];
                    lblRates[intI].innerHTML = "average of " + t;
                    lblRates[intI].className = "pnlResultShow";
                    iRateNmb++;
                    if (iRateNmb > aryRates.length)
                        break;
                }
            }
        }
    }
   
function setrsisegcookie(rsiseg)
{
    if (rsiseg.length > 0)
    {
        var rsiseg20 = "";
        var segID = "";
        for (var i = 0; i < rsiseg.length; i++) {
            if (rsiseg[i] != "")
            {
                segID = rsiseg[i];
                segID = segID.substring(segID.indexOf("_"));
                rsiseg20 += segID;
            }
            if (i >=19)
                break;
        }    
        var rsi_exp=new Date(rsi_now.getTime()+2419200000);
        var rsi_dom=location.hostname;
        rsi_dom=rsi_dom.replace(/.*(\.[\w\-]+\.[a-zA-Z]{3}$)/,'$1');
        rsi_dom=rsi_dom.replace(/.*(\.[\w\-]+\.\w+\.[a-zA-Z]{2}$)/,'$1');
        rsi_dom=rsi_dom.replace(/.*(\.[\w\-]{3,}\.[a-zA-Z]{2}$)/,'$1');
        SetCookie("rsi_segs", rsiseg20, rsi_exp, rsi_dom);
     }
} 

function SetCookie (name, value, expires, domain) {  
    try 
    {
	    document.cookie = name + "=" + escape (value) +  "; expires=" + expires.toGMTString() + "; path=/; domain=" + domain; 
    }
    catch(ex)
    {
	    throw(ex);
    }
}
function isValidState(sState)
{
    sState = sState.toUpperCase() + "|";
    var validStates = /AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY|/;
    var isValid = sState.match(validStates);
    if(isValid == "")
        return false;
    else
        return true;
}

function debugMethod()
{
    var debug = true;
}

function removeFrame() {

    try {
        var url = top.location.toString().toLowerCase();
        var pos = url.indexOf("nadaguides", 0);
        if (pos < 0) {
            top.location.href = document.location.href;
        }
    }
    catch (e) {
        top.location.href = document.location.href;
    }
}


