﻿/// <reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5-vsdoc.js" />
/// <reference path="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js" />
/// <reference path="debugversions/ba-debug.js" />
/// <reference path="debugversions/underscore.js" />
/// <reference path="debugversions/underscore.strings.js" />
/// <reference path="BondiTouch.js" />
/// <reference path="BondiTouch.Utility.js" />

/* ************************************************************************************************
* ************************************************************************************************
*  TODO: The IssueListing is CURRENTLY the same for all users, and stays constant for all past decades and years.
*  Eventually the issue listing will be in two parts - user's issues and all issues.  The all issues bit  
*  is ripe for caching on the client - suggest that the server side-rendered html fragments are cached to local 
*  storage, and a lazy-load approach is used (look first in local storage, if  not found, look at server
* ************************************************************************************************
* ************************************************************************************************/

(function () {

	var $ = jQuery,
		_b = BondiTouch;

	/* IssueListing Functions */
	_b.IssueListing = {
		_loaded: false,
		_loading: false,

		// cache jquery objects
		$s: {
			body: $("body"),
			header: $("header"),
			menu: $("#menu_issues"),
			menuButton: $("#issuesButton"),
			contents: $("#issuesContents")
		},

		// ----------------------------------------------------------------------------
		init: function () {
			var that = this, this$s = this.$s;

			//Hook up menu button
			this$s.menuButton.click(function () { that.toggleMenu(); });
		},

		// ----------------------------------------------------------------------------
		//		fitIssuesMenu: function () {
		//			var margin = 5,
		//			startWidth = 252 //this.$s.decadesSection.width() + this.$s.yearsSection.width() + margin,
		//			//startHeight = this.$s.header.height() + margin;
		//			$("#issues").width(this.$s.body.width() - startWidth);
		//			//	.height(this.$s.body.height() - startHeight);
		//		},

		// ----------------------------------------------------------------------------
		loadTimeline: function () {
			if (this._loaded || this._loading)
				return;

			var that = this,
				this$s = this.$s;

			this._loading = true;

			//TODO: Display loading graphic instead
			this$s.contents.html("<div class='menu_message'>Loading...</div>");

			//load the timeline, and hook up events on completion
			this$s.contents.load(_b.Utility.makeProxyUrl(_b.Uri.timeline), function (response, status, xhr) {
				that._loading = false;

				if (status == "error") {
					debug.error("The BondiTouch.IssueListing.loadTimeline callback reported an error: " + response);
					return;
				};

				that._loaded = true;

				//Append newly created elements to jQuery cache
				this$s = $.extend(this$s, {
					decadesSection: $("#issueDecades"),
					yearsSection: $("#issueYears"),
					issuesSection: $("#issues")
				});

				//Add Decade click behavior, and 'click' the first decade (i.e. chronologically latest decade)
				this$s.decadesSection.find(".issueDecade")
				.click(function () { that.onIssueDecadeClick($(this)); })
				.first().click();

				//Add Year click behavior
				this$s.yearsSection.find(".issueYear")
				.click(function () { that.onIssueYearClick($(this)); });
				//Click the selected decade's first child
				this$s.yearsSection.find("ul.selected").children().first().click();

				// //make sure the menu fits
				// $(window).bind("resize", that.fitIssuesMenu);
				// that.fitIssuesMenu();
				
				that.handleResize();
			});
		},

		// ----------------------------------------------------------------------------
		onIssueDecadeClick: function ($el) {
			var this$s = this.$s;
			//don't repeat clicks:
			if ($el.hasClass("selected")) { return; }

			//cleanup from last decade click
			this$s.issuesSection.empty();
			this$s.decadesSection.find(".issueDecade").removeClass("selected");
			$el.addClass("selected");


			//show only the years for the clicked decade
			var decade = $el.attr("data-decade");
			this$s.yearsSection.find(".issueYears").removeClass("selected");
			this$s.yearsSection.find("#issueDecade" + decade).addClass("selected");
		},

		// ----------------------------------------------------------------------------
		onIssueYearClick: function ($el) {
			//don't repeat clicks:
			if ($el.hasClass("selected")) { return; }

			//cleanup from last year click
			this.$s.yearsSection.find(".issueYear").removeClass("selected");
			$el.addClass("selected");

			//get the issues
			var year = $el.attr("data-year");
			this.loadIssues(year);
		},

		// ----------------------------------------------------------------------------
		loadIssues: function (year) {
			// Load the Library timeline  
			//TODO: switch to use jquery.tmplt
			var that = this,
				this$s = this.$s,
				uri = _.template(_b.Uri.issues, { "year": year });

			this$s.issuesSection.load(_b.Utility.makeProxyUrl(uri), function (response, status, xhr) {
				if (status == "error") {
					//TODO: Handle error load
					debug.error("The BondiTouch.IssueListing.loadIssues callback reported an error: " + response);
					return;
				};
				
				//Add click events to covers and dates
				this$s.issuesSection.find("a.issueLink").click(function () { 
					that.onIssueClick($(this)); 
				})

				that.handleResize();
			});
		},

		// ----------------------------------------------------------------------------
		onIssueClick: function ($el) {
			var issue = $el.attr("data-issue");
			_b.Core.navigateTo(issue);
		},

		// ----------------------------------------------------------------------------
		//TODO: Tap into standard menu toggle function (to be created)
		toggleMenu: function () {
			//TODO: Explicitly call show/hide rather than toggle to avoid duplicating other calculations
			var this$s = this.$s;
			if (this$s.menu.is(":hidden")) {
				//TODO: We need a standalone menu show/hide that uses CSS3 transforms for iPad
				//hide all open menus
				// Showing: Cancel the timeout
				$(".menu").hide();
				this$s.menu.focus();
				this.loadTimeline();
				this$s.menu.show();
				this.handleResize();
				this$s.menuButton.addClass("selected");
			} else {
				this.$s.menu.hide();
				this$s.menuButton.removeClass("selected");
			}
		},

		// ----------------------------------------------------------------------------
		handleResize: function () {
			if (this.$s.menu.is(":hidden"))
				return;
			
			var left = $("#issueYears").width() + $("#issueDecades").width(); 
			var availWidth = $("#menu_issues").width() - left - $("#closeIssues").width();
			var $issues = $("#issues");
			$issues
				.css({left: left})
				.width(availWidth || 400);	
				
			$("#issuesContents").css({"min-height": $issues.height()});		
		}

	};

	//BondiTouch.libLoadTimeline = function () {
	//	// Load the menu interactivity
	//	_b$.issuesMenuButton.unbind("click").bind("click", _b.libToggleMenu);
	//	// Load the Library timeline
	//	_b$.libTimeline.load(_b.Utility.makeProxyUrl(_b.Uri.timeline), _b.onLibLoadTimelineComplete);
	//};

	// ----------------------------------------------------------------------------

	//BondiTouch.onLibLoadTimelineComplete = function (response, status, xhr) {
	//	if (status == "error") {
	//		//TODO: Handle error load
	//		debug.error("The BondiTouch.loadLibTimeline callback reported an error: " + response);
	//		return;
	//	};
	//	//TODO: At some point we should just scroll the menu and leave the header menu alone
	//	//var tocScroll = new iScroll("menu_contents");
	//	_(_b$).extend({
	//		libClose: $("#libClose")
	//	});
	//	_b$.libClose.click(_b.libToggleMenu);
	//
	//	//Add Decade click behavior
	//	_b$.libTimeline.find("li.libDecade").click(function () { _b.onLibDecadeClick($(this)); });
	//
	//	//Add Year click behavior
	//	_b$.libTimeline.find("li.libYear").click(function () { _b.onLibYearClick($(this)); });
	//
	//	//"click" the currently loaded decade and year, to keep synchronized with the currently loaded issue
	//	var currentDecade = Math.floor(_b.navState.issueKey / 100000) * 10,
	//		    currentYear = Math.floor(_b.navState.issueKey / 10000);
	//	_b$.libTimeline.find("li.libDecade[data-decade=" + currentDecade + "]").click();
	//	_b$.libTimeline.find("li.libYear[data-year=" + currentYear + "]").click();
	//
	//};


})();
