/*
 * Constructor and general  init
 * capital
 */
var Checkout = function(initData) {
	this.weight = (initData.weight || 0) * 1;
	this.cartTotal = (initData.cart_total || 0) * 1;
	this.credits = (initData.credits || 0) * 1;
	this.discount = (initData.discount || 0) * 1;
    this.promoDiscount = (initData.promo_discount || 0) * 1;
	this.shipmentPrice = null;
	this.shipmentPriceHints = {
		noShipmentMethod: $("#serviceMessageNoShipment").html(),
		noCountry:  $("#serviceMessageNoCountry").html(),
		noRegion: $("#serviceMessageNoRegion").html(),
		loading: "<img src='/static/img/ajax-loader1.gif' alt='loading...' />"
	};

	this.defaultArea = initData.area || null;
    this.defaultRegionId = initData.regionId || null;

	this.defaults = {
		moscow: initData.capitalName || "Москва",
		moscowRegion: initData.capitalId || 42,
		moscowAreaRegion: initData.capitalRegionId || 43,
		russia: 184
	};
	this.paymentPrice = 0;
	this.giftwrapPrice = 0;
	this.insurancePrice = 0;
	this.discountPrice = 0;
    this.promoDiscountPrice = 0;
	this.creditsUsed = 0;

    this.discountSum = (initData.discount_sum || 0) * 1;
    this.promoDiscountSum = (initData.promo_discount_sum || 0) * 1;

	this.lastShipment = null;
	this.lastPayment = null;

	this.currentArea = null;
	this.defaultShipmentForArea = {
		"moscow": 11,
		"mo": 2,
		"russia": 2,
		"restofworld": 6
	};
	
	this.defaultPaymentForShipment = {};
	this.defaultCityForArea = {};
	this.defaultRegionForArea = {};
	this.defaultCountryForArea = {};

	this.shipmentMethod = null;	 // object

	this.country = null;
	this.region = null;
	this.city = "";

    this.gaAccount = initData.gaAccount || "UA-7047870-1";
	
	this.init();
};
Checkout.prototype.init = function() {
	$("#login_is_required").parent().hide();
	$("#old_checkout").parent().hide();
	$("#oldCartParams").parent().hide();
	$("#quick_checkout").show();

	this.initOptions();
	this.updateSummary();
	this.initShipmentArea();
	this.initShipmentMethods();
	this.initPaymentMethods();
	this.initAddress();
	this.initSubmitButton();
};
/*
 * Init form elements
 */
