var year = 2003;

//------------------------------------------------------------------------------
// Returns number of days between two dates given by day and month number. 
// Note: It does not calculate february on leap year correct, which is ok for me, since
// I'm using it only for periods from June to September ;-) Date1 must be before than date2! 
//------------------------------------------------------------------------------
function daysbetween(day1, month1, day2, month2)
{
	var monthDayNum = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	var num = day2 - day1;
	for (var i = month1; i < month2; i++)
		num += monthDayNum[i - 1];
	return num;
}

//------------------------------------------------------------------------------
// Compares two dates given by day and month number.
// Return values: -1 when date1 < date2, 0 when date1 == date2, 1 when date1 > date2
//------------------------------------------------------------------------------
function comparedate(day1, month1, day2, month2)
{
	var date1 = month1 * 32 + day1;
	var date2 = month2 * 32 + day2;
	return (date1 < date2 ? -1 : (date1 > date2 ? 1 : 0));
}


//------------------------------------------------------------------------------
// Function returns apartment price for period given by 'sDay', 'sMonth' (start date)
// and 'eDay', 'eMonth' (end date) for 'persons' persons. Number of persons also
// determines for which apartment price is being calculated.
// Note: calculatePrice() uses arrays defined in prices.js
//------------------------------------------------------------------------------
function calculatePrice(sDay, sMonth, eDay, eMonth, persons)
{
	// For saving number of days that falls within each period
	var perioddays = [0, 0, 0];

	// Temp variables
	var day1, day2, month1, month2;

	// Count days in each of the three periods (loop has 5 steps since periods 3 and 2 have two parts)
	for (var i = 0; i < 5; i++)
	{
		// Check if periods intersects
		if (comparedate(eDay, eMonth, periodlist[i].sday, periodlist[i].smonth) > 0 && comparedate(sDay, sMonth, periodlist[i].eday, periodlist[i].emonth) < 0)
		{
			if (comparedate(sDay, sMonth, periodlist[i].sday, periodlist[i].smonth) > 0)
			{
				day1 = sDay;
				month1 = sMonth;
			}
			else
			{
				day1 = periodlist[i].sday;
				month1 = periodlist[i].smonth;
			}

			if (comparedate(eDay, eMonth, periodlist[i].eday, periodlist[i].emonth) <= 0)
			{
				day2 = eDay;
				month2 = eMonth;
			}
			else
			{
				day2 = periodlist[i].eday;
				month2 = periodlist[i].emonth;
			}

			perioddays[periodlist[i].period - 1] += daysbetween(day1, month1, day2, month2);
		}
	}
	
	var apartmentprice = 0;

	var apartment;
	if (persons > 5)
	{
		// Apartment A for 6-8 persons
		apartment = 0;
		persons -= 6;  // because this will be used as index in an array
	}
	else
	{
		// Apartment A for 4-5 persons
		apartment = 1;
		persons -= 4;
	}
	
	// Price calculation
	for (var i = 0; i < 3; i++)
		apartmentprice += perioddays[i] * pricelist[apartment][i][persons];

	return apartmentprice;
}

//------------------------------------------------------------------------------
// Reads period information from periodlist[] in prices.js and returns
// string containing formatted period dates.
//------------------------------------------------------------------------------
function formatPeriodString(index)
{
	var result = "";
	result += (periodlist[index].sday < 10 ? '0' : '') + periodlist[index].sday + '.';
	result += (periodlist[index].smonth < 10 ? '0' : '') + periodlist[index].smonth + '.-';
	result += ((periodlist[index].eday - 1) < 10 ? '0' : '') + (periodlist[index].eday-1) + '.';
	result += (periodlist[index].emonth < 10 ? '0' : '') + periodlist[index].emonth + '.';
	return result;
	
}

//------------------------------------------------------------------------------
// Returns HTML-formatted string containing dates for selected period.
//------------------------------------------------------------------------------
function readPeriod(period)
{
	var periodString;
	switch (period)
	{
		case 1:
			periodString = formatPeriodString(2)
		break;
		case 2:
			periodString = formatPeriodString(1);
			periodString += "<br>";
			periodString += formatPeriodString(3);
		break;
		case 3:
			periodString = formatPeriodString(0);
			periodString += "<br>";
			periodString += formatPeriodString(4);
		break;
	}
	return periodString;
}


//------------------------------------------------------------------------------
// Returns ordinal number suffix for number given by 'num' (for num < 100)
//------------------------------------------------------------------------------
function ordinalSuffix(num)
{
	var suffixes = ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"];
	return ((num > 10 && num < 20) ? "th" : suffixes[num % 10]);
}

//------------------------------------------------------------------------------
// This function process onChange events of elements in any form that
// calculate apartment price depending on period and number of persons. Such
// form have these elements in common:
// - cMonth, cDay (starting date combos)
// - cDuration (duration of period combo), cDurationType ('weeks' or 'days')
// - cPersons (num of persons combo)
// There are also several named anchors to summarize results:
// - aSMonth, aSDay (start date)
// - aEMonth, aEDay (calculated end date)
// - aPersons (num of persons)
// - aPrice, aPricePerPerson (calculated price)
//------------------------------------------------------------------------------
var sDay, eDay;
var sMonth, eMonth;
var duration;
var persons;
var price;
var pricePerPerson;

