$(document).ready(function() {
	var tab_now = 0;
	
	function confirm_go(){
		var cook=$.cookie("product_items");
        var table=$("table#lol").html();
		$('div#confirmation').html( '<table width="100%" id="confirm">'+table+'</table>'+ $('form#contact').html() );
        $("table#confirm thead").attr("height","24px");
        $("table#confirm thead th").eq(6).remove();
        $("table#confirm tr:last").remove();
        $("table#confirm tr").each(function(){
            $(this).find("td").eq(0).attr("width","50px");
            $(this).find("td").eq(0).find("img").attr("width","50px");
            $(this).find("td").eq(6).remove();
        });
        var i=0;
        $("table#lol input.count").each(function(){
            $("table#confirm input.count").eq(i).val($(this).val());
            i++;
        });
		$('div#confirmation input').removeClass('ui-state-error');
		$('div#confirmation input').addClass('ui-state-highlight');
		$('div#confirmation textarea').addClass('ui-state-highlight');
		$('div#confirmation input').attr('disabled', 'disabled');
		$('div#confirmation textarea').attr('disabled', 'disabled');
		$('div#confirmation input[name=z_fio]').val( $('form#contact input[name=z_fio]').val() );
		$('div#confirmation input[name=z_phone]').val( $('form#contact input[name=z_phone]').val() );
		$('div#confirmation input[name=z_email]').val( $('form#contact input[name=z_email]').val() );
		$('div#confirmation textarea[name=z_adres]').val( $('form#contact textarea[name=z_adres]').val() );
		$('div#confirmation textarea[name=z_primech]').val( $('form#contact textarea[name=z_primech]').val() );
		if ($('div#confirmation textarea[name=z_adres]').val().length > 1)
		{
			$('div#confirmation textarea[name=z_adres]').attr('disabled', 'disabled');
			$('div#confirmation textarea[name=z_adres]').prev().html('Адрес доставки');
		}
		else 
		{
			$('div#confirmation textarea[name=z_adres]').prev().remove();
			$('div#confirmation textarea[name=z_adres]').remove();
		}
		var str = '';
		str += '<fieldset class="register">';
		str += '<label class="register">Оплата</label>';
		str += '<input type="text" class="ui-widget-content ui-corner-all ui-state-highlight" value="'+$('div#oplata_zakaza label[aria-pressed=true] span').html()+'" disabled />';
		str += '<input type="hidden" name="z_oplata" value="'+$('div#oplata_zakaza label[aria-pressed=true]').attr('id')+'" />';
		str += '<label class="register">Доставка</label>';
		str += '<input type="text" class="ui-widget-content ui-corner-all ui-state-highlight" value="'+$('div#dostavka_zakaza label[aria-pressed=true] span').html()+'" disabled />';
		str += '<input type="hidden" name="z_dostavka" value="'+$('div#dostavka_zakaza label[aria-pressed=true]').attr('id')+'" />';
		str += '</fieldset>';
		
		if ($.cookie("product_order"))
			str += '<input type="hidden" name="z_order" value="'+$.cookie("product_order")+'" />';
		
		$('div#confirmation').append(str);
	}
	
	$('div#form_dialog').dialog({
		autoOpen: false,
		width: 900,
		height: window.screen.availHeight-200,
		modal: true,
		buttons: {
			'Назад': function(){
				tab_now = 0;
				$('div#form_dialog').parent().find("div button").eq(1).children("span").html("Подтвердить");
				$('div#form_dialog').parent().find("div button").eq(0).hide();
				$('div#form_dialog').parent().find("div button").eq(2).show();
				$('#form_tabs').tabs("option","disabled", []);
				$('#form_tabs').tabs("select", 0);
				$('#form_tabs').tabs("option","disabled", [3]);
			},
			'Подтвердить': function(){
				if(!$('div#form_dialog').parent().find("div button").eq(1).children("span").html().match("Оформить")) {
					var prov=false;
					$('div#form_dialog form#contact').find("input").each(function(){
						if($(this).val()=="") {
							$(this).addClass('ui-state-error');
							$('div#form_dialog').find(".dialogTips").addClass('ui-state-highlight').text("Поле не может быть пустым");
							$('#form_tabs').tabs("select", 0);
							prov=true;
							return false;
						}    
					});
					if ($('div#oplata_zakaza label[aria-pressed=true]').attr('id') == 2 && !$.cookie("product_order"))
					{
						prov = true;
						alert("Для безналичного типа оплаты нужно сначала оплатить заказ в системе WebPay");
					}
					if(prov)
						return;
					$('div#form_dialog form#contact').find("input").each(function(){
						$(this).removeClass('ui-state-error');
					});
					$('div#form_dialog').parent().find("div button").eq(2).hide();
					$('div#form_dialog').parent().find("div button").eq(1).children("span").html("Оформить");
					$('div#form_dialog').parent().find("div button").eq(0).show();
					$('#form_tabs').tabs("option","disabled", []);
					$('#form_tabs').tabs("select", 3);
					$('#form_tabs').tabs("option","disabled", [0, 1, 2]);
					confirm_go();
				}
				else {
					send();
				}
			},
			'Далее': function(){
				tab_now = (tab_now < 2)? tab_now+1: tab_now;
				if (tab_now == 2) $('div#form_dialog').parent().find("div button").eq(2).hide();
				$('#form_tabs').tabs("select", tab_now);
			}
		},
		open: function(event, ui) {  
			$('div#form_dialog').parent().find("div button").eq(0).hide();
			$('#form_tabs').tabs("select", 0);
		}
	});
	
	$("#form_tabs").tabs({
		ajaxOptions: {
			async: true,
			error: function(xhr, status, index, anchor) {
				$(anchor.hash).html("Не удалось загрузить содержимое. Обратитесь к администратору");
			}
		},
		cache: true,
		selected: 1,
		disabled: [3],
		select: function(){
			setTimeout(function(){
				tab_now = $("#form_tabs").tabs('option', 'selected');
				if (tab_now == 2) $('div#form_dialog').parent().find("div button").eq(2).hide();
				if (tab_now < 2) $('div#form_dialog').parent().find("div button").eq(2).show();
			}, 100);
		}
	});
	
	function send(){
		var req="";
		$('div#form_dialog div#confirmation').find("input,textarea").each(function(){
			req+=$(this).attr("name")+"="+$(this).val()+"&";
		});
        req+="count="
        $("table#confirm input.count").each(function(){
            req+=$(this).val()+"-";
        });
		$.ajax({
			url: $("div#site_name").html()+"include/ajax/zakaz_oformit.php",
			data: req,
			type: "POST",
			success: function(answ) {
				if(answ.match("0")){
					alert("Ваш заказ успешно оформлен, наш оператор свяжется с Вами.\nКопия заказа выслана на указанный email.\nСпасибо что выбрали нас.");
					$("div#form_dialog").dialog("close");
					$('div#trash_dialog').dialog('close');
					$.cookie("product_price",null,{expires:0, path: "/", domain: ""});
					$.cookie("product_count",null,{expires:0, path: "/", domain: ""});
					$.cookie("product_items",null,{expires:0, path: "/", domain: ""});
					$.cookie("product_order",null,{expires:0, path: "/", domain: ""});
					window.location.reload();
				}
				else if(answ.match("5"))
					alert("В процессе оформления возникла ошибка.\nВы выбрали безналичный тип оплаты.\nСначала оплатите Ваш заказ с помощью системы WebPay");
				else   
					alert("В процессе оформления возникла ошибка.\nПовторите попытку");
			}
		});
	}
	
});
