var maxOrderDate = 44;
var prevHour = null;
var prevMinute = null;
var initHour = null;
var initMinute = null;
var initDay = null;
var initMonth = null;
var initYear = null;

$(document).ready(function() {
	if ($.browser.msie) {
        $("input[type='text'].tbPhone").bind("focusin", function() {
            tbPhoneFocusIn($(this));
        });

        $("input[type='text'].tbPhone").bind("focusout", function() {
            tbPhoneFocusOut($(this));
        });
    } else {
        $("input[type='text'].tbPhone").focus(function() {
            tbPhoneFocusIn($(this));
        });

        $("input[type='text'].tbPhone").blur(function() {
            tbPhoneFocusOut($(this));
        });
    }

	function tbPhoneFocusIn(ptr) {
        if (ptr.val() == "код" ||
            ptr.val() == "телефон" ||
            ptr.val() == "добав.")
            ptr.val("");
    }

    function tbPhoneFocusOut(ptr) {
        if (ptr.val() == "") {
            if (ptr.hasClass("tbPhoneCode"))
                ptr.val("код");
            if (ptr.hasClass("tbPhoneNumber"))
                ptr.val("телефон");
            if (ptr.hasClass("tbPhoneAdd"))
                ptr.val("добав.");
        }
    }

	$('a.changeCaptchaLink').click(function() {
		var imgid = $(this).attr('captchaId');
		var imgsrc = $('#' + imgid).attr('src');
		$('#' + imgid).attr('src', imgsrc + new Date() + Math.random());
		return false;
	});
	
	// Little hack for Mozilla Firefox.
	if ($.browser.mozilla)
		$('a.changeCaptchaLink').trigger('click');

	// Order form saving actions.
	$('input.saveMeForm, select.saveMeForm').change(function() {
		var options = {path: '/', expires: 365};
		var type = $(this).attr('type');
		var name = $(this).attr('name');

		if ('checkbox' == type) {
			$.cookie(name, $(this).attr('checked'), options);
		}
		if ('text' == type || 'password' == type || 'select' == this.tagName.toLowerCase()) {
			$.cookie(name, $(this).val(), options);
		}
		//console.log('%s is %s', name, this.tagName);
	});

	// Order form restore actions.
	$('input.saveMeForm, select.saveMeForm').each(function() {
		var name = $(this).attr('name');
		var value = $.cookie(name);
		var type = $(this).attr('type');

		if (value != null) {
			if ('checkbox' == type) {
				$(this).attr('checked', value === 'true');
			}
			if ('text' == type || 'password' == type || 'select' == this.tagName.toLowerCase()) {
				if (value)
					$(this).val(value);
			}
			if ('bagaz' == name && value === 'true')
				chng_bagaz();
			if ('pay' == name && value === 'true') {
				chng_pay();
				document.getElementById('bonus').checked = false;
				chng_bonus();
			}
			if ('bonus' == name && value === 'true') {
				chng_bonus();
				document.getElementById('pay').checked = false;
				chng_pay();
			}
		} else {
			//console.log('%s is %s', name, value);
		}
	});

	initDatePicker();

	$('input[name="chooseMap"]').change(function() {
		$.cookie('m', $(this).val(), {'expires': new Date(new Date().getTime() + 365 * 24 * 60 * 60 * 1000)});
		$('#changeMap').val('1');
		$('#orderForm').submit();
	});
});

function initDatePicker() {
	if ($.datepicker) {
		initDay = $('#date_day').val();
		initMonth = $('#date_month').val();
		initYear = $('#date_year').val();
		initHour = prevHour = $('#time_hours').val();
		initMinute = prevMinute = $('#time_minutes').val();

		var td = $('#date_day').parents('td');
		td.children().remove();
		td.append('<input class="text2" type="text" id="order_date" id="order_date" /><input type="hidden" id="date_day" name="date_day" /><input type="hidden" id="date_month" name="date_month" /><input type="hidden" id="date_year" name="date_year" />');
		var idp = $('#order_date');
		idp.keydown(function() {
			return false;
		});

		var minDateDay = '0d';
		if (initHour == '00' && (initMinute == '00' || initMinute == '05' || initMinute == '10' || initMinute == '15' || initMinute == '20'))
			minDateDay = '1d';

		idp.datepicker({
			dateFormat: 'dd.mm.y',
			minDate: minDateDay,
			maxDate: '+' + maxOrderDate + 'd',
			onSelect: function(dateText, inst) {
				var arr = dateText.split('.');
				$('#date_day').val(arr[0]);
				$('#date_month').val(arr[1]);
				$('#date_year').val(arr[2]);
				checkTime();
			}
		});
		idp.val(initDay + '.' + initMonth + '.' + initYear);
		$('#date_day').val(initDay);
		$('#date_month').val(initMonth);
		$('#date_year').val(initYear);

		$('#time_hours, #time_minutes').live($.browser.msie ? 'click' : 'change', function() {
			checkTime();
		});

		$('#time_hours, #time_minutes').mouseover(function() {
			prevHour = $('#time_hours').val();
			prevMinute = $('#time_minutes').val();
		});
	}
}

function checkTime() {
	if ($('#date_day').val() == initDay &&
		$('#date_month').val() == initMonth &&
		$('#date_year').val() == initYear) {

		if ($('#time_hours').val() < initHour ||
			($('#time_minutes').val() < initMinute && $('#time_hours').val() <= initHour)) {
			alert('На прошедшее время заказать такси нельзя');
			$('#time_hours').val(initHour);
			$('#time_minutes').val(initMinute);
		}
	}
}

