/**
 * Availability page dynamic behaviour
 */

SHORT_BREAK_PERCENTAGE = 60; // Percentage of full weekly price for short breaks

$(document).ready(function(){
	
	// Create popup lightboxes
	$('a.popup').each(function(){
		window.$(this).colorbox({href:this.href, maxWidth:"100%"})
	});
	
	// Create booking options lightboxes
	$('#availability button').each(function(){
		var b = window.$(this);
		var id = this.id.split('-')[1];
		b.colorbox({
			inline: true,
			href: "#bookingForm-" + id,
			width:"800px",
			height: "500px",
			onComplete: onOpenBookingBox
		});
	});
	
	//Add listeners to update booking forms when inputs are changed
	$('.bookingForm input[type=radio]').bind('change', onBookingInputChange)
	$('.bookingForm input[type=radio]').bind('click', onBookingInputChange)
		
});

/**
 * @method onOpenBookingBox
 * Called on opening booking lightbox. Resets form to default values.
 */
function onOpenBookingBox() {
	var f = window.$("#bookingForm-" + this.id.split('-')[1])[0];
	
	checkFirstRadio(f.duration);
	checkFirstRadio(f.payment_type);
	
	updateBookingForm(f);
}

/**
 * @method onBookingInputChange
 * Called on changing an input value in a booking form. Updates prices and description in the form
 */
function onBookingInputChange() {
	updateBookingForm(this.form);
}


/**
 * @method updateBookingForm
 * Updates booking form by calculating price and description based on currently selected options
 * @param {Element} form DOM form element to update
 */
function updateBookingForm(form) {
	// Calculate price and description
	var price = form.full_price.value;
	var desc;
	
	var duration = getRadioValue(form.duration);
	var pt = getRadioValue(form.payment_type);
	
	if (duration.val != "week") {
		price = price * (SHORT_BREAK_PERCENTAGE/100);		
	}
	
	desc = " for " + form.cottage_name.value + " for " + duration.text;
		
	if (pt.val == "deposit") {
		price = price/3;
		desc = "1/3 Deposit" + desc;		
	}else {
		desc = "Full Payment" + desc;
	}
	price = Math.round(price*100)/100;
	
	// Set new price
	form.amount.value = price;
	window.$('#displayPrice-' + form.id.split('-')[1]).html(price);
	
	// Set new description
	form.item_name.value = desc;
}

/**
 * @method getRadioValue
 * Returns the currently selected value of a group of radio buttons
 * @param {Element[]} radio Group of radio buttons
 */
function getRadioValue(radio) {
	var d = {};
	$(radio).each(function(){
		if (this.checked) {
			d.val = this.value;
			d.text = window.$(this).parent().find('span')[0].innerHTML;
			return false;
		}
	});
	return d;
}

/**
 * @method checkFirstRadio
 * Sets the first non-disabled radio button in a group of radio buttons as checked
 * @param {Element[]} radio Group of radio buttons
 */
function checkFirstRadio(radio) {
	$(radio).each(function(){
		if (!this.disabled) {
			this.checked = true;
			return false;
		}
	});
}
