//USED IN RESERVATION SEARCH

function checkSpecialEvents (resArrive, resDepart, action) {
	arriveYear = resArrive.getFullYear(); // refererence point for events database
	for (i=0; i < num_events; i++) {
		// convert to timestamps
		//eventStart = new Date(arriveYear, specialEvents[i][1] - 1, specialEvents[i][2], 0,0,0,0);
		eventStart = new Date(specialEvents[i][18]);
		// if the event end month is less than the start month, put it in the following year
		if (specialEvents[i][3] < specialEvents[i][1]) endYear = arriveYear + 1;
		else endYear = arriveYear;
		//eventEnd = new Date(endYear,  specialEvents[i][3] - 1, specialEvents[i][4], 0,0,0,0);
		eventEnd = new Date(specialEvents[i][19]);
		// check for intersection
		if (eventStart < resDepart && eventEnd > resArrive) {
			if (action == "min_stay") return specialEvents[i][5];
			else if (action == "min_stay2") return specialEvents[i][6];
			else if (action == "min_stay3") return specialEvents[i][7];
			else if (action == "min_stay4") return specialEvents[i][8];
			else if (action == "waiver_adjust") return specialEvents[i][9];
			else if (action == "waiver_adjust2") return specialEvents[i][10];
			else if (action == "waiver_adjust3") return specialEvents[i][11];
			else if (action == "waiver_adjust4") return specialEvents[i][12];
			else if (action == "sec_deposit") return specialEvents[i][13];
			else if (action == "pricing") return specialEvents[i][14];
			else if (action == "pricing2") return specialEvents[i][15];
			else if (action == "pricing3") return specialEvents[i][16];
			else if (action == "pricing4") return specialEvents[i][17];
			else if (action == "event") return specialEvents[i][0];
		}
	}
	return 0;
}

function checkMinStay (resArrive, resDepart) {
	startMo = resArrive.getMonth();
	startYear = resArrive.getYear()
	endMo = resDepart.getMonth();
	endYear = resDepart.getYear()
	
	// check for year cross
	endMo = endMo + (12 * (endYear - startYear));
	//alert(startMo + " start/end " + endMo);
	
	minStay = houseMinStay;
	
	for (i=startMo; i<=endMo; i++) {
		index = (i % 12);
		if (houseMinStayMo[index] > minStay) minStay = houseMinStayMo[index]
		//alert("Mo: " + index + ", " + houseMinStayMo[index] + ", " + minStay);
	}
	return minStay;
}


function resTotal(withDeposit) {
	var subtotal = 	parseFloat(document.reservation.up_rent.value) +
					parseFloat(document.reservation.up_fee_arr_early.value) +
					parseFloat(document.reservation.up_fee_dep_late.value) +
					parseFloat(document.reservation.up_fee_pool.value) +
					//parseFloat(document.reservation.up_city_tax.value) +
					parseFloat(document.reservation.up_fee_cleaning.value) +
					parseFloat(document.reservation.up_fee_pet.value) +
					parseFloat(document.reservation.up_fee_misc.value);
	//removed security deposit: + parseFloat(document.reservation.up_fee_sec_dep.value)					
	var total = subtotal + parseFloat(document.reservation.up_fee_peace_waiver.value)  + parseFloat(document.reservation.up_fee_sec_dep.value);
	//alert(subtotal);
	if (withDeposit) return total;
	else return subtotal;
}
					
function updateTotals() {
	// calculate processing fee - only if res is longer than 7 days, or res is 7 days or more in advance
	// and, the processing fee checkbox is checked CHANGED TO ALWAYS APPLY THE PROCESSING FEE - 2009-06-19

	// display the totals
	theRent = "$" + formatAsMoney(resTotal(false));
	document.getElementById('subtotal').innerHTML = theRent;
	theRent = "$" + formatAsMoney(resTotal(true));
	document.getElementById('total').innerHTML = theRent;
	
	totalRent = Math.round((resTotal(true) + parseFloat(document.reservation.up_fee_processing.value) + parseFloat(document.reservation.up_city_tax.value)) * 100)/100;
	theRent = "$" + formatAsMoney(totalRent);
	document.getElementById('total_w_proc_fee').innerHTML = theRent;
	document.reservation.credit_total.value = totalRent;
}

