var current_index = 0;
var tree;
var currentRequest = null;

$(document).ready(function() {
	$("#destinations :text").labelify({
		text: function(input) {
			if($(input).val().length == 0) {
				return $(input).attr("title");
			}
		}
	});

	tree = new $.mptt($("#destinations"));

	tieFunctions();
	setTripDatesMessage();
	//enableDisableDatepickers();

	$(".add_destination_row").click(function(e) {
		e.preventDefault();
		if(!$(this).hasClass("busy") && (currentRequest == null)) {
			var that = this;
			var mostRightIdx = tree.findAll().length;
			$(this).addClass("busy");

			tree.insertAfter(parseInt($(tree.findRightMostNode('', 1)).attr('idx')), function(lft, rgt) {
				var newDestinationIdx = mostRightIdx+1;

				currentRequest = $.post(
					'/trips/get_trip_destination_row',
					{
						'data[index]': newDestinationIdx,
						'data[lft]': lft,
						'data[rgt]': rgt
					},
					function(data) {
						// Insert the new node after the final root node, or the final root node's final child if it exists.
						var mostRightRootNodeIdx = parseInt($(tree.findRightMostNode('', 1)).attr("idx"));
						var endNodeIdx = mostRightRootNodeIdx;
						var mostRightRootNodeChilden = tree.findByParent(mostRightRootNodeIdx);
						if(mostRightRootNodeChilden.length > 0) {
							endNodeIdx = parseInt($(tree.findRightMostNode(mostRightRootNodeIdx, 2)).attr("idx"));
						}

						$(that).removeClass("busy");
						$("#destination-"+endNodeIdx).after(data);
						tieFunctions();
						setTripDatesMessage();
						//enableDisableDatepickers();
						currentRequest = null;
					}
				);
			});
		}
	});

	// insert destination info tooltip
	$(".insert_destination").live('mouseover', function(e) {
		var windowWidth = getWindowWidth();
		var margin = parseInt($("#center_wrap").css('left').replace('px', '')) - 500;
		var intLeft = (windowWidth > 1200) ? (e.pageX - margin) : e.pageX;
		$("#insert_dest_info").css('left', intLeft);
		$("#insert_dest_info").css('top', (e.pageY - ($("#insert_dest_info").height()/2)));
		$("#insert_dest_info").show();

		// hide tooltip after 10 secs
		setTimeout(function() {
			$("#insert_dest_info").hide();
		}, 10000);
	});
	$(".insert_destination").live('mouseout', function() {
		$("#insert_dest_info").hide();
	});

	// add a sub-destination info tooltip
	$(".add_sub_destination").live('mouseover', function(e) {
		var windowWidth = getWindowWidth();
		var margin = parseInt($("#center_wrap").css('left').replace('px', '')) - 500;
		var intLeft = (windowWidth > 1200) ? (e.pageX - margin) : e.pageX;
		$("#subtrip_info").css('left', intLeft);
		$("#subtrip_info").css('top', (e.pageY - ($("#subtrip_info").height()/2)));
		$("#subtrip_info").show();

		// hide tooltip after 10 secs
		setTimeout(function() {
			$("#subtrip_info").hide();
		}, 10000);
	});
	$(".add_sub_destination").live('mouseout', function() {
		$("#subtrip_info").hide();
	});

	$("#submit_plan_btn").click(function(e) {
		e.preventDefault();

		tree.findAll().each(function() {
			var idx = $(this).attr('idx');
			var parent = $(this).attr('parent');
			var lft = $(this).attr('lft');
			var rgt = $(this).attr('rgt');

			var idxInputStr = "<input id=\"TripDestination"+idx+"Idx\" type=\"hidden\" value=\""+idx+"\" name=\"data[TripDestination]["+idx+"][idx]\"/>";
			var lftInputStr = "<input id=\"TripDestination"+idx+"Lft\" type=\"hidden\" value=\""+lft+"\" name=\"data[TripDestination]["+idx+"][lft]\"/>";
			var rgtInputStr = "<input id=\"TripDestination"+idx+"Rgt\" type=\"hidden\" value=\""+rgt+"\" name=\"data[TripDestination]["+idx+"][rgt]\"/>";
			var parentInputStr = "<input id=\"TripDestination"+idx+"Parent\" type=\"hidden\" value=\""+parent+"\" name=\"data[TripDestination]["+idx+"][parent_id]\"/>";

			$(".column-5", this).append(idxInputStr+lftInputStr+rgtInputStr+parentInputStr);
		});

		$("#plan_a_trip form").submit();
	});
});


