$(document).ready(function(){
	$.post('cart.php',{cart_info: "on"},function(incoming){
		$('#cart_info').html(incoming.substring(0,incoming.indexOf('<center>')));
	},'text');
	$.ajax({
				url: "cart.php",
				data: "cart_info=true",
				type: "POST",
				dataType : "text",
				async: true,
				success: function (data) {
					$('#cart_info').html(data);
					}
			});
	$('#cart_open').click(function(){
		$("#dialog").dialog("open");
		$(".dialog_open").trigger('click');
	});
	
	$(".dialog_open").click(function() {
		
		$('#step_2_button').hide();
		$('#main_fields').hide();
		$('#quick_register_buttons').hide();
		$('#additional_fields').hide();
		$('#cart').show();
		if(typeof(yaCounter2316919)!="undefined") yaCounter2316919.reachGoal('addCart');
		if($("#dialog").dialog("isOpen") != true )
		{
		$.get('cart.php',{ add2cart	: $(this).attr('id').substring($(this).attr('id').indexOf('_')-1+2,$(this).attr('id').length), shopping_cart: "yes"},function(incoming){
			$('#cart').html(incoming);
			if($('#cart').html()=='<center><p><font>Ваша корзина пуста</font></p></center>')
				$('.ui-dialog-buttonpane').hide();
			
			$('#step_1_button').hide();
			//кнопка закрыть
			$('#close_dialog').click(function(){
				$('#dialog').dialog("close");
			});
			//кнопка оформление заказа
			$('#step_1').click(function(){
				$('#cart').hide();
				$('#step_2').show();
				$('#main_fields').show();
			});
			//кнопка очистить
			$('#clear_cart').click(function(){
				$.get('cart.php',{ clear_cart : "yes", shopping_cart : "yes"},function(incoming){
					$('#cart').html(incoming);
				}, 'text');
			});
			//кнопка удалить товар
			$('.remove_item').click(function(){
				$.get('cart.php',{ shopping_cart : "yes", remove : $(this).attr('id')},function(incoming){
					$(".dialog_open").trigger('click');
				}, 'text');
			});
			//кнопка обновить
//			$('#refresh').click(function(){
			$('.items_count').keyup(function(){
				if($(this).val() == "0")
					{
						$(this).val("1");
					}
				if($(this).val() != "")
				{
				var fields = $('#products_count').serialize();
				$.ajax({
					url: "cart.php",             // указываем URL и
					data: fields,
					type: "POST",
					dataType : "text",                     // тип загружаемых данных
					async: true,
					success: function (data) {
						$(".dialog_open").trigger('click');
   					}
				});
				}
			});
			$('#phone').removeClass("ui-state-error");
			$('#email').removeClass("ui-state-error");
		},'text')}
		else
			{
			$.get('cart.php',{shopping_cart : "yes"},function(incoming){
				$('#cart').html(incoming);
				if($('#cart').html()=='<center><p><font>Ваша корзина пуста</font></p></center>')
					$('.ui-dialog-buttonpane').hide();
				$('#step_1_button').hide();
				//кнопка закрыть
				$('#close_dialog').click(function(){
					$('#dialog').dialog("close");
				});
				//кнопка оформление заказа
				$('#step_1').click(function(){
					$('#cart').hide();
					if(typeof(yaCounter2316919)!="undefined") yaCounter2316919.reachGoal('orderStep1');
					$('#step_2').show();
					$('#main_fields').show();
				});
				//кнопка очистить
				$('#clear_cart').click(function(){
					$.get('cart.php',{ clear_cart : "yes", shopping_cart : "yes"},function(incoming){
						$('#cart').html(incoming);
					}, 'text');
				});
				//кнопка удалить товар
				$('.remove_item').click(function(){
					$.get('cart.php',{ shopping_cart : "yes", remove : $(this).attr('id')},function(incoming){
						$(".dialog_open").trigger('click');
					}, 'text');
				});
				//кнопка обновить
//				$('#refresh').click(function(){
				$('.items_count').keyup(function(){
					if($(this).val() == "0")
					{
						$(this).val("1");
					}
					if($(this).val() != "")
					{
					var fields = $('#products_count').serialize();
					$.ajax({
						url: "cart.php",             // указываем URL и
						data: fields,
						type: "POST",
						dataType : "text",                     // тип загружаемых данных
						async: true,
						success: function (data) {
							$(".dialog_open").trigger('click');
	   					}
					});
					}
				});
			},'text')
			}
		$("#dialog").dialog("open");
		$('#product_name').text("Товар: "+$(this).attr('id').substring($(this).attr('id').indexOf('_')-1+2,$(this).attr('id').length));
		$('#product_name').hide();
		return false;
	});
	
	$("#dialog").dialog({
		autoOpen : false,
//		height : 350,
		width : 600,
		modal : true,
		show: "fade",
		hide: "fade",
		buttons : {
			"Далее" : function() {
				if($('#step').val() == "step_1"){
					$('#step_1').trigger('click');
					$('#step').attr("value","step_2");
				}
				else
				{
					if($('#step').val() == "step_2"){
						$('#step').attr("value","step_3");
						$('#step_2').trigger('click');
						
	//					$('.ui-button-text').text('Заказать');
					}
					else
					{
						if($('#step').val() == "step_3"){
//							alert('нажал');
							if(typeof(yaCounter2316919)!="undefined") yaCounter2316919.reachGoal('orderStep3');
//							$('.ui-dialog-buttonset').hide();
							$('.ui-dialog-buttonpane').html($('.ui-dialog-buttonpane').html()+'<img src=\'/25.gif\'><span id=blinking style="font-size:15;">Отправка данных...</span>');
							$.fn.wait = function(time, type) {
						        time = time || 200;
						        type = type || "fx";
						        return this.queue(type, function() {
						            var self = this;
						            setTimeout(function() {
						                $(self).dequeue();
						            }, time);
						        });
						    };
						    function runIt() {
						      $("#blinking").wait()
						              .animate({"opacity": 0.1},50)
						              .wait()
						              .animate({"opacity": 1},100,runIt);
						    }
						    runIt();
							$.post('index.php',{ order4_confirmation_quick: "yes", shippingMethodID: $('#dostavka option:selected').val().substring($('#dostavka option:selected').val().indexOf(';:')-1+3,$('#dostavka option:selected').val().length), order_comment: $('#comments').val(), paymentMethodID: $('#payment option:selected').val().substring($('#payment option:selected').val().indexOf(';:')-1+3,$('#payment option:selected').val().length), submit: "true", shipping_addres: $('#shipping_addres').val()},function(incoming){$('#memo').html(incoming); $.post('invoice.php',{ orderID: incoming, complete_order : "yes" },function(data){$('.body_txt').html(data); $('body,html').animate({scrollTop: 0}, 800); $('#dialog').dialog('close');$.post('sendmail.php',{ sendmail_async: "yes", orderID: incoming, shippingMethodID: $('#dostavka option:selected').val().substring($('#dostavka option:selected').val().indexOf(';:')-1+3,$('#dostavka option:selected').val().length), paymentMethodID: $('#payment option:selected').val().substring($('#payment option:selected').val().indexOf(';:')-1+3,$('#payment option:selected').val().length), email: $('#email').val(), shipping_addres: $('#shipping_addres').val() },function(data){},'text');},'text');},'text')
							
							
							$('#step').attr("value","step_1");
						}
					}
				}
			}
		},
		open: function(event,ui){
			$.ajax({
				url: "cart.php",
				data: "cart_info=true",
				type: "POST",
				dataType : "text",
				async: true,
				success: function (data) {
					$('#cart_info').html(data);
					}
			});
		},
		close: function(event,ui){
			$('#step').attr("value","step_1");
			$.ajax({
				url: "cart.php",
				data: "cart_info=true",
				type: "POST",
				dataType : "text",
				async: true,
				success: function (data) {
					$('#cart_info').html(data);
					}
			});
		}
	});
	$('#step_2').hide();
	$('#main_fields').hide();
	$('#quick_register_buttons').hide();
	$('#additional_fields').hide();
	
	$('#step_2').click(function(){
		if(formCheck()>0){
			$('#phone').removeClass("ui-state-error");
			$('#email').removeClass("ui-state-error");
			$('#main_fields').hide();
			if(typeof(yaCounter2316919)!="undefined") yaCounter2316919.reachGoal('orderStep2');
			$.post('cart.php',{ step_2: "true", name: $('#first_name').val(), phone: $('#phone').val(), email: $('#email').val()},function(incoming){
				$('#additional_fields').show();
					$('#ajax_shipping').html(incoming)
					
					$('#dostavka_info').text($('#dostavka option:selected').val().substring(0,$('#dostavka option:selected').val().indexOf(';:')));
					
					var SID = $('#dostavka option:selected').val().substring($('#dostavka option:selected').val().lastIndexOf(';:')-1+3,$('#dostavka option:selected').val().length)
					SID = SID-1;
					$.post('index.php',{ ajax_payment: "test", num: SID },function(incoming){
						$('#ajax_payment').html(incoming);
						$('#payment_info').text($('#payment option:selected').val().substring(0,$('#payment option:selected').val().indexOf(';:')));
						$('#payment').change(function(){
							$('#payment_info').text($('#payment option:selected').val().substring(0,$('#payment option:selected').val().indexOf(';:')));
						});
					}, 'text');
					
					$('#dostavka').change(function(){
						$('#dostavka_info').text($('#dostavka option:selected').val().substring(0,$('#dostavka option:selected').val().indexOf(';:')));
						var SID = $('#dostavka option:selected').val().substring($('#dostavka option:selected').val().lastIndexOf(';:')-1+3,$('#dostavka option:selected').val().length)
						if(SID == 4)
							$('#addres').hide(1000);
						else
							$('#addres').show(1000);
						SID = SID-1;
						$.post('index.php',{ ajax_payment: "test", num: SID },function(incoming){
							$('#ajax_payment').html(incoming);
							$('#payment_info').text($('#payment option:selected').val().substring(0,$('#payment option:selected').val().indexOf(';:')));
							$('#payment').change(function(){
								$('#payment_info').text($('#payment option:selected').val().substring(0,$('#payment option:selected').val().indexOf(';:')));
							});
						}, 'text');
					});
					
//					$('#submit_order').click(function(){
////						var query = "&shippingMethodID="+$('#dostavka option:selected').val().substring($('#dostavka option:selected').val().indexOf(';:')-1+3,+"&paymentMethodID="+$('#payment option:selected').val().substring($('#payment option:selected').val().indexOf(';:')-1+3,$('#payment option:selected').val().length);
////						$('#dialog').dialog('close');
////						location.href = location.href+"?"+query;
//						alert('ушло');
//						$.post('index.php',{ order4_confirmation_quick: "yes", shippingMethodID: $('#dostavka option:selected').val().substring($('#dostavka option:selected').val().indexOf(';:')-1+3,$('#dostavka option:selected').val().length), order_comment: $('#comments').val(), paymentMethodID: $('#payment option:selected').val().substring($('#payment option:selected').val().indexOf(';:')-1+3,$('#payment option:selected').val().length), submit: "true", shipping_addres: $('#shipping_addres').val()},function(incoming){ $.post('invoice.php',{complete_order : "yes"},function(data){$('.body_txt').html(data);/*location.href=location.href*/},'text')},'text')
//					});	
//				}, 'text');
			}, 'text');
		}
		else
		{
			$('#phone').addClass("ui-state-error");
			$('#email').addClass("ui-state-error");
			updateTips("Укажите телефон (и, по желанию, e-mail).");
			$('#step').attr("value","step_2");
		}

	});
	
	function formCheck()
	{
		var fields = $('#RegisterForm').serialize();
		var phone = fields.substring(fields.lastIndexOf('phone=')-1+7,fields.length);
		if(phone.indexOf('&')!=-1)
			phone = phone.substring(0,phone.indexOf('&'));
		var email = fields.substring(fields.lastIndexOf('email=')-1+7,fields.length);
		if(email.indexOf('&')!=-1)
			email = email.substring(0,email.indexOf('&'));
		if(email.indexOf('%40')!=-1)
			email = email.substring(0,email.indexOf('%40'))+"@"+email.substring(email.indexOf('%40')-1+4,email.length);
		var pattern = new RegExp(/.{1,}@.{2,}$/);
//		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		var result = 0;
		if(pattern.test(email)==true)
			result++;
		var pattern =  new RegExp(/^((8|\+7)[\-\+]?)?(\(?\d{3}\)?[\-\+]?)?[\d\-\+]{7,10}$/);
		if(unescape(phone).match(pattern)) 
			result++;
		else result = 0;
		
		/\d/
		return result;
	}
	
	function updateTips(t) {
		if (t != "")
			$(".validateTips").text(t).addClass("ui-state-highlight");
		else
			$(".validateTips").addClass("ui-state-highlight");
		setTimeout(function() {
			$(".validateTips").removeClass("ui-state-highlight", 1500);
		}, 500);
	}
});
