// contactus.js
//
// browser sensing and formatMoney() modified or taken from David Regier, regier@maui.net
// Geoff did the rest of this messy code
//

netscape_string = "Netscape";
msie_string = "Microsoft Internet Explorer";

browser_name = navigator.appName;
browser_ver = parseInt(navigator.appVersion);

if(browser_name == netscape_string && browser_ver >=4)
	version = "n4";
else if(browser_name == netscape_string && browser_ver == 3)
	version = "n3";
else if(browser_name == netscape_string && browser_ver == 2)
	version = "n2";
else if(browser_name == msie_string && browser_ver >= 3)
	version = "e4";
else if(browser_name == msie_string && browser_ver == 2)
	version = "e3";

var capable = (version == "e4" || version == "n4") ? true : false;


var email_field_clicked = 0;

function emailReminder()
{
	if(version != "n2")
	{
		if(!email_field_clicked)
		{
			alert("Please make sure you enter a valid email address. Thank you!");
			email_field_clicked = 1;
		}
	}
}

function clearFields()
{
	if(!capable)
	{
		alert("We're detected that your browser may not be able to clear the form correctly.");
	}

	document.res_form.guest_name.value = document.res_form.guest_name.defaultValue;
	document.res_form.street_address.value = document.res_form.street_address.defaultValue;
	document.res_form.city.value = document.res_form.city.defaultValue;
	document.res_form.state_prov.value = document.res_form.state_prov.defaultValue;
	document.res_form.postal_code.value = document.res_form.postal_code.defaultValue;
	document.res_form.country.value = document.res_form.country.defaultValue;
	document.res_form.email.value = document.res_form.email.defaultValue;
	document.res_form.home_phone.value = document.res_form.home_phone.defaultValue;
	document.res_form.work_phone.value = document.res_form.work_phone.defaultValue;
	document.res_form.fax_num.value = document.res_form.fax_num.defaultValue;
	document.res_form.num_guests.selectedIndex = 0;

	document.res_form.costdisplay.value = 'Click "Check Cost" below for a price quote\n';

	document.res_form.comments.value = document.res_form.comments.defaultValue;

	setDates();
}

function setDates()
{
	setPulldowns(document.res_form.arriv_month, document.res_form.arriv_day, document.res_form.arriv_year);
	setPulldowns(document.res_form.depart_month, document.res_form.depart_day, document.res_form.depart_year);

	if(capable)
	{
		var date = new Date();
		var current_month = date.getMonth() + 1;
		var current_day = date.getDate();

		var unformatted_year = "" + date.getYear();
		var current_year = parseInt(unformatted_year.substring( unformatted_year.length - 2));

		document.res_form.arriv_month.selectedIndex = current_month - 1;
		document.res_form.arriv_day.selectedIndex = current_day - 1;
		document.res_form.arriv_year.selectedIndex = current_year - 2;

		document.res_form.depart_month.selectedIndex = current_month - 1;
		document.res_form.depart_day.selectedIndex = current_day - 1;
		document.res_form.depart_year.selectedIndex = current_year - 2;
	}
	
	else
	{
		// HACK: hardwire November 1, 2002
		document.res_form.arriv_month.selectedIndex = 10;
		document.res_form.arriv_day.selectedIndex = 0;
		document.res_form.arriv_year.selectedIndex = 0;

		// HACK: hardwire November 8, 2002
		document.res_form.depart_month.selectedIndex = 10;
		document.res_form.depart_day.selectedIndex = 7;
		document.res_form.depart_year.selectedIndex = 0;
	}
}

