//	2004-Apr-05
//	Florin Zagan
//	florin.zagan@connex.ro
//	fzagan@hotmail.com

//	refresh apartment pic that has to be displayed. o execut la onLoad
function refreshPic()
{	with(document)
	{	s = forma.select_apartment.selectedIndex - 1;
		if(s < 0)
			pic_apartment.src = 'images/blank.gif';
		else
			pic_apartment.src = imageSource[s].src;
	}
}

//se declanseaza la selectarea unui apartment in forma.select_apartment
function update_apDetails()
{	with(document)
	{	s = forma.select_apartment.selectedIndex - 1;
		if(s < 0)
		{	pic_apartment.src = 'images/blank.gif';
			forma.text_price_normal.value = '';
			forma.text_price_7.value = '';
			forma.text_price_14.value = '';
			forma.text_price_30.value = '';
			forma.text_stay_cost.value = '';
		}
		else
		{	pic_apartment.src = imageSource[s].src;
			forma.text_price_normal.value = forma_hidden.elements[s].value;
			forma.text_price_7.value = forma_hidden.elements[s].value * (1 - 10 / 100);
			forma.text_price_14.value = forma_hidden.elements[s].value * (1 - 15 / 100);
			forma.text_price_30.value = forma_hidden.elements[s].value * (1 - 20 / 100);
			if(forma.text_stay_duration.value != '' && !isNaN(forma.text_stay_duration.value) && forma.text_stay_duration.value >= 1)
				forma.text_stay_cost.value = calculateCost(forma.text_stay_duration.value);
			else forma.text_stay_cost.value = '';
		}
		forma.text_name.focus();
		forma.text_name.blur();
		forma.text_name.select();
	}
}


function calculateCost(diff)
{	if(diff <= 7)
		return (document.forma.text_price_normal.value * diff);
	else if(diff > 7 && diff <= 14)
		return (document.forma.text_price_7.value * diff);
	else if(diff > 14 && diff <= 30)
		return (document.forma.text_price_14.value * diff);
	else if(diff > 30)
		return (document.forma.text_price_30.value * diff);
}


var monthLength = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