Checkout.prototype.initShipmentArea = function() {
	var thiz = this;

	if(this.defaultArea) {
		var a = $("li#" + this.defaultArea);
		if(a.size() > 0) {
			$("#shipment_area li").removeClass("active");
		}
		a.addClass("active");
		this.defaultCityForArea[this.defaultArea] = $("input[name=city]").val();
	}

	$("#shipment_area a").click(function() {
		$("#shipment_area li").removeClass("active");
		$(this).parent().addClass("active");
		$(this).blur();
		thiz.changeShipmentArea();
		return false;
	});
//	alert(this.defaultShipmentForArea);
	thiz.changeShipmentArea();
};
Checkout.prototype.initAddress = function() {
	var thiz = this;
        
	if(this.defaultRegionId) {
		$("select[name=region]").val(this.defaultRegionId);
		this.defaultRegionForArea[this.defaultArea] = $("select[name=region]").val();
		if (this.currentArea != 'moscow') $("input[name=city]").parent().show();
        if ($("select[name=region]").attr("value") == 0) $("input[name=city]").parent().hide();
        thiz.updateSummary();
	}

	$("select[name=country]").change(function() {
		thiz.updateSummary();
	});
	var regionChange = function() {
		var city = $("option[value=" + $(this).val() + "]", this).attr("city");
		$("input[name=city]").parent().show();
        if ($("select[name=region]").attr("value") == 0) $("input[name=city]").parent().hide();
        $("input[name=city]").val(city);
		thiz.updateSummary();
	};
	$("select[name=region]").change(regionChange);
	$("select[name=region]").keyup(regionChange);
	$("input[name=city]").keyup(function() {
		thiz.updateFormErrors();
	});
	$("input[name=zipcode]").keyup(function() {
		thiz.updateFormErrors();
	});
	$("input[name=address]").keyup(function() {
		thiz.updateFormErrors();
	});
	$("input[name=email]").keyup(function() {
		thiz.updateFormErrors();
	});
	$("input[name=fio]").keyup(function() {
		thiz.updateFormErrors();
	});
	$("input[name=phone]").keyup(function() {
		thiz.updateFormErrors();
	});       
    $("input[name=iagree]").click(function() {
		thiz.updateFormErrors();
	});
    $("select[name=learned_from]").change(function() {
		thiz.updateFormErrors();
	});       
};
Checkout.prototype.initShipmentMethods = function() {
	var thiz = this;
	$("#shipment_methods li input").click(function() {
		thiz.defaultShipmentForArea[$("#shipment_area li.active").attr("id")] = $("#shipment_methods input[type=radio]:checked").val();
		thiz.lastShipment = $("#shipment_methods input[type=radio]:checked").val();
		thiz.changeShipment($(this).attr("value"));
	});
};
Checkout.prototype.initPaymentMethods = function() {
	var thiz = this;
	$("#payment_methods li input").click(function() {
		thiz.defaultPaymentForShipment[$("#shipment_area li.active").attr("id")+'_'+$("#shipment_methods input[type=radio]:checked").val()] = $("#payment_methods input[type=radio]:checked").val();
		thiz.lastPayment = $("#payment_methods input[type=radio]:checked").val();
	});
};
Checkout.prototype.initOptions = function() {
	var thiz = this;
	$("#giftwrap_option input").click(function() {
		thiz.calculateGrandTotal();
	});
	$("#insurance_option input").click(function() {
		thiz.calculateGrandTotal();
	});
};

/*
 * Update summary
 */
