var DropdownChecklist = new Class({
	options : {
	    width: null,
	    maxDropHeight: null,
	    firstItemChecksAll: false,
	    lastItemChecksAll: true,
	    itemOptions:{'items':[]},
	    minWidth: 50
	},
	
	initialize : function(id, options) {
		var self = this;

		self.sourceObj = $(id);
		if (options != null) {
			self.options = $merge(self.options, options);
		}

		self.sourceObj.style.display = 'none';
		self.sourceObj.disabled = true;
		self.controlWrapper = self.appendControl();
		self.dropWrapper = self.appendContainer();

		self.setSize(self.appendItem(self.options.itemOptions));

		self.drop = false;
		self.controlWrapper.addEvent('click', function(e) {
			new Event(e).stopPropagation();// 停止事件传播
			self.toggleDropContainer();
		});
	},
	
	// 创建div模仿select下拉
	appendContainer : function(){
		var wrapper = new Element('div',{
			'class': 'ui-dropdownchecklist-dropcontainer-wrapper',
			'styles': {
		        'position': 'absolute',
		        'top': '-3300px',
		        'left': '-3300px',
		        'width': '3300px',
		        'height': '3300px'
		    }
		});
		wrapper.inject(document.body);
		
		var container = new Element('div',{
			'class': 'ui-dropdownchecklist-dropcontainer',
			'_name': 'container',
			'styles': {
		        'overflow-y': 'auto'
		    }
		});
		container.inject(wrapper);
		
		return wrapper;
	},
	
	// 创建span模仿select
	appendControl : function(){
		var options = this.options;
		
		var wrapper = new Element('span',{
			'class': 'ui-dropdownchecklist-wrapper',
			'styles': {
		        'cursor': 'default',
		        'display': 'inline-block'
		    }
		});
		wrapper.inject(this.sourceObj,'after');
		
		var control = new Element('span',{
			'class': 'ui-dropdownchecklist',
			'_name': 'control',
			'styles': {
		        'display': 'inline-block'
		    }
		});
		control.inject(wrapper);
		
		var textContainer  = new Element('span',{
			'html': options.text,
			'class': 'ui-dropdownchecklist-text',
			'_name': 'textContainer',
			'styles': {
		        'display': 'inline-block',
		        'overflow': 'hidden'
		    }
		});
		textContainer.inject(control);
		
		wrapper.addEvents({
			'mouseover':function(){
				control.addClass('ui-dropdownchecklist-hover');
			},
			'mouseout':function(){
				control.removeClass('ui-dropdownchecklist-hover');
			},
			click : function(){
				// TODO:点击事件未完成
			}
		});
		
		return wrapper;
	},
	
	createContainterItem : function(options) {
		var op = {
			'class' :'ui-dropdownchecklist-item',
			'styles' : {
				'whiteSpace' :'nowrap'
			},
			'events': {
		        'click': function(e){
					new Event(e).stopPropagation();// 停止事件传播
		        }
			}
		};
		if (options) {
			op = $merge(op, options);
		}
		return new Element('div', op);
	},
	
	createItem : function(index, value, text, clickFn, checked, indent){
		var self = this;

		var item = self.createContainterItem();
		if (indent) {
			item.addClass("ui-dropdownchecklist-indent");
		}
		
		var checkBoxOp = {
			'type' :'checkbox',
			'index':index,
			'_text':text,
			'value':value,
			'styles' : {
				'whiteSpace' :'nowrap'
			},
			'events': {
				'click': function(e){
					new Event(e).stopPropagation();// 停止事件传播
				}
			}
		}
		if (checked) {
			checkBoxOp['checked'] = 'checked';
		}
		var checkBox = new Element('input', checkBoxOp);
		item.grab(checkBox);
		
		var label = new Element('span',{
			'class': 'ui-dropdownchecklist-text',
			'text': text,
			'styles': {
		        'cursor': 'default',
		        'width': '100%'
		    }
		});
		item.grab(label);
		
		var clickFn = clickFn.bind(checkBox);
		checkBox.addEvent('click', clickFn);
		item.addEvents( {
			'mouseover' : function() {
				item.addClass('ui-dropdownchecklist-item-hover');
			},
			'mouseout' : function() {
				item.removeClass('ui-dropdownchecklist-item-hover');
			},
			'click' : function(e) {
				if(!checkBox.disabled){
					checkBox.checked = !checkBox.checked;
					clickFn();
				}
			}
		});
		
		return item;
	},
	
	appendItem : function(itemOptions) {
		var self = this, options = this.options;
		var container = this.dropWrapper.getElement('div[_name=container]');
		container.setStyle('float','left');
		
		itemOptions.items.each(function(item,index){
			var clickFn = item.clickFn?item.clickFn:itemOptions.clickFn;
			var createItem = item.createItem?item.createItem.bind(self):self.createItem.bind(self);
			container.grab(createItem(index,item.value,item.text,clickFn,item.checked,item.indent));
		});
		
		var dropSize = container.getSize();
		container.setStyle('float','');
		return dropSize;
	},
	
	setSize: function(dropSize){
		var options = this.options, dropWrapper = this.dropWrapper, controlWrapper = this.controlWrapper;
		
		var controlWidth;
		
		if (options.width) {
            controlWidth = parseInt(options.width);
        } else {
            controlWidth = dropSize.x;
            var minWidth = options.minWidth;
            if (controlWidth < minWidth) {
                controlWidth = minWidth;
            }
        }
        controlWrapper.getElement('span[_name=textContainer]').setStyle('width',controlWidth);
        
        var controlOuterWidth = controlWrapper.getSize().x;
        var dropHeight = options.maxDropHeight ? parseInt(options.maxDropHeight) : dropSize.y;
        var dropWidth = dropSize.x < controlOuterWidth ? controlOuterWidth : dropSize.x;

        dropWrapper.setStyles({
        	'width':dropWidth,
        	'height':dropHeight
        })
        
        dropWrapper.getElement('div[_name=container]').setStyle('height',dropHeight);
	},
	
	toggleDropContainer: function(){
		var self = this, dropWrapper = this.dropWrapper, controlWrapper = this.controlWrapper;

        var hideFn = function(e) {
			if (e) {
				new Event(e).stopPropagation();// 停止事件传播
			}

			self.dropWrapper.setStyles( {
				'top' :'-3300px',
				'left' :'-3300px'
			});
			self.controlWrapper.getElement('span[_name=control]').removeClass('ui-dropdownchecklist-active');
			self.drop = false;

			$(document).removeEvents('click');
		};

		if (self.drop) {
			hideFn();
		} else {
			var controlPosition = self.controlWrapper.getPosition();
			var controlSize = self.controlWrapper.getSize();
			self.dropWrapper.setStyles( {
				'top' :controlPosition.y + controlSize.y,
				'left' :controlPosition.x
			});
			self.controlWrapper.getElement('span[_name=control]').addClass('ui-dropdownchecklist-active');
			self.drop = true;
			$(document).addEvent('click', hideFn);
		}
	}
});

