// JavaScript 1.2 functions for use in HTML forms
// (C)2000-2002 Donald McIntosh
//
//	
// function valNumber(myNumber, min, max, msg)
//		Number string formed of characters 0-9, length between min and max
//
// function valFloat(myFloat, min, max, places)
//		Floating point number string formed of characters 0-9, pre-decimal
//		length between min and max, post-decimal length of places
//
// function sayRefresh()
//		Puts message in status bar telling user to click on Refresh Display
//		(submit) button when allfields input.
//
// function valString(string, min, max, msg)
//      Checks that a string of alphanumerics with length between min and max
//      is input
//
// function valDate(myDate)
//      Checks date in format dd/mm/yyyy
//
// function valMnthDay(month, day)
//		Check day number selected matches month
//
/*
var wide=1024;
var high=768;
if( window.outerHeight != high || window.outerWidth != wide ){
	if(screen.availHeight < high || screen.availWidth < wide ){
		window.resizeTo(screen.availWidth, screen.availHeight);
	}else{
		window.resizeTo(wide, high);
	}
}
*/
var chkfeatures;
var bigpic;	/* window for showing full size pictures */
var stocklist;	/* child window for stocklist/invoices */
/*****************************************************
* ypSlideOutMenu
* 3/04/2001
*
* a nice little script to create exclusive, slide-out
* menus for ns4, ns6, mozilla, opera, ie4, ie5 on 
* mac and win32. I've got no linux or unix to test on but 
* it should(?) work... 
*
* Revised:
* - 08/29/2002 : added .hideAll()
* - 04/15/2004 : added .writeCSS() to support more 
*                than 30 menus.
*
* --youngpup--
*****************************************************/
ypSlideOutMenu.Registry = []
ypSlideOutMenu.aniLen = 250
ypSlideOutMenu.hideDelay = 1000
ypSlideOutMenu.minCPUResolution = 10
// constructor
function ypSlideOutMenu(id, dir, left, top, width, height)
{
this.ie = document.all ? 1 : 0
this.ns4 = document.layers ? 1 : 0
this.dom = document.getElementById ? 1 : 0
if (this.ie || this.ns4 || this.dom) {
this.id = id
this.dir = dir
this.orientation = dir == "left" || dir == "right" ? "h" : "v"
this.dirType = dir == "right" || dir == "down" ? "-" : "+"
this.dim = this.orientation == "h" ? width : height
this.hideTimer = false
this.aniTimer = false
this.open = false
this.over = false
this.startTime = 0
this.gRef = "ypSlideOutMenu_"+id
eval(this.gRef+"=this")
ypSlideOutMenu.Registry[id] = this
var d = document
var strCSS = "";
strCSS += '#' + this.id + 'Container { visibility:hidden; '
strCSS += 'left:' + left + 'px; '
strCSS += 'top:' + top + 'px; '
strCSS += 'overflow:hidden; z-index:10000; }'
strCSS += '#' + this.id + 'Container, #' + this.id + 'Content { position:absolute; '
strCSS += 'width:' + width + 'px; '
strCSS += 'height:' + height + 'px; '
strCSS += 'clip:rect(0 ' + width + ' ' + height + ' 0); '
strCSS += '}'
this.css = strCSS;
this.load()
}
}
ypSlideOutMenu.writeCSS = function() {
document.writeln('<style type="text/css">');
for (var id in ypSlideOutMenu.Registry) {
document.writeln(ypSlideOutMenu.Registry[id].css);
}
document.writeln('</style>');
}
ypSlideOutMenu.prototype.load = function() {
var d = document
var lyrId1 = this.id + "Container"
var lyrId2 = this.id + "Content"
var obj1 = this.dom ? d.getElementById(lyrId1) : this.ie ? d.all[lyrId1] : d.layers[lyrId1]
if (obj1) var obj2 = this.ns4 ? obj1.layers[lyrId2] : this.ie ? d.all[lyrId2] : d.getElementById(lyrId2)
var temp
if (!obj1 || !obj2) window.setTimeout(this.gRef + ".load()", 100)
else {
this.container = obj1
this.menu = obj2
this.style = this.ns4 ? this.menu : this.menu.style
this.homePos = eval("0" + this.dirType + this.dim)
this.outPos = 0
this.accelConst = (this.outPos - this.homePos) / ypSlideOutMenu.aniLen / ypSlideOutMenu.aniLen 
// set event handlers.
if (this.ns4) this.menu.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);
this.menu.onmouseover = new Function("ypSlideOutMenu.showMenu('" + this.id + "')")
this.menu.onmouseout = new Function("ypSlideOutMenu.hideMenu('" + this.id + "')")
//set initial state
this.endSlide()
}
}
ypSlideOutMenu.showMenu = function(id)
{
var reg = ypSlideOutMenu.Registry
var obj = ypSlideOutMenu.Registry[id]
if (obj.container) {
obj.over = true
for (menu in reg) if (id != menu) ypSlideOutMenu.hide(menu)
if (obj.hideTimer) { reg[id].hideTimer = window.clearTimeout(reg[id].hideTimer) }
if (!obj.open && !obj.aniTimer) reg[id].startSlide(true)
}
}
ypSlideOutMenu.hideMenu = function(id)
{
var obj = ypSlideOutMenu.Registry[id]
if (obj.container) {
if (obj.hideTimer) window.clearTimeout(obj.hideTimer)
obj.hideTimer = window.setTimeout("ypSlideOutMenu.hide('" + id + "')", ypSlideOutMenu.hideDelay);
}
}
ypSlideOutMenu.hideAll = function()
{
var reg = ypSlideOutMenu.Registry
for (menu in reg) {
ypSlideOutMenu.hide(menu);
if (menu.hideTimer) window.clearTimeout(menu.hideTimer);
}
}
ypSlideOutMenu.hide = function(id)
{
var obj = ypSlideOutMenu.Registry[id]
obj.over = false
if (obj.hideTimer) window.clearTimeout(obj.hideTimer)
obj.hideTimer = 0
if (obj.open && !obj.aniTimer) obj.startSlide(false)
}
ypSlideOutMenu.prototype.startSlide = function(open) {
this[open ? "onactivate" : "ondeactivate"]()
this.open = open
if (open) this.setVisibility(true)
this.startTime = (new Date()).getTime() 
this.aniTimer = window.setInterval(this.gRef + ".slide()", ypSlideOutMenu.minCPUResolution)
}
ypSlideOutMenu.prototype.slide = function() {
var elapsed = (new Date()).getTime() - this.startTime
if (elapsed > ypSlideOutMenu.aniLen) this.endSlide()
else {
var d = Math.round(Math.pow(ypSlideOutMenu.aniLen-elapsed, 2) * this.accelConst)
if (this.open && this.dirType == "-") d = -d
else if (this.open && this.dirType == "+") d = -d
else if (!this.open && this.dirType == "-") d = -this.dim + d
else d = this.dim + d
this.moveTo(d)
}
}
ypSlideOutMenu.prototype.endSlide = function() {
this.aniTimer = window.clearTimeout(this.aniTimer)
this.moveTo(this.open ? this.outPos : this.homePos)
if (!this.open) this.setVisibility(false)
if ((this.open && !this.over) || (!this.open && this.over)) {
this.startSlide(this.over)
}
}
ypSlideOutMenu.prototype.setVisibility = function(bShow) { 
var s = this.ns4 ? this.container : this.container.style
s.visibility = bShow ? "visible" : "hidden"
}
ypSlideOutMenu.prototype.moveTo = function(p) { 
this.style[this.orientation == "h" ? "left" : "top"] = this.ns4 ? p : p + "px"
}
ypSlideOutMenu.prototype.getPos = function(c) {
return parseInt(this.style[c])
}
ypSlideOutMenu.prototype.onactivate = function() { }
ypSlideOutMenu.prototype.ondeactivate = function() { }
// initialise navbar stuff
var myMenu1 = new ypSlideOutMenu('home', 'down', 0, 0, 250, 180);
var myMenu2 = new ypSlideOutMenu('stocklist', 'down', 0, 0, 250, 180);
var myMenu3 = new ypSlideOutMenu('sales', 'down', 0, 0, 250, 180);
var myMenu4 = new ypSlideOutMenu('servicing', 'down', 0, 0, 250, 180);
var myMenu5 = new ypSlideOutMenu('services', 'down', 0, 0, 250, 180);
var myMenu6 = new ypSlideOutMenu('location', 'down', 0, 0, 250, 180);
var myMenu10 = new ypSlideOutMenu('admin', 'down', 0, 0, 250, 180);
ypSlideOutMenu.writeCSS();

