/**
 * 	Date			: May 13, 2009
 *		Author		: Paul Warelis
 *		Copyright	: Dine.TO (www.dine.to)
 *		Description	: Showtime row plugin
 */

(function($) {

	$.fn.showtimeRow = function() {
		return this.each(function() {
			// Save movie id
			this.movieId = this.id.replace("mov","");
			var $this = $(this);

			$this.click($.fn.showtimeRow.handleMouseClick);
		});
	};

	// Event handlers
	$.fn.showtimeRow.handleMouseClick = function() {
		if (callInProgress) return false;
		var $this = $(this);

		var selectedMovie = $this.parents(".resultBox").find(".movieRowSelected");
		if (selectedMovie.length > 0) {
			var bail = $this.hasClass("movieRowSelected");
			selectedMovie.removeClass("movieRowSelected").next().hide();
			// Unselect active theater
			$.fn.showtimeTheaterRow.unselectTheaterRow();

			$("#showtimeMap").disableMap("Please select a movie to show theater locations");
			if (bail) {
				$("#tabShowtimes .resultBox").removeClass("grayOutAllRows");
				return;
			}
		}
		$("#showtimeMap").enableMap();
		
		$this.addClass("movieRowSelected");
		
		var tabShowtimes = $("#tabShowtimes");
		tabShowtimes.find(".resultBox").addClass("grayOutAllRows");

		if (typeof(this.theaterList) == "undefined") {
			// Make an ajax call to get movie information
			$("#showtimeMap").disableMap("<img src='images/indicator.gif'>");
			callInProgress = true;
			$.post(ajaxFile, {
					action	: "getMovieShowtimeInfo",
					movieId	: this.movieId,
					lastAction : stList.lastAction,
					region	: stList.lastRegion,
					day		: $("#showDay").val(),
					time		: $("#showTime").val()
				}, function (data) {
					$("#showtimeMap").enableMap();
					if (errorDetected(data)) return;
					
					var theaterList = data.theaterList.split(",");
					// Save the list
					$this.get(0).theaterList = theaterList;
					
					// Insert the html content into the movie row
					$this.parent().append(data.htmlContent);
					
					// Loaded the movie datails along with a div holding all theaters.
					// Initialize all theater rows
					$this.next().find(".movLocation").showtimeTheaterRow(data.movieId);
					$this.next().find(".movieRegionSelect select").change(movList.regionSelectChange);
					$this.next().find(".movLocation span.movieDetailLink").click(stList.viewTheaterInfo);

					// Attempt to map all of the theaters
					$("#showtimeMap").mapTheaters(theaterList);
				},
			"json");
			
		} else {
			// Movie info is there, show it and make a call to the map
			$this.next().show();
			$("#showtimeMap").mapTheaters(this.theaterList).enableMap();
		}
		
	};

})(jQuery);

