﻿/// <reference path="./Cineplex.js" />

Agility.RegisterNamespace("Cineplex.MovieDetails");

(function(MovieDetails) {


	var _isFirstLoad = true;
    $(function() {
		$("#tabsMovieDetails").tabs();
		
		//bind the save as favourite action		
		var filmID = parseInt($("#lnkSaveMovieFavourite").attr("filmID"));
		
		if (Cineplex.UserContext.IsFavouriteMovie(filmID)) {
			$("#lnkSaveMovieFavourite").css("visibility", "hidden");
		} else {
			$("#lnkSaveMovieFavourite").click(function() {		
				var filmID = parseInt($(this).attr("filmID"));
				if (! isNaN(filmID)) {
					Cineplex.UserContext.AddFavoriteMovie(filmID);
					return false;
				}
			});
		}
		
		//bind the skinned dropdowns
		$("#lstShowtimeDates").CineplexCombo({
		onchange: function() {
		        var selDate = $("#lstShowtimeDates li a.selected").attr("dateStr");
		        var todaysDate = Date.now().toString("yyyy-M-d");
		        if (selDate != todaysDate) {
		            $("#NoShowtimeMessage").css("display", "none");
		        }
		        else {
		            $("#NoShowtimeMessage").css("display", "inline");
		        }									
				_populateListings();
				return false;
			}
		});
		
		//bind the time format-switching links
		function lnkSwitchTimeFormat_click(newFormat) {
		    var $hidden = $("#txtTimeFormat");
		    $hidden.val(newFormat);
		    var pageIndex = $("#pnlTheatreListingPager").data("pageIndex");
		    _populateListings(undefined, pageIndex);
		    return false;
		}
		$("#lnkSwitchTimeFormat12hr").click(function() { return lnkSwitchTimeFormat_click("12hr"); });
		$("#lnkSwitchTimeFormat24hr").click(function() { return lnkSwitchTimeFormat_click("24hr"); });
		
		//add autocomplete to location field
		$("#movie-details-location").autocomplete(Agility.ResolveUrl("~/Services/LocationAutoComplete.ashx"));
		
		//location search
		var setLocation = function() {
			Cineplex.UserContext.SetCurrentLocation($("#movie-details-location").val(), _populateListings);
		};
		
		$("#movie-details-location-search-button").click(function() {
			setLocation();		
			return false;
		});
		
		$("#movie-details-location").keydown(function(e) {
			if (e.keyCode == 13) {
				setLocation();		
				return false;
			}
		});
		
		//check for location
        var location = Cineplex.UserContext.GetCurrentLocation();

        if (location == null) {
            //show the location and come back here when done...
            Cineplex.ShowLocationDialog(function(loc) {
                _populateListings(loc);
                _populateRating(loc);
            });            
        } else {
			_populateRating(location);
			_populateListings(location);						
        }
        
        //link  up the map links
        $("#Showtimes .MapLink").live("click", _mapLinkClick);
    });
    
    
    function _populateRating(location) {
		
		if (location == null || location.length < 3) return;
		
		
		var url = Agility.ResolveUrl("~/Services/AjaxServices.asmx/GetFilmRating");
				
		var arg = { 
			filmID: Cineplex_CurrentFilmID,			
			province: location.substring(location.length - 2)			
		};
		
		$.ajax({
		  type: "POST",
		  contentType: "application/json; charset=utf-8",
		  url: url,
		  data: JSON.encode(arg),
		  dataType: "json",
		  success: function(result) {
		 
			if (result != undefined && result.d != undefined) {
				 var rating = result.d;
				$("#pnlMovieRating img.RatingIcon").attr("src", rating.ImageUrl);
				$("#pnlMovieRating img.RatingIcon").attr("alt", rating.Description);
				$("#pnlMovieRating div.RatingMessage").html(rating.Warning);
						 
			}			
		
		  },
		  error: function(error) {
			 //do nothing...
		  }

		});
    }
    
    var _currentDateStr = null;
    
    function _populateListings(location, pageIndex) 
    {
    	if (location == undefined) {
			location = $("#movie-details-location").val();			
		}
		
		
		if (pageIndex == undefined) {
			pageIndex = 0;
		}
		
		if (location == "") return;
						
		$("#movie-details-location").val(location);
		
		//set the height so we don't "jump"
		if (! _isFirstLoad) {
			$("#pnlTheatreListing").css("minHeight", $("#pnlTheatreListing").height()).css("overflow", "hidden");	
		}
		
		//show progess....
		$("#pnlTheatreListing").html(Cineplex.AjaxSpinner());
		$("#pnlTheatreListing").show();
					
		
		//build the query...
		var url = Agility.ResolveUrl("~/Services/AjaxServices.asmx/SearchTheatresWithMovieListings");
		
		var d = new Date();
		var dateStr = $("#lstShowtimeDates li a.selected").attr("dateStr");
		if (dateStr == null || dateStr == "") {
			dateStr = d.toString("yyyy-M-d");
		}		
		var timeFormat = $("#txtTimeFormat").val();				
		
		_currentDateStr	= Date.parse(dateStr).toString("MMMM dd, yyyy");
			
		
		var arg = { 
			movieID: Cineplex_CurrentMovieID,
			dateStr: dateStr,
			location: location,
			pageIndex: pageIndex,
			timeFormat: timeFormat
			};
		
		$.ajax({
		  type: "POST",
		  contentType: "application/json; charset=utf-8",
		  url: url,
		  data: JSON.encode(arg),
		  dataType: "json",
		  success: function(result) {
		 
			if (result == undefined || result.d == undefined) {
				 $("#pnlTheatreListing").html(Cineplex_errSearchNotCompleted);
				 
			} else {
		
				var ret = result.d;
				var ary = ret.ary;
				var count = ret.count;
				
							
				$("#pnlTheatreListing").setTemplateElement("txtTheatreListingTemplate");
				$("#pnlTheatreListing").setParam("getMapLink", _getMapLink);	
				$("#pnlTheatreListing").setParam("getTicketingLink", Cineplex.GetTicketingLink);	
				$("#pnlTheatreListing").setParam("getFFECDisplay", _getFFECDisplay);	
				
				
				$("#pnlTheatreListing").processTemplate(ary);
				
				 Cineplex.InitializeAjaxPager($("#pnlTheatreListingPager"), 5, pageIndex, count, function(newPageIndex) {
					_populateListings(location, newPageIndex)					
				 });
		
				//load the similar cities plugin		
				$("#pnlSimilarCities").SimilarCities(function(newLocation) {
					Cineplex.UserContext.SetCurrentLocation(newLocation, function(setLoc) {
						_populateListings(setLoc);
					});
				});
				
				//show the correct clock format link
				var otherFormat = (timeFormat == "12hr") ? "24hr" : "12hr";
				$("#lnkSwitchTimeFormat" + timeFormat).hide();
				$("#lnkSwitchTimeFormat" + otherFormat).show();
				
				if (! _isFirstLoad) {
					//set the height so we don't "jump"
					$(document).scrollTo($("#Showtimes"), {
						 duration:500,
						 easing: "swing",
						 onAfter : function() {
							$("#pnlTheatreListing").css("minHeight", null).css("overflow", "visible");	
						 }
					});
				}
				
				_isFirstLoad = false;
				
			}
		
		  },
		  error: function(error) {
			 $("#pnlTheatreListing").html(Cineplex_errSearchNotCompleted);			 
		  }

		});
		
		function _getMapLink(t) {
			var url = "http://maps.google.com/?q=";
			url += escape(t.Name) + "@" + t.Latitude + "," + t.Longitude;			
			return url;							
		}				
		
		
    }
    
    function _getFFECDisplay(ffec) {
		var desc = ffec.FilmEnhancementDescription;
		desc = desc.replace("(", "").replace(")", "");
		
		if (desc == null || desc == "") {
			return _currentDateStr;
		} else {			
			return _currentDateStr + " - <strong>" +  desc + "</strong>";
		}
    }
    
    function _mapLinkClick() {
		var latitude = $(this).attr("latitude");
		var longitude = $(this).attr("longitude");
		var theatre = $(this).attr("theatre");        
		var theatreid = $(this).attr("theatreid");
		
		if (Cineplex.ShowMapDialog([{
				latitude: latitude,
				longitude: longitude,
				theatre: theatre,
				theatreid: theatreid
			}])) {
				return false;
			}	   
    }        
    
})(Cineplex.MovieDetails);
