/**
 * 	Date			: May 13, 2009
 *		Author		: Paul Warelis
 *		Copyright	: Dine.TO (www.dine.to)
 *		Description	: Showtimes tab
 */

var stList = {
	// The last action/argument is for sorting
	lastAction	: "",
	lastRegion	: null,

	getMovieList : function (sortCol) {
		if (this.lastRegion == 0 || this.lastRegion == "" || this.lastRegion == null) {
			return;
		}

		if (typeof(sortCol) == 'undefined') {
			sortCol = "";
		}
		serverBusy("showtimeCall", true);
		callInProgress = true;
		$.post(ajaxFile, {
				action	: this.lastAction,
				region	: this.lastRegion,
				sort		: sortCol,
				day		: $("#showDay").val(),
				time		: $("#showTime").val()
			}, function (data) {
				serverBusy("showtimeCall", false);
				if (errorDetected(data)) return;
				
				// This basically follows the same rules as movies.js function
				var tabShowtimes = $("#tabShowtimes");
				
				if (typeof data.postalError != "undefined") {
					// The invalid postal code code is a little retarded, tight schedule mate
					tabShowtimes.find(".resultBox").html("").removeClass("grayOutAllRows");;
					tabShowtimes.find(".resultHeader").show().find("span").html(data.postalError).show();
					tabShowtimes.find("#showtimeMap").disableMap(data.postalError);
					tabShowtimes.find("#showtimeMapButton").hide();
					return;
				}
				
				// If postal is present, pass it to the map
				if (typeof data.postalGeo != "undefined") {
					$("#showtimeMap").setPostalCode(data.postalGeo.split(","));
				} else {
					$("#showtimeMap").setPostalCode(null);
				}

				tabShowtimes.find(".resultBox").html(data.movieList).removeClass("grayOutAllRows");;
				tabShowtimes.find(".resultHeader").show().find("span").html(data.heading).show();
				tabShowtimes.find(".movieDetailLink").click(stList.viewMovieInfo);
				tabShowtimes.find(".backToList").hide();
				
				// Sort column controls
				tabShowtimes.find(".thHeader span").bind("click", stList.sortMovies);
				// Initialize all movie rows
				tabShowtimes.find(".movieRow").showtimeRow();

				$("#showtimeMap").disableMap("Please select a movie to show theater locations");
				if (data.movieList == "") $("#showtimeMapButton").hide();
				else $("#showtimeMapButton").show();

			},
		"json");
		return true;
	},

	updateTimeOptions : function () {
		// Depending on the current time, make custom options in the time select control
		var timeLabel = ["Morning", "Afternoon", "Late Afternoon", "Evening", "Night" ];
		var times = [
			[ 2*60,		12*60 ],		// 2am - 12pm
			[ 12*60+1,	15*60 ],		// 12pm - 3pm
			[ 15*60+1,	18*60 ],		// 3pm - 6pm
			[ 18*60+1,	21*60 ]		// 6pm - 9pm
			// Everything else is night: 9pm - 1:59am
		];

		var curIndex = 0;
		var optionsHtml = "";
		// If showing "Today", check if options need to be updated

		if ($("#showDay").val() == 0) {
			// Today is selected, update selection options
			var date = new Date();
			var curTime = date.getHours()*60+date.getMinutes();
			curIndex = 4; // default = Night
			for (var i=0; i<times.length; i++) {
				if (curTime >= times[i][0] && curTime <= times[i][1]) {
					curIndex = i;
					break;
				}
			}
			
			optionsHtml = "<option value='0'>Soon</option>";
			this.todayIndex = curIndex;
		} else {
			curIndex = 0;
		}
		// Keep the last selected option
		var selectedOption = $("#showTime").val();
		for (var i=curIndex; i<timeLabel.length; i++) {
			optionsHtml += "<option value='"+(i+1)+"'>"+timeLabel[i]+"</option>";
		}
		$("#showTime").html(optionsHtml).val(selectedOption);
	},

	/* Control event handlers (use stList, not "this") */

	backToListClick : function() {
		var tab = $("#tabShowtimes");
		
		tab.find(".tempRow").remove();
		
		tab.find(".listHeading, .thHeader, .movieDiv").show();
		$(this).hide();

		// Depending on the list state, modify the map		
		var selectedMovie = tab.find(".movieRowSelected");
		
		if (selectedMovie.length > 0) {
			// Show theater locations
			$("#showtimeMap").mapTheaters(selectedMovie.get(0).theaterList);
			
			var selectedTheater = selectedMovie.next().find(".movieRowTheaterSelected");
			if (selectedTheater.length > 0) {
				// Zoom in to the theater
				$("#showtimeMap").zoomInOnTheater(selectedTheater.get(0).theaterId);
			}
		} else {
			tab.find(".resultBox").removeClass("grayOutAllRows");
			$("#showtimeMap").disableMap("Please select a movie to show theater locations");
		}
	},

	getFancyShowtimes : function () {
		stList.lastAction = "getFancyShowtimes";
		stList.lastRegion = 1;
		stList.getMovieList();
	},

	// this and the next function can probably go in favor of getMovieList
	getShowtimesByRegion : function () {
		var region = $("#showtimeRegion").val();
		if (region == 0) return;
		stList.lastRegion = region;
		stList.lastAction = "getShowtimesByRegion";
		stList.getMovieList();
	},

	getTheatersByPostal : function () {
		if (postalCode == '') return;
		stList.lastAction = "getShowtimesByPostal";
		stList.lastRegion = postalCode;
		$("#showtimeRegion").val(0);
		stList.getMovieList();
	},

	getShowtimesByTime : function () {
		if (stList.lastAction == "getFancyShowtimes") return;
		stList.getMovieList();
	},
	
	getShowtimesByDay : function () {
		if ($("#showtimeRegion").val() == 0) return;
		stList.updateTimeOptions();
		if (stList.lastAction == "getFancyShowtimes") return;
		// Since this is the day change, load the movie showtimes
		stList.getMovieList();
	},
	
	sortMovies : function () {
		stList.getMovieList(this.className);
	},
	
	viewMovieInfo : function(event) {
		var movieRow = $(this).parents(".movieRow");
		if (movieRow.length == 0) {
			movieRow = $(this).parents(".theaterMovieRow");
		}
		var movieId = movieRow.get(0).movieId;
		
		if (callInProgress) return false;
		callInProgress = true;
		serverBusy("showtimeCall", true);
		$.post(ajaxFile, {
				action		: "getMovieInfo",
				movieId		: movieId
			}, function (data) {
				serverBusy("showtimeCall", false);
				if (errorDetected(data)) return;

				var theaterList = data.theaterList.split(",");
				
				// Insert the html content into a temporary movie row
				var tabShowtimes = $("#tabShowtimes");
				tabShowtimes.find(".tempRow").remove();
				
				tabShowtimes.find(".thHeader, .movieDiv").hide();
				tabShowtimes.find(".listHeading").hide();
				tabShowtimes.find(".backToList").show();
				
				tabShowtimes.find(".resultBox").append(
				"<div class='movieDiv tempRow'><div id='mov"+data.movieId+"' class='movieRow movieRowSelected' style='display: none;'></div>\
				<div>"+data.htmlContent+"</div></div>");

				// Save movie and theater info inside the row element
				var tempRow = tabShowtimes.find(".tempRow");
				var movieRow = tempRow.children();
				movieRow.get(0).movieId = data.movieId;
				movieRow.get(0).theaterList = theaterList;
				
				// Initialize all theater rows
				tempRow.find(".movLocation").theaterRow(data.movieId);
				tempRow.find(".movieRegionSelect select").change(movList.regionSelectChange);
				tempRow.find(".movLocation span.movieDetailLink").click(stList.viewTheaterInfo);

				// Attempt to map all of the theaters
				$("#showtimeMap").enableMap().mapTheaters(theaterList);
				$("#showtimeMapButton").show();
				callInProgress = false;
			},
		"json");
		event.stopPropagation();
		return false;
	},
	
	viewTheaterInfo : function(event) {
		var theaterId = $(this).parents(".movLocation").get(0).theaterId;

		if (callInProgress) return false;
		serverBusy("showtimeCall", true);
		callInProgress = true;
		$.post(ajaxFile, {
				action		: "getSingleTheater",
				theaterId	: theaterId
			}, function (data) {
				serverBusy("showtimeCall", false);
				if (errorDetected(data)) return;

				var tab = $("#tabShowtimes");
				tab.find(".tempRow").remove();
				
				tab.find(".listHeading, .thHeader, .movieDiv").hide();
				tab.find(".backToList").show();
				
				tab.find(".resultBox").append(data.theaterList);

				$("#showtimeMap").enableMap().mapTheaters(data.theaterIdList.split(","));
				$("#movieMapButton").show();

				// Initialize all theater rows
				tab.find(".theaterDiv").addClass("tempRow")
					.find(".theaterRow").theaterTabRow(stList.viewMovieInfo).trigger("click");
			},
		"json");
		event.stopPropagation();
		return false;
	}
}