function testEmail(field, required)
{
	var str= field.value;
	var locSpace= str.indexOf(" ");
	var locAt= str.indexOf("@");
	var tmpStr= str.substring(locAt+1);
	var locDot= tmpStr.indexOf(".");
                
	// check if field is required, and if field is empty.
	if(required== "yes")
	{
		if(str=="")
		{
			return("\n    - Your Email is not specified");
		}
	} // end if required
	// field is not required. Check if field is empty. If it is return true. If there
	// is some data in the field, perform the checks.
	else
	{
		if(str=="")
			return("");
                
	} // end else

	locSpace= str.indexOf(" ");
	// check if the email address contains " " ( space ). If it does, give an error message.
	if(locSpace> -1)
	{
		return("\n    - Your Email address can not contain a space character");
	}
                
	locSpace= str.indexOf(",");
	// check if the email address contains ",". If it does, give an error message.
	if(locSpace> -1)
	{
		return("\n    - Your Email address can not contain a \",\" character");
	}

	locAt= str.indexOf("@");
	// check if the email address contains "@". If it doesn't, give an error message.
	if(locAt< 0)
	{
		return("\n    - Your Email address must be in the form \"username@domain\"");
	}
                        
	tmpStr= str.substring(locAt+1);
	locAt= tmpStr.indexOf("@");
	// check if the email address contains a second "@". If it does, give an error message.
	if(locAt> -1)
	{
		return("\n    - Your Email address can contain only one \"@\"");
	}

	locAt= str.indexOf("@");
	tmpStr= str.substring(locAt+1);
	locDot= tmpStr.indexOf(".");
	// check if the email address domain contains at least one "." character. If not, give an error message
	if((locDot<0))
	{
		return("\n    - Your Email domain must contain at least one \".\"-character");
	}                       
                        
	// check if the "username" starts with a dot
	if(str.charAt(0)== ".")
	{
		return("\n    - Your Email username can not start with a \".\"-character");
	}

	locAt= str.indexOf("@");
	tmpStr= str.substring(0,locAt);
	locDot= tmpStr.charAt(tmpStr.length-1);
	//alert("Username: "+tmpStr+" locAt: "+locAt+" locDot2: "+locDot);
	// check if the "username" ends with a dot
	if(tmpStr.charAt(tmpStr.length-1)== ".")
	{
		return("\n    - Your Email username can not end with a \".\"-character");
	}

	// check if the "domain" ends with a dot
	if(str.charAt(str.length-1)== ".")
	{
		return("\n    - Your Email domain can not end with a \".\"-character");
	}
                
	locAt= str.indexOf("@");
	tmpStr= str.substring(locAt+1);
	// check if the "domain" starts with a dot
	if(tmpStr.charAt(0)== ".")
	{
		return("\n    - Your Email domain can not start with a \".\"-character");
	}

	return("");        
}


// bCheckCostClicked must be true to allow form submission
var bCheckCostClicked = false;

function checkForm()
{
	var null_fields = "";

	if(document.res_form.guest_name.value == document.res_form.guest_name.defaultValue)
	{
		null_fields += "\n    - Your Name is not specified";
	}

	if(document.res_form.street_address.value == document.res_form.street_address.defaultValue)
	{
		null_fields += "\n    - Street Address is not specified";
	}

	if(document.res_form.city.value == document.res_form.city.defaultValue)
	{
		null_fields += "\n    - City is not specified";
	}

	if(document.res_form.state_prov.value == document.res_form.state_prov.defaultValue)
	{
		null_fields += "\n    - State is not specified";
	}

	if(document.res_form.postal_code.value == document.res_form.postal_code.defaultValue)
	{
		null_fields += "\n    - Postal Code is not specified";
	}

	if(document.res_form.country.value == document.res_form.country.defaultValue)
	{
		null_fields += "\n    - Country is not specified";
	}

	emailerror = testEmail(document.res_form.email, "yes");

	if ( emailerror != "") {
		null_fields += emailerror;
	}

	if(document.res_form.home_phone.value == document.res_form.home_phone.defaultValue)
	{
		null_fields += "\n    - Home Phone Number is not specified";
	}

	if(document.res_form.referrer.selectedIndex == 0)
	{
		null_fields += "\n    - Referred By is not specified";
	}

	if( bCheckCostClicked == false )
	{
		null_fields += "\n    - Cost Estimator has not been run";
	}

	if(null_fields != "")
	{
		alert("There was a problem with the following:\n" + null_fields + "\n\nPlease enter this information and try again.");
		return false;
	}

	return true;

}


