/**
 *************************************************************************************
 * [标题：ExmayUI JQuery Combobox 插件]<br>
 *************************************************************************************
 * [描述：ExmayUI JQuery Combobox 插件]<br>
 *************************************************************************************
 * @author Exmay Team / 亿美团队
 *************************************************************************************
 * @version Version 1.0.1 Beta / v1.0.1 测试版
 *************************************************************************************
 */

/*
 * ***********************************************************************************
 * JQuery 插件： [ExmayUI JQuery Combobox 插件]
 * ***********************************************************************************
 * 版权：Copyright © 2012 Exmay Inc. All Rights Reserved. 长沙亿美软件有限公司　版权所有
 * ***********************************************************************************
 * 企业文化：专注　创新　分享　共赢
 * ***********************************************************************************
 * 官方网站：http://www.exmay.com
 * ***********************************************************************************
 * 官方邮箱：service@exmay.com
 * ***********************************************************************************
 */

//
//　[Combobox插件]
//
(function($) {

	// 初始化下拉选框
	function initExmayCombobox(target) {
		var $target = $(target);
		$target.hide();
		var $combobox = $('<span class="exmayui-combobox"></span>').insertAfter(target);
		var $valueField = $('<input type="hidden" class="exmayui-combobox-value" />').appendTo($combobox);
		var $textField = $('<input class="exmayui-combobox-text" />').appendTo($combobox);
		var $arrow = $('<span><span class="exmayui-combobox-arrow"></span></span>').appendTo($combobox);
		var $content = $('<div class="exmayui-combobox-content"></div>').insertAfter($combobox);
		var name = $target.attr("name");
		if (name) {
			$combobox.find("input.exmayui-combobox-value").attr("name", name);
			$target.removeAttr("name").attr("comboboxName", name);
		}
		$content.css( {
			zIndex : 10000
		});
		//		$valueField.attr("name", $target.attr("id"));
		$valueField.attr("name", name);
		// 是否自动补全
		$textField.attr("autocomplete", "off");
		$textField.attr("exmayRequired", $target.attr("validator"));
		return {
			exmayCombobox : $combobox,
			content : $content
		};
	}
	;
	
	// 下拉选框事件绑定
	function bindExmayComboboxEvents(target) {
		var $target = $(target);
		var opts = $target.data("exmayCombobox").options;
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		var $content = $target.data("exmayCombobox").content;
		var $text = $combobox.find(".exmayui-combobox-text");
		var $arrow = $combobox.find(".exmayui-combobox-arrow");
		
		// 取消事件绑定
		$(document).unbind(".exmayCombobox");
		$content.unbind(".exmayCombobox");
		$text.unbind(".exmayCombobox");
		$arrow.unbind(".exmayCombobox");

		// 下拉选框启用
		if (!opts.disabled) {
			
			// 文档对象绑定
			$(document).bind("mousedown.exmayCombobox", function() {
				$(".exmayui-combobox-content").hide();
			});
			
			// 箭头事件绑定
			$arrow.bind("mousedown.exmayCombobox", function() {
				if($content.css("display") == "none") {
					//$text.focus();
					//$(".exmayui-combobox-text").blur();
					//$text.css("background-color","");
					$(".exmayui-combobox-content").hide();
					//$text.css("background-color","");
					//$text.css("color","");
					showComboboxContent(target, "");
				} else {
					//$text.blur();
					//$(".exmayui-combobox-text").blur();
					$text.focus();
					//$text.css("background-color","#316AC5");
					//$text.css("color","#FFFFFF");
					//$text.css("color","#FFFFFF");
					$content.hide();
				}
				return false;
				//$text.trigger("click");
			}).bind("mouseover.exmayCombobox", function() {
				$(this).addClass("exmayui-combobox-arrow-hover");
			}).bind("mouseout.exmayCombobox", function() {
				$(this).removeClass("exmayui-combobox-arrow-hover");
			});

			// 文本框绑定（兼容document mousedown 事件）
			$text.bind("mousedown.exmayCombobox", function() {
				return false;
			});
			
			// 文本框绑定
			$text.bind("focus.exmayCombobox", function() {
				/*if($content.css("display") == "none") {
					showComboboxContent(target, "");
				} else {
					$content.hide();
				}*/
				//$text.css("background-color","#316AC5");
				//$text.css("color","#FFFFFF");
			}).bind("blur.exmayCombobox", function() {
				//$text.css("background-color","");
				//$text.css("color","");
			}).bind("click.exmayCombobox", function() {
//				if($content.css("display") == "none") {
//					$(".exmayui-combobox-content").hide();
//					showComboboxContent(target, "");
//				} else {
//					$content.hide();
//				}
				$arrow.trigger("mousedown");
			}).bind("keydown.exmayCombobox", function(e) { // 键盘事件
				var $selected = $content.find("div.exmayui-combobox-item-selected");
				switch (e.keyCode) {
				case 38: // 向上up 
						var $prevItem = $selected.prev();
						if ($prevItem.length) {
							$selected.removeClass("exmayui-combobox-item-selected");
							$prevItem.addClass("exmayui-combobox-item-selected");
							selectComboboxItem(target, $prevItem.attr("value"));
						}
						break;
					case 40: // 向下down
						var $nextItem = $selected.next();
						if ($nextItem.length) {
							$selected.removeClass("exmayui-combobox-item-selected");
							$nextItem.addClass("exmayui-combobox-item-selected");
							selectComboboxItem(target, $nextItem.attr("value"));
						}
						break;
					case 13: // 回车enter
						selectComboboxItem(target, $selected.attr("value"));
						$content.hide();
						break;
					case 27: // 退出esc
						$content.hide();
						break;
					case 9 : // Tab
						return true;
					default:
						showComboboxContent(target, $(this).val());

					}
					return false;
				});
			// 失去焦点处理
			//            $text.bind("blur.exmayCombobox",function(){
			//            	$(".exmayui-combobox-content").hide();
			//            });

			// 内容绑定
			$content.bind("mousedown.exmayCombobox", function() {
				return false;
			});
			// 兼容滚动事件
			//var $tab = $(target).parents("id=['exmay-tab-panel-0']");
			//var $tab = $("#exmay-tab-panel-0");
			var $tab = $(target).parents("div[id^='exmay-tab-panel']"); 
			$tab.scroll(function(){
				if($content.css("display") == "block") {
					showComboboxContent(target, "");
				}
			});
		}
	}
	;
	
	// 下拉选框事件绑定
	function bindTreeEvents($target) {
		var opts = $target.data("exmayCombobox").options;
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		var $content = $target.data("exmayCombobox").content;
		$content.find(">ul")( {
			onClick : function(data) {
				if (opts.onBeforeSelect.call($target, data) == false) {
					return;
				}
				var $valueField = $combobox.find("input.exmayCombobox-value").val();
				$combobox.find("input.exmayCombobox-value").val(data.id);
				$combobox.find("input.exmayCombobox-text").val(data.text);
				$content.hide();
				// 验证(略)
				opts.onSelect.call($target, data);
				if ($valueField != data.id) {
					// 改变
					//opts.onChange.call($target, data.id, $valueField);
				}
			}
		});
	}
	;

	// 调整下位框大小
	function exmayResizeCombobox(target, data) {
		var $target = $(target);
		var opts = $target.data("exmayCombobox").options;
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		var $content = $target.data("exmayCombobox").content;
		if (data) {
			opts.width = data;
		}
		
		if (isNaN(opts.width)) {
			opts.width = $combobox.find("input.exmayui-combobox-text").outerWidth();
		}
		var arrowWidth = $combobox.find(".exmayui-combobox-arrow").outerWidth();
		var data = opts.width - arrowWidth - ($combobox.outerWidth() - $combobox.width());
		$combobox.find("input.exmayui-combobox-text").width(data);
		if (opts.listWidth) {
			$content.width(opts.listWidth);
		} else {
			$content.width($.boxModel == true ? $combobox.outerWidth() - ($content.outerWidth() - $content.width()) : $combobox.outerWidth());
		}
		if (opts.listHeight) {
			$content.height(opts.listHeight);
		}
		
//		// 兼容父div position=absolute
//		var $parent = $content.parents("div");
//		if($parent !=null && $parent.css("position") == "absolute") {
//			$content.width(120);
//		}
	}
	;

	// 销毁下栏选框
	function destroyCombobox(target) {
		var $target = $(target);
		$target.data("exmayCombobox").content.remove();
		$target.data("exmayCombobox").exmayCombobox.remove();
		$target.remove();
	}
	;

	// 选择下拉选项
	function selectComboboxItem(target, data) {
		var $target = $(target);
		var datas = $target.data("exmayCombobox").data;
		var opts = $target.data("exmayCombobox").options;
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		var $content = $target.data("exmayCombobox").content;
		$content.find("div.exmayui-combobox-item-selected").removeClass("exmayui-combobox-item-selected");
		for ( var i = 0; i < datas.length; i++) {
			var rec = datas[i];
			if (rec[opts.valueField] == data) {
				var comboboxValue = $combobox.find("input.exmayui-combobox-value").val();
				var $text = $combobox.find("input.exmayui-combobox-text");
				$combobox.find("input.exmayui-combobox-value").val(rec[opts.valueField]);
				$text.val(rec[opts.textField]);
				//				if(rec["img"]) {
				//					$text.addClass("exmayui-combobox-icon");
				//					$text.css({backgroundImage: "url(" + rec["img"] + ")"});
				//				} else {
				//					$text.css({backgroundImage: ""});
				//					// 背景图片
				//					if(rec["icon"]) {
				//						$text.addClass("exmayui-combobox-icon");
				//						$text.addClass(rec["icon"]);
				//					} else {
				//						$text.removeClass();
				//						$text.addClass("exmayui-combobox-text");
				//					}
				//				}
				//				var comboboxWidth = $.boxModel == true ? $combobox.outerWidth() - ($content.outerWidth() - $content.width()) : $combobox.outerWidth();
				//				var contentWidth = $content.width();
				//				if(comboboxWidth != contentWidth) {
				//					$text.width($text.width() - (comboboxWidth -contentWidth));
				//				}	
				setComboboxBackGroudImage($target, rec["img"], rec["icon"]);
				$content.find("div.exmayui-combobox-item[value=" + data + "]").addClass("exmayui-combobox-item-selected");
				if (opts.radio == "true") {
					// 单选处理
				}
				opts.onSelect.call(target, rec);
				opts.onChange.call(target, rec);
				if (comboboxValue != data) {
					// 改变
					//opts.onChange.call(target, data, comboboxValue);
				}
				exmayValidateCombobox(target, true);
				return;
			}
		}
	}
	;

	// 设置背景
	function setComboboxBackGroudImage($target, img, icon) {
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		var $content = $target.data("exmayCombobox").content;
		var $text = $combobox.find("input.exmayui-combobox-text");
		if (img) {
			$text.addClass("exmayui-combobox-icon");
			$text.css( {
				backgroundImage : "url(" + img + ")"
			});
		} else {
			$text.css( {
				backgroundImage : ""
			});
			$text.removeClass();
			$text.addClass("exmayui-combobox-text");
			// 背景图片
			if (icon) {
				$text.addClass("exmayui-combobox-icon exmay-ui-png");
				$text.addClass(icon);
			}
		}
		var comboboxWidth = $.boxModel == true ? $combobox.outerWidth() - ($content.outerWidth() - $content.width()) : $combobox.outerWidth();
		var contentWidth = $content.width();
		if (comboboxWidth != contentWidth) {
			$text.width($text.width() - (comboboxWidth - contentWidth));
		}
	}
	;

	// 清除复选框值
	function clearComboboxValue(target) {
		var $target = $(target);
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		$combobox.find("input.exmayui-combobox-value").val("");
		$combobox.find("input.exmayui-combobox-text").val("");
	}
	;
	
	function exmayGetSelected(target) {
		var $target = $(target);
		var opts = $target.data("exmayCombobox").options;
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		if(opts.tree) {
			return $(opts.exmayTree).exmayTree("getSelected");
		}
		return null;
	}

	// 获取已选值
	function getValue(target) {
		var $target = $(target);
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		return $combobox.find("input.exmayui-combobox-value").val();
	}
	;

	// 获取下拉选框选中文本
	function getText(target) {
		var $target = $(target);
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		return $combobox.find("input.exmayui-combobox-text").val();
	}
	;

	// 解析下拉选框选项
	function parserComboboxItem($target) {
		var opts = $target.data("exmayCombobox").options;
		var data = [];
		$('>option', $target).each(function() {
			var $item = {};
			//$item[opts.valueField] = $(this).attr('value') || $(this).html();
			$item[opts.valueField] = $(this).attr('value');
			$item[opts.textField] = $(this).html();
			// 判断默认是否选中
			$item["selected"] = $(this).attr("selected");
			$item["img"] = $(this).attr("img");
			$item["icon"] = $(this).attr("icon");
			$(this).removeAttr("img");
			$(this).removeAttr("icon");
			data.push($item);
		});
		// 删除避免表单提交产生无KEY参数
		$('>option', $target).remove();
		// 如果默认没有选中的项，默认选中第一项
		//data[0]["selected"] = "selected";
		return data;
	}
	;

	// 加载数据 (两种情况，普通下拉选框数据和树形下拉选框数据)
	function loadData(target, data) {
		var $target = $(target);
		var opts = $target.data("exmayCombobox").options;
		$target.data("exmayCombobox").data = data;
		var $content = $target.data("exmayCombobox").content;
		var valueField = null;
		$content.empty();
		for ( var i = 0; i < data.length; i++) {
			var $item = $('<div class="exmayui-combobox-item"></div>').appendTo($content);
			$item.attr("value", data[i][opts.valueField]);
			$item.html(data[i][opts.textField]);
			var $icon = $('<span class="exmayui-combobox-item-icon"></span>');
			$icon.prependTo($item);
			if (data[i]["img"]) {
				$('<img src="' + data[i]["img"] + '" width="16" height="16" />').appendTo($icon);
			} else {
				if (data[i]["icon"]) {
					$icon.addClass(data[i]["icon"]);
				} else {
					$icon.remove();
				}
			}
			if (opts.checkbox) {
				$('<input type="checkbox" name="' + $target.attr("name") + '" class="exmayui-checkbox"></input>').insertAfter($icon);
			} else {
				if (opts.radio) {
					$('<input type="radio" name="' + $target.attr("name") + '" class="exmayui-radio"></input>').insertAfter($icon);
				}
			}
			if (data[i]["selected"]) {
				valueField = data[i];
				if(opts.selectedValue) {
					valueField = opts.selectedValue;
				}
			}
		}
		
		if (valueField) {
			var selected = {"text":opts.selectedText,"value":valueField};
			if(typeof valueField == "string") {
				exmaySetComboboxValue(target, selected);
			} else {
				exmaySetComboboxValue(target, valueField);
			}
		} else {
			exmaySetComboboxValue(target, data[0]);
		}

		opts.onLoadSuccess.call(target, data);
		$(".exmayui-combobox-item", $content).hover(function() {
			$(this).addClass("exmayui-combobox-item-hover");
		}, function() {
			$(this).removeClass("exmayui-combobox-item-hover");
		}).click(function() {
			$content.hide();
			exmaySetComboboxValue(target, {"text":$(this).text(),"value":$(this).attr("value")});
		});
	}
	;

		// 得新加载数据
	    function reloadData(target, url) {
			var $target = $(target);
	        var opts = $target.data("exmayCombobox").options;
	        if (url) {
	            opts.url = url;
	        }
	        if (!opts.url) {
	            return;
	        }

	        $.ajax({
	            url: opts.url,
	            dataType: "json",
	            success: function(data) {
	        		var data = data.items;
	        		data[0]["selected"] == true;
	                loadData(target, data);
	                bindExmayComboboxEvents(target);
	            },
	            error: function() {
	                opts.onLoadError.apply(target, arguments);
	            }
	        });
	    };

	// 显示下拉选框内容
	function showComboboxContent(target, options) {
		var $target = $(target);
		var opts = $.data(target, "exmayCombobox").options;
		options = options || "";
		if(opts.fetchType=="lazy") {
			initTreeFromJSON($target, opts.url);
			opts.fetchType="eager";
		} 
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		var $content = $target.data("exmayCombobox").content;
		var $textFiled = $combobox.find("input.exmayui-combobox-text").val();
		$content.find("div.exmayui-combobox-item-selected").removeClass("exmayui-combobox-item-selected");
		$content.find("div.exmayui-combobox-item").each(function() {
			var $this = $(this);
			if ($this.text().indexOf(options) == 0) {
				$this.show();
				if ($this.text() == $textFiled) {
					$this.addClass("exmayui-combobox-item-selected");
				}
			} else {
				$this.hide();
			}
		});
		if ($content.find("div.exmayui-combobox-item-selected").length == 0) {
			$content.find("div.exmayui-combobox-item:visible:first").addClass("exmayui-combobox-item-selected");
		}
		if ($.fn.exmayWindow) {
			var $top = window.document.body;
			if (self != top) {
				$top = window.top.document.body;
			}
			var $_window = $(".exmayui-window:last", $top);
			if ($_window.html() != null) {
				$.fn.exmayWindow.defaults.zIndex = $_window.css("z-index");
			}
			$content.css("z-index", $.fn.exmayWindow.defaults.zIndex++);
		}

		var top = $combobox.offset().top + $combobox.outerHeight();
		
		// 下边框边界处理
		if (top + $content.outerHeight() > $(window).height() + $(document).scrollTop()) {
			top = $combobox.offset().top - $content.outerHeight();
		}
		if (top < $(document).scrollTop()) {
			top = $combobox.offset().top + $combobox.outerHeight();
		}
//		if (top < $(document).scrollTop()) {
//			top = $combobox.offset().top + $combobox.outerHeight();
//		}
		$content.css( {
			left : $combobox.offset().left,
			top : top
		});

		// 兼容对话框/窗口
		var $window = $content.parents(".exmayui-window");
		if ($content.parents(".exmayui-window").html() != null) {
			$content.css( {
				left : $combobox.offset().left - $window.offset().left,
				top : top - $window.offset().top
			});
		}
		
		// 兼容父div position=absolute
		var $parent = $content.parents("div");
		if($parent !=null && $parent.css("position") == "absolute") {
			$content.css( {
				left : $combobox.offset().left - $parent.offset().left,
				top :  $combobox.offset().top + $combobox.outerHeight() - $parent.offset().top
			});
		}
		
		$content.show();
		opts.onShow.call($content);
	}
	;

	// 验证
	function exmayValidateCombobox(target, data) {
		if ($.fn.validator) {
			var opts = $.data(target, "exmayCombobox").options;
			var $text = $.data(target, "exmayCombobox").exmayCombobox.find("input.exmayui-combobox-text");
			$text.validatebox(opts);
			if (data) {
				$text.validatebox("validate");
				$text.trigger("mouseleave");
			}
		}
	}
	;

	// 是否禁用下拉选框
	function isDisableCombobox(target, isDisable) {
		var $target = $(target);
		var opts = $target.data("exmayCombobox").options;
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		if (isDisable) {
			opts.disabled = true;
			$target.attr("disabled", true);
			$combobox.find(".exmayui-combobox-value").attr("disabled", true);
			$combobox.find(".exmayui-combobox-text").attr("disabled", true);
		} else {
			opts.disabled = false;
			$target.removeAttr("disabled");
			$combobox.find(".exmayui-combobox-value").removeAttr("disabled");
			$combobox.find(".exmayui-combobox-text").removeAttr("disabled");
		}
	}
	;

	// 初始化下拉选项数据
	//    function initDataFromJSON($target, url) {
	//    	var opts = $target.data("exmayCombobox").options;
	//		var $combobox = $target.data("exmayCombobox").exmayCombobox;
	//		var $content = $target.data("exmayCombobox").content;
	//		if (url) {
	//			opts.url = url;
	//		}
	//		$.ajax({
	//			url : opts.url,
	//			dataType : "json",
	//			success:function(data){
	//				loadData($target[0], data.items);
	//				opts.onLoadSuccess.apply(this, arguments);
	//			},
	//			error:function(){
	//				opts.onLoadError.apply(this, arguments);
	//			}
	//		})
	//    };

	// 从后台获取JSON数据初始化树
	function initTreeFromJSON($target, url) {
		var opts = $target.data("exmayCombobox").options;
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		var $content = $target.data("exmayCombobox").content;
		if (url) {
			opts.url = url;
		}
		var $tree = $("<ul></ul>").appendTo($content);
		$tree.exmayTree( {
			url : opts.url,
			checkbox : opts.checkbox,
			radio : opts.radio,
			disabledNode : opts.disabledNode,
			onClick : function(node) {
				var oldValue = $combobox.find("input.exmayui-combobox-value").val();
				$combobox.find("input.exmayui-combobox-value").val(node.id);
				$combobox.find("input.exmayui-combobox-text").val(node.text);
				$content.hide();
				// 设置背景图片
				setComboboxBackGroudImage($target, node.img, node.icon);

				opts.onSelect.call($target, node);

				if (oldValue != node.id) {
					// 改变
					opts.onChange.call($target, node.id, oldValue);
				}
			}
		});
		
		opts.exmayTree = $tree;
		
		//var data = [];
		var item = {};
		if(opts.selectedText == "" && opts.selectedText == "") {
//			item[opts.textField] = data.id;
//			item[opts.valueField] = data.name;
		} else {
			item[opts.textField] = opts.selectedText;
			item[opts.valueField] = opts.selectedValue;
			if(opts.tree) {
				item["icon"] = "icon-system";
			}
		}
		exmaySetComboboxValue($target[0], item);
	};
	
	function initTreeFromHTML($target, tree) {
		var opts = $target.data("exmayCombobox").options;
		var $combobox = $target.data("exmayCombobox").exmayCombobox;
		var $content = $target.data("exmayCombobox").content;
		$(tree).appendTo($content);
		$(tree)( {
			onClick : function(node) {
				var oldValue = $combobox.find("input.exmayui-combobox-value").val();
				$combobox.find("input.exmayui-combobox-value").val(node.id);
				$combobox.find("input.exmayui-combobox-text").val(node.text);
				$content.hide();
				// 设置背景图片
				setComboboxBackGroudImage($target, node.img, node.icon);

				opts.onSelect.call($target, node);

				if (oldValue != node.id) {
					// 改变
					//opts.onChange.call($target, node.id, oldValue);
				}

			}
		});
	}
	;

	// 设值(两种情况，普通下拉框与树形下拉框)
	function exmaySetComboboxValue(target, data) {
		var $target = $(target);
		var cache = $target.data("exmayCombobox");
		var opts = cache.options;
		var $combobox = cache.exmayCombobox;
		var datas = cache.data;
		var comboboxValue = $combobox.find("input.exmayui-combobox-value").val();
		var valueField = null;
		var textField = null;
		var icon = null;
		var img = null;
		
		// 获取初始值
		if (typeof data == "object") {
			valueField = data[opts.valueField];
			textField = data[opts.textField];
			img = data["img"];
			icon = data["icon"];
		} else {
			valueField = data;
			for ( var i = 0; i < datas.length; i++) {
				if (datas[i][opts.valueField] == valueField) {
					textField = datas[i][opts.textField];
					img = datas[i]["img"];
					icon = datas[i]["icon"];
					break;
				}
			}

		}
		
		if (textField == null) {
			if (opts.tree) {
				textField = "";
			} else {
				textField = valueField;
			}
		}

		var $text = $combobox.find("input.exmayui-combobox-text");
		// 给值域设值
		$combobox.find("input.exmayui-combobox-value").val(valueField);
		// 给文本框设值
		$text.val(textField);
		
		// 设置背景图片
		setComboboxBackGroudImage($target, img, icon);
		exmayValidateCombobox(target, true);
		if (comboboxValue != valueField) {
			// 改变
			if(opts.onChange) {
				opts.onChange.call(target, valueField, comboboxValue);
			}
		}
	}
	;
	
	// 设置是否可编辑
	function exmaySetComboboxEditable(target){
		var $target = $(target);
		var cache = $target.data("exmayCombobox");
		var opts = cache.options;
		var $combobox = cache.exmayCombobox;
		$("input.exmayui-combobox-text", $combobox).attr("readonly", !opts.editable);
	}

	// 下拉选框插件定义
	$.fn.exmayCombobox = function(options, data) {

		// 方法调用
		if (typeof options == "string") {
			return $.fn.exmayCombobox.methods[options](this, data);
		}

		options = options || {};

		// 下拉选框主方法
		return this.each(function() {
			var $this = $(this);
			var cache = $this.data("exmayCombobox");
			
			var opts;
			if (cache) {
				opts = $.extend(cache.options, options);
				cache.options = opts;
			} else {
				var $target = initExmayCombobox(this);
				var opts = $.extend( {}, $.fn.exmayCombobox.defaults, $.fn.exmayCombobox.parserOptions(this), options);
				$this.data("exmayCombobox", {
					options : opts,
					exmayCombobox : $target.exmayCombobox,
					content : $target.content
				});
				$this.removeAttr("disabled");
				if (opts.tree) {
					// 树形选框加载数据
					loadData(this, parserComboboxItem($this));
				} else {
					// 普通下拉选框加载数据
					loadData(this, parserComboboxItem($this));
				}
				
				//			if(cache.options.tree == "false") {
				//				if (cache.options.data) {
				//					loadData(this, cache.options.data);
				//				}
				//				reloadData(this);
				//			}
				// 初始化下拉树
				if (opts.tree) {
					if (opts.url) {
						if(opts.fetchType=="eager") {
							initTreeFromJSON($this, opts.url);
						}
						//bindTreeEvents($this);
					} else {
						initTreeFromHTML($this, opts.tree);
					}
				} else {
					//            	if(opts.url) {
					//            		initDataFromJSON($this, opts.url);
					//            	}
				}
			}
			exmaySetComboboxEditable(this);
			isDisableCombobox(this, opts.disabled);
			bindExmayComboboxEvents(this);
			exmayResizeCombobox(this);
//			exmaySetComboboxValue(this, {
//				value : opts.selectedValue,
//				text : opts.selectedText
//			});
			exmayValidateCombobox(this);
		var item = {};
		if(opts.selectedText == "" && opts.selectedText == "") {
//			item[opts.textField] = data.id;
//			item[opts.valueField] = data.name;
		} else {
			item[opts.textField] = opts.selectedText;
			item[opts.valueField] = opts.selectedValue;
			if(opts.tree) {
				item["icon"] = "icon-system";
			}
		}
		exmaySetComboboxValue(this, item);
		});
	};

	//
	// 下拉选框方法
	//
	$.fn.exmayCombobox.methods = {
		destroy : function(target, data) {// 销毁下拉选框
			return this.each(function() {
				destroyCombobox(target);
			});
		},
		resize : function(target, data) { // 调整下拉选框大小
			return this.each(function() {
				exmayResizeCombobox(target, data);
			});
		},
		select : function(target, data) {//选中下拉选框选项
			return $(target).each(function() {
				selectComboboxItem(target, data);
			});
		},
		clear : function(target, data) { // 清除下拉选框选中数据
			return this.each(function() {
				clearComboboxValue(target);
			});
		},
		setValue : function(target, data) { // 设置下拉选框选中值
			return this.each(function() {
				exmaySetComboboxValue(target, data);
			});
		},
		getSelected : function(target, data) {
			return exmayGetSelected(target[0]);
		},
		getValue : function(target, data) { // 获取下拉选框选中值
			return getValue(target[0]);
		},
		getText : function(target, data) { // 获取下拉选框选中文本
			return getText(target[0]);
		},
		loadData : function(target, data) { // 加载数据
			return this.each(function() {
				loadData(target, data);
			});
		},
		reload : function(target, data) { // 重新加载数据
			return target.each(function() {
				reloadData(target, data);
			});
		},
		disable : function(target, data) { // 禁用下拉选框
			return this.each(function() {
				isDisableCombobox(target, true);
				bindExmayComboboxEvents(target);
			});
		},
		enable : function(target, data) { // 启用下拉选框
			return this.each(function() {
				isDisableCombobox(target, false);
				bindExmayComboboxEvents(target);
			});
		}
	};

	// 下拉选框属性
	$.fn.exmayCombobox.parserOptions = function(target) {
		var $target = $(target);
		return {
			width : (parseInt($target.css("width")) || undefined),
			listWidth : $target.attr("listWidth"),
			listHeight : $target.attr("listHeight"),
			valueField : $target.attr("valueField"),
			textField : $target.attr("textField"),
			selectedValue : $target.attr("selectedValue"),
			selectedText : $target.attr("selectedText"),
			editable : ($target.attr("editable") ? $target.attr("editable") == "true" : undefined),
			disabled : ($target.attr("disabled") ? true : undefined),
			tree : ($target.attr("tree") ? ($target.attr("tree") == "true" || $target.attr("tree") == true) : undefined),
			disabledNode : $target.attr("disabledNode"),
			url : $target.attr("url"),
			radio : ($target.attr("radio") ? ($target.attr("radio") == "true" || $target.attr("radio") == true) : undefined),
			checkbox : ($target.attr("checkbox") ? ($target.attr("checkbox") == "true" || $target.attr("checkbox") == true) : undefined),
			required : ($target.attr("exmayRequired") ? ($target.attr("exmayRequired") == "true" || $target.attr("exmayRequired") == true) : undefined),
			missingMessage : ($target.attr("missingMessage") || undefined)
		}
	};

	//
	// 下拉选框属性
	//
	$.fn.exmayCombobox.defaults = {
		tree : false, // 是否是树,
		exmayTree : null,
		disabledNode : "", // 树节点禁用
		width : "auto", // 宽度
		listWidth : null, // 列表宽度
		listHeight : null, // 列表高度
		valueField : "value", // 值
		textField : "text", // 文本
		selectedValue : null, // 默认值
		selectedText : null, // 默认值
		editable : true, // 是否可编辑
		disabled : false, // 是否禁用
		url : null, // URL
		radio : false, // 单选
		checkbox : false, // 复选
		data : null, // 数据
		required : false, // 是否必需
		missingMessage : "不能这空!", // 丢失信息
		fetchType : "lazy", // layz,eager
		onLoadSuccess : function() {
		}, // 加载成功
		onShow : function() {
		}, // 加载失败
		onLoadError : function() {
		}, // 加载失败
		onSelect : function(item) {
		}, // 选择
		onChange : function(item, oldItem) {
		} // 改变
	};

})(jQuery);
//
//　[/Combobox插件]
//

// Bug 

// 输入文字时　框向下，　清空文字时框向上内容向左偏移
// 上下键选择时，value为空时有问题，会将所有为空项选中