function updateReservationForm()
{
	var months = ["June", "July", "August", "September", "October", "November"];
	var monthDays = [30, 31, 31, 30, 31, 30];
	
	sDay = document.forms.reservationinfo.cDay.selectedIndex + 1;
	sMonth = document.forms.reservationinfo.cMonth.selectedIndex + 6;
	persons = document.forms.reservationinfo.cPersons.options[document.forms.reservationinfo.cPersons.selectedIndex].text; // E jebo te Netscape
	
	// First make sure that June and September don't have 31st day selected (they have 30 days only)
	if (sDay == 31 && (sMonth == 6 || sMonth == 9))
	{
		document.forms.reservationinfo.cDay.selectedIndex = 29; 
		sDay--;
	}
	
	duration = document.forms.reservationinfo.cDuration.selectedIndex + 1;
	var durationType = document.forms.reservationinfo.cDurationType.options[document.forms.reservationinfo.cDurationType.selectedIndex].text;  // E jebo te Netscape!!
	if (durationType == "week(s)")
	{
		// Limit duration to 5 weeks only
		if (duration > 5)
		{
			duration = 5;
			document.forms.reservationinfo.cDuration.selectedIndex = 4;
		}

		// Convert weeks into days
		duration *= 7;
	}

	// Calculate end date (using start date and duration)
	eDay = sDay + duration;
	eMonth = sMonth;
	while (eDay > monthDays[eMonth - 6])
		eDay -= monthDays[eMonth++ - 6];

	// Check if reservation exceeds October 1st
	if (comparedate(eDay, eMonth, 1, 10) == 1)
	{
		// Limit reservation duration so it does not exceeds October 1st
		duration = daysbetween(sDay, sMonth, 1, 10);
		document.forms.reservationinfo.cDuration.selectedIndex = duration - 1;
		// Select 'days' for duration type
		document.forms.reservationinfo.cDurationType.selectedIndex = 0;
		eDay = 1;
		eMonth = 10;
	}


	// Calculate price for apartment
	price = calculatePrice(sDay, sMonth, eDay, eMonth, persons);

	// Calculate price per person per day
	pricePerPerson = price / (duration * persons);
	// Get 2-digit precision only
	pricePerPerson *= 100;
	pricePerPerson = Math.ceil(pricePerPerson);
	pricePerPerson /= 100;
	
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		// named anchors can be accessed without document.all[] even when inside form??
		// maybe it would be better using 'this' as parameter for this function??
		aSMonth.innerText = months[sMonth - 6];
		aSDay.innerText = sDay + ordinalSuffix(sDay); 
		aPersons.innerText = persons;

		aEMonth.innerText = months[eMonth - 6];
		aEDay.innerText = eDay + ordinalSuffix(eDay);
	
		aPrice.innerText = price;
		aPricePerPerson.innerText = pricePerPerson;
	}
	else
	{
		document.forms.reservationinfo.txtPrice.value = price;
	}
}


//------------------------------------------------------------------------------
// Function will verify that requested period is available and compose mail.
//------------------------------------------------------------------------------
function verifyReservation(form)
{
	updateReservationForm();
	
	var monthDayNum = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

	var month = sMonth - 1;
	var day = sDay;
	var reserved = false;
	var apartment = persons > 5 ? 1 : 2;
	
	// Check if apartment is free during requested period
	for (var i = 0 ; i < duration; i++)
	{
		if (eval("month" + month + year + apartment)[day-1] == 1)
		{
			reserved = true;
			break;
		}
		day++;
		if (day > monthDayNum[month])
		{
			day = 1;
			month++;
		}
	}
	
	if (reserved)	
	{
		alert("Sorry, this apartment is not available during requested period.\nPlease check reservations calendar for this apartment.");
		return false;
	}

	// Compose mail body that this form will send.
	form.mailBody.value = "\n";
	form.mailBody.value += "This mail is reservation request you made for apartments Milina. \n\n";
	form.mailBody.value += "Reservation period : " + sDay + "." + sMonth + ". - " + eDay + "." + eMonth + ". " + year + ". (" + duration + " days)\n";
	form.mailBody.value += "Number of persons  : " + persons + "\n";
	form.mailBody.value += "Apartment          : " + (apartment == 1 ? "A" : "B") + "\n";
	form.mailBody.value += "Calculated price   : " + price + " EUR (" + pricePerPerson + " EUR/person/night)\n";
	form.mailBody.value += "Contact person     : " + document.forms.reservationinfo.personName.value + "\n";
	form.mailBody.value += "Country            : " + document.forms.reservationinfo.country.options[document.forms.reservationinfo.country.selectedIndex].text + "\n";

	return true;
	
}

// Failed attempt to send mail by changing location. It seems impossible to put newline chars in message body...
// document.location = "mailto:imilina@foi.hr?subject=rezervacija&body=messagebody";