var DropdownChecklist2 = new Class({
	Extends: DropdownChecklist,
	
	initialize : function(id, options) {
		var self = this;
		if (typeof options == 'object') {
			self.options = $merge(self.options, options);
		}
		
		self.sourceObj = $(id);
		
		var items = [];
		for(var i=0,len=self.sourceObj.options.length;i<len;i++){
			var selectOp = $(self.sourceObj.options[i]);
			items.push({
				'text':selectOp.get('text'),
				'value':selectOp.get('value')
			});
		}
		
		var textId = self.getTextId();
		var valueId = self.getValueId();
		var html = '<input id="'+textId+'" type="text" style="border:none;" readOnly="readOnly" />'
					+'<input id="'+valueId+'" type="hidden"  name="'+(self.sourceObj.name?self.sourceObj.name:'')+'" />';
		self.options.text = html;

		if(self.options.itemOptions == null){
			self.options.itemOptions = {};
		}
		if(self.options.itemOptions['items'] == null || self.options.itemOptions['items'].length == 0){
			self.options.itemOptions['items'] = items;
		}
		if(self.options.itemOptions['clickFn'] == null){
			self.options.itemOptions['clickFn'] = function(){
				var text = '';
				var val = '';
				self.dropWrapper.getElements('input[type=checkbox][checked]').each(function(temp){
					if(text != '') text += ',';
					text += temp.get('_text');
					if(val != '') val += ',';
					val += temp.value;
				})
				$(textId).value = text;
				$(valueId).value = val;
			};
		}
		self.sourceObj.style.display = 'none';
		self.sourceObj.disabled = true;
		self.controlWrapper = self.appendControl();
		self.dropWrapper = self.appendContainer();

		self.setSize(self.appendItem(self.options.itemOptions));

		self.drop = false;
		self.controlWrapper.addEvent('click', function(e) {
			new Event(e).stopPropagation();// 停止事件传播
			self.toggleDropContainer();
		});
	},
	
	getTextId : function(){
		return 'DropdownChecklist2_text_'+this.sourceObj.id
	},
	
	getValueId : function(){
		return 'DropdownChecklist2_value_'+this.sourceObj.id
	}
});

