var cleanOption = function(option) {
 var obj = $(option);
 obj.options.length = 0;
}


var addOptions = function(object,objOptions,optSelected) {
 var selectedIndex = false;
 for ( var property in objOptions )
 {
 object.options[object.options.length] = new Option(objOptions[property],property);
 if ( optSelected == property) selectedIndex = object.options.length - 1;
 }

 if ( selectedIndex ) object.options.selectedIndex = selectedIndex;
}

var loadCities = function(location_id) {
   var optRegions = $('region');
   var region_id = optRegions[optRegions.selectedIndex].value;
   cleanOption($('city'));
   loadingCitiesOption($('city'));
   getCities(region_id,location_id);
}

var evalResponse = function(request) {
    try {
        return eval('('+request.responseText+')');
    } catch (e) {}
}

var getCities = function(region_id, city_id) {
   var opt = {
      method: 'get',
	  parameters: 'region_id=' + region_id,
	  onSuccess: function(request) {
         //$('cities').disabled = false;
		 if (request.responseText != "[]"){
			 var json = evalResponse(request);		 
			 if ( json.clone )
			 {
				//$('tr_city').hide();
				//$('location').value = "false";
				$('city').value = -1;
			 }
			 else
			 {
				// if ( !Element.visible('tr_city') ) { $('tr_city').show(); }
				cleanOption($('city'));
				//$('location').value = "true";
			    $('city').options[$('city').options.length] = new Option('- Choose a city -','-1');
				addOptions($('city'),json,city_id);
			 }
		 }
		 else
		 {
			//$('tr_city').hide();	
			//$('location').value = "false";
			$('city').value = -1;
		 }
	  },
	  onLoading: function() {
    	 //cleanOption($('form[location_id]'));
         //$('form[location_id]').disabled = true;
	     //loadingLocationOption($('form[location_id]'));
	  },
	  on404: function(t) {
		 alert('Error 404: location "' + t.statusText + '" was not found.');
	  },
	  onFailure: function(t) {
		 alert('Error ' + t.status + ' -- ' + t.statusText);
	  }
   }
   new Ajax.Request('/ajax_get_cities.php', opt);
}

var loadingCitiesOption = function(object) {
   object.options[object.options.length] = new Option('Loading cities...','');
}

