var Ingredients = new Class({
	Implements: Events,
	initialize: function(ele) {
		this.deepHash = "#dl"
		this.deep = window.location.hash == this.deepHash;
		this.endpoints = new Hash({
			"cats": "/json/categories.jsp?catGroup=ingredients",
			"gda": "/json/gda.jsp?",
            "menu_item": "/json/menu-item.jsp?menu_item="			
		});
		
		//this.warners = ["nu","pe"];
		this.warners = [];
		
		
		this.main_fields = $("selection_fields");
		this.deep_info = $("deep_linked")
		
		this.frm = ele;
		this.subbtn = $("view_ing");
		this.updatecategory = $("update_category");
		this.spinner = $$("img.spinner");
		this.cat_sel = $("cat");
		this.men_sel = $("menu_item");
		this.deli_fields = $("deli_fields");
		this.deli_defaults = $$("#deli_brd_brown","#deli_chs_no","#deli_sld_no");
		this.accord_wrap = $("accord_ing_wrap");
		this.allergens = $("allergens");
		
		this.categories = new Hash();
		this.deli_items = new Hash();
		
		this.setupUI();
		if (!this.deep) this.setListeners();
		if (!this.deep) this.fetchData(this.endpoints.get("cats"), "categories");
	},
	
	setupUI: function() {
		if (this.deep) this.main_fields.setStyle("display", "none");
		if (this.deep) this.deep_info.setStyle("display", "block");
		
		this.subbtn.setStyle("display", "none");
		this.updatecategory.setStyle("display", "none");
		if (!this.deep) this.accord_wrap.empty();
		if (!this.deep) this.allergens.getChildren().each(function(li){li.set("class", "")});
		
		if (!this.deep) this.cat_sel.addEvent("change", this.handleCategorySelect.bindWithEvent(this))
		if (!this.deep) this.men_sel.addEvent("change", this.handleMenuItemSelect.bindWithEvent(this))
		
		this.ing_accord = new Accordion($('accord_ing_wrap'), 'h4.toggler', 'div.accord_ele', {alwaysHide:true, display:null});				
	},
	
	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")});
		
		$$("#deli_fields input").each(function(input, i){ input.addEvent("change", this.getMenuItem.bindWithEvent(this)) }.bind(this));
		
		this.responders = new Hash({
			"categories": this.handleCategoriesLoaded,
			"menu_item":  this.handleMenuItemLoaded
		});
		
		this.responder_objs = new Hash({
			"categories": "categories",
			"menu_item":  "menuitem"
		});
	},
	
	fetchData: function(dataPath, key) {
		this.fireEvent("fetchDataStarted");
		new Request.JSON({method: 'get', url: dataPath, onComplete: function(data){ this.fireEvent("dataLoaded", [key, data]);}.bind(this)}).get();
	},
	
	deliRbChecker: function(name) {
		el = deli_fields.getElements('input[name='+name+']');
		return el.get("checked").contains(true);
	},
	
	handleDataLoaded: function(key, data) {
		if(key == "gda_init" || key == "gda_changed" || data[this.responder_objs[key]]) {
			this.responders[key].run(data, this);
		} else {
			this.handleDataError.run(data, this);
		}
	},
	
	handleDataError: function(data) {
		this.fireEvent("dataError");
		alert("ERROR "+data.err[0].err_code+":\n"+data.err[0].err_description);
	},
	
	handleCategoriesLoaded: function(data) {
		this.categories = data.categories;
		this.setUpSelects(this.cat_sel, this.categories, true);
		this.setUpSelects(this.men_sel, this.categories[0].items, false);
		this.handleMenuItemSelect();
	},
	
	setUpSelects: function(sel, opts, cat) {
		sel.empty();
		opts.each(function(opt,i){ 
			var key = cat ? i : opt.id;
			this.deli_items[opt.id] = opt.deli; new Element("option", {value:key, html:opt.title, "class":"opt"+i}).inject(sel);
		}.bind(this));
	},
	
	
	handleCategorySelect: function() {
		this.setUpSelects(this.men_sel, this.categories[this.cat_sel.value].items, false);
		this.handleMenuItemSelect();
	},
	
	handleMenuItemSelect: function() {
		this.setUpDeliFields(this.deli_items.get(this.men_sel.value))
		this.getMenuItem();
	},
	
	getMenuItem: function() {
		this.fetchData(this.endpoints.get("menu_item")+this.men_sel.value+'&'+this.deli_fields.toQueryString(), "menu_item");
	},
	
	handleMenuItemLoaded: function(data) {
		this.accord_wrap.empty();
		this.ing_accord.togglers.empty();
		this.ing_accord.elements.empty();
		
		for (var i = data.menuitem.components.length - 1; i >= 0; i--){
			var ing = data.menuitem.components[i];
			var h4 = new Element("h4", {"class":"toggler","html":ing.title});
			var wrp = new Element("div", {"class":"accord_ele","html":"<p>"+ing.ingredients+"</p><br />"});
			this.ing_accord.addSection(h4,wrp);
		};
		
		if (data.menuitem.components.length == 1) this.ing_accord.display(0);
		
		data.menuitem.allergens.each(function(all,i){
			// var cls = this.warners.contains(all.t) ? "w" : all.v;
			var cls = all.v;
			$("allergen_"+all.t).set("class", cls);
		}.bind(this));
	},
	
	setUpDeliFields: function(needed) {
		if (needed) {
			this.deli_fields.setStyle("display", "block");
			this.deli_defaults.setProperty("checked", "checked");
		} else {
			this.deli_fields.setStyle("display", "none");
			$$("#deli_fields input").each(function(input, i){ input.setProperty("checked", ""); });
		}
	}
});

window.addEvent('domready', function(){
	if (!$("nojs") && $("ingredients_frm")) { window.ingredients = new Ingredients($("ingredients_frm"));}
});