// Анимация конверта при отправке данных
var intervalID;
var backgroundPosition_x = 0;
function animation_order_bg() {
	backgroundPosition_x ++;
	$("#order-bg").css('background-position', backgroundPosition_x + 'px top');
}    
// -----------------------------------------------------------------------------
$(document).ready(function() {
	// Вызов формы заказа (конверт выезжает слева)
    $('.order-button').click(function() {
		$('#msg-box').css('display', 'none');
		$('#msg-box').css('opacity', 0);

		$('#order-publish').removeClass('noactive');
		$("#al_error").text('');
		$('#al_normal').css('display', 'block');
		
    	$('#order-form').css('left', '-650px');
        $('#wrapper').css('display', 'none');
        $('#order-box').css('display', 'block');            
        $('#order-form').css('display', 'block');            
        $('#order-form').animate({left: Math.round(($('body').width() - $('#order-form').width()) / 2) }, 
        	{ duration: 1000, easing: 'easeOutElastic' }, function() {   });

        return false;
    });
    
	// --------------------------------------------------
    // Закрытие формы заказа сайта при отмене
    function close_afte() {
        $('#order-box').css('display', 'none');
        $('#wrapper').css('display', 'block');        	
    }
    
    $('.closer').click(function() {
        clearInterval(intervalID); // Останавливаю анимация верхнего бекграунда конверта
        // Конверт уезжает влево
        $('#order-form').animate({left: - ($('#order-form').width() + 50) }, { duration: 500, easing: 'easeInElastic' });
        window.setTimeout(close_afte, 600);	        
        return false;
    });
	// --------------------------------------------------
	// Закрытие формы заказа сайта после отправки письма         
    function close_send() {
        clearInterval(intervalID); // Останавливаю анимация верхнего бекграунда конверта
   		$('body').css('overflow', 'hidden'); // Во избежание горизонтальной прокрутки
   		// Уезжаю формой в право после отсылки письма с заказом
        $('#order-form').animate({left: Math.round(($('body').width() + $('#order-form').width() + 50)) }, 
        							{ duration: 800, easing: 'easeInBack' });            	
    }
	function close_afte_send() { 
    		$('body').css('overflow', 'auto');
			$('#order-form').css('display', 'none');
			$('#order-form').css('opacity', 1);
			$('#msg-box').css('display', 'block');
			$('#msg-box').animate({opacity: 1}, 500, 'linear', function() {   });
	}
	// --------------------------------------------------
    // Перехват сабмита формы заказа
    var options = {
		target: "#al_error",
		url: "/messenger/send_email/",
		success: function() {
			//alert('E-mail отправлен!'); 
			$('#al_normal').css('display', 'none');
			if ($('#al_error').text().slice(0, 5) == 'Yahoo') {
	            window.setTimeout(close_send, 1000);
	            window.setTimeout(close_afte_send, 2200);
			} else {
				if ($('#al_error').text().slice(0, 5) != 'Error') {
					$("#al_error").text('Упс! Какие-то проблемки на сервере. Перезвоните на 095 909 67 68.');
				}
		        clearInterval(intervalID); // Останавливаю анимация верхнего бекграунда конверта
           		$('#order-publish').removeClass('noactive');
			}
	  	}
	};					
	$('#formochka').ajaxForm(options); // Запуск перехвата сабмита формы заказа (на всякий случай)
        
    $('#order-publish').click(function() {
    	if (!$('#order-publish').hasClass('noactive')) {
    		$('#order-publish').addClass('noactive');
    		intervalID = window.setInterval('animation_order_bg()', 20);
			$('#formochka').ajaxSubmit(options); // Ajax Submit  формы заказа
    	}	
		return false;
    });             
    // ------------------------
    // Добавление фоновой картинки превьюшек после загрузки страници
    $('#design_view').css('background-image', "url('/design/i/design_preview.jpg')");
    // Переключение превьюшек
    $('#design_preview a').click(function() {
    	if (!$(this).hasClass('active')) {
        	num = $(this).attr('rel');
        	$('#design_preview a').removeClass('active');
        	$(this).addClass('active');
        	
        	tmp1 = -387*(parseInt(num)-1) + 'px top';
            $('#design_view').stop().animate({backgroundPosition: tmp1}, {duration: 1000, easing: 'easeOutBack'});
            
    	}	
    	return false;
    });
    // ------------------------
    // Подгрузка картинок
    var imgs_array = new Array(
    	'/design/i/logo_night.png',
    	'/design/i/order_shadow.png',
    	'/design/i/order-close.png',
    	'/design/i/order-form_top.png',
    	'/design/i/order-publish.png',
		'/design/i/ajax-loader.gif'
    );
    var i = 0;
    $('#img_load').attr('src', imgs_array[i]);
    
	$('#img_load').load(function() {
		i++;
		if (i < imgs_array.length) {
			$('#img_load').attr('src', imgs_array[i]);
		}	
	});
    // ------------------------
    
    
    
});

// Выход из формы заказа сайта по клавише  Esc
$(document).keyup(function(e) {
   if (e.keyCode == 27) { $('.closer').click(); }
});

