// 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 showByPosition(object,x,y,e)
//		Show tooltips layer
//
// function hide(object)
//		Hide tooltips layer
//
// 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 clicked=0;
var chkfeatures;
var adcount=0;	// cars selected in newadvert.pl

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;
	}
    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 == 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 showByPosition(object,x,y,e) {
	if(object != null){
	// alert('object is ' + object + ' x is ' + x + ' y is ' + y);
    if (document.layers && document.layers[object]) {
        // if ((e.x + x + 50 + document.layers[object].clip.width) > (window.pageXOffset + window.innerWidth))
            // x = x - document.layers[object].clip.width;

        // if ((e.y + y + 50 + document.layers[object].clip.height) > (window.pageYOffset + window.innerHeight))
            // y *= -4;

        // document.layers[object].left = e.x + x;
        // document.layers[object].top = e.y + y;
		if(x<50){x=50;}
        document.layers[object].left = x;
        document.layers[object].top = y;
        document.layers[object].visibility = 'visible';
    }
	else if (document.all) {
		// alert('Here I am');
        e = window.event;

        // if ((e.x + x + document.all[object].clientWidth) > (document.body.clientWidth + document.body.scrollLeft))
            // x = (document.body.clientWidth + document.body.scrollLeft) - document.all[object].clientWidth;
        // else
            // x = e.x + x;

        // if ((e.y + y + document.all[object].clientHeight) > (document.body.clientHeight + document.body.scrollTop))
            // y = e.y - (y * 4);
        // else
            // y = e.y + y;

		if(x<50){x=50;}
        document.all[object].style.posLeft = x;
        document.all[object].style.posTop = y;
        document.all[object].style.visibility = 'visible';
    }
}
}


function hide(object) {
    if (document.layers && document.layers[object])
        document.layers[object].visibility = 'hidden';
    else if (document.all)
        document.all[object].style.visibility = 'hidden';
}

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;
}


// global menu state
var menuReady = false;

// pre-cache menubar image pairs
if (document.images) {
    var imagesNormal = new Array();
    imagesNormal["home"] = new Image(20, 80);
    imagesNormal["home"].src = "/graphics/m_home_off.png";
    imagesNormal["stocklist"] = new Image(20, 80);
    imagesNormal["stocklist"].src  = "/graphics/m_stocklist_off.png";
    imagesNormal["sales"] = new Image(20, 80);
    imagesNormal["sales"].src  = "/graphics/m_sales_off.png";
    imagesNormal["servicing"] = new Image(20, 80);
    imagesNormal["servicing"].src  = "/graphics/m_servicing_off.png";
    imagesNormal["services"] = new Image(20, 80);
    imagesNormal["services"].src  = "/graphics/m_services_off.png";
    imagesNormal["location"] = new Image(20, 80);
    imagesNormal["location"].src  = "/graphics/m_location_off.png";
    imagesNormal["about"] = new Image(20, 80);
    imagesNormal["about"].src  = "/graphics/m_about_off.png";
    imagesNormal["admin"] = new Image(20, 80);
    imagesNormal["admin"].src  = "/graphics/m_admin_off.png";

    var imagesHilite = new Array();
    imagesHilite["home"] = new Image(20, 80);
    imagesHilite["home"].src = "/graphics/m_home_on.png";
    imagesHilite["stocklist"] = new Image(20, 80);
    imagesHilite["stocklist"].src  = "/graphics/m_stocklist_on.png";
    imagesHilite["sales"] = new Image(20, 80);
    imagesHilite["sales"].src  = "/graphics/m_sales_on.png";
    imagesHilite["servicing"] = new Image(20, 80);
    imagesHilite["servicing"].src  = "/graphics/m_servicing_on.png";
    imagesHilite["services"] = new Image(20, 80);
    imagesHilite["services"].src  = "/graphics/m_services_on.png";
    imagesHilite["location"] = new Image(20, 80);
    imagesHilite["location"].src  = "/graphics/m_location_on.png";
    imagesHilite["about"] = new Image(20, 80);
    imagesHilite["about"].src  = "/graphics/m_about_on.png";
    imagesHilite["admin"] = new Image(20, 80);
    imagesHilite["admin"].src  = "/graphics/m_admin_on.png";
}

