$(function(){$("button").text("");}); //**CHANGE INIT
function ShowSelectDistance(){
	$("#comp thead tr th.no-sort span").css("border-bottom-color", "#ebebec");
	$("#div-landmark").show();
}
function HideSelectDistance(){
	$("#comp thead tr th.no-sort span").css("border-bottom-color", "#7d8287");
	$("#div-landmark").hide();
}  //**CHANGE END

var htmlTemplates = {
	emptyList: "<tr><td colspan=5><p><strong>Your favorites list is empty.</strong></p><p><a href='/hotels/'>Click here to browse more hotels.</a></p></td></tr>",
	loading: "<img src=/assets/shared/loading.gif width=26>"
};

function book(property_key, idx) {
	var d = get_page_data();
	if (!d.arrive || !d.depart || !d.adults || !d.rooms) {
		return alert("You must enter an arriving date, departing date, number of adults, and number of rooms to continue.");
	}
	var u = "/hotel-data/search.php?cid={cid}&hotel={hotel}&amo={amo}&aday={aday}&dmo={dmo}&dday={dday}&adults={adults}&children={children}&rooms={rooms}";
	d.hotel = property_key;
	var fin = interp(u, d);
	location.href = fin;
}

var Availability = {
	load: function() {
		var arrive = $("#arrive").val();
		var depart = $("#depart").val();
		var rooms = $("#rooms").val();
		var adults = $("#adults").val();
		var children = $("#children").val();

		if (!arrive || !depart) {
			var future = new Date();
			future.setDate(future.getDate() + 7);
			$("#arrive").val(alz(future.getMonth() + 1,2) + "/" + alz(future.getDate(),2) + "/" + future.getFullYear());
			future.setDate(future.getDate() + 3);
			$("#depart").val(alz(future.getMonth() + 1,2) + "/" + alz(future.getDate(),2) + "/" + future.getFullYear());

			var arrive = $("#arrive").val();
			var depart = $("#depart").val();
		}
		
		if ($("#rooms").val() > $("#adults").val() || !$("#rooms").val()) {
			$("#adults").val("1");
			$("#children").val("0");
			$("#rooms").val("1");

			var rooms = $("#rooms").val();
			var adults = $("#adults").val();
			var children = $("#children").val();
		}

		Availability.updateCookies();
				
		var ca = $(".cell-availability");
		ca.each(function(i) {
			if (this.id) {
				var idx = this.id.replace(/cell-availability-/, "");
				if (idx) {
					$(this).html("<span class=avail-scan>" + htmlTemplates.loading + "</span>");
					$("#availability-go").attr("disabled", "disabled");
					var hotel_id = get_hotel_id_for_idx(idx);
					$.get("/favorites_avail",
						{ arrive: arrive,
							depart: depart,
							hotel_id: hotel_id,
							rooms: rooms,
							adults: adults,
							children: children
						},
						function(data) {
							if (data.match(/yes.*/i)) {
								var parts = data.split(";");
								if (parts[2] != parts[1]) {
									$("#cell-price-" + idx).html("<strike>" + parts[1] + "</strike><br/>" + parts[2]);
								} else {
									$("#cell-price-" + idx).html(parts[1]);
								}
								$("#cell-availability-" + idx).html("<!--<span class=avail-yes>Yes</span>-->");  //**CHANGE LINE
								$("#row" + idx + " button").attr("disabled", "").removeClass();  //**CHANGE LINE
								$("#comp").trigger("update"); 
							}
							else if (data == "no") {
								$("#cell-price-" + idx).html("n/a");
								$("#cell-availability-" + idx).html("<!--<span class=avail-no>No</span>-->"); //**CHANGE LINE
								$("#row" + idx + " button").attr("disabled", "disabled").addClass("disabled"); //**CHANGE LINE
								$("#comp").trigger("update"); 
							}
							else {
								alert(data);
							}
						}
					);
					
					// re-enable the button eventually
					setTimeout(
						function() {
							$("#availability-go").attr("disabled", "");
							$("#availability-loading").html("");
							$("#comp").trigger("update"); 
						}, 2000
					);
				}
			}
		});
	},

	updateCookies: function() {
		var arrive = $("#arrive").val();
		var depart = $("#depart").val();
		var rooms = $("#rooms").val();
		var adults = $("#adults").val();
		var children = $("#children").val();
		Fed.cookie("arrive", $("#arrive").val());
		Fed.cookie("depart", $("#depart").val());
		Fed.cookie("rooms", rooms);
		Fed.cookie("adults", adults);
		Fed.cookie("children", children);
	}
}

