/* thanks to http://delete.me.uk/2005/03/iso8601.html for this function */
Date.prototype.setISO8601 = function (string) {
	var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
		"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
		"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
	var d = string.match(new RegExp(regexp));
	
	var offset = 0;
	var date = new Date(d[1], 0, 1);
	
	if (d[3]) { date.setMonth(d[3] - 1); }
	if (d[5]) { date.setDate(d[5]); }
	if (d[7]) { date.setHours(d[7]); }
	if (d[8]) { date.setMinutes(d[8]); }
	if (d[10]) { date.setSeconds(d[10]); }
	if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
	if (d[14]) {
		offset = (Number(d[16]) * 60) + Number(d[17]);
		offset *= ((d[15] == '-') ? 1 : -1);
	}
	
	offset -= date.getTimezoneOffset();
	time = (Number(date) + (offset * 60 * 1000));
	this.setTime(Number(time));
}

jQuery.validator.addMethod("captcha", function(value, element) {
	return value === "human";
}, "Are you human?");

jQuery.validator.addMethod("phoneUK", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, "");
    return this.optional(element) || /^\d+$/.test(phone_number);
}, "Please specify a valid phone number");

jQuery.validator.addMethod("emailList", function(list, element) {
	list = list.split(",");
	var valid = true;
	var emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
	$.each(list, function(i, email) {
		email = $.trim(email);
		if(email && !emailRegex.test(email)) {
			valid = false;
			return false;
		}
	});
	return valid;
}, "Valid emails only please");

function doNothing() {
	return false;
}


function createBookingConfirmationHTML(data) {
	var html = '<h2 class="arrow">Thanks for booking<span>Please check these details are correct:</span><span class="point"></span></h2>' +
	'<div id="bookingConfirmation">' +
		'<p>Hi '+data.organiser_first+' '+data.organiser_last+', you have been emailed the details of your viewing, and one of our team will be in touch to confirm.</p>' +
		'<p>If you need to cancel or rearrange your viewing, please call us on '+data.manager_phone+'.</p>';
		if(data.invitees) {
			html += '<p>You have sent email invitations to the following addresses: '+data.invitees+'</p>';
		}
		html += '<div class="facebook_event panel margintop">' +
			'<img class="grid2col left" src="'+window.template_directory+'/images/property-page/event_icon.png" />' +
			'<a href="#">Why not create a Facebook event and invite your housemates?</a>' +
		'</div>' +
		'<p id="facebookResults"></p>' +
		'<div class="grid3col">' +
			'<h6>Your Booking:</h6>' +
			'<p class="grid1col orange left bold">Address:</p><p class="grid2col right">'+data.property+'</p>' +
			'<br class="clearboth" />' +
			'<p class="grid1col orange left bold">Time:</p><p class="grid2col right">'+data.start_time+'</p>' +
			'<br class="clearboth" />' +
			'<p class="grid1col orange left bold">Date:</p><p class="grid2col right">'+data.date+'</p>' +
			'<br class="clearboth" />' +
		'</div>' +
		'<div id="options">' +
			'<div id="options_name">Viewing at '+data.property+'</div>' +
			'<div id="options_start_time">'+data.iso_start_time+'</div>' +
			'<div id="options_end_time">'+data.iso_end_time+'</div>' +
			'<div id="options_location">'+data.property+', '+data.postcode+', UK</div>' +
			'<div id="options_privacy_type">SECRET</div>' +
		'</div>' +
		'<div id="fb-root"></div>' +
	'</div>';
	return html;
}

