/*
 * SimpleStore View
 * 
 */
SS.Views.SimpleStore = Backbone.View.extend({
	
	// Events bound to top level view
	events: {
		"click #searchbtn": "doSearch",
		"keypress #searchBox": "keyPressSearchProduct",
		"click #categoryLinks li > a:not( #moreLink )": "loadCategoryFromTab",
		"mouseover .more": "giveMoreCategories"
		//"mouseout .more": "hideMoreCategories"
		//"change #categoryDropdown": "loadCategoryFromDropdown"
	},
	
	
	// initialize
	initialize: function(spec) {
		var 
			that = this,
			renderedProductList = $("#products");
		
		// Bind this to functions
		_.bindAll(this, "render", "updateOrder", "doSearch", "loadCategory", "loadCategoryFromDropdown", "hideMoreCategories");
		
		// Custom handlers
		// TODO: figure out why default event doesn't work
		// Probably something to do with another delegation event binded at document level for the same element
		$(document).delegate("#categoryDropdown", "change", this.loadCategoryFromDropdown);
		$(document).bind("mouseover", this.hideMoreCategories);
		
		// Bind events handlers to models
		this.model.categoryList.bind("change:order", this.updateOrder)
		
		// Initialize global client-side cache object
		SS.Cache = {
			scope: "global",
			key: "",
			categoryCache: {
				"all": renderedProductList,
				currentCategory: "all"
			},
			searchCache: {
				"": renderedProductList,
				currentSearch: ""
			}
		};
		
		/*
		 	Create nested views
		*/
		
		// Create category views
		this.model.categoryList.each( function(category) {
			var id = category.get("id");
			id = id !== undefined ? id : "";
			
			// Create a reference to each view in the model for convenience
			category.view = new SS.Views.Category({
				model: category,
				el: $("#category_" + id)
			});
		});
		
		// Create cart view
		this.model.cartView = new SS.Views.Cart({
			model: this.model.cartModel,
			el: $("#cartArea")
		});
		
		// Create productlist view
		this.model.productListView = new SS.Views.ProductList({
			el: $("#productArea"),
			cartView: this.model.cartView // Pass a reference so views can easily access each other
		});
		if($("#productForm_fromFacebook").val()== "true") {
			EcommerceObj.createTabs();
		}
		/*
		 	Initialize visuals
		*/
		SS.Utils.initSelectBoxes();
		if($("#productForm_fromFacebook").val()== "false") {
			this.model.updateOrder( EcommerceObj.getEcommerceObj().categoryOrders );
		}
		
	},
	
	// Render function
	render: function() {
		return this;
	},
	
	
	updateOrder: function() {
		// Empty ul element without removing bindings and data
		var 
			$ul = $("#categoryLinks"),
			$prev = $ul.prev();
		
		$ul.children().detach();
		
		// Re-attach list elements in correct ordering
		this.model.categoryList.each( function(category) {
			$ul.append(category.view.render().el);
		});
		
		
		$ul.detach();
		$prev.after($ul);
	},
	
	
	loadCategoryFromDropdown: function(e) {
		var 
			$eventEl = $(e.currentTarget).find("option:selected"),
			targetName = $.trim($eventEl.html()).toLowerCase();
		
		this.loadCategory($eventEl.val(), targetName);
	},
	
	
	loadCategoryFromTab: function(e) {
		var 
			eventEl = e.currentTarget,
			targetName = $.trim(eventEl.innerHTML).toLowerCase();
		
		this.loadCategory(eventEl.href, targetName);
	},
	
		
	// Loads product list of categories via AJAX
	loadCategory: function(eventElHref, targetName) {
			
		var
			that = this,
			categoryCache = SS.Cache.categoryCache;
		
		// Set cache scope
		SS.Cache.scope = targetName === "all" ? "global" : "categoryCache";
		
		// Check cache
		if ( categoryCache[targetName] !== undefined ) {
			if ( categoryCache.currentCategory === targetName )
				return;
			
			//$("#products").replaceWith(categoryCache[targetName]);
			//categoryCache.currentCategory = SS.Cache.key = targetName;
			
			//return;
		}
		
		// Ajax loader
		SS.Utils.showAjaxLoader();
		
		// Load product html through GET request
		$.ajax({
			type: "GET",
			url: SS.Utils.buildHostUrl( document.location.href, eventElHref ),
			success: function(data) {
				var 
					dom = $("<div>" + data + "</div>"),
					productList = dom.find("#products");
				
				// Insert into cache
				if (categoryCache[categoryCache.currentCategory] === undefined) {
					categoryCache[categoryCache.currentCategory] = $("#products");
				}
				if (categoryCache[targetName] === undefined) {
					categoryCache[targetName] = productList;
				}
				
				// Replace product DOM element with new element
				categoryCache.currentCategory = SS.Cache.key = targetName;
				$("#products").replaceWith(productList);
				
				// Special initialization data is needed and element has been replaced
				// so re-run initSelectBoxes
				SS.Utils.initSelectBoxes();
				SS.Utils.hideAjaxLoader();
			}
		});
	},
	
		
	// Handles search
	keyPressSearchProduct: function(e) {

		if(e.keyCode == 13){
			this.doSearch(e);
		}
		
	},
	
	
	doSearch: function(e) {
		var
			that = this,
			searchCache = SS.Cache.searchCache,
			actionUrl = "/~site/siteapps/simplestore.action",
			searchKey = this.$("#searchBox").val().toLowerCase();
		    hiddenPath = this.$("#hiddenPath").val();
		
		if ( e ) {
			e.preventDefault();
		}
		
		// Set cache scope
		SS.Cache.scope = searchKey.length === 0 ? "global" : "searchCache";
		
		// If a category is selected we need to revert back to "all"
		this.model.categoryList.get("").view.select();
		SS.Cache.categoryCache.currentCategory = "";
		
		// Check cache
		if ( searchCache[searchKey] !== undefined ) {
			// return if we're in searchScope and we're accessing same search or
			// if we're in globalScope and we're trying to access the same cache key
			//if ( searchCache.currentSearch === searchKey )
				//return;
			
			//$("#products").replaceWith(searchCache[searchKey]);
			//searchCache.currentSearch = SS.Cache.key = searchKey;
			
			//return;
		}
		
		// Ajax loader
		SS.Utils.showAjaxLoader();
		
		$.ajax({
			type: "GET",
			data: $(document.searchForm).serialize(),
			url: document.location.protocol + "//" + document.location.host + document.location.pathname + (document.location.search === "" ? "?timestamp=" + (new Date()).getTime() + hiddenPath : document.location.search + "&timestamp=" + (new Date()).getTime() + hiddenPath),
			success: function(data) {
				var 
					dom = $("<div>" + data + "</div>"),
					productList = dom.find("#products");
				
				// Insert into cache
				if ( searchCache[searchCache.currentSearch] === undefined ) {	
					searchCache[searchCache.currentSearch] = $("#products");
				}
				if (searchCache[searchKey] === undefined) {
					searchCache[searchKey] = productList;
				}
				
				// Replace product DOM element with new element
				searchCache.currentSearch = SS.Cache.key = searchKey;
				$("#products").replaceWith(productList);
				
				SS.Utils.initSelectBoxes();
				SS.Utils.hideAjaxLoader();
			}
		});
	},
	
	
	giveMoreCategories: function(e) {
		if ( e ) {
			e.stopPropagation();
		}
		
		if ( $(".more ul").css("display") === "none" ) {
			$(".more").find("ul").show();
			$(".more").find("#moreLink").toggleClass("moreLink_hover", true);
		}
	},
	
	
	hideMoreCategories: function(e) {
		$(".more").find("ul").hide();
		$(".more").find("#moreLink").toggleClass("moreLink_hover", false);
	}
	
});

