var minTimeCollection = 300; // 3h

function toggleDisclaimer()
{
	if($('#sendEmail').attr('checked'))
		$('#disclaimer').css('display', 'block');
	else
	{
		$('#disclaimer').css('display', 'none');
		$('#disclaimer input').each(function()
		{
			$(this).val('');
		});
	}
}

function checkEmail(emailString)
{
	var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
	var email = emailString;
	if($.trim(email) != '')
	{
		if (email.search(emailRegEx) == -1) {
			  return false;
		 }
	}
	return true;
}


function townTokenize(townSelect)
	{
		var form  = townSelect.form;
		var idx = townSelect.selectedIndex;
		var text = townSelect.options[idx].text;

		var cap = $.trim(text.substr(0,5));
		var town = $.trim(text.substring(6, (text.indexOf('(')-1)));
		var prov = $.trim(text.substring(text.indexOf('(')+1, text.indexOf(')')));
													  
		if(townSelect.name == "senderTownList")	
		{
			form.senderPostalCode.value = cap;
			form.senderTown.value = town;
			form.senderProvince.value = prov;
		}
		else if(townSelect.name == "receiverTownList")
		{
			form.receiverPostalCode.value = cap;
			form.receiverTown.value = town;
			form.receiverProvince.value = prov;
		}
 	}


function regenerateTime(dateSelector, timeSelector, selectString)
{
	$('input').removeClass('error');
	$('select').removeClass('error');
	
	var chk = '=';
	
	if(dateSelector.value != '')
	{
		//Split selected date
//		var dateSelected = convertDate(dateSelector.value);
//		index = today  - dateSelected;
		
		chk = checkDate(dateSelector.value);
	}
	
	// the current day
	if (chk == '=')
	{ 
		createTimeOptions(timeSelector,selectString,1,startHr,0,endHr,0);				
	}
	else 
	{
		createTimeOptions(timeSelector,selectString,0,startHr,0,endHr,0);
	}

	if(chk == '<')
	{
		dateSelector.focus();
		dateSelector.className = 'error';
		alert("La data del ritiro deve essere uguale o maggiore a quella odierna");	
		return;
	}
	
	var day = convertDate(dateSelector.value).getDay();
	
	
	if(day == 0 || day == 6)
	{
		dateSelector.focus();
		dateSelector.className = 'error';
		alert('La data del ritiro non pu\u00F2 essere di Sabato o di Domenica');	
	}
	
}


function populateTimeSelects()
{
	var form = document.bookingForm; 
	
	regenerateTime(form.collectionDate, form.availabilityTime, 'selezionare');

	createTimeOptions(form.priOpnTime,selectString,0,startHr,0,endHr,0);
	createTimeOptions(form.priCloTime,selectString,0,startHr,0,endHr,0);
	createTimeOptions(form.secOpnTime,selectString,0,startHr,0,endHr,0);
	createTimeOptions(form.secCloTime,selectString,0,startHr,0,endHr,0);	
}

function updateTimeSelects(obj1, obj2, obj3, obj4)
{
	if(obj1)
	{
		var nextStartValue = obj1.options[obj1.options.length - 1].value;
		
		if((obj1.selectedIndex + 1) < obj1.options.length)
		{
			nextStartValue = obj1.options[obj1.selectedIndex + 1].value;
			
			if((nextStartValue % 100) > 0)
				nextStartValue = parseInt(nextStartValue/100) + 0.5;
			else
				nextStartValue = parseInt(nextStartValue/100);
		}
			
		createTimeOptions(obj2,selectString,0,nextStartValue,0,endHr,0);
		createTimeOptions(obj3,selectString,0,nextStartValue,0,endHr,0);
		createTimeOptions(obj4,selectString,0,nextStartValue,0,endHr,0);
		return;
	}
	
	if(obj2)
	{
		var nextStartValue = obj2.options[obj2.options.length - 1].value;
		
		if((obj2.selectedIndex + 1) < obj2.options.length)
		{

			var nextStartValue = obj2.options[obj2.selectedIndex + 1].value;
			
			if((nextStartValue % 100) > 0)
				nextStartValue = parseInt(nextStartValue/100) + 0.5;
			else
				nextStartValue = parseInt(nextStartValue/100);
		}
		
		createTimeOptions(obj3,selectString,0,nextStartValue,0,endHr,0);
		createTimeOptions(obj4,selectString,0,nextStartValue,0,endHr,0);		
		return;
	}

	if(obj3)
	{
		var nextStartValue = obj3.options[obj3.options.length - 1].value;
		
		if((obj3.selectedIndex + 1) < obj3.options.length)
		{
			var nextStartValue = obj3.options[obj3.selectedIndex + 1].value;
			
			if((nextStartValue % 100) > 0)
				nextStartValue = parseInt(nextStartValue/100) + 0.5;
			else
				nextStartValue = parseInt(nextStartValue/100);
		}
			
		createTimeOptions(obj4,selectString,0,nextStartValue,0,endHr,0);		
		return;
	}
}

