/*
	Javascript code written by PSLWeb.co.uk for Humble Cake (www.humblecake.co.uk)
	Copyright ©2007 PSLWeb.co.uk - All Rights Rerserved
*/
/*
Change Log
----------

071119 - Removed Cheque processing calendar
*/

var tmpImg = new Image; // Pre-load images
tmpImg.src = "images/misc/cal_arrow_l.gif";
tmpImg.src = "images/misc/cal_arrow_r.gif";
tmpImg.src = "images/misc/cal_arrow_l_over.gif";
tmpImg.src = "images/misc/cal_arrow_r_over.gif";
tmpImg.src = "images/misc/null_arrow.gif";
var calData = new Array();
var showMonths = 0;
var existingPaymentMethod = "";

/*
	Function:    swapImg
	Inputs:      img: Object - the image object whose image we're going to swap
				 leftImg: Bool - if this the left image (TRUE) or right image (FALSE)
				 overImg: Bool - If TRUE then change to 'Over' image, restore if FALSE
	Called From: Dynamically written Javascript (the calendar left/right images)
	Description: Creates an image rollover for the left/right arrow images on the calendar.
*/
function swapImg(img, LeftImg, OverImg) {
	if (LeftImg)
		img.src = (OverImg) ? "../images/misc/cal_arrow_l_over.gif" : "../images/misc/cal_arrow_l.gif";
	else
		img.src = (OverImg) ? "../images/misc/cal_arrow_r_over.gif" : "../images/misc/cal_arrow_r.gif";
}

/*
	Function:    selectCalendar
	Inputs:      caller: String - Values are '' | 'PP' | 'CH'
	Called From: Form Field 'PaymentMethod' (onclick event) or Initialise
	Description: Decides which calendar to display based on selected payment method.
*/
function selectCalendar(caller) {
	var payMethod = document.getElementById('paymentMethodPP'); // Get PayPal radial button
	// CL-071119 Start
	var showCalendar = document.getElementById('showCalendar');
	var calFieldText = document.getElementById('calFieldText');
	// CL-071119 End
	if (payMethod.checked) { // If PayPal selected
		calData = calDataPP; // Reference PP data
		showMonths = showMonthsPP;
		newOpt = 'PP';
		// CL-071119 Start
		showCalendar.style.display = 'block';
		calFieldText.innerHTML = "Please note that cakes will be <strong>dispatched</strong> on the selected date and will be <strong>delivered 1-2 days later</strong>. " +
				"For addresses with postcode NR34, NR35, IP19, IP20 cakes will be delivered on the day selected.";
		// CL-071119 End
	}
	else { // Cheque selected
		calData = calDataCH; // Reference CH data
		showMonths = showMonthsCH;
		newOpt = 'CH';
		// CL-071119 Start
		showCalendar.style.display = 'none';
		calFieldText.innerHTML = "Please telephone to arrange a dispatch date (after confirming your order and receiving your confirmation email). Cakes will be <strong>delivered 1-2 days later</strong>.";
		// CL-071119 End
	}
	// If called from initialisation (caller == "") or we have changed the payment method
	if ((caller == "") || (existingPaymentMethod != newOpt)) {
		existingPaymentMethod = newOpt;
		calPos = 0; // Reset calendar month back to first month
		var disDateSel = document.getElementById('dispatchDate');
		disDateSel.selectedIndex = 0; // Reset SELECT field
		if (newOpt == 'PP') { // If now PayPal
			nowYear = parseInt(calDataPPBase.substr(0, 4), 10);
			nowMonth = parseInt(calDataPPBase.substr(4, 2), 10);
		}
		else { // Cheque
			nowYear = parseInt(calDataCHBase.substr(0, 4), 10);
			nowMonth = parseInt(calDataCHBase.substr(4, 2), 10);
		}
		setDateText(); // Re-display Date Text
	}
	drawCalendar(nowYear, nowMonth); // Re-draw calendar
}