function autoCompleteJSON(raw) {
	var parsed = [];
	if(raw.length > 0) {
		var i=0;
		for(i=0; i<raw.length; i++) {
			var json = raw[i];
			parsed.push({
				data: json,
				value: json['Geoname']['asciiname']+', '+json['countryinfo']['name'],
				result: json['Geoname']['asciiname']+', '+json['countryinfo']['name']
			});
		}
	}
	return parsed;
}

var updateFields = function(data, index) {
	// Reset fields
	$("#TripDestination"+index+"Latitude").val("");
	$("#TripDestination"+index+"Longitude").val("");
	$("#TripDestination"+index+"Name").val("");
	$("#TripDestination"+index+"Country").val("");
	$("#TripDestination"+index+"CountryCode").val("");
	$("#TripDestination"+index+"GeonameId").val("");

	// Update the relevant form fields with the destination's attributes and center map.
	map.setCenter(new GLatLng(data.Geoname.latitude, data.Geoname.longitude), 7);
	$("#TripDestination"+index+"Latitude").val(data.Geoname.latitude);
	$("#TripDestination"+index+"Longitude").val(data.Geoname.longitude);
	$("#TripDestination"+index+"Name").val(data.Geoname.asciiname);
	$("#TripDestination"+index+"Country").val(data.countryinfo.name);
	$("#TripDestination"+index+"CountryCode").val(data.Geoname.country);
	$("#TripDestination"+index+"GeonameId").val(data.Geoname.geonameid);

	validateLocationFields(index);
}

function startSearch() {
	$("#TripAddForm input:visible:not(.autoComplete),textarea,select,button").each(function() {
		if($(this).attr("disabled")) {
			$(this).addClass("wasDisabled");
		} else {
			$(this).removeClass("wasDisabled");
		}

		if(!$(this).hasClass("wasDisabled")) {
			if(!$(this).hasClass("hasDatepicker")) {
				$(this).attr("disabled", "disabled");
			}

			if($(this).hasClass("hasDatepicker")) {
				$(this).datepicker("disable");
			}
		}
	});

	$("#location_input_icon_"+current_index).attr("src", "/img/ajax_loading.gif");
}

function endSearch(index) {
	$("#TripAddForm input:visible:not(.autoComplete),textarea,select,button").each(function() {
		if(!$(this).hasClass("wasDisabled")) {
			if(!$(this).hasClass("hasDatepicker")) {
				$(this).removeAttr("disabled");
			}

			if($(this).hasClass("hasDatepicker")) {
				$(this).datepicker("enable");
			}
		} else {
			$(this).removeClass("wasDisabled");
		}
	});

	$("#location_input_icon_"+index).attr("src", "/img/icon_globe.gif");
}

function validateLocationFields(index) {
	var completed = true;

	if($("#TripDestination"+index+"Latitude").val() == '')
		completed = false;
	if($("#TripDestination"+index+"Longitude").val() == '')
		completed = false;
	if($("#TripDestination"+index+"Name").val() == '')
		completed = false;
	if($("#TripDestination"+index+"Country").val() == '')
		completed = false;
	if($("#TripDestination"+index+"CountryCode").val() == '')
		completed = false;
	if($("#TripDestination"+index+"GeonameId").val() == '')
		completed = false;

	if(completed == true) {
		$("#location_input_icon_"+index).attr("src", "/img/tick.gif");

		// replace the query text with the currently select field
		$("#TripDestination"+index+"Query").val($("#TripDestination"+index+"Name").val()+', '+$("#TripDestination"+index+"Country").val());
	} else {
		$("#location_input_icon_"+index).attr("src", "/img/cross.gif");
	}
}


