var id_country = 0;
var page = 1;
var search = '';
//начальный массив стран
var country = {
'51j' : { 'name':'Турция', 'currency':'usd'},	  
'66j' : { 'name':'Греция', 'currency':'eur'},	  
'58j' : { 'name':'Египет', 'currency':'usd'},	  
'83j' : { 'name': 'Тунис', 'currency': 'usd'},	  
'72j' : { 'name':'Испания', 'currency': 'eur'},	  
'67j' : { 'name':'Кипр', 'currency':'eur'},	  
'80j' : { 'name':'Италия', 'currency':'eur'},
'68j' : { 'name':'ОАЭ', 'currency':'usd'},
'81j' : { 'name':'Куба', 'currency':'usd'},
'82j' : { 'name':'Доминикана', 'currency':'usd'},
'84j' : { 'name':'Мальдивы', 'currency':'usd'},
'98j' : { 'name':'Таиланд', 'currency':'usd'},
'93j' : { 'name':'Индия', 'currency':'usd'}
};
	
$(document).ready(function() {
	//прячем
	$('#main_tbl, #adv_tbl, #search_button').hide();
	
	path = new String(window.location.pathname);
	path_pos = path.indexOf('/country/');
	if(path_pos != -1) {
		path_country = path.substr(path_pos + 9, path.length - path_pos - 9);
		$('#form').append('<div id="countryPriceTable"></div>');
		$('#countryPriceTable').load('/ajax/country.php?country='+path_country);
		//ajax/country.php?country=greece
		//console.log(path_country);
	}
	
	$('#tbl_res').html('<img src="/ajax/ajax-loader.gif" alt="" >').load('/ajax/tbl.php');
	//$('table.s_container2, table.s_container4, #adv_tbl').hide(); //скрытие лишнего (потом приписать к этим элементам display:none)
	//формирование селектора стран
	opt = '<option value="0">Выберите страну</option>';
	$.each(country, function(k, v) { 
		opt+='<option value="'+k+'">'+v.name+'</option>';
	});
	$('#country').html(opt);
	
	var hash = window.location.hash.toString();

	if (hash.length > 1) {
		hash = hash.substr(1);
		var tmp = new Array();
		var tmp2 = new Array();
		var param = new Array();

		tmp = hash.split('&');
		for(var i=0; i < tmp.length; i++) {
			tmp2 = tmp[i].split('=');
			param[tmp2[0]] = tmp2[1];
		}
		
		if (param['country'] != null && country[param['country']] != null) {
			$('#country').val(param['country']); country_change();
			if (param['tour'] != null && country[param['country']]['tour'][param['tour']] != null) {
				$('#tour').val(param['tour']); tour_change();
			}
		}
		
		if (param['town_from'] != null) $('#town_from').val(param['town_from']);
		if (param['date1'] != null) $('#date1').val(param['date1']);
		if (param['date2'] != null) $('#date2').val(param['date2']);
		if (param['nights_from'] != null) $('#nights_from').val(param['nights_from']);
		if (param['nights_to'] != null) $('#nights_to').val(param['nights_to']);
		if (param['adult'] != null) $('#adult').val(param['adult']);
		if (param['child'] != null) $('#child').val(param['child']);
		if (param['id_star'] != null) $('#id_star').val(param['id_star']);
		if (param['currency'] != null) $('#currency').val(param['currency']);
		if (param['meal'] != null) $('#meal').val(param['meal']);
		if (param['max_price'] != null) $('#max_price').val(param['max_price']);
		if (param['page'] != null) page = param['page'];
		
		//грузим
		load_data(); 
	}
	else {
		$('#tour').attr('disabled', true);
	}
	
	$('#id_star').data('id_star', '');
		
	$('#country').change(country_change); //смена страны
	$('#tour').change(tour_change); //смена региона
	
	//субмитим форму
	$('#form').submit(function(){
		if (window.location.pathname.indexOf("/search") == -1) {
			location.href = '/search/#'+$(this).serialize();
			return false;
		}
		load_data(); 
		return false;
	});
	
	//смена валюты
	$('#currency').change(function(){
		if (search.length === '') return;
		cb_load(search);
	});	
	
	//смена звезд
	$('#id_star').change(function(){ 
		switch ($(this).val()) {
		case '2' : id_star='2*'; break;
		case '3' : id_star='3*'; break;
		case '4' : id_star='4*'; break;
		case '5' : id_star='5*'; break;
		case '6' : id_star='VILLA'; break;
		default : id_star=''; break;
	}
	
	$(this).data('id_star', id_star);
	if ($('#adv_tbl').css('display') != 'none') load_adv();
	});
	
	//рассширенный поиск
	$('#advs').click(function(){
		$('#adv_tbl').show();
		load_adv();
		return false;
	});
	
	//скрытие рассширенного поиска
	$('#turn').click(function(){
		$('#adv_tbl').hide();
		return false;
	});
	
	//прослушка кликов по чекбоксам для курортов
    $('#towns input').live("click", function() {
		html_hotels = '';
		rel = $('#all_town').data('rel');

		$('#towns input').each(function() {
			if ( $(this).attr('checked') ) {
				html_hotels += hotels(country[id_country]['tour'][rel[$(this).val()]]['towns'][$(this).val()]['hotels'], '');
			}
		});
		
		if (html_hotels != '') {
			$('#hotels').html(html_hotels);
			$('#all_town').attr('checked', false);
		}
		else load_adv();
    });
	
	//прослушка кликов по чекбоксам для отелей
    $('#hotels input').live("click", function() {
		$('#all_hotel').attr('checked', $('#hotels input:checked').length == 0 );
    });
	
	$('#fasthot').keyup(function() {
		html_hotels = '';
		rel = $('#all_town').data('rel');
		filter = $('#fasthot').val();
		is_all_town = $('#all_town').attr('checked');
		
		$('#towns input').each(function() {
			if ( is_all_town || $(this).attr('checked') ) {
				html_hotels += hotels(country[id_country]['tour'][rel[$(this).val()]]['towns'][$(this).val()]['hotels'], filter);
			}	
		});
		
		$('#hotels').html(html_hotels);
	});
	
	$('#all_town').click(function(){$('#towns input').attr('checked', false); $(this).attr('checked', true); towns();});
	$('#all_hotel').click(function(){$('#hotels input').attr('checked', false); $(this).attr('checked', true);});
	
	//календарь
	$.datepicker.setDefaults($.datepicker.regional['ru']);
	var dates = $('#date1, #date2').datepicker({
	defaultDate: "+1d",
	minDate: "+1d",
	numberOfMonths: 2,
	onSelect: function(selectedDate) {
		var option = this.id == "date1" ? "minDate" : "maxDate";
		var instance = $(this).data("datepicker");
		var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
		dates.not(this).datepicker("option", option, date);
				
		if (this.id == 'date1') change_date(selectedDate, 60*60*24*7*1000);
		}
	});
});