// functie folosita de checkDateElements(name)
function checkDate(year, month, day)
{	var past = 0;
	var diff = 0;
	var now = new Date();
	now = now.getTime(); //NN3

	var dateToCheck = new Date();
	dateToCheck.setFullYear(year);
	dateToCheck.setMonth(month-1);
	dateToCheck.setDate(day);
	var checkDate = dateToCheck.getTime();

	diff = Math.round((checkDate - now) / (1000 * 60 * 60 * 24));
	
	if(diff < 0)
		past = 1;
	return past;
}
function constructTimestamp(name)	// fctie folosita de compareDates()
{	var past = 0;
	var x = document.forma.elements;
	var year = parseInt(x[name+ '_year'].options[x[name+ '_year'].selectedIndex].value);
	var month = parseInt(x[name+ '_month'].options[x[name+ '_month'].selectedIndex].value);
	var day = x[name+ '_day'].value;
	
	past = checkDate(year, month, day);
	if(past == 0)
	{	timestamp = new Date();
		timestamp.setFullYear(year);
		timestamp.setMonth(month-1);
		timestamp.setDate(day);
		timestamp = timestamp.getTime();
		return timestamp;
	}
	else
		return false;
}
// fctie apelata onSubmit, parte din form validation. 
//in mod normal, validarea datelor se petrece cind se introduce data in form, dar daca userul nu modifica, ci alege din valori trecute datorita capabilitatii window de a lista valorile introduse in trecut, 
//nu se mai declanseaza fctia checkDateElements, asa cum ar fi normal, asa ca fctia compareDates() e fctie de backUp
function compareDates()
{	var message = '';
	var arrival_timestamp = constructTimestamp('arrival');
	var departure_timestamp = constructTimestamp('departure');
	
	if(arrival_timestamp == false)
		message += ' Invalid arrival date.';
	if(departure_timestamp == false)
		message += ' Invalid departure date. ';
	if(message == '')
	{	diff = ((departure_timestamp - arrival_timestamp) / (1000 * 60 * 60 * 24));
		if(diff < 1)
			message += ' you set your departure either before your arrival or on the same date. ';
	}
	return message;
}
function checkDateElements(name, alerta)
{	message = '';

	var x = document.forma.elements;
	var apartment = x['select_apartment'].options[x['select_apartment'].selectedIndex].value;
	var year = parseInt(x[name+ "_year"].options[x[name+ "_year"].selectedIndex].value);
	var month = parseInt(x[name+ "_month"].options[x[name+ "_month"].selectedIndex].value);
	var month_name = x[name+ "_month"].options[x[name+ "_month"].selectedIndex].text;
	var day = x[name+ "_day"].value;
	
	var now = new Date();
		
	//	DAY CHECK           --------------------
	if(day != '')
	{	if((isNaN(day)) || (day < 1) || (day > monthLength[month - 1]))
		{	if(name == 'departure')
			{	message += ' Warning: invalid day. I changed it to one day after tomorrow. Please feel free to change it.';
				day = x[name+ '_day'].value = now.getDate() + 2;
			}
			if(name == 'arrival')
			{	message += ' Warning: invalid day. I changed it to tomorrow\'s day. Please feel free to change it.';
				day = x[name+ '_day'].value = now.getDate() + 1;
			}
		}
	}
	if(day == '')
	{	if(name == 'arrival')
			x[name+ '_date'].value = '';
		if(name == 'departure')
			x[name+ '_date'].value = '';
	}
	
	//	MONTH CHECK           ------------------------------
	// provided i have selected the current year, i need to take care of which month i also select, in order not to pick a month in the past. for a year selected in the future, i don't care about month
	if(month != '')
	{	if(year != '')
			if(now.getFullYear() >= year)
				if(now.getMonth() + 1 > month)
				{	if((now.getMonth() + 1) > 12)
					{	month = x[name+ '_month'].value = 1;
						year = x[name+ '_year'].value = now.getFullYear() + 1;
					}
					else
						month = x[name+ '_month'].value = now.getMonth() + 1;
					message += ' \nWarning: \''+ year+ '-'+ month_name+ '\' is a date in the past. I changed month to current. Please feel free to change it.\n';
					x[name+ '_month'].focus();
				}
		else
		{	if(name == 'arrival')
				x[name+ '_date'].value = '';
			if(name == 'departure')
				x[name+ '_date'].value = '';
		}
	}
	if(month == '')
	{	if(name == 'arrival')
			x[name+ '_date'].value = '';
		if(name == 'departure')
			x[name+ '_date'].value = '';
	}

	
	//	YEAR CHECK                   -----------------------------------
	if(year != '')
	{	//anii bisecti au 29 de zile (ii identific pt ca se divid la 4)
		if (year / 4 == parseInt(year / 4))
			monthLength[1] = 29;
		else
			monthLength[1] = 28;
		if(month != '')
			if(now.getFullYear() >= year)	// current year selected by user
				if(now.getMonth() + 1 > month)	// user chooses a month earlier to the current month, which is not good (this is bad only if user selected current year also, see line above)
				{	if((now.getMonth() + 1) > 12)		// va trebui sa incrementez luna aleasa de user, dar sa fiu atent sa nu ajung la 13, pt ca max e 12
					{	month = x[name+ '_month'].value = 1;
						year = x[name+ '_year'].value = now.getFullYear() + 1;
					}
					else
						month = x[name+ '_month'].value = now.getMonth() + 1;
					message += ' \nWarning: \''+ year+ '-'+ month_name+ '\' is a date in the past. I changed month to current. Please feel free to change it.\n';
					x[name+ '_month'].focus();
				}
		else
		{	if(name == 'arrival')
				x[name+ '_date'].value = '';
			if(name == 'departure')
				x[name+ '_date'].value = '';
		}
	}
	if(year == '')
	{	if(name == 'arrival')
			x[name+ '_date'].value = '';
		if(name == 'departure')
			x[name+ '_date'].value = '';
	}
	
	
	//	FULL DATE CHECK                    -------------------------------------
	if(day != '' && month != '' && year != '')
	{	past = checkDate(year, month, day);
		if(past == 1)	// user chose a date in the past, then I modify it to be over the current
		{	if(name == 'departure')
			{	message += ' \nWarning: you set your date in the past. I changed it to one day after tomorrow. Please feel free to change it.\n';
				if(now.getDate() + 2 > monthLength[month - 1])
				{	day = x[name+ '_day'].value = 1;
					if((now.getMonth() + 2) > 12)
					{	month = x[name+ '_month'].value = 1;
						year = x[name+ '_year'].value = now.getFullYear() + 1;
					}
					else
						month = x[name+ '_month'].value = now.getMonth() + 2;
				}	
				else
					day = x[name+ '_day'].value = now.getDate() + 2;
			}
			if(name == 'arrival')
			{	message += ' \nWarning: you set your date in the past. I changed it to tomorrow\'s date. Please feel free to change it.\n';
				if(now.getDate() + 1 > monthLength[month - 1])
				{	day = x[name+ '_day'].value = 1;
					if((now.getMonth() + 2) > 12)
					{	month = x[name+ '_month'].value = 1;
						year = x[name+ '_year'].value = now.getFullYear() + 1;
					}
					else
						month = x[name+ '_month'].value = now.getMonth() + 2;
				}
				else
					day = x[name+ '_day'].value = now.getDate() + 1;
			}
		}
		
		if(!(isNaN(day)) && (day >= 1) && (day <= monthLength[month - 1]))
		{	hidden = new Date();
			
			// daca nu folosesc if aici, se calculeaza ambele hidden elements, si arrival_date si departure_date, chiar daca nu sint introduse elementele de data, le declanseazacealalta data
			if(name == 'arrival')
			{	hidden.setFullYear(year);
				hidden.setMonth(month);
				hidden.setDate(day);
				hidden_date = hidden.getTime();
				x[name+ '_date'].value = hidden_date;	// name poate fi doar 'arrival' sau 'departure'
			}
			if(name == 'departure')
			{	hidden.setFullYear(year);
				hidden.setMonth(month);
				hidden.setDate(day);
				hidden_date = hidden.getTime();
				x[name+ '_date'].value = hidden_date;	// name poate fi doar 'arrival' sau 'departure'
			}
			
			if(x['arrival_date'].value != '' && x['departure_date'].value != '' && !isNaN(x['arrival_date'].value) && !isNaN(x['departure_date'].value))
			{	diff = Math.round((x['departure_date'].value - x['arrival_date'].value) / (1000 * 60 * 60 * 24));
				if(diff <= 0 )
				{	message += ' Warning: you set your departure date before the arrival or identical. Please make the correction.';
					x['text_stay_duration'].value = '';
					x['text_stay_cost'].value = '';
				}
				else
				{	x['text_stay_duration'].value = diff;
					if(apartment != '')
						x['text_stay_cost'].value = calculateCost(diff);
					else
						x['text_stay_cost'].value = '';
				}
			}
			else
			{	x['text_stay_duration'].value = '';
				x['text_stay_cost'].value = '';
			}
		}
		else
		{	x['text_stay_duration'].value = '';
			x['text_stay_cost'].value = '';
		}
	}
	else
	{	x['text_stay_duration'].value = '';
		x['text_stay_cost'].value = '';
		if(name == 'arrival')
			x[name+ '_date'].value = '';
		if(name == 'departure')
			x[name+ '_date'].value = '';
	}
	
	if(message != '')
		if(alerta == 1) alert(message);
}