/*
	Function:    drawCalendar
	Inputs:      year: Integer - the (four digit) year for the calendar
				 month: Integer - the month for the calendar
	Called From: Initialize, nextMonth, prevMonth
	Description: Creates a dynamically written calendar for the given year/month. Calendar is
				written to a DIV with an ID = 'calendar'.
*/
function drawCalendar(year, month) {
	var idx = year * 100 + month; // Index for CalHTML
	var monthName = calData[idx][0];
	var calHTML = "<table cellspacing=\"0\" summary=\"This table shows which days of the " +
			"month " + monthName + " " + year + ", are available to book.\"><tr>" +
			"<td id=\"calTitle\" colspan=\"7\">";
	if (calPos > 0) // If there are possible previous months show 'previous' arrow
		calHTML += "<div class=\"arrowLeft\"><a href=\"javascript:prevMonth();\">" +
				"<img src=\"../images/misc/cal_arrow_l.gif\" width=\"20\" height=\"20\" " +
				"alt=\"Previous Month\" onmouseover=\"swapImg(this, true, true);\" " +
				"onmouseout=\"swapImg(this, true, false);\" /></a></div>";
	else
		calHTML += "<div class=\"arrowLeft\"><img src=\"../images/misc/null_arrow.gif\" " +
				"width=\"20\" height=\"20\" alt=\"\" /></div>";
	if (calPos < showMonths - 1) // If there are possible next months show 'next' arrow
		calHTML += "<div class=\"arrowRight\"><a href=\"javascript:nextMonth();\">" +
				"<img src=\"../images/misc/cal_arrow_r.gif\" width=\"20\" height=\"20\" " +
				"alt=\"Next Month\" onmouseover=\"swapImg(this, false, true);\" " +
				"onmouseout=\"swapImg(this, false, false);\" /></a></div>";
	else
		calHTML += "<div class=\"arrowRight\"><img src=\"../images/misc/null_arrow.gif\" " +
				"width=\"20\" height=\"20\" alt=\"\" /></div>";
	calHTML += "<span>" + monthName + "&nbsp;" + year + "</span></td></tr><tr><th>S</th>" +
			"<th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>";
	var day = calData[idx][1]; // Day offset
	var daysInMonth = calData[idx][2]; // Days in Month
	var i = 0;
	var today = "";
	while (day <= daysInMonth) {
		calHTML += "<tr>";
		calHTMLTemp = "";
		for (i = 1; i <= 7; i++) {
			if ((day > 0) && (day <= daysInMonth)) { // Is this day in range?
				//today = dataVal + day; // Generate 8 char data value	
				if (calData[idx][(day + 2)]) // This day is postal day
					calHTML += "<td><a href=\"javascript:setDatVal(" + day + ");\">" + day + "</a></td>";
				else // This day is NOT a postal day
					calHTML += "<td><p>" + day + "</p></td>";
			}
			else // This day is blank (greyed out on the calendar)
				calHTML += "<td class=\"nullCell\">&nbsp;</td>";
			day++; // Increment day
		}
		calHTML += "</tr>";
	}
	calHTML += "</table>\n";
	var calDiv = document.getElementById('calendar');
	calDiv.innerHTML = calHTML;
}

/*
	Function:    setDateText
	Inputs:      None
	Called From: setDatVal and selectCalendar
	Description: Sets the text on the form to match the date selected in the SELECT field.
*/
function setDateText() {
	var idx = document.getElementById('dispatchDate').selectedIndex;
	var disDateText = document.getElementById('dispatchDate').options[idx].text;
	disDateText = disDateText.replace('(PayPal Only)', '');
	document.getElementById('printDisDate').childNodes[0].nodeValue = disDateText;
}

/*
	Function:    setDatVal
	Inputs:      day: Integer - the day in the calendar month that has been selected from the calendar
	Called From: Dynamically written Javascript (the calendar clickable dates)
	Description: Sets the value of the SELECT field 'dispatchDate'.
*/
function setDatVal(day) {
	var disDateVal = nowYear * 10000 + nowMonth * 100 + day; // Value for SELECT field
	var disDateSel = document.getElementById('dispatchDate');
	disDateSel.value = disDateVal;
	setDateText(); // Re-display Date Text
}

/*
	Function:    prevMonth
	Inputs:      None
	Called From: Dynamically written Javascript (the calendar left arrow image)
	Description: Decrements the month/year and re-displays the calendar.
*/
function prevMonth() {
	if (calPos > 0) { // Can we show another month?
		calPos--;
		nowMonth--;
		if (nowMonth == 0) {
			nowYear--;
			nowMonth = 12;
		}
		drawCalendar(nowYear, nowMonth);
	}
}

