/*
 * Ext JS Library 2.2.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

Ext.grid.filter.ListFilter = Ext.extend(Ext.grid.filter.Filter, {
	labelField:  'text',
	tooltipField: 'fullSource',
	categoryField: 'domestic',
	domesticOnly:false,
	foreignOnly:true,
	domesticUsage:true,
	category:'',
	sourceStore:null,
	loadingText: 'Loading...',
	loadOnShow:  true,
	value:       [],
	loaded:      false,
	phpMode:     false,
	toolbar:	null,
	
	init: function(){
		
		
		this.menu.add('<span class="loading-indicator">' + this.loadingText + '</span>');
		
		if(this.store && this.loadOnShow) {
		  this.menu.on('show', this.onMenuLoad, this);
		} else if(this.options) {
			var options = [];
			for(var i=0, len=this.options.length; i<len; i++) {
				var value = this.options[i];
				switch(Ext.type(value)) {
					case 'array':  
            options.push(value);
            break;
					case 'object':
            options.push([value.id, value[this.labelField]]);
            break;
					case 'string':
            options.push([value, value]);
            break;
				}
			}
			
			this.store = new Ext.data.Store({
				reader: new Ext.data.ArrayReader({id: 0}, ['id', this.labelField])
			});
			this.options = options;
			this.menu.on('show', this.onMenuLoad, this);
		}
		this.store.on('load', this.onLoad, this);
		this.sourceStore = this.store;
		this.bindShowAdapter();
	},
	
	/**
	 * Lists will initially show a 'loading' item while the data is retrieved from the store. In some cases the
	 * loaded data will result in a list that goes off the screen to the right (as placement calculations were done
	 * with the loading item). This adaptor will allow show to be called with no arguments to show with the previous
	 * arguments and thusly recalculate the width and potentially hang the menu from the left.
	 * 
	 */
	bindShowAdapter: function() {
		var oShow = this.menu.show;
		var lastArgs = null;
		this.menu.show = function() {
			if(arguments.length == 0) {
				oShow.apply(this, lastArgs);
			} else {
				lastArgs = arguments;
				oShow.apply(this, arguments);
			}
		};
	},
	
	onMenuLoad: function() {
		if(!this.loaded) {
			if(this.options) {
				this.store.loadData(this.options);
      } else {
				this.store.load();
      }
		}
	},
	
	onLoad: function(store, records) {
		//console.log('store loading');
		var visible = this.menu.isVisible();
		this.menu.hide(false);
		
		this.menu.removeAll();
		var menuItemList = [];
		menuItemList['DOM_BUS'] = new Ext.menu.Menu();
		menuItemList['FOR_BUS'] = new Ext.menu.Menu();
		menuItemList['DOM_GEN'] = new Ext.menu.Menu();
		menuItemList['FOR_GEN'] = new Ext.menu.Menu();
		menuItemList['ICE_BUS'] = new Ext.menu.Menu();
		menuItemList['DOM_FUN'] = new Ext.menu.Menu();
		menuItemList['ICE_ABR'] = new Ext.menu.Menu();
		menuItemList['DOM_SPO'] = new Ext.menu.Menu();
		var gid = this.single ? Ext.id() : null;
		//var domesticMenu = new Ext.menu.Menu();
		//var foreignMenu = new Ext.menu.Menu();
		
		
		
		for(var i=0, len=records.length; i<len; i++) {
			
			var item = new Ext.menu.CheckItem({
				text: records[i].get(this.tooltipField),
				queryStr: records[i].get(this.labelField),
				group: gid, 
				checked: !(this.value.indexOf(records[i].id) > -1),
				tooltip:records[i].get(this.tooltipField),
				hideOnClick: false
			});
			
			item.itemId = records[i].id;
			item.on('checkchange', this.checkChange, this);
			//console.log(this.value.indexOf(records[i].id) > -1);
			//this.menu.add(item);
			
			if(records[i].get(this.categoryField)==this.category) {
				item.checked=true;
				menuItemList[this.category].add(item);
			}else if(menuItemList[records[i].get(this.categoryField)]){
				item.checked=false;
				menuItemList[records[i].get(this.categoryField)].add(item);
			}
			
		}
		if(this.domesticUsage) {
		var domGenItem = new Ext.menu.CheckItem({
			text:keldan_lang_text('news-domestic'),
			checked:this.category=='DOM_GEN',
			hideOnClick:false,
			category:'DOM_GEN',
			menu:menuItemList['DOM_GEN']
		});
		domGenItem.on('checkchange',this.checkGroupChange,this);
		this.menu.add(domGenItem);
		
		var domBusItem = new Ext.menu.CheckItem({
			text:keldan_lang_text('news-dombus'),
			checked:this.category=='DOM_BUS',
			category:'DOM_BUS',
			hideOnClick:false,
			menu:menuItemList['DOM_BUS']
		});
		domBusItem.on('checkchange',this.checkGroupChange,this);
		this.menu.add(domBusItem);
		
		var forGenItem = new Ext.menu.CheckItem({
			text:keldan_lang_text('news-foreign'),
			checked:this.category=='FOR_GEN',
			category:'FOR_GEN',
			hideOnClick:false,
			menu:menuItemList['FOR_GEN']
		}); 
		forGenItem.on('checkchange',this.checkGroupChange,this);
		this.menu.add(forGenItem);
		
		var forBusItem = new Ext.menu.CheckItem({
			text:keldan_lang_text('news-forbus'),
			checked:this.category=='FOR_BUS',
			category:'FOR_BUS',
			hideOnClick:false,
			menu:menuItemList['FOR_BUS']
		});
		forBusItem.on('checkchange',this.checkGroupChange,this);
		this.menu.add(forBusItem);
		var domFunItem= new Ext.menu.CheckItem({
			text:keldan_lang_text('news-domfun'),
			checked:this.category=='DOM_FUN',
			category:'DOM_FUN',
			hideOnClick:false,
			menu:menuItemList['DOM_FUN']
		});
		
		domFunItem.on('checkchange',this.checkGroupChange,this);
		this.menu.add(domFunItem);
		
		var iceAbrItem= new Ext.menu.CheckItem({
			text:keldan_lang_text('news-forice'),
			checked:this.category=='ICE_ABR',
			category:'ICE_ABR',
			hideOnClick:false,
			menu:menuItemList['ICE_ABR']
		});
		
		iceAbrItem.on('checkchange',this.checkGroupChange,this);
		this.menu.add(iceAbrItem);
		
		var sportItem = new Ext.menu.CheckItem({
			text:keldan_lang_text('news-sports'),
			checked:this.category=='DOM_SPO',
			category:'DOM_SPO',
			hideOnClick:false,
			menu:menuItemList['DOM_SPO']
		});
		sportItem.on('checkchange',this.checkGroupChange,this);
		this.menu.add(sportItem);
		
		}else {
			var iceBusItem = new Ext.menu.CheckItem({
				text:keldan_lang_text('news-dombus'),
				checked:this.category=='ICE_BUS',
				category:'ICE_BUS',
				hideOnClick:false,
				menu:menuItemList['ICE_BUS']
			});
			iceBusItem.on('checkchange',this.checkGroupChange,this);
			this.menu.add(iceBusItem);
			
			var forGenItem = new Ext.menu.CheckItem({
				text:keldan_lang_text('news-foreign'),
				checked:this.category=='FOR_BUS',
				category:'FOR_BUS',
				hideOnClick:false,
				menu:menuItemList['FOR_BUS']
			});
			forGenItem.on('checkchange',this.checkGroupChange,this);
			this.menu.add(forGenItem);
		}
			
			
			
		this.setActive(this.isActivatable());
		this.loaded = true;
		
		if(visible) {
			this.menu.show(); //Adaptor will re-invoke with previous arguments
    }
	},
	
	checkChange: function(item, checked) {
		//console.log('checkChange');
		var value = [];
		this.menu.items.each(function(item) {
			item.menu.items.each(function(i) {
			if(i.checked) {
				value.push(i.queryStr);
			}
      })
		},this);
		this.value = value;
		this.setActive(this.isActivatable());
		this.fireEvent("update", this);
	},
	checkGroupChange:function(item,checked) {
		item.menu.items.each(function(i){
			i.suspendEvents();
			i.setChecked(checked);
			i.resumeEvents();
		});
		this.checkChange(item, checked);
	},
	isActivatable: function() {
		return this.value.length > 0;
	},
	
	setValue: function(value) {
		var value = this.value = [].concat(value);

		if(this.loaded) {
			this.menu.items.each(function(item) {
				item.menu.items.each(function(j){
					j.setChecked(false, true);
					for(var i=0, len=value.length; i<len; i++) {
						if(j.itemId == value[i]) {
						j.setChecked(true, true);
          }
        }
			})	}, this);
		}
			
		this.fireEvent("update", this);
	},
	
	getValue: function() {
		return this.value;
	},
	setCategoryValues : function(category,values,notify) {
		var sourceVals = new Ext.util.MixedCollection();
		sourceVals.addAll(values);
		var value = [];
		var scope = {
				obj:this,
				notify:notify
		};
		this.menu.items.each(function(item){
			//if(item.category==category) {
				//console.log('got menu with category '+category);
				item.menu.items.each(function(mitem) {
					if(sourceVals.contains(mitem.queryStr)) {
						mitem.setChecked(true,true);
						value.push(mitem.queryStr);
					}else
						mitem.setChecked(false,true);
					
				});
				scope.obj.value = value;
				scope.obj.setActive(scope.obj.isActivatable(),scope.notify);
				
			//}
				
				
		},scope);
		
		//console.log('reload filters');
	},
	serialize: function() {
    var args = {type: 'list', value: this.phpMode ? this.value.join(',') : this.value};
    this.fireEvent('serialize', args, this);
		return args;
	},
	
	validateRecord: function(record) {
		var res = this.getValue().indexOf(record.get(this.dataIndex)) > -1;
		return res;
	}
});