
function updateServiceNotification(id, source)
{
	var frm = document.frmService;
	if(!frm) return;
	
	Element
	.getElementsByClassName(frm, 'notification')
	.each(function(notif)
	{
		if(notif.tagName != 'TR') return;
		
		if(id && notif.id == id && (!source || source.checked))
		{
			Element.show(notif);
		}
		else
		{
			Element.hide(notif);
		}
	});
}

function updateServiceChoice()
{
	$('wisselNotification').style.display = this.checked ? '' : 'none';
	$('tyrewebshopNotification').style.display = 'none';
	$('halfordsNotification').style.display = 'none';	
}


function checkLastLocation(frm)
{
	if(frm.SAVE_PARAMETER_SAV_LAST_DEPOT.selectedIndex <= 0)
	{
			alert('Selecteer eerst een vestiging om door te gaan.');
			return false;
	}
	return true;
}


function fireCarRegistrationBuild(cri)
{
	var carreg = cri.value = trim(cri.value).toUpperCase();
	var frm = cri.form;
	/*var carreg  
		= trim(frm.cr1.value).toUpperCase()
		+ trim(frm.cr2.value).toUpperCase()
		+ trim(frm.cr3.value).toUpperCase();

	frm.SAVE_PARAMETER_SAV_CAR_REGISTRATION_CODE.value = carreg;*/
	
	
	if(carreg.length > 5)
	{
		$('cardata').style.display = '';
		tryCompleteCarData(carreg);
	}
}

/*
function fireCarRegistrationChanged(cri)
{
	var frm = cri.form;
	if(cri.name == 'cr1')
	{
		if(trim(cri.value).length >= 2)
		{
			frm.cr2.select();
			frm.cr2.focus();
		}
	}
	if(cri.name == 'cr2')
	{
		if(trim(cri.value).length >= 2)
		{
			frm.cr3.select();
			frm.cr3.focus();
		}
	}
}*/

/* Converts a value of a field to uppercase.
*/
function toUpper(field)
{
 	field.value = ('' + field.value).toUpperCase();
}
function tryCompleteCarData(orignatingElement) 
{
	var frm = $('frmCar');
	var url = frm.getAttribute('action');
	//location.href = url + '?action=ProcessSelection'
	//			+ '&REDIRECT_TEMPLATE=ShowCarDataSearchProxy'
	//			 + '&AJAX_CAR_REGISTRATION_CODE=' + frm.FIELD_SCH_CAR_REGISTRATION_CODE.value;
	
	//return;
	
	// ie fix
	if(frm.attributes && frm.attributes.getNamedItem)
	{
		url = frm.attributes.getNamedItem('action').value;
	}
	if(frm.SAVE_PARAMETER_SAV_CAR_REGISTRATION_CODE.value != ''
		&& frm.SAVE_PARAMETER_SAV_CAR_REGISTRATION_CODE.value.length >= 5)
	{
		var myAjax = new Ajax.Request(url,
		{
			method : 'get',
			onSuccess : tryCompleteCarDataHandler,
			onFailure : function(ajaxResponse){alert(ajaxResponse.responseText)},
			parameters : ('action=ProcessSelection'
				+ '&REDIRECT_TEMPLATE=ShowCarDataSearchProxy'
				+ '&AJAX_CAR_REGISTRATION_CODE=' + frm.SAVE_PARAMETER_SAV_CAR_REGISTRATION_CODE.value)
		});
	}
}

