/*

$('#select').fit_select({
	url     : 'home/get_select',    //数据
	multi   : true ,                //是否允许多选
	onclick : function( id , selected ) {  //点击后的事件
		//id       : 选中或者取消 值
		//selected : true : 选中 false 取消
		alert(id , selected);
	}
});

$('#tt').click(function(){
	console.log( $('#select').fit_select_value() );  //取单选值
	console.log( $('#select').fit_select_values() ); //取多选值
});

<div id="select" class="fit-select" ></div>
*/


;(function($) {
	// 插件的定义
	$.fn.fit_select = function(options) { 
		//debug(this);
		
		if (!$(this).length) {
			return this;
		}
		
		// 插件的defaults
		var defaults = {
			url       : false,
			multi     : false,
			onclick   : false
		};

		//合并设置  
		var ops = fixOps( this , defaults , options);
		
		return this.each(function() {
			$this = $(this);
			
			if ( ops.url ) {
				$.post( ops.url , null , function(ret){
					ret = $.parseJSON(ret);
					var html = '<ul>';
					for ( var i = 0 ; i < ret.length ; i++ ) {
						html += '<li><a href="#" value="'+ ret[i]['id'] +'"><span>'+ret[i]['text']+'</span></a></li>';
					}
					html += '</ul>';
					$this.html(html);
					init_select( $this , ops );
				});
			} else {
				init_select( $this , ops );	
			}
			
		});
		

	};
	
	function init_select( $this , ops ) {
		$this.find('a').click(function(event){
			event.preventDefault(event);
			var selected = false ;
			if ( $(this).attr('class') == 'selected' ) {
				$(this).removeClass('selected');
			} else {
				if ( !ops.multi ) {
					
					$(this).parents('ul').find('a').removeClass('selected');
					$(this).addClass('selected');
					
				} else {
					$(this).addClass('selected');
				}
				selected = true ;
			}
			
			if ( ops.onclick ) {
				ops.onclick($(this).attr('value') , selected );
			}
		});
	}

	
	function fixOps( $obj , defaults , options) {
		options = $.extend( defaults , options);

		for( var key in defaults ) {

			if ( typeof( $obj.attr(key) != 'undefined' ) && !options[key] ){
				options[key] = $obj.attr(key) ;
			}
		}
		
		return options ;
	}
	
	// 定义暴露format函数	
	/*
	// 私有函数：debugging
	function debug($obj) {
		if (window.console && window.console.log)
			window.console.log('fit_select selection count: ' + $obj.size());
	};
	*/
	
	// 闭包结束
})(jQuery);

;(function($) {
	// 插件的定义
	$.fn.fit_select_value = function(options) { 
		var val = '' ;
		$(this).find('a').each(function(){
			if ( $(this).attr('class') == 'selected' ) {
				val = $(this).attr('value') ;
			}
		});

		return val;
		
	};
	// 闭包结束
})(jQuery);

;(function($) {
	// 插件的定义
	$.fn.fit_select_values = function(options) { 
		var val = [] ;
		$(this).find('a').each(function(){
			if ( $(this).attr('class') == 'selected' ) {
				val.push( $(this).attr('value') );
			}
		});

		return val ;
		
	};
	// 闭包结束
})(jQuery);
