// ----------------------------------------------------------------------
// AJAX basics

function runAjax (objID, serverPage) {
	
	//alert ("Running AJAX ... for Page "+serverPage);
	//Create a boolean variable to check for a valid IE instance.
	var xmlhttp = false;
	//var returnValue = false;
	
	//Check if we are using IE.
	try {
		//If the javascript version is greater than 5.
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		//If not, then use the older active x object.
		try {
			//If we are using IE.
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			//Else we must be using a non-IE browser.
			xmlhttp = false;
		}
	}
	
	//If we are using a non-IE browser, create a JavaScript instance of the object.
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		xmlhttp = new XMLHttpRequest();
	}

	var theObject = document.getElementById(objID);

	xmlhttp.open("GET", serverPage);
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				theObject.innerHTML = xmlhttp.responseText;
//				alert("ResponseTxt: " + xmlhttp.responseText);
//				alert("innerHTML: " + theObject.innerHTML + "\n Visibility: " + theObject.style.visibility + "\n Position: left->" + theObject.style.left + ", top->" + theObject.style.top);
				//returnValue = true;
			}
		}
	}
	xmlhttp.send(null);
	//return returnValue;
	return true;
}


// End AJAX basics
// ----------------------------------------------------------------------------
// Start AJAX functions



function updateCalendar (year, month){
	
	//The location we are loading the page into.
	var objID = "calendar";
	var serverPage = "includes/calendar.inc.php?year="+year+"&month="+month;
	
	runAjax(objID,serverPage); // perform the AJAX
	
}


function updateCalendarDetails (year, month){
	
	//The location we are loading the page into.
	var objID = "calendar_details";
	var serverPage = "includes/calendar_details.inc.php?year="+year+"&month="+month;
	
	if( document.getElementById ) // this is the way the standards work
		elem = document.getElementById( objID );
	else if( document.all ) // this is the way old msie versions work
		elem = document.all[objID];
	else if( document.layers ) // this is the way nn4 works
		elem = document.layers[objID];

	// only update details if logged in
	if (elem.style.display == 'block') {
		runAjax(objID,serverPage); // perform the AJAX
	}
}


function updateMessage (Msg){
	
	//The location we are loading the page into.
	var objID = "messages";
	document.getElementById(objID).style.display = 'block'; // display the block
	document.getElementById(objID).innerHTML = Msg; // update the HTML
}


// handles the different update sections
function updateMonitor (year, month, inputField, inputForm) {
	if (inputField != '') {
		display_input_calendar (year, month, inputField, inputForm);
	} else {
		updateCalendar(year, month);
		updateCalendarDetails(year, month);
		updateMessage(""); // clear the message
		document.getElementById('messages').style.display = 'none'; // display the block
	}
}


function display_input_calendar (year, month, inputField, inputForm){
	
	//The location we are loading the page into.
	var objID = "calendar_input";
	// set the position of the calendar
	document.getElementById(objID).className = inputField;
	document.getElementById(objID).style.display = 'block';
	
	// if it is the second date, get the month and year of the first date and use them
	//alert('Input Field: '+inputField);
	if (inputField == 'endDate') {
		// get dates from start field if first time through, otherwise use requested month and date
		if (document.forms[inputForm].elements['startDate'].value.length != 0) {
			var startDateSet = document.forms[inputForm].elements['startDate'].value;
			var brokenString = startDateSet.split("/");
			// check month ... make sure year is accounted
			if ((month < brokenString[1]) && (year == brokenString[2])) {
				month = brokenString[1]; // overwrite date details
			}
			if (year < brokenString[2]) { // sey year as new year
				year = brokenString[2];
			}
		}
		//alert('End Date: '+month+','+year);
	}
	
	var serverPage = "includes/input_calendar.inc.php?year="+year+"&month="+month+"&div="+inputField+"&form="+inputForm;
	//alert('Server Page: '+serverPage);
	var objID = "calendar_input_calendar";
	runAjax(objID,serverPage); // perform the AJAX
	
}

function hide_calendar (objID){
	//The location we are loading the page into.
	document.getElementById(objID).style.display = 'none';
	document.getElementById(objID).className = ''; // clear the class name
}


function set_input_value (calendarID, objID, dateValue) {
	var input = document.forms[calendarID].elements[objID];
	//alert('Input:' + input.value);
	input.value = dateValue;
	hide_calendar ('calendar_input');
}