/**
* @see tryCompleteCarData
*/
function tryCompleteCarDataHandler(ajaxResponse, orignatingElement)
{
	var frm = $('frmCar');
	
	var response = '';
	eval('response = ' + ajaxResponse.responseText);

	if(response.datasource)
	{
		var brandoptions = frm.SAVE_PARAMETER_CAR_BRANDNAME_DESC.options;
		var foundInList = false;
		for(var i=0; i<brandoptions.length; i++)
		{
			if(brandoptions[i].value == response.car.brandName.toUpperCase())
			{
				foundInList = true;
				frm.SAVE_PARAMETER_CAR_BRANDNAME_DESC.selectedIndex = i;
			}
		}
		if(!foundInList)
		{
			var opt = new Option(response.car.brandName.toUpperCase(), response.car.brandName.toUpperCase());
			var idx = brandoptions.length;
			brandoptions[idx] = opt;
			frm.SAVE_PARAMETER_CAR_BRANDNAME_DESC.selectedIndex = idx;
			//frm.SAVE_PARAMETER_CAR_OWNER_CODE.value = 'UNKNOWN';
		}
		
		
		if(response.datasource == 'HORUS')
		{
			frm.SAVE_PARAMETER_CAR_TYPE_DESC.value = response.car.model;
		}
		else
		{
			frm.SAVE_PARAMETER_CAR_TYPE_DESC.value = response.car.model
				+ ' ' + response.car.modelFunction
				+ ' ' + response.car.cylinders
				+ ' cil. ' + response.car.transmission
				+ ' ' + response.car.typeNr;
		}
		
		if(response.car.fuel == 'Benz.' || response.car.fuel == 'BENZINE')
		{
			frm.SAVE_PARAMETER_CAR_FUEL_CODE.value = 'BENZINE';
		}
		else if(response.car.fuel == 'Diesel' || response.car.fuel == 'DIESEL')
		{
			frm.SAVE_PARAMETER_CAR_FUEL_CODE.value = 'DIESEL';
		}
		else if(response.car.fuel == 'Lpg' || response.car.fuel == 'LPG')
		{
			frm.SAVE_PARAMETER_CAR_FUEL_CODE.value = 'LPG';
		}
		else
		{
			frm.SAVE_PARAMETER_CAR_FUEL_CODE.selectedIndex = 0;
		}
		
		frm.SAVE_PARAMETER_CAR_YOM_DESC.value = (response.car.buildyear
			&& typeof(response.car.buildyear) != 'undefined')
			? response.car.buildyear : '';
		
		if(response.owner)
		{
			var ownership = response.owner != 'PARTIC' ? 'LEASE' : 'PARTICULIER';
			frm.SAVE_PARAMETER_CAR_OWNERSHIP_CODE.value = ownership;
			if(ownership == 'LEASE')
			{
				$('leaseContainer').style.display = '';
				var options = frm.SAVE_PARAMETER_CAR_OWNER_CODE.options;
				var foundInList = false;
				for(var i=0; i<options.length; i++)
				{
					if(options[i].value == response.owner)
					{
						foundInList = true;
						frm.SAVE_PARAMETER_CAR_OWNER_CODE.selectedIndex = i;
					}
				}
				if(!foundInList)
				{
					var opt = new Option(response.ownername, response.owner);
					var idx = options.length;
					options[idx] = opt;
					frm.SAVE_PARAMETER_CAR_OWNER_CODE.selectedIndex = idx;//options.length;
					//frm.SAVE_PARAMETER_CAR_OWNER_CODE.value = 'UNKNOWN';
				}
			}
			else
			{
				frm.SAVE_PARAMETER_CAR_OWNER_CODE.selectedIndex = 0;
				$('leaseContainer').style.display = 'none';
			}
		}
		else
		{
			frm.SAVE_PARAMETER_CAR_OWNERSHIP_CODE.selectedIndex = 0;
			frm.SAVE_PARAMETER_CAR_OWNER_CODE.selectedIndex = 0;
			$('leaseContainer').style.display = 'none';
		}
	}
	else
	{
		frm.SAVE_PARAMETER_CAR_BRANDNAME_DESC.selectedIndex = 0;
		frm.SAVE_PARAMETER_CAR_TYPE_DESC.value = '';
		frm.SAVE_PARAMETER_CAR_FUEL_CODE.selectedIndex = 0;
		frm.SAVE_PARAMETER_CAR_YOM_DESC.value = '';
		frm.SAVE_PARAMETER_CAR_OWNERSHIP_CODE.selectedIndex = 0;
		frm.SAVE_PARAMETER_CAR_OWNER_CODE.selectedIndex = 0;		
		$('leaseContainer').style.display = 'none';
	}
	frm.myAjax = null;
}



/**
* Emailaddress check...
*/
function fireIdentifyEmailChanged(f)
{
	var val 
		= f.SAVE_PARAMETER_SAV_ORDER_EMAIL.value 
		= trim(f.SAVE_PARAMETER_SAV_ORDER_EMAIL.value);
		
	if(val == '' || !isEmailAddress(val))
	{
		alert('Vul eerst uw e-mailadres in.');	
		f.SAVE_PARAMETER_SAV_ORDER_EMAIL.focus();
		return;
	}

	f.elements['action'].value = 'ProcessSelection';
	f.submit();	
	
}