// GLOBAL VAR -- for diag printing functions
var month_arr = new Array();
month_arr[0] = "January";
month_arr[1] = "February";
month_arr[2] = "March";
month_arr[3] = "April";
month_arr[4] = "May";
month_arr[5] = "June";
month_arr[6] = "July";
month_arr[7] = "August";
month_arr[8] = "September";
month_arr[9] = "October";
month_arr[10] = "November";
month_arr[11] = "December";

function diagPrintCalendarLengths()
{
	document.write("<BR>");

	for (i = 0; i < 36; i++)
	{
		if(i < 12)
		{
			document.write(" num. days in " + month_arr[i] + ", 2002 is: " + calendar_arr[i].length + "<BR>");
		}

		if(i >= 12 && i <= 23)
		{
			document.write(" num. days in " + month_arr[i-12] + ", 2003 is: " + calendar_arr[i].length + "<BR>");
		}

		if(i >= 24 && i <= 35)
		{
			document.write(" num. days in " + month_arr[i-24] + ", 2004 is: " + calendar_arr[i].length + "<BR>");
		}
	}

	document.write("<BR><BR>");
}

function diagPrintCalendarTotalCosts()
{
	document.write("<BR>");

	var count = 0;

	for (i = 0; i < 36; i++)
	{
	
		count = 0; // reset count
		for(j = 0; j < calendar_arr[i].length; j++)
		{
			count += calendar_arr[i][j];
		}

		if(i < 12)
		{
			document.write("Total cost for " + month_arr[i] + ", 2002 is: " + count + "<BR>");
		}

		if(i >= 12 && i <= 23)
		{
			document.write("Total cost for " + month_arr[i-12] + ", 2003 is: " + count + "<BR>");
		}

		if(i >= 24 && i <= 35)
		{
			document.write("Total cost for " + month_arr[i-24] + ", 2004 is: " + count + "<BR>");
		}
	}

	document.write("<BR><BR>");
}

// 02  03  04
//
// 0,  12, 24 January:   215 (except for the 1st which is $250??)
// 1,  13, 25 February:  215
// 2,  14, 26 March:     215
// 3,  15, 27 April:     215
// 4,  16, 28 May:       195
// 5,  17, 29 June:      195
// 6,  18, 30 July:      195
// 7,  19, 31 August:    195
// 8,  20, 32 September: 195
// 9,  21, 33 October:   195
// 10, 22, 34 November:  215
// 11, 23, 35 December:  215 (except 18-31 which are $250??)

// GLOBAL VAR -- don't know about passing arrays over "stack" yet
var calendar_arr = new Array();

function createCalendarArray()
{
	for (i = 0; i < 12; i++)
	{
		// JAN       MAR       MAY       JUL       AUG       OCT       DEC
		if(i == 0 || i == 2 || i == 4 || i == 6 || i == 7 || i == 9 || i == 11)
		{
			calendar_arr[i] = new Array(31);	
			calendar_arr[i + 12] = new Array(31);
			calendar_arr[i + 24] = new Array(31);
		}

		//  APR       JUN       SEP       NOV
		if (i == 3 || i == 5 || i == 8 || i == 10)
		{
			calendar_arr[i] = new Array(30);	
			calendar_arr[i + 12] = new Array(30);
			calendar_arr[i + 24] = new Array(30);
		}

		//  FEB
		if (i == 1)
		{
			calendar_arr[i] = new Array(28);	
			calendar_arr[i + 12] = new Array(28);
			calendar_arr[i + 24] = new Array(29); // LEAP YEAR
		}
	}
}


// GLOBALS
var NORM_RATE = 195;
var PEAK_RATE = 215;
var WINT_RATE = 250;

