$(document).ready(function() {
	$('#arrow').click(function() {
	    var from = $('#from').val();
	    $('#from').val($('#to').val());
	    $('#to').val(from);
	    $('#to').focus().select();
	});

	if (!($.browser.msie && $.browser.version.substring(0,1) == '6')) {
		var trainSearchText = 'Найти поезд';
		var stationSearchText = 'Найти станцию';
		$('#trainsSearch').val(trainSearchText).click(function() {
			if ($('#trainsSearch').val() == trainSearchText ) {
				$('#trainsSearch').val('');
			}
		}).blur(function() {
			if ($('#trainsSearch').val() == '') {
				$('#trainsSearch').val(trainSearchText);
			};
		}).suggest('/train/suggest').focus(function() {
			$(this).select();
		});

		$('#stationsSearch').val(stationSearchText).click(function() {
			if( $('#stationsSearch').val() == stationSearchText ) {
				$('#stationsSearch').val('');
			}
		}).blur(function() {
			if ($('#stationsSearch').val() == '') {
				$('#stationsSearch').val(stationSearchText);
			};
		}).suggest('/station/suggest').focus(function() {
			$(this).select();
		});

		$('#from').suggest('/index/cities').focus(function() {
			$(this).select();
		});
		$('#to').suggest('/index/cities').focus(function() {
			$(this).select();
		});
	}
	$('#from').focus();
	$('#adultsCount').change(changePassengersSelect);
	$('#childsCount').change(changePassengersSelect);
	$('#infantsCount').change(changePassengersSelect);
	$('#searchForm').submit(function(e) {
		var from = $('#from').val();
		var to = $('#to').val();
		if ($.trim(from) == $.trim(to)) {
			$.notify({text:'Станции отправления и прибытия совпадают', title:'Ошибка!', icon:'/img/dialog-error.png'});
			$('#to').focus();
			return false;
		}
		if ($.trim(from).length < 2) {
			$.notify({text:'Непонятно откуда Вы хотите ехать. Похоже, Вы ничего не ввели?', title:'Ошибка!', icon:'/img/dialog-error.png'});
			$('#from').focus();
			return false;
		}
		if ($.trim(to).length < 2) {
			$.notify({text:'Непонятно куда Вы хотите ехать. Похоже, Вы ничего не ввели?', title:'Ошибка!', icon:'/img/dialog-error.png'});
			$('#to').focus();
			return false;
		}
		//Проверка даты
		if(!/^((0[1-9]|[1-2][0-9]|3[0-1])\.(01|03|05|07|08|10|12)|(0[1-9]|[1-2][0-9]|30)\.(04|06|09|11)|(0[1-9]|[1-2][0-9])\.02)\.(19|20)[0-9][0-9]$/.test($('#departureDate').val())) {
			$.notify({text:'Непонятно когда Вы хотите ехать. Что-то не так с датой отправления.', title:'Ошибка!', icon:'/img/dialog-error.png'});
			$('#departureDate').focus();
			return false;
		}
		//Преобразование станции отправления в код
		if (!$('#fromCode').val().length) {
			$.ajax({
				type:"POST",
				url:"/index/stationtocode",
				dataType:"json",
				data: ({stationName:from}),
				async: false,
				success:function(data) {
					if (data.error) {
						$.notify({text:'Непонятно откуда Вы хотите ехать. Может быть опечатка?', title:'Ошибка!', icon:'/img/dialog-error.png'});
						$('#from').focus();
					}
					else if (data.stationCode) {
						$('#fromCode').val(data.stationCode);
					}
					else {
						showPreciseModal(data, '#fromCode', 'Уточните станцию отправления...');
						e.preventDefault();
					}
				}
			});
		}

		//Преобразование станции назначения в код
		if (!$('#toCode').val().length) {
			$.ajax({
				type:"POST",
				url:"/index/stationtocode",
				dataType:"json",
				data: ({stationName:to}),
				async: false,
				success:function(data) {
					if (data.error) {
						$.notify({text:'Непонятно куда Вы хотите ехать. Может быть опечатка?', title:'Ошибка!', icon:'/img/dialog-error.png'});
						$('#to').focus();
					}
					else if (data.stationCode) {
						$('#toCode').val(data.stationCode);
					}
					else {
                        showPreciseModal(data, '#toCode', 'Уточните станцию назначения...');
                        e.preventDefault();
					}
				}
			});
		}

        if (!$('#toCode').val().length || !$('#fromCode').val().length) {
            return false;
        }
		showLoading();
	});

    $('#departureDate').focus(function(){
        $('#calendar').fadeIn('normal');
    });

    $('img#calendarImg').click(function(){
        $('#calendar').fadeIn('normal');
    });

    $('#calendar a[class!="tColor1"]').mouseover(function() {
        $(this).addClass('date_act');
    });

    $('#calendar a[class!="tColor1"]').mouseout(function() {
        $(this).removeClass('date_act');
    });

	$('#closecalendar').click(function() {
		$('#calendar').hide();
	});

    $('#calendar a[class!="tColor1"]').click(function() {
        $('#departureDate').val($(this).attr('date'));
        $('#calendar').hide();
    });

});