function round(number,X) {
// rounds number to X decimal places, defaults to 2
	if(X == 0) return Math.round(number);
	X = (!X ? 2 : X);
	var result = Math.round(number*Math.pow(10,X))/Math.pow(10,X);
	return (result == Math.floor(result)) ? result + '.00' : (  (result*10 == Math.floor(result*10)) ? result + '0' : result);
}

function valNumber(myNumber, min, max, msg) {
	var validPattern = "^[0-9]{" + min + "," + max + "}$";
	var re = new RegExp(validPattern);

	if(myNumber.value == ""){
		return true;
	}
	if(! re.test(myNumber.value)){
		alert(msg);
		return false;
	}
    return true;
} 

function valFloat(myFloat, min, max, places, msg) {
	var validPattern
		= "^[-]{0,1}[0-9]{" + min + "," + max + "}[.]{0,1}[0-9]{0," + places + "}$";
	var re = new RegExp(validPattern);

	if(! re.test(myFloat.value)){
		alert(msg + " '" + myFloat.value +"'");
		myFloat.value="";
		myFloat.focus();
		myFloat.select();
		return false;
	}
	myFloat.value=round(myFloat.value, places);
    return true;
} 

function sayRefresh(){
	window.status="Click on Action Button after making all selections";
	return true;
}

