/*
'******************************************************************************
'* nansi.js
'*
'* Client-side JavaScript library for NANSI
'*
'* History
'*	v0.01		RGD/GTW				19/Apr/2002		Development
'*	20021008						08/Oct/2002		Phase 1 Release
'*				GAS					01/Dec/2002		launchPopup() - brings window into focus
'*				Ruth				25/Oct/2004		Used Car Comparator - add vehicle to saved list
'*  VSN 3.0.0.0 Ruth				29/12/2005		Put new function in to PCase the range descriptions.
'*				Pradeep				05/02/2007		Created try catch block in launch popup method
'*				Pradeep				15/03/2007		To Add SlideShow Methods
'*
'* (c) Glass's Information Services 2002
'******************************************************************************
*/

// Globals

// Regular Expression Constants
var REGEXP_UK_POSTCODE_REVERSED = /^\s*[A-Z]{2}\d ?[A-Z\d]{1,2}[A-Z]{1,2}$/i;
var REGEXP_UK_TELEPHONE_NUMBER = /^[0-9\(\)\+ ]+$/;
var REGEXP_EMAIL_ADDRESS = /^[^@\s]+@[^@\.\s]+\.[^@\s]+\s*$/;
var REGEXP_ALL_SPACES = /^\s+$/;

// used for dynamic population of the Range SELECT
var objRanges = new Object();
var d=document;
// used by function adjustElementHeight
var animationTimeoutID;
var INCREASE_HEIGHT = true;
var DECREASE_HEIGHT = false;

// used to prevent multiple attempts to submit a form
var blnAllowFormSubmit = true;

function launchPopup(i_strURL, i_strWindowName, i_intMode, i_intWidth, i_intHeight) {
/*
'******************************************************************************
'* Launches pop-up window
'*
'* Inputs:  i_strURL         - URL
'*          i_strWindowName  - Window name
'*          i_intMode        - Mode
'*          i_intWidth       - Window width
'*          i_intHeight      - Window height
'******************************************************************************
*/
try
{
	var windowFeatures = "width=" + i_intWidth + ",height=" + i_intHeight + ",directories=0,hotkeys=1,location=0,menubar=0,personalbar=0,resizeable=0,scrollbars=1,status=0,toolbar=0";
	var popup

	if (i_intMode) { 
		// Mode 1, default pop-up settings (full window)
		popup = window.open(i_strURL,i_strWindowName);
	} else {
		// Mode 0, optimised pop-up settings
		popup = window.open(i_strURL,i_strWindowName,windowFeatures);
	}
	popup.focus();
}
catch(err)
{}

}

