var MAX_CHILD_AGE = 11;

Validate = {
	submit : function() {
		if (this.all()) {
			if (typeof (showLoadingBeforeResults) != "undefined") {
				showLoadingBeforeResults('true');
			}
			return true;
		} else return false;
	},

	// Updates the number of selectable children based on the number of adults

	party : function(selectBox) {
		var noAdults, noChildren, allowedChildren;
		noAdults = jQuery('#partyComposition\\.adults').val();
		noChildren = jQuery('#partyComposition\\.children').val();
		noInfants = jQuery('#partyComposition\\.infants').val();
		allowedChildren = Math.min(9 - noAdults, noAdults * 2);

		if (parseInt(noAdults) + parseInt(noChildren) + parseInt(noInfants) > 9
				|| noChildren > allowedChildren) {
			if (arguments.length > 0) {
				jQuery(selectBox).val(0);
				if (selectBox.id == 'partyComposition.children') {
					jQuery('div.qtip:visible').qtip('hide');
				}
			} else {
				jQuery('#partyComposition\\.children').val(0);
				jQuery('#partyComposition\\.infants').val(0);
				jQuery('div.qtip:visible').qtip('hide');
			}

			alert('The total size of the party cannot exceed 9 people and only a maximum of 2 children per adult is allowed.');

			return false;
		} else return true;

	},

	childAges : function() {
		var returnBool = true;
		if (jQuery("#partyComposition\\.children").val() != '0') {
			if (jQuery('.qtip #childAges input').length == 0) {
				alert('Child ages must be between 2 and ' + MAX_CHILD_AGE + ' years of age and cannot be left blank.');
				jQuery('#partyComposition\\.children').val('0');
				jQuery('#childString').html('');
				jQuery('div.qtip:visible').qtip('hide');
			}

			// For each input field within the childages qtip
			jQuery('.qtip #childAges input').each(function(i) {
				if (this.value < 2 || this.value > MAX_CHILD_AGE || this.value == "") {
					returnBool = false;
				}
				else {
					setAgeString();

					// For each qtip child age, copy it into the forms child ages
					jQuery('#childAgeContent.hide #childAges input#' + this.id).val(this.value);
				}
			});

			if (returnBool == false) {
				alert('Child ages must be between 2 and ' + MAX_CHILD_AGE + ' years of age and cannot be left blank.');
				jQuery('#partyComposition\\.children').val('0');
				jQuery('#childString').html('');
				jQuery('div.qtip:visible').qtip('hide');
			}
			return returnBool;
		}
		else return true;
	},

	all : function() {
		if (this.party() && this.childAges()) return true;
		else return false;
	}
}

function addChildAges(selectId) {
	if (Validate.party(document.getElementById(selectId))) {
		var numberOfChildren = dwr.util.getValue(selectId)
		var div = dwr.util.byId("childAges");

		// First clear all current children
		while (div.hasChildNodes()) {
			div.removeChild(div.firstChild);
		}

		for ( var i = 0; i < numberOfChildren; i++) {
			var label = document.createElement("label");
			label.innerHTML = "Child " + (i + 1);
			div.appendChild(label);
			var input = document.createElement("input");
			input.id = "childAges" + i;
			input.name = "childAges[" + i + "]";
			div.appendChild(input);
		}

		jQuery('div.qtip-content').html(jQuery('div#childAgeContent').html());
	}
}

function setCookie(name, value, daysToExpire) {
	var expiryDate = new Date();
	expiryDate.setDate(expiryDate.getDate() + daysToExpire);
	document.cookie = name
			+ "="
			+ escape(value)
			+ ((daysToExpire == null) ? "" : ";expires="
					+ expiryDate.toGMTString());
}

function getCookie(name) {
	if (document.cookie.length > 0) {
		cookieStart = document.cookie.indexOf(name + "=");
		if (cookieStart != -1) {
			cookieStart = cookieStart + name.length + 1;
			cookieEnd = document.cookie.indexOf(";", cookieStart);
			if (cookieEnd == -1) {
				cookieEnd = document.cookie.length;
			}
			return unescape(document.cookie.substring(cookieStart, cookieEnd));
		}
	}
	return "";
}

// Show the ages string
function setAgeString() {
	var ageString = "Child ages (";
	for ( var i = 0; i < jQuery('#partyComposition\\.children').val(); i++) {
		var cid = "#childAges" + i;
		ageString += jQuery('div.qtip-content > div').children(cid).val();

		if (i < +jQuery('#partyComposition\\.children').val() - 2)
			ageString += ', ';

		else if (i == +jQuery('#partyComposition\\.children').val() - 2)
			ageString += ' and ';
	}

	ageString += ") <a onclick=jQuery('.qtip').qtip('show') class='clickable'>change</a>";
	jQuery('#childString').html(ageString);
}

jQuery(document).ready(function() {

	// Using qtip plugin to do child ages popup
	jQuery('#partyComposition\\.children').qtip({
		content : {
			text : jQuery('div#childAgeContent').html(),
			prerender : true
		},

		api : {
			beforeShow : function() {
				if (jQuery(
						'#partyComposition\\.children')
						.val() == '0') {

					jQuery('#childString').html('');
					return false;
				}
			},
			beforeHide : function() {
				Validate.childAges();
			}
		},

		show : {
			when : {
				target : jQuery('#partyComposition\\.children'),
				event : 'change'
			}
		},

		hide : {
			when : {
				target : jQuery('a.okChild'),
				event : 'click'
			}
		},

		position : {
			adjust : {
				x : 121,
				y : 0
			},
			corner : {
				target : 'rightMiddle',
				tooltip : 'leftMiddle'
			}
		},

		style : {
			tip : {
				corner : 'leftMiddle',
				color : '#f9f9f9;',
				size : {
					x : 31, // Be careful that the x
							// and y values refer to
							// coordinates on
							// screen, not height or
							// width.
					y : 50
				// Depending on which corner your
				// tooltip is at, x and y could mean
				// either height or width!
				}
			},

			border : {
				width : 0,
				radius : 0,
				color : '#989898'
			},

			width : 215,
			padding : 10
		}
	});

	// Dear future self. I have no idea why this is here. Past self
	// put it in without comments. Sorry, Present Self.
	Validate.party();
});