Checkout.prototype.updateSummary = function() {
	$("#cartWeightValue").html(this.weight);
	$("#cartTotalValue").html(Checkout.outputPrice(this.cartTotal));
	this.calculateGrandTotal();
	this.calculateShipmentCost();
	if(this.paymentPrice) {
		$("#paymentPrice").parents("tr").show();
		$("#paymentPrice").html(Checkout.outputPrice(this.paymentPrice));
	} else {
		$("#paymentPrice").parents("tr").hide();
	}

	this.updateFormErrors();
};
Checkout.prototype.updateAddressInfo = function() {
	this.country = $("select[name=country]").val();
	this.region = $("select[name=region]").val();
	this.city = $("input[name=city]").val();

	this.defaultCityForArea[this.currentArea] = this.city;
	this.defaultRegionForArea[this.currentArea] = this.region;
	this.defaultCountryForArea[this.currentArea] = this.country;
};
Checkout.prototype.calculateGrandTotal = function() {
	// giftwrap:
	if($("#giftwrap_option:visible").size() > 0 && $("#giftwrap_option input:checked").size() > 0) {
		for(var i = 0; i < Checkout.giftwrap_cost.length; i++) {
			if(this.weight < Checkout.giftwrap_cost[i]['weight']) {
				this.giftwrapPrice = Checkout.giftwrap_cost[i]['price'] * 1;
				break;
			}
		}

		$("#giftwrapPrice").html(Checkout.outputPrice(this.giftwrapPrice));
		$("#giftwrapPrice").parents("tr").show();
	} else {
		this.giftwrapPrice = 0;
		$("#giftwrapPrice").parents("tr").hide();
	}

    // show potential gift price
    for(var i = 0; i < Checkout.giftwrap_cost.length; i++) {
        if(this.weight < Checkout.giftwrap_cost[i]['weight']) {
            var gift_price = Checkout.giftwrap_cost[i]['price'] * 1;
            $("#gift_wrap_price").html(gift_price);
            break;
        }
    }

	// insurance:
	if(this.shipmentMethod) {
		if($("#insurance_option:visible").size() > 0 && $("#insurance_option input:checked").size() > 0) {
			this.insurancePrice = (this.cartTotal) * this.shipmentMethod['insurance_rate'];
			$("#insurancePrice").html(Checkout.outputPrice(this.insurancePrice));
			$("#insurancePrice").parents("tr").show();
		} else {
			this.insurancePrice = 0;
			$("#insurancePrice").parents("tr").hide();
		}
	}

	// discount:
	if(this.discount) {
        this.discountPrice = this.discountSum;  //this.cartTotal * this.discount;
		$("#userDiscountValue").parents("tr").show();
		$("#userDiscountValue").html(Checkout.outputPrice(-this.discountPrice));	// todo: rub values here
	} else {
		$("#userDiscountValue").parents("tr").hide();
	}

    // Promo-discount:
	if(this.promoDiscount) {
		this.promoDiscountPrice = this.promoDiscountSum * 1;    //this.cartTotal * this.promoDiscount * 0.01;
		$("#promoCodeDiscountValue").parents("tr").show();
		$("#promoCodeDiscountValue").html(Checkout.outputPrice(-this.promoDiscountPrice));	// todo: rub values here
	} else {
		$("#promoCodeDiscountValue").parents("tr").hide();
	}

	this.grandTotalPrice = this.cartTotal + this.shipmentPrice + this.giftwrapPrice + this.insurancePrice; // - this.discountPrice - this.promoDiscountPrice;

	// credits:
	if(this.credits) {
		this.creditsUsed = this.grandTotalPrice > this.credits ? this.credits : this.grandTotalPrice;
		$("#userCreditsValue").parents("tr").show();
		$("#userCreditsValue").html(Checkout.outputPrice( this.creditsUsed));	// todo: rub values here
	} else {
		$("#userCreditsValue").parents("tr").hide();
	}

	// grand total
	$("#cartGrandTotalValue").html(Checkout.outputPrice(this.grandTotalPrice - this.creditsUsed));


};
Checkout.prototype.calculateShipmentCost = function() {
	this.updateAddressInfo();
	if(this.shipmentMethod !== null && this.country && this.region) {
		if(this.shipmentMethod['freeshipment_total'] > 0 && this.shipmentMethod['freeshipment_total'] <= this.cartTotal) {
			this.shipmentPrice = 0;
			$("#shipmentPrice").html(Checkout.outputPrice(this.shipmentPrice));
			this.calculateGrandTotal();
			return;
		}

		$("#shipmentPrice").html(this.shipmentPriceHints['loading']);
		$("#cartGrandTotalValue").html(this.shipmentPriceHints['loading']);

		var thiz = this;

		$.ajax({
			url: "/checkout/calc_shipment_cost",
			type: "POST",
			data: {
				"country": this.country,
				"region": this.region,
				"city": encodeURIComponent(this.city) ,
				"shipment_method": this.shipmentMethod.id
			},
			success: function(data, textStatus, XMLHttpRequest) {
				thiz.shipmentPrice = data*1;
				$("#shipmentPrice").html(Checkout.outputPrice(thiz.shipmentPrice));
				thiz.calculateGrandTotal();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
//			   console.log(errorThrown);
			},
			dataType: "text"
		})
	} else {
		if(this.shipmentMethod === null) {
			$("#shipmentPrice").html(Checkout.outputHint(this.shipmentPriceHints.noShipmentMethod));
		} else if(!this.country) {
			$("#shipmentPrice").html(Checkout.outputHint(this.shipmentPriceHints.noCountry));
		} else if(!this.region) {
			$("#shipmentPrice").html(Checkout.outputHint(this.shipmentPriceHints.noRegion));
		}
	}
};