var Distance = {
	display: function(data) {
		if (data.match(/[0-9,:]+/)) {
			$(".cell-distance").html("n/a");
			var parts = data.split(",");
			for (var idx in parts) {	
				var parts2 = parts[idx].split(":");
				var hotel_id = parts2[0];
				var dist = parts2[1];
				var idx = get_idx_for_hotel_id(hotel_id);
				$("#cell-distance-" + idx).html("<!-- " + dist + " --> <span class=distance-yes>"+ dist + " mi</span>");
			}
			$("#comp").trigger("update"); 
			$("#distance-go").attr("disabled", "");
		} else {
			alert(data);
		}
	},
	load: function(data) {
		var landmark = $("#landmark").val();
		if (!landmark) {
			var landmark = $("#landmark").get(0);
			for (var i = 0; i < landmark.options.length; i++) {
				if (landmark.options[i].text == default_landmark) {
					landmark.selectedIndex = i;
					break;
				}
			}
			var landmark = $("#landmark").val();
		}
		Distance.updateCookies();
		$(".cell-distance").html("<span class=distance-scan>" + htmlTemplates.loading + "</span>");
		$("#distance-go").attr("disabled", "disabled");
		var ids = [];
		for (var i in hotels) 
			if (hotels[i] != -1)
				ids.push(hotels[i].property_key);
		var list = ids.join(",");
		$.get("/favorites_distance",
			{ landmark: landmark,
				hotel_ids: list },
			Distance.display);
	},
	updateCookies: function() {
		Fed.cookie("landmark", $("#landmark").val());
	}
}