/*
function display_forms () {
	docOut = 'Num: Name - Type - Value \n';
	docOut = docOut + ' --- Form 1 --- \n';
	for (var i=1;i<document.forms[0].length;i++) {
		current = document.forms[0].elements[i];
		docOut = docOut + i + ': ';
		docOut = docOut + current.name + ' - ';
		docOut = docOut + current.type + ' - ';
		docOut = docOut + current.value + ' \n';
	}
	docOut = docOut + ' --- Form 2 --- \n';
	for (var i=1;i<document.forms[1].length;i++) {
		current = document.forms[1].elements[i];
		docOut = docOut + i + ': ';
		docOut = docOut + current.name + ' - ';
		docOut = docOut + current.type + ' - ';
		docOut = docOut + current.value + ' \n';
	}
	return docOut;
}
*/
// -----------------------------------------------------------------

// handles the different update sections
function confirmBooking (year, month, ID, status) {
	
	updateMessage("Confirming Booking ... ");
	
	//The location we are loading the page into.
	var objID = "messages";
	var serverPage = "includes/confirm_booking.inc.php?ID="+ID+"&status="+status;
	
	runAjax(objID,serverPage); // perform the AJAX

	// reload the calendar and details
	updateCalendar(year, month);
	updateCalendarDetails(year, month);
	
}


function confirmRemoval(year, month, ID) {
	var answer = confirm("Are you sure you want to remove this booking? \n This can NOT be undone.");
	if (answer){
		confirmBooking(year,month,ID,0);
	}
	else{
		return;
	}
}

// handles the validation of the booking request
function handleBooking () {
	
	updateMessage("Validating Booking ... "); 

	var sdate = document.bookingForm.startDate.value;
	var edate = document.bookingForm.endDate.value;
	var desc = document.bookingForm.description.value;
	var cst = document.bookingForm.cost.value;
	
	// check the start date exits
	if ((sdate == "") || (sdate.length < 10)) {
		updateMessage("You must have a Start Date in the format (dd/mm/yyyy) ...<br />2 digits for both DAY and MONTH, 4 digits for the YEAR");
		document.bookingForm.startDate.focus(); // put the focus on the form
		return;
	}
	// check the end date exits
	if ((edate == "") || (edate.length < 10)) {
		updateMessage("You must have an End Date in the format (dd/mm/yyyy) ...<br />2 digits for both DAY and MONTH, 4 digits for the YEAR");
		document.bookingForm.endDate.focus(); // put the focus on the form
		return;
	}
	
	// get the seperate parts of the start date
	var s = new Array();
	s = sdate.split('/'); // split the date into an array
	s_day = s[0];
	s_month = s[1];
	s_year = s[2];

	// get the parts of todays date
	var d = new Date();
	var t_day = d.getDate();      // Returns the day of the month
	var t_month = d.getMonth();      // Returns the month as a digit
	t_month++; // account for the month being one less
	
	// now check if month and day are 2 digits if not, add a 0 in front
	if (t_day < 10) {
		t_day.toString();
		t_day = '0' + t_day;
	}
	if (t_month < 10) {
		t_month.toString();
		t_month = '0' + t_month;
	}
	var t_year = d.getFullYear();  // Returns 4 digit year
	var today = t_day + "/" + t_month + "/" + t_year;
	
	// now check that the start date is not older than today
	if (s_year < t_year) {
		if (!confirm ('The start date ('+sdate+') is before today ('+today+'), \n Do you really want to add a booking starting in the past?')) {
			updateMessage("Correct your Booking details ... ");
			document.bookingForm.startDate.focus(); // put the focus on the form
		} else performBooking(s_year, s_month, sdate, edate, desc, cst);
	} else if ((s_year == t_year) && (s_month < t_month)) {
		if (!confirm ('The start date ('+sdate+') is before today ('+today+'), \n Do you really want to add a booking starting in the past?')) {
			updateMessage("Correct your Booking details ... ");
			document.bookingForm.startDate.focus(); // put the focus on the form
		} else performBooking(s_year, s_month, sdate, edate, desc, cst);
	} else if ((s_year == t_year) && (s_month == t_month) && (s_day < t_day)) {
		if (!confirm ('The start date ('+sdate+') is before today ('+today+'), \n Do you really want to add a booking starting in the past?')) {
			updateMessage("Correct your Booking details ... ");
			document.bookingForm.startDate.focus(); // put the focus on the form
		} else performBooking(s_year, s_month, sdate, edate, desc, cst);
	} else {
		// Preform the booking as everything checks out OK
		performBooking(s_year, s_month, sdate, edate, desc, cst);
	}
}

function performBooking(year, month, sdate, edate, desc, cst) {
	// carry on and perform the booking
	//The location we are loading the page into.
	
	var objID = "messages";
	var serverPage = "includes/handle_booking.inc.php?startDate="+escape(sdate)+"&endDate="+escape(edate)+"&description="+escape(desc)+"&cost="+escape(cst);
	
	var validated = false;
	validated = runAjax(objID,serverPage); // perform the AJAX

	if (validated) {
		// reload the calendar and details
		updateCalendar(year, month);
		updateCalendarDetails(year, month);
	}
}