/*
 * set area
 */
Checkout.prototype.changeShipmentArea = function() {
	var areas = ["moscow", "mo", "russia", "restofworld"];
	var current = $("#shipment_area li.active").index();
	this.currentArea = areas[current];
	// отображение способов доставки в зависимости от места доставки
	this.showShipmentsForArea(this.currentArea);
	this.changeAddressFormForArea(this.currentArea);
	// отмечание способа доставки
	this.changeShipment(this.defaultShipmentForArea[this.currentArea]);
	if(this.currentArea == "moscow" || this.currentArea == "mo") {
		$("#onestepcheckout").show();
	} else {
		$("#onestepcheckout").hide();
	}
};
Checkout.prototype.showShipmentsForArea = function(area) {
	$("#shipment_methods li").hide();
	for(var i = 0; i < Checkout.shipments.length; i++) {
		if(Checkout.shipments[i][area] == 1) {
			if(!Checkout.shipments[i]['min_total'] || Checkout.shipments[i]['min_total'] < this.cartTotal) {
				$("#shipment_methods li.shipment_" + Checkout.shipments[i]['id']).show();
			}
		}
	}
    $("#banned_shipment li").hide();
    var banned_message = 0;
	for(var i = 0; i < Checkout.banned_shipments.length; i++) {
		if(Checkout.banned_shipments[i][area] == 1) {
			if(!Checkout.banned_shipments[i]['min_total'] || Checkout.banned_shipments[i]['min_total'] < this.cartTotal) {
				$("#banned_shipment li.shipment_" + Checkout.banned_shipments[i]['id']).show();
                banned_message = 1;
			}
		}
	}
    if (banned_message) $("#banned_shipment li.shipment_0").show();
};
Checkout.prototype.changeAddressFormForArea = function(area) {
	$("select[name=country]").parents("label").show();
	$("select[name=region]").parents("label").show();
	$("input[name=city]").parent().show();
	$("input[name=zipcode]").parent().show();
    $("input[name=zipcode]").attr("maxlength", 6);
	if(area == "moscow") {
		$("select[name=country]").val(this.defaults.russia).parents("label").hide();
		$("select[name=region]").val(this.defaults.moscowRegion).parents("label").hide();
		$("input[name=city]").val(this.defaults.moscow).parent().hide();
		if(this.shipmentMethod) {
			if(this.shipmentMethod.id != 1 || this.shipmentMethod.id != 2) {
				$("input[name=zipcode]").parent().hide();
			}
		}
	}
	if(area == "mo") {
		$("select[name=country]").val(this.defaults.russia).parents("label").hide();
		$("select[name=region]").val(this.defaults.moscowAreaRegion).parents("label").hide();
		$("input[name=city]").val(this.defaultCityForArea['mo'] || "");
	}
	if(area == "russia") {
		$("select[name=country]").val(this.defaults.russia).parents("label").hide();
		$("select[name=region]").val(this.defaultRegionForArea['russia'] || "");
		$("input[name=city]").val(this.defaultCityForArea['russia'] || "");
                if ($("select[name=region]").attr("value") == 0) $("input[name=city]").parent().hide();
	}
	if(area == "restofworld") {
        $("input[name=zipcode]").attr("maxlength", 10);
		$("select[name=country]").val(this.defaultCountryForArea['restofworld'] || "");
		$("select[name=region]").val(this.defaults.moscowRegion).parents("label").hide(); // set moscow just to not keep it null
		$("input[name=city]").val(this.defaultCityForArea['restofworld'] || "");
	}
};
Checkout.prototype.changeAddressFormForShipment = function(shipmentId) {
	if($.inArray(shipmentId * 1, [4,5,12,11,16,18,19,20,21]) >= 0) {	// courier or somivyvoz
		$("input[name=zipcode]").parent("label").hide();
	} else {
		$("input[name=zipcode]").parent("label").show();
	}
    $("#selfDeliveryAddressChina").hide();
    $("#selfDeliveryAddressGrandma").hide();
    $("#specialDeliveryDolgoprudniy").hide();
    $("#specialDeliveryZelenograd").hide();
	if(shipmentId == 11) {	  // samovyvoz
		$("input[name=address]").parent("label").hide();
		$("#selfDeliveryAddress").show();
		$("#meetingDeliveryAddress").hide();
		$("#houseDeliveryWarning").hide();
	} else if(shipmentId == 16) {	  // samovyvoz
		$("input[name=address]").parent("label").hide();
		$("#selfDeliveryAddressChina").show();
		$("#meetingDeliveryAddress").hide();
		$("#houseDeliveryWarning").hide();
        $("#selfDeliveryAddress").hide();
	} else if(shipmentId == 18) {	  // samovyvoz
		$("input[name=address]").parent("label").hide();
		$("#selfDeliveryAddressGrandma").show();
		$("#meetingDeliveryAddress").hide();
		$("#houseDeliveryWarning").hide();
        $("#selfDeliveryAddress").hide();
	} else if(shipmentId == 5) {	  // curier
		$("input[name=address]").parent("label").hide();
		$("#selfDeliveryAddress").hide();
		$("#meetingDeliveryAddress").show();
		$("#houseDeliveryWarning").hide();
	} else if(shipmentId == 20) {	  // samovyvoz
		$("#houseDeliveryWarning").hide();
		$("input[name=address]").parent("label").show();
		$("#selfDeliveryAddress").hide();
		$("#meetingDeliveryAddress").hide();
        $("#specialDeliveryDolgoprudniy").show();
	} else if(shipmentId == 21) {	  // samovyvoz
		$("#houseDeliveryWarning").hide();
		$("input[name=address]").parent("label").show();
		$("#selfDeliveryAddress").hide();
		$("#meetingDeliveryAddress").hide();
        $("#specialDeliveryZelenograd").show();
	} else if(shipmentId == 4 && this.currentArea == 'mo') {	  // curier on home
		$("input[name=zipcode]").parent("label").hide();
		$("input[name=address]").parent("label").show();
		$("#selfDeliveryAddress").hide();
		$("#meetingDeliveryAddress").hide();
		$("#houseDeliveryWarning").show();
	} else {
		$("#houseDeliveryWarning").hide();
		$("input[name=address]").parent("label").show();
		$("#selfDeliveryAddress").hide();
		$("#meetingDeliveryAddress").hide();
	}
    if (this.currentArea == 'moscow') {
		$("input[name=city]").parent("label").hide();
	}
	if (this.currentArea == 'mo' && (shipmentId == 11 || shipmentId == 5)) {
		$("input[name=city]").parent("label").hide();	
	}
	if (this.currentArea == 'mo' && shipmentId != 11 && shipmentId != 5) {
		$("input[name=city]").parent("label").show();	
	}
};

