var TreeSelector = function(config)
{
	this.rootName = '树根';
	this.title='树选择器';
	this.selectTitle='选择的节点';
	this.max=3;
	this.autoLoad=false;
	this.displayField=null;
	this.valueField=null;
	this.width=400;
	this.nodeWidth=120;
	this.single=false;
	this.cls='tree-selector';
	this.button=null;
	Ext.apply(this,config);
	this.tpl = new Ext.XTemplate('<tpl for="."><li class="tree-node child-count{child}" style="width:'+this.nodeWidth+'px"><input type="checkbox" {checked}><a href="javascript:void(0)">{title}</a></li></tpl><br style="clear:both"/>');
	this.selectedTpl = new  Ext.XTemplate('<tpl for="."><div class="tree-node" ><input type="checkbox" checked>{title}</div></tpl><br style="clear:both"/>');
	
	
	this.rendered=false;
	
	var globalStore = Ext.StoreMgr.get(this.tree)||new  Ext.data.JsonStore({
		storeId:this.tree,
		id:'id',
		url:'/api/?do=gettreenode&tree='+this.tree,
		fields:['id','title','parent','child','checked'],
		root:'nodes',
		listeners:{
			beforeload:function(){
				globalStore.loaded=true;
			}
		}
	});
	
	
	var loadData=function()
	{
		//nodeStore.data=globalStore.data.clone();
		
		var records =[];
		globalStore.data.each(function(r){
			records[records.length]=r;
		});
		nodeStore.loadRecords({records:records},{},true);
	}
	var nodeStore = new Ext.data.JsonStore({
		id:'id',
		fields:['id','title','parent','child','checked'],
		load:function(){
			nodeStore.fireEvent('beforeload');
			if(!globalStore.loaded){
				globalStore.load();
				globalStore.on('load',function(){
					loadData();
				});
			}else{
				if(globalStore.getCount()>0){
					loadData();
				}else{
					globalStore.on('load',function(){
						loadData();
					});
				}
			}
		},
		listeners:{
			'load':function(store){
				if(this.valueField && this.autoLoad)
					this.selectNode(this.valueField.dom.value);
				store.filter('parent',0);
				//this.sync();
			},
			scope:this
		}
		
	});
	this.nodeStore=nodeStore;
	this.nodeStore.on('datachanged',function(){
		if(this.rendered && this.el.isVisible()){
			this.el.alignTo(this.button,'tl-bl?');
		}
	},this,{delay:10});
	
	this.selectedStore = new Ext.data.JsonStore({
		fields:['id','title','parent','child','checked'],
		listeners:{
			add:function(){
				this.sync();
			},
			remove:function(){
				this.sync();
			},
			scope:this
		}
	});
	this.currentRoot=0;
	Ext.onReady(function(){
		if(this.displayField) this.displayField = Ext.get(this.displayField);
		if(this.valueField){
			this.valueField=Ext.get(this.valueField);
		}
		if(this.button){
			this.button = Ext.get(this.button);
			this.button.on('click',function(){
				this.show(this.button);
			},this);
			if(!this.displayField)
			{
				if(this.single)
					this.displayField = this.button;
				else{
					if(this.valueField){
						this.displayField = this.valueField.insertSibling({tag:'span'},'before');
						//this.displayField.dom.parentNode.style.border='1px solid red';
					}
				}
			}
		}
		if(this.autoLoad){
			this.nodeStore.load();
			this.render();
		}
	},this);
}
Ext.extend(TreeSelector,Ext.util.Observable,{
	show:function(target)
	{
		this.render();
		if(target){
			this.el.alignTo(Ext.get(target),'tl-bl?');
		}else{
			this.el.center();
		}
		this.el.show();
	},
	hide:function(){
		this.el.hide();
	},
	render:function(){
		if(this.rendered) return;
		this.rendered=true;
		this.el = new NiceLayer(this);
		
		this.el.body.update([
			'<div class="title" style="padding-left:10px"><div class="close" style="float:right"><a href="javascript:void(0)" style="padding:2px">关闭</a></div><h1 style="float:left">'+this.title+'</h1>('+(this.single?'单选':'最多可以选'+this.max+'项')+')<br style="clear:both"/></div>',
			'<div class="select-path"><span class="path-node" nid=0><a href="javascript:void(0)">'+this.rootName+'</a></span></div>',
			'<ul class="node-list"  ></ul>',
			'<h3 class="select-title">'+this.selectTitle+'</h3>',
			'<div class="selected-list"></div>',
			'<div class="close" style="text-align:center"><a href="javascript:void(0)">确定</a></div>'
		].join(''));
		
		this.el.on('click',function(ev){
			var node=null;
			if( node =ev.getTarget('span.path-node'))
					this.onPathClick(node);
			else if (ev.getTarget('.close')) this.onClose();
		},this);
		
		
		this.pathEl=this.el.body.child('.select-path');
		var view = new Ext.DataView({
			tpl:this.tpl,
			store:this.nodeStore,
			el:this.el.body.child('.node-list'),
			itemSelector:'.tree-node',
			cls:'selector-view',
			loadingText:'正在装载数据'
		});
		view.render();
		if(!this.autoLoad)
		this.nodeStore.load();
		view.on('click',function(v,i,n,e){
			var r = this.nodeStore.getAt(i);
			if(e.getTarget().nodeName=='INPUT' || r.get('child')==0)
			{
				if(this.isLock()) return;
				if(!r.get('checked'))
				{
					
					if(this.single) this.clearSelection();
					else{
						
						//if(this.nodeStore.snapshot||this.nodeStore.snapshot)
						if(r.get('parent')!='0' && this.nodeStore.snapshot.key(r.get('parent')).get('checked')=='checked' )
						{
							//alert('aaa');
							this.nodeStore.snapshot.key(r.get('parent')).data['checked']='';
							this.selectedStore.remove(this.selectedStore.getById(r.get('parent')));
						}
						
						if(this.selectedStore.getCount()>=this.max && !this.hasSelectedChild(r.get('id')) ){
							if(e.getTarget().nodeName=='INPUT'){
								e.getTarget().checked=false;
								e.getTarget().removeAttribute('checked');
							}
							return;
						}
					}
					if(r.get('child')>0){
						this.clearSelectedChildren(r.get('id'));
					}
					r.data['checked']='checked';
					Ext.fly(n).child('input',true).setAttribute('checked',true);
					this.selectedStore.add([r.copy()]);
				}else{
					//r.set('checked','',true);
					var checkbox = Ext.fly(n).child('input',true)
					checkbox.setAttribute('checked',false);
					checkbox.removeAttribute('checked');
					r.data['checked']='';
					this.selectedStore.remove(this.selectedStore.getById(r.get('id')));
				}
				return;
			}
			var id = r.get('id');
			var title=r.get('title');
			this.pathEl.insertHtml('beforeEnd',String.format('<span class="path-node" nid={0}>/<a href="javascript:void(0)">{1}</a></span>',id,title));
			this.listNode.defer(1,this,[id]);
		},this);
		this.nodeView=view;
		var selectedView = new Ext.DataView({
			store:this.selectedStore,
			tpl:this.selectedTpl,
			el:this.el.body.child('.selected-list'),
			itemSelector:'.tree-node'
		});
		selectedView.on('click',function(v,i,n,e){
			if(e.getTarget().nodeName=='INPUT')
			{
				var r  = v.store.getAt(i);
				//var oldLock = this.isLock();
				id=r.get('id');
				if(this.nodeStore.getById(id)){
					this.nodeStore.getById(id).set('checked','');
					
					
				}else if(this.nodeStore.snapshot && this.nodeStore.snapshot.key(id)){
					this.nodeStore.snapshot.key(id).data['checked']=''
				}
				v.store.remove.defer(1,v.store,[r]);
				/*
				if(oldLock && !this.isLock()){
					this.nodeView.el.select('input').each(function(el){
						el.dom.removeAttribute('disabled');
					});
				}*/
			}
		},this);
		this.selectedView=selectedView;
		selectedView.render();
		this.el.hide();
		
		Ext.getBody().on('click',function(ev){
			var target=ev.getTarget();
			if(ev.within(this.el)||target==this.button.dom) return;
			this.el.hide();
		},this);
		
	},
	listNode:function(pid){
		this.nodeStore.clearFilter(true);
		r = this.nodeStore.getById(pid);
		this.nodeStore.filter('parent',new RegExp('^'+pid+'$'));
		/*
		if(this.isLock()){ 
			this.nodeView.el.select('input').each(function(el){
					el.dom.setAttribute('disabled',true);
			});
		}*/
	},
	close:function(){
		
	},
	destroy:function(){
		if(this.rendered){
			this.nodeView.destroy();
			this.el.removeAllListeners();
			this.el.remove();
		}
	},
	onPathClick:function(node){
		var pid = node.getAttribute('nid');
		while(node.nextSibling) node.parentNode.removeChild(node.nextSibling);
		this.listNode(pid);
	},
	onClose:function(){
		this.hide();
		/*
		this.el.fadeOut({
			callback:this.destroy,
			scope:this
		})*/
	},
	onValueFieldChange:function()
	{
		this.selectNode(this.valueField.dom.value);
	},
	selectNode:function(nodes){
		this.clearSelection();
		if(!nodes||nodes=='0') return;
		var buff=[];
		var ids = nodes.split(',');
		var records = this.nodeStore.snapshot||this.nodeStore.data;
		if(records.getCount()==0) return;
		for(var i=0;i<ids.length;i++)
		{
			var r=this.nodeStore.getById(ids[i]);
			if(r){
				r.set('checked','checked');
			}else{
				r=records.key(ids[i]);
				r.data['checked']='checked';
			}
			buff.push(r.copy());
			
		}
		this.selectedStore.add(buff);
	},
	
	 clearSelection:function()
	{
		this.selectedStore.each(function(r){
			if(this.nodeStore.getById(r.get('id'))){
				this.nodeStore.getById(r.get('id')).set('checked','');
			}
			else this.nodeStore.snapshot.key(r.get('id')).data['checked']='';
			this.selectedStore.remove(r);
		},this);
	},
	clearSelectedChildren:function(parentId){
		var store = this.nodeStore;
		var selectedStore = this.selectedStore;
		var data = store.snapshot||store.data
		var isAncestor=function(nodeId){
			var match=false;
			
			var current = data.key(nodeId);
			while(current){
				if(current.get('parent')==parentId) return true;
				current=data.key(current.get('parent'));
			}
			return false
		}
		
		selectedStore.each(function(r){
			if(isAncestor(r.get('id'))){
				data.key(r.get('id')).data['checked']='';
				selectedStore.remove(r);
			}
		});
		
	},
	isLock:function(){
		return false;
		var lock=false;
		var data=this.nodeStore.snapshot||this.nodeStore.data;
		this.pathEl.select('.path-node').each(function(el){
			var id = el.dom.getAttribute('nid');
			if(data.key(id) && data.key(id).get('checked')){
				lock=true;
				return false;
			}
		});
		return lock;
	},
	onSelectChange:function(){
		
	},
	getSelectedValue:function(){
		var buff=[];
		this.selectedStore.each(function(r){
			buff.push(r.get('id'));
		});
		return buff.join(',');
	},
	getSelectedText:function(){
		var buff=[];
		this.selectedStore.each(function(r){
			buff.push(r.get('title'));
		});
		return buff.join(',');
	},
	sync:function(){
		if(this.displayField)
		{
			if(this.displayField.dom.nodeName=='INPUT') this.displayField.dom.value=this.getSelectedText()||this.emptyText;
			else this.displayField.update(this.getSelectedText()||this.emptyText);
		}
		if(this.valueField) this.valueField.dom.value= this.getSelectedValue()
		
	},
	hasSelectedChild:function(id){
		
		var store = this.nodeStore;
		var selectedStore = this.selectedStore;
		var data = store.snapshot||store.data
		var isAncestor=function(nodeId){
			var match=false;
			
			var current = data.key(nodeId);
			while(current){
				if(current.get('parent')==id) return true;
				current=data.key(current.get('parent'));
			}
			return false
		}
		var found=false;
		selectedStore.each(function(r){
			if(isAncestor(r.get('id'))){
				found=true;
				return false;
			}
		});
		return found;
	}
});


