/************************************************************
		
					Amadori.com / 2011
					
					amadoriProductMenu.js

		<----------------------------------------->
		
		Agency: vanGoGh
		Agency URL: http://vangogh-creative.it
		Author: Federico Weber
		Author URL: http://federicoweber.com

		<----------------------------------------->
			
					TABLE OF CONTENTS
				• CREATE DEPENDENCIES
				• DEFINE MVC
					- FirstLevelElement_Model
					- LevelElements_Collection
					- FirstLevelMenuElement_View
					- SubLevelMenuElement_View
					- ProductMenu_View

				• INIT

		<----------------------------------------->


************************************************************/

$(function amadoriProductMenu(){
	"use strict";
	//--------------------------------------------------------------------------> CREATE DEPENDECIES
	// This is the Model that controll the ChekBox interface
	var ChekBox_Model = Backbone.Model.extend({
		defaults: {
			"checked": false,
			"id": this.cid,
			"title": this.cid 
		},

		checked: function(){
			return this.get("checked");
		}
	});

	// This is the Collection that contain all the Checkbox for the interface
	var MultiToggle_Collection = Backbone.Collection.extend({
		model: ChekBox_Model,

		//set the  default name that is used for the local storage
		initialize: function() {
			this.name = "multiToggle";
			this.bind('change', this.toggleList, this);
		},

		//create a local storage for the collection is it possible to pass a custom name for it
		setStorage: function(name){
			if (name){
				this.name = name;
			}	
			this.localStorage = new Store(this.name);
		},

		checked: function(){
			 return this.filter(function(check){ return check.checked(); });
		}

	});	

	// CREATE DEPENDECIES <--------------------------------------------------------------------------
		
	//--------------------------------------------------------------------------> DEFINE MVC
	var Element_Model = Backbone.Model.extend({
		defaults: {
			"cat": "generico",
			"active": false
		}
	});

	var LevelElements_Collection = Backbone.Collection.extend({
		model: Element_Model,

		//return active element
		active: function(){
			return this.filter(function(check){ return check.get("active"); });
		}

	});

	// This is the view for the first level menu
	var FirstLevelMenuElement_View = Backbone.View.extend({
		tagName: "li",
		// compile the template once for faster rendering
		template:  Handlebars.compile($("#1LevelElement-template").html()) ,

		// bind events from the model
		initialize: function() {
			this.className = "cat_"+this.model.get("cat");
			this.model.bind('change', this.render, this);
		},

		events: {
			"click": "setActive"
		},

		render: function(){

			$(this.el).html(this.template(this.model.toJSON()));	
			if(this.model.get("active")){
				$(this.el).addClass("active");	
			} else {
				$(this.el).removeClass("active");	
			}
			return this;
		},

		setActive: function() {
			// set all of the elements inactive
			this.model.collection.each(function(model){
				model.set({"active": false});
			});
			this.model.set({"active": true});

			//trigger activated event
			this.model.collection.trigger("activated");
		}
	});

	//This is the view for the sublevel menues
	var SubLevelMenuElement_View = Backbone.View.extend({
		tagName: "li",
		// compile the template once for faster rendering
		template:  Handlebars.compile($("#subLevelElement-template").html()) ,

		// bind events from the model
		initialize: function() {
			this.model.bind('change', this.render, this);
		},

		events: {
			"click": "setActive"
		},

		render: function(){

			$(this.el).html(this.template(this.model.toJSON()));	
			if(this.model.get("active")){
				$(this.el).find(".li_prod").addClass("active");	
			} else {
				$(this.el).find(".li_prod").removeClass("active");	
			}
			return this;
		},

		setActive: function() {
			// set all of the elements inactive
			this.model.collection.each(function(model){
				model.set({"active": false});
			});
			this.model.set({"active": true});

			//trigger activated event
			this.model.collection.trigger("activated", true);
		}
	});

	//This view will take care of the entire menu app
	var ProductMenu_View = Backbone.View.extend({
		tagName: "aside",
		el: "#menu_prodotti",
		init: true,

		events: {
			"mouseenter": "openRelated",
			"mouseleave": "closeSublevels"
		},

		initialize: function(){
			//use this var to enable debug
			this.debug = false;

			//console.log("---> initialize");
			//Instantiate the collections
			this.firstLevelData = new LevelElements_Collection({id: "firstLevel"});
			this.secondLevelData = new LevelElements_Collection({id: "secondLevel"});
			this.thirdLevelData = new LevelElements_Collection({id: "thirdLevel"});
			this.collections = [this.firstLevelData, this.secondLevelData, this.thirdLevelData];
			
			//bind all the events related to the collections
			this.firstLevelData.bind('reset', this.firstLevelReset, this);
			this.secondLevelData.bind('reset', this.secondLevelReset, this);
			this.thirdLevelData.bind('reset', this.thirthLevelReset, this);

			this.firstLevelData.bind('activated', this.firstLevelActivated, this);
			this.secondLevelData.bind('activated', this.secondLevelActivated, this);
			this.thirdLevelData.bind('activated', this.thirthLevelActivated, this);

			//Read from the html to get active menu element on page load
			this.firstLevelActive = $("#level1_wrap").data("active");
			this.secondLevelActive = $("#level2_wrap").data("active");
			this.thirdLevelActive = $("#level3_wrap").data("active");

			//prepare url link for the sevels
			this.secondLevelUrl = "";
			this.thirdLevelUrl = "";

			//set base color class
			this.changeColorClass("generico");

			//Kick in loading data for the first level
			this.loadDataLevel(0, $("#menu_prodotti").data("firstlevelurl"));

			//Force sublevels to close after 2,5 sec
			var that = this;			
			var delayedClose = function() {
				//var show = $("#menu_prodotti").animate({"opacity": 1}, 500, 'easeInOutCubic');
				//that.closeSublevels(show,10);
				$("#menu_prodotti").animate({"opacity": 1}, 500, 'easeInOutCubic');
			};

			setTimeout(delayedClose,1500);
			
			$("#menu_prodotti").css({"opacity": 0});
		},

		changeColorClass: function(cat){
			$("#level1_wrap").removeClass().addClass("level1 cat_"+cat);
			$("#subMenulevle2Holder").removeClass().addClass("prod_sub_menu level2 cat_"+cat+"_l2");
			$("#subMenulevle3Holder").removeClass().addClass("prod_sub_menu level3 cat_"+cat+"_l3");	
		},

		loadDataLevel: function(level, url){
			
			if(this.debug){
				console.log("---> loadDataLevel level: "+level+", url: "+url);
			}	

			var that = this;
			var load = function(){
			//load the proper level data
				$.getJSON(url+'?profilo='+currentProfile,function(data){
					//if have a description use it for the second level
					if(data.abstract){
						that.secondLevelDescription = data.abstract;
					}	

					//copy the url or clean it
					if(data.url){
						if(level == 1){
							//that.secondLevelUrl = data.url;
							//MOdifica short url tecla
							var longURL = data.url;
							longURL = longURL.toString();
							var shortURL = longURL.replace('wps/wcm/connect/it/home','site'); 
							that.secondLevelUrl = shortURL;
						}else if(level == 2){
							//that.thirdLevelUrl = data.url;
							//MOdifica short url tecla
							var longURL = data.url;
							longURL = longURL.toString();
							var shortURL = longURL.replace('wps/wcm/connect/it/home','site'); 
							that.thirdLevelUrl = shortURL;
						}
					} else {
						if(level == 1){
							that.secondLevelUrl = "";
						}else if(level == 2){
							that.thirdLevelUrl = "";
						}
					}
						
					// assign the data to the proper colleciton and reset it 
					if(that.collections){
						that.collections[level].reset(data.elements);
					}

				});
			};

			// the debounce is used to prevent funciton overriding befoar load is completed
			var lazyLoad = _.throttle(load, 500);
			lazyLoad();

		},

		firstLevelReset: function(){
			var that = this;
			
			//create first level menu view
			this.firstLevelData.each(function(element){
				var view = new FirstLevelMenuElement_View({model: element, id: element.get("id"), className: "cat_"+element.get("cat")});
				$("#level1_wrap ul").append(view.render().el);
				that.updateMeuHeight();
			});

			//activate base passed element, load the proper sublevel and clear firstLevelActive once done
			if(this.firstLevelActive){
				if(this.firstLevelData.get(this.firstLevelActive)){
					this.firstLevelData.get(this.firstLevelActive).set({"active": true});
					this.firstLevelData.trigger("activated");
				}
				this.firstLevelActive = false;
			}

			if(this.debug){
				console.log("---> firstLevelReset firstLevelData: ");
				console.log(this.firstLevelData);
			}	

			//enable mouse event
			this.delegateEvents({
				"mouseenter": "openRelated",
				"mouseleave": "closeSublevels"
			});
		},
		firstLevelActivated: function(){
			if(this.debug){
				console.log("---> firstLevelActivated");
			}	

			this.undelegateEvents();

			//open callback function
			var load = function(that){	

				//clear sublevel collections
				//that.collections[1].reset({},{silent: true});	
				//that.collections[2].reset(({},{silent: true}));

				//set current colorCLass
				that.changeColorClass(that.firstLevelData.active()[0].get("cat"));

				//load second level 
				that.loadDataLevel(1, that.firstLevelData.active()[0].get("urllev"));

			};

			//close sublevel and load
			this.closeSublevels(load);
		},

		secondLevelActivated: function(){
			if(this.debug){
				console.log("---> secondLevelActivated");
			}	

			this.undelegateEvents();

			var model = this.secondLevelData.active()[0];
			var urllev = model.get("urllev");
			
			//MOdifica short url tecla
			var longURL = model.get("url");
			longURL = longURL.toString();
			//var shortURL = longURL.toString();
			var shortURL = longURL.replace('wps/wcm/connect/it/home','site'); 
			var url = shortURL;

			var that = this;


			//open subLevel or open url
			if(urllev && urllev !== "" ){
				//load callback function
				var load = function(that){

				//load third level 
				that.loadDataLevel(2, urllev);
				};

				//close sublevel and load
				this.animateLevels("close", "#subMenulevle3Holder", -2, load);
				
			} else {
				//open callback function
				var open = function(){		
					window.open(url,"_self");
				};
				
				//close sublevel and load
				this.closeSublevels(open);
			}
		},

		thirthLevelActivated: function(){
			if(this.debug){
				console.log("---> thirthLevelActivated");
			}	

			this.undelegateEvents();

			var model = this.thirdLevelData.active()[0];
			
			//MOdifica short url tecla
			var longURL = model.get("url");
			longURL = longURL.toString();
			//var shortURL = longURL.toString();
			var shortURL = longURL.replace('wps/wcm/connect/it/home','site'); 
			var url = shortURL;

			//open callback function
			var open = function(){			
				window.open(url,"_self");
			};

			//close sublevel and load
			this.closeSublevels(open);
		},

		closeSublevels: function(callback,time){
			if(this.debug){
				console.log("---> closeSublevels");
			}	

			//shrink nav width
			$("#menu_prodotti nav").stop().animate({"width":"223px"},time? time : 1000);


			this.animateLevels("close", "#subMenulevle3Holder", -2, null, time);
			this.animateLevels("close", "#subMenulevle2Holder", -13, callback, time);
		},

		openRelated: function(){
			
		var activeAreaWidth  = 223;

			if(this.debug){
				console.log("---> openRelated");
			}	
			
			// turn off init fase
			if (this.init === true && this.secondLevelData.length){
				this.init = false;
			}

			var l1Active = this.firstLevelData.active(), l2Active = this.secondLevelData.active();	

			//open first level
			if(l1Active.length > 0 && this.secondLevelData.length > 0){
				this.animateLevels("open", "#subMenulevle2Holder", 190);	
				activeAreaWidth = 416;
			}
			//open second level
			if(l2Active.length > 0 && this.thirdLevelData.length > 0){
				this.animateLevels("open", "#subMenulevle3Holder", 404);
				activeAreaWidth  = 700
			}

			//expand nav width
			$("#menu_prodotti nav").stop().animate({"width":activeAreaWidth+"px"},0);

		},


		animateLevels: function(action, target, movingRange, callback, time){
			
			// if(this.debug){
			// 	console.log("---> animateLevels action: "+action+", target: "+target+", callback: "+callback);
			// }

			var that = this, time = time? time : 400;

			switch(action){
				case "close":
					if($(target).hasClass('open')){
	
						$(target).removeClass('open');
						$(target).stop(true,true).animate({
							"left": movingRange+"px"
						}, time, 'easeInOutCubic', function(){
		
							if(typeof callback === "function"){
			
								callback(that);
							}
						});						
					} else if (typeof callback === "function"){
	
						callback(that);
					}

					break;

				case "open":
					if(target === "#subMenulevle3Holder"){
						time = 600;
					}
					$(target).addClass('open');
					$(target).stop(true,true).animate({
						"left": movingRange+"px"
					}, time, 'easeInOutCubic', function(){
	
						if(typeof callback === "function"){
							callback(that);
						}
					});	
					break;
			}	
						
				
		},

		secondLevelReset: function(){
			var that = this;

			//remove old scrollbar if it exist
			var jScroll = $("ul.level2").jScrollPane().data().jsp; 
			jScroll.scrollToY(0,false);
			jScroll.destroy();
			$("ul.level2").empty();

			//add the description, title and url
			$(".desc_level2").html(this.secondLevelDescription);
			$(".title_level2").html(this.firstLevelData.active()[0].get("name"));
			if(this.secondLevelUrl.length){
				$("#bt_linea_2").click(function(){
					window.open(that.secondLevelUrl,"_self");
				})
			}

			//populate the menu using jspPane created div
			this.secondLevelData.each(function(element){
				var view = new SubLevelMenuElement_View({model: element, id: element.get("id"), className: "cat_"+element.get("cat")});
				$("#level2_wrap ul").append(view.render().el);
			});

			this.updateMeuHeight();

			//apply custom scrollbar
			$("ul.level2").jScrollPane({
				verticalDragMinHeight:  54,
				verticalDragMaxHeight:  54,
				horizontalDragMinWidth: 15,
				horizontalDragMaxWidth: 15
			});

			//activate base passed element, load the proper sublevel and clear firstLevelActive once done
			if(this.secondLevelActive && this.secondLevelData && this.init === true){
				var elementModel = this.secondLevelData.get(this.secondLevelActive);
				var urllev = elementModel.get("urllev");

				if(typeof urllev !== "undefined" && urllev !== "" ){
					elementModel.set({"active": true});
					this.secondLevelData.trigger("activated");
				}
				this.secondLevelActive = false;

			} 

			if(this.debug){
				console.log("---> secondLevelReset secondLevelData: ");
				console.log(this.secondLevelData);
			}

			//menu open and close logic
			if(this.init === false && this.secondLevelData.length){
				this.openRelated();	
			}

			//enable mouse event
			this.delegateEvents({
				"mouseenter": "openRelated",
				"mouseleave": "closeSublevels"
			});

		},

		thirthLevelReset: function(){
			var that = this;

			//remove old scrollbar if it exist
			var jScroll = $("ul.level3").jScrollPane().data().jsp; 
			jScroll.scrollToY(0,false);
			jScroll.destroy();

			//update title and url
			if(this.secondLevelData.active()[0]){
				$(".title_level3").html(this.secondLevelData.active()[0].get("name"));
			}
			if(this.thirdLevelUrl.length){

				$("#bt_linea_3").click(function(){
					window.open(that.thirdLevelUrl,"_self");
				})
			}



			$("ul.level3").empty();

			//populate the menu using jspPane created div
			this.thirdLevelData.each(function(element){
				var view = new SubLevelMenuElement_View({model: element, id: element.get("id"), className: "cat_"+element.get("cat")});
				$("#level3_wrap ul").append(view.render().el);
			});

			this.updateMeuHeight();

			//apply custom scrollbar
			$("ul.level3").jScrollPane({
				verticalDragMinHeight:  54,
				verticalDragMaxHeight:  54,
				horizontalDragMinWidth: 15,
				horizontalDragMaxWidth: 15
			});

			//open sublevl if manually activated
			if(this.init === false && this.secondLevelData.length){
				this.openRelated();
			} 			

			if(this.debug){
				console.log("---> thirthLevelReset thirdLevelData: ");
				console.log(this.thirdLevelData);	
			}
			
		},

		updateMeuHeight: function(){
			var menu_h = $('.level1').height();
			var menu_2_h = menu_h - (($(".desc_level2").height())) -108;	
			var menu_3_h = menu_h-93;

			if(this.secondLevelData.length < 2){
				menu_2_h = menu_h;
			}

			if(this.thirdLevelData.length < 2){
				menu_3_h = menu_h;
			}

			$('#menu_prodotti nav').height(menu_h+"px");
			$('.level2 ul').height(menu_2_h+"px");
			$('.level3 ul').height(menu_3_h+"px");

			$("#menu_prodotti").css({"display": "block"});
			
			//console.log("---> updateMeuHeight menu_h: "+menu_h+", amProductMenu: "+menu_2_h+", menu_3_h: "+menu_3_h);

			//enable mouse event
			this.delegateEvents({
				"mouseenter": "openRelated",
				"mouseleave": "closeSublevels"
			});
		}

	});



	//DEFINE MVC <--------------------------------------------------------------------------

	//--------------------------------------------------------------------------> INIT

	//get current Profile or set consumer 
	var currentProfile = "consumer";
	var profiles = new MultiToggle_Collection();
	profiles.setStorage("AmadoriMenu-profiles");
	profiles.fetch();
	if(!profiles.length){
		var consumer = new ChekBox_Model({"id": "consumer", "title": "consumatore", "checked": true});
		profiles.add(consumer);
	}

	//check current profile for data load
	if(profiles.checked()[0].id !== "consumer") {
		currentProfile = "pro";
	}
	
	//create the app and kick in 
	var productMenu = new ProductMenu_View();

	//INIT<----------------------------------------------------------------------------

});