/*
 * set shipment
 */
Checkout.prototype.changeShipment = function(shipmentId) {
	if (this.defaultShipmentForArea[this.currentArea] != 0) {
		shipmentId = this.defaultShipmentForArea[this.currentArea];	
	}
	for(var i = 0; i < Checkout.shipments.length; i++) {
		if(Checkout.shipments[i]['id'] == shipmentId) {
			this.shipmentMethod = Checkout.shipments[i];
		}
	}

	if(this.shipmentMethod) {
		if(this.shipmentMethod['allow_giftwrap'] > 0) {
			$("#giftwrap_option").show();
		} else {
			$("#giftwrap_option").hide();
		}

		if(this.shipmentMethod['insurance_rate'] > 0) {
			$("#insurance_option").show();
		} else {
			$("#insurance_option").hide();
		}
	}

	this.defaultShipmentForArea[this.currentArea] = shipmentId;
	$("input", "#shipment_methods li.shipment_" + shipmentId).attr("checked", true);
	this.changeAddressFormForShipment(shipmentId);
	this.showPaymentsForShipment(shipmentId);
	this.updateSummary();
};
Checkout.prototype.showPaymentsForShipment = function(shipmentId) {
	$("#payment_methods li").hide();
	var paymentFlag = false;
	for(var i = 0; i < Checkout.shipments_to_payments.length; i++) {
		if(Checkout.shipments_to_payments[i]['shipment_method'] == shipmentId) {
			$("#payment_methods li.payment_" + Checkout.shipments_to_payments[i]['payment_method']).show();
			if (this.lastPayment == Checkout.shipments_to_payments[i]['payment_method']) {
				paymentFlag = true;
			}
		}
	}
	// switch payment:
	if (paymentFlag && this.lastPayment) {
		this.changePayment(this.lastPayment);
	} else if(this.defaultPaymentForShipment[this.currentArea+'_'+shipmentId]) {
		this.changePayment(this.defaultPaymentForShipment[this.currentArea+'_'+shipmentId]);
	} else {
		this.changePayment($("input", "#payment_methods li:visible:first").val());
	}
};

