// JavaScript Document
City = function(id) {
	this.element = $('#' + id);
	
	this.init = function() {
		var obj = this;
		this.element.find('h2 a').click(
			function() {
				obj.element.find('.h-citypopup-wrap').toggle();
				return false;
			}
		);
		this.load();
	}
	
	this.load = function() {
		var obj = this;
		
		$.ajax({
		   type: "POST",
		   url: '/ajax/default_city/',     // this is the path from above
		   success: function(s) {
				if($(s).find('success item').length) {
					var perCol = Math.ceil($(s).find('success item').length / 3);
					var html = '';
					
					for(var i = 0; i < $(s).find('success item').length; i++) {
						if(i == 0) {
							html += '<td><ul>';
						} else if(i == perCol || i == perCol * 2) {
							html += '</ul></td><td><ul>';
						}
						
						selected = $(s).find('success item:eq(' + i + ')').attr('selected') ? true : false;
						if(selected) {
							obj.element.find('h2 a').text($(s).find('success item:eq(' + i + ')').text());
						}
						html += '<li' + (selected ? ' class="active"' : '') + '><a href="" rel="' + $(s).find('success item:eq(' + i + ')').attr('id') + '">';
						html += $(s).find('success item:eq(' + i + ')').text();
						html += '</a></li>';
						
						if(i == ($(s).find('success item').length - 1)) {
							html += '</ul></td>';
						}
					}
					
					obj.element.find('table.city-list tr').empty();
					obj.element.find('table.city-list tr').html(html);
					
					obj.element.find('table.city-list tr td a').click(
						function() {
							obj.switchCity(this);
							return false;
						}
					);
					
					obj.element.show();
				}
		   }
		});
	}
	
	this.switchCity = function(ele) {
		var id = $(ele).attr('rel');
		var obj = this;
		$.ajax({
		   type: "POST",
		   url: '/ajax/default_city/set.php', 
		   data: 'id=' + id,
		   success: function(s) {
			   obj.load();
			   obj.element.find('.h-citypopup-wrap').toggle();
		   }
		});
	}
}