var nightsChangeID = 0;


function nightsChange(nights) {
	clearTimeout(nightsChangeID);
	if (nights != "") nightsChangeID = setTimeout('nightsChangeExecute()',800);
}

function nightsChangeExecute() {

	nights = document.reservation.up_stay_nights.value
	nowYear = document.reservation.up_arrive_year.value
	nowMonth = document.reservation.up_arrive_month.value
	nowDay = document.reservation.up_arrive_day.value
	
	arriveDate = new Date(nowYear, nowMonth - 1, nowDay, 0, 0, 0, 0);
	theNights = nights * (1000 * 60 * 60 * 24);
	departDate.setTime(arriveDate.getTime() + theNights);
	
	thenYear = departDate.getFullYear();
	thenMonth = departDate.getMonth()+1;
	thenDay = departDate.getDate();
		
		
// Need to change bellow for admin side
	if(location.href.indexOf('calendar.html')>0 ) {
		document.reservation.up_depart_year.selectedIndex = 1;
		document.reservation.up_depart_month.selectedIndex = thenMonth-1; 
		document.reservation.up_depart_day.selectedIndex = thenDay-1;														 	
	} else {
		document.reservation.up_depart_year.value = thenYear;
		document.reservation.up_depart_month.value = thenMonth; 
		document.reservation.up_depart_day.value = thenDay;		
	}

	m = thenMonth;
	d = thenDay;
	if(thenYear > 2000)
		y = thenYear-2000;
	else
		y = thenYear;
		
	if(y<10)
		y='0'+y;
	if(m < 10)
		m = '0'+m;
	if(d < 10)
		d = '0'+d;
	document.reservation.depart.value = m+'/'+d+'/'+y;
	
	updateCalcRes();
}

