/*!
 * 通用无限级联动下拉菜单插件
 * 调用方式：$('#area').linkSelect({url: "ajax.js"});
 * JSON数据格式：[{"title": "北京", "value": "beijing"},{"title": "湖南", "value": "hunan"},{"title": "湖北", "value": "hubei"}]
 * www.JSPGen.com
 * @revise 1.0
 */
;(function($){$.extend($.fn,{linkSelect:function(options){var settings={url:"",parameter:"id",title:"title",value:"value",alt:"请选择",separator:",",cssClass:"linkSelect",cssStyle:{"margin-right":"10px"},isFadeIn:true};$.extend(settings,options);return this.each(function(){var $this=$(this);$this.hide();var selectGroupClass="linkSelect"+Math.round(Math.random()*1000000);var items={};var selectName=$this.attr("name");var defaultPath=$this.attr("defaultPath");if(defaultPath==null||defaultPath==""){addSelect($this);}else{var $select=$this;var defaultPathArray=defaultPath.split(settings.separator);for(var i=0;i<defaultPathArray.length;i++){var $nextSelect=addSelect($select,defaultPathArray[i]);if($nextSelect){$select=$nextSelect;}}}
function bindSelect(element){element.bind("change",function(){addSelect(element);$this.attr("value",element.val());});}
function getJson(key){if(typeof(items[key])=="undefined"){var url=settings.url;if(key!="linkSelectRoot"){var parameter=settings.parameter;if(parameter!=null){if(url.indexOf("?")>0){url=url+"&"+parameter+"="+key;}else{url=url+"?"+parameter+"="+key;}}}
$.ajaxSetup({async:false});$.getJSON(url,function(json){items[key]=json;});}
return items[key];}
function fill(element,key,selected){var json=getJson(key);if(!json){return false;}
var length=0;for(j in json){length++;}
if(length==0){return false;}else{element.empty();if(settings.alt!=null){element.append('<option value="">'+settings.alt+'</option>');}
$.each(json,function(id,object){var optionValue="";if(object.value.indexOf(settings.separator)>=0){var optionValueArray=object.value.split(settings.separator);optionValue=optionValueArray[optionValueArray.length-1];}else{optionValue=object.value;}
var option;if(selected&&optionValue==selected){option=$('<option value="'+object.value+'" selected>'+object.title+'</option>');}else{option=$('<option value="'+object.value+'">'+object.title+'</option>');}
element.append(option);});return true;}}
function addSelect(element,selected){var $nextSelect;var isFill;if(element.is("select")){element.nextAll("."+selectGroupClass).remove();if(element.val()==""){return;}
element.after('<select class="'+settings.cssClass+' '+selectGroupClass+'" style="display:none;"></select>');$nextSelect=element.next("."+selectGroupClass);isFill=fill($nextSelect,element.val(),selected);}else{element.after('<select class="'+settings.cssClass+' '+selectGroupClass+'" style="display:none;"></select>');$nextSelect=element.next("."+selectGroupClass);isFill=fill($nextSelect,"linkSelectRoot",selected);}
if(isFill){element.css(settings.cssStyle);if(settings.isFadeIn){$nextSelect.fadeIn();}else{$nextSelect.show();}
bindSelect($nextSelect);return $nextSelect;}else{$nextSelect.remove();}}});}});})(jQuery);