function valString(mystring, min, max, msg) {
	var rawstring=mystring.value;
    if (rawstring.length > max) {
        return false;
    }
    if (rawstring.length < min) {
        alert(msg);
        return false;
    }
	var string=rawstring.replace(/\s/g, " ");
	// var string=rawstring;

    var valid="|\":@\/?;~!-+#*£<> ,'&()[].%0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    for (var i=0; i<string.length; i++) {
		// alert(string.charAt(i));
        if (valid.indexOf(string.charAt(i)) < 0) {
            alert(msg + " ( " + string.charAt(i) + " character not allowed)" );
            return false;
        }
    }

    return true;
} 

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

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
}

function valDate(myDate) {
// checks date in format dd/mm/yyyy
	var string = myDate.value.replace(/ */g,'');
	myDate.value = string;
	if(string.length == 6){
		var day=string.substr(0, 2);
		var month=string.substr(2, 2);
		var year=string.substr(4, 2);

		if(year<50){
			year = year*1 + 2000*1;
		}else{
			year = year*1 + 1900*1;
		}
		string=day + "/" + month + "/" + year;
		myDate.value=string;
		// alert("Date is " + string);
	}

	if(string.length == 0){
		return true;
	}
	re = /^[0-9d][0-9d]\/[0-9m][0-9m]\/[0-9y][0-9y][0-9y][0-9y]$/;
	if(! re.test(string)){
		alert("Invalid Date (enter as dd/mm/yyyy)");
		myDate.focus();
		myDate.select();
		return false;
	}
	re = /^[d][d]\/[m][m]\/[y][y][y][y]$/;
	if(re.test(string)){
		return true;
	}
	re = /^[0-9][0-9]\/[0-9][0-9]\/[0-9][0-9][0-9][0-9]$/;
	if(! re.test(string)){
		alert("Invalid Date (enter as dd/mm/yyyy)");
		myDate.focus();
		myDate.select();
		return false;
	}
	var day=string.substr(0,2);
	var month=string.substr(3,2);
	var year=string.substr(6,4);
	if(!isDate(day, month, year)){
		alert("Invalid Date (enter as dd/mm/yyyy)");
		myDate.focus();
		myDate.select();
		return false;
	}
	return true;
}

