//Global Javascript page
GLOBAL_CLICKED = false;
//Coenie se functions
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 ShowErrorFixError(aObject,aMessage,aDefault){ // used 9 times
	if (!aDefault) { aDefault=0; }
	 alert(aMessage);
	 aObject.value = aDefault;
	 aObject.focus();
}
///////////////////////////////////////////////////////////////////////////////
//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){   // used 14 times
	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;
}
// 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 isNum(obj) {
	
	if(isNaN(parseFloat(obj.value)) == true) {
		alert('Please enter valid number');
		obj.value='';
		obj.focus();
	}
}







function checkLen(obj, maxLen) {
	if(obj.value.length >= maxLen) {
		return false;
	}
	return true;
}
function SetMainContent(aContent){
  s = "<table width=100% height=100%><tr><td align=center valign=middle style='font-family:verdana;color:#c0c0c0'>"+aContent+"</td></tr></table>"
  parent.frames.Main.document.clear();
  parent.frames.Main.document.write(s)
  parent.frames.Main.document.close();
}
function frmValidation(frmObj) {
  with (frmObj) {
    var functionArr = new Array(4);
    var frmObjItem;
    functionArr[0] = 'isEmpty(frmObjItem.value)';  //1
    functionArr[1] = '!isEmail(frmObjItem.value)'; //2
    functionArr[2] = '!isLegal(frmObjItem.value)'; //3
    functionArr[3] = '!isSAID(frmObjItem.value)';  //4
	functionArr[4] = '!isNum(frmObjItem.value)'; //5
    for (i=0;i<frmObj.length;i++) {
      if (frmObj[i].attributes.param != undefined) {
        tmpArr = frmObj[i].attributes.param.value.split(',');
        if (tmpArr[0] == 1) {
          frmObjItem = frmObj[i];
          if (isNaN(tmpArr[1])) {
            if (eval(tmpArr[1].substr(1,tmpArr[1].length-2))) {
              alert(tmpArr[2].substr(1,tmpArr[2].length-2));
              frmObjItem.focus();
              return false;
            }// if
          } else {
            if (eval(functionArr[tmpArr[1]])) {
              alert(tmpArr[2].substr(1,tmpArr[2].length-2));
              frmObjItem.focus();
              return false;
            }// if
          } // isNaN
        }// if
      }// if
    }// for
  }// with
  return true;
}
function openWin(url,w,h) {
	window.open(url,'pop','width='+w+',height='+h+',scrollbars=no,toolbars=no');
}
function popDiv(visDiv,hidDiv,hidDiv2) {
	document.all[visDiv].style.visibility = "visible";
	document.all[hidDiv].style.visibility = "hidden";
	document.all[hidDiv2].style.visibility = "hidden";
}
function viewVehicle(newContent,displayHere) {
	newDiv = eval('document.all.'+newContent);
	disDiv = eval('document.all.'+displayHere);
	disDiv.innerHTML = newDiv.innerHTML;
}
//Returns a value of a drop down
function valueOfDropDown(aDropDown){return aDropDown.options[aDropDown.selectedIndex].value;}
//Returns a text of a drop down
function textOfDropDown(aDropDown){return aDropDown.options[aDropDown.selectedIndex].text;}
//Writen by gilbert
function PopulateHiddenValue(aform,afield,aDropDown){
	theField = eval("document."+aform+"."+afield);
	theField.value = aDropDown.options[aDropDown.selectedIndex].text;
	//alert(theField.value);
}
//aidan stuff...i just put it here because its where it should be
var numeric = "0123456789";
function y2k(number) { return (number < 1000) ? number + 1900 : number; }
function isInteger(val){
    for(var i=0;i<val.length;i++){
        if(!isDigit(val.charAt(i))){return false;}
        }
    return true;
    }
function isDigit(num) {
    if (num.length>1){return false;}
    if (numeric.indexOf(num)!=-1){return true;}
    return false;
    }