function tieFunctions() {
	/* Make each insert-destination button insert a new row beneath */
	$(".insert_destination").each(function() {
		$(this).unbind("click");
		$(this).click(function(e) {
			e.preventDefault();
			if(!$(this).hasClass("active") && (currentRequest == null)) {
				var that = this;
				var idx = parseInt($(this).parent().parent().parent().attr("idx"));
				$(this).addClass("active");

				tree.insertAfter(idx, function(lft, rgt) {
					// give the new node +1 of the highest idx.
					var newDestinationIdx = tree.findAll().length+1;

					currentRequest = $.post(
						'/trips/get_trip_destination_row',
						{
							'data[index]': newDestinationIdx,
							'data[lft]': lft,
							'data[rgt]': rgt
						},
						function(data) {
							// Insert the new node after the src node, or the src node's final child if it exists.
							var lastNodeIdx = idx;
							var srcNodeChildren = tree.findByParent(idx);
							if(srcNodeChildren.length > 0) {
								lastNodeIdx = parseInt($(tree.findRightMostNode(idx, 2)).attr("idx"));
							}

							var lastNode = $("#destination-"+lastNodeIdx);

							// If it's the first row, skip the 'Destinations' th row.
							if($(lastNode).hasClass('first')) {
								if($("~ tr:not(.trip_destination)", lastNode).length == 1) {
									lastNode = $("~ tr:not(.trip_destination)", lastNode).get();
								}
							}

							$(lastNode).after(data);
							$(that).removeClass("active");
							tieFunctions();
							setTripDatesMessage();
							currentRequest = null;
							//enableDisableDatepickers();
						}
					);
				});
			}
		});
	});

	/* Make each sub-trip button display a sub-trip row */
	$(".add_sub_destination").each(function() {
		$(this).unbind("click");
		$(this).click(function(e) {
			e.preventDefault();
			if(!$(this).hasClass("active") && (currentRequest == null)) {
				var that = this;
				var parent = $(this).attr("parent");
				$(this).addClass("active");

				tree.insertChild(parent, function(lft, rgt) {
					// give the new node +1 of the highest idx.
					var newDestinationIdx = tree.findAll().length+1;

					currentRequest = $.post(
						'/trips/get_trip_destination_row',
						{
							'data[index]': newDestinationIdx,
							'data[parent]': parent,
							'data[lft]': lft,
							'data[rgt]': rgt
						},
						function(data) {
							var rightMostNode = tree.findRightMostNode(parent, 2);
							$(rightMostNode).after(data);
							$(that).removeClass("active");
							tieFunctions();
							setTripDatesMessage();
							//enableDisableDatepickers();
							currentRequest = null;
						}
					);
				});
			}
		});
	});


	// set up each destination query field
	tree.findAll().each(function() {
		var idx = $(this).attr('idx');

		$(".autoComplete", this).each(function() {
			if(!($(this).hasClass("ui-autocomplete-input"))) {
				$(this).autocomplete({
					url: '/trip_destinations/ajaxSearch',
					dataType: "json",
					delay: 400,
					matchSubset: false,
					parse: function(raw) {
						endSearch(idx);
						return autoCompleteJSON(raw);
					},
					formatItem: function(row) {
						var output = '<img class="flag" src="/img/flags/'+row['Geoname']['country']+'.png"/><span class="name">'+row['Geoname']['asciiname']+'</span>, <span class="admin1">'+row['admin1Codes']['name']+'</span>, <span class="country">'+row['countryinfo']['name']+'</span>';
						return output;
					},
					result: function(event, data) {
						updateFields(data, idx);
					},
					extraParams: {
						preSearchFunc: function(current_index) {
							startSearch(current_index);
						}
					}
				});
			}

			// Check if Location data was completed on field exit
			$(this).blur(function() {
				validateLocationFields(idx);
			});

			$(this).focus(function() {
				current_index = idx;
			});
		});
	});

	$(".remove_destination_row").unbind('click');
	$(".remove_destination_row").click(function(e) {
		e.preventDefault();
		index = parseInt($(this).attr('i'));

		if($("#destination-"+index+":visible").length == 1) {
			if($(".remove_destination_row:visible").length > 1) {
				var blnDoRemove = true;
				if(typeof($('#TripDestination'+index+'Id').val()) != 'undefined') {
					blnDoRemove = confirm('Are you sure you want to remove this destination?\nAny scoops tied to this destination will be deleted!');
				}

				if(blnDoRemove === true) {
					tree.deleteNode(index, function(node) {
						var idx = $(node).attr('idx');
						if(typeof($('#TripDestination'+idx+'Id', node).val()) == 'undefined') {
							$(node).remove();
						} else {
							$(node).hide();
							$(node).removeClass('node');
							$('#TripDestination'+index+'Remove').val('true');

							tree.findByParent(idx).each(function() {
								var this_idx = $(this).attr('idx');
								$(this).hide();
								$(this).removeClass('node');
								$('#TripDestination'+this_idx+'Remove').val('true');
							});
						}
					});

					setTripDatesMessage();
				}
			}
		}
	});

	// instantiate datepickers on the new row
	$(".trip_destination:not(:has(input.hasDatepicker))").each(function() {
		var row = this;
		var idx = parseInt($(this).attr('idx'));

		// hide start-date select boxes and add an input for the datepicker.
		$(".column-2", this).each(function() {
			$("#TripDestination"+idx+"StartDateDay").hide();
			$("#TripDestination"+idx+"StartDateMonth").hide();
			$("#TripDestination"+idx+"StartDateYear").hide();

			var objStartDate = "<input type=\"text\" id=\"startDate-"+idx+"\" class=\"startDate\" />";
			if($("#TripDestination"+idx+"StartDateDay").hasClass('form-error')) {
				objStartDate = $(objStartDate).addClass('form-error');
			}
			$(".input", this).append(objStartDate);
		});

		// hide end-date select boxes and add an input for the datepicker.
		$(".column-3", this).each(function() {
			$("#TripDestination"+idx+"EndDateDay").hide();
			$("#TripDestination"+idx+"EndDateMonth").hide();
			$("#TripDestination"+idx+"EndDateYear").hide();

			var objEndDate = "<input type=\"text\" id=\"endDate-"+idx+"\" class=\"endDate\" />";
			if($("#TripDestination"+idx+"EndDateDay").hasClass('form-error')) {
				objEndDate = $(objEndDate).addClass('form-error');
			}
			$(".input", this).append(objEndDate);
		});

		// insert StartDate from select boxes into the new datePicker field
		if($("#TripDestination"+idx+"StartDateYear").length == 1) {
			var current_start_date_str = $("#TripDestination"+idx+"StartDateYear").val()+'-'+$("#TripDestination"+idx+"StartDateMonth").val()+'-'+$("#TripDestination"+idx+"StartDateDay").val();

			if(current_start_date_str != '--') {
				var current_start_date = $.datepicker.formatDate('dd/mm/yy', $.datepicker.parseDate('yy-mm-dd', current_start_date_str));
				$("#startDate-"+idx).val(current_start_date);
			}
		}


		// insert EndDate from select boxes into the new datePicker field
		if($("#TripDestination"+idx+"EndDateYear").length == 1) {
			var current_end_date_str = $("#TripDestination"+idx+"EndDateYear").val()+'-'+$("#TripDestination"+idx+"EndDateMonth").val()+'-'+$("#TripDestination"+idx+"EndDateDay").val();

			if(current_end_date_str != '--') {
				var current_end_date = $.datepicker.formatDate('dd/mm/yy', $.datepicker.parseDate('yy-mm-dd', current_end_date_str));
				$("#endDate-"+idx).val(current_end_date);
			}
		}

		// instantiate datepicker on start and end date fields
		var maxDate = null;
		var minDate = null;
		var datepicker_setup = {
			dateFormat: 'dd/mm/yy',
			gotoCurrent: true,
			yearRange: '-20:+10',
			showOn: 'both',
			prevText: '<',
			nextText: '>',
			onClose: function() {
				setTripDatesMessage();
				//enableDisableDatepickers();
			},
			buttonImage: '/img/icon_calendar.gif',
			buttonImageOnly: true,
			hideIfNoPrevNext: true,
			beforeShow: function(input, inst) {
				var startDateMin = null;
				var startDateMax = null;
				var endDateMin = null;
				var endDateMax = null;

				/*  Set the startDate's range as follows:
				 *    Min - If this has a previous destination, use its endDate, else if it has a parent,
				 *    use its startDate, else its the first startDate and can be anything.
				 *    startDate.
				 *    Max - If its endDate is set, use it, else if its parent's endDate is set, use it, else
				 *    it can be anything.
				 *
				 *  Set the endDate's range as follows:
				 *    Min - If this destination's startDate's been set use it, else if it has a
				 *    a parent, use its endDate.
				 *    Max - If this has a next destination, use its startDate, else if it has a
				 *    parent, use its endDate, else it's the last destination of the trip and can
				 *    be anything.
				 */
				var parentDest = tree.findByIdx(parseInt($(row).attr('parent')));
				var nextDest = tree.findByLft(parseInt($(row).attr('rgt'))+1);
				var prevDest = tree.findByRgt(parseInt($(row).attr('lft'))-1);

				/* Start Date - Min */
				if(($(".endDate", prevDest).length == 1) && ($(".endDate", prevDest).datepicker("getDate") != null)) {
					//tree.debug('startDate using prevDest', prevDest);
					startDateMin = new Date($(".endDate", prevDest).datepicker("getDate"));
				} else if(($(".startDate", parentDest).length == 1) && ($(".startDate", parentDest).datepicker("getDate") != null)) {
					//tree.debug('startDate using parentDest', parentDest);
					startDateMin = new Date($(".startDate", parentDest).datepicker("getDate"));
				}
				/* Start Date - Max */
				if(($(".endDate", row).length == 1) && ($(".endDate", row).datepicker("getDate") != null)) {
					//tree.debug('startDate using prevDest', prevDest);
					startDateMax = new Date($(".endDate", row).datepicker("getDate"));
					startDateMax.setDate(startDateMax.getDate());
				} else if(($(".endDate", parentDest).length == 1) && ($(".endDate", parentDest).datepicker("getDate") != null)) {
					//tree.debug('startDate using parentDest', parentDest);
					startDateMax = new Date($(".endDate", parentDest).datepicker("getDate"));
					startDateMax.setDate(startDateMax.getDate());
				}

				/* End Date - Min */
				if(($(".startDate", row).length == 1) && ($(".startDate", row).datepicker("getDate") != null)) {
					//tree.debug('endDate Min using row', row);
					endDateMin = new Date($(".startDate", row).datepicker("getDate"));
				} else if(($(".endDate", parentDest).length == 1) && ($(".endDate", parentDest).datepicker("getDate") != null)) {
					//tree.debug('endDate Min using parentDest', parentDest);
					endDateMin = new Date($(".endDate", parentDest).datepicker("getDate"));
				}
				/* End Date - Max */
				if(($(".startDate", nextDest).length == 1) && ($(".startDate", nextDest).datepicker("getDate") != null)) {
					//tree.debug('endDate Max using nextDest', nextDest);
					endDateMax = new Date($(".startDate", nextDest).datepicker("getDate"));
				} else if(($(".endDate", parentDest).length == 1) && ($(".endDate", parentDest).datepicker("getDate") != null)) {
					//tree.debug('endDate Max using parentDest', parentDest);
					endDateMax = new Date($(".endDate", parentDest).datepicker("getDate"));
				}

				if(input.id == "endDate-"+idx) {
					inst.settings.defaultDate = endDateMin; //$(".startDate", row).datepicker("getDate");
				} else if(input.id == "startDate-"+idx) {
					if(prevDest.length == 1) {
						inst.settings.defaultDate = startDateMin; //$(".endDate", prevDest).datepicker("getDate");
					}
				}

				return {
					//minDate: (input.id == "endDate-"+idx ? endDateMin : startDateMin),
					//maxDate: (input.id == "endDate-"+idx ? endDateMax : startDateMax)
					defaultDate: (input.id == "endDate-"+idx ? endDateMin : startDateMin)
				};
			},
			onSelect: function(date,picker) {
				// update the hidden select boxes after picking a date
				if(picker.id == "startDate-"+idx) {
					$("#TripDestination"+idx+"StartDateDay").val(addZero(picker.selectedDay));
					$("#TripDestination"+idx+"StartDateMonth").val(addZero(picker.selectedMonth+1));
					$("#TripDestination"+idx+"StartDateYear").val(picker.selectedYear);

					// if there are child nodes, set the first child's start date to this start date.
					var lft = parseInt(tree.findByIdx(idx).attr('lft'));
					var firstChildNode = tree.findByLft(lft+1);
					if(firstChildNode.length == 1) {
						var firstChildNodeStartDate = $("input.startDate.hasDatepicker", firstChildNodeStartDate);
						if($(firstChildNodeStartDate).datepicker("getDate") == null) {
							$(firstChildNodeStartDate).datepicker("disable");
							$(firstChildNodeStartDate).datepicker("setDate", new Date(picker.selectedYear, picker.selectedMonth, picker.selectedDay));
							$(firstChildNodeStartDate).datepicker("enable");
							updateNodeDateFields(parseInt($(firstChildNode).attr('idx')));
						}
					}
				} else if(picker.id == "endDate-"+idx) {
					$("#TripDestination"+idx+"EndDateDay").val(addZero(picker.selectedDay));
					$("#TripDestination"+idx+"EndDateMonth").val(addZero(picker.selectedMonth+1));
					$("#TripDestination"+idx+"EndDateYear").val(picker.selectedYear);

					// set the start date of the next node to this end date.
					var rgt = parseInt(tree.findByIdx(idx).attr('rgt'));
					var nextNode = tree.findByLft(rgt+1);
					if(nextNode.length == 1) {
						var nextNodeStartDate = $("input.startDate.hasDatepicker", nextNode);
						if($(nextNodeStartDate).datepicker("getDate") == null) {
							$(nextNodeStartDate).datepicker("disable");
							$(nextNodeStartDate).datepicker("setDate", new Date(picker.selectedYear, picker.selectedMonth, picker.selectedDay)).datepicker("hide");
							$(nextNodeStartDate).datepicker("enable");
							updateNodeDateFields(parseInt($(nextNode).attr('idx')));
						}
					}
				}
			}
		};
		if($("#startDate-"+idx).length == 1) {
			$("#startDate-"+idx).datepicker(datepicker_setup);

			// if there's a previous node, set this start date to the previous end date.
			var lft = parseInt(tree.findByIdx(idx).attr('lft'));
			var prevNode = tree.findByRgt(lft-1);
			if(prevNode.length == 1) {
				if(tree.findByIdx(idx).attr('parent') == '') {
					var prevNodeEndDate = $("input.endDate.hasDatepicker", prevNode);
					if($(prevNodeEndDate).datepicker("getDate") != null) {
						$("#startDate-"+idx).datepicker("disable");
						$("#startDate-"+idx).datepicker("setDate", $(prevNodeEndDate).datepicker("getDate")).datepicker("hide");
						$("#startDate-"+idx).datepicker("enable");
						updateNodeDateFields(idx);
					}
				}
			} else {
				// else if there's a parent node, set this start date to the parent's start date.
				var lft = parseInt(tree.findByIdx(idx).attr('lft'));
				var parentNode = tree.findByLft(lft-1);
				if(parentNode.length == 1) {
					var parentNodeStartDate = $("input.startDate.hasDatepicker", parentNode);
					if($(parentNodeStartDate).datepicker("getDate") != null) {
						$("#startDate-"+idx).datepicker("disable");
						$("#startDate-"+idx).datepicker("setDate", $(parentNodeStartDate).datepicker("getDate")).datepicker("hide");
						$("#startDate-"+idx).datepicker("enable");
							updateNodeDateFields(idx);
					}
				}
			}
		}
		if($("#endDate-"+idx).length == 1) {
			$("#endDate-"+idx).datepicker(datepicker_setup);
		}
	});
}

