var /*defaultCountryId = selectCountryId = 147573; */
    selectCountryId
	, allCountries = [];
var AUSTRIA_COUNTRY_ID =  147573;//AUSTRIA 
var AUSTRIA_DEFAULT_NIGHTS =  2
	, DEFAULT_NIGHTS = 7;

$(function() {
	loadReferences(loadCountryWithPermit);
	
	$('#cities').change(function() {				
		$('#countries').html(''); 	
		loadCountryWithPermit(
			$(this).val()
			, allCountries
			, $('#countries')
			, loadByCountry
		);
	});
	
	$('#countries').change(function() {
		selectCountryId = eval($(this).val());
		var ids = [];
		$.each(allCountries, function(i, country){
			ids.push(country.countryId);
		});
		
		if ($.inArray(selectCountryId, ids) < 0) {
			selectCountryId = ids[0]; /*defaultCountryId;*/
		} 
		
		setDays(selectCountryId);
		
		loadByCountry(
			selectCountryId
			, eval($('#cities').val())
		);
	});
	
	$('#ts-form-last-tr input:button').click(search);
});

function setDays (selectCountryId) {
	if (selectCountryId == AUSTRIA_COUNTRY_ID) {
        $('#days').val(AUSTRIA_DEFAULT_NIGHTS);	
  } else {
  	$('#days').val(DEFAULT_NIGHTS);	
  }
}

function removeDupes(arr, key) {
    var nonDupes = [];
    $.each(arr, function(i, element) {
    	var isDuplicate = false;
    	$.each(nonDupes, function(j, elm) {
    		if (element[key] == elm[key]) {
    			isDuplicate = true;
    		}
    	});
    	if (!isDuplicate) nonDupes.push(element);
    });
    return nonDupes;
}  

function inCities(cities, id) {
	var result = false; 
	$.each(cities, function(i, city) {
		if (city.cityId == id) {
			result = true;
		}
	});
	return result;
}

function loadReferences(callLoadCountryWithPermit) {
	var url = 'search/references.html';
	$.getJSON(
		url,
		function(data) {
			$.each(data.currencies, function(i, item) {
				$('#currencies').append(
					$('<option>')
						.attr('value', item.currencyId)
						.append(item.code)
				);
			});
			
			allCountries = removeDupes(data.countries, 'countryId');
			selectCountryId = allCountries[0].countryId; 

			callLoadCountryWithPermit(
				DEFAULT_CITY_TO_SEARCH
				, allCountries
				, $('#countries')
				, loadByCountry
			);
			
			var $selectCityId = (inCities(data.cities, DEFAULT_CITY_TO_SEARCH) ? DEFAULT_CITY_TO_SEARCH : 345);
			
			$.each(data.cities, function(i, item) {
				var $optItem = $('<option>').attr('value', item.cityId).append(item.name);
				if (item.cityId == $selectCityId) $optItem.attr('selected', 'selected'); 
				$optItem.appendTo($('#cities'));
			});
			
			$('#dateRange-from').val(TS_DATE_FROM);

		});

}

var loadByCountry = function (currCountry, currCity) {
	$('#tourIds').val('["all"]');
	
	$('#ts-form-last-tr input:button')
	  .removeClass('butt-opacity')
	  .removeAttr('disabled');
}

var loadCountryWithPermit = function (cityId, allResortCountries, container, callLoadByCountry) {	
    // to countries
	$.getJSON(
		"search/permitCountry.html"
		, { depCityId: cityId }
		, function(data) {
			if (data.success) {				
    	        $.each(allResortCountries, function(idx, country) {
    	        	$.each(data.countries, function(i, dataCountryId) {
    	        		if (dataCountryId == country.countryId) {
    	        			var $optItem = $('<option>').attr('value', country.countryId).append(country.name);    	        			
    	        			if (dataCountryId == selectCountryId) $optItem.attr('selected', 'selected'); 
    	        			$optItem.appendTo(container);
    	        		}
    	        	});       				
    	        });
    	        
/*    	    	if ($.inArray(selectCountryId, data.countries) < 0) {
    	    		selectCountryId = defaultCountryId;
    	    	}
*/
    	        setDays(selectCountryId);
    	        
    	        if (callLoadByCountry) callLoadByCountry(selectCountryId, DEFAULT_CITY_TO_SEARCH);
				
			} else {
				alert('Error load permits resort country.');
			} 	
	});
}  

function addDate(fromDate) {
	var temp = new Array();
	temp = fromDate.split(".");
	var toDate = new Date();

	toDate.setFullYear(temp[2]);
	toDate.setMonth(temp[1] - 1);
	toDate.setDate(temp[0]);
	toDate.setDate(toDate.getDate() + 7);

	return toDate.getDate() + "." + (toDate.getMonth() + 1) + "."
			+ toDate.getFullYear();
}

function showError(element, backgroundColor) {
	var bgc = backgroundColor || {backgroundColor:'#fffffe'};
	if (backgroundColor == null) element.css('border-color', '#CD0A0A');
	element.stop().css('background-color', '#cd0a0a').animate(bgc, 1000);
	element.focus();
}

function IsNumeric(input){
    var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    return (RE.test(input));
}

function validateParams() {
	$('#ts-form input:text').css('border-color', '');
	
	var $checkIn = $('#ts-form input[id=dateRange-from]');
	if ($checkIn.val() == '') {
		showError($checkIn);
		return false;
	}
	
	var $priceFrom = $('#priceFrom');	
	if (!IsNumeric($priceFrom.val())) {
		showError($priceFrom);
		return false;
	}  
	
	var $priceFromVal = eval($priceFrom.val());
	if ($priceFromVal < 0) {
		showError($priceFrom);
		return false;		
	}
	
	var $priceTo = $('#priceTo');
	if (!IsNumeric($priceTo.val())) {
		showError($priceTo);
		return false;
	}	
	var $priceToVal = eval($priceTo.val());
	if ($priceToVal < 0 || $priceFromVal > $priceToVal || $priceToVal == 0) {
		showError($priceTo);
		return false;		
	}
	
	return true;
}

var search = function () {
	if (!validateParams()) return false; 
	
	var cityId = $('#cities').val();
	var countryId = $('#countries').val();
	var fromDate = $('#dateRange-from').val();
	var toDate = addDate(fromDate);
	var days = $('#days').val();
	var priceFrom = $('#priceFrom').val();
	var priceTo = $('#priceTo').val();
	var currency = $('#currencies').val();
	var tourIds = $('#tourIds').val();
    var hotelClassId = countryId == AUSTRIA_COUNTRY_ID ? 261942 : 2569;
    var rAndBId = countryId == AUSTRIA_COUNTRY_ID ? 15350 : 2424;
    
	var query = '#result{"locale":"' + TS_LOCALE + '","cityId":'
			+ cityId
			+ ',"countryId":"'
			+ countryId
			+ '","after":"'
			+ fromDate
			+ '","before":"'
			+ toDate
			+ '","nightsMin":'
			+ days
			+ ',"nightsMax":29,"priceMin":'
			+ priceFrom
			+ ',"priceMax":'
			+ priceTo
			+ ',"currency":"'
			+ currency
			+ '","tourId":'
			+ tourIds
			+ ',"hotelClassId":' 
			+ hotelClassId 
			+ ',"hotelClassBetter":true,"rAndBId":' + rAndBId + ',"rAndBBetter":true,"hotelId":[],"hotelInStop":false,"noTicketsTo":false,"noTicketsFrom":false,"tourType":"1","accommodationId":2, "version":2}';

	location.href = "search.html" + query;

}
