services	= new Array();
prices		= new Array();
pre_prices	= new Array();

$(function(){
	if($('#payform').size()) {
		setUpCalendar();
		changeAirport();
	}
})

function changeAirport()
{
	updateServices();
}

function changeService()
{
	updateTariffs();
	if(1 == services[$('#payform select[name=service]').val()]) {
		$('#seats_loading').show();
		$('#trainSeats').show();
		$('#tripTime').show();
		
		requestTime();
		
	} else {
		$('#trainSeats').fadeOut();
		$('#tripTime').fadeOut();
	}
}

function chaneTariff()
{
	/*
	$('#tdesc > div').hide();
	
	selected_service = $('#payform select[name=service]').val();
	selected_tariff = $('#payform select[name=tariff]').val();
	
	$('#tdesc_' + selected_service + '_' + selected_tariff).show();
	*/
	calculateSum();
}

function updateServices()
{
	airport	= $('#payform select[name=airport]').val();
	url		= '/services/' + airport;
	
	stupidIE = new Date();

	$.ajax({
		url: '/newpayform/ajax.php?url=' + url + '/' + stupidIE.getTime(),
		dataType: 'xml',
		beforeSend: function(){
			/*
			$('#payform select[name=service]').html('<option value="1">Обычный</option>');
			$('#payform select[name=tariff]').html('<option value="1">Полный</option>');
			*/
		},
		success: function(xml){
			if($(xml).find('services > service').size())
				$('#payform select[name=service]').html('');

			i = 0;
			$(xml).find('services > service').each(function(){
				$('#payform select[name=service]').append('<option value="' + $(this).attr('id') + '" ' + (i++ ? '' : 'selected="true"') + ' >' + $(this).attr('title') + '</option>');
				services[$(this).attr('id')] = $(this).attr('seats');
			});
			
			changeService();
		}
	});
}

function updateTariffs()
{
	service	= $('#payform select[name=service]').val();
	url		= '/tariffs/' + service;
	
	stupidIE = new Date();
	
	$.ajax({
		url: '/newpayform/ajax.php?url=' + url + '/' + stupidIE.getTime(),
		dataType: 'xml',
		beforeSend: function(){
			/*
			$('#payform select[name=tariff]').html('<option value="1">Полный</option>');
			*/
		},
		success: function(xml){
			if($(xml).find('tariffs > tariff').size())
				$('#payform select[name=tariff]').html('');
			
			i = 0;
			$(xml).find('tariffs > tariff').each(function(){
				$('#payform select[name=tariff]').append('<option value="' + $(this).attr('id') + '" ' + (i++ ? '' : 'selected="true"') + ' >' + $(this).attr('title') + '</option>');
				prices[$(this).attr('id')] = $(this).attr('value');
				pre_prices[$(this).attr('id')] = $(this).attr('pre_value');
			});
			
			chaneTariff();
		}
	});
}

function setUpSeats()
{
	$('#seats_loading').fadeOut();
	
	$('#seats > div.free')
		.click(function(){
			$('#seat_selected').html(this.innerHTML);
			$('#payform input[name="place"]').val(this.innerHTML);
							
			if($('#seats > div.selected').get() != '')
				$('#seats > div.selected').get(0).className = 'free';
							
			this.className = 'selected';
			
		});
		
	if($('#seats > div.free').size()) {
		seat = $('#seats > div.free').get(0).innerHTML
		$('#seats > div.free').get(0).className = 'selected';
		$('#seat_selected').html(seat);
		$('#payform input[name="place"]').val(seat);
	}
	
	$('#seats > div').fadeIn();
	
	$('#countFree').html('(' + $('#seats > div.free').size() + ')');
}
			
function requestSeats()
{	
	if($('#classSelect').val() == 1)
		return;
		
	d = $('#payform input[name=day]').val();
	m = $('#payform input[name=month]').val();
	y = $('#payform input[name=year]').val();
	
	time = $('#tripTimeSelect').val();
	
	airport = $('#payform select[name="airport"]').val();
	direction = $('#payform input[name="direction"]:checked').val();
	url = '/seats/' + airport + '/' + direction + '/' + y + '-' + m + '-' + d + '/' + time + '/';
	
	stupidIE = new Date();
	
	$.ajax({
		url: '/newpayform/ajax.php?url=' + url + stupidIE.getTime(),
		dataType: 'xml',
		beforeSend: function(){			
			$('#seats').html('');
			$('#seats_loading').fadeIn();
			$('#seat_selected').html('тамбур');
			$('#countFree').html('');
			
			$('#payform input[name="place"]').val('');
		},
		success: function(xml){
			$(xml).find('train > seat').each(function(){
				$('#seats').append('<div id="seat_' + $(this).attr('id') + '" class="' + $(this).attr('type') + '">' + $(this).attr('id') + '</div>');
			});
			
			setUpSeats();
		}
	});
	
	return false;
}

