var country_copy = country,
	city_copy = city;
		  
$(function(){
		  
	var $country = $('#form_search_country'),
		$city = $('#form_search_city'),
		$button = $('#form_search_button'),
		$region = $('#form_search_region'),
		country_html = $country.html(),
		city_html = $city.html(),
		$star_ratings = $('<div/>').attr('id','EastMedia_star_ratings').hide().appendTo('#EastMedia'),
		$loader = $('<img/>').attr({
				src : '/images/structure/loading.gif',
				alt : 'Loading'
			}).hide().appendTo('#EastMedia_search p'),
		value;

	
	$('.EastMedia_hotel_class').click(function(){
					
		var $this = $(this),
			offset = $this.offset();
					
		if ($star_ratings.is(':empty')) {
			$star_ratings.load('/star_ratings.html',function(){
				$('<a/>').attr({
						href : '#',
						id : 'EastMedia_star_ratings_close'
					}).text('Close').click(function(){
						$star_ratings.fadeOut(250);
					}).appendTo($star_ratings);
				});
		}
		
		$star_ratings.css({
			top : offset.top + $this.height() + 1,
			left : offset.left
		}).fadeIn(250);
											   
		return false;
	});
	
	$('#form_search_region').change(function(){

		

		value = $(this).val();
			
		$country.empty().html(country_html).attr('disabled',true);
		$city.empty().html(city_html).attr('disabled',true);
		$button.attr('disabled',true);
			
		if (!value) {
			return false;
		}
		
		showLoader();

		$.getJSON('/json/countries.php',{region:value},function(data){
			if (data.error) {
				if (data.error === 'empty') {
					$country.empty().append($("<option/>").html('No countries found'));
					hideLoader();
					return;
				}
			}

			var lastValue;

			$.each(data.i,function(i,item){
				$("<option/>").attr("value",item).html(item).appendTo($country);
				lastValue = item;
			});
			$country.attr('disabled',false);

			if (country) {
				$country.val(country).trigger('change');
				country = null;
			} else if (data.i.length === 1) {
				$country.val(lastValue).trigger('change');
			}
			
			hideLoader();
		});

	});

	$country.change(function(){

		value = $(this).val();
			
		$city.empty().html(city_html).attr('disabled',true);
		$button.attr('disabled',true);
			
		if (!value) {
			return false;	
		}
		
		showLoader();

		$.getJSON('/json/citys.php',{country:value},function(data){
			$.each(data.i,function(i,item){
				$("<option/>").attr("value",item).html(item).appendTo($city);
			});
			$city.attr('disabled',false);
			
			if (city) {
				$city.val(city).trigger('change');
				city = null;
			}
			
			hideLoader();
			
		});

	});
	
	$city.change(function(){

		if ($(this).val()) {
			$button.attr('disabled',false);	
		} else {
			$button.attr('disabled',true);	
		}
	});
	
	if ($region.val()) {
		$region.trigger('change');
	}
	
	function showLoader() {
		$loader.fadeIn(250);
	}
	
	function hideLoader() {
		$loader.fadeOut(250);
	}

});
