var gInitializing = true;
$(function() {
    prependAdd("06","homepage", "#TopAd");    
	// NOTA BENE: The best way to understand this code is to make sure you pay 
	// attention to what things have to happen AFTER an Ajax call succeeds.
	// Sorry about all the brackets, but at least it ain't Lisp :)
	
	Roller("Loading").appendTo("ul#Main")
	
	// preload some images
	$("<img/>").attr("src","images/yFade.png")
	$("<img/>").attr("src","images/iBack.png")
	
	
	//
	// SEARCH FUNCTIONS
	//

	var resetFrontSearch = function() {
		$("#headSearch").val("Search").addClass("Empty").focus();
		$("#searchResults li:not(.Back), #searchResults .Footer, .Warning").remove();
	};

	var frontSearch = function() {
		if($("#headSearch").val().length<2) {
			alert('please enter at least 2 letters'); // why?
			return;
		}

		$("#searchResults li:not(.Back), #searchResults .Footer, .Warning").remove();
		$("#searchResults").append(Roller("Loading "+$("#headSearch").val()))
		swipePage(null,"#searchResults")

	    $.getJSON("/iphone/searchtitles", {text: $("#headSearch").val()}, function(searchResults) {
			$("#searchResults .Roller").remove();
			//var onclick = "window.location=\"/resources/showMovie.html?movie_id=\"+this.href";
			if (searchResults.ERROR) {
			    $("#searchResults").append($("<div class='Warning'>No matches found</div>"));
			} else {
				$.each(searchResults, function() {
					$("<li/>").attr("href",this.movie_id).click(function() {
					    window.location="showMovie.html?id="+$(this).attr("href") + gPropagateParams;
					}).text(this.movie_name).appendTo("#searchResults")
				})
				$("#searchResult").append(credits);
			}

			/*
			if($("#SearchTopAd").length == 0)
			$("<li/>").attr("id","SearchTopAd").addClass("TopAd").prependTo("ul#searchResults");*/
			//prependAdd("06","search/movies", "#TopAd");
	    });
	}

	var resetTheaterSearch = function() {
		$("#zip").val("Zipcode").addClass("Empty").focus();
		$("#theaters li:not(.Back), #theaters .Footer").remove();
		$("#theaters").append(credits);
	};

	var SearchZip = function(auto) {    
		$("#theaters li:not(.Back), #theaters .Footer").remove();		
		var ziptext = $("#zip").val();
		ziptext = ziptext.replace(/\s/g, "");
	    if (!ziptext.match(/\d{5}/) || ziptext.length>5) {
			$("#theaters").append($("<li>Please enter a valid 5 digit zip code</li>"));
			$("#theaters").append(credits);
			return;
	    }
	
		
		$("#theaters").append(Roller("Loading "+$("#zip").val()))

		createCookie("zip",ziptext,30);
	
	    $.getJSON("/iphone/theaters", {"zip": ziptext,"auto": (gInitializing) ? 1 : 0}, function(searchResults) {
			$("#theaters .Roller").remove();
			if(searchResults.length>0 && !searchResults.ERROR) {
				$.each(searchResults, function() {
					var ticketing="";
					if(this.ticketing == "Y") {
						ticketing="<span>Get tickets &rarr;</span>"
					}
					$("<li/>").attr("href",this.house_id).text(this.house_name).click(function() {
					    window.location = "showTheater.html?id="+$(this).attr("href") + gPropagateParams;
					}).prepend(ticketing).appendTo("#theaters")
				})
			} else {
			    $("#theaters").append($("<li>No theaters found in " + $("#zip").val() + "</li>"));
			}
			$("#theaters").append(credits);
			//prependAdd("06","theater/theater_listing", "#TopAd");
	    });
	};	
	
	function makeSearchBox(id,init_text,mysearch,reset,destination) {
		// form to handle CR - why return false?
		var searchForm = $("<form/>").submit(function() {
			mysearch();
			return false;
		}); 
		
		// searchfield
		var inputElement = $("<input type='text'/>")
			.attr({id: id, name: id, value: init_text, className: "Empty", size:  10})
			.focus(function() { // clear contents of box on first click
				if($(this).is(".Empty")) {
					$(this).removeClass("Empty").val("");
				}
			}).blur(function() {
				if($(this).val()=="") {
					$(this).addClass("Empty").val(init_text)
				}
			}).appendTo(searchForm)

		// search button
		$("<img/>").attr({src: "images/search.png", alt: "Search"}).click(mysearch).prependTo(searchForm);
		// reset button
		$("<span>&times;</span>").addClass("clearX").click(reset).prependTo(searchForm);

		var searchdiv = $("<div/>").addClass("searchdiv").click(function(e) {e.stopPropagation()}).append(searchForm).prependTo(destination);
		if (gReferrer && id == "headSearch") {
		    searchdiv.css("width", "100px");
		    inputElement.css("width", "55px").attr("size",5);
		}
			
		var fromCookie = readCookie(id);
		if(fromCookie  && fromCookie!="") {
			inputElement.val(fromCookie).removeClass("Empty");
			mysearch(true);
		}
		return;
	}

	//
	// END SEARCH FUNCTIONS
	//


	// TEMPLATE FUNCTIONS
	var boxOffice = function(movie) {
		return "<li href='"+movie.movie_id+"'>"
			+"<span>($" + movie.gross + ")</span>"
			+"<img height=40 src='images/photos/69x100/"+movie.photo+"'>"
			+movie.movie_name+"</li>";
	}

	var findTheaters = function(movie) {
	}
	
	var newsTitles = function(story) {
		return "<li href='"+story.id+"'>"+story.headline+"</li>"		
	};
	
	var timesTickets = function(movie) {
		return "<li href='"+movie.movie_id+"'>"+movie.movie_name+"</li>"		
	};

	var gLastDate = 0;
	var newReleases = function(movie) {	    
	    if (movie.release0 != gLastDate) {
			gLastDate = movie.release0;
			return "<li class='NRDate'>"+movie.release0+"</li><li href='"+movie.movie_id+"'>" +movie.movie_name+"</li>"
	    } else {
			return "<li href='"+movie.movie_id+"'>"+movie.movie_name+"</li>"
//				"<img height=40 src='images/photos/69x100/"+this.photo+"'>"+				
	    }
	};
	// END TEMPLATE FUNCTIONS

	// this optional function is for action to take after the menu content has been populated
	var postMovieNews= function() {
		// Select each of these new list elements, except for the pre-existing one marked "Back"
		// and add a click action to each one..
	    var newsCounter = 0;
		$("#newsTitles > li").not(".Back").click(function() {

			// When clicked, toggle yourself selected and untag your siblings
			$(this).toggleClass("Selected")
			.siblings("li").removeClass("Selected");
			// TO-DO animated action
			// If I haven't already added a child div with news
			var isDisplayed = ($(this).children().css("display") == "block");

			if($(this).children("div").length==0) {
			    newsCounter++;
			    $(this).attr("id","NewsHeading" + newsCounter);

				// Get the news article related to this headline...
				$("#newsTitles > li.Selected").append(Roller("Loading story"))
				$.getJSON("/iphone/newsStory", {id: $(this).attr("href"),
									afid: gAFID,
									referrer: gReferrer,
									reficon: gRefIcon},
					  function(json) {
					// And insert it at the end of the LI
					$("#newsTitles > li.Selected > .Roller").remove();
					$("<div/>").addClass("Story")
					    .attr("id","NewsStory" + newsCounter)
					    .append(json[0].body).appendTo("#newsTitles > li.Selected");
				
					var rand = new Date().getTime();
					$("<div/>").attr("id","StoryAd" + newsCounter).css("float","right").prependTo("#NewsStory" + newsCounter);

					//prependAdd("04","news/news_details", "#StoryAd" + newsCounter);
					  });
				
		    } else if (isDisplayed) {
			   $(this).children().hide("slow");
			} else {
			   $(this).children().show("slow");
			}
		})
	};
	
	var populatePage = function(menuContents,thisMenu) {
	    if (menuContents.ERROR) {
		$("#"+thisMenu.datasource).append("Could not access data");
		return;
	    }

		// Remove loading Roller if there is one
		$("ul#"+thisMenu.datasource+" .Roller").remove();
	
	    // add each element to the content area per the provided template
		$.each(menuContents, function() {
			$("#"+thisMenu.datasource).append(thisMenu.template(this))
		})
	    // after this is populated, do any needed post-processing
	    if (thisMenu.post) {
			thisMenu.post()
		} else {
			if(!thisMenu.next){return;} // this makes a next action optional
			// default - add a click action to load a new page
			$("#"+thisMenu.datasource+" > li").not(".Back")
				.click(function() {
				    window.location = thisMenu.next+"?id=" + $(this).attr("href") + gPropagateParams;
				})
	    }
	    $("#"+thisMenu.datasource).append(credits);
	};

	// ************ THE ACTION BEGINS
	// To start: a simple array of hashes describing the menus
	// text: the string to appear as the menu item (required)
	// datasource: the url to fetch JSON fron; also, the id of the content block
	// template: formatting instructions for interpreting JSON - use flydom.js format
	// next: datasource action to take next with ID from JSON
	// post: actions to take after populating the content block
	var menus = [ 
		{ text: "Times & Tickets", datasource: "timesTickets", template: timesTickets, next: "showMovie.html" },
		{ text: "New Releases", datasource: "newReleases", template: newReleases, next: "showMovie.html" },
		{ text: "Box Office", datasource: "boxOffice", template: boxOffice, next: "showMovie.html" },
		{ text: "Find Theaters", datasource: "theaters", template: findTheaters, next: "showTheater.html" },
		{ text: "Movie News", datasource: "newsTitles", template: newsTitles, next: "newsStory", post: postMovieNews},
	]

	// Setup the banner logo to act as a back button/home button
    $("#CoolHeader").click(function() {if (gCurPage && gCurPage != "#Main") swipePage(null, "#Main", true)});

	// clear the loading banner from the main page
	$("ul#Main .Roller").remove();

	// For each of the defined home page menus
	$.each(menus, function(i, thisMenu) {
		// Add an li.Swiper for this menu to the main menu
		$("<li/>").addClass("Swiper")
			.attr({href:"#"+thisMenu.datasource, id:thisMenu.datasource+"_choice"})
			.append("<span>"+thisMenu.text+"</span>")
			.append("<img class='iArrow' src='/images/iArrow.png'>")
			.click(function() {
				swipePage($(this).parent(),$(this).attr("href"))
			})
			.appendTo("ul#Main");
		// Add a ul.Menu.Sub for the content associated with this menu to the body
		$("<ul/>").attr("id", thisMenu.datasource).addClass("Menu Sub").appendTo("#Content");

		// Put a first li.Back in the content area
		$("<li/>").addClass("Back").text(thisMenu.text).appendTo("#"+thisMenu.datasource);
		if(thisMenu.datasource!="theaters") {
			$("ul#"+ thisMenu.datasource).append(Roller("Loading "+thisMenu.text))			
		}
	});
	$.each(menus, function(i, thisMenu) {
		if (thisMenu.datasource == "theaters") {
			makeSearchBox("zip", "Zipcode",
				SearchZip, resetTheaterSearch,$("#"+thisMenu.datasource+" li.Back"));
		} else {
			// For this menu, get the JSON of the content
			$.getJSON("/iphone/"+thisMenu.datasource, {auto: 1}, function(menuContents) {
			    populatePage(menuContents,thisMenu);
			});
		}
	})

	// add search box to header

	   makeSearchBox("headSearch","Search",frontSearch,resetFrontSearch,$("#CoolHeader"))

	// make a destination for it
	$("<ul/>").attr("id", "searchResults").addClass("Menu Sub").appendTo("#Content");
	// add a back bar
	$("<li/>").addClass("Back").appendTo("#searchResults");
		
    
	// ************ MISCELLANEOUS
	
	// Add back buttons
	// populate li.Back with an a.iBack, with a click action to swipe back to main
	// TO-DO: preload the iBack background image
	//$("<a/>").addClass("iBack").text("back").prependTo("li.Back");
$("<a/>").addClass("iBack").text("Back").prependTo("li.Back");
	$("a.iBack").click(function() {swipePage($(this).parent().parent(), "#Main", true)})
	


	// Setup top movies carousel
	// give them a home by adding ul#TopPosters.
	// You can easily move it by changing the insertAfter target
	$("<ul/>").attr("id","TopPosters").addClass("jcarousel-skin-MovieTickets").append(Roller("Loading posters")).appendTo("ul#Main")


	
	// Preload carousel images
	$("<img/>").attr("src","js/skins/MovieTickets/next-horizontal.png")
	$("<img/>").attr("src","js/skins/MovieTickets/prev-horizontal.png")


	
	// No, browser scaling is not a good idea.  But I'm lazy. TO-DO (scale posters on server when updating DB)
	var posterWidth = 67;
	var posterHeight = 100;
	// Get the top 10 posters list

	$.getJSON("/iphone/top10posters", function(top10){
	    window.scrollTo(0, 1);  
	    var onclick = "window.location=\"/showMovie.html?movie_id=\"+this.href" + gPropagateParams;
		// This function dynamically provides images wrapped in li's on demand to the carousel
		// installed below as callback
		function top10_load(carousel, state) {
		    for (var i = carousel.first; i <= carousel.last; i++) {
		        if (carousel.has(i)) {continue;}
		        if (i > top10.length) {break;}
				var onclick = "window.location=\"/showMovie.html?id="+top10[i-1].movie_id + gPropagateParams + "\"";
		        carousel.add(i,
			 		"<li onclick='"+onclick+"' href="+top10[i-1].movie_id+">"+
					"<img src=\"/images/photos/69x100/"+top10[i-1].photo+"\" alt='"+top10[i-1].movie_name+"' width="+posterWidth+" height="+posterHeight+">"+
					"</li>");
		    }
		}

		// clear out loading roller
		$("#TopPosters .Roller").remove()	
			
		// create carousel
	    jQuery('#TopPosters').jcarousel({
			size: top10.length, // which is, duh, always 10, but better to do this
	        itemLoadCallback: {onBeforeAnimation: top10_load} // dynamic image loader install
	    })
	});


	
	// Add full site link
	$("<li/>")
			.click(function() {window.location="http://www.movietickets.com/"})
			.append("<span>Switch to full site</span>")
			.append("<img class='iArrow' src='/images/iArrow.png'>")
			.appendTo("ul#Main");


	// Insert an ad above the top entry.  For future expansion.  5 second fuse, then a slow roll.
//	window.setTimeout(function() {
//		$("<li/>").addClass("Ad").prependTo("ul#Main")
//		.append('<img alt="Transformers - #1 Movie in America" src="/images/transformers.jpg">').slideDown(1000);
//	}, 5000)
	
	// sign it
	$("ul#Main").append(credits);


	gInitializing = false;
})