/*
 * set payment
 */

Checkout.prototype.changePayment = function(paymentId) {
	for(var i = 0; i < Checkout.payments.length; i++) {
		if(Checkout.payments[i]['id'] == paymentId) {
			this.paymentMethod = Checkout.payments[i];
		}
	}
	$("input", "#payment_methods li.payment_" + paymentId).attr("checked", true);
};

Checkout.prototype.checkPromoDiscount = function(value) {
	this.promoDiscount = value;
    //this.calculateGrandTotal();
};


/*
 * validate form
 */
Checkout.prototype.updateFormErrors = function() {
	var errors = this.getFormErrors();
	$("#errors").html(errors.join("<br/>"));

	if(errors.length == 0) {
		$("#ajaxSubmit").attr("disabled", false);
	} else {
		$("#ajaxSubmit").attr("disabled", true);
	}
};
Checkout.prototype.getFormErrors = function() {
	var errors = [];
	if(this.paymentMethod == null) {
		errors.push($("#serviceMessageNoPayment").html());
	}
	if($.trim($("input[name=fio]").val()).length == 0) {
		errors.push($("#serviceMessageNoFio").html());
	}
	if($.trim($("input[name=email]").val()).length == 0) {
		errors.push($("#serviceMessageNoEmail").html());
	}
	if($.trim($("input[name=phone]").val()).length < 5) {
		errors.push($("#serviceMessageNoPhone").html());
	}
    var shipment = this.shipmentMethod ? this.shipmentMethod['id']*1 : 0;
    if($.trim($("input[name=zipcode]").val()).length < 3 && (this.currentArea != 'moscow') && $.inArray(shipment, [4, 5, 11, 12, 16, 18, 20, 21])<0) {
		errors.push($("#serviceMessageNoZipcode").html());
	}
	if($.trim($("input[name=address]").val()).length < 3 && $.inArray(shipment, [5, 11, 16, 18])<0) {
		errors.push($("#serviceMessageNoAddress").html());
	}
    if($("select[name=learned_from]").length>0) {
        if (!($("select[name=learned_from]").val() > 0)) {
            errors.push($("#serviceMessageNoLearnedFrom").html());
        }
    }
	if($("#iagree:checked").size() == 0) {
		errors.push($("#serviceMessageNoAgreement").html());
	}
	if(this.shipmentMethod == null) {
		errors.push($("#serviceMessageNoShipment").html());
	} else {
		if($.inArray(this.shipmentMethod['id']*1, [4, 5, 12]) >= 0) {
			// courier specific
		}
//		alert(this.shipmentMethod['id']);
		if($.inArray(this.shipmentMethod['id']*1, [1,2,3,6,7,8,9,13,14,15]) >= 0) {
			switch(this.currentArea) {
				case 'restofworld':
					if($.trim($("select[name=country]").val()).length == 0) {
						errors.push($("#serviceMessageNoCountry").html());
					}
					if($.trim($("input[name=city]").val()).length == 0) {
						errors.push($("#serviceMessageNoCity").html());
					}
					break;
				case 'russia':
					if($.trim($("select[name=region]").val()).length == 0) {
						errors.push($("#serviceMessageNoRegion").html());
					}
					if($.trim($("input[name=city]").val()).length == 0) {
						errors.push($("#serviceMessageNoCity").html());
					}
					break;
				case 'mo':
					if($.trim($("input[name=city]").val()).length == 0) {
						errors.push($("#serviceMessageNoCity").html());
					}
					break;
				case 'moscow':
					if($.trim($("input[name=address]").val()).length == 0) {
						errors.push($("#serviceMessageNoAddress").html());
					}
			}
		}
	}

	return errors;
};
Checkout.prototype.initSubmitButton = function() {
	var errorTranslations = {
		'EMAIL IS IN WRONG FORMAT': $("#serviceMessageWrongEmail").html(),
        'PHONE SHOULDNT BE MORE THEN 5 DIGITS': $("#serviceMessageShortPhone").html(),
		'ZIPCODE FOR RUSSIA MUST BE 6 DIGITS': $("#serviceMessageWrongRussiaZipcode").html(),
		'CHOOSE SHIPMENT METHOD': $("#serviceMessageNoShipment").html(),
		'CHOOSE PAYMENT METHOD': $("#serviceMessageNoPayment").html(),
        'CITY SHOULDNT BE EMPTY': $("#serviceMessageNoCity").html(),
        'ADDRESS SHOULDNT BE EMPTY': $("#serviceMessageNoAddress").html()
	};

	$("#ajaxSubmit").click(function() {
		var data = $(this).parent().serialize();
		$("#ajaxSubmit").attr("disabled", true).val($("#serviceMessageLoading").html());
		$.post("/checkout/quick", data, function(response) {
			if(response.order) {
//				alert(response.liquidform);
				$("#new_order_id").html(response.order);
				$("#link_to_order a").attr("href", "/order/view/" + response.order + '/' + response.anonym_key);
				if(response.paymentform) $("#paymentform").html(response.paymentform);
				$("#content").html($("#order_success").html());
				//if(response.liquidform && confirm('Перейти к оплате?')) {
				//	$("#liquid_form").submit();
				//}
                $(".cart_wrap").html("");
                window.location = "#top";

                // yaMetrika order inform
                try {
                    var yaCounter2291794 = new Ya.Metrika(2291794);
                    yaCounter2291794.reachGoal(
                        'commit_order', {order_id: response.order, order_price: response.order_total}
                    );
                } catch(err) {}

                // ga Inform
                try {
                    _gaq.push(['_setAccount', this.gaAccount]);
                    _gaq.push(['_trackPageview']);
                    _gaq.push(['_addTrans',
                        response.order,         // order ID - required
                        "",                     // affiliation or store name
                        "0",   // total - required
                        "0",                    // tax
                        "0", // shipping
                        "",                     // city
                        "",                     // state or province
                        ""                      // country
                    ]);
                    _gaq.push(['_trackTrans']); //submits transaction to the Analytics servers
                } catch(err) {}

			} else {
				$("input[name=email]").parent().removeClass("error");
				var errors = [];
				for(var i = 0; i < response.errors.length; i++) {
					errors.push(errorTranslations[response.errors[i]] || response.errors[i]);
					if(response.errors[i] == "EMAIL IS IN WRONG FORMAT") {
						$("input[name=email]").parent().addClass("error");
					}
				}
				alert($("#serviceMessageFixErrors").html() + " \n" + errors.join(";\n"));
				$("#ajaxSubmit").attr("disabled", false).val($("#serviceMessageProceedCheckout").html());
			}

		}, 'json');
		return false;
	});
};