/**
* @return boolean
*/
function fireIdentifySubmitted(f)
{
	var errors = [];
	var strAlert = "U heeft de volgende velden niet of niet juist ingevuld: \n- ";

	var email = f.SAVE_PARAMETER_SAV_ORDER_EMAIL.value 
			= trim(f.SAVE_PARAMETER_SAV_ORDER_EMAIL.value);
			
	if(email == '' || !isEmailAddress(email))
	{
		errors.push('E-mail adres');
	}
		
	if(!f.SAVE_PARAMETER_PRS_GENDER_CODE[0].checked 
		&& !f.SAVE_PARAMETER_PRS_GENDER_CODE[1].checked) 
	{
		errors.push('Aanhef');
	}
		
	f.SAVE_PARAMETER_PRS_INITIALS_DESC.value = trim(f.SAVE_PARAMETER_PRS_INITIALS_DESC.value);
	if(f.SAVE_PARAMETER_PRS_INITIALS_DESC.value.length == 0)
	{
		errors.push('Voorletter(s)');
	}
		
	f.SAVE_PARAMETER_PRS_MIDDLE_NAME_DESC.value = trim(f.SAVE_PARAMETER_PRS_MIDDLE_NAME_DESC.value);

	f.SAVE_PARAMETER_PRS_LAST_NAME_DESC.value = trim(f.SAVE_PARAMETER_PRS_LAST_NAME_DESC.value);
	if(f.SAVE_PARAMETER_PRS_LAST_NAME_DESC.value.length == 0)
	{
		errors.push('Achternaam');
	}
		
	f.SAVE_PARAMETER_PRS_ADDRESS_ZIP_CODE.value = trim(f.SAVE_PARAMETER_PRS_ADDRESS_ZIP_CODE.value);
	if(f.SAVE_PARAMETER_PRS_ADDRESS_ZIP_CODE.value.length == 0) 
	{
		errors.push('Postcode');
	}

	f.SAVE_PARAMETER_PRS_ADDRESS_NUMBER_DESC.value = trim(f.SAVE_PARAMETER_PRS_ADDRESS_NUMBER_DESC.value);
	if(f.SAVE_PARAMETER_PRS_ADDRESS_NUMBER_DESC.value.length == 0) 
	{
		errors.push('Huisnummer');
	}

	f.SAVE_PARAMETER_PRS_ADDRESS_STREET_DESC.value = trim(f.SAVE_PARAMETER_PRS_ADDRESS_STREET_DESC.value);
	if(f.SAVE_PARAMETER_PRS_ADDRESS_STREET_DESC.value.length == 0) 
	{
		errors.push('Adres');
	}

	f.SAVE_PARAMETER_PRS_ADDRESS_TOWN_DESC.value = trim(f.SAVE_PARAMETER_PRS_ADDRESS_TOWN_DESC.value);
	if(f.SAVE_PARAMETER_PRS_ADDRESS_TOWN_DESC.value.length == 0) 
	{
		errors.push('Woonplaats');
	}

	// match "+31 678 12345"
	// match "06789-12345"
	// match "+3167812345"
	// no match "09876"	
	// no match "+31-09876"	
	// no match "09876 09876"	
	// no match "09876a9876"	
	// a minimum of 10 digits and must common notations are allowed
	var phone1 = f.SAVE_PARAMETER_PRS_PRIVATE_PHONE_DESC.value 
		= trim(f.SAVE_PARAMETER_PRS_PRIVATE_PHONE_DESC.value);		
	var isPhone1 = !(!phone1.match(/^[+]?\d+[ -]?\d+[ -]?\d+$/)
		|| (phone1.replace(/[^\d]/g, '').length < 10));

	var phone2 = f.SAVE_PARAMETER_PRS_MOBILE_PHONE_DESC.value 
		= trim(f.SAVE_PARAMETER_PRS_MOBILE_PHONE_DESC.value);	
	var isPhone2 = !(!phone2.match(/^[+]?\d+[ -]?\d+[ -]?\d+$/)
		|| (phone2.replace(/[^\d]/g, '').length < 10));

	if(!isPhone1 && !isPhone2) 
	{
		errors.push('Telefoon vast of Telefoon mobiel');
	}

	//end phone
	
	if(f.SAVE_PARAMETER_SAV_ORDER_REMARK_DESC)
	{
		f.SAVE_PARAMETER_SAV_ORDER_REMARK_DESC.value = trim(f.SAVE_PARAMETER_SAV_ORDER_REMARK_DESC.value);
	}
		
	if(f.SAVE_PARAMETER_SAV_ORDER_ACTIONCODE)
	{
		f.SAVE_PARAMETER_SAV_ORDER_ACTIONCODE.value 
			= trim(f.SAVE_PARAMETER_SAV_ORDER_ACTIONCODE.value);
	}
	
	
	if(f.FIELD_PASSWORD1_CODE && f.FIELD_PASSWORD2_CODE)
	{
		var pw1 = f.FIELD_PASSWORD1_CODE.value
			= trim(f.FIELD_PASSWORD1_CODE.value);

		var pw2 = f.FIELD_PASSWORD2_CODE.value
			= trim(f.FIELD_PASSWORD2_CODE.value);
			
		if(pw1.length > 0)
		{
			if(pw1.length < 6 || !/^[a-zA-Z0-9]{6,}$/.test(pw1))
			{
				errors.push('Uw wachtwoord voldoet niet aan de criteria.');
			}
			else if(pw1 != pw2)
			{
				errors.push('Uw wachtwoord is niet gelijk aan uw controle wachtwoord');				
			}
		}
	}
	

	var isValidated = (errors.length == 0);
	if(!isValidated)
	{
		alert(strAlert + errors.join('\n- '));
	}
//	else
//	{
//		if(!f.SAVE_PARAMETER_SAV_CONDITIONS_ACCEPTED[0].checked)
//		{
//			isValidated = false;
//			alert('U moet akkoord gaan met onze algemene voorwaarden voordat wij uw afspraak afronden');
//		}
//	}
	
	if(isValidated)
	{
		if(!f.isSubmitted)
		{
			showWibaSubmitted();
	
			f.isSubmitted = 1;
			f.submit();
		}
		else
		{
			alert('Uw afspraak wordt al verwerkt...\n\nEen ogenblik geduld a.u.b.');
		}
	}
}