function doSearchForm() {
/*
'******************************************************************************
'* Validates and submits search form
'******************************************************************************
*/

var formOK = true;
var errMsg = "";
var selectedAllDefaults = true;
var confirmOK = true;
var postCodeOK = true;

	with (document.frmSearch) {

		if (document.frmSearch.txtPostCode) {
			// max db table field length is 12
			// limit form field to maximim of 9 characters
			//if (txtPostCode.value.length > 12) {
			if (txtPostCode.value.length > 9) {
				errMsg += "'Postcode' too long (max 9 characters).\n";
				postCodeOK = false;
				formOK = false;
			}

			// form-field validation 

			// postcode
			// First of all, reverse the postcode, then do
			// a regExp test with a reversed pattern;
			// otherwise we can run into problems with
			// 'greedy' matching from the left with postcodes
			// of form 'L1 1AA' when the space is omitted.
			// Forward r.e.: /^[A-Z]{1,2}[A-Z\d]{1,2} ?\d[A-Z]{2}\s*$/i
			var pcRev = ""
			for (var i = txtPostCode.value.length-1; i > -1; i--) {
				pcRev += txtPostCode.value.charAt(i);
			}
			if (txtPostCode.value.length > 0 && !REGEXP_UK_POSTCODE_REVERSED.test(pcRev)) {
				errMsg += "Please enter a valid UK postcode.\n";
				postCodeOK = false;
				formOK = false;
			}
		} // if (txtPostCode)

		if (document.frmSearch.selManufacturer) {
			if (selManufacturer.options[selManufacturer.selectedIndex].value != "")
				selectedAllDefaults = false;
		} // if (selManufacturer)

		if (document.frmSearch.selRange) {
			if (selRange.options[selRange.selectedIndex].value != "")
				selectedAllDefaults = false;
		} // if (selRange)

		if (document.frmSearch.selPriceRange) {
			if (selPriceRange.options[selPriceRange.selectedIndex].value != "")
				selectedAllDefaults = false;
		} // if (selPriceRange)

		if (document.frmSearch.selDistanceLimit) {
			if (selDistanceLimit.options[selDistanceLimit.selectedIndex].value != "") {
				selectedAllDefaults = false;
				// Check a valid postcode entered in order to calculate search result distances
				// Assumption: txtPostCode must be present if selDistanceLimit is available
				if (postCodeOK && txtPostCode.value.length == 0) {
					errMsg += "You have selected a distance to limit the search but not entered your postcode.\nPlease enter a valid UK postcode.\n";
					formOK = false;
				}
			}
		} // if (selDistanceLimit)

		if (document.frmSearch.selTransmissionType) {
			if (selTransmissionType.options[selTransmissionType.selectedIndex].value != "")
				selectedAllDefaults = false;
		} // if (selTransmissionType)

		if (document.frmSearch.selBodyType) {
			if (selBodyType.options[selBodyType.selectedIndex].value != "")
				selectedAllDefaults = false;
		} // if (selBodyType)

		if (document.frmSearch.selFuelType) {
			if (selFuelType.options[selFuelType.selectedIndex].value != "")
				selectedAllDefaults = false;
		} // if (selFuelType)

		if (document.frmSearch.selClassification) {
			if (selClassification.options[selClassification.selectedIndex].value != "")
				selectedAllDefaults = false;
		} // if (selClassification)

		if (document.frmSearch.selAgeLimit) {
			if (selAgeLimit.options[selAgeLimit.selectedIndex].value != "")
				selectedAllDefaults = false;
		} // if (selAgeLimit)

		if (document.frmSearch.selEngineCapacity) {
			if (selEngineCapacity.options[selEngineCapacity.selectedIndex].value != "")
				selectedAllDefaults = false;
		} // if (selEngineCapacity)

		if (document.frmSearch.selOdometerReadingLimit) {
			if (selOdometerReadingLimit.options[selOdometerReadingLimit.selectedIndex].value != "")
				selectedAllDefaults = false;
		} // if (selOdometerReadingLimit)

		
		if (formOK) {
			// Confirm search with all default values
			if (selectedAllDefaults) {	
				if (!confirm(g_strMessageConfirmDefaultCriteria))
					confirmOK = false;
			}
			
			// Confirm search with no postcode
			if (confirmOK && document.frmSearch.txtPostCode && txtPostCode.value.length == 0) {
				if (!confirm(g_strMessageConfirmNoPostcode))
					confirmOK = false;
			}
			
			// ConfirmOK must be true for Submit to continue server side		
			// Global blnAllowFormSubmit must also be true for this to happen
			if (confirmOK && blnAllowFormSubmit) {
				// inhibit the form from being submitted again
				blnAllowFormSubmit = false;
				return true;
			}
			else {
				return false;
			}
			
		} else {
			alert(errMsg);
			return false;
		} // if (formOK)
		
	} // with (document.frmSearch)

}

