/*
* writen by: aa.temkin@gmail.com
* Last mod: 12.09.2008
* Release: 1
*/

	//if (!tsControl) tsControl = Class.create();
	tsControl.Selector = Class.create();
	tsControl.Selector.instances = 0;
	tsControl.Selector.prototype = Object.extend(tsControl.Selector,{
		initialize: function(options){
			tsControl.Selector.instances++;
			this.instance = tsControl.Selector.instances;
			this.items = [];
			this.options = Object.extend({
				target: false,
				name : 'selector[]',
				items : [],
				multiple : true,
				className : 'selector_container',
				classScroll : 'selector_croll',
				autocreate : true,
				removeItems : true,
				country : false,
				textDelete : '(#Delete#)',
				textNoTranslate : '(#not_translated#)',
				parent : null,
				onCreate : Prototype.emptyFunction,
				onClick : Prototype.emptyFunction,
				onComplete : Prototype.emptyFunction,
				onUpdate : Prototype.emptyFunction,
				onRemove : Prototype.emptyFunction,
				haveTwins : false
			},options || {});
			this.target = $(this.options.target);
			if ($(this.target)){
				if (this.options.autocreate){
					this.Create();
				}
			}else return false;
		},
		Create : function(){
			this.link = [];
			if (this.options.multiple && this.options.country) this.box = new Element('div');
			this.container = new Element('ul',{className : this.options.className});
			var i=0;
			var tmpItems = [];
			var HTML = [];
			if (this.options.items!=null && this.options.items)
			if (this.options.items[0]!=null) for(i=0;i<this.options.items.length;i++){
				try{
					var item = this.options.items[i];
					item['textDelete'] = this.options.textDelete;
					tmpItems[tmpItems.length] = item['id'];
					if (item['noItem']){
						item['text'] = this.options.textNoTranslate; 
					}
					var txt = '<li childof="#{parent}" item_id="#{id}" id="selector#{id}_'+this.instance+'">#{text}';
					this.getTree().items[this.getTree().items.length] = item['id'];
					if (this.options.removeItems){
						if (this.options.multiple || this.options.country){
							item['tmpID'] = this.getTree().uniqId();
							this.link[this.link.length] = item['tmpID'];
							txt+= '&nbsp;<a class="selector_container_delete" item_id="#{id}" href="javascript:void(0);" id="#{tmpID}">#{textDelete}</a>';
						}
					}
					txt+='</li>';
					var tTemplate = new Template(txt);
					var li = tTemplate.evaluate(item);
					HTML[HTML.length] = li;
				}catch(e){};
			}
			if (this.options.multiple && this.options.country){
				if (HTML.length>=5) this.box.setStyle({'height':'100px', 'overflow':'auto'});
				this.box.insert(this.container);
				this.target.insert(this.box);
			}else this.target.insert(this.container);
			if (HTML.length!=0){
				this.container.update(HTML.join(''));
				if (this.options.multiple || this.options.country){
					var i;
					for(i=0; i<this.link.length; i++) {
						if ($(this.link[i])){
							$(this.link[i]).observe('click',function(event){
								var elm = Event.element(event);
								if (elm.up().tagName=='LI'){
									var id = elm.readAttribute('item_id');
									this.getTree().uncheckNode(id);
									this.getTree().items = this.getTree().items.without(id);
									this.getTree().updateInput();
									elm.up().remove();
								}
								var k;
								for(k=0;k<this.link.length; k++){
									if (!$(this.link[k])) this.link = this.link.without(this.link[k]);
								}
							}.bind(this));
						}
					}
				}
			}
			//if (this.options.items.length==0) this.container.update('no no no David Blain');
		},
		
		Create_old : function(){
			if (this.options.multiple && this.options.country) this.box = new Element('div',{className : this.options.classScroll});
			this.container = new Element('ul',{className : this.options.className});
			var i=0;
			if (this.options.items!=null && this.options.items)
			if (this.options.items[0]!=null)
			for(i=0;i<this.options.items.length;i++){
				if ( !this.options.items[i] ) continue;
				if (!this.options.items[i]['path']) this.options.items[i]['path'] = '/'+this.options.items[i]['id']+'/';
				var obj = this.getTree().getItemById(this.options.items[i]['id']);
				if (obj){
					var id = this.options.items[i]['id'];
					this.getTree().items[this.getTree().items.length] = parseInt(id);
					this.getTree().items = this.getTree().items.uniq().compact();
					this.getTree().value = this.getTree().items.join(',');
					if (this.getTree().options.input) $(this.getTree().options.input).value = this.getTree().value;
					this.addItem(obj.info);
					this.getTree().checkNode(id);
				}else{
					this.getTree().getNode(0,function(){
						this.getTree().openNodeByPath(this.options.items[i]['path'],function(id,obj){
							this.getTree().items[this.getTree().items.length] = parseInt(id);
							this.getTree().items = this.getTree().items.uniq().compact();
							this.getTree().value = this.getTree().items.join(',');
							if (this.getTree().options.input) $(this.getTree().options.input).value = this.getTree().value;
							if (!obj){
								var obj = [];
								obj['info'] = {
									'id':id, 
									'haveChild' : false, 
									'opened' : false, 
									'url' : '#', 
									'parent' : null,
									'noItem' : true,
									'text': this.options.textNoTranslate
								};
								this.getTree().addNode(obj.info);
							}
							this.addItem(obj.info);
							this.getTree().checkNode(id);
							this.items = this.items.uniq();
						}.bind(this));
					}.bind(this));
				}
			}
			if (this.options.multiple && this.options.country){
				this.box.insert(this.container);
				this.target.insert(this.box);
			}else this.target.insert(this.container);
		},
		addItem : function(item){
			if (!this.options.multiple){
				for(i=0;i<this.items.length;i++){
					this.removeItem(this.items[i]['id']);
				}
			}
			var li = new Element('li',{title : item['text'],item_id : item['id'], id : 'selector'+item['id']+'_'+this.instance }).writeAttribute('level',item['level']).writeAttribute('childof',item['parent']);
			li.info = item;
			if (!item['name']) item['name'] = this.options.name;
			if (item['level']) item['text'] = item['text'];
			var title = new Element('span').update(item['text']);
			li.insert(title);
			if (this.options.multiple){
				var control = new Element('a',{href:'javascript:void(0);', item_id : item['id']}).update(' '+this.options.textDelete);
				li.insert(control);
				$(control).addClassName('selector_container_delete');
				control.observe('click',function(event){
					var elm = Event.element(event);
					var item_id = elm.readAttribute('item_id');
					this.getTree().uncheckNode(item_id);
					this.removeItem(item_id);
				}.bind(this));
			}
			var input = new Element('input',{type : 'hidden', name : item['name'], value : item['value']});
			li.insert(input);
			if (item['noItem']) $(li).addClassName('err');
			if (this.options.country){
				if (item['parent'] && item['parent']!=0 && item['parent']!=null){
					var obj = this.getItemById(item['parent']);
					if (obj){
						var elm = $(obj['element']);
						elm.insert(li);
					}else this.container.insert(li);
				}else this.container.insert(li);
			}else this.container.insert(li);
			item['element'] = li;
			item['instance'] = this.instance;
			this.items[this.items.length] = item;
			this.options.onUpdate(item,this);
			this.sortItems();
			return item;
		},
		
		sortItems : function(){
			
		},
		getValue : function(item,value){
			var obj = false;
			if (typeof(item)=='object') obj = $(item);
			else if (typeof(item)=='number') obj = $(this.items[item]['element']);
			if (obj){
				try{
					if (!value) value='item_id';
					if (obj.hasAttribute(value)) return obj.readAttribute(value);
					else return false;
				}catch(e){return false;}
			} return false;
		},
		getItemById : function(id){
			var i=0;
			for(i=0;i<this.items.length;i++){
				if (this.items[i]['id']==id) return this.items[i];
			}
			return false;
		},
		
		getTree : function(){
			if (this.options.parent) if (this.options.parent.Tree) return this.options.parent.Tree;
			return false;
		},
		Twice : function(){
			if (this.options.parent) if (this.options.parent.sysSelector) if (this.options.parent.sysSelector!=this) return this.options.parent.sysSelector;
			return false;
		},
		removeItem : function(id,nocall){
			if ($('selector'+id+'_'+this.instance)){
				var obj = this.getItemById(id); 
				var item = obj['element'];
				var stop = false;
				while(!stop){
					stop = true;
					for(i=0;i<this.items.length;i++){
						if (this.getValue(i,'childof')==id){
							this.removeItem(this.getValue(i),nocall);
							stop = false;
						}
					}
				}

				try{
					this.options.onRemove(item.info,this);
					$('selector'+id+'_'+this.instance).remove();
					item.remove(); 
				}catch(e){};
			}
			if (!nocall){
				if (this.getTree().getItemById(id).control.checked) this.getTree().uncheckNode(id);
			}
			for(i=0;i<this.items.length;i++){
				if (this.items[i]['id']==id) this.items = this.items.without(this.items[i]).uniq();
			}
			this.getTree().updateInput();
			if (!nocall) this.options.onUpdate();
			return this;
		},
		emptyItemList : function(){
			/*var stop = false;
			while(!stop){
				if (this.items.length==0) stop=true;
				for(i=0;i<this.items.length;i++) this.removeItem(this.items[i]['id'],true);
			}*/
			//if (this.items.length) 
			//this.container.update();
			return this;
		},
		updateItemList : function(items){
			items = items.uniq();
			new Ajax.Request(this.getTree().options.dataUrl,{
				method : 'POST',
				parameters : {
					'mode':'getItemsById',
					'id' : items.join(',')
				},
				onComplete : function(transport){
					var tmp_obj;
					var str = 'tmp_obj = '+transport.responseText+';';
					eval(str);
					this.target.update(this.options.textLoading);
					this.options.items = tmp_obj;
					this.Create();
				}.bind(this)
			});
		},
		updateItemList1 : function(items){
			this.emptyItemList();
			//if (!items) items = this.getTree().getFullItemsInfo();
			var stop = false;
			if (items)
			while(!stop){
				if (items.length==0) stop = true;
				for(i=0;i<items.length;i++){
					this.addItem(items[i]);
					items = items.without(items[i]);
				}
			}
			return this.items;
		},
		updateItems : function(){
			
		}
	});