function populateCalendarArray()
{
	for (i = 0; i < 12; i++)
	{
		for(j = 0; j < calendar_arr[i].length; j++)
		{
			// JANUARY 1 THROUGH JANUARY 15 is WINTER RATE
			if(i == 0 && j <= 14)
			{
				calendar_arr[i][j] = WINT_RATE;
				calendar_arr[i + 12][j] = WINT_RATE;
				calendar_arr[i + 24][j] = WINT_RATE;
			}

			// JANUARY 16 THROUGH JANUARY 31 is PEAK RATE
			else if (i == 0 && j > 14)
			{
				calendar_arr[i][j] = PEAK_RATE;
				calendar_arr[i + 12][j] = PEAK_RATE;
				calendar_arr[i + 24][j] = PEAK_RATE;
			}

			// FEBRUARY 1 THROUGH APRIL 30 is PEAK RATE
			else if (i >= 1 && i <= 3)
			{
				calendar_arr[i][j] = PEAK_RATE;
				calendar_arr[i + 12][j] = PEAK_RATE;
				calendar_arr[i + 24][j] = PEAK_RATE;
			}

			// MAY 1 THROUGH MAY 31 is NORMAL RATE
			else if (i == 4)
			{
				calendar_arr[i][j] = NORM_RATE;
				calendar_arr[i + 12][j] = NORM_RATE;
				calendar_arr[i + 24][j] = NORM_RATE;
			}

			// JUNE 1 THROUGH JUNE 15 is NORMAL RATE
			else if (i == 5 && j <= 14)
			{
				calendar_arr[i][j] = NORM_RATE;
				calendar_arr[i + 12][j] = NORM_RATE;
				calendar_arr[i + 24][j] = NORM_RATE;
			}

			// JUNE 16 THROUGH JUNE 30 is PEAK RATE
			else if (i == 5 && j > 14)
			{
				calendar_arr[i][j] = PEAK_RATE;
				calendar_arr[i + 12][j] = PEAK_RATE;
				calendar_arr[i + 24][j] = PEAK_RATE;
			}

			// JULY 1 THROUGH AUGUST 31 is PEAK RATE
			else if (i >= 6 && i <= 7)
			{
				calendar_arr[i][j] = PEAK_RATE;
				calendar_arr[i + 12][j] = PEAK_RATE;
				calendar_arr[i + 24][j] = PEAK_RATE;
			}

			// SEPTEMBER 1 THROUGH NOVEMBER 30 is NORMAL RATE
			else if (i >= 8 && i <= 10)
			{
				calendar_arr[i][j] = NORM_RATE;
				calendar_arr[i + 12][j] = NORM_RATE;
				calendar_arr[i + 24][j] = NORM_RATE;
			}

			// DECEMBER 1 THROUGH DECEMBER 31 is WINTER RATE
			else
			{
				calendar_arr[i][j] = WINT_RATE;
				calendar_arr[i + 12][j] = WINT_RATE;
				calendar_arr[i + 24][j] = WINT_RATE;
			}
		}
	}

	//  BAD LEAP YEAR HACK!
	calendar_arr[25][28] = PEAK_RATE; // fill in 29th day because code above doesn't
}


//------------------------------------------------------------------------------------
function formatMoney(theNumber) {
var newNum = "" + theNumber;
var theLength = newNum.length;
var theDecLoc = newNum.lastIndexOf(".");

        if (theDecLoc == -1) {
                newNum = newNum + ".00";
                return newNum;

}
        if (theDecLoc != -1) {
                var theDollars = newNum.substring(0,theDecLoc);
                var theCents = newNum.substring(theDecLoc,theLength);
                var theCents = "" + Math.round(theCents * 100);
                //if statment fixes bug when theCents = 100
                if (theCents == "100") {
                        theDollars = parseFloat(theDollars); //theDollars from string into number
                        theDollars += 1;
                        newNum = theDollars + ".00";
                        return newNum;
                        }
                else {
                var newCents = (theCents.length == 1) ? "0" + theCents: theCents;
                newNum = theDollars + "." + newCents;
                return newNum;
                }
        }
}
//---------------------------------------------------------------------------------------