function clearSearchForm() {
/*
'******************************************************************************
'* Sets all form input values to 'New' search defaults
'******************************************************************************
*/

	with (document.frmSearch) {

		if (document.frmSearch.txtPostCode) {
			txtPostCode.value = "";
		} // if (txtPostCode)

		if (document.frmSearch.selManufacturer) {
			selManufacturer.selectedIndex = 0;
		} // if (selManufacturer)

		if (document.frmSearch.selRange) {
			populateRanges(false);
		} // if (selRange)

		if (document.frmSearch.selPriceRange) {
			selPriceRange.selectedIndex = 0;
		} // if (selPriceRange)

		if (document.frmSearch.selDistanceLimit) {
			selDistanceLimit.selectedIndex = 0;
		} // if (selDistanceLimit)

		if (document.frmSearch.selTransmissionType) {
			selTransmissionType.selectedIndex = 0;
		} // if (selTransmissionType)

		if (document.frmSearch.selBodyType) {
			selBodyType.selectedIndex = 0;
		} // if (selBodyType)

		if (document.frmSearch.selFuelType) {
			selFuelType.selectedIndex = 0;
		} // if (selFuelType)

		if (document.frmSearch.selClassification) {
			selClassification.selectedIndex = 0;
		} // if (selClassification)

		if (document.frmSearch.selAgeLimit) {
			selAgeLimit.selectedIndex = 0;
		} // if (selAgeLimit)

		if (document.frmSearch.selEngineCapacity) {
			selEngineCapacity.selectedIndex = 0;
		} // if (selEngineCapacity)

		if (document.frmSearch.selOdometerReadingLimit) {
			selOdometerReadingLimit.selectedIndex = 0;
		} // if (selOdometerReadingLimit)
		
		if (document.frmSearch.radSortOrder) {
			radSortOrder[0].checked = true;
		} // if (radSortOrder)

	} // with (document.frmSearch)

}

//Modified by EUCOMP 20080929
function adjustElementHeight(i_strElementID, i_lngMaxHeight, i_blnIncrease) {
/*
'******************************************************************************
'* Adjusts the height of the given element and sets a timeout to call
'* self, if appropriate, to provide an animated height transition 
'*
'* Inputs:  i_strElementID      -	ID of element (e.g. TD) to adjust height of 
'*          i_lngMaxHeight		-	the full-size height of the element
'*			i_blnIncrease		-	true  : increase to i_lngMaxHeight
'*									false : decrease from  i_lngMaxHeight to 0
'******************************************************************************
*/
    try 
    {
        if (i_blnIncrease) 
        {
            Resize2(i_lngMaxHeight);
        }
    }
    catch(e)
    { }

    adjustElementHeight_Real(i_strElementID, i_lngMaxHeight, i_blnIncrease);
}

//Renamed by EUCOMP 20080929 from adjustElementHeight.
function adjustElementHeight_Real(i_strElementID, i_lngMaxHeight, i_blnIncrease) {
    /*
    '******************************************************************************
    '* Adjusts the height of the given element and sets a timeout to call
    '* self, if appropriate, to provide an animated height transition 
    '*
    '* Inputs:  i_strElementID      -	ID of element (e.g. TD) to adjust height of 
    '*          i_lngMaxHeight		-	the full-size height of the element
    '*			i_blnIncrease		-	true  : increase to i_lngMaxHeight
    '*									false : decrease from  i_lngMaxHeight to 0
    '******************************************************************************
    */
    var lngAnimationSteps = 10;
    var lngPauseTimeMS = 1;
    var lngStep = Math.ceil(i_lngMaxHeight / lngAnimationSteps);
    var blnDoNextStep = false;

    // get the element's current height without units
    var lngHeight = parseInt(eval(i_strElementID + ".style.height"))

    clearTimeout(animationTimeoutID);

    if (i_blnIncrease) {
        if (lngHeight < i_lngMaxHeight) {
            lngHeight += lngStep;
            if (lngHeight > i_lngMaxHeight)
                lngHeight = i_lngMaxHeight;
            blnDoNextStep = true;
        }
    }
    else {
        if (lngHeight > 0) {
            lngHeight -= lngStep;
            if (lngHeight < 0)
                lngHeight = 0;
            blnDoNextStep = true;
        }
    }
    if (blnDoNextStep == true) {
        // set the height
        eval(i_strElementID + ".style.height = " + lngHeight);
        // set up the next step
        animationTimeoutID = setTimeout("adjustElementHeight_Real('" +
			i_strElementID + "', " + i_lngMaxHeight + ", " +
			i_blnIncrease + ")", lngPauseTimeMS);
    }
    // FJ. 20080925
    else {
    try{
    Resize();
    }
    catch(e)
    {}
    }
}