function showWibaSubmitted()
{
	var page = $('identifyForm');
	
	// find the position of the inner page and
	// adjust the xy point for the indicator
	var point = Position.positionedOffset(page);
	
	// unfortunately, IE wont let us show the indicator 
	// above the select (which would give a nicer effect),
	// so we show the indicator right next to the <select>.
	point[0] += Element.getWidth(page) / 2 - 120; // x
	point[1] += 300; // y	
	
	Element.setStyle('wibaSubmittedIndicator', 
	{
		display: 'block',
		left: point[0] + 'px',
	 	top: point[1] + 'px'
	});
}



/**
 * 
 */
function findTyreSelect(frm, item)
{
	var elements = Form.getElements(frm);
	var i=0;
	
	// skip all selects before <item>
	for(; i<elements.length; i++)
		if(elements[i] == item) break;
	
	// if <item> not found, abort function
	if(i >= elements.length)
		return;
	
	var nextSelect = elements[++i];
	
	if(nextSelect && nextSelect.name == 'SAVE_PARAMETER_SAV_TYR_REMARK_DESC')
	{
		nextSelect = null;
	}
	
	if(nextSelect)
	{
		var busyIndicator = 'busyIndicator';
	
		// find the position of the select and
		// adjust the xy point for the busyIndicator
		var point = Position.positionedOffset(nextSelect);
		
		// unfortunately, IE wont let us show the indicator 
		// above the select (which would give a nicer effect),
		// so we show the indicator right next to the <select>.
		point[0] += Element.getWidth(nextSelect) + 4; // x
		point[1] += 2; // y	
		
		Element.setStyle(busyIndicator, 
		{
			display: 'block',
			left: point[0] + 'px',
		 	top: point[1] + 'px'
		});
	}

	if(nextSelect)
	{		
		// for each select after <item>, remove all-but-first
		// options. these will be refilled later.
		for(; i<elements.length; i++)
		{
			var el = elements[i];
			if(el.tagName.toLowerCase() == 'select'
				&& el.name != 'SAVE_PARAMETER_SAV_TYR_REMARK_DESC')
			{
				var options = el.childNodes;
				for(var j=options.length-1; j>0; j--)
					if(options[j] != el.options[0])
						el.removeChild(options[j]);
				el.selectedIndex = 0;
			}
		}
	}
	
	// if user selected 'hint' option, 
	// we do not have to update the next select box
	if(item.selectedIndex == 0 && item.value == ''
		&& item.name != 'SAVE_PARAMETER_SAV_TYR_BRANDGROUP_CODE')
	{
		Element.hide('busyIndicator');
		Element.hide('next');
		return;
	}
	
	//if(frm && nextSelect)
	{
		findTyreSelectCall(frm, nextSelect);
	}
	findTyreSelectNext(frm);
}


/**
 * 
 */
