/** 
 * $Id: appt_setter.js 7645 2010-06-17 15:50:18Z 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)
	{}
	
	loadAppointmentSetter();

}

//---- Load an interstitial page into the overlay.  This has been disabled in favor of going directly to the date/time select due to low appointment set rate
function loadPreamble () {
	
	//---- Get overlay html -- uses 'wsHelperRegionCode' which was set up in the individual LPs & 'ThankYou' page
	var url = 'form_html/preamble.php?region_id='+wsHelperRegionCode+'&first_name='+firstName;
	$('#wrap_overlay').load ( url, wsHelperRegionCode, function() { setupPreamble() } );
	
}


// Shows the overlay and dialog box
function setupPreamble () {

	// 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";

}

//---- Links in the preamble page cause the actual appointment setter to take over the overlay.  They call this function.
function loadAppointmentSetter() {

	//---- Get overlay html -- uses 'wsHelperRegionCode' which was set up in the individual LPs & 'ThankYou' page
	var url = 'form_html/overlay.php?region_id='+wsHelperRegionCode+'&first_name='+firstName;
	if(typeof(isMakeOver)!="undefined"){
		url = url+'&isMakeOver=true';
	}
	$('#wrap_overlay').load ( url, wsHelperRegionCode, function() { setupAppointmentSetter() } );
	
}

//---- Set up things the appointment setter needs after it has been loaded into #wrap_overlay.  Has to happen after it's fully loaded hence the call-back.
function setupAppointmentSetter() {
	
	// Show the overlay (disables rest of page)
	$('#dialogContainer').show();

	//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);

	//only standalone appt setter will use leadSubmitDate

	try {
		$("input[name='hiddenLeadSubmitDate']").val(leadSubmitDate);
	} catch (err) {
	}

}

/* 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+"' onclick='setSelectedTime(this.id,\""+tourIds[i].Time+"\","+tourIds[i].ID+","+tourIds[i].KidsOK+"); return false;'>"+tourIds[i].Time+"&nbsp;&nbsp;</a>\n");
			}
			$("#appointmentDynamicTimes").html ( availableTimesText );
			break;
		}
	}

	//---- Show the select time panel and shrink the club information panel.
	//---- Also set the background of the SELECT DATE header to dark gray and turn on the arrow to guide people to the SELECT TIME panel.
	$("#select-time").show();
	$("#confirmation-form").hide();
	$("#club-information").css ( "width", "294px" );
	$("#club-information").css ( "left", "591px" );
	$("#club-information-header").css ( "width", "304px" );
	$("#club-information-footer").css ( "width", "304px" );
	$('#select-date-header').hide();
	$('#select-time-header').removeClass ( "gray-background" );
	$('#select-time-header').addClass ( "red-background" );
	$('#colOneArrow').show();
	$('#colTwoArrow').hide();

	// HMO only
	$('#hmo-seal').hide();

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

	$('#hiddenDatePretty').val ( oDisplayDate );
	$('#hiddenDate').val ( oKeyDate );
	$('#hiddenTime').val ( '' );
	
	//highlight this item in the Date list
	setSelectedRow ( obj );

}

/* Select more dates.  Essentially jump back to stage 1, where time column and confirmation form aren't there and club information is. */
function selectMoreDates() {
	
	getAvailableTimes(1,0);
	
	$('#select-date-header').show();
	$('#select-time-header').removeClass ( "red-background" );
	$('#select-time-header').addClass ( "gray-background" );
	$('#select-time').hide();
	
	$('#confirmation-form').hide();
	$('#club-information').show();
	$("#club-information").css ( "width", "459px" );
	$("#club-information").css ( "left", "422px" );
	$("#club-information-header").css ( "width", "473px" );
	$("#club-information-footer").css ( "width", "473px" );
	$('#colOneArrow').hide();
	$('#colTwoArrow').hide();
	
}

/* Show the 1st page of dates */
function selectPrevDates() {

	getAvailableTimes(0,1);

	$('#select-date-header').hide();
	$('#select-time-header').removeClass ( "gray-background" );
	$('#select-time-header').addClass ( "red-background" );
	$('#select-time').show();

	$('#confirmation-form').hide();
	$('#club-information').show();
	$("#club-information").css ( "width", "459px" );
	$("#club-information").css ( "left", "422px" );
	$("#club-information-header").css ( "width", "473px" );
	$("#club-information-footer").css ( "width", "473px" );
	$('#colOneArrow').hide();
	$('#colTwoArrow').hide();

}

/* Control the show/hide of various text areas within col 3 */
function selectedSingle ( toggleButton ) {
	
	$('#attendTogether').hide();
	$('#cbox_married').attr ( 'checked', true );

	$('#verifyHeader').show();
	$('#checkboxSection').show();
	$('#captureSpouseName').hide();

	$('#hiddenMaritalStatus').val ( "single" );
	
	$('#cbox_sitter').css ( "top", "0px" );
	$('#cbox_sitter_label').css ( "top", "0px" );
	$('#cbox_time').css ( "top", "70px" );
	$('#cbox_time_label').css ( "top", "70px" );
	$('#cbox_directions').css ( "top", "110px" );
	$('#cbox_directions_label').css ( "top", "110px" );

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

}

