// JavaScript Document
(function($) {
	$.fn.dmenu = function(options) {
		$.fn.dmenu.setting(options, $(this));
		var opts = $.fn.dmenu.defaults;
		var objs = opts.objList.split('>');
		var curs = new Array();

		for(ix=0; ix<objs.length; ix++) {
			var dom = $(objs[ix]);
			var id = dom.attr('id');
			var name = dom.attr('name');
			var cls =dom.attr('class');
			var maps = dom.attr('maps');
			curs[ix] = dom.val();
			var html = '<select id="'+id+'" name="'+name+'" class="'+cls+'" maps="'+maps+'"'+(objs[ix+1] ? 'onchange="$.fn.changeNote(\''+objs[ix]+'\', \''+objs[ix+1]+'\', \''+maps+'\', this.value)"' : '')+'>';
			html+= '<option value="">ÇëÑ¡Ôñ</option>';
			if (ix == 0) {
				html+= $.fn.loadNote(objs[ix]);
			}
			html+= '</select>';
			dom.replaceWith(html);
		}
		for(ix=0; ix<objs.length; ix++) {
			if (curs[ix]) {
				var dom = $(objs[ix]);
				var maps = dom.attr('maps');
				if (objs[ix+1]) {
					$.fn.changeNote(objs[ix], objs[ix+1], maps, curs[ix]);
				}
				$(dom).selected(curs[ix]);
			}
		}
		
	};
	
	$.fn.loadNote = function(dom, val) {
		var opts = $.fn.dmenu.defaults;
		var maps = $(dom).attr('maps');
		var html = '';
		$.ajax({
			url:opts.dataScript,
			dataType:"xml",
			async:false,
			success:function(xml){
				if (val) {
					$(xml).find(maps+'[name='+val+']').children().each(function(i){
						html+= '<option value="'+$(this).attr("name")+'">'+$(this).attr("name")+'</option>';
					});
				} else {
					$(xml).find(maps).each(function(i){
						html+= '<option value="'+$(this).attr("name")+'">'+$(this).attr("name")+'</option>';
					});
				}
			}
		});
		return html
	};
	
	$.fn.changeNote = function(dom, tpos, maps, val) {
		var opts = $.fn.dmenu.defaults;
		var html = '';
		$.ajax({
			url:opts.dataScript,
			dataType:"xml",
			async:false,
			success:function(xml){
				if (val) {
					html+= '<option value="">ÇëÑ¡Ôñ</option>';
					$(xml).find(maps+'[name='+val+']').children().each(function(i){
						html+= '<option value="'+$(this).attr("name")+'">'+$(this).attr("name")+'</option>';
					});
				}
				$(tpos).empty().append(html);
			}
		});
	}

	$.fn.dmenu.setting = function(options, form) {
		$.fn.dmenu.defaults = $.extend($.fn.dmenu.defaults, options);
	};

	$.fn.dmenu.defaults = {
		dataScript: '/appdata/district.xml',
		objList: 'province>city'
	};
})(jQuery);