function checkEmail(alerta)
{	var emailStr = document.forma.text_email.value;						//	email entered into the text field
	var emailPat = /^(.+)@(.+)$/;									//	the entered e-mail address fits the user@domain format.  It also is used to separate the username from the domain.
	var specialChars ="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";							//	string represents the pattern for matching all special chars that we don't want to allow in the address. These characters include ( ) < > @ , ; : \ " . [ ] 
	var validChars = "\[^\\s" + specialChars + "\]";						//	string represents the range of characters allowed in a username or domainname.  It really states which chars aren't allowed.
	var quotedUser = "(\"[^\"]*\")";									//	pattern applies if the "user" is a quoted string (in which case, there are no rules about which characters are allowed and which aren't).  E.g. "jiminy cricket"@disney.com
	var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;	//	pattern applies for domains that are IP addresses, rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal e-mail address. NOTE: The square brackets are required.
	var atom = validChars + '+';										//	string represents an atom (basically a series of non-special characters.)
	var word = "(" + atom + "|" + quotedUser + ")";						//	string represents one word in the typical username. For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string.
	var userPat = new RegExp("^" + word + "(\\." + word + ")*$");				//	patern describes the structure of the user
	var domainPat = new RegExp("^" + atom + "(\\." + atom +")*$");				//	pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above.

	if (emailStr == '')
	{	if(alerta == 1) alert('Please enter your email.\n');
		return false;
	}
	// Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze.
	var matchArray = emailStr.match(emailPat);
	if (matchArray == null) 
	{	if(alerta == 1) alert("Email address seems incorrect (check @ and .'s)\n");
		return false;
	}
	
	var user = matchArray[1];
	var domain = matchArray[2];

	// See if "user" is valid 
	if (user.match(userPat) == null) 
	{	if(alerta == 1) alert("The username in the email doesn't seem to be valid.\n");
		return false;
	}
	// if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid.
	var IPArray = domain.match(ipDomainPat);
	if (IPArray != null) 
		for (var i=1; i<=4; i++) 
			if (IPArray[i] > 255) 
			{	if(alerta == 1) alert("Destination IP address in the email is invalid!\n");
				return false;
			}
	// Domain is symbolic name
	var domainArray = domain.match(domainPat);
	if (domainArray == null) 
	{	if(alerta == 1) alert("The domain name in the email doesn't seem to be valid.\n");
		return false;
	}

	// domain name seems valid, but now make sure that it ends in a three-letter word (like com, edu, gov) or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country.

	// Now we need to break up the domain to get a count of how many atoms it consists of.
	var atomPat = new RegExp(atom, "g");
	var domArr = domain.match(atomPat);
	var len = domArr.length;
	if (domArr[domArr.length - 1].length < 2 || domArr[domArr.length - 1].length > 3) 
	{	if(alerta == 1) alert("The email address must end in a three-letter domain, or two letter country.\n");
		return false;
	}

	// Make sure there's a host name preceding the domain.
	if (len < 2) 
	{	if(alerta == 1) alert("This email address is missing a hostname!\n");
		return false;
	}

	// If we've gotten this far, everything's valid!
	return true;
}