function advancedConcealReveal(i_strElementID, i_lngMaxHeight, i_blnIncrease) {
/*
'******************************************************************************
'* Wrapper function for adjustElementHeight specific to revealing and concealing
'* advanced search criteria
'*
'* Inputs:  i_strElementID      -	ID of element (e.g. TD) to adjust height of 
'*          i_lngMaxHeight		-	the full-size height of the element
'*			i_blnIncrease		-	true  : increase to i_lngMaxHeight
'*									false : decrease from  i_lngMaxHeight to 0
'******************************************************************************
*/
	// call the function to reveal or conceal the advanced criteria
	adjustElementHeight(i_strElementID, i_lngMaxHeight, i_blnIncrease)
		
	// set the flag to reflect the state		
	document.frmSearch.hdnAdvancedRevealed.value = i_blnIncrease;
	
	// display the appropriate Quick or Advanced tab as active
	setQuickAdvancedTabs(i_blnIncrease)
	
}

function saveStockItem() {
/*
'******************************************************************************
'* Checks ability to save a stock item, and prompts user to confirm action
'******************************************************************************
*/

// TBD

}

function doEnquiryForm() {
/*
'******************************************************************************
'* Validates and submits enquiry form
'******************************************************************************
*/

var formOK = true;
var errMsg = "";

	with (document.frmEnquiry) {
	
		if (document.frmEnquiry.txtName) {
			if (txtName.value.length == 0) {
				errMsg += "Please enter your name.\n";
				formOK = false;
			}
			if (txtName.value.length > 40) {
				errMsg += "'Name' too long (max 40 characters).\n";
				formOK = false;
			}
		} // if (txtName)

		if (document.frmEnquiry.txaAddress) {
			if (txaAddress.value.length > 128) {
				errMsg += "'Address' too long (max 128 characters).\n";
				formOK = false;
			}
		} // if (txaAddress)

		if (document.frmEnquiry.txtPostCode) {
			if (txtPostCode.value.length > 9) {
				errMsg += "'Postcode' too long (max 9 characters).\n";
				formOK = false;
			}
			// FORM-FIELD VALIDATION 
			// postcode
			// First of all, reverse the postcode, then do
			// a regExp test with a reversed pattern;
			// otherwise we can run into problems with
			// 'greedy' matching from the left with postcodes
			// of form 'L1 1AA' when the space is omitted.
			// Forward r.e.: /^[A-Z]{1,2}[A-Z\d]{1,2} ?\d[A-Z]{2}\s*$/i
			var pcRev = ""
			for (var i = txtPostCode.value.length-1; i > -1; i--) {
				pcRev += txtPostCode.value.charAt(i);
			}
			if (txtPostCode.value.length > 0 && !REGEXP_UK_POSTCODE_REVERSED.test(pcRev)) {
				errMsg += "Please enter a valid UK postcode.\n";
				formOK = false;
			}
		} // if (txtPostCode)

		if (document.frmEnquiry.txtTelephoneNumber) {
			if (txtTelephoneNumber.value.length > 24) {
				errMsg += "'Telephone number' too long (max 24 characters).\n";
				formOK = false;
			}
			// FORM-FIELD VALIDATION 
			// phone - numeric plus '(', ')', '+', ' '
			// reject all spaces
			if (txtTelephoneNumber.value.length > 0 && (!REGEXP_UK_TELEPHONE_NUMBER.test(txtTelephoneNumber.value) || REGEXP_ALL_SPACES.test(txtTelephoneNumber.value)) ) {
				errMsg += "Please enter a valid telephone number.\n";
				formOK = false;
			}
		} // if (txtTelephoneNumber)
				
		if (document.frmEnquiry.txtEmailAddress) {
			if (txtEmailAddress.value.length > 50) {
				errMsg += "'Email' too long (max 50 characters).\n";
				formOK = false;
			}
			// FORM-FIELD VALIDATION 
			// email 
			if (txtEmailAddress.value.length > 0 && !REGEXP_EMAIL_ADDRESS.test(txtEmailAddress.value)) {
				errMsg += "Please enter a valid email address.\n";
				formOK = false;
			}
		} // if (txtEmailAddress)

		if (document.frmEnquiry.txtEmailAddress && document.frmEnquiry.txtTelephoneNumber) {		
			if (txtEmailAddress.value.length == 0 && txtTelephoneNumber.value.length == 0) {
				errMsg += "Please enter your telephone number or email address.\n";
				formOK = false;
			}
		}

		if (formOK && blnAllowFormSubmit) {
			// inhibit form from being submitted again
			blnAllowFormSubmit = false;
			return true;
		}
		else {
			if (!formOK) 
				alert(errMsg);
			return false;
		}
			
	} // with (document.frmEnquiry)

}