function addZero(num) {
	(String(num).length < 2) ? num = String("0" + num) :  num = String(num);
	return num;
}

function setTripDatesMessage() {
	var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

	var firstDestination = tree.findLeftMostNode('', 1);
	//firstDestination = tree.findByLft(parseInt($(firstDestination).attr('rgt'))+1);
	var lastDestination = tree.findRightMostNode('', 1);

	if((firstDestination != lastDestination) && ($(".endDate", firstDestination).length == 1) && ($(".endDate", lastDestination).length == 1)) {
		var startDate = new Date($(".endDate", firstDestination).datepicker("getDate"));
		var endDate = $(".endDate", lastDestination).datepicker("getDate");
		var message = '';

		if((startDate != null) && (startDate.getFullYear() > 1970)) {
			var startDate_day_ord = getDayOrdinal(startDate.getDate());
			message = 'Your trip begins on '+startDate.getDate()+startDate_day_ord+' '+months[startDate.getMonth()]+' '+startDate.getFullYear();
			if((endDate != null) && (endDate.getFullYear() > 1970)) {
				var endDate_day_ord = getDayOrdinal(endDate.getDate());
				message += ' and finishes on '+endDate.getDate()+endDate_day_ord+' '+months[endDate.getMonth()]+' '+endDate.getFullYear();
			}

			message += ':'
		}
		$("#dates_message").html(message);
	}
}

