$(document).ready(function(){
	$('form.call-me').submit(function(){
		if($('input[name="phone"]', this).val() !== ''){
			$.ajax({
				url: '/call-me/',
				type: 'POST',
				data: $(this).serialize() + '&ajax=1',
				success: function(data){
					if(data.error == ''){
						$('.call-me .phone').slideUp('slow');
					}
					if($('#tooltip').length == 0){
						$('body').append('<div id="tooltip" />');
						$('#tooltip').append('<div id="tooltip-header" />', '<div id="tooltip-body" />', '<div id="tooltip-button" />');
					}
					$('#tooltip-button').text('OK');
					$('#tooltip-header').text(data.header);
					$('#tooltip-body').html('<p>' + data.message + '</p>');
					$('#tooltip').show().stop().fadeTo(100, 1, function(){
						$(this).fadeTo(5000, 1, function(){
							$(this).fadeTo(5000, 0);
						});
					});
				},
				dataType: 'json'
			});
		}
		return false;
	});
	$('#order-form form').live('submit', function(){
		var formData = $(this).serialize() + '&' + 'ajax=1';
		$.ajax({
			url: '/contacts/',
			type: 'POST',
			cache: false,
			data: formData,
			contentType: 'application/x-www-form-urlencoded',
			beforeSend: function(){
				$('#order-form input.hand').attr('disabled', 'disabled');
				$('#order-form .tr-form').fadeTo('fast', 0.5);
			},
			success: function(data){
				if(data.html){
					initForm(data);
				}
				else{
					$('#order-form').remove();
					showTooltip(data);
				}
			},
			error: function(xhr){
				//console.log(xhr);
			},
			dataType: 'json'
		});
		return false;
	});
	$('a.tab:first').click(function(){
		if($('#order-form').length == 0){
			$('body').append('<div id="order-form" />');
			$.ajax({
				url: '/contacts/',
				data: {ajax: 1},
				success: function(data){
					initForm(data);
				},
				dataType: 'json'
			});
		}
		$('#order-form').fadeIn('fast');
		return false;
	});
	$('span.tab').click(function(){
		$('.call-me .phone').slideToggle('slow');
	});
	$('#order-form .mask, #tooltip-button').live('click', function(){
		$(this).parent().hide();
	});
	$('#order-form .close-button').live('click', function(){
		$('#order-form').hide();
	});
});

function initForm(data){
	$('#order-form').html(data.html).append('<div class="mask" />');
	$('#order-form .form-ttl, #order-form i').remove();
	$('#order-form .tr-form').append('<div class="close-button" title="Закрыть" />').prepend('<h3>Пишите нам!</h3>');
}

function showTooltip(data){
	if($('#tooltip').length == 0){
		$('body').append('<div id="tooltip" />');
		$('#tooltip').append('<div id="tooltip-header" />', '<div id="tooltip-body" />', '<div id="tooltip-button" />');
	}
	$('#tooltip-button').text('OK');
	$('#tooltip-header').text(data.header);
	$('#tooltip-body').html('<p>' + data.message + '</p>');
	$('#tooltip').show().stop().fadeTo(100, 1, function(){
		$(this).fadeTo(5000, 1, function(){
			$(this).fadeTo(5000, 0);
		});
	});
}