//инициализация рассширенного поиска
function load_adv() { 
	$('#towns').html('').data('c', 0);
	$('#all_town').attr('checked', true).data('rel', new Array());
	$('#all_hotel').attr('checked', true).data('rel', new Array());
	$('#hotels').html('').data('c', 0);
	
	if (country[id_country]['adv'] == null) {
		//$.getJSON("http://po-exali.ru/ajax/jsonp_adv.php?callback=?", 'id_country='+id_country, cb_adv);
		$.ajax({
			url: "/ajax/jsonp_adv.php?callback=?",
			dataType : "jsonp",
			async:false,
			data: 'id_country='+id_country,
			success: cb_adv
		});
	}
	
	towns();
}

//обратная функция инициализации рассширенного поиска, загон в кэш
function cb_adv(data) {
	country[id_country]['adv'] = 1;
	$.each(data, function(k, v) {
		if (country[id_country]['tour'][k] != null) country[id_country]['tour'][k]['towns'] = v;
	});
	//towns();
}

//прорисовка отелей с учетом фильтра
function hotels(data, filter) {
	id_star = $('#id_star').data('id_star');
	
	if (data == null) return '';
	html_hotels = '';
	filter = filter.toUpperCase();
	$.each(data, function(k, v) {  
		if (id_star != '' && id_star != v.star) return true;
		if (filter == '' || v.name.toUpperCase().indexOf(filter) != -1)
		html_hotels+= '<label><input name="hotel[]" type="checkbox" value="'+k+'"/>'+v.name+'</label><br/>';
	});
	return html_hotels;
}

//прорисовка курортов
function towns() {
	id_tour = $('#tour').val();
	html_towns = '';
	html_hotels = '';
	//rel = $('#all_hotel').data('rel');
	rel = $('#all_town').data('rel');
	
	$.each(country[id_country]['tour'], function(k, v) {

	if (id_tour != '0j' && id_tour != k) return true; 
		if (k != '0j' && v.towns != null) {  
			$.each(v.towns, function(kk, vv) {
				html_towns+='<label><input name="town[]" type="checkbox" value="'+kk+'"/>'+vv.town+'</label><br/>';
				rel[kk] = k;
				
				if (vv.hotels != null) {
					html_hotels+= hotels(vv.hotels, '');
				}
			});
		}
		//$('#all_hotel').data('rel', rel);
		$('#all_town').data('rel', rel);
	});
	$('#towns').html(html_towns);
	$('#hotels').html(html_hotels);
}

//смена страны
function country_change() { 
	$('#tour').attr('disabled', false);
	$('#main_tbl, #search_button').show();
	
	if (id_country == 0) {
		$('#country option:eq(0)').remove();
		$('#search_button').show();				
	}
	
	id_country = $('#country').val();
			
	$('#reg').html('<img src="/ajax/17-0.gif" alt="" />');
	$('#currency option:eq(1)').val(((country[id_country]['currency'] == 'usd') ? 2 : 3)).html(country[id_country]['currency']);
			
	if (country[id_country]['tour'] == null) {
		//$.getJSON("http://po-exali.ru/ajax/jsonp_country.php?callback=?", 'id_country='+id_country, cb_country);
		$.ajax({
	        url: "/ajax/jsonp_country.php?callback=?",
	        dataType : "jsonp",
			async:false,
			data: 'id_country='+id_country,
	        success: cb_country
		});
	}
	else cb_country(country[id_country]['tour']);
			
	$('#res').html('');
}
		