var DropdownChecklist3 = new Class({
	Extends: DropdownChecklist,
	
	initialize : function(id, options) {
		var self = this;
		if (typeof options == 'object') {
			self.options = $merge(self.options, options);
		}
		
		self.sourceObj = $(id);
		if(self.sourceObj == null) return ;
		
		if(self.sourceObj.options.length > 0){
			self.options.text = $(self.sourceObj.options[self.sourceObj.selectedIndex]).get('text');
		}else{
			self.options.text = '';
		}
		
		var items = [];
		for(var i=0,len=self.sourceObj.options.length;i<len;i++){
			var selectOp = $(self.sourceObj.options[i]);
			items.push({
				'text':selectOp.get('text'),
				'value':selectOp.get('value')
			});
		}

		if(self.options.itemOptions == null){
			self.options.itemOptions = {};
		}
		if(self.options.itemOptions['items'] == null || self.options.itemOptions['items'].length == 0){
			self.options.itemOptions['items'] = items;
		}
		self.sourceObj.style.display = 'none';
		self.sourceObj.disabled = true;
		self.controlWrapper = self.appendControl();
		self.dropWrapper = self.appendContainer();

		self.setSize(self.appendItem(self.options.itemOptions));

		self.drop = false;
		self.controlWrapper.addEvent('click', function(e) {
			new Event(e).stopPropagation();// 停止事件传播
			self.toggleDropContainer();
		});
	},
	
	createItem : function(index, value, text, clickFn, checked, indent){
		var self = this;

		var item = self.createContainterItem();
		if (indent) {
			item.addClass("ui-dropdownchecklist-indent");
		}
		
		var label = new Element('span',{
			'class': 'ui-dropdownchecklist-text',
			'text': text,
			'styles': {
		        'cursor': 'default',
		        'width': '100%'
		    }
		});
		item.grab(label);
		
		item.addEvents( {
			'mouseover' : function() {
				item.addClass('ui-dropdownchecklist-item-hover');
			},
			'mouseout' : function() {
				item.removeClass('ui-dropdownchecklist-item-hover');
			},
			'click' : function(e) {
				self.controlWrapper.getElement('span[_name=textContainer]').set('text',text);
				self.toggleDropContainer();
				self.sourceObj.selectedIndex = index;
				if(self.sourceObj.onchange != null){
					self.sourceObj.onchange();
				}
			}
		});
		
		return item;
	},
	
	getTextId : function(){
		return 'DropdownChecklist2_text_'+this.sourceObj.id
	},
	
	getValueId : function(){
		return 'DropdownChecklist2_value_'+this.sourceObj.id
	}
});