var Email = {
	prepare: function() {
		$("#email-form").html($("#email-form").html().replace("<p><big><b>Message sent!</b></big></p>", ""));
		var v = $("#email-message").val();
		var d = document.domain;
		var arrive = $("#arrive").val().replace(/\//g, "");
		var depart = $("#depart").val().replace(/\//g, "");
		var landmark = $("#landmark").val();
		var hotel_lst = fnotempty(fpluck(hotels, "property_key")).join(",");
		if (!hotel_lst) {
			tb_remove();
			alert("You must select some favorite hotels before using the email feature");
			setTimeout(tb_remove, 250);
			return false;
		}
		var url = "http://" + d + "/favorites?" + arrive + "-" + depart + "-" + landmark + "-" + hotel_lst + "-e";
		v = v.replace(/http:\/\/.*favorites.*-e/, "");
		$("#email-message").val(v + url);
	},

	send: function() {
		var from_ = $("#email-from").val();
		var to_ = $("#email-to").val();
		var msg = $("#email-message").val();
		
		if (!from_ || !from_.match(/.+@.+/) || 
				!to_ || !to_.match(/.+@.+/) ||
				!msg)
			return alert("You must fill out all fields before the email can be sent!");
		
		$("#email-go").attr("disabled", "disabled");
		$.post("/favorites_email", 
			{
				from: from_,
				to: to_,
				msg: msg
			},
			Email.thanks
		);
	},

	thanks: function() {
		$("#email-form").html("<p><big><b>Message sent!</b></big></p>" + $("#email-form").html());
		$("#email-go").attr("disabled", "");
		setTimeout(tb_remove, 2500);
	}
};

function get_page_data() {
	return {
		amo: $("#arrive").val().split("/")[0],
		aday: $("#arrive").val().split("/")[1],
		adults: $("#adults").val(),
		arrive: $("#arrive").val(),
		children: $("#children").val(),
		cid: cid,
		city: city,
		dmo: $("#depart").val().split("/")[0],
		dday: $("#depart").val().split("/")[1],
		depart: $("#depart").val(),
		rooms: $("#rooms").val(),
		landmark: $("#landmark").val(),
		state: state
	};
}

function get_idx_for_hotel_id(hotel_id) {
	for (var idx in hotels) {
		if (hotels[idx].property_key == hotel_id)
			return idx;
	}
	return -1;
}

function get_hotel_id_for_idx(idx) {
	return hotels[idx].property_key;
}

function init() {
	restoreStateFromCookies();
	
	// setup calendar
	$("#arrive,#depart").calendar({ 
		autoPopUp: "focus", 
		dateFormat: "MDY/",
		speed: "" 
	});

	$("#arrive").bind('change', function() {
		var ch = 0;
		if (!Fed.Dates.valid($("#arrive").val())) {
			$("#arrive").val(Fed.Dates.add(Fed.Dates.today(), 7));
			ch = 1;
		}
		if (Fed.Dates.lt($("#arrive").val(), Fed.Dates.today())) {
			$("#arrive").val(Fed.Dates.add(Fed.Dates.today(), 7));
			ch = 1;
		}
		if (Fed.Dates.gt($("#arrive").val(), $("#depart").val())) {
			$("#depart").val(Fed.Dates.add($("#arrive").val(), 3));
			ch = 1;
		}
		Availability.load();
	});

	$("#depart").bind('change', function() {
		if (!Fed.Dates.valid($("#depart").val()) ||
				Fed.Dates.gt($("#arrive").val(), $("#depart").val())) {
			$("#depart").val(Fed.Dates.add($("#arrive").val(), 3));
		}
		Availability.load();
	});
	
	$("#rooms,#adults,#children").bind('change', Availability.load);

	Availability.load();
	Distance.load();
	
	// hover-over effect for data cells
	$(".data-cell").hover(
		function() {
			// the row gets a light highlight
			var id = this.id.replace(/^.*-.*-/, "");
			$("#row" + id).addClass("highlight1");
			$("#more-info-row-" + id).addClass("highlight1");  //**CHANGE LINE
			return;
			
			// the row gets a very light highlight
			var id = this.id.replace(/-[0-9]+/, "");
			$("//td[@id^=" +id + "]").addClass("highlight2");
		},
		function() {
			var id = this.id.replace(/^.*-.*-/, "");
			$("#row" + id).removeClass("highlight1");
			$("#more-info-row-" + id).removeClass("highlight1");  //**CHANGE LINE			
			return;
			
			var id = this.id.replace(/-[0-9]+/, "");
			$("//td[@id^=" +id + "]").removeClass("highlight2");
		}
	);
	// mark name field as sorted ascending
	$("#comp th").eq(1).addClass("sort-down");

	setTimeout(function() {
		$("#comp").tablesorter({
			doneCallback: MoreInfo.refreshAll,
			startCallback: MoreInfo.closeAll,
			0: {
				sorter: false
			},
			4: {
				sorter: "floating"
			},
			5: {
				sorter: "text"
			},
			6: {
				sorter: false
			}
		}); 
	}, 2000);

	// disable all the book now buttons until availability comes back
	$(".cell-tools button").attr("disabled", "disabled").addClass("disabled"); //**CHANGE LINE
}

function interp(str, arr) {
	for (var i in arr) {
		str = str.replace('{' + i + '}', arr[i]);
	}
	return str;
}

var MoreInfo = {

	// vars
	idx: -1,
	idxToPropertyKey: {},

	closeAll: function(cell) {
		if (cell) { 
			$("#comp th").lt(cell).removeClass("sort-down").removeClass("sort-up");
			$("#comp th").gt(cell).removeClass("sort-down").removeClass("sort-up");
			var e = $("#comp th").eq(cell);
			if (e.is(".sort-up")) 
				e.removeClass("sort-up").addClass("sort-down");
			else if (e.is(".sort-down"))
				e.removeClass("sort-down").addClass("sort-up");
			else
				e.addClass("sort-down");
		}
		$(".more-info-row").remove();
		$(".more-info-open").removeClass("more-info-open");
	},

	createEmptyPane: function(idx) {
		var new_div = $("<tr id='more-info-row-" + idx + "' class='more-info-row'><td colspan='5' class='more-info data-cell' id='more-info-" + idx + "'>&nbsp;</td></tr>");  //**CHANGE LINE
		new_div.insertAfter($("#row" + idx));
		$("#row" + idx).addClass("more-info-open");
		$("#more-info-" + idx).html(htmlTemplates.loading);
	},
	
	displayProfile: function(data) {
		var parts = data.split("====");
		var idx = parts[0];
		var data = parts[1];
		$("#more-info-" + idx).html(data);
		MoreInfo.Map.load(idx);
	},

	getProfile: function(property_key, idx) {
		$.get("/favorites_info", { hotel_id: property_key, idx: idx }, MoreInfo.displayProfile);
	},
	
	Map: {
		getHtml: function(idx) {
			var name = hotels[idx].name;
			var address_1 = hotels[idx].address;
    	var html = "";
    	html = html + "<strong>" + name + "</strong>";
    	return html;
    },
    load: function(idx) {
      if (GBrowserIsCompatible()) {
        var map = new GMap2($("#map" + idx).get(0));
       	map.addControl(new GSmallMapControl());
        //map.addControl(new GMapTypeControl());
        var geocoder = new GClientGeocoder();
        var address = hotels[idx].address;
				var point = new GLatLng(hotels[idx].latitude, hotels[idx].longitude);
				map.setCenter(point, 13);
				var marker = new GMarker(point);
				map.addOverlay(marker);
      }
    }
  },
  
	// display (or close) the more info pane for given property
	open: function(property_key, idx) {
		if (!($("#more-info-row-" + idx).get(0))) {
			// more info pane doesn't exist? create it
			MoreInfo.createEmptyPane(idx);
			MoreInfo.idxToPropertyKey[idx] = property_key;
			MoreInfo.getProfile(property_key, idx);
			$("#details-" + idx).html("Hide details").addClass("details-link-hide"); //**CHANGE LINE
			return false;
		} else {
			// if they clicked this a second time, hide it
			delete MoreInfo.idxToPropertyKey[idx];
			$("#more-info-row-" + idx).remove();
			$("#row" + idx).removeClass("more-info-open");
			$("#details-" + idx).html("Show details").removeClass("details-link-hide"); //**CHANGE LINE
			return false;
		}
	},
	
	Photo: { 
		next: function(property_key) {
			$("#pic-" + property_key + " img").attr("src", "/assets/shared/loading.gif");
			var pics = eval("pics_" + property_key);
			var cur = eval("pics_" + property_key + "_cur");
			var last_i = 0;
			var seen = 0;
			for (var i in pics) {
				if (cur == last_i) {
					MoreInfo.Photo.set(property_key, pics[i]);
					seen = 1;
					eval("pics_" + property_key + "_cur = " + i);
					break;
				} else
					last_i = i;
			}
			if (!seen) {
				for (var first_idx in pics) {
					break;
				}
				MoreInfo.Photo.set(property_key, pics[first_idx]);	
				eval("pics_" + property_key + "_cur = " + first_idx);
			}
		},
		
		set: function(property_key, url) {
			$("#pic-" + property_key +" img").attr("src", url);
		}
	},

	refreshAll: function() {
		MoreInfo.closeAll();
		for (var idx in MoreInfo.idxToPropertyKey) {
			var prop = MoreInfo.idxToPropertyKey[idx];
			MoreInfo.createEmptyPane(idx);
			MoreInfo.getProfile(prop, idx);
		}
	}
}

function remove(property_key, idx) {
	$("#row" + idx).empty();
	delete hotels[idx];
	Fed.Faves.remove(property_key);
	Fed.Faves.refreshHeader();
	if (Fed.Faves.count() < 1) {
		var n = $(htmlTemplates.emptyList);
		n.insertAfter($("#comp tbody"));
	}
}

function restoreStateFromCookies() {
	if (Fed.cookie("arrive"))
		$("#arrive").val(Fed.dateToSlashed(Fed.cookie("arrive")));
	if (Fed.cookie("depart"))
		$("#depart").val(Fed.dateToSlashed(Fed.cookie("depart")));
	if (Fed.cookie("rooms"))
		$("#rooms").val(Fed.cookie("rooms"));
	if (Fed.cookie("adults"))
		$("#adults").val(Fed.cookie("adults"));
	if (Fed.cookie("children"))
		$("#children").val(Fed.cookie("children"));
	if (Fed.cookie("landmark"))
		$("#landmark").val(Fed.cookie("landmark"));	
}

$(document).ready(init);