function bookingFormInit(elem) {
	/* interaction between big booking button, label and the radio buttons */
	var $bookingForm = $(elem),
		$days = $bookingForm.find('#week div.day'),
		$radios = $bookingForm.find('input[type=radio]');
	$radios.click(function() {
		var iClicked = $radios.index(this);		
			$day = $(this).closest('div.day'),
			start_time = $(this).val(), // e.g. "2010-05-12T15:00:00.000Z"
			i = $days.index($day),
			timeLabel = this.id.replace(/\w/,''),
			d = new Date(),
			d.setISO8601(start_time),
			now = new Date(),
			dayDiff = d.getDate() - now.getDate(),
			monthDiff = d.getMonth() - now.getMonth(),
			yearDiff = d.getYear() - now.getYear(),
			dayLabel = "";
		
		if(iClicked===0) {
			$bookingForm.find('#earlierSlot').addClass('unclickable');
		} else if(iClicked===$radios.length-1) {
			$bookingForm.find('#laterSlot').addClass('unclickable');
		} else {
			$bookingForm.find('#earlierSlot, #laterSlot').removeClass('unclickable');
		}
		
		if(monthDiff===0 && yearDiff===0) {
			if(dayDiff===0) {
				dayLabel = "Today";
			} else if(dayDiff===1) {
				dayLabel = "Tomorrow";
			} else {
				dayLabel = start_time.substring(8,10)+"/"+start_time.substring(5,7);
			}
		} else {
			dayLabel = start_time.substring(8,10)+"/"+start_time.substring(5,7);
		}
		$bookingForm.find('#bookSlot').val("Click to book "+timeLabel+" "+dayLabel);
	});
	$bookingForm.find('span.radio').live("click", function() {
		$(this).next().click();
	});
	
	/* earlier/later buttons */
	$bookingForm.find('#earlierSlot, #laterSlot').click(function(e) {
		e.preventDefault();
		
		if($(this).hasClass('unclickable')) {
			return false;
		}

		var direction = this.id === 'earlierSlot' ? -1 : 1,
			i = $radios.index($radios.filter(':checked'));
		i += direction;
		$radios.eq(i).click();
	});
	
	// select the first slot
	$radios.eq(0).click();
	$bookingForm.find("#bookingSystem").validate({
		rules: {
			student_email2: {
				equalTo: $bookingForm.find("#email")
			}
		},
		showErrors: function(errorMap, errorList) {

			// mainly copied from jquery.validate.js
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
				this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow = this.toShow.add( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
				}
			}
			this.toHide = this.toHide.not( this.toShow );
			this.hideErrors();
			this.addWrapper( this.toShow ).show();
			
			var widthAdjustment = 16;
			
			$bookingForm.find("label.error")
				.each(function() {
					var $label = $(this);
					if(!isNaN(parseInt($label.css('left'),10))) {
						$label.css('left', -(parseInt($label.width(),10)+widthAdjustment)+"px");
					} else {
						$label.css('right', -(parseInt($label.width(),10)+widthAdjustment)+"px");
					}
				});
		},
		submitHandler: function(form) {
			doNothing.savedParams = {
				buttonVal: $bookingForm.find('#bookSlot').val()
			};

			$bookingForm.find('#bookSlot')
				.bind("click", doNothing)
				.css({
					'cursor':'default',
					'background-position':'0 -100px'
				})
				.val("Please wait...");

			/* booking system expects:
				$property_id,
				$viewing_time,
				$organiser_email,
				$organiser_first,
				$organiser_last,
				$organiser_phone,
				$invitees
			*/
			var data = {
				action: 			'hmfs_save_viewing',
				property_id:		$bookingForm.find('#property_id').val(),	
				organiser_email:	$bookingForm.find('#email').val(),
				viewing_time:		$bookingForm.find('#bookingSystem input[type=radio]:checked').val(),
				organiser_first:	$bookingForm.find('#first_name').val(),
				organiser_last:		$bookingForm.find('#last_name').val(),
				organiser_phone:	$bookingForm.find('#phone').val(),
				invitees:			$bookingForm.find('#invite').val()
			};
			
			$.ajax({
				url: window.bookingSystemAction+'?r=' +Math.floor(Math.random()*10000),
				type: 'post',
				data: data,
				success: function(response) {
					var html,
						d,
						end_time;
					if(response && response==="error") {
						$bookingForm.find('#bookSlot')
							.unbind('click', doNothing)
							.css({
								'cursor':'pointer',
								'background-position':'0 -40px'
							})
							.val(doNothing.savedParams.buttonVal);
					} else {
						d = new Date(data.viewing_time);
						end_time = d.clone().add(parseInt($bookingForm.find('#viewing_length').val(),10)).minutes();
						data.manager_phone = "0800 910 1171"; // JRL - this should be a setting
						data.property = $bookingForm.find('#address').val();
						data.postcode = $bookingForm.find('#postcode').val();
						// Facebook doesn't want timezones, so this removal of the Z timezone forces these bookings to be interpreted as local time
						data.iso_start_time = (new Date(data.viewing_time)).toISOString().replace("Z","");
						data.iso_end_time = end_time.toISOString().replace("Z", "");
						data.start_time = d.toString("HH:mm");
						data.date = d.toString("dddd d")+d.getOrdinal()+d.toString(" MMMM");
						html = createBookingConfirmationHTML(data);
						$bookingForm.html(html);
						// now add the facebook_event script in
						$.getScript(window.template_directory+'/js/facebook_event.js', function() {
							loadFacebookScript();
						});
					}
				},
				error: function() {
					$bookingForm.find('#bookSlot')
						.unbind('click', doNothing)
						.css({
							'cursor':'pointer',
							'background-position':'0 -40px'
						})
						.val(doNothing.savedParams.buttonVal);
					if('console' in window && console.log) {
						console.log(arguments);
					}
				}	
			});
		}
	});
	
	// all slots
	$bookingForm.find('#seeAll').hoverIntent(function() {
		var okToCloseFromClick = false;
		if(!$bookingForm.find('#allSlots').is(":visible")) {
			$bookingForm.find('#allSlots').show();
			$(document).bind('click.allSlots', function(e) {
				if('which' in e) { // check this is a real mouse click
					if($(e.target).parents('#allSlots').length || (e.target.id==="seeAll" && okToCloseFromClick)) {
						$(document).unbind('click.allSlots');
						window.setTimeout(function() {
							$bookingForm.find('#allSlots').hide();
						}, 300);
					}
				}			
			});
			window.setTimeout(function() {
				okToCloseFromClick = true;
			}, 600);
		}
	}, function() {
		
	});
}


$(document).ready(function() {
	$('div.bookingForm').each(function() {
		bookingFormInit(this);
	});
});

