var MultiItemTable = new Class({
	Implements: Events,
	initialize: function(ele, compIds, group) {
		this.gda = getGDA();
		if (group) {
			this.endpoints = new Hash({
				"catsSTUB":'/static/js/stub/',
				"cats": "/json/categories.jsp?catGroup=",
				"gda": "/json/gda.jsp?",
	          	"menu_item": "/json/menu-item.jsp?gda=" + this.gda + "&menu_item="			
			});			
		} else {
			this.endpoints = new Hash({
				"catsSTUB":'/static/js/stub/',
				"cats": "/json/categories.jsp?catName=",
				"gda": "/json/gda.jsp?",
	          	"menu_item": "/json/menu-item.jsp?gda=" + this.gda + "&menu_item="			
			});
		}
		
		this.keys = ["calories", "protein", "carbs", "sugar", "fat", "satfat", "fibre", "salt"];
		this.group = group;
		this.frm = ele;
		this.catID = $("categoryID").value;
		this.sub = $("add_item");
		this.spinner = $$("img.spinner");
		this.link = $("full_nut_link");
		this.alink = $("full_ing_link");
		// this.link.setStyle("display", "none");

		this.selects = [];
		this.ids = compIds;
		
		compIds.each(function(id,i){
			//console.log("here")
			//console.log(id)
			this[id+"_select"] = $(id);
			this.selects.push($(id));
			this[id+"_id"] = 0;
			
			this[id+"_mass_cells"] = $$("table td."+id+"_mass");
			//console.log("after")
			//console.log(this[id+"_mass_cells"].length)
			this[id+"_range_cells"] = $$("table td."+id+"_range");
		}.bind(this))

		//this.setupUI(); delegated to after cats loaded
		this.sub.setStyle("display", "none")
		this.setListeners();
		this.fetchData(this.endpoints.get("cats")+this.catID, "categories");
	},

	setupUI: function() {
		this.selects.each(function(sel,i){
			sel.addEvent("change", this.handleMenuItemSelect.bindWithEvent(this, this.ids[i]));
			sel.fireEvent("change");
		}.bind(this));
	},

	setListeners: function() {
		this.addEvent("dataLoaded", this.handleDataLoaded);
		this.addEvent("fetchDataStarted", function(){this.spinner.setStyle("display", "block")});
		this.addEvent("dataLoaded", 	  function(){this.spinner.setStyle("display", "none")});

		this.responders = new Hash({
			"categories": this.handleCategoriesLoaded,
			"menu_item":  this.handleMenuItemLoaded
		});

		this.responder_objs = new Hash({
			"categories": "categories",
			"menu_item":  "menuitem"
		});
	},
	
	handleDataLoaded: function(key, data, comp) {
		if (comp) {
			this[comp+"_id"] = data.menuitem.meta.id;
			this.update_link();
		}
		if(key == "gda_init" || key == "gda_changed" || data[this.responder_objs[key]]) {
			this.responders[key].run([data, comp], this);
		} else {
			this.handleDataError.run(data, this);
		}
	},
	
	update_link: function() {
		var url1 = "/food/nutrition/nutrition-counter.mcd?"
		var url2 = "/food/nutrition/our-ingredients.mcd?"
		this.ids.each(function(id){
			url1 += "selected_menu_item="+this[id+"_id"]+"&";
			url2 += "menu_item="+this[id+"_id"]+"&";
		}.bind(this))
		url1 += "#dl"
		url2 += "#dl"
		if (!($$('.i-happymeal')[0])) {this.link.setProperty("href",url1);}
		if (!($$('.i-happymeal')[0])) {this.alink.setProperty("href",url2);}
		// this.link.setStyle("display", "block");
	},
	
	handleDataError: function(data) {
		this.fireEvent("dataError");
		alert("ERROR "+data.err[0].err_code+":\n"+data.err[0].err_description);
	},
	
	fetchData: function(dataPath, key, comp) {
		this.fireEvent("fetchDataStarted");
		new Request.JSON({method: 'get', url: dataPath, onComplete: function(data){ this.fireEvent("dataLoaded", [key, data, comp]);}.bind(this)}).get();
	},
	
	handleCategoriesLoaded: function(data) {
		data.categories.each(function(cat,i){
			var sel = this.selects[i];
			sel.empty()
			cat.items.each(function(opt,i){ 
 				new Element("option", {value:opt.id, html:opt.title, "class":"opt"+i}).inject(sel);
			}.bind(this));
		}.bind(this))
		
		this.setupUI();
	},
	
	handleMenuItemSelect: function(e,comp) {
		var sel = $(comp);
		this.getMenuItem(sel.value, comp)
	},
	
	getMenuItem: function(val,comp) {
		this.fetchData(this.endpoints.get("menu_item")+val, "menu_item", comp);
	},
	
	handleMenuItemLoaded: function(data, comp) {
		$(comp+"_title").set("html",data.menuitem.meta.name);
		if($(comp+"_title2")) {$(comp+"_title2").set("html",data.menuitem.meta.name);};

		this.keys.each(function(key,i){
			this[comp+"_mass_cells"][i].set("text", data.menuitem.nutrition.bymass[key]);
			this[comp+"_range_cells"][i].getElement('span.gml').set("text", data.menuitem.nutrition.per100gml[key]);
			this[comp+"_range_cells"][i].getElement('span.gda').set("text", data.menuitem.nutrition.byGDA[key]);
		}.bind(this));
		
		if (this.group) {
			var idx = this.ids.length;
			$$("table td.total_mass").each(function(totalMass,i) {
		        var loop = idx;
				var total = 0;
				while (loop--) {
					total += $$('table td.item_sel'+loop+'_mass')[i].get('text').toInt();
				};
				totalMass.set("text",total);
			});
		}
	}
});

window.addEvent('domready', function(){
	if (!$("nojs") && $("happy_meal_table_form")) { 
		window.multiItemTable = new MultiItemTable($("happy_meal_table_form"), ["item_sel0", "item_sel1", "item_sel2"], true);
	}

	if (!$("nojs") && $("subrange_table_form")) { 
		window.multiItemTable = new MultiItemTable($("subrange_table_form"), ["item_sel0"], false);}
});