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

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

(function($) {
	
	function initExmaySelector(target){
		var $target = $(target);
		var cache = $target.data("exmaySelector");
		var opts = cache.options;

		var selects = exmayParserNameValues(target);

		cache.options = $.extend(opts, {"selects" : selects});
		// AJAX加载JSON数据
		exmayLoadData(target);
	};
	
	function exmayParserNameValues(target) {
		var $target = $(target);
		var cache = $target.data("exmaySelector");
		var opts = cache.options;	
		var name = $target.attr("name");
		var inames = (name + "," + opts.names).split(",");
		var values = opts.values;
		var ivalues = [];
		var selects = [];
		if(values != undefined && values != null) {
			ivalues = values.split(",");
		}
		for(var i=0; i <inames.length; i++) {
			var sname = inames[i];
			var svalue = null;
			if(ivalues != null) {
				svalue = ivalues[i];
			}
			var iselects = {index : i ,"name" : sname , "value" : svalue};
			selects.push(iselects);
		}
		return selects;
	};	
	
	function exmayLoadData(target, current, data) {
		var $target = $(target);
		var opts = $target.data("exmaySelector").options;
		var param = {};		
		if(data) {
			param = data;
		}
		if(current) {
			$target = $(current);
		}
		$.ajax( {
			type : 'post',
			url : opts.url,
			data : param,
			dataType : 'json',
			beforeSend : function(data) {
		
			},
			success : function(data) {
				var items = data.items;
				$target.empty();
				if(items.length == 0) {
					$target.hide();
					return;
				} else {
					$target.show();
				}
				var $current = null;
				if(current == null) {
					$current = $target;
				} else {
					$current = $(current);
				}
				var select = exmayGetSelect(opts.selects, $current.attr("name"));
				var value = select.value;
				var index = select.index;
				for(var i = 0; i < items.length; i ++) {
					var item = items[i];
					var $option = $('<option></option>');
					$option.attr("value", item.id);
					$option.text(item.name);
					$option.appendTo($target);
					if (value == item.id) {
						$option.attr("selected", true);
					}
				}
				$target.hide().show();
				if(index+1 < opts.selects.length) {
					var nselect = opts.selects[index + 1];
					var nvalue = nselect.value;
					if(nvalue != undefined && nvalue != null) {
						var $select = exmayInitSelect($current, nselect.name);
						exmaySelectChange($target[0], $select[0], opts.selects[index].value);
					}
					exmayOptionBingEvents($current, nselect);
				}
			},
			error : function() {
	
			}
		});
	};
	
	function exmayOptionBingEvents($current, nselect) {
		$current.change(function(){
			var parentId = $(this).val();
			var $select = $("select[name='" + nselect.name + "']");
			if($select == undefined || $select == null || $select.attr("name") == undefined) {
				$select = exmayInitSelect($current, nselect.name);
			}
			exmaySelectChange($current[0], $select[0], parentId);
		});
	};
	
	function exmayGetSelect(selects, name) {
		for(key in selects) {
			if(selects[key].name == name) {
				select = selects[key];
				break;
			}
		}
		return select;
	}
	
	function exmaySelectChange(target, current, parentId) {
		var $target = $(target);
//		var cache = $target.data("exmaySelector");
//		var opts = cache.options;

		/*if($this == undefined || $this == null) {
			$this = exmayInitSelect(target);
			selects.push({"name": name, "target" : $this});
			cache.options = $.extend(opts, {"selects" : selects});
		}*/
		exmayLoadData($target, current, {"parentId" : parentId});
	}
	
	function exmayInitSelect(target, name) {
		var $target = $(target);
		var opts = $target.data("exmaySelector").options;
		//var $select = $(' <select class="exmayui-selector"></select>');
		var $select = $target.clone();
		$select.attr("name", name);
		$select.insertAfter($target);
		return $select;
	}
	
	function bindExmaySelectorEvents($target) {
		
	};
	
	// 定义插件
	$.fn.exmaySelector = function(options, data) {
        if (typeof options == "string") {
            return $.fn.exmaySelector.methods[options](this, data);
        }
		this.each(function(){
			var $this = $(this);
			var opts = null;
			var cache = $this.data("exmaySelector");
			if(cache) {
				opts = $.extend(cache.options, options || {});
				cache.options = opts;
				//unbindEvents($this);
				//unbindItemEvents($this);
			} else {
				opts = $.extend( {}, $.fn.exmaySelector.defaults, $.fn.exmaySelector.parseOptions(this), options || {});
				$this.data("exmaySelector", {
					options : opts
				});
				initExmaySelector(this);
			};
			bindExmaySelectorEvents($this);
		});
	};
	
	$.fn.exmaySelector.methods = {
		setSelected : function(target, data) {
			return exmaySelected(target, data); // 选中
		}
	};
	
    $.fn.exmaySelector.parseOptions = function(target) {
        var $target = $(target);
        return {
        	url : $target.attr("url"),
        	names : $target.attr("names"),
        	values : $target.attr("values")
        };
	};
	
	$.fn.exmaySelector.defaults = {
		
	};
	
})(jQuery);