function isNotNumeric(num){
  if(num.length==0){
    return true;
  }
  for(i=0;i<num.length;i++){
    if(numeric.indexOf(num.charAt(i))>-1){
      return false;
    }
  }
  return true;
}
function isNumeric(num){
  if(num.length==0){
    return true;
  }
  for(i=0;i<num.length;i++){
    if(numeric.indexOf(num.charAt(i))<0){
      return false;
    }
  }
  return true;
}
function isEmail(string) {
    if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
        return true;
    else
        return false;
}
function isDate (day,month,year) {
// checks if date passed is valid
// will accept dates in following format:
// isDate(dd,mm,ccyy), or
// isDate(dd,mm) - which defaults to the current year, or
// isDate(dd) - which defaults to the current month and year.
// Note, if passed the month must be between 1 and 12, and the
// year in ccyy format.
    var today = new Date();
    year = ((!year) ? y2k(today.getYear()):year);
    month = ((!month) ? today.getMonth():month-1);
    if (!day) return false
    var test = new Date(year,month,day);
    if ( (y2k(test.getYear()) == year) &&
         (month == test.getMonth()) &&
         (day == test.getDate()) )
        return true;
    else
        return false
}
// global pop up function
function openPopUp(URL,width,height) {
    ID = "NewWindow";
    width = "width="+width;
    height = "height="+height;
    calcWin = window.open(URL, ID, ''+width+', '+height+', scrollbars=yes');
    calcWin.focus();
}

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();
}

    // compair vehicles functions.
    function jumpMakes(MakeID,ipkCategoryID){
        //alert("jumpMakes: "+MakeID);
        newURL = "default.asp?load=VehicleComparisons&ipkCategoryID="+ipkCategoryID+"&ipkVehicleMakeID="+MakeID;
        //alert(newURL);
        window.location=newURL;
    }
    function jumpToCompair(SeriesID,ipkCategoryID){
        //alert(MakeID);
        newURL = "default.asp?load=VehicleComparisons&ipkCategoryID="+ipkCategoryID+"&ipkVehicleSeriesID="+SeriesID;
        //alert(newURL);
        window.location=newURL;
    }
    function checkAmount(obj) {
	    count = 0;
        //alert(count);
    	with (document.compareForm) {
    		if (!document.compareForm.compareBox) {
    			count = 0;
    		} else {
    			for (i=0;i<document.compareForm.compareBox.length;i++) {
    				if (document.compareForm.compareBox[i].checked == true) {
    					count++;
    				}
    			}
    		}
    	}
    	if (count > 2) {
    		alert('Sorry!\nYou may only compare 2 vehicles at a time!');
    		obj.checked = false;
    	} else if (count == 2) {
    		if (confirm("View comparison?")) {
    			comparer();
    		}
    	}
    }
    function comparer() {
    	counter = 0;
    	tempString = "";
    	if (!document.compareForm.compareBox) {
    		alert("Nothing to compare!");
    	} else {
    		with (document.compareForm) {
    			for (i=0;i<compareBox.length;i++) {
    				if (compareBox[i].checked == true) {
    					counter++;
    					if (tempString == "") {
    						tempString = compareBox[i].value;
    					} else {
    						tempString = tempString + "," + compareBox[i].value;
    					}
    				}
    			}
    		}
    		if (counter != 2) {
    			alert("You must select 2 vehicles to compare!");
    		} else {
                ipkCategoryID = 0;
                newURL = "default.asp?load=VehicleComparisons&ipkCategoryID="+ipkCategoryID+"&carString=" + tempString;
                alert(newURL);
                window.location=newURL;
    		}
    	}
    }
function goTo() {
	with ( document.linkForm ) {
		window.open(externalLinks.options[externalLinks.selectedIndex].value);
	}
}

function changepic(imgName, photo) {
	directPath = "http://images.eliance.co.za/MT_Images/General/";
	parent.document.a.src = directPath + photo;
}