$(function() {

		// 	window.$blockedDaysList = false;
		eval (  'window.$holidaysList=' + $('#CarwashHolidays').val() ); // dates blocked
		eval (  'window.$blockedDaysList=' + $('#CarwashBlockedDays').val() ); // days of the week blocked
		eval (  'window.$monthsToShow=' + $('#CarwashMonthsToShow').val() ); // days of the week blocked
		eval (  'window.$daysBeforeNext=' + $('#CarwashDaysBeforeNext').val() );

		eval (  'window.$franchiseTitle="' + $('#CarwashFranchiseTitle').val() + '";' );
		eval (  'window.$franchiseIntro="' + $('#CarwashFranchiseIntro').val() + '";' );

		BookingInit();
	});

function BookingInit() {

	var s = '';
	s += '<div id="BookingFormContainer"></div>';

	s += '<div id="Intro">' + window.$franchiseIntro + '</div>';
	s += '<div id="DateTime">';
	s += '<div id="TimePicker"></div>';

	s += '<div id="DatePicker">';
	s += '<h2>Select A Date</h2>';
	s += '<div id="DatePickerCalendar"></div>';
	s += '</div>';

	s += '<div class="clear"></div>';
	s += '</div>';


	$('#Booking').html(s);

	BookingFormInit();

	// http://stackoverflow.com/questions/677976/jquery-ui-datepicker-disable-specific-days
	$("#DatePickerCalendar").datepicker({
			minDate: +1,
				maxDate: '+' + window.$monthsToShow + 'M',
				beforeShowDay: blockedDays,
				dateFormat: 'yymmdd',
				onSelect: BookingDatePicked
				});	

}

function BookingDatePicked ( date ) {

 	$("#TimePicker span").unbind ( 'click' );
	$("#Intro").hide();
 	$("#TimePicker:hidden").show();
 	$("#BookingError").hide();
	$("#TimePicker").html('<div class="TimePickerLoading"></div>');
	$.getJSON( '/carwash', { franchise_key: $('#CarwashFranchise').val(), view: 'date', date: date },  function(data){
			if ( data == -1 ) {
				return false;
			}
			var s = '';
			s += '<h2>Select A Time</h2>';
			s += '<ul>';
			for ( var i in data.slots ) {
				slot = data.slots[i];
				var booked = false;
				for ( ix in data.booked ) {
					if ( data.booked[ix] === slot ) {
						booked = true;
					}
				}

				if ( booked ) {
					s += '<li><a href="/carwash/' + date + slot + '" rel="booked" class="booked"><span>' + slot.substr(0,2) + ':' + slot.substr(2,2) + '</span></a></li>';
				} else {
					s += '<li><a href="/carwash/' + date + slot + '" rel="' + slot + '" id="slot-' + date + slot + '"><span>' + slot.substr(0,2) + ':' + slot.substr(2,2) + '</span></a></li>';
				}
			}

			s += '</ul>';

 			$("#TimePicker").html(s);

			// clear existing handlers
			$("#TimePicker span").bind ( 'click', function (e) {

					$("#BookingError").hide();
					var t = $(e.target).parent();
					t.blur();
					var time = t.attr('rel');
					if ( 'booked' == time ) {
						return false;
					}

					$('#TimePicker ul li a.active').removeClass('active');
					t.addClass('active');

					$('#datetime').val( date + '' + time );

					var d = $('#datetime').val();
					if ( d != undefined ) {
						$("#BookingForm").show();
						$("#BookingFormContainer").show();

						d = d.substr( 0, 4 ) + '/' + d.substr ( 4, 2 ) + '/' + d.substr ( 6 , 2 ) + ' ' + d.substr( 8, 2 ) + ':' + d.substr ( 10, 2 ) + ':00';
						var myDate = new Date( d );
						$('#BookingFormDate').html( myDate.format ( 'HH:MM, ddd d mmmm yyyy' ) );
						// 				$('#BookingFormDate').html( 'Booking for ' + myDate.format ( 'HH:MM, dddd, mmmm d yyyy' ) );
					}

					// 				});

					return false;

				});

		});

}



function blockedDays(date) {
	
	var fdate = date.format ( 'yyyymmdd' );

	for ( i = 0; i < window.$holidaysList.length; i++ ) {
		if ( fdate == window.$holidaysList[i] ) {
			return [false, ''];
		}
	}

 	var fday = date.format ( 'ddd' );

 	for ( i = 0; i < window.$blockedDaysList.length; i++ ) {
 		if ( fday == window.$blockedDaysList[i] ) {
 			return [false, ''];
 		}
 	}

	return [true, ''];

}

function noWeekendsOrHolidays(date) {
	var noWeekend = $.datepicker.noWeekends(date);
	if (noWeekend[0]) {
		return blockedDays(date);
	} else {
		return noWeekend;
	}
}