function updateCalc() {

	if(document.reservation.up_arrive_empty.value == 'true') {
		//No arrival date has been set
		document.forms['reservation'].arrive.value = 'Arrival';	
	} else {
		nowYear = document.reservation.up_arrive_year.value
		nowMonth = document.reservation.up_arrive_month.value
		nowDay = document.reservation.up_arrive_day.value	
		//alert(nowMonth+"/"nowDay+"/"nowYear);
		
		currentDate = new Date();
		currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(),0,0,0,0) ;
		arriveDate = new Date(nowYear, nowMonth - 1, nowDay, 0, 0, 0, 0);
	}
	if(document.reservation.up_depart_empty.value == 'true') {
		//no departure date
		document.forms['reservation'].depart.value = 'Departure';		
	} else {
		thenYear = document.reservation.up_depart_year.value
		thenMonth = document.reservation.up_depart_month.value
		thenDay = document.reservation.up_depart_day.value
		//alert(arriveDate.toLocaleString());
		// don't allow dates prior to today - only for customer entry
		//if (arriveDate < currentDate) arriveDate = new Date(currentDate.getFullYear() + 1, nowMonth - 1, nowDay, 0, 0, 0, 0);

		departDate = new Date(thenYear, thenMonth - 1, thenDay, 0, 0, 0, 0);	
		//alert(departDate);
		//alert(departDate.toLocaleString());
	}

	lengthOfStay = Math.round((departDate.getTime() - arriveDate.getTime())/(1000 * 60 * 60 * 24));

	lengthOfAdvance = Math.round((arriveDate.getTime() - currentDate.getTime())/(1000 * 60 * 60 * 24));
	
	if (parseInt(lengthOfStay) < 2) {
		//alert("days less than 2");
		twoDays = 2 * (1000 * 60 * 60 * 24);
		departDate.setTime(arriveDate.getTime() + twoDays);
		lengthOfStay = 2;
	}
	
	//alert("checkminstay");
	// get the house minimumStay for this reservation (houses have minimum stays per month)
	resMinStay = checkMinStay(arriveDate, departDate);

	// check for intersecting special event minimum stay
	if (numBeds <= 3) specialEventMinStay = checkSpecialEvents(arriveDate, departDate, "min_stay");
	else if (numBeds == 4) specialEventMinStay = checkSpecialEvents(arriveDate, departDate, "min_stay2");
	else if (numBeds == 5) specialEventMinStay = checkSpecialEvents(arriveDate, departDate, "min_stay3");
	else if (numBeds > 5) specialEventMinStay = checkSpecialEvents(arriveDate, departDate, "min_stay4");
	if (specialEventMinStay > resMinStay) resMinStay = specialEventMinStay;

	if (lengthOfStay < resMinStay) {
		minDays = resMinStay * (1000 * 60 * 60 * 24);
		departDate.setTime(arriveDate.getTime() + minDays);
		
		alert("There is a minimum stay for this home of " + resMinStay + " days for this time period.  This is reflected in the price quote.");
		//alert("Your depart date has been set to " + departDate);
		//alert(departDate.toLocaleString());		
		// alert(thenYear + "-" + thenMonth + "-" + thenDay);
		
		lengthOfStay = resMinStay;
	}
	//alert("hi" + lengthOfStay);
	document.reservation.up_stay_nights.value = lengthOfStay;
	
	//CHECK FOR SECURITY DEPOSIT
	var secDepositStatus = checkSpecialEvents(arriveDate, departDate, "sec_deposit");
	if (secDepositStatus == "yes") {
		alert('During this time period we require a security deposit.  Please call (800) 590-3110 to make this reservation.');
	}

	// convert back from date format to correct for invalid dates such as Feb 31
	nowYear = arriveDate.getFullYear();
	nowMonth = arriveDate.getMonth() + 1;
	nowDay = arriveDate.getDate();
	
	thenYear = departDate.getFullYear();
	thenMonth = departDate.getMonth() + 1;
	thenDay = departDate.getDate();
	
	displayDate = (thenMonth + "/" + thenDay + "/" + thenYear);
	//document.getElementById('show_depart_date').innerhtml = displayDate;
	//document.checkavail.depart.value = displayDate;
	//document.checkavail.up_stay_nights.value = resMinStay;
	//alert(displayDate);
	
	// Reservation might be text or select box

	if(location.href.indexOf('home_detail.php') > 0 ) {
		document.reservation.up_arrive_year.value = nowYear;
		document.reservation.up_arrive_month.value = nowMonth;
		document.reservation.up_arrive_day.value = nowDay;
	
		document.reservation.up_depart_year.value = thenYear;
		document.reservation.up_depart_month.value = thenMonth; 
		document.reservation.up_depart_day.value = thenDay;
	} else {
		document.reservation.up_arrive_year.selectedIndex = nowYear - currentDate.getFullYear() + 1;
		document.reservation.up_arrive_month.selectedIndex = nowMonth - 1; // months 0-11
		document.reservation.up_arrive_day.selectedIndex = nowDay - 1;
	
		document.reservation.up_depart_year.selectedIndex = thenYear - currentDate.getFullYear() + 1;
		document.reservation.up_depart_month.selectedIndex = thenMonth - 1; // months 0-11
		document.reservation.up_depart_day.selectedIndex = thenDay - 1;
	}

	// NEW determine the summer/winter rate period
	arriveYear = arriveDate.getFullYear(); // refererence point start year
	summerStart = new Date(arriveYear, summerMo - 1, summerDy, 0,0,0,0);
	
	if (winterMo < summerMo) endYear = arriveYear + 1;
	else endYear = arriveYear;
	
	summerEnd = new Date(endYear, winterMo - 1, winterDy - 1, 0,0,0,0);
	
	// check for only the arrive date of the res to determine if in summer or winter
	if (summerStart <= arriveDate && summerEnd >= arriveDate) ratePeriod = "summer";
	else ratePeriod = "winter";
	
	// calculate the rent
	if (ratePeriod == "summer") {
		// staying less than a week
		if (lengthOfStay < 7) up_rent = lengthOfStay * summer_nt;
		// staying more than a week, but less than a month
		else if (lengthOfStay >= 7 && lengthOfStay < 30) up_rent = lengthOfStay * (summer_wk / 7.0);
		// staying longer than a month
		else up_rent = lengthOfStay * (summer_mo / 30.0);
	} else { // winter
		// staying less than a week
		if (lengthOfStay < 7) up_rent = lengthOfStay * winter_nt;
		// staying more than a week, but less than a month
		else if (lengthOfStay >= 7 && lengthOfStay < 30) {
			numOfWeeks = (lengthOfStay / 7) | 0;
			numOfDaysExtra = lengthOfStay % 7;
			weekRent = numOfWeeks * winter_wk;
			daysExtraRent = numOfDaysExtra * (winter_wk / 5.0);
			up_rent = weekRent + daysExtraRent;
			//up_rent = lengthOfStay * (winter_wk / 7.0);
		}
		// staying longer than a month
		else up_rent = lengthOfStay * (winter_mo / 30.0);
	}


		
	// check for special event pricing
	priceAdjustment = 100; // 100 percent
	earlyLateFee = fee_early_late;
	if (lengthOfStay < 30) {
		
		//CHECK SPECIAL PRICING BASED ON BEDROOMS
		if (numBeds <= 3) { specialEventPricing = checkSpecialEvents(arriveDate, departDate, "pricing"); }
		else if (numBeds == 4) { specialEventPricing = checkSpecialEvents(arriveDate, departDate, "pricing2"); }
		else if (numBeds == 5) { specialEventPricing = checkSpecialEvents(arriveDate, departDate, "pricing3"); }
		else if (numBeds > 5) { specialEventPricing = checkSpecialEvents(arriveDate, departDate, "pricing4"); }
		
		if (specialEventPricing != 0) {
			priceAdjustment = specialEventPricing;
			earlyLateFee = fee_early_late_special;
		}
	}
	specialEventName = checkSpecialEvents(arriveDate, departDate, "event");
	if (specialEventName == 0) 	specialEventName = "None";

	eventString = "Min Stay: " + resMinStay + ", Event: " + specialEventName + ", Event Min: " + specialEventMinStay + ", Price: " + priceAdjustment + "%";
	document.getElementById('special_event').firstChild.nodeValue = eventString;
	
	//Check for WAIVER ADJUSTMENTS
		if (numBeds <= 3) waiverAdjust = checkSpecialEvents(arriveDate, departDate, "waiver_adjust");
		else if (numBeds == 4) waiverAdjust = checkSpecialEvents(arriveDate, departDate, "waiver_adjust2");
		else if (numBeds == 5) waiverAdjust = checkSpecialEvents(arriveDate, departDate, "waiver_adjust3");
		else if (numBeds > 5) waiverAdjust = checkSpecialEvents(arriveDate, departDate, "waiver_adjust4");
		if (waiverAdjust > 100) {
			fee_peace_waiver = fee_peace_waiver * waiverAdjust/100;
		}
	
	// indicate early - late fees
	document.getElementById('show_early').innerHTML = earlyLateFee;
	document.getElementById('show_late').innerHTML = earlyLateFee;

	if (document.reservation.up_event_pricing_ch.value == "yes") up_rent = up_rent * priceAdjustment/100;
	
	if (document.reservation.up_guest_type.value == "owner" || document.reservation.up_guest_type.value == "maintenance") {
		document.reservation.up_custom_pricing.checked = true;
		document.reservation.up_rent.value = formatAsMoney(0);
		document.reservation.up_city_tax.value = formatAsMoney(0);
		document.reservation.up_fee_cleaning.value = formatAsMoney(0);
		document.reservation.up_fee_sec_dep.value = formatAsMoney(0);
		document.reservation.up_fee_peace_waiver.value = formatAsMoney(0);
		document.reservation.up_fee_pet.value = formatAsMoney(0);
		document.reservation.up_fee_arr_early.value = formatAsMoney(0);
		document.reservation.up_fee_dep_late.value = formatAsMoney(0);
		document.reservation.up_fee_pool.value = formatAsMoney(0);
		document.reservation.up_fee_processing.value = formatAsMoney(0);
	} else if (!document.reservation.up_custom_pricing.checked) {
		up_rent = Math.round(up_rent * 100)/100;
		document.reservation.up_rent.value = formatAsMoney(up_rent);
				
		// calculate cleaning fee
		document.reservation.up_fee_cleaning.value = formatAsMoney(fee_cleaning);
	
		// calculate security deposit & peace of mind damage waiver fee
		if (document.reservation.up_peace_waiver_ch.value == "yes") {
			document.reservation.up_fee_sec_dep.value = formatAsMoney(0);
			document.reservation.up_fee_peace_waiver.value = formatAsMoney(fee_peace_waiver);
		} else {
			document.reservation.up_fee_sec_dep.value = formatAsMoney(fee_sec_dep);
			document.reservation.up_fee_peace_waiver.value = formatAsMoney(0);
		}
			
	
		// calculate pet fee
		if (document.reservation.up_num_pets.selectedIndex > 0) document.reservation.up_fee_pet.value = formatAsMoney(75*document.reservation.up_num_pets.selectedIndex);
		else document.reservation.up_fee_pet.value = formatAsMoney(0);
		
		// calculate early/late arrival/departure
		if (document.reservation.up_arr_early.checked) document.reservation.up_fee_arr_early.value = formatAsMoney(earlyLateFee);
		else document.reservation.up_fee_arr_early.value = formatAsMoney(0);
	
		if (document.reservation.up_dep_late.checked) document.reservation.up_fee_dep_late.value = formatAsMoney(earlyLateFee);
		else document.reservation.up_fee_dep_late.value = formatAsMoney(0);
		
		// calculate pool charges	
		if (document.reservation.up_pool_heat.checked) {
			if (lengthOfStay < 7) { // staying less than a week
				up_fee_pool = lengthOfStay * fee_pool_day;
			} else if (lengthOfStay >= 7 && lengthOfStay < 30) { // staying more than a week, but less than a month
				up_fee_pool = lengthOfStay * (fee_pool_week / 7.0);
			} else up_fee_pool = 0; // staying longer than a month, no pool feel, will be charged for utilties
			
			up_fee_pool = Math.round(up_fee_pool * 100)/100; // round to 2 decimal places
		} else up_fee_pool = 0.00;
		document.reservation.up_fee_pool.value = formatAsMoney(up_fee_pool);
		
		//CALC PROCESSING FEE
		if (!document.reservation.up_custom_pricing.checked) {
		if (document.reservation.up_proc_fee_pricing_ch.value == "yes" && (lengthOfStay >= 0 || lengthOfAdvance >= -1)) {		
			up_fee_processing = Math.round((resTotal(true) * processing_fee_rate) * 100)/100;
		} else up_fee_processing = 0;
		document.reservation.up_fee_processing.value = formatAsMoney(up_fee_processing);
		}
		
		// calculate lodging tax	
		if (lengthOfStay < 30) {
			total_rent = up_rent;
			if (document.reservation.up_arr_early.checked) total_rent += earlyLateFee;
			if (document.reservation.up_dep_late.checked) total_rent += earlyLateFee;
			if (document.reservation.up_num_pets.selectedIndex > 0) total_rent += (75*document.reservation.up_num_pets.selectedIndex);
			total_rent += fee_cleaning;
			total_rent += parseFloat(document.reservation.up_fee_processing.value);
			up_city_tax = city_tax_rate * total_rent;
			up_city_tax = Math.round(up_city_tax * 100)/100;  // round to 2 decimal places
		} else up_city_tax = 0;
		document.reservation.up_city_tax.value = formatAsMoney(up_city_tax);			

 	}

	updateTotals();
}
		
function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}