function getDayOrdinal(day) {
	var ord = "";
	if (day == 1 || day == 21 || day ==31) {
		ord = "st";
	} else if(day == 2 || day == 22) {
		ord = "nd";
	} else if(day == 3 || day == 23) {
		ord = "rd";
	} else {
		ord = "th";
	}

	return ord;
}

/*  Loops through each destination row and disables each input
 *  if the previous input (or parent, if there is no previous)
 *  is empty, else enables it.
 */
function enableDisableDatepickers() {
	var firstRow = tree.findLeftMostNode('', 1);

	var firstRowIdx = parseInt($(firstRow).attr('idx'));
	$(".trip_destination:has(input.hasDatepicker)").each(function() {
		var row = this;
		var idx = parseInt($(this).attr('idx'));

		// keep the first destination's endDate enabled
		if(idx > firstRowIdx) {
			$("input.hasDatepicker", this).each(function() {
				var parentDest = tree.findByIdx(parseInt($(row).attr('parent')));
				var nextDest = tree.findByLft(parseInt($(row).attr('rgt'))+1);
				var prevDest = tree.findByRgt(parseInt($(row).attr('lft'))-1);
				var idx = parseInt($(this).attr('idx'));
				var input = this;

				$(input).datepicker("disable");
				if($(input).hasClass("startDate")) {
					if($(".endDate", prevDest).length == 1) {
						if($(".endDate", prevDest).datepicker("getDate") == null) {
							$(input).datepicker("disable");
						} else {
							$(input).datepicker("enable");
						}
					} else if($(".startDate", parentDest).length == 1) {
						if($(".startDate", parentDest).datepicker("getDate") == null) {
							$(input).datepicker("disable");
						} else {
							$(input).datepicker("enable");
						}
					}
				} else {
					if($(".startDate", row).datepicker("getDate") == null) {
						$(input).datepicker("disable");
					} else {
						$(input).datepicker("enable");
					}
				}
			});
		}
	});
}