function BookingFormInit() {

	var s = '';
	s += "\n";

	s += '<div id="BookingForm">' + "\n";
 	s += '<h2 id="BookingFormDate"></h2>' + "\n";

 	s += '<p>Enter your details to make your booking</p><br />' + "\n";

 	s += '<form action="" method="post">' + "\n";

	s += '<input type="hidden" name="datetime" id="datetime" />' + "\n";

	s += '<p>' + "\n";
	s += '<label for="vehicle_make">Make</label>' + "\n";
	s += '<select name="vehicle_make" id="vehicle_make">' + "\n";
	s += '<option value="lexus">Lexus</option>' + "\n";
	s += '<option value="citroen">Citroen</option>' + "\n";
	s += '</select>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="vehicle_model">Model</label>' + "\n";
	s += '<input type="text" name="vehicle_model" id="vehicle_model" />' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";


	s += '<p>' + "\n";
	s += '<label for="email">Your Email</label>' + "\n";
	s += '<input type="text" name="email" id="email" />' + "\n";
	s += '<span id="email-error"></span>' + "\n";
	s += '</p>' + "\n";

	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="name_given">Given Name</label>' + "\n";
	s += '<input type="text" name="name_given" id="name_given" />' + "\n";
	s += '<span id="name_family-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="name_family">Family Name</label>' + "\n";
	s += '<input type="text" name="name_family" id="name_family" />' + "\n";
	s += '<span id="name_family-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="phone_mobile">Mobile Phone</label>' + "\n";
	s += '<input type="text" name="phone_mobile" id="phone_mobile" />' + "\n";
	s += '<span id="phone_mobile-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";

	s += '<p>' + "\n";
	s += '<label for="phone_mobile">Vehicle Registration</label>' + "\n";
	s += '<input type="text" name="registration" id="registration" />' + "\n";
	s += '<span id="registration-error"></span>' + "\n";
	s += '</p>' + "\n";
	s += '<div class="clear"></div>' + "\n";


	s += '<p>' + "\n";
	s += '<label for="">&nbsp;</label>' + "\n";
	s += '<input type="button" id="BookingSubmit" value="Book Carwash" />' + "\n";
	s += '</p>' + "\n";

 	s += '<br />' + "\n";

 	s += '</form>' + "\n";

	s += '</div>' + "\n";

	s += '<div id="BookingProcessing">' + "\n";
	s += '<span>Making Your Booking...</span>' + "\n";
	s += '</div>' + "\n";

	s += '<div id="BookingProcessed">' + "\n";
	s += '<h2>Your booking is complete</h2>' + "\n";
	s += '<p>You have been emailed details of your booking, and will be notified the evening before the day of your carwash.</p>' + "\n";
	s += '<p>' + "\n";
	s += '<form action="" method="post">' + "\n";
	s += '<input type="button" id="BookingReboot" value="OK" />' + "\n";
	s += '</form>' + "\n";
	s += '</p>' + "\n";
	s += '</div>' + "\n";

	s += '<div id="BookingError">' + "\n";
	s += '<h2></h2>' + "\n";
	s += '<p></p>' + "\n";
	s += '<form action="" method="post">' + "\n";
	s += '<input type="button" id="BookingErrorDismiss" value="OK" />' + "\n";
	s += '</form>' + "\n";
	s += '</div>' + "\n";

	$('#BookingFormContainer').html(s);

	$('#BookingReboot').click ( function () {
			$('#BookingFormContainer').fadeOut( 250 );
			$('#DateTime').fadeOut( 250, function () {
					BookingInit();
				});
		});

 	$('#BookingSubmit').click( function () { 
			$(this).blur(); 
			bookingFormProcess(); 
			return false;
		});

 	$('#email').focus();

}


function bookingFormProcess() {

    if ( ! bookingFormValidate() ) {
        return false;
    }

    var request = {
        m: $('#RPCmodule').val(),
        rpc: 'booking_process',
        franchise_key: $('#CarwashFranchise').val(),
        registration: $('#registration').val(),
        vehicle_make: $('#vehicle_make').val(),
        vehicle_model: $('#vehicle_model').val(),
        name_given: $('#name_given').val(),
        name_family: $('#name_family').val(),
        email: $('#email').val(),
        phone_mobile: $('#phone_mobile').val(),
        datetime: $('#datetime').val()
    };

	$('#BookingForm').fadeOut( 250, function() {
			$('#BookingProcessing').fadeIn( 250, function () {
					$.post( '/index.php', request, function ( response ) {

							// 							log ( response );

							if ( 'booked' == response ) {
								$('#BookingProcessing').fadeOut( function () {
										$('#BookingProcessed').fadeIn();
									});
							} else if ( 'existing' == response.substr ( 0, 8 ) ) {
								response = response.split('|');
								var washAgainAfter = response[1]; // YYYYMMDD of first date user can book from
								bookingFormDialog ( 'existing', washAgainAfter );
								return false;
								// car already has a booking
							} else if ( 'unavailable_datetime' == response ) {
								// date+time is booked out (go back to
								// select time after message
								// dismissed)
								bookingFormDialog ( 'unavailable_datetime', false );
							} else if ( 'unavailable_date' == response ) {
								// date / time is unavailable (go back
								// to select date after message
								// dismissed)
							} else if ( 'quota_exceeded' == response.substr ( 0, 14 ) ) {
								// registration already has a booking or
								// has exceeded quota
								response = response.split('|');
								var washAgainAfter = response[1]; // YYYYMMDD of first date user can book from
								bookingFormDialog ( 'quota_exceeded', washAgainAfter );
							}
						});
				});

			return false;

		});

}