function findTyreSelectHandler(frm, select, transport)
{
	if(!frm || !select)
		return;
		
	var props;
	try { eval('props = ' + transport.responseText); } 
	catch(e) { props = {}; }

	var elements = Form.getElements(frm);

	findTyreSelectHandlerUpdate(frm, props, select, elements);
	
	if(select)
	{
		// always show the busyIndicator for a small period, 
		// to notify the user something is changing/has changed.
		setTimeout(function()
		{
			Element.hide('busyIndicator');
		}, 300);
	}
	
	findTyreSelectNext(frm);
	
	frm.myAjax = null;
}



function findTyreSelectNext(frm)
{
	var elements = Form.getElements(frm);
	
	// check if each select is ok
	// season has no hint option at 0
	// brandgroup is not required
	var allFilled = true;
	for(var i = 0; i<elements.length; i++)
	{
		var el = elements[i];
		if(el.tagName.toLowerCase() == 'select')
		{
			if(el.name != 'SAVE_PARAMETER_SAV_TYR_SEASON_CODE'
				&& el.name != 'SAVE_PARAMETER_SAV_TYR_BRANDGROUP_CODE')
			{
				if(el.selectedIndex == 0)
				{
					allFilled = false;
				}
			}
		}
	}
		
	if(allFilled)
	{
		Element.setStyle('next', {display:'block'});
	}
	else
	{
		Element.hide('next');
	}
	
}


function findTyreSelectHandlerUpdate(frm, props, select, elements)
{
	// select.name = ~SAVE_PARAMETER_SAV_TYR_BRANDGROUP_CODE
	// props[SAV_TYR_BRANDGROUP_CODE]
	var key = select.name.substring('SAVE_PARAMETER_'.length);
	var options = props[key];
	if(options) 
	{
		var optionLength = 0;
		if(key == 'SAV_TYR_BRANDGROUP_CODE')
		{
			for(var i=0; i<options.length; i+=2)
			{
				// count tyres
				optionLength += options[i+1].length;
				
				var brand = options[i];
				options[i+1].each(function(item)
				{
					select.options[select.options.length] 
						= new Option(brand + ' ' + item[item.length-1], item[0]);
				});
			}
		}
		else
		{
			optionLength = options.length;
			options.each(function(item)
			{
				select.options[select.options.length] 
					= new Option(item[item.length-1], item[0]);
			});
		}
		
		// If search result had only 1 item, 
		// handle the result for the next select too
		if(optionLength == 1)
		{
			select.selectedIndex = 1;
			
			var i=0;
			
			// skip all selects before <item>
			for(; i<elements.length; i++)
				if(elements[i] == select) break;
			
			if(i < elements.length-2)
			{
				var nextSelect = elements[++i];
				findTyreSelectHandlerUpdate(frm, props, nextSelect, elements);
			}
		}
	}
}



function findTyreSelectCall(frm, select)
{
	var url = getFormAction(frm);	
	var params = Form.serialize(frm);
	
	params += '&REDIRECT_PARAMETER_xsl=FindTyre1';

	if(frm.myAjax)
	{
		try
		{
			frm.myAjax.transport.abort();			
		}
		catch(e) { /* ignored */ }
		frm.myAjax = null;
	}

	// request the data for the next select. 
	// this is an asynchronized process
	// also used to store params
	frm.myAjax = new Ajax.Request(url,
	{
		method : 'get',
		onSuccess : function(transport)
		{
			findTyreSelectHandler(frm, select, transport);
		},
		/* just testing browser response with async */
		asynchronous : true,
		parameters : params
	});
}


/**
*/
function popupOpen()
{	
	document.getElementById('tyreSearch').style.display = "none";
	document.getElementById('tyreSearchInformationPopup').style.display = "block";
}


/**
*/
function popupClose()
{
	document.getElementById('tyreSearch').style.display = "block";
	document.getElementById('tyreSearchInformationPopup').style.display = "none";
}



/**
*/
function isEmailAddress(value)
{
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return filter.test(value);
}


/**
 * Returns the value of the attribute 'action' in the form element.
 * @return string
 */
function getFormAction(frm)
{
	var url = frm.getAttribute('action');
	// ie fix
	if(frm.attributes && frm.attributes.getNamedItem)
	{
		url = frm.attributes.getNamedItem('action').value;
	}
	return url;
}


if(!String.prototype.trim)
{
	String.prototype.trim = function()
	{
		return this.replace(/^\s+|\s+$/g, '');
	}
}

/**
* Removes leading and trailing whitespace
* @param str String
* @return String
*/
function trim(str)
{
	//return str.replace(/^\s+|\s+$/g, '');
	return str.trim();
}
