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

		for(ix=0; ix<doms.length; ix++) {
			var dom = $(doms[ix]);
			var id = dom.attr('id');
			var name = dom.attr('name');
			var maps = dom.attr('maps');
			var cls = dom.attr('class');
			curs[ix] = dom.val();
			var html = '<select id="'+id+'" name="'+name+'" class="'+cls+'" maps="'+maps+'"'+(doms[ix+1] ? 'onchange="$.fn.changeNote('+ix+', \''+maps+'\', this.value)"' : '')+'>';
			html+= '<option value="">'+(texts[ix] ? texts[ix] : '&#491;&#1121;&#1329;')+'</option>';
			if (ix == 0) {
				html+= $.fn.loadNote(doms[ix]);
			}
			html+= '</select>';
			dom.replaceWith(html);
		}
		for(ix=0; ix<doms.length; ix++) {
			if (curs[ix]) {
				var dom = $(doms[ix]);
				var maps = dom.attr('maps');
				if (doms[ix+1]) {
					$.fn.changeNote(ix, 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(ix, maps, val) { 
		var opts = $.fn.dmenu.defaults;
		var doms = opts.domList.split('>');
		var names = opts.textList.split('>');
		var html = '';
		$.ajax({
			url:opts.dataScript,
			dataType:"xml",
			async:false,
			success:function(xml){
				html+= '<option value="">'+(names[ix+1] ? names[ix+1] : '&#491;&#1121;&#1329;')+'</option>';
				if (val) {
					$(xml).find(maps+'[name="'+val+'"]').children().each(function(i){
						html+= '<option value="'+$(this).attr("name")+'">'+$(this).attr("name")+'</option>';
					});
				}
				var i = 0; while (true) { i++;
					if (!doms[ix+i]) {
						break;
					}
					$(doms[ix+i]).empty().append('<option value="">'+(names[ix+i] ? names[ix+i] : '&#491;&#1121;&#1329;')+'</option>');
				}
				$(doms[ix+1]).empty().append(html);
			}
		});
	}

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

	$.fn.dmenu.defaults = {
		defaultOption: '<option value="">&#491;&#1121;&#1329;</option>',
		dataScript: '/appdata/area.xml',
		domList: 'province>city',
		textList: '&#673;>&#656;'
	};
})(jQuery);