function setEnvironment(isInternational, payment)
{
	if(isInternational)
		showHidePaymentData('hide');
	else
		if(payment == 'W')
			showHidePaymentData('show');
		else
			showHidePaymentData('hide');
}


function showHidePaymentData(state)
{
	if(state == 'hide')	
		getObj('divPayment').style.display = 'none';
	else
		getObj('divPayment').style.display = 'block';
}

function resetFields(form)
{
	if(!confirm("Sei sicuro di voler cancellare tutti i campi?"))
		return;
	
	$('input').removeClass('error');
	$('select').removeClass('error');


	for(i=0; i < form.elements.length; i++)
	{
		if(form.elements[i].type == 'text')
			form.elements[i].value = "";
		if(form.elements[i].tagName == 'TEXTAREA')
			form.elements[i].value = "";
		if(form.elements[i].tagName == 'SELECT')
			form.elements[i].selectedIndex = 0;
	}
	if(getObj('sndTownList'))
		getObj('sndTownList').style.display = 'none';
		
	if(getObj('rcvTownList'))
		getObj('rcvTownList').style.display = 'none';
		
}

function submitTheForm()
{
	$('input').removeClass('error');
	$('select').removeClass('error');

	substringLimit('pickUpInstr', 80);
	
	var form = document.bookingForm;
	var isValid = true;
	var msg ="";

	$('input.required, select.required').each(function()
	{
		$(this).val($.trim($(this).val()));
		if($(this).val() == '')
		{
			(isValid)?($(this).focus()):('');
			
			$(this).addClass('error');
			msg = 'I campi evidenziati sono obbligatori';
			isValid = false;
		}
	});
	
	$('#disclaimer input').each(function()
	{
		$(this).val($.trim($(this).val()));
		if($('#sendEmail').attr('checked'))
		{
			if($(this).val() == '')
			{
				(isValid)?($(this).focus()):('');
				
				$(this).addClass('error');
				msg = 'I campi evidenziati sono obbligatori';
				isValid = false;
			}		
		}
	});	
	
	$('div[id=pkgSection]').find('input[name=pkgItemNo]').each(function()
	{
		isEmpty = true;		
		if($('input[name=envItemNo]').val() != '')
			isEmpty = false;
			
		if(isEmpty)
			if($(this).val() != '')
				isEmpty = false;	

	});	

	if(isEmpty)
	{
		if($('input[name=envItemNo]').val() == '')
			$('input[name=envItemNo]').addClass('error');
		
		$('div[id=pkgSection]').find('input[name=pkgItemNo][value=\'\']').addClass('error');

		(isValid)?($('input[name=envItemNo]').focus()):('');		
		msg = "I campi evidenziati sono obbligatori";
		isValid = false;
	}	

	var checkVolume = new Array();
	var totPkgSections = 0;
	var areDimsRequired = false;
	
	$('div[id=pkgSection]').each(function()
	{
		if($(this).find('input[name=pkgItemNo]').val() != '')
		{
			if($(this).find('input[name=pkgWeight]').val() == '')
			{
				(isValid)?($('input[name=envItemNo]').focus()):('');		
				msg = "I campi evidenziati sono obbligatori";
				$(this).find('input[name=pkgWeight]').addClass('error');
				isValid = false;
			}
			if($(this).find('select[name=pkgType]').val() == 'P')
				areDimsRequired = true;

			if(	$(this).find('input[name=pkgWidth]').val() != '' ||
				$(this).find('input[name=pkgHeight]').val() != '' ||
				$(this).find('input[name=pkgLength]').val() != '' ||
				areDimsRequired == true)
			{
				areDimsRequired = true;	
				
				if($(this).find('input[name=pkgWidth]').val() == '')
				{
					(isValid)?($('input[name=envItemNo]').focus()):('');
					$(this).find('input[name=pkgWidth]').addClass('error')				
					msg = "I campi evidenziati sono obbligatori";
					isValid = false;
				}
				if($(this).find('input[name=pkgHeight]').val() == '')
				{
					(isValid)?($('input[name=envItemNo]').focus()):('');
					$(this).find('input[name=pkgHeight]').addClass('error')				
					msg = "I campi evidenziati sono obbligatori";
					isValid = false;
				}
				if($(this).find('input[name=pkgLength]').val() == '')
				{
					(isValid)?($('input[name=envItemNo]').focus()):('');
					$(this).find('input[name=pkgLength]').addClass('error')				
					msg = "I campi evidenziati sono obbligatori";
					isValid = false;
				}
			
			}

			if($(this).children('input[name=pkgVolume]').val() != "")
				checkVolume[totPkgSections] = $(this).find('input[name=pkgVolume]').val();
			else
				$(this).find('input[name=pkgVolume]').addClass('error');
		
		}
		totPkgSections++;
	});

	if(checkVolume.length > 0 && checkVolume.length != totPkgSections)
	{
		(isValid)?($('input[name=envItemNo]').focus()):('');		
		msg = "I campi evidenziati sono obbligatori";
		isValid = false;
	}
	else
		$('input[name=pkgVolume]').removeClass('error');
	
	/**********************Peso buste***********************************/
	if($('input[name=envItemNo]').val() != '')
		if($('input[name=envWeight]').val() == '')
		{
			isValid = false;
			msg = "I campi evidenziati sono obbligatori";
			$('input[name=envWeight]').addClass('error');
			(isValid)?($('input[name=envWeight]').focus()):('');
		}
	
	
	if(form.isTpoint && form.isTpoint.value !='Y')
	{
		if(form.payment[0].checked && $('[name=destination]').get(0).checked)
		{

			if(trim($('#receiverTown').val()) == "")
		{
			if(isValid)
				$('#receiverTown').focus();

			msg = "I campi evidenziati sono obbligatori";
			$('#receiverTown').addClass('error');	
			isValid = false;			
		}

		if(isValid)
		{
		/*********************Check Vat Number ****************************************/
			var vatNumber = $('#vatNumber').val();
			if(vatNumber.length > 0)
			{
				if(vatNumber.length <= 11)
				{
					if(!ControllaPIVA(vatNumber))
					{
						if(isValid)
							$('#vatNumber').focus();

						msg = "Partita IVA Errata";
						$('#vatNumber').addClass('error');
						isValid = false;
					}
				}
				else
				{
					if(!ControllaCF(vatNumber))
					{
						if(isValid)
							$('#vatNumber').focus();

						msg = "Codice Fiscale Errato";
						$('#vatNumber').addClass('error');

						isValid = false;
					}
				
				}
				
			}
	}
/************************** check cod **************************************/
			var insurance = $('#insurance').val();
			var cod = $('#cod').val();
			insurance = insurance.replace(',','.');
			cod = cod.replace(',','.');
			if(parseFloat(cod) > 10000)
			{
				if(isValid)
				{
					$('#cod').focus();
					$('#cod').addClass('error');
					msg = "Il valore massimo del Contrassegno per le prenotazioni on-line \u00E8 di 10.000 Euro. Per Contrassegni di valore superiore contattare il Servizio Clienti 199.803.868.";	
				}
				isValid = false;			
			}

			if(parseFloat(insurance) > 500)
			{
				if(isValid)
				{
					$('#insurance').focus();
					$('#insurance').addClass('error');
					msg = "Il valore massimo dell'Assicurazione per le prenotazioni on-line \u00E8 di 500 Euro. Per assicurare merci per un valore superiore contattare il Servizio Clienti 199.803.868.";	
				}
				isValid = false;			
			}
		}	
		if(!form.agree.checked)
		{
			(isValid)?($('#agree').focus()):("");
			$('#alert').attr("src","/_img/ic_exception.gif");
			msg = "I campi evidenziati sono obbligatori";
			isValid = false;			
		
		}

	}

/***********************Check times*************************************************/

	var priOpnTime = $('#priOpnTime').val();
	var priCloTime = $('#priCloTime').val();
	var secOpnTime = $('#secOpnTime').val();
	var secCloTime = $('#secCloTime').val();

		if(((secOpnTime == '') && (secCloTime != '')) || ((secOpnTime != '') && (secCloTime == '')) )
		{
			if(isValid)
				{
					$('#secOpnTime').focus();
					$('#secOpnTime').addClass('error');
					$('#secCloTime').addClass('error');
					msg = "Entambi i campi devono essere valorizzati";	
				}
				isValid = false;			
		}

	var collectionTime = $('#availabilityTime').val();
	
	var morning = collectionTime >= priOpnTime && collectionTime < priCloTime;
	var afternoon =  collectionTime >= secOpnTime && collectionTime < secCloTime;

	if(!morning && !afternoon)
	{
			if(isValid)
				{
					$('#priOpnTime').focus();
					$('#priOpnTime').addClass('error');
					$('#priCloTime').addClass('error');
					$('#secOpnTime').addClass('error');
					$('#secCloTime').addClass('error');
					msg = "L'orario di disponibilit\u00E0 deve essere compreso tra quelli di apertura.";	
				}
				isValid = false;			
	}
	
		
	if(((parseFloat(secCloTime) - parseFloat(collectionTime)) < 300) || (secCloTime == ''))
	{
		if((parseFloat(priCloTime) - parseFloat(collectionTime)) < 300)
		{
				if(isValid)
				{
					$('#priOpnTime').focus();
					$('#priOpnTime').addClass('error');
					$('#priCloTime').addClass('error');
					$('#secOpnTime').addClass('error');
					$('#secCloTime').addClass('error');
					$('#availabilityTime').addClass('error');
					msg = "Per poter effettuare il ritiro sono necessarie almeno 3 ore tra l'orario di disponibilit\u00E0 della merce e l'orario di chiusura.";	
				}
				isValid = false;
		}
	}
	
	if(isValid)
	{
		if(!checkEmail($('#senderEmail').val()))
		{
			msg = "Formato email non valido";
			$('#senderEmail').addClass('error');
			(isValid)?($('#senderEmail').focus()):('');
			isValid = false;
		}
		
		if(!checkEmail($('#ordererEmail').val()))
		{
			msg = "Formato email non valido";
			$('#ordererEmail').addClass('error');
			(isValid)?($('#ordererEmail').focus()):('');
			isValid = false;
		}
	}
	
	if(!isValid)
	{
		alert(msg);
		return false;
	}

	document.bookingForm.submit();
}