/* Takes an idx and updates the 3 dd/mm/yyyy inputs to match the corresponding datepicker field. */
function updateNodeDateFields(idx) {
	if(__getClass(idx) == 'Number') {
		var node = tree.findByIdx(idx);

		if(node.length == 1) {
			var datepickers = $("input.hasDatepicker", node);

			datepickers.each(function() {
				var date = $(this).datepicker("getDate");
				if(date != null) {
					if($(this).hasClass('startDate')) {
						$("#TripDestination"+idx+"StartDateDay").val(addZero(date.getDate()));
						$("#TripDestination"+idx+"StartDateMonth").val(addZero(date.getMonth()+1));
						$("#TripDestination"+idx+"StartDateYear").val(date.getFullYear());
					} else if($(this).hasClass('endDate')) {
						$("#TripDestination"+idx+"EndDateDay").val(addZero(date.getDate()));
						$("#TripDestination"+idx+"EndDateMonth").val(addZero(date.getMonth()+1));
						$("#TripDestination"+idx+"EndDateYear").val(date.getFullYear());
					}
				}
			});
		}
	}
}

function getWindowWidth() {
	var myWidth = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
	} else if( document.documentElement && document.documentElement.clientWidth ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
	} else if( document.body && document.body.clientWidth ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
	}

	return myWidth;
}