// focus on first empy cell
function focus_first_empty(f){
	for( var i = 0; i < f.length; i++){
		var e = f.elements[i];
		// alert("element " + i + " is " + e.name);
		if( (e.type == "text") && ((e.value == null) || (e.value == "")) ){
			e.focus();
			return true;
		}
	}
	return false;
}

function valMnthDay(month, day) {
	if((month.value == 9) && (day.value > 30)){day.value=30; return true}
	if((month.value == 4) && (day.value > 30)){day.value=30; return true}
	if((month.value == 6) && (day.value > 30)){day.value=30; return true}
	if((month.value == 11) && (day.value > 30)){day.value=30; return true}
	if((month.value == 2) && (day.value > 28)){day.value=28; return true}
	return true;
}

function get_models(make){
	// alert('get_models ' + make);
	// delete all existing variants
/*
	while(document.vehicles.v_variant.options.length){
		document.vehicles.v_variant.options.remove(0);
	}
	// add "select one"
	var newElem=document.createElement("OPTION");
	newElem.text='Choose Model First';
	newElem.value=0;
	document.vehicles.v_variant.options.add(newElem);
*/

	// delete all existing models
	while(document.vehicles.v_model.options.length){
		document.vehicles.v_model.options.remove(0);
	}
	var newElem=document.createElement("OPTION");
	newElem.text='Choose Model';
	newElem.value=0;
	document.vehicles.v_model.options.add(newElem);

	var models = new Array();
	var ctr=0;
	for(loop=0; loop<abi_code.length; loop++){
		// alert('Loop: ' + loop + '; Code: ' + abi_code[loop] + ' Make: ' + make + '; abi_make: ' + abi_make[abi_code[loop]]);
		if(make == abi_make[abi_code[loop]]){
			models[ctr]=abi_model[abi_code[loop]];
			ctr++;
		}
	}
	models.sort();	// sort into (alpha) order
	var old='';
	for(loop=0; loop<models.length; loop++){
		if(old != models[loop]){
			var newElem=document.createElement("OPTION");
			newElem.text=models[loop];
			newElem.value=models[loop];
			document.vehicles.v_model.options.add(newElem);
		}
		old=models[loop];
	}
	return true;
}

function get_variants(make, model){
	// alert('get_variants');
	// delete all existing
	while(document.vehicles.v_variant.options.length){
		document.vehicles.v_variant.options.remove(0);
	}
	var newElem=document.createElement("OPTION");
	newElem.text='Choose Variant';
	newElem.value=0;
	document.vehicles.v_variant.options.add(newElem);

	var variants = new Array();
	var codes = new Array();
	var ctr=0;
	for(loop=0; loop<abi_code.length; loop++){
		if((make == abi_make[abi_code[loop]]) && (model == abi_model[abi_code[loop]])){
			variants[ctr]=abi_variant[abi_code[loop]];
			codes[ctr]=abi_code[loop];
			ctr++;
		}
	}
	// variants.sort();	// sort into (alpha) order
	var old='';
	for(loop=0; loop<variants.length; loop++){
		if(old != variants[loop]){
			var newElem=document.createElement("OPTION");
			newElem.text=variants[loop];
			newElem.value=codes[loop];
			document.vehicles.v_variant.options.add(newElem);
			// alert('Code: ' + codes[loop] + ' Label: ' + variants[loop]);
		}
		old=variants[loop];
	}
	return true;
}