function bookingFormDialog ( message, messageMeta ) {

	$('#BookingProcessing').hide();
 	$('#BookingErrorDismiss').unbind( 'click' );

	if ( 'existing' == message ) {
		$('#BookingError h2').html( 'Your vehicle already has a booking' );
		if ( messageMeta ) {
			var d = messageMeta.substr( 0, 4 ) + '/' + messageMeta.substr ( 4, 2 ) + '/' + messageMeta.substr ( 6 , 2 ) + ' 00' + messageMeta.substr( 8, 2 ) + ':' + messageMeta.substr ( 10, 2 ) + ':00';
			var myDate = new Date( d );
			$('#BookingError p').html( 'We allow one carwash every ' + window.$daysBeforeNext + ' days. Please try again after ' + myDate.format ( 'ddd d mmmm' ) + '.' );
		}
		$('#BookingError').show();

		$('#BookingErrorDismiss').click( function () { 
				$('#BookingError').fadeOut( function() {
						BookingInit();
						return false;
					});
			});

	}

	if ( 'unavailable_datetime' == message ) {
		$('#BookingError h2').html( 'The time you selected is fully booked' );
		$('#BookingError').show();

		$('#BookingErrorDismiss').click( function () { 
				$('#BookingError').fadeOut( function() {
						$('#DateTime').show();
					});
			});
	}

	if ( 'quota_exceeded' == message ) {
		$('#BookingError h2').html( 'You have had a carwash recently' );

		var d = messageMeta.substr( 0, 4 ) + '/' + messageMeta.substr ( 4, 2 ) + '/' + messageMeta.substr ( 6 , 2 ) + ' 00' + messageMeta.substr( 8, 2 ) + ':' + messageMeta.substr ( 10, 2 ) + ':00';
		var myDate = new Date( d );

		$('#BookingError p').html( 'We allow one carwash every ' + window.$daysBeforeNext + ' days. Please try again on or after ' + myDate.format ( 'ddd d mmmm' ) + '.' );

		$('#BookingError').show();

		$('#BookingErrorDismiss').click( function () { 
				$('#BookingError').fadeOut( function() {
						$('#DateTime').show();
					});
			});
	  
	}
	
	$('#BookingError').show();

	// set event handler on dismiss button



	return false;
}


function bookingFormValidate () {

    var valid = true;

    if ( ! $('#phone_mobile').val() ) {
        $('#phone_mobile').addClass( 'invalid' );
        $('#phone_mobile').focus();
        valid = false;
    } else {
        $('#phone_mobile').removeClass( 'invalid' );
    }

    if ( ! $('#name_family').val() ) {
        $('#name_family').addClass( 'invalid' );
        $('#name_family').focus();
        valid = false;
    } else {
        $('#name_family').removeClass( 'invalid' );
    }

    if ( ! $('#name_given').val() ) {
        $('#name_given').addClass( 'invalid' );
        $('#name_given').focus();
        valid = false;
    } else {
        $('#name_given').removeClass( 'invalid' );
    }

    if ( ! $('#registration').val() ) {
        $('#registration').addClass( 'invalid' );
        $('#registration').focus();
        valid = false;
    } else {
        $('#registration').removeClass( 'invalid' );
    }

    if ( ! $('#vehicle_make').val() ) {
        $('#vehicle_make').addClass( 'invalid' );
        $('#vehicle_make').focus();
        valid = false;
    } else {
        $('#vehicle_make').removeClass( 'invalid' );
    }

    if ( ! $('#vehicle_model').val() ) {
        $('#vehicle_model').addClass( 'invalid' );
        $('#vehicle_model').focus();
        valid = false;
    } else {
        $('#vehicle_make').removeClass( 'invalid' );
    }

    if ( ! $('#email').val() || ! validateEmail ( $('#email').val() ) ) {
        $('#email').addClass( 'invalid' );
        $('#email').focus();
        valid = false;
    } else {
        $('#email').removeClass( 'invalid' );
    }

    return valid;

}



function validateEmail(str) {

    var at="@";
    var dot=".";
    var lat=str.indexOf(at);
    var lstr=str.length;
    var ldot=str.indexOf(dot);
    if (str.indexOf(at)==-1) {
        return false;
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) {
        return false;
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) {
        return false;
    }

    if (str.indexOf(at,(lat+1))!=-1) {
        return false;
    }

    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) {
        return false;
    }

    if (str.indexOf(dot,(lat+2))==-1) {
        return false;
    }

    if (str.indexOf(" ") != -1) {
        return false;
    }

    return true;
}

function log ( s ) {
	if ( $('#log').length == 0 ) {
		$('#background').prepend('<div id="log" style="background: #fc0;">-</div>');
	}
	$('#log').html(s);
}

/*
 * http://blog.stevenlevithan.com/archives/date-time-format
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


