// ZA VERSION
// utils.js
// Version 1.0 02-03-2000
// J Crosby
// See bottom for routines to run
// This function decodes the any string
// that's been encoded using URL encoding technique
function URLDecode(psEncodeString) 
{
  // Create a regular expression to search all +s in the string
  var lsRegExp = /\+/g;
  // Return the decoded string
  return unescape(String(psEncodeString).replace(lsRegExp, " ")); 
}
function qstringvars(name) {
	querystring = location.search.substring(1);
	startsearch = querystring.indexOf(name + '=');
	if (startsearch != -1) {
		startpos = querystring.indexOf("=", startsearch)+1;
		endpos = querystring.indexOf("&", startpos);
		if (endpos != -1) {
			ret_value = querystring.substring(startpos, endpos);
		}
		else {
			ret_value = querystring.substring(startpos);
		}
		return (URLDecode(ret_value));
	} else {
		return ("");
	}
}

function multipleqstringvars(name) {
	querystring = location.search.substring(1);
	var list = '';
	pos = querystring.indexOf(name + '=');
	while ( pos != -1 ) {
	   	startpos = querystring.indexOf("=", pos)+1;
			endpos = querystring.indexOf("&", startpos);
            // the param must be at the end of the querystring, so set the length accordingly
            if (endpos == -1)
            {
                    endpos = querystring.length;
            }
      
			if (endpos != -1) {
				list = querystring.substring(startpos, endpos) + '_' + list;
			}
	   	pos = querystring.indexOf(name,pos+1);
	}
	//alert('DEBUG\nlist=' + list);
	return list;
}

function convertParam (paramName, paramValue)
{
	var value = paramValue;
	
	if (paramValue != '')
	{
		switch (paramName)
		{
			case 'min_year':
			{
					value = paramValue +'00';
					break;
			}

			case 'max_year':
			{
					value = paramValue +'12';
					break;
			}
		
			case 'source':
			{
				switch (paramValue)
				{
					case '1':
						value = 'p';
						break;
					case '2':
						value = 't';
						break;
					default:
						value = '0'
						break;
				}
				break;				
			}
			
			case 'sort':
			{
				switch (paramValue)
				{
					case '0':
						value = 'specified_price';
						break;
					case '1':
						value = 'make';
						break;
					case '12':
						value = 'model';
						break;
					case '4':
						value = 'distance';
						break;
					case '5':
						value = 'neg_price';
						break;
					case '9':
						value = 'mileage';
						break;
					case '10':
						value = 'neg_year';
						break;
					case '14':
						value = 'neg_mileage';
						break;
					default:
						value = 'neg_price'
						break;
				}
			}
		}
	}
	
	return value;	
}

function broadcast (formname, qname, qnameUK) {
	// Check whether this form field is disabled already for some reason(Not logged in). 
	// In such cases ignore prefill.
	if(!formname.disabled)
	{
	if(qname == 'did_multiple') {
		var value = didqstring();
	} else {
		var value = qstringvars(qname);
	} 
	
  if (value == '' && qnameUK != '')
  {
  	var ukValue = '';
  	
  	if (qnameUK == 'county')
  	{
	  	ukValue = multipleqstringvars(qnameUK);
  	}
  	else
  	{
	  	ukValue = qstringvars(qnameUK);
	}
        // If we have a new style UR param name, but an old style form field name, then we have to convert the value back to the old style values
	    if (formname.name == qname)
	    {
	        value = convertParam(qnameUK, ukValue); 
        }
	    else
	    {
	        value=ukValue;
	    }

  	
  }
	
	// Now work out the type of field we are dealing with
	if (!(formname.type) == true)
	{
		var type = 'radio';
	}
	else
	{
		var type = formname.type;
	}
	if (type == 'select-one')
	{
		if (!(formname.options) == false) 
		{
			// prefill make dropdown
			var total    = formname.options.length;
			for(z=0;z < total; z++) 
			{
				if (formname.options[z].value == value)
				{
					formname.selectedIndex = z;
					// check for make, call model prefill function!
					if (qname == 'make_id_EQI')
					{
			            if ( document.mainform.model_EQS != null || document.mainform.model != null )
			            {
							if (typeof UpdateDropDown == 'function')  
						   	{            
								UpdateDropDown(formname.selectedIndex);            
							}
							else if (typeof get_range =='function')  
						   	{            
								get_range(_model[formname.selectedIndex]);            
							}
			            }
					}
				}
			}
		} else {
			// must be a text box
			prefill_a_textbox (formname, qname);
		}
	} else if (type == 'select-multiple'){
		if (!(formname.options) == false) {
			// prefill make dropdown
			var total    = formname.options.length;
			var VALUES = value.split('_');
			for(f=0;f < VALUES.length; f++){
				for(z=0;z < total; z++) {
					if (formname.options[z].value == VALUES[f]){
						formname.options[z].selected = 'checked';
					}
				}
			}
		} else {
			// must be a text box
			prefill_a_textbox (formname, qname);
		}
	} else if (type == 'text'){
		if (value != "")
			formname.value=value;
	} else if (type == 'radio'){
		if (value != ""){
			if (value == formname.value)
				formname.checked=1;
		}
	}
	} //not disabled	
}

function start_prefill() {
	var c = document.forms['mainform'].elements;
	var accept = new Array		('make_id_EQI', 'model_EQS', 	'specified_price_GT', 	'specified_price_LT', 	'source_EQS', 	'mileage_RANGE', 'keywords_LKSPLIT', 'photo', 	'geolocate', 'postcode', 'orderby', 'year_CONV', 	'currency', 'engine_cc', 'country', 'county_id_IN',	'county_sel', 	'year_GT',	'year_LT',	'subcat_EQS',	'county','did_multiple');
	var acceptUK = 	new Array	('make', 		'model', 		'min_pr',		 		'max_pr', 				'source', 		'', 			 'keywords', 		 '', 		'miles', 	 'postcode', 'sort', 	'', 			'currency', '', 		 'country', 'county',		'',				'min_year',	'max_year',	'subcat', 			'county','');

	for(i=0;i< c.length; i++)
	{
		var field = c[i];
		if (!(field) == false)
		{
			// check for and prefill the specified field
			for(j=0; j < accept.length; j++)
			{
		        if (field.name == accept[j] || field.name == acceptUK[j])			
				{
					//alert('MATCHED IT: ' + field.name + ' => ' + accept[j]);
		            broadcast (field, accept[j], acceptUK[j]);					
					break;
				}
			}
		}
	}
}


//prefill the dealers during a group search
//converts multiple versions of "did_multiple" to a string separated by '_'
function didqstring() {
	querystring = location.search.substring(1);
	var list = '';
	pos = querystring.indexOf("did_multiple");
	while ( pos != -1 ) {
	   	startpos = querystring.indexOf("=", pos)+1;
			endpos = querystring.indexOf("&", startpos);
			if (endpos != -1) {
				list = querystring.substring(startpos, endpos) + '_' + list;
			}
	   	pos = querystring.indexOf("did_multiple",pos+1);
	}
	return list;
}


