/*
 * jxselect 1.0
 * Copyright (c) 2013 Dacheng  http://www.jxcms.com/
 * Date: 2013-02-28
 */
 (function($){
    $.fn.jxselect = function(pid, action){
        var self = this, className = 'jxselect_' + $(this).attr('id');
		this.getSelect = function(obj, pid, sid){
			if(typeof(sid) == "undefined") sid = 0;
			if(typeof(action) == "undefined") action = 'api/area.php';
			$.post(action, 'pid='+pid+'&sid='+sid, function(data){
				if(data){
					var html = '';
					for(var i in data){
						html += self.toSelect(data[i]);
					}
					$(obj).after(html);
					self.bindChange();
					if(!sid) $(self).val('');
				} else $(self).val(pid);
			}, 'json');
		}
		this.toSelect = function(data){
			var html = '';
			if(data){
				var sel = '';
				html += '<select class="' + className + '"><option></option>';
				for(var i in data){
					sel = data[i]['sel'] ? ' selected="selected"' : '';
					html += '<option value="' + data[i]['areaid'] + '"' + sel + '>' + data[i]['name'] + '</option>';
				}
				html += '</select>';
			}
			return html;
		}
		this.bindChange = function(){
			$("." + className).unbind("change").change(function(){
				$(this).nextAll("." + className).remove();
				var pid = $(this).val();
				if (pid) self.getSelect(this, pid);
			});
		}
		if(typeof(pid) == "undefined") pid = 0;
		else pid = parseInt(pid);
		this.getSelect(this, pid, $(this).val());
	}
})(jQuery);