//Global Javascript page
GLOBAL_CLICKED = false;

function populateSeries(formName, makeField, seriesField, arrayName, carType) {
	with (eval("document." + formName)) {
		
		varMakeField = eval(makeField);
		//alert(varMakeField.type);
		if ( varMakeField.type == 'hidden' ) {
			tempNum = varMakeField.value;
		} else {
			tempNum = varMakeField.selectedIndex;
		}
		//empty out series box
		varSeriesBox = eval(seriesField);
		for (i=0;i<varSeriesBox.lenght;i++) {
			varSeriesBox.options[i]=null
		}
		varSeriesBox.options.length = 0;
		
		//create new options
		varCarArray = new Array();
		varCarArray = eval(arrayName);
		
		//split new and used 0 = New, 1 = Used
		if (carType == 0) {
			for (j=0;j<varCarArray[tempNum].length;j++) {
				seriesString = varCarArray[tempNum][j];
				var tempOption = new Option(seriesString, seriesString);
				varSeriesBox.options[j] = tempOption;
			}
		} else {
			for (j=0;j<varCarArray[tempNum].length;j++) {
				seriesString = varCarArray[tempNum][j];
				starPos = seriesString.indexOf("*");
				if (parseInt(starPos) > 0) {
					displayString = seriesString.substring(0,parseInt(starPos));
					valueString = seriesString.substring(parseInt(starPos) + 1,seriesString.length);
				} else {
					displayString = seriesString;
					valueString = "All";
				}
				var tempOption = new Option(displayString, valueString);
				varSeriesBox.options[j] = tempOption;
			}
		}
		
	}
}

//generic populate scripts
function populateMakes2(formName, makeField, seriesField, arrayName, carType) {
	with (eval("document." + formName)) {
		varFormField = eval(makeField);
		
		for (i=0;i<varFormField.length;i++) {
			varFormField.options[i]=null
		}
		
		varFormField.options.length = 0;
		varCarArray = new Array();
		varCarArray = eval(arrayName);
		
		for (i=0;i<varCarArray.length;i++) {
			var tempOption = new Option(varCarArray[i].value, varCarArray[i].value)
			varFormField.options[i] = tempOption;
		}
		
		//populate series box
		populateSeries2(formName, makeField, seriesField, arrayName, carType);
	}
}
//For Series and Model
function populateSeries2(formName, makeField, seriesField, arrayName, carType) 
{
	
	with (eval("document." + formName)) 
	{
		//set make index variables
		varMakeField = eval(makeField);
		tempNum = varMakeField.selectedIndex;
		
		//empty out series box
		varSeriesBox = eval(seriesField);
		for (i=0;i<varSeriesBox.length;i++) 
		{varSeriesBox.options[i]=null}
		varSeriesBox.options.length = 0;
		
		//create new options
		varCarArray = new Array();
		varCarArray = eval(arrayName);
		
		//split new and used 0 = New, 1 = Used
		for (j=0;j<varCarArray[tempNum].length;j++)
		{
			doIt = 1;
			seriesString = varCarArray[tempNum][j];
			starPos = seriesString.indexOf("*");
			
			//split array for series and models
			if (parseInt(starPos) > 0)
			{seriesDisplayString = seriesString.substring(0,parseInt(starPos));}
			else 
			{seriesDisplayString = seriesString;}
			
			//stop duplicates
			for (k=0;k<varSeriesBox.options.length;k++) 
			{
				if (seriesDisplayString == varSeriesBox.options[k].value) 
				{
					doIt = 0;
					break; 
				}
			}
			if (doIt == 1) 
			{
				var tempOption = new Option(seriesDisplayString, seriesDisplayString);
				varSeriesBox.options[k] = tempOption;
				tempOption = null;
			}
 		}
	}
}

//generic populate scripts
function populateMakes(formName, makeField, seriesField, arrayName, carType) {
	with (eval("document." + formName)) {
		varFormField = eval(makeField);
		
		for (i=0;i<varFormField.lenght;i++) {
			varFormField.options[i]=null
		}
		
		varFormField.options.length = 0;
		varCarArray = new Array();
		varCarArray = eval(arrayName);
		
		for (i=0;i<varCarArray.length;i++) {
			var tempOption = new Option(varCarArray[i].value, varCarArray[i].value)
			varFormField.options[i] = tempOption;
		}
		
		//populate series box
		populateSeries(formName, makeField, seriesField, arrayName, carType);
	}
}