function requestTime()
{
	if(1 != services[$('#payform select[name=service]').val()])
		return;
		
	if($('#classSelect').val() == 0)
		return;
		
	$('#tripTimeSelect').html('<option>загрузка</optin>');
	
	d = $('#payform input[name=day]').val();
	m = $('#payform input[name=month]').val();
	y = $('#payform input[name=year]').val();
	
	airport = $('#payform select[name="airport"]').val();
	direction = $('#payform input[name="direction"]:checked').val();
	url = '/times/' + airport + '/' + direction+ '/' + d + '-' + m + '-' + y;
	
	stupidIE = new Date();
	
	$.ajax({
		url: '/newpayform/ajax.php?url=' + url + '/' + stupidIE.getTime(),
		dataType: 'xml',
		beforeSend: function(){			
			$('#seats').html('');
			$('#seats_loading').fadeIn();
			$('#seat_selected').html('тамбур');
			$('#countFree').html('');
			
			$('#payform input[name="place"]').val('');
		},
		success: function(xml){
			$('#tripTimeSelect').html('');
			
			$(xml).find('times > time').each(function(){
				$('#tripTimeSelect').append('<option id="' + $(this).attr('id') + '">' + $(this).attr('name') + '</option>');
			});
			
			requestSeats();
		}
	});
}

function swClass(e)
{
	if($(e).val() == 1) {
		$('#trainSeats').fadeOut();
		$('#tripTime').fadeOut();
		
		$('#tripPrice').html('250');
	} else {
		$('#seats_loading').show();
		$('#trainSeats').fadeIn();
		$('#tripTime').fadeIn();
		
		$('#tripPrice').html('700');
		
		requestTime();
	}
}

function userGetPassword()
{
	$('#loginForm').attr('action', $('#newPassword').attr('href'));
	$('#loginForm').submit();
	return false;
}

function calculateSum()
{
	selected_date = $.datepicker.parseDate('dd-mm-yy', $("#datepicker").val());
	current_date = new Date();
	
	if(selected_date.getTime() - current_date.getTime() < 1000*60*60*24*30)
		sum = prices[$('#payform select[name=tariff]').val()];
	else
		sum = pre_prices[$('#payform select[name=tariff]').val()];
		
	$('#tripPrice').html(sum);
}

function gotoConfirm()
{
	if(window.location.href.indexOf('/en/') > 0) {
		empty_date = 'Select the date, please';
		wrong_airport = 'Choose the airport, please';
		didnt_agree = 'You should agree with the transport rules for pay the ticket';
	} else {
		empty_date = 'Пожалуйста, выребите дату поездки';
		wrong_airport = 'Пожалуйста, выберите аэропорт';
		didnt_agree = 'Для оплаты билета необходимо согласиться с правилами перевозок';
	}
	
	if(!$("#datepicker").val()
		|| $("#datepicker").val() == '-- Choose --'
		|| $("#datepicker").val() == '-- Выбор --')
		return alert(empty_date);
	
	if(!($('#payform select[name="airport"]').val()*1))
		return alert(wrong_airport);
		
	if(!$('.checkbox:checked').size())
		return alert(didnt_agree);
		
	$('#payform').submit();
}

function setUpCalendar()
{
	$("#datepicker").datepicker({ dateFormat: 'dd-mm-yy', maxDate: '+4m', minDate: '-0d' });
	if(window.location.href.indexOf('/en/') > 0) {
		$("#datepicker").val('-- Choose --');
	} else {
		$("#datepicker").val('-- Выбор --');
	}
	/*
	$("#datepicker").val($.datepicker.formatDate('dd-mm-yy', new Date()));
	calChanged();
	*/
}

function calChanged()
{
	date = $.datepicker.parseDate('dd-mm-yy', $("#datepicker").val());
	
	$('#payform input[name=day]').val($.datepicker.formatDate('dd', date));
    $('#payform input[name=month]').val($.datepicker.formatDate('mm', date));
    $('#payform input[name=year]').val($.datepicker.formatDate('yy', date));
	
	requestTime();
	calculateSum();
	
}