function getElementStyle(elem, IEStyleProp, CSSStyleProp) {
    if (elem.currentStyle) {
        return elem.currentStyle[IEStyleProp];
    } else if (window.getComputedStyle) {
        var compStyle = window.getComputedStyle(elem, "");
        return compStyle.getPropertyValue(CSSStyleProp);
    }
    return "";
}

// carry over some critical menu style sheet attribute values
var CSSRuleValues = {menuItemHeight:"18px",
                     menuItemLineHeight:"1.4em",
                     menuWrapperBorderWidth:"2px",
                     menuWrapperPadding:"3px",
                     defaultBodyFontSize:"12px"
                    };

// specifications for menu contents and menubar image associations
var menus = new Array();
// NOTE admin only menu is built in initMenus
menus[0] = {mBarImgId:"menuImg_1",
            mBarImgNormal:imagesNormal["home"],
            mBarImgHilite:imagesHilite["home"],
            menuItems:[],
            elemId:""
           };
menus[1] = {mBarImgId:"menuImg_a",
            mBarImgNormal:imagesNormal["stocklist"],
            mBarImgHilite:imagesHilite["stocklist"],
            menuItems:[],
            elemId:""
           };
menus[2] = {mBarImgId:"menuImg_2",
            mBarImgNormal:imagesNormal["sales"],
            mBarImgHilite:imagesHilite["sales"],
            menuItems:[ {text:"Warranty", href:"/cgi-bin/warranty.pl"},
                        {text:"Finance", href:"/cgi-bin/finance.pl"},
                        {text:"Vehicle Replacement Ins.", href:"/cgi-bin/insurance.pl"},
                        {text:"Guaranteed Asset Protection", href:"/cgi-bin/gap.pl"}
                      ],
            elemId:""
           };
menus[3] = {mBarImgId:"menuImg_3", 
            mBarImgNormal:imagesNormal["servicing"],
            mBarImgHilite:imagesHilite["servicing"],
            menuItems:[ {text:"Scheduled", href:"/cgi-bin/maintenance.pl"},
                        {text:"M.O.T.", href:"/cgi-bin/MOT.pl"}
                      ],
            elemId:""
           };
menus[4] = {mBarImgId:"menuImg_4",
            mBarImgNormal:imagesNormal["services"],
            mBarImgHilite:imagesHilite["services"],
            menuItems:[],
            elemId:""
           };
menus[5] = {mBarImgId:"menuImg_5",
            mBarImgNormal:imagesNormal["location"],
            mBarImgHilite:imagesHilite["location"],
            menuItems:[],
            elemId:""
           };
menus[6] = {mBarImgId:"menuImg_6",
            mBarImgNormal:imagesNormal["about"],
            mBarImgHilite:imagesHilite["about"],
            menuItems:[],
            elemId:""
           };
// NOTE admin only menu is built in initMenus

// create hash table-like lookup for menu objects with id string indexes
function makeHashes() {
    for (var i = 0; i < menus.length; i++) {
        menus[menus[i].elemId] = menus[i];
        menus[menus[i].mBarImgId] = menus[i];
    }
}

// assign menu label image event handlers
function assignLabelEvents() {
    var elem;
    for (var i = 0; i < menus.length; i++) {
        elem = document.getElementById(menus[i].mBarImgId);
        elem.onmouseover = swap;
        elem.onmouseout = swap;
    }
}