function populateRanges(i_blnNewManufacturer) {
/*
'******************************************************************************
'* Dynamically creates the Range options available for selection depending
'* upon the selected Manufacturer
'*
'* Inputs:  i_blnNewManufacturer - Indicates whether to display default "Any" value
'*                                 for a new manufacturer or display previous
'*                                 selection recalling server side hidden value
'******************************************************************************
*/
var i;
var manCode;

	// get currently selected Manufacturer code
	with (document.frmSearch.selManufacturer) {
		manCode = options[selectedIndex].value;
	}

	var ranges = eval("objRanges.code" + manCode);

	// clear the current options
	document.frmSearch.selRange.options.length = 0;

	for (i=0; i < ranges.length; i++) {
		// create and add new option to the Ranges SELECT
		var k = document.frmSearch.selRange.options.length;
		document.frmSearch.selRange.options[k] = new Option(ranges[i].desc, ranges[i].code);
	}

	// select the range appropriately
	if (i_blnNewManufacturer) {
		document.frmSearch.selRange.selectedIndex = 0;
		// re-set the hidden form field values
		document.frmSearch.hdnRangeIndex.value = "0";
		document.frmSearch.hdnRangeCode.value = "";
	}
	else
		document.frmSearch.selRange.selectedIndex = document.frmSearch.hdnRangeIndex.value;

}


function selectManufacturer(manufacturerCode)
{
	document.frmSearch.selManufacturer.value=manufacturerCode;
}

function Range(i_strCode, i_strDesc) {
/*
'******************************************************************************
'* Constructor function for the Range object
'*
'* Inputs:  i_strCode - Range code
'*          i_strDesc - Range description
'******************************************************************************
*/

	// Range object constructor
	this.code = i_strCode;
	this.desc = i_strDesc;

}

function SetHiddenRangeValues() {
/*
'******************************************************************************
'* Sets hidden form input variables for Range index and code
'******************************************************************************
*/

	with (document.frmSearch) {
		hdnRangeIndex.value = selRange.selectedIndex;
		hdnRangeCode.value = selRange.options[selRange.selectedIndex].value;
	}
	
}

function setQuickAdvancedTabs(i_blnIsAdvanced) {
/*
'******************************************************************************
'* Sets the Quick and Advanced tab images appropriately
'*
'* Inputs:  i_blnIsAdvanced - Flag to track whether Quick or Advanced state
'******************************************************************************
*/

	if (i_blnIsAdvanced) { 
		if (document['imgQuick'])
			document['imgQuick'].src = imgQuickoff.src;
		if (document['imgAdvanced'])
			document['imgAdvanced'].src = imgAdvancedon.src;
	} 
	else {
		if (document['imgQuick'])
			document['imgQuick'].src = imgQuickon.src;
		if (document['imgAdvanced'])
			document['imgAdvanced'].src = imgAdvancedoff.src;
	}

}