var CitySelector=function(config)
{
	var c={
		rootName:'省份',
		//url:'/api/?do=gettreenode&tree=city',
		tree:'city',
		title:'地区选择',
		selectTitle:'已选择的地区',
		width:460,
		nodeWidth:140,
		single:true,
		emptyText:'地区不限'
	}
	Ext.apply(c,config);
	CitySelector.superclass.constructor.call(this,c);
}
Ext.extend(CitySelector,TreeSelector);

var PositionSelector=function(config){
	var c={
		rootName:'职位顶级分类',
		//url:'/api/?do=gettreenode&tree=post',
		tree:'post',
		title:'职位分类选择',
		selectTitle:'已选择的职位',
		width:600,
		nodeWidth:190,
		single:true,
		emptyText:'职位不限'
	}
	Ext.apply(c,config);
	PositionSelector.superclass.constructor.call(this,c);
}
Ext.extend(PositionSelector,TreeSelector);
var MajorSelector=function(config){
	var c={
		rootName:'专业顶级分类',
		//url:'/api/?do=gettreenode&tree=major',
		tree:'major',
		title:'专业选择',
		selectTitle:'已选择的专业',
		width:600,
		nodeWidth:190,
		single:true
	}
	Ext.apply(c,config);
	MajorSelector.superclass.constructor.call(this,c);
}
Ext.extend(MajorSelector,TreeSelector);