function cb_country(data) {
	opt = '<option value="0j">Все</option>';
	min_date = ''; min_date_index = '';

	$.each(data, function(k, v) {
		if (k == 0) return true;
		date = v.date.split('.');
		date = date[2] + '-' + date[1] + '-' + date[0];
		
		if (!min_date || min_date > date) {
			min_date = date;
			min_date_index = k;
		}

		opt+='<option value="'+k+'">'+v.tour+'</option>';
	});
				
	if (country[id_country]['tour'] == null) {
		data['0j'] = {'tour' : 'Все', 'date': ( (data[min_date_index] != null) ? data[min_date_index]['date'] : $('#date1').val() )};
		country[id_country]['tour'] = data;
	}
				
	$('#tour').html(opt).val(0);
	$('#reg').html('');
				
	change_date(data[$('#tour').val()]['date'], 60*60*24*7*1000);
}

//смена даты		
function change_date(date1, add) {
	d2 = new Date();
	ar = date1.split('.');
	d2.setTime(Date.parse(ar[1] + '/' + ar[0] + '/' + ar[2]));
	d2 = new Date(d2.getTime() + add);
	y = d2.getFullYear().toString();
	m = d2.getMonth() + 1; 
	if (m < 10) m = '0' + m.toString();
	else m = m.toString();
	d = d2.getDate();
	if (d < 10) d = '0' + d.toString();
	else d = d.toString();
				
	$('#date1').val(date1);
	$('#date2').val(d+'.'+m+'.'+y);	

	if ($('#adv_tbl').css('display') != 'none') load_adv();
}

function tour_change() {  
	id_tour = $('#tour').val();
	change_date(country[id_country]['tour'][id_tour]['date'], 60*60*24*7*1000);
}
	
function load_data() {
	get = $('#form').serialize() + '&page='+page;
	$('#res').html('<img src="/ajax/ajax-loader.gif" alt="" >');
	//$.getJSON("http://po-exali.ru/ajax/jsonp_res.php?callback=?", get, cb_load);
		$.ajax({
	        url: "/ajax/jsonp_res.php?callback=?",
	        dataType : "jsonp",
			async:false,
			data: get,
	        success: cb_load
		});
	location.href = '#' + get;
	page = 1;
}
	
function cb_load(data) {
	html = '<table class="tsys_res" cellspacing="0" cellpadding="6"> \
                <tr class="header"> \
                  <td><br> \
			Авиа</td> \
                   <td><br>  \
                    Заезд</td> \
                  <td><br> \
                    Регион</td> \
                  <td><br> \
                    Ночи</td> \
                  <td><br> \
                    Отель</td> \
                  <td align="center">Тип номера<br> \
                    Размещение</td> \
                  <td align="center"><br> \
                    Питание</td> \
                  <td><br>Цена</td> \
                  <td><br> \
                    Заказ</td> \
                </tr>';
	
		currency = $('#currency').val();
		c = 0;
	$.each(data.data, function(k, v) { c++;
		 switch (currency) {
			case '2': val = v.price + ' $'; break;
			case '3': val = v.price + ' &euro;'; break;
			default: val = v.rur + ' р.'; break;
		 }
		 
		 if (v.hotel == null) return true;
		 expr = new RegExp('^(.+)\\s\\d\\*');
		 tophotel = v.hotel.match(expr); 
		 tophotel = (tophotel != null) ? tophotel[1] : v.hotel;

		 html+= '<tr '+((c%2 == 0) ? ' class="dark"' : '')+'> \
                  <td'+((v.system == ' ') ? ' class="yes"' : '')+'>'+v.system+'</td> \
                  <td>'+v.date+'<br> \
                    '+v.w+'</td> \
                  <td>'+v.tour+'</td> \
                  <td align="center">'+v.nights+'</td> \
                  <td><a class="hot" target="_blank" href="http://www.tophotels.ru/main/hotels/?srch=1&amp;CO=0&amp;name='+encodeURIComponent(tophotel)+'&amp;CO=0">'+v.hotel+'</a></td> \
                  <td align="center">'+v.room+'<br> \
                    '+v.location+'</td> \
                  <td align="center">'+v.meal+'</td> \
                  <td nowrap="nowrap"><a class="oprice" target="_blank" href="/search_order/?id_travel='+v.id_travel+'">'+val+'</a></td> \
                  <td align="center"><a target="_blank" href="/search_order/?id_travel='+v.id_travel+'"><img src="/images/order.gif" border="0"></a></td> \
                </tr>';
	});
	html+= '</table>';
	html+= data.navi;
	
	if (!data.all) html = 'ничего не найдено';
	$('#res').html(html);
	search = data;
	
	$('#navi a').click(function(){
		page = $(this).html();
		load_data();
	return false;
	});
}