function selectedMarried ( toggleButton ) {
	
	$('#verifyHeader').show();
	$('#checkboxSection').show();
	$('#attendTogether').show();
	$('#cbox_married').attr ( 'checked', false );

	$('#hiddenMaritalStatus').val ( "married" );
	if ( ! spouseName ) {
		$('#captureSpouseName').show();
		$('#cbox_sitter').css ( "top", "75px" );
		$('#cbox_sitter_label').css ( "top", "75px" );
		$('#cbox_time').css ( "top", "140px" );
		$('#cbox_time_label').css ( "top", "140px" );
		$('#cbox_directions').css ( "top", "178px" );
		$('#cbox_directions_label').css ( "top", "178px" );
	}
	
	//if requested, en/disable the ApptSetterButton
	if ( toggleButton ) toggleEnableApptSetterButton ( true );
	
}

function displayConfirmationForm () {
	
	$('#confirmation-form').show();
	$('#confirmation-form-header').css ( "width", "304px" );
	$('#confirmation-form-footer').css ( "width", "304px" );
	$('#select-time-header').removeClass ( "red-background" );
	$('#select-time-header').addClass ( "gray-background" );
	$('#colOneArrow').hide();
	$('#colTwoArrow').show();
	if ( spouseName ) {
		selectedMarried ( true );
		$('#maritalStatus').hide();
	} else {
		$('#maritalStatus').show();
	}
	$('#lightbox_submit_btn_off').show();

	//uncheck all checkboxes
	setAllCheckboxes ( false );

	if ( $('#hiddenKidsOK').val() == true ) {
		$('#cbox_sitter').attr ( 'checked', true );
		$('#sitterSection').hide();
	} else {
		$('#cbox_sitter').attr ( 'checked', false );
		$('#sitterSection').show();
	}
	
}

/* Set a Time as selected, and control show/hide of other cols/text/hidden areas */
function setSelectedTime ( obj, Time, TourID, kidsAllowed ) {
	
	$('#club-information').hide();
	
	$('#hiddenTourId').val ( TourID );
	
	// pass through the status of whether or not kids are allowed
	$('#hiddenKidsOK').val ( kidsAllowed );

	displayConfirmationForm();
	toggleEnableApptSetterButton();

	//update the display & form sections for the right time
	$('#hiddenTime').val ( Time );
	$('#appointment-info').html ( "<span id='displayDate'>" + $('#hiddenDatePretty').val() + "</span><br /><span id='displayTime'>" + Time + "</span>" );

	//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("_");

	//clear all other Rows
	for (i=1; i <=15; i++) {
		if ( document.getElementById(types[0]+"_"+i) !== null) {
			$('#' + types[0] + "_" + i ).removeClass ( "red-background");
			$('#' + types[0] + "_" + i ).addClass ( "light-gray-background");
		}
	}
	//set this row
	if (document.getElementById(obj) !== null) {
		$('#' + obj ).removeClass ( "light-gray-background");
		$('#' + obj ).addClass ( "red-background");
	}
	
}

/* 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() {
	
	$('#lightbox_submit_btn_on').show();
	$('#lightbox_submit_btn_on').removeAttr ( 'disabled' );
	
}

function disableSubmitButton () {
	
	$('#lightbox_submit_btn_on').hide();
	$('#lightbox_submit_btn_on').attr ( 'disabled', 'disabled' );
	
}

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

	if ( areAllCheckboxesChecked() ) {
		if ( isSpouseNameEmpty() ) {
			//need to check if married & spouse name not there...
			if ( ($('#hiddenMaritalStatus').val() == "married") && ! spouseName ) {
				//cboxes are all checked, spouse name req'd, but spouse name is blank. Highlight spouse name field
				$('#captureSpouseName').css ( { 'color': "#E83842", 'fontWeight': "bold" } );
				$('#spouseFirst').css ( { 'border': "1px solid red", "backgroundColor": "yellow" } );
				$('#spouseLast').css ( { 'border': "1px solid red", "backgroundColor": "yellow" } );

				if ( ! firstNameWasFocused ) $('#spouseFirst').focus();
				firstNameWasFocused = true;
				disableSubmitButton();
			} else {
				enableSubmitButton();
			}
		} else {
			$('#captureSpouseName').css ( { 'color': "#666" } );
			$('#spouseFirst').css ( { 'border': "1px solid #666", "backgroundColor": "white" } );
			$('#spouseLast').css ( { 'border': "1px solid #666", "backgroundColor": "white" } );
			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 = $('#spouseFirst').val().replace(/^\s+|\s+$/,'');
	if(($('#spouseFirst').val() != null) && (spouseFirstNoSpaces != '') && (spouseFirstNoSpaces.length >= 2)) {
		spouseFirstEmpty = false;
	}
	
	var spouseLastNoSpaces = $('#spouseLast').val().replace(/^\s+|\s+$/,'');
	if(($('#spouseLast').val() != 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 (($('#cbox_married').attr ( 'checked' ) || $('#radio_married').val() == "true") && 
			$('#cbox_sitter').attr ( 'checked' ) &&
			$('#cbox_time').attr ( 'checked' ) &&
			$('#cbox_directions').attr ( 'checked' ) );
	
}

/* set (or clear) value of all (changeable) checkboxes */
function setAllCheckboxes ( blnValue )  {
	
	blnValue = ( blnValue );
	
	$('#cbox_married').attr ( 'checked', blnValue );
	$('#cbox_sitter').attr ( 'checked', blnValue );
	$('#cbox_time').attr ( 'checked', blnValue );
	$('#cbox_directions').attr  ('checked', blnValue );
	
	
}