// invoked from init(), generates the menu div elements and their contents.
// all this action is invisible to user during construction
function makeMenus() {
    var menuDiv, menuItem, itemLink, mbarImg, textNode, offsetLeft, offsetTop;
    
    // determine key adjustment factors for the total height of menu divs
    
    var menuItemH = 0;
	// font-size *must* be specified in style sheet to avoid errors
    var bodyFontSize = parseInt(getElementStyle(document.body, "fontSize", "font-size"));
    // test to see if browser's font size has been adjusted by the user
    // and that the new size registers as an applied style property
    if (bodyFontSize == parseInt(CSSRuleValues.defaultBodyFontSize)) {
        menuItemH = (parseFloat(CSSRuleValues.menuItemHeight));
    } else {
        // works nicely in Netscape 7
        menuItemH = parseInt(parseFloat(CSSRuleValues.menuItemLineHeight) * bodyFontSize);
    }
    var heightAdjust = parseInt(CSSRuleValues.menuWrapperPadding) + 
        parseInt(CSSRuleValues.menuWrapperBorderWidth);
    if (navigator.appName == "Microsoft Internet Explorer" && 
        navigator.userAgent.indexOf("Win") != -1 && 
        (typeof document.compatMode == "undefined" || 
        document.compatMode == "BackCompat")) {
        heightAdjust = -heightAdjust;
    }
    
    // use menus array to drive div creation loop
    for (var i = 0; i < menus.length; i++) {
        menuDiv = document.createElement("div");
        menuDiv.id = "popupmenu" + i;
        // preserve menu's ID as property of the menus array item
        menus[i].elemId = "popupmenu" + i;
        menuDiv.className = "menuWrapper";
        if (menus[i].menuItems.length > 0) {
            menuDiv.style.height = (menuItemH * menus[i].menuItems.length) - heightAdjust + "px";
        } else {
            // don't display any menu div lacking menu items
            menuDiv.style.display = "none";
        }
        // define event handlers
        menuDiv.onmouseover = keepMenu;
        menuDiv.onmouseout = requestHide;

        // set stacking order in case other layers are around the page
        menuDiv.style.zIndex = 1000;
        
        // assemble menu item elements for inside menu div
        for (var j = 0; j < menus[i].menuItems.length; j++) {
            menuItem = document.createElement("div");
            menuItem.id = "popupmenuItem_" + i + "_" + j;
            menuItem.className = "menuItem";
            menuItem.onmouseover = toggleHighlight;
            menuItem.onmouseout = toggleHighlight;
            menuItem.onclick = hideMenus;
            menuItem.style.top = menuItemH * j + "px";
            itemLink = document.createElement("a");
            itemLink.href = menus[i].menuItems[j].href;
            itemLink.className = "menuItem";
            itemLink.onmouseover = toggleHighlight;
            itemLink.onmouseout = toggleHighlight;
            textNode = document.createTextNode(menus[i].menuItems[j].text);
            itemLink.appendChild(textNode);
            menuItem.appendChild(itemLink);
            menuDiv.appendChild(menuItem);
        }
        // append each menu div to the body
        document.body.appendChild(menuDiv);
    }
    makeHashes();
    assignLabelEvents();
    // pre-position menu
    for (i = 0; i < menus.length; i++) {
        positionMenu(menus[i].elemId);
    }
    menuReady = true;
}

// initialize global that helps manage menu hiding
var timer;

// invoked from mouseovers inside menus to cancel hide
// request from mouseout of menu bar image et al.
function keepMenu() {
    clearTimeout(timer);
}

function cancelAll() {
    keepMenu();
    menuReady = false;
}

// invoked from mouseouts to request hiding all menus
// in 1/4 second, unless cancelled
function requestHide() {
    timer = setTimeout("hideMenus()", 250);
}

// "brute force" hiding of all menus and restoration
// of normal menu bar images
function hideMenus() {
    for (var i = 0; i < menus.length; i++) {
       document.getElementById(menus[i].mBarImgId).src = menus[i].mBarImgNormal.src;
       var menu = document.getElementById(menus[i].elemId)
       menu.style.visibility = "hidden";
    }
}