function setPulldowns(months, days, years)
{
	var i = months.selectedIndex;

	var temp;

	if(i == 0 || i == 2 || i == 4 || i == 6 || i == 7 || i == 9 || i == 11)
	{
//		alert('31 days!');

		// always attempt to build up
		for (j = days.length - 1; j < 31; j++)
		{
			var temp = new Option(j + 1, j);
			days.options[j] = temp;
		}
	}

	if (i == 3 || i == 5 || i == 8 || i == 10)
	{
//		alert('30 days!');

		// build up
		for (j = days.length - 1; j < 30; j++)
		{
			var temp = new Option(j + 1, j);
			days.options[j] = temp;
		}

		// or build down

		for (j = days.length - 1; j > 29; j--)
		{
			days.options[j] = null;
		}
	}

	if (i == 1)
	{
		if(years.selectedIndex == 2)
		{
//			alert('29 days!');

			// build up
			for (j = days.length - 1; j < 29; j++)
			{
				var temp = new Option(j + 1, j);
				days.options[j] = temp;
			}

			// or build down
			for (j = days.length - 1; j > 28; j--)
			{
				days.options[j] = null;
			}
		}
		else
		{
//			alert('28 days!');

			// always attempt to build down
			for (j = days.length - 1; j > 27; j--)
			{
				days.options[j] = null;
			}
		}
	}
}