//отображение модального окна уточнения станций
function showPreciseModal(data, id, text) {
    var modalContents = '<div id="modalPrecise" class="c_btb_1 clr"><div class="c_btb_2"><div class="c_btb_3"><div class="c_btb_4"><span class="font1"><img style="vertical-align: middle" src="/img/warn_ic.gif" border="0" /> ' + text + '</span><br/><br/>';
    for (var key in data.stations) {
        var station = data.stations[key];
        modalContents += '<a class="link1" stationCode="' + station.stationCode +'"><span >' + station.stationCode + ' ' + station.stationName + '</span></a><br/>';
    }
    modalContents += '</div></div></div></div>';
    $(modalContents).modal({
        containerCss:{background:'none', width: '500px'},
        dataCss:{'background-color':'#000', 'background-opacity':'50%'},
        close:false,
        onOpen: function (dialog) {
                    dialog.overlay.fadeIn('fast', function () {
                        dialog.container.slideDown('fast', function () {
                            dialog.data.fadeIn('fast');
                        });
                    });
                }
    });
    $('#modalPrecise a').each(function() {
    $(this).click(function() {
            $(id).val($(this).attr('stationCode'));
            $.modal.close();
            $('#modalPrecise').remove();
            $('#searchForm').submit();
        });
    });
}

//обработчик состава пассажиров
function changePassengersSelect() {
	//optimize stuff below this comment
	var adultsCount = $('#adultsCount').val();
	var childsCount = $('#childsCount').val();
	var infantsCount = $('#infantsCount').val();
	//alert(adultsCount + '=' + childsCount  + '='  + infantsCount);
	//очищаем опции селектов
	$('#adultsCount').empty();
	$('#childsCount').empty();
	$('#infantsCount').empty();
	//вычисляем допустимые опции
	var maxAdults = 4;
	adultsCount = maxAdults < adultsCount ? maxAdults : adultsCount;
	var maxChilds = 4 - adultsCount;
	maxChilds = maxChilds > 3 ? 3 : maxChilds;
	maxChilds = maxChilds < 0 ? 0 : maxChilds;
	childsCount = maxChilds < childsCount ? maxChilds : childsCount;
	var maxInfants = 4 - adultsCount - childsCount;
	maxInfants = maxInfants > 2 ? 2 : maxInfants;
	maxInfants = maxInfants < 0 ? 0 : maxInfants;
	maxInfants = maxInfants > adultsCount ? adultsCount : maxInfants;
	infantsCount = maxInfants < infantsCount ? maxInfants : infantsCount;
	//заполняем селекты допустимыми значениями
	for (var i = 1; i <= maxAdults; i++) {
		var selected = (i == adultsCount ? ' selected="true"' : '');
		$('<option' + selected + '>' + i + '</option>').appendTo('#adultsCount');
	}
	for (var i = 0; i <= maxChilds; i++) {
		var selected = (i == childsCount ? ' selected="true"' : '');
		$('<option' + selected + '>' + i + '</option>').appendTo('#childsCount');
	}
	for (var i = 0; i <= maxInfants; i++) {
		var selected = (i == infantsCount ? ' selected="true"' : '');
		$('<option' + selected + '>' + i + '</option>').appendTo('#infantsCount');
	}
}