//Coenie se functions
  function setCookie(name, value, expires, path, domain, secure) 
  {
    var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
    document.cookie = curCookie;
  }
  
  function getCookie(name) 
  {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
      begin = dc.indexOf(prefix);
      if (begin != 0) return null;
    } else
      begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
      end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
  }
 
  function deleteCookie(name, path, domain) 
  {
    if (getCookie(name)) 
    {
      document.cookie = name + "=" + 
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
  }
 
  function readCookie(aName)
  {
    //alert(document.cookie);
    var start = document.cookie.indexOf(aName+"=");
    if (start == -1){return ''} 
    start = document.cookie.indexOf("=",start)+1;
    var end =  document.cookie.indexOf(";",start);
    if (end == -1){return ''}
    return unescape(document.cookie.substring(start,end));
  }
  
  function viewImage(obj,size) {
	window.open('showImage.cfm?imageName='+obj+'&size='+size,'imageWin','width=180,height=180,scrollbars=no,toolbars=no');
  }
  
  function openWin(url,w,h) {
	window.open(url,'pop','width='+w+',height='+h+',scrollbars=no,toolbars=no');
  }
  
  function fixDate(date) 
  {
    var base = new Date(0);
    var skew = base.getTime();
    if (skew > 0)
      date.setTime(date.getTime() - skew);
  }
  
  function writeCookie(aName,aValue)
  {
    var exDate = new Date(2050,1,1,1,1,1,1);
    var start = document.cookies.indexOf(aName+"=");
    var end =  document.cookies.indexOf(";e",start)-1;
    if ((end == -1)||(start == -1))
    {
      document.cookies = document.cookies+''+aName+'='+aValue+';expires='+exDate+';';
    }
    else
    {
      s = document.cookies.substring(0,start)+
      aName+"="+aValue+";expires="+exDate+";"+                  
      document.cookies.substring(end,99999);
    }
  }
  
 function popMessage(arrayNum) {
  	if (arrayNum != null) {
		tempMessage = messageArray[arrayNum];
		if (arrayNum == 0) {
			window.status = "";
			if (parent.botbar) {
				t = window.setTimeout("parent.botbar.document.messageForm.helpMessage.value = tempMessage;", 1000);
			}
		} else {
			parent.botbar.document.messageForm.helpMessage.value = tempMessage;
		}
	}
 }
  
function out(obj,color){obj.style.backgroundColor = color;}
function over(obj,color){obj.style.backgroundColor = color;cursor(obj);}
function cursor(obj){obj.style.cursor = 'hand';}
function clicked(obj){if ((obj.cells[1].children[0])&&(!GLOBAL_CLICKED)){if (obj.cells[1].children[0].tagName == "A"){location.href = obj.cells[1].children[0].href;}}}
function clicked0(obj){if ((obj.cells[0].children[0])&&(!GLOBAL_CLICKED)){if (obj.cells[0].children[0].tagName == "A"){parent.content.location.href = obj.cells[0].children[0].href;}}}

function addList(cons, carID, Type) {
	if (Type == "New") {
		varString = "carID";
	} else {
		varString = "adnumber";
	}
	//alert(carID);
	parent.botbar.location.href = "botbar.cfm?" + varString + "=" + carID + "&Type=" + Type;
	var tempImageObject;
	tempImageObject = eval("document." + cons + carID);
	tempImageObject.src = "../images/misc/blankBut.gif";
}

function goFinance(sURL) {
	if (!sURL) {
		URL = "https://www.wesbank.co.za/fastapp/mccarthy/selectmake.asp";
	} else {
		URL = sURL;
	}
	ID = "Finance";
	t = window.open(URL, ID, 'width=780, height=480, scrollbars=yes');
	t.focus();
}

function viewDetailUsed(adnumber, page) {
	sURL = "viewVehicle.cfm?adnumber=" + adnumber + page;
	ID = "detailWin";
	t = window.open(sURL, ID, 'width=650, height=440, scrollbars=yes');
	t.focus();
}
function viewDetailNew(carID, page) {
	sURL = "viewVehicle.cfm?carID=" + carID + page;
	ID = "detailWin";
	t = window.open(sURL, ID, 'width=650, height=440, scrollbars=yes');
	t.focus();
}

//varChecked = false;

function ShowErrorFixError(aObject,aMessage,aDefault)
{
	if (!aDefault) { aDefault=0; }
	 alert(aMessage);
	 aObject.value = aDefault;	
	 aObject.focus();
}

//calculator functions----------------------------------------------------
function calculate() {
	with (document.calculatorForm) {
		//validate all fields
		varCalc = true;
		if ((price.value == "")||(isNaN(price.value))) {
			ShowErrorFixError(price,"Please enter a valid price!")
			varCalc = false;
		} else if ((deposit.value == "")||(isNaN(deposit.value))) {
			ShowErrorFixError(deposit,"Please enter a valid deposit!")
			varCalc = false;
		} else if ((interest.value == "")||(isNaN(interest.value))) {
			ShowErrorFixError(interest,"Please enter a valid interest rate!")
			varCalc = false;
		} else if ((payments.value == "")||(isNaN(payments.value)) || (payments.value > 60)) {
			ShowErrorFixError(payments,"Please enter a valid number of payments!\nA maximum of 60 is allowed",60)
			varCalc = false;
		}
		
		if (varCalc == true) {
			//all values are set, do calculations
			if (interest.value > 1.0) {
	        	varInterest = parseFloat(interest.value)/100.0;
	    	}
			varInterest = parseFloat(varInterest)/12;
			varPow = 1;
			for (i = 0; i < payments.value; i++) {
	        	varPow = varPow * (1 + varInterest);
			}
			tempMonthly = ((parseInt(price.value) - parseInt(deposit.value)) * varPow * varInterest) / (varPow - 1);
			monthly.value = twodec(tempMonthly);
		}
	}
}

function twodec(value) {
	tempValue = parseInt(value*100)/100;
	return tempValue;
}

function doDeposit(tempDeposit) {
	cons = parseInt(tempDeposit)/100;
	depositAmount1 = parseInt(document.calculatorForm.price.value) * cons;
	document.calculatorForm.deposit.value = Math.round(depositAmount1);
	calculate();
}
///////////////////////////////////////////////////////////////////////////////
//Global vars
//////////////////////////////////////////////////////////////////////////////

// whitespace characters
var whitespace = " \t\n\r";
//All the ilegal characters in a email adress i think!




var ilegal = "!\"#$%&'()*+,/:;<=>?[\\]^`{|}~  กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟ";
//																																																																		|

var g_strFromDB = "";
// Check whether string s is empty.
function isEmpty(s)
{
  return ((s == null) || (s.length == 0))
}

// Returns true if string s is empty or
// whitespace characters only.
function isWhitespace (s)
{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}
function isEmail (s,canBeEmpty)
{   if (isEmpty(s))
       if (!canBeEmpty) return false;
       else return true;

    // is s whitespace?
    if (isWhitespace(s)) return false;

    // there must be >= 1 character before @, so we
    // start looking at character position 1
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
   while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    //look for a dubble @
	 if (s.indexOf("@") != -1)
	 {
		if (s.indexOf("@",s.indexOf("@")+1) != -1)
		{
			return false;
		}
	 }
	 // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function test_path()
{
alert("it works!");
}

// checks for ilegal chars
function isLegal (s)
{   var i;

	//Well if the string is not a valid email adress then  add the @ sign
	if (isEmail(s)){ilegal1 = ilegal}else{ilegal1 = ilegal + "@"}
    // Search through string's characters one by one
    // until we find a ilegal character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (ilegal1.indexOf(c) != -1) return false;
    }

    // All characters are whitespace.
	 return true;
}


//Strips a numeric value of all illegal chars. Gunther Kruger.
function cleanNumericField(iVal) {
	var re = /\s|\W|\D/g;
	if ( iVal != '' ) {
		var tmpStr = iVal;
		tmpStr = tmpStr.replace(re, '');
		if ( tmpStr != '' ) {
			return parseInt(tmpStr);
		} else {
			return parseInt(0);
		}
	} else {
		return parseInt(0);
	}
}

function frameCrawlerBasic(){
	if (parent.location.href == self.location.href){
	  window.location.href = '../index.cfm' + self.location.search
	}
}

///////////////////////////////////////////////////////////////////////////

function DisplayDiv(sitemname, dropDown, e)
{
  var oitem = document.getElementsByName(sitemname)[0];
  //if(oitem.getAttribute("dropItLikeItsHot")) {
    if(oitem.style.display=='none')
    {
      oitem.style.display = 'block';
    }
    else if(oitem.style.display=='block')
    {
      oitem.style.display = 'none';
    }
    else
    {
      oitem.style.display = 'none';
    }
  //}
  
  if (dropDown == 1) {
  
    theBody = document.getElementById('body');
    theBody.setAttribute('dropDown',1);
    StopProp(e);
  }
}

function SetDropdown(oitem, eleName, formName, submitIt, displaySpan, theDropDown)
{
  
  
  
  var otargetfield = document.getElementsByName(eleName)[0];
  //alert(document.getElementsByName(eleName).length);
  var oform = document.getElementsByName(formName)[0];
  var oDisplayField = document.getElementById(displaySpan);
  otargetfield.value = oitem.getAttribute("value");
  
  
  if(submitIt){
    changeSrchResults(1, oitem.getAttribute("value"),10,'');
  } else{
    oDisplayField.innerHTML = oitem.innerHTML;
    DisplayDiv(theDropDown);
  }
  checkDrops();
}


function NavigateToModel(iwebspecid)
{
	//alert("/cfm/productGallery.cfm?series=&ifkDealerID=&model=" + iwebspecid);
    location.href = "/cfm/productGallery.cfm?series=&ifkDealerID=&model=" + iwebspecid;
}




function SiteNav(surl)
{
    location.href = surl;
}

function StopProp(e)
{
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();

}



function CheckToHide(oitem, shidename)
{
    if(oitem.getAttribute("IsOpen")==1)
    {
        DisplayDiv(shidename)
        oitem.setAttribute("IsOpen",0);
    }
}



function MakeTimer(sitemname, shidename)
{
    var oitem = document.getElementsByName(sitemname)[0];
    
    if(oitem.getAttribute("TimerName"))
    {
        var stemp = oitem.getAttribute("TimerName");
        eval("clearInterval(" + stemp + ")");
    }
    
    oitem.setAttribute("TimerName", oitem.id + "_Timer");
    
    scmd = "" +  oitem.id + "_Timer" + " = setInterval(\"TimerEvent('" + oitem.id + "', '" + shidename + "')\", 4000)";
    eval(scmd);            
}
        
function TimerEvent(sitemname, shidename)
{
   /*
    var oitem = document.getElementsByName(sitemname)[0];   
    
    if(oitem.getAttribute("IsOver")==0)
    {
        DisplayDiv(shidename)
       
        var stemp = oitem.getAttribute("TimerName");
        ClearTimer(stemp);
    }
    */
}

function ClearTimer(stimername)
{
    eval("clearInterval(" + stimername + ")");
}








//vvvvvvvvv********************* Scroller ***************vvvvvvvvvv//
var iChildCount=0;


var oImgChecked = new Image();
  var oImgUnChecked = new Image();
                  
  var bEnableScroll=false;
  var oitem=null;
  var otimer=null;
  var ispeed=2;
  function ScrollRight()
  {
      if(oitem.scrollLeft>=0 && (oitem.scrollLeft+ispeed)>0 && bEnableScroll==true)
      {
          oitem.scrollLeft += ispeed;
      }
      
      if(oitem.scrollLeft>=oitem.scrollWidth-725)
      {
        setScrollDir('left');
      }
     
      if(otimer)
      {
          clearInterval(otimer);
      }
      otimer = setInterval(ScrollRight, 1);
  }

  
  function ScrollLeft()
  {
    try {
      
      if(oitem.scrollLeft>0 && (oitem.scrollLeft-ispeed)>0 && bEnableScroll==true)
      {
          oitem.scrollLeft -= ispeed;
      }
      else if(oitem.scrollLeft<=2)
      {
        setScrollDir("right");
      }
     
      if(otimer)
      {
          clearInterval(otimer);
      }
      otimer = setInterval(ScrollLeft, 1);
      
    } catch(ex){}
  }
  
  function StartScroll(sListName, iNewSpeed)
  {
       oitem = document.getElementsByName(sListName)[0];
       bEnableScroll = true;
       ispeed = iNewSpeed;
  } 
  
  function setScrollDir(sdir)
  {
    oitem.setAttribute('autoscroll_dir', sdir)
  }
  
  function StopScroll()
  {
  
     if(oscrolltimer)
     {
        clearInterval(oscrolltimer);
     }
     clearInterval(otimer);
     bEnableScroll = false; 
  }
  
  function ScrollState()
  {
    try {
      return oitem.getAttribute('autoscroll_dir');
    } catch(evp){}
  }
  
  var oscrolltimer=null;
  function AutoScroll(sListName)
  {
    
      StartScroll(sListName,1);
      
      if(ScrollState()=='right')
      {
        ScrollRight();
      }
      else
      {
        ScrollLeft();
      }
      
      StopScroll();
        
      
      oscrolltimer = setInterval("AutoScroll('" + sListName + "')", 30);
  }
  
  //^^^^^^^********************* Scroller ***************^^^^^^^^^//