function checkBookingAvailability()
{
				countryIsValid = true;

				if($('#colCountry').val() == '')
					return;

				var cty = $('#colCountry').val();
				$.blockUI('<img src="/_img/ic_wait.gif" />&#160; Verifica disponibilit&#224; servizio...');
				$.post
				(
					'/booking/InternationalBooking.do',
					{
						actionType: 'check',
						colCountry: $('#colCountry').val(),
						yourLoc: 'IT',
						international: 'Y',
						cmd: 'v'
					},
					function(data){
						if(data == 'unavailable')
						{
							$.blockUI('Non &#232; possibile effettuare prenotazioni di ritiri on-line in questo paese.<br/>Contatta il nostro <span class="orange"><b>Servizio Clienti 199.803.868</b></span><br/><a href="#" onclick="$.unblockUI()">chiudi</a>');
							countryIsValid = false;
						}
						else
							$.unblockUI();

						togglePostCode(cty, 'oPostcode');
						checkedCountry = $('#colCountry').val();
						return;
					});
}


/*
function initMask()
{
	 $.mask.fixedChars = '[():/]';  
	 $.mask.rules = $.extend($.mask.rules,
	 {
		't': /[0-9a-zA-ZçÇáàãéèíìóòõúùü&\s\.,\'\-_]/,
		'l': /[a-zA-ZçÇáàãéèíìóòõúùü\s\.,\']/,
		'm': /[0-9a-zA-Z\.@&\-_]/,
		'c': /[0-9a-zA-Z]/
	 
	 });
	 
	$('#companyName').setMask({mask:'tttttttttttttttttttttttttttttttttttttttttttttttttt'});
	$('#address').setMask({mask:'tttttttttttttttttttttttttttttttttttttttttttttttttt'});
	$('#senderPostalCode').setMask({mask:'99999'});
	$('#senderTown').setMask({mask:'llllllllllllllllllllllllllllllllllllllllllllllllll'});
	$('#senderProvince').setMask({mask:'aa'});
	$('#contactName').setMask({mask:'lllllllllllllllllllllllll'});
	$('#phoneID1').setMask({mask:'99999'});
	$('#phoneID2').setMask({mask:'999999999999999'});
	$('#faxID1').setMask({mask:'99999'});
	$('#faxID2').setMask({mask:'999999999999999'});
	$('#senderEmail').setMask({mask:'mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm'});
	$('#ordererEmail').setMask({mask:'mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm'});
	$('#vatNumber').setMask({mask:'cccccccccccccccc'});
	$('#receiverPostalCode').setMask({mask:'99999'});
	$('#receiverTown').setMask({mask:'llllllllllllllllllllllllllllllllllllllllllllllllll'});
	$('#receiverProvince').setMask({mask:'aa'});
	
}
*/
function initMask()
{
}