function checkFlight(alerta)
{	var message = '';
	var notgood = '';
	var notGoodChars = "\`~!@#$%^&*+=/?[]{}()<>|\\,.;:\"";
	theNumber = document.forma.text_flight_number.value;
	
	if(theNumber == '')
		message += 'Please enter your flight number.\n';
	else
	{	for(i = 0; i <= theNumber.length - 1; i++)
			if(notGoodChars.indexOf(theNumber.charAt(i)) != -1) 
				notgood += theNumber.charAt(i);
		if(notgood != '')
			message += 'Warning: some characters in the flight number field not allowed:\n'+ notgood+ '\n';
		if(theNumber.length > 0 && theNumber.length < 6)
			message += 'Warning: too short a flight number.\n';
	}
	
	if(message != '')
	{	if(alerta == 1) alert(message);
		return false;
	}
	else
		return true;
}


function checkPhone(alerta)
{	var message = '';
	var notgood = '';
	var goodChars = "0123456789()-+ ";
	theNumber = document.forma.text_phone.value;
	
	if(theNumber == '')
		message += 'Please enter your phone number.\n';
	else
	{	for(i = 0; i <= theNumber.length - 1; i++)
			if(goodChars.indexOf(theNumber.charAt(i)) == -1) 
				notgood += theNumber.charAt(i);
		if(notgood != '')
			message += 'Warning: some characters in the phone number field not allowed:\n'+ notgood+ '\n';
		if(theNumber.length > 0 && theNumber.length < 10)
			message += 'Warning: too short a phone number.\n';
	}
	
	if(message != '')
	{	if(alerta == 1) alert(message);
		return false;
	}
	else
		return true;
}