var DateSelector = function(config)
{
	var store = new Ext.data.SimpleStore({
		fields:['value','title'],
		data:[
			[1,'一天内'],[3,'三天内'],[7,'一周内'],[15,'半月内'],[30,'一月内'],[90,'三个月内']
		]
	});
	Ext.apply(this,config);
	Ext.onReady(function(){
		this.el = new NiceLayer({width:320,cls:'tree-selector'});
		this.el.body.update([
			'<div><div class="close" style="float:right"><a href="javascript:void(0)">关闭</a></div>日期选择</div>'
		].join(''));
		this.el.child('.close').on('click',function(){
			this.el.hide();
		},this);
		this.view = new Ext.DataView({
			store:store,
			tpl:'<tpl for="."><li style="width:90" class="tree-node"><a href="javascript:void(0)">{title}</a></li></tpl>',
			el:this.el.body.createChild({tag:'ul'}),
			itemSelector:'.tree-node',
			style:'padding:10px',
			listeners:{
				click:function(v,i,n,e){
					var r = v.store.getAt(i);
					this.button.dom.value=r.get('title');
					this.valueField.dom.value=r.get('value');
					this.el.hide();
				},
				scope:this
			}
		});
		this.view.render();
		this.button = Ext.get(this.button);
		this.valueField=Ext.get(this.valueField);
		this.button.on('click',function(){
			this.el.show();
			this.el.alignTo(this.button,'tl-bl');
		},this);
		Ext.getBody().on('click',function(ev){
			if(ev.within(this.el)||ev.getTarget()==this.button.dom) return;
			this.el.hide();
		},this);
	},this);
}