// set menu position just before displaying it
function positionMenu(menuId, tooltip){
    // use the menu bar image for position reference of related div
    var mBarImg = document.getElementById(menus[menuId].mBarImgId);
    var offsetTrail = mBarImg;
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    var menuDiv = document.getElementById(menuId);
    menuDiv.style.left = offsetLeft + "px";
    menuDiv.style.top = offsetTop + mBarImg.height + "px";
	//alert('Tooltip is ' + tooltip + ' x is ' + menuDiv.style.left + ' y is ' + menuDiv.style.top);
	showByPosition(tooltip, offsetLeft -200, offsetTop + mBarImg.height, event);
}

// display a particular menu div
function showMenu(menuId, tooltip) {
    if (menuReady) {
        keepMenu();
        hideMenus();
        positionMenu(menuId, tooltip);
        var menu = document.getElementById(menuId);
        menu.style.visibility = "visible";
    }
}

// menu bar image swapping, invoked from mouse events in menu bar
// swap style sheets for menu items during rollovers
function toggleHighlight(evt) {
    evt = (evt) ? evt : ((event) ? event : null);
    if (typeof menuReady != "undefined") {
        if (menuReady && evt) {
            var elem = (evt.target) ? evt.target : evt.srcElement;
            if (elem.nodeType == 3) {
                elem = elem.parentNode;
            }
            if (evt.type == "mouseover") {
                keepMenu();
                elem.className ="menuItemOn";
            } else {
                elem.className ="menuItem";
                requestHide();
            }
            evt.cancelBubble = true;
        }
    }
}

function swap(evt) {
    evt = (evt) ? evt : ((event) ? event : null);
    if (typeof menuReady != "undefined") {
        if (evt && (document.getElementById && document.styleSheets) && menuReady) {
            var elem = (evt.target) ? evt.target : evt.srcElement;
			var tooltip = 'tt_' + elem.id;
			// alert('tooltip is ' + tooltip);
			// alert('elem ' + menus[elem.id].elemId );
            if (elem.className == "menuImg") {
                if (evt.type == "mouseover") {
                    showMenu(menus[elem.id].elemId, tooltip);
                    elem.src = menus[elem.id].mBarImgHilite.src;
					// showByPosition(tooltip, 150, 0, event);
                } else if (evt.type == "mouseout") {
                    requestHide();
					hide(tooltip);
                }
                evt.cancelBubble = true;
            }
        }
    }
}

// create menus only if key items are supported
function initMenus() {
	// set up admin menu only if user logged in as administrator
	// (which means that menuImg_7, the Admin button, will exist)
	if(document.getElementById("menuImg_7")){
	// alert ('Its there!');
	menus[7] = {mBarImgId:"menuImg_7",
				mBarImgNormal:imagesNormal["admin"],
				mBarImgHilite:imagesHilite["admin"],
				menuItems:[
							{text:"Vehicle Administration", href:"/cgi-bin/admin/vehicles.pl"},
							{text:"Read AutoTrader Advert", href:"/cgi-bin/utility/adsplit.pl"},
							{text:"Stock List Print", href:"/cgi-bin/admin/catalogue.pl"},
							{text:"ABI Database", href:"/cgi-bin/admin/abidetails.pl"},
							{text:"Car Features", href:"/cgi-bin/admin/features.pl"},
							{text:"Sales Pitches(reminders)", href:"/cgi-bin/admin/pitches.pl"},
							{text:"Car Colours", href:"/cgi-bin/admin/colours.pl"},
							{text:"Car Makes", href:"/cgi-bin/admin/makes.pl"},
							{text:"Paint Finishes", href:"/cgi-bin/admin/finishes.pl"},
							{text:"Body Types", href:"/cgi-bin/admin/bodies.pl"},
							{text:"Fuel Types", href:"/cgi-bin/admin/fuels.pl"}
				],
				elemId:""
			   };
	}

    if (document.getElementById && document.styleSheets) {
        setTimeout("makeMenus()", 5);
        window.onunload=cancelAll;
    }
}

function get_models(make){
	// alert('get_models');
	// 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 valReg(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;
} 