function calcCost(arriv_month, arriv_day, arriv_year, depart_month, depart_day, depart_year)
{
	createCalendarArray();
//	diagPrintCalendarLengths()
	populateCalendarArray();
//	diagPrintCalendarTotalCosts()

	var orig_arriv_month = arriv_month;
	var orig_depart_month = depart_month;

	var subtotal_cost = 0;

	if(arriv_year == 1)
	{
		arriv_month += 12;
	}
	else if(arriv_year == 2)
	{
		arriv_month += 24;
	}

	if(depart_year == 1)
	{
		depart_month += 12;
	}
	else if(depart_year == 2)
	{
		depart_month += 24;
	}

	var i = arriv_month;
	var j = arriv_day;
	var night_count = 0; // total night count
	var peak_count = 0; // total peak night count
	var norm_count = 0; // total normal night count
	var wint_count = 0; // total winter night count

	while (i <= depart_month)
	{
		if(i == depart_month)
		{
			while(j < calendar_arr[i].length && j < depart_day) // you don't count the last "day"?
			{
//				alert ('calendar_arr[' + i + '] = ' + calendar_arr[i].length + 
//					'\ndepart_day = ' + depart_day +
//					'\nj = ' + j);
				subtotal_cost += calendar_arr[i][j];
				night_count++; // accumulate the nights

				if(calendar_arr[i][j] == PEAK_RATE)
				{
					peak_count++;
				}
				else if(calendar_arr[i][j] == WINT_RATE)
				{
					wint_count++;
				}
				else
				{
					norm_count++;
				}

				j++
			}
		}

		else
		{
			while(j < calendar_arr[i].length)
			{
				subtotal_cost += calendar_arr[i][j];
				night_count++; // accumulate the nights 

				if(calendar_arr[i][j] == PEAK_RATE)
				{
					peak_count++;
				}
				else if(calendar_arr[i][j] == WINT_RATE)
				{
					wint_count++;
				}
				else
				{
					norm_count++;
				}

				j++
			}
		}

		j = 0;		
		i++;
	}

// HACK - REMOVE WHEN YOU UPDATE CALENDAR AND REMOVE 2002

	if(document.res_form.arriv_year.selectedIndex == 0 || document.res_form.depart_year.selectedIndex == 0)
	{
		alert(	' There is a problem with your arrival and/or departure date(s) ' + '\n\n' +
			'            Please select the year 2003 or greater.            ' + '\n\n' +
			'        Please check your selected dates and try again.        ');
		document.res_form.costdisplay.value = 'Please enter:\n\n - A valid arrival date\n - A valid departure date\n\nThen click "Check Cost" again.';
		// we can't allow submit
		bCheckCostClicked = false;
		return;
	}

	if(night_count < 7)
	{
		alert(	' There is a problem with your arrival and/or departure date(s) ' + '\n\n' +
			'           We require a minimum booking of 7 nights.           ' + '\n\n' +
			'        Please check your selected dates and try again.        ');
		document.res_form.costdisplay.value = 'Please enter:\n\n - A valid arrival date\n - A valid departure date\n\nThen click "Check Cost" again.';
		// we can't allow submit
		bCheckCostClicked = false;
		return;
	}

	var sdiscount = 0.0;
	var idiscount = 0.0;

	var stay_discount_string;

	var internet_discount = 0.07;
	var tax_rate = 0.114167;
	var tax_total = 0.0;
	var grand_total = 0.0;

	// APPLY 10% discount for stays of two weeks to one month
	if(night_count >= 14 && night_count <= 30)
	{
		sdiscount = 0.10 * subtotal_cost;
		stay_discount_string = "14+ NIGHT DISCOUNT:  - $" + formatMoney(sdiscount) + " (10%)";
	}

	// APPLY 15% discount for stays greater than one month
	else if(night_count > 30)
	{
		sdiscount = 0.15 * subtotal_cost;	
		stay_discount_string = "30+ NIGHT DISCOUNT:  - $" + formatMoney(sdiscount) + " (15%)";
	}
	else
	{
		stay_discount_string = "NO DISCOUNT:            " + "(under 2 weeks)";
	}

//	if(!sdiscount)
//	{
//		idiscount = subtotal_cost * internet_discount;
//	}
//	else
//	{
//		idiscount = sdiscount * internet_discount;
//	}

	idiscount = (subtotal_cost - sdiscount) * internet_discount;

	tax_total = tax_rate * (subtotal_cost - sdiscount - idiscount);

	grand_total = subtotal_cost + tax_total - sdiscount - idiscount;

// FORMATTING:

	var night_count_string;
	var norm_count_string;
	var peak_count_string;
	var wint_count_string;

	if(night_count <= 9)
	{
		night_count_string = "  " + night_count;
	}
	else if(night_count >= 10 && night_count < 100)
	{
		night_count_string = " " + night_count;
	}
	else if (night_count >= 100)
	{
		night_count_string = "" + night_count;
	}


	if(norm_count <= 9)
	{
		norm_count_string = "  " + norm_count;
	}
	else if(norm_count >= 10 && norm_count < 100)
	{
		norm_count_string = " " + norm_count;
	}
	else if (norm_count >= 100)
	{
		norm_count_string = "" + norm_count;
	}


	if(peak_count <= 9)
	{
		peak_count_string = "  " + peak_count;
	}
	else if(peak_count >= 10 && peak_count < 100)
	{
		peak_count_string = " " + peak_count;
	}
	else if (peak_count >= 100)
	{
		peak_count_string = "" + peak_count;
	}


	if(wint_count <= 9)
	{
		wint_count_string = "  " + wint_count;
	}
	else if(wint_count >= 10 && wint_count < 100)
	{
		wint_count_string = " " + wint_count;
	}
	else if (wint_count >= 100)
	{
		wint_count_string = "" + wint_count;
	}



	document.res_form.costdisplay.value = 	'TOTAL NIGHTS:          ' + night_count_string + '\n' +
						'NORMAL RATE NIGHTS:    ' + norm_count_string + ' @ $' + NORM_RATE + '\n' +
						'PEAK RATE NIGHTS:      ' + peak_count_string + ' @ $' + PEAK_RATE + '\n' +
						'WINTER RATE NIGHTS:    ' + wint_count_string + ' @ $' + WINT_RATE + '\n\n' +
						'SUBTOTAL:              $' + formatMoney(subtotal_cost) + '\n' +
						stay_discount_string + '\n' + 
						'INTERNET DISCOUNT:   - $' + formatMoney(idiscount) + ' (7%)\n' + 
						'TAX:                 + $' + formatMoney(tax_total) + ' (11.4167%)\n' +
						'------------------------------------------\n' +
						'GRAND TOTAL:           $' + formatMoney(grand_total) + ' USD*\n\n' +
						'*quote is preliminary and subject to confirmation\n\n' +
						'ARR: ' + (orig_arriv_month+1) + '/' + (arriv_day+1) + '/' + (arriv_year+2002) +'\n' +
						'DEP: ' + (orig_depart_month+1) + '/' + (depart_day+1) + '/' + (depart_year+2002) +'\n';


	// we can allow submit
	bCheckCostClicked = true;
}