function split_variant(variant){
	var string=variant;
	if(string == 0){	// user re-selects prompt option
		return true;
	}
	// alert('Code is ' + string + ' = ' + abi_variant[string]);
	// first split between variant name & specification data
	var str=abi_variant[string].split('{');
	// want second part i.e. what came AFTER {, hence subscript [1]
	var fields=str[1].split(',');

	// split into fields
	var cc=fields[0].split(' ');
	document.forms[0].v_engine.value=cc[0];

	if(fields[3].search(/PETROL/i)>=0){
		// unleaded PETROL
		document.forms[0].v_fuel.value='U';
	}else{
		document.forms[0].v_fuel.value='D';
	}

	var doors=fields[5].split(' ');
	document.forms[0].v_doors.value=doors[1];

	if(fields[4].search(/ESTATE/i)>=0){
		document.forms[0].v_form.value='E';
	}else{
		if(document.forms[0].v_doors.value==4){
			document.forms[0].v_form.value='S';
		}else{
			document.forms[0].v_form.value='H';
		}
	}

	var grp=fields[6].split(' ');
	document.forms[0].v_ins_group.value=grp[2];

	// default number of seats to 5
	document.forms[0].v_seats.value='5';
	document.forms[0].v_seats.select();
	document.forms[0].v_seats.focus();

	return true;
}

function get_vehicle_opts(make, model, variant){
	get_models(make);
	get_variants(make, model);
	document.forms[0].v_model.value=model;
	document.forms[0].v_variant.value=variant;
	return true;
}

function fasttrack_vehicle( f, registration, reg_year, variant, body, seats, colour, finish, miles, owners, drive, tradesave, sell, fuel, doors, engine, ins_grp ){
	var space=0;
	for( var i = 0; i < f.length; i++){
		var e = f.elements[i];
		if( (e.type == "text") && (e.name.substr(0,3) == "reg") && ((e.value == null) || (e.value == "")) ){
			e.value=registration.value;
			registration.value="";
			e=f.elements[i+1];
			e.value=reg_year.value;
			reg_year.value="";
			e=f.elements[i+2];
			e.value=variant.value;
			e=f.elements[i+3];
			e.value=body.value;
			body.value="";
			e=f.elements[i+4];
			e.value=seats.value;
			seats.value="";
			e=f.elements[i+5];
			e.value=colour.value;
			colour.value='U';
			e=f.elements[i+6];
			e.value=finish.value;
			finish.value='P';
			e=f.elements[i+7];
			e.value=miles.value;
			miles.value="";
			e=f.elements[i+8];
			e.value=owners.value;
			owners.value="";
			e=f.elements[i+9];
			e.value=drive.value;
			drive.value="";
			e=f.elements[i+10];
			if( tradesave.checked ){
				e.value='Y';
			}else{
				e.value='N';
			}
			tradesave.checked=false;
			e=f.elements[i+11];
			e.value=sell.value;
			sell.value="";
			e=f.elements[i+12];
			e.value=fuel.value;
			fuel.value="";
			e=f.elements[i+13];
			e.value=doors.value;
			doors.value="";
			e=f.elements[i+14];
			e.value=engine.value;
			engine.value="";
			e=f.elements[i+15];
			e.value=ins_grp.value;
			ins_grp.value="";
			space=1;
			break;
		}
	}
	if(space == 0){
		alert('No space for more vehicles - save these first!');
	}
	return false;
}	

function form_total(frm, varname, totalfield){
	var total=0.0;
	// Run through all the form fields
	for (var i=0; i < frm.elements.length; ++i) {

		// Get the current field
		form_field = frm.elements[i]

		// Get the field's name
		form_name = form_field.name

		// Is it a "varname" field?
		if (form_name.substring(0,varname.length) == varname) {
			total += form_field.value*1;
		}
	}
	totalfield.value=round(total, 2);
}

function balance(frm){
	var total=0.0;

	total+=frm.inv_sellprice.value*1.0;
	total+=frm.inv_extras.value*1.0;
	total+=frm.inv_warranty.value*1.0;
	total+=frm.inv_rfl.value*1.0;
	total-=frm.inv_allow.value*1.0;
	total-=frm.inv_deposit.value*1.0;
	total+=frm.inv_pxowed.value*1.0;

	frm.inv_netdue.value=round(total, 2);
}