/*
	Function:    nextMonth
	Inputs:      None
	Called From: Dynamically written Javascript (the calendar right arrow image)
	Description: Increments the month/year and re-displays the calendar.
*/
function nextMonth() {
	if (calPos < showMonths - 1) { // Can we show another month?
		calPos++;
		nowMonth++;
		if (nowMonth > 12) {
			nowYear++;
			nowMonth = 1;
		}
		drawCalendar(nowYear, nowMonth);
	}
}

/*
	Function:    redisplayCalendar();
	Inputs:      None
	Called From: initialiseCalendar (effectively the BODY onload event)
	Description: Checks the hidden variable 'disDateRedisplay' to see if it's populated. If it is
				then this form is being re-displayed (e.g. a server-side form error was found) and
				we want to pick the previously set Display Date (if set) and force the calendar to
				default to this value.
*/
function redisplayCalendar() {
	var disDateReVal = document.getElementById('disDateRedisplay').value;
	if (disDateReVal != "") { // If we have a date to re-display
		nowYear = parseInt(disDateReVal.substr(0, 4), 10);
		nowMonth = parseInt(disDateReVal.substr(4, 2), 10);
		var day = parseInt(disDateReVal.substr(6, 2), 10);
		drawCalendar(nowYear, nowMonth);
		setDatVal(day);
	}
}

/*
	Function:    initialiseCalendar();
	Inputs:      None
	Called From: setFocus (effectively the BODY onload event)
	Description: Displays the calendar.
*/
function initialiseCalendar() {
	document.getElementById('printDisDate').style.display = 'block';
	document.getElementById('dispatchDate').style.display = 'none';
	document.getElementById('calendar').style.display = 'block';
	existingPaymentMethod = (document.getElementById('paymentMethodPP').checked) ? 'PP' : 'CH';
	selectCalendar('');
	redisplayCalendar();
}

/*
	Function:    validate
	Called From: join.php form memberForm Submit button (onsubmit method)
	Description: Checks all required form fields to see if any are blank. If so then it highlights
					the Label text and sets the focus to that field (bottom up). Form submission is
					aborted if any fields are in error.
*/
function validate() {
	var userForm = document.getElementById('catOrderForm');
	var errorFound = false; // Assume no error found
	// List of all compulsory fields
	var payMethod = document.getElementById('paymentMethodPP'); // Get PayPal radial button
	if (payMethod.checked) // PayPal payment
		var fields = new Array('name', 'address', 'postcode', 'telephone', 'email', 'dispatchDate');
	else // Cheque payment
		var fields = new Array('name', 'address', 'postcode', 'telephone', 'email');
	// Count backwards so we highlight first field in error on the form
	for (i = fields.length - 1; i >= 0; i--) {
		x = fields[i]; // Get this field name
		if (userForm[x].value == '') { // Is it blank?
			if (x != 'dispatchDate')
				userForm[x].focus(); // Set the focus here if it's not the dispatchdate field
			document.getElementById(x + 'Label').className = 'error'; // Label text shows error class
			errorFound = true;
		}
		else
			document.getElementById(x + 'Label').className = ''; // If no error clear error class
	}
	if (errorFound) { // Pop-up error window
		alert("Please complete required form fields");
		return false;
	}
	else
		return true;
}

/*
	Function:    setFocus
	Inputs:      fieldIdfr: integer denoting the field in error (top down)
	Called From: Body element (onload method) - only if server-side form validation error detected
	Description: Sets the focus to the first field that server-side code has detected as being in
					error.
*/
function setFocus(fieldIdfr) {
	if (fieldIdfr > 0) { // If server-side script sets error field
		var userForm = document.getElementById('catOrderForm');
		if (fieldIdfr == 19)
			fieldIdfr = 20;
		if (fieldIdfr >= 20) { // If this is a cake row in error
			var x = 'quantity[' + String(fieldIdfr - 20) + ']';
			if (userForm[x])
				userForm[x].focus(); // Set the focus
		}
		else { // The error is in the User details area
			var fields = new Array('null', 'name', 'company', 'address', 'postcode', 'telephone',
					'null', 'email', 'deliveryAddress', 'deliveryPostcode', 'null', 'null',
					'null', 'comments', 'deliveryName', 'paymentMethod', 'null', 'cakeInst');
			x = fields[fieldIdfr]; // Get the field name in error
			if (x != 'null') // Set the focus if field is not null
				userForm[x].focus(); // Set the focus
		}
	}
	initialiseCalendar('');
}