function checkText(name, alerta)
{	var message = '';
	var notgood = '';
	var notGoodChars = "\`~!@#$%^*+=/?[]{}()<>|\\,.;:0\"123456789";
	var x = document.forma.elements;
	var theNumber = x['text_'+ name].value;
	
	if(theNumber == '')
		message += 'Please enter a name.\n';
	else
	{	for(i = 0; i <= theNumber.length - 1; i++)
			if(notGoodChars.indexOf(theNumber.charAt(i)) != -1) 
				notgood += theNumber.charAt(i);
		if(notgood != '')
			message += 'Warning: some characters in the '+ name+ ' field not allowed:\n'+ notgood+ '\n';
		if(theNumber.length > 0 && theNumber.length < 3)
			message += 'Warning: too short a name.\n';
	}
	
	if(message != '')
	{	if(alerta == 1) alert(message);
		return false;
	}
	else
		return true;
}

function checkLength(text, len)
{	if (text.length > len)
	{	message += ' text too long. Must be '+ len+ ' characters or less.\n';
		return false;
	}
	return true; 
}

/*
function calculateLengthTextarea()
{	while(forma.textarea_length.value > 0)
		forma.textarea_length.value = (forma.comments_len.value - forma.textarea_comments.value.length);
}
*/
function processOrder()
{	var message = '';
	var x = document.forma.elements;
	
	if(x['select_apartment'].options[x['select_apartment'].selectedIndex].value == '')
		message += 'Which apartment would you like to book?\n';
	
	if(x['text_name'].value == '')
		message += 'Please enter your name.\n';
	else if(checkText('name', 0) == false)
		message += 'Please review the name you entered.\n';
	
	if(x['select_country'].value == '') 
		message += 'Please select country.\n';
	
	if(x['text_town'].value == '')
		message += 'Please enter town.\n';
	else if(checkText('town', 0) == false)
		message += 'Please review the name of the town you entered.\n';
	
	if(x['text_phone'].value == '')
		message += 'Please enter your phone number.\n';
	else if(checkPhone(0) == false)
		message += 'Please review the phone number you entered.\n';
	
	if(x['text_email'].value == '')
		message += 'Please enter your email.\n';
	else if(checkEmail(0) == false)
		message += 'Please review the email address you entered.\n';
	
	date_complete = 1;
	datesAreWrong = '';
	if(x['arrival_year'].options[x['arrival_year'].selectedIndex].value == '' || x['arrival_month'].options[x['arrival_month'].selectedIndex].value == '' || x['arrival_day'].value == '')
	{	message += 'Please enter your arrival date.\n';
		date_complete = 0;
	}
	if(x['departure_year'].options[x['departure_year'].selectedIndex].value == '' || x['departure_month'].options[x['departure_month'].selectedIndex].value == '' || x['departure_day'].value == '')
	{	message += 'Please enter your departure date.\n';
		date_complete = 0;
	}
	if(date_complete == 1)
	{	datesAreWrong = compareDates();
		if(datesAreWrong != '')
			message += 'Please review your dates: '+ datesAreWrong+ '\n';
	}
	
	if(x['select_adults'].options[x['select_adults'].selectedIndex].value == '')
		message += 'Please tell us the number of adults.\n';
	
	if(x['checkbox_airport_transfer'].checked == true)
	{	if(x['select_airport'].options[x['select_airport'].selectedIndex].value == '')
			message += 'Please select the airport you\'re landing.\n';
		
		if(x['text_flight_number'].value == '')
			message += 'Please enter your flight code.\n';
		else if(checkFlight(0) == false)
			message += 'Please review the flight number you entered.\n';
		
		if(x['select_arrival_hour'].options[x['select_arrival_hour'].selectedIndex].value == '' || x['select_arrival_minutes'].options[x['select_arrival_minutes'].selectedIndex].value == '')
			message += 'Please enter your arrival time.\n';
	}
	
	if(x['textarea_comments'].value != '')
		if(checkLength(x['textarea_comments'].value, x['comments_length'].value) == false)
			message += 'Please shorten the text in the comments field.\n';
	
	
	if(message != '')
	{	alert('In order to be able to submit your data: \n\n'+ message);
		return false;
	}

	return true;

}


