$(function() {
	var texts = {};
	$.getJSON("eshop/get_jsTexts.php", {k: "cart.empty,cart.tariff,cart.list.delivery,cart.order.delivery_options,common.currency"}, 
			  function(json) {
		$.extend(texts, json);
	});

	$("#cart tr .remove input").click(function() {
        var orderCode = $(this).val();
        $.ajax({
            type: "GET",
            url: "index.php?page=cart",
            data: "remove[]=" + orderCode,
            success: function() {
                $("#cart tr .remove input[value=" + orderCode + "]").parent().parent().fadeOut(500, function() {
                    $(this).remove();
                    calcPrice(texts);
                });
            },
            error: function() {
                window.location(url+"&remove[]="+orderCode);
            }
        });
    });
    
    $("#cart tr .quantity input").change(function() {
        var orderCode = $(this).attr("name").slice(9, -1);
        var quantity = $(this).val();
        $.ajax({
            type: "GET",
            url: "index.php?page=cart",
            data: "quantity[" + orderCode + "]=" + quantity,
            success: function() {
                var startColor = $("#cart tr .quantity input[name*=" + orderCode + "]").parent().parent().hasClass("odd") ? "#eee" : "#fff";
                $("#cart tr .quantity input[name*=" + orderCode + "]").parent().parent().find("td").animate({ backgroundColor: "#ff8" }, 100).animate({ backgroundColor: startColor }, 800);
                calcPrice(texts);
            },
            error: function() {
                window.location(url +"&quantity[" + orderCode + "]=" + quantity);
            }
        });
    });

            $("#copyPersonalData").change(function(){
                if($('#copyPersonalData').is(':checked')) {
                    $("#oFirstNameGuarantee").val($("#oFirstName").val());
                    $("#oLastNameGuarantee").val($("#oLastName").val());
                    areaVal = $("#oArea option:selected").val();
                    cityVal = $("#oCity option:selected").val();
                    $("#oAreaGuarantee").selectOptions(areaVal, true);
                    $("#oCity").copyOptions("#oCityGuarantee", "all");
                    $("#oCityGuarantee").selectOptions(cityVal, true);
                    $("#oZipCodeGuarantee").val($("#oZipCode").val());
                    $("#oStreetGuarantee").val($("#oStreet").val());
                    $("#oPhoneGuarantee").val($("#oPhone").val());
                }
                $(this).blur();
            });

            $("#person").click(function(){
                $("#companyFields").hide();
                $("#personFields").fadeIn("fast");
                $(this).blur();
            });

            $("#company").click(function(){
                $("#personFields").hide();
                $("#companyFields").show("slow");
                $(this).blur();
            });

            $("#submitOblasti").click(function(){
                $("#step").val('order');
                $("#theForm").submit();
            });

            $("select#sArea").change(function(){
                $.getJSON("eshop/_inc/cart/order_naseleniMesta.php",{obl_let: $(this).val(), responseType: 'json'}, function(j){
                  var options = '';
                  for (var i = 0; i < j.length; i++) {
                    options += '<option value="' + j[i].optionValue + '"';
                    if (j[i].optionSelected == "yes")  options += ' selected="seleccted"';
                    options += '>' + j[i].optionDisplay + '</option>';
                  }
                  $("select#sCity").html(options);
                  var deliveryText = texts["cart.order.delivery_options"] + ' <input type="hidden" name="delivery" value="" />';
                   $("#deliveryOptions").html(deliveryText);
                })
              })

              $("select#sCity").change(function(){
                $.getJSON("eshop/_inc/cart/check_deliveryOptions.php",{nm_id: $(this).val(), total_price: $('#total_priceValue').val(),responseType: 'json'}, function(j){
                  var options = '';
                  //alert (j[0].nm_id);
                  for (var i = 1; i < j.length; i++) {
                    if (j[i].deliveryPrice == undefined) j[i].deliveryPrice = '';
                    options += '<input id="'+j[i].id+'" class="deliveryOption" type="radio" name="delivery" value="' + j[i].deliveryName + '" price="' + j[i].deliveryPrice + '" /> ' + j[i].deliveryName;
                    if (j[i].deliveryText)  options += ' / ' + j[i].deliveryText;
                    if (j[i].deliveryLink)  options += ' / <a href="' + j[i].deliveryLink + '" target="_blank">' + texts["cart.tariff"] + '</a>';
                    if (j[i].deliveryPrice)  options += ' / ' + CurrencyFormatted(j[i].deliveryPrice) + ' ' + texts["common.currency"];
                    options += '<br />'
                  }
                   if (options == '') options = texts["cart.order.delivery_options"] + ' <input type="hidden" name="delivery" value="" />';
                   $("#deliveryOptions").html(options);
                })
              })

              $("select#sAreaGuarantee").change(function(){
                  $.getJSON("eshop/_inc/cart/order_naseleniMesta.php",{obl_let: $(this).val(), responseType: 'json'}, function(j){
                    var options = '';
                    for (var i = 0; i < j.length; i++) {
                      options += '<option value="' + j[i].optionValue + '"';
                      if (j[i].optionSelected == "yes")  options += ' selected="selected"';
                      options += '>' + j[i].optionDisplay + '</option>';
                    }
                    $("select#sCityGuarantee").html(options);
                  })
                })

              $(".deliveryOption").live("click",function(){
                  var totalPrice, deliveryName = $(this).attr("value");
                  var deliveryPrice = $(this).attr("price");
                  if (deliveryPrice == '') deliveryPrice = 0;
                  $("#deliveryPriceInput").attr("value",deliveryPrice);
                  $("#deliveryName").html(texts["cart.list.delivery"] + '*: ' + deliveryName);
                  if (deliveryPrice != 0) {
                      $("#deliveryPrice").html(CurrencyFormatted(deliveryPrice));
                      totalPrice = $("#total_priceValue").val();
                      totalPrice = parseFloat(totalPrice) + parseFloat(deliveryPrice);
                      $("#total_price div").text(CurrencyFormatted(totalPrice) + ' ' + texts["common.currency"]);
                  } else {
                      $("#deliveryPrice").html('-');
                      totalPrice = $("#total_priceValue").val();
                      $("#total_price div").text(CurrencyFormatted(totalPrice) + ' ' + texts["common.currency"]);
                  }
            });

});

function calcPrice(texts) {
    var totalPrice = 0;
    $("#cart tr .quantity").parent().each(function() {
        var quantity = $(".quantity input", this).val();
        if (quantity < 0) quantity = (quantity*(-1));
        var unitPrice = $(".unit_price", this).text();
        var extendedPrice = (quantity*unitPrice);
        totalPrice += extendedPrice;
        
        $(".extended_price", this).html(extendedPrice.toFixed(2) + ' ' + texts["common.currency"]);
        $("#total_price").html(totalPrice.toFixed(2) + ' ' + texts["common.currency"]);
    });
    if ( totalPrice == 0 ) {
        $("#cart").parent().replaceWith("<p class='center'>" + texts["cart.empty"] + "</p>");
    }
}


function formTabs(domChunk){
    $(domChunk).click(function(){
        var tabID = $(this).attr('href');
        $("#tabs li").removeClass('active');
        $(this).parent().addClass('active');
        formTabShow(tabID);
        this.blur();
        return false;
    });
    $(window).load(function(){
        $('#order').find(".step").hide();
        $('#personalData').show("slow");
        $("#personalDataTab").parent().addClass("active");
    });
}

function formTabShow(tabID) {
    $('#order').find(".step").hide();
    $(tabID).show();
}

function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}