// handles the validation of the booking request
function editBooking () {
	
	updateMessage("Validating Booking Edit ... "); 

	var sdate = document.bookingForm.startDate.value;
	var edate = document.bookingForm.endDate.value;
	var desc = document.bookingForm.description.value;
	var cst = document.bookingForm.cost.value;
	
	// check the start date exits
	if ((sdate == "") || (sdate.length < 10)) {
		updateMessage("You must have a Start Date in the format (dd/mm/yyyy) ...<br />2 digits for both DAY and MONTH, 4 digits for the YEAR");
		document.bookingForm.startDate.focus(); // put the focus on the form
		return;
	}
	// check the end date exits
	if ((edate == "") || (edate.length < 10)) {
		updateMessage("You must have an End Date in the format (dd/mm/yyyy) ...<br />2 digits for both DAY and MONTH, 4 digits for the YEAR");
		document.bookingForm.endDate.focus(); // put the focus on the form
		return;
	}
	
	// get the seperate parts of the start date
	var s = new Array();
	s = sdate.split('/'); // split the date into an array
	s_day = s[0];
	s_month = s[1];
	s_year = s[2];

	// get the parts of todays date
	var d = new Date();
	var t_day = d.getDate();      // Returns the day of the month
	var t_month = d.getMonth();      // Returns the month as a digit
	t_month++; // account for the month being one less
	
	// now check if month and day are 2 digits if not, add a 0 in front
	if (t_day < 10) {
		t_day.toString();
		t_day = '0' + t_day;
	}
	if (t_month < 10) {
		t_month.toString();
		t_month = '0' + t_month;
	}
	var t_year = d.getFullYear();  // Returns 4 digit year
	var today = t_day + "/" + t_month + "/" + t_year;
	
	// now check that the start date is not older than today
	if (s_year < t_year) {
		if (!confirm ('The start date ('+sdate+') is before today ('+today+'), \n Do you really want to add a booking starting in the past?')) {
			updateMessage("Correct your Booking details ... ");
			document.bookingForm.startDate.focus(); // put the focus on the form
		} else performBookingEdit(s_year, s_month, sdate, edate, desc, cst);
	} else if ((s_year == t_year) && (s_month < t_month)) {
		if (!confirm ('The start date ('+sdate+') is before today ('+today+'), \n Do you really want to add a booking starting in the past?')) {
			updateMessage("Correct your Booking details ... ");
			document.bookingForm.startDate.focus(); // put the focus on the form
		} else performBookingEdit(s_year, s_month, sdate, edate, desc, cst);
	} else if ((s_year == t_year) && (s_month == t_month) && (s_day < t_day)) {
		if (!confirm ('The start date ('+sdate+') is before today ('+today+'), \n Do you really want to add a booking starting in the past?')) {
			updateMessage("Correct your Booking details ... ");
			document.bookingForm.startDate.focus(); // put the focus on the form
		} else performBookingEdit(s_year, s_month, sdate, edate, desc, cst);
	} else {

		// Preform the booking as everything checks out OK
		performBookingEdit(s_year, s_month, sdate, edate, desc, cst, document.bookingForm.id.value);
	}
}

function performBookingEdit(year, month, sdate, edate, desc, cst, ID) {
	// carry on and perform the booking
	updateMessage("Booking Validated, Updating record ("+ID+") in DB ... "); 

	//The location we are loading the page into.
	var objID = "messages";
	var serverPage = "includes/handle_edit_booking.inc.php?startDate="+escape(sdate)+"&endDate="+escape(edate)+"&description="+escape(desc)+"&cost="+escape(cst)+"&ID="+escape(ID);
	
	var validated = false;
	validated = runAjax(objID,serverPage); // perform the AJAX

	if (validated) {
		// reload the calendar and details
		updateCalendar(year, month);
		updateCalendarDetails(year, month);
		displayClearBookingForm();
	}
}


function displayClearBookingForm() {

	//The location we are loading the page into.
	var objID = "addBooking";
	var serverPage = "includes/display_clear_booking.inc.php";
	
	runAjax(objID,serverPage); // perform the AJAX

}


// handles the validation of the booking request
function handleRequest (year, month) {
	
	updateMessage("Sending Request ... "); 

	var sdate = document.requestForm.req_startDate.value;
	var edate = document.requestForm.req_endDate.value;
	var desc = document.requestForm.req_description.value;

	// check the start date exits
	if ((sdate == "") || (sdate.length < 10)) {
		updateMessage("You must have a Start Date in the format (dd/mm/yyyy) ...<br />2 digits for both DAY and MONTH, 4 digits for the YEAR");
		document.requestForm.req_startDate.focus(); // put the focus on the form
		return;
	}
	
	// check the end date exits
	if ((edate == "") || (edate.length < 10)) {
		updateMessage("You must have an End Date in the format (dd/mm/yyyy) ...<br />2 digits for both DAY and MONTH, 4 digits for the YEAR");
		document.requestForm.req_endDate.focus(); // put the focus on the form
		return;
	}

	// Preform the booking as everything checks out OK
	performRequest(year, month, sdate, edate, desc, email);

}

