$(document).ready (function () {
	$(".bcsource").click (function (a) {
		if (a.currentTarget.value == "hotel") {
			showHotelForm ();
		} else if (a.currentTarget.value == "cruise") {
			showCruiseForm ();
		}
	});
	$("#hotelform").hide ();
	$("#cruiseform").hide ();
	$("#hotellist").hide ();
	
	$(".hotelfield").change (calcTotalHotel);
	
	$(".datepick").datepicker({
		dateFormat: 'MM dd, yy',
		minDate: new Date (),
		numberOfMonths: 2
	});
	$("#arrivaldate").change (function () {
		$("#departuredate").datepicker( "option", "minDate", $("#arrivaldate").val ());
	});

	var tours = $("#selecttour");
	$.each (bbcrates, function (index) {
		var o = bbcrates[index];
		if (o != null)
			tours.append ("<option value='" + index + "'>" + o['name'] + "</option>");
	});
	var url = location.href;
	url = url.toLowerCase ();
	$.each (bbcrates, function (index) {
		var o = bbcrates[index];
		if (o != null) {
			if (o.url != null) {
				var pos = url.lastIndexOf (o.url.toLowerCase());
				var len = o.url.length;
				var len2 = url.length;
				if (url.length - pos == len) {
					tours.val (index);
				}
			}
		}
	});
	
	var options = $("#selectlocation");
	$.each (bbchotels, function (item) {
		var o = bbchotels[item];
		options.append ($("<option />").val(item).text(o.name));
	});
	options.change (function () {
		var loc = options.val ();
		var hotelsdiv = $("#hotellist");
		var hotels = $("<select/>");
//		var hotels = $("#selecthotel");
		var locobject = bbchotels[loc];
		if (locobject != null) {
			hotels.show ();
			hotels.append ($("<option />").text("[Select Your Hotel]"));
			h = locobject.hotels;
			$.each (h, function (item) {
				hotels.append ($("<option />").text(h[item]));
			});
			hotelsdiv.show ();
		} else {
			hotels.hide ();
			hotelsdiv.hide ();
		}
		hotelsdiv.html (hotels);
	});

	$("#dockdate").change (function () {
		var date = $("#dockdate").val ();
		var d0 = Date.parse ($("#dockdate").val ());
		var shipsdiv = $("<select id='selectship'/>");
		shipsdiv.change (calcTotalHotel);
		shipsdiv.append ($("<option />").text("[Select Your Ship]"));
		var sss = ships;
		var shipdate = ships[d0];
		if (shipdate == null) {
			alert ("There are no ships docking on this date. Please select another date");
		} else {
			$.each (shipdate.ships, function (i) {
				var ship = shipdate.ships[i];
				shipsdiv.append ($("<option />").val (ship.port).text(ship.ship));
			});
			$("#shiplist").html (shipsdiv);
		}
	});

	showCruiseForm ();
	
	$.ajax ({
		url: "ships.csv",
		success: function (data) { parseShipsCSV (data) },
		errro: function (a, b, c) {
			alert ("Failed to load ship schedule " + a + ", " + b + ", " + c);
		}
	});
});

var ships = {};
function parseShipsCSV (data) {
	var header = true;
	var hnames = [];
	var lines = data.split ("\n");
	for (var lineindex in lines) {
		var line = lines[lineindex];
		line = line.replace ("\r", "");
		var linelst = line.split ("\t");
		var o = {};
		var year=2012, month, day;
		for (var i in linelst) {
			var token = linelst[i];
			if (header) {
				hnames.push (token);
			} else {
				var type = hnames[i];
//if (type == null) alert ("Type = null " + i + ", " + token);
				type = trim (type);
				if (type == "Month") {
					month = token;
					o.ships = [];
				} else if (type == "Day") {
					day = token;
					o.ships = [];
				} else if ((token != "") && (type != "")) {
					o.ships.push ({ ship:token, port:type });
				}
			}
		}
		if (!header) {
			if ((o.ships != null) && (o.ships.length > 0)) {
				var date = new Date (year, month-1, day);
				o.date = date;
				ships[date.getTime ()] = o;
			}
		}
		header = false;
	}
}

function showHotelForm () {
	$("#hotelform").show ();
	$("#formdiv").css ("background-color",hotelcolor);
	$("#cruiseform").hide ();
	$("#cbhotel").attr('checked', true);
}
function showCruiseForm () {
	$("#cruiseform").show ();
	$("#formdiv").css ("background-color", cruisecolor);
	$("#hotelform").hide ();
	$("#cbcruise").attr('checked', true);
}

function checkSubmit (form) {
	if (getTotalCost () > 0) {
		form.submit ();
		return true;
	}
	alert ("Please complete the form and press 'Buy Now' button again");
	return false;
}

function getTotalCost () {
	var total = 0;
	var tour = $("#selecttour").val ();
	var adults = $("#adults").val ();
	var children = $("#children").val ();
	var rates = bbcrates;
	var location = null;

	if ($("#cbhotel").attr('checked')) {
		location = $("#selectlocation").val ();
	} else if ($("#cbcruise").attr('checked')) {
		location = $("#selectship").val ();
	}
	if ((rates[tour] != null) && (rates[tour].origins[location] != null)) {
		total = rates[tour].origins[location].adult*adults;
		total += rates[tour].origins[location].child*children;
	}
	return total;
}

function calcTotalHotel () {
	var total = getTotalCost ();
	$("#totalhotel").html (total);
	$("#paypal_amount").val (total);
	if (total == 0) return;
	
	var tour = $("#selecttour").val ();
	var adults = $("#adults").val ();
	var children = $("#children").val ();
	var rates = bbcrates;
	var descr = rates[tour].name + " tour";
	if (adults > 0) descr += "\n" + adults + " adult(s)";
	if (children > 0) descr += "\n" + children + ((children == 1)?" child":" children");
	$("#paypal_name").val (descr);
}

var trimchars = " \t\n\r";
function trim (s) {
	if (s.length <= 0) return s;
	var c = s.charAt (0);
	while (trimchars.search (c) >= 0) {
		s = s.substr (1);
		if (s.length <= 0) return s;
		c = s.charAt (0);
	}
	c = s.charAt (s.length-1);
	while (trimchars.search (c) >= 0) {
		s = s.substr (0, s.length-1);
		if (s.length <= 0) return s;
		c = s.charAt (s.length-1);
	}
	return s;
}

var hotelcolor = "#D3D8C4";
var cruisecolor = "#D3D8C4";
