/** 
 * $Id: appt_setter.js 3786 2009-08-05 21:09:13Z morouxshi $
 *
 * Main control of appt setter 'overlay'.
 *
 * Controls field show/hide, as well as enabling/disabling cboxes & buttons, populating fields based on user selections.
 * Tested as working on IE7/IE6 on PC and FF on Mac (Safari has minor issues, but not worth the time)
 *
 * This overlay is commonly known as a "lightbox"
 *
 * @author rICh <rich@intermundomedia.com>, free beachler <fbeachler@gmail.com>
 * depends on Prototype.js
**/

//used across functions.
var spouseName = '';
var isMarried = false;
var firstNameWasFocused = false; //used to disable focus of FirstName field (should only happen once)

/**
  * Check for variable
  */

function isdefined(variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

/**
  * Hide/Show overlay code
  */
function getOverlay()  {

	// Disable the expose
	try {
		$("#right").expose({api: true}).close();
	}
	catch(err)
	{}

	//get overlay html -- uses 'wsHelperRegionCode' which was set up in the individual LPs & 'ThankYou' page
	var url = 'form_html/overlay.php?region_id='+wsHelperRegionCode;
	$('#wrap_overlay').load(url,wsHelperRegionCode,function (){loadOverlay()});
}

// Shows the overlay and dialog box
function loadOverlay() {
	// Show the overlay (disables rest of page)
	$('#dialogContainer').show();

	// scroll underlying window to top,left so that overlay (and grey) displays correctly
	window.top.scroll(0,0);

	// All code below required for correct overlay by IE6. Seems to be ignored by other browsers
    bod = document.getElementsByTagName('body')[0];
    bod.style.height = "100%";
    bod.style.overflow = "hidden";
	
    htm = document.getElementsByTagName('html')[0];
    htm.style.height = "100%";
    htm.style.overflow = "hidden";
	
	//create cookie and get 1st set of available Times
	createCookie('set_appt','true',1);
	getAvailableTimes(0,0);
	//maintain passed in vals
	$("input[name='hiddenLeadId']").val(appointmentId);
	$("input[name='hiddenPostcode']").val(postcode);
}

/*
 * Hide/Show columns code
 */
function showColumn(obj) {
	var element = document.getElementById(obj);
	element.style.display = '';
}

function hideColumn(obj) {
	var element = document.getElementById(obj);
	element.style.display = 'none';
}

/* Set a date as selected, and control show/hide of other cols/text/hidden areas */
function setSelectedDate(obj,oKeyDate) {
	//populate the times with the dynamic results corresponding to the selected date
	var availableTimesText = '';
	var tourIds = [];
	var kidsAllowed = 0;
	var kidsAge = 12; // most are 12, just default it
	for (i=0; i<datesArray.length; i++) {
		if (datesArray[i].Date == oKeyDate) {
			oDisplayDate = datesArray[i].DateDisplay;
			tourIds = datesArray[i].Tours;
			kidsAge = datesArray[i].KidsAge;
			var availableTimeCount = 0;
			for (i=0; i<tourIds.length; i++) {
				availableTimeCount = i + 1;
				availableTimesText += ("<a  id='time_"+availableTimeCount+"' style='display:block;cursor:pointer' onclick='setSelectedTime(this.id,\""+tourIds[i].Time+"\","+tourIds[i].ID+","+tourIds[i].KidsOK+"); return false;'>"+tourIds[i].Time+"&nbsp;&nbsp;</a>\n");
			}
			document.getElementById("appointmentDynamicTimes").innerHTML = availableTimesText;
			break;
		}
	}

	// show 2nd column & hide the Third
	showColumn("columnTwo");
	hideColumn("columnThree");
	showColumn("columnFour");

	//clear out the time selections
	setSelectedRow("time_0");

	//update the display KidsAge fields
	document.getElementById('displayKidsAge').innerHTML = kidsAge;
	
	//update the display & hidden sections for the right date
	document.getElementById('displayDate').innerHTML = oDisplayDate.replace(', ','<br />');
	document.getElementsByName('hiddenDate')[0].value = oKeyDate;

	//show the arrow next to Col1, hide the arrow next to col2
	document.getElementById('colOneArrow').style.left = "222px";
	document.getElementById('colTwoArrow').style.left = "-2000px";
	
	//highlight this item in the Date list
	setSelectedRow(obj);
}

/* Select more dates */
function selectMoreDates() {
	getAvailableTimes(1,0);
	hideColumn('columnTwo');
	document.getElementById('colOneArrow').style.left = '-2000px';
	hideColumn('columnThree');
	showColumn('columnFour');
	document.getElementById('colTwoArrow').style.left = '-2000px';
}

/* Show the 1st page of dates */
function selectPrevDates() {
	getAvailableTimes(0,1);
	hideColumn('columnTwo');
	document.getElementById('colOneArrow').style.left = '-2000px';
	hideColumn('columnThree');
	showColumn('columnFour');
	document.getElementById('colTwoArrow').style.left = '-2000px';
}

/* Control the show/hide of various text areas within col 3 */
function controlColumnThree(toggleButton) {
	//get value of 'radio_married' radio control to determine if married or not
	var selectedMaritalStatus = false;
	
	isMarried = document.getElementsByName('radio_married')[1].checked;
	if((document.getElementsByName('radio_married')[0].checked) || document.getElementsByName('radio_married')[1].checked) {
		selectedMaritalStatus = true;
	}

	//show/hide of marital status question. On Hide, also display all of the other relevant sections.
	//if they are married (as determined by cbox or by entering Spouse on lead form), display the 'verifySpouse' booking point.
	if(isMarried || spouseName) {
		document.getElementById('attendTogether').style.display= '';
		document.getElementById('cbox_married').checked = false;
	} else {
		document.getElementById('attendTogether').style.display= 'none';
		document.getElementById('cbox_married').checked = true;
	}

	//if they are married, but we didn't capture spouse name on Lead Form, prompt for it
	if(isMarried && !spouseName) {
		document.getElementById('captureSpouseName').style.display = '';
	} else {
		document.getElementById('captureSpouseName').style.display = 'none';
	}

	//if they passed in spouse name -OR- they selected married, don't bother asking for marital status -AND-
	// adjust cboxSection top. This is being kept separate from the conditional above as it may get rolled back.
	// DirectBuy is demanding this be enabled although IMM thinks it a bad idea...
	if(isMarried || spouseName) {
		document.getElementById('maritalStatus').style.display= 'none';
		document.getElementById('checkboxSection').style.top = '50px';
	} else {
		document.getElementById('maritalStatus').style.display= '';
	}

	//if they stated marital status, go ahead & display the 'verify' cbox sections.
	if(spouseName || selectedMaritalStatus) {
		document.getElementById('verifyHeader').style.display= '';
		document.getElementById('checkboxSection').style.display= '';
	} else {
		document.getElementById('verifyHeader').style.display= 'none';
		document.getElementById('checkboxSection').style.display= 'none';
	}

	//if requested, en/disable the ApptSetterButton
	if(toggleButton) {
		toggleEnableApptSetterButton();
	}
}

/* Set a Time as selected, and control show/hide of other cols/text/hidden areas */
function setSelectedTime(obj,Time,TourID,kidsAllowed) {
	//control the layout of the content
	controlColumnThree(false);

	document.getElementsByName('hiddenTourId')[0].value = TourID;
	//hide (and check) /show the 'babysitting' checkbox if 'kidsAllowed' is turned on/off 
	if (kidsAllowed) {
		document.getElementById('cbox_sitter').checked = true;
		document.getElementById('sitterSection').style.display = 'none';
	} else {
		document.getElementById('cbox_sitter').checked = false;
		document.getElementById('sitterSection').style.display = '';
	}
	//and pass through the status of whether or not kids are allowed
	document.getElementsByName('hiddenKidsOK')[0].value = kidsAllowed;

	//show 3rd Column
	showColumn("columnThree");
	hideColumn("columnFour");
	//uncheck all checkboxes
	setAllCheckboxes(false);
	//disable submit btn
	toggleEnableApptSetterButton();

	//update the display & form sections for the right time
	document.getElementById('displayTime').innerHTML = Time;
	document.getElementsByName('hiddenTime')[0].value = Time;

	//show the arrow next to Col1, hide the arrow next to col2
	document.getElementById('colTwoArrow').style.left = "372px";

	//highlight this item in the Time list
	setSelectedRow(obj);
}

/* helper function for setSelectedDate/Time functions. Sets BG color of selected row only */
function setSelectedRow(obj) {
	var types = obj.split("_");
	var i = 1;
	//clear all other Rows
	for (i=1; i <=15; i++) {
		if (document.getElementById(types[0]+"_"+i) !== null) {
			document.getElementById(types[0]+"_"+i).style.backgroundColor="#000";
		}
	}
	//set this row
	if (document.getElementById(obj) !== null) {
		document.getElementById(obj).style.backgroundColor="#D00";
	}
}

/* boilerplate cookie write function */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days *24 *60 *60 *1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/* boilerplate cookie read function */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// Helper functions for 'toggleEnableApptSetterButton'
function enableSubmitButton() {
	document.getElementById('lightbox_submit_btn_on').style.left = "32px";
	document.getElementById('lightbox_submit_btn_off').style.left = "-2000px";
	document.getElementById('lightbox_submit_btn_on').disabled = false;
}

function disableSubmitButton() {
	document.getElementById('lightbox_submit_btn_on').style.left = "-2000px";
	document.getElementById('lightbox_submit_btn_off').style.left = "32px";
	document.getElementById('lightbox_submit_btn_on').disabled = true;
}

// Only enable the "set appointment" button if all 4 checkboxes are checked
function toggleEnableApptSetterButton() {
	//ucthe first/last values on key up
	document.getElementById('spouseFirst').value = ucwords(document.getElementById('spouseFirst').value);
	document.getElementById('spouseLast').value = ucwords(document.getElementById('spouseLast').value);

	if (areAllCheckboxesChecked()) {
		if(isSpouseNameEmpty()) {
			//need to check if married & spouse name not there...
			if(isMarried && !spouseName) {
				//cboxes are all checked, spouse name req'd, but spouse name is blank. Highlight spouse name field
				document.getElementById('captureSpouseName').style.color = "#F00";
				document.getElementById('captureSpouseName').style.fontWeight = "bold";
				document.getElementById('spouseFirst').style.border = "1px solid red";
				document.getElementById('spouseLast').style.border = "1px solid red";

				if(!firstNameWasFocused) {
					spouseFirst.focus();
				}
				firstNameWasFocused = true;

				disableSubmitButton();
			} else {
				enableSubmitButton();
			}
		} else {
			document.getElementById('captureSpouseName').style.color = "#000";
			document.getElementById('captureSpouseName').style.fontWeight = "";
			document.getElementById('spouseFirst').style.border = "1px solid black";
			document.getElementById('spouseLast').style.border = "1px solid black";
			enableSubmitButton();
		}
	} else {
		disableSubmitButton();
	}
}

/* capitalzie the first letter of each word in string (Helper function for toggleEnableApptSetterButton) */
function ucwords( str ) {
    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase ( ); } );
}