function setImageSource(i_strImageName, i_blnMouseOver, i_blnDoImageSwap) {
/*
'******************************************************************************
'* Sets the Image source for rollover animation images triggered by the
'* onmouseover and onmouseout events.  This relies on there being preloaded
'* Image objects having the same name as the document image (i_strImageName)
'* but with the suffixes 'on' and 'off'.
'*
'* Inputs:  i_strImageName   - Name of Image Object
'*          i_blnMouseOver   - Flag to indicate whether mouseover (imgOn) or mouseout (imgOff)
'*          i_blnDoImageSwap - Flag whether animation is required or not
'******************************************************************************
*/

	if (document.images) {
		// test whether rollover animation is required 
		if (i_blnDoImageSwap) {
			if (i_blnMouseOver) {
				if (document[i_strImageName])
					document[i_strImageName].src = eval(i_strImageName+"on.src");
			}
			else {
				if (document[i_strImageName])
					document[i_strImageName].src = eval(i_strImageName+"off.src");			
			}
		}
	}

}

function Querystring() {
/*
'******************************************************************************
'* Object to enable easy access to the URL query string variables
'******************************************************************************
*/
	
	// get the query string, ignore the ? at the front.
	var querystring=location.search.substring(1,location.search.length);

	// parse out name/value pairs separated via &;
	var args = querystring.split('&');

	// split out each name = value pair
	for (var i=0;i<args.length;i++) {
		
		var pair = args[i].split('=');

		// Fix broken unescaping
		temp = unescape(pair[0]).split('+');
		temp0 = temp.join(' ');
			
		temp = unescape(pair[1]).split('+');
		temp1 = temp.join(' ');
			
		this[temp0]=temp1;
	}

	this.get=Querystring_get;
}

function Querystring_get(strKey,strDefault) {
/*
'******************************************************************************
'* Method of Querystring object to retrieve a given querystring variable value
'******************************************************************************
*/	
	
	var value=this[strKey];

	if (value==null){value=strDefault;}
		
	return value;

}

function PCase(STRING)
{
	var strReturn_Value = "";
	var iTemp = STRING.length;
	if(iTemp==0)
	{
		return"";
	}

	var UcaseNext = false;
	strReturn_Value += STRING.charAt(0).toUpperCase();
	for(var iCounter=1;iCounter < iTemp;iCounter++)
	{
		if(UcaseNext == true)
		{
			strReturn_Value += STRING.charAt(iCounter).toUpperCase();
		}
		else
		{
			strReturn_Value += STRING.charAt(iCounter).toLowerCase();
		}
		var iChar = STRING.charCodeAt(iCounter);
		if(iChar == 32 || iChar == 45 || iChar == 46)
		{
			UcaseNext = true;
		}
		else
		{
			UcaseNext = false
		}
		
		if(iChar == 99 || iChar == 67)
		{
			if(STRING.charCodeAt(iCounter-1)==77 || STRING.charCodeAt(iCounter-1)==109)
			{
				UcaseNext = true;
			}
		}

	} //End For

	return strReturn_Value;
} //End Function



/* Included by Pradeep on 15/03/2007 Begins */

var slideShowSpeed = 5000;
var crossFadeDuration = 3;
var t;
var j = 0;

function PreLoadVehicleImages() 
{ //v3.0

  if(d.images)
  {
   if(!d.preLoad) d.preLoad = new Array();
   
   var i,j=d.preLoad.length,a=PreLoadVehicleImages.arguments; 
   
   for(i=0; i<a.length; i++)
       if (a[i].indexOf("#")!=0)
       { 
			d.preLoad[j] = new Image();
			d.preLoad[j++].src = a[i];
		}	
	}

}

function runSlideShow()
{
   if (d.preLoad.length > 0)
   {
		if (document.all)
		{
			document.images.SlideShow.style.filter="blendTrans(duration=2)";
			document.images.SlideShow.style.filter="blendTrans(duration=crossFadeDuration)";
			document.images.SlideShow.filters.blendTrans.Apply();      
		}
			document.images.SlideShow.src = d.preLoad[j].src;
			
		if (document.all)
		{
			document.images.SlideShow.filters.blendTrans.Play();
		}
		   
		j = j + 1;
		if (j > (document.preLoad.length-1)) j=0;
		t = setTimeout('runSlideShow()', slideShowSpeed);
   }
}

/* Included by Pradeep on 15/03/2007 Ends */