// Gets the form for editing the booking info
function editGetBookingForm (ID) {
	
	//The location we are loading the page into.
	var objID = "addBooking";
	var serverPage = "includes/edit_get_booking.inc.php?ID="+ID;
	
	runAjax(objID,serverPage); // perform the AJAX

}




// Login function

function viewLogin (returnPage){
	
	//The location we are loading the page into.
	var objID = "rightTopContent";
	var serverPage = "includes/login.inc.php?page="+returnPage;
	
	runAjax(objID,serverPage); // perform the AJAX
}




// End AJAX functions
// ----------------------------------------------------------------------------


function logged_in_div_height () {

	var topObject = document.getElementById("rightTopContent");
	var botObject = document.getElementById("rightBottomContent");
	
	topObject.style.height = "100px";
	botObject.style.height = "340px";
	botObject.style.top = "104px";
}


function logged_out_div_height () {

	var topObject = document.getElementById("rightTopContent");
	var botObject = document.getElementById("rightBottomContent");
	
	topObject.style.height = "220px";
	botObject.style.height = "220px";
	botObject.style.top = "224px";
}

// Start Picture Gallery Finctions
// ---------------------------------------------------------------------------

pictureNames = new Array();
pictureNames['mainTopLeft'] = 'ludlow4';
pictureNames['mainBottomLeft'] = 'bedroom1';
pictureNames['mainTopCenter'] = 'familyroom1';
pictureNames['mainBottomCenter'] = 'ludlow3';
pictureNames['mainTopRight'] = 'solarium2';
pictureNames['mainBottomRight'] = 'diningroom1';

pictureText = new Array();
pictureText['mainTopLeft'] = '<p>Ludlow is nestled in the beautiful Marches countryside in Shropshire, England. Everything about the town is picturesque, from the old Norman Castle, the grand tower of St. Lawrence Church, and the 17th century buildings.</p>';
pictureText['mainBottomLeft'] = '<p>Two bedrooms with Queen Beds: one overlooking the garden, and one on the front of the cottage.</p><p>There is also a bedroom up two flights of stairs with a skylight and two single beds.</p>';
pictureText['mainTopCenter'] = '<p>A sitting room with gas fireplace, television, video and DVD, stereo, adjoining conservatory leading to the garden.</p>';
pictureText['mainBottomCenter'] = '<p>Toad Hall is located just outside the Broad Gate, part of the original city wall, on Lower Broad Street.</p><p>All this comfot is located within a 3 minute walk to the center of town where you can explore the old Norman Castle, the bustling farmers market, or the grand tower of St. Lawrence Church with its spectacular view of the countryside.</p>';
pictureText['mainTopRight'] = '<p>In the Garden there are two sheds, two patios, tables and chairs, an herb garden, a pond, and fruit trees.</p>';
pictureText['mainBottomRight'] = '<p>There is a beautiful dining room with gas fireplace, two washrooms, one with a shower and full bathtub, one is a WC on the ground floor.</p><p>Laundry facilities on the ground floor oposite the kitchen which is fully equipped with dishwasher, gas cooker, microwave, refrigerator and freezer.</p>';

bigPicDIV = 'mainBigPic';
bigTextDIV = 'mainPicText';
picTextDIV = 'picTEXT';

bigPicID = 'bigPic';
picSrcRoot = 'images/pics/';
picSrcEnd = '_big.jpg';

function showPic (div) {
	// hide small pics
	for ( var divID in pictureNames) {
		document.getElementById(divID).style.display = 'none';
	}
	// display the big Bic
	document.getElementById(bigPicDIV).style.display = 'block'; // display the image div
	document.getElementById(bigPicID).src = picSrcRoot+pictureNames[div]+picSrcEnd; //set the image source	
	// display the big pics text
	document.getElementById(bigTextDIV).style.display = 'block'; // display the image text div
	document.getElementById(picTextDIV).innerHTML = pictureText[div]; // add in the text
}

function hidePic () {
	// hide small pics
	for ( var divID in pictureNames) {
		document.getElementById(divID).style.display = 'block';
	}
	// hide the big Bic
	document.getElementById(bigPicDIV).style.display = 'none'; // hide the image div
	document.getElementById(bigPicID).src = ''; //reset the image source	
	// hide the big pics text
	document.getElementById(bigTextDIV).style.display = 'none'; // hide the image text div
}