/* return whether or not the Appt Setter spouse name has been filled out */
function isSpouseNameEmpty() {
	var spouseFirstEmpty = true;
	var spouseLastEmpty = true;

	var spouseFirstNoSpaces = document.getElementById('spouseFirst').value.replace(/^\s+|\s+$/,'');
	if((document.getElementById('spouseFirst') != null) && (spouseFirstNoSpaces != '') && (spouseFirstNoSpaces.length >= 2)) {
		spouseFirstEmpty = false;
	}
	
	var spouseLastNoSpaces = document.getElementById('spouseLast').value.replace(/^\s+|\s+$/,'');
	if((document.getElementById('spouseLast') != null) && (spouseLastNoSpaces != '') && (spouseLastNoSpaces.length >= 2)) {
		spouseLastEmpty = false;
	}
	//first must be filled. Last is assumed to be same
	return (spouseFirstEmpty || spouseLastEmpty);
}

/* return whether or not all 'verify' required cboxes are checked */
function areAllCheckboxesChecked()  {
	return (document.getElementById('cbox_married').checked && 
	   document.getElementById('cbox_sitter').checked &&
	   document.getElementById('cbox_time').checked &&
	   document.getElementById('cbox_directions').checked);
}

/* set (or clear) value of all (changeable) checkboxes */
function setAllCheckboxes(value)  {
	value = (value);	//type-safe cast
	document.getElementById('cbox_time').checked = value;
	document.getElementById('cbox_directions').checked = value;
}

