var URL = '/';

$(function () {
    $("a[rel^='gallery']").prettyPhoto({
        theme:'dark_square',
        showTitle: false
    });

    $('#background').cycle({
        speed: 4000,
        random: true
    });
    
    $('#background').supersize();
    

    var getPrice = function (number) {
        number = number.replace(/,/,'.');
        number = parseFloat(number);

        return number;
    };

    var setPrice = function (number) {        
        number = number.toFixed(2);
        number = number.replace(/\./,',');
        
        return number;
    };

    var addToCart = function (div) {
        var amount = div.find('input#addToCart-amount').val();
        div.find('input#addToCart-amount').val('1').blur();
        if (amount === '') {
            amount = 0;
        }
        amount = parseInt(amount, 10);
        if (amount === 0 || amount*1 !== amount) {
            return false;
        }

        var price = getPrice($('#productInfo .price').text());

        var cart = {
            price: getPrice($('#cartPrice').text())
        };

        $('#cartPrice').html(setPrice(cart.price + amount * price) +' &euro;');

        var id = $("div[id^='product-']").attr('id').split('-')[1];
        
        $.post(URL + 'e-shop/addToCart', {id: id, amount: amount, color: 0});

        var text = "bolo pridaných do košíka.";
        if (amount === 1) {
            text = "bol pridaný do košíka.";
        } else if (amount < 5) {
            text = "boli pridané do košíka.";
        }
        alert(amount + ' ks '+ text);
    };
    

    $("#addToCart").live('click', function () {
        var div = $(this).parent();
        addToCart(div);
    });

    $("input#addToCart-amount").live('keypress', function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code === 13) {
            var div = $(this).parent().parent();
            addToCart(div);            
        }
    });


    var cartCount = function (tr) {
      var amount = tr.find('input').val();
      var split = tr.attr('id').split('-');
      var id = split[1];
      var color = 0;
      if (split.length === 3) {
          color = split[2];
      }
      
      if (amount === '') {
          amount = 0;
      }
      amount = parseInt(amount, 10);
      if (amount*1 !== amount || amount < 0) {
          amount = 0;
      }
      
      var price = getPrice(tr.find('.price').text());
      var sum = amount * price;

      $.post(URL + 'e-shop/changeAmount', {id: id, amount: amount, color: color});

      tr.find('.sum').text(setPrice(sum));
      if (sum == 0) {
          tr.find('td:not(.amount)').addClass('lineThrough');
      } else {
          tr.find('td').removeClass('lineThrough');
      }

      var overal = {
          amount: 0,
          price: 0
      };
      
      $("#cartDetail tbody tr").each(function () {
          var amount = $(this).find('.amount input').val();
          if (amount === '') {
              amount = 0;
          }
          amount = parseInt(amount, 10);
          if (amount*1 !== amount || amount < 0) {
              amount = 0;
          }
          var price = getPrice($(this).find('.sum').text());
          overal.amount += amount;
          overal.price += price;
      });

      $(".overal-amount").text(overal.amount);
      $("#overal-price-vat").text(setPrice(overal.price));
      $("#cartPrice").html(setPrice(overal.price) +' &euro;');
      
      var discount = getPrice($("#discount").text());
      if (discount > 0) {
          var overalDiscount = overal.price / 100 * discount;
          overalDiscount = Math.round(overalDiscount*100)/100;          
          overal.price = overal.price - overalDiscount;
          $("#overal-discount").text('- '+ setPrice(overalDiscount));
          $("#overal-price-discount").text(setPrice(overal.price));
      }

      /*var vat = parseFloat($("#vat").text());
      var overalVat = overal.price / 100 * vat;        

      
      $("#overal-vat").text(setPrice(overalVat));
      $("#overal-price-vat").text(setPrice(parseFloat(overal.price) + parseFloat(overalVat.toFixed(2))));
      */
    };

    $("#cartDetail .amount input").live('change', function () {
        cartCount($(this).parent().parent());
    });

    $("#cartDetail .count").live('click', function () {
        cartCount($(this).parent().parent());
    });

    /*$("input[id^='paymentMethod-']").click(function () {
        var payment = parseInt($(this).attr('id').split('-')[1], 10);
        $("input[id^='deliveryMethod-']").parent().hide();
        $("input[id^='deliveryMethod-']").attr('checked', false);
        if (payment === 1) {
            $("input[id^='deliveryMethod-']").parent().hide();
            $("#deliveryMethod-1").parent().show();
        } else if (payment === 2) {
            $("input[id^='deliveryMethod-']").parent().hide();
            $("#deliveryMethod-2, #deliveryMethod-3").parent().show();
        } else if (payment === 3) {
            $("input[id^='deliveryMethod-']").parent().show();
        }
    });

    $("#cart-submit").click(function () {
        if ($("input[id^='paymentMethod-']:checked").length === 0 || $("input[id^='deliveryMethod-']:checked").length === 0) {
            alert('Nevyplnili ste spôsob platby alebo odberu / dopravy!');
            return false;
        }
    });*/

    $("#openTermsAndConditions").click(function () {
        var content = $.ajax({
            url: URL + 'e-shop/termsAndConditions',
            async: false
        }).responseText;
        $("body").append('<div id="termsAndConditions">' + content + '</div>');
        $("#termsAndConditions").dialog({
            bgiframe: true,
            resizable: false,
            modal: true,
            width: 751,
            height: 460,
            dialogClass: 'dialog',
            close: function(event,ui){
                $(this).remove();
            }
        });
    });


    $("#orderForm").submit(function () {
        if ($("input#TAC").attr('checked') === false) {
            alert('Ak chcete pokračovať v objednávke, musíte súhlasiť so Všeobecnými obchodnými podmienkami.');
            return false;
        }
        return true;
    });

    $("#orderFinalForm").submit(function () {        
        var ans = confirm('Naozaj si prajete odoslať všetky údaje a záväzne si objednať požadovaný tovar?');
        if (ans) {
            return true;
        }
        return false;
    });

    
    
    
    $('.placeholder').css('color', '#ccc');
    $('.placeholder').focus(function () {
        if ($(this).val() === $(this).attr('title')) {
            $(this).val('');
            $(this).css('color', '#fff');
        }
    }).blur(function () {
        if ($(this).val() === '') {
            $(this).val($(this).attr('title'));
            $(this).css('color', '#ccc');
        }
    });
         
         
         
         
         
    $('.productOrder select').change(function () {
        var orderBy = $(this).parent().find('.orderBy').val();
        var orderType = $(this).parent().find('.orderType').val();
        
        location = $.trim($(this).parent().find('.orderUrl').html()) +'?orderBy='+ orderBy +'&orderType='+ orderType;
    });
    
    $('.chooseColors').click(function () {
        var id = $(this).attr('id').split('-')[1];
        
        dialog.initialise();
        $('#dialog').append('<div class="loading">Načítavam...</div>');        
        
        $.get(URL +'e-shop/productColors/'+ id, function (html) {
           $('#dialog .loading').remove();
           $('#dialog').append(html);
           dialog.center();
           
           $("a[rel^='colors']").prettyPhoto({
              theme:'dark_square'
           });
           
           $('#colors li').click(function () {
              $('input', this).select();
           });
           
           var max = 0;
           $('#colors li').each(function () {
               if ($(this).height() > max) {
                   max = $(this).height();
               }
           });
           
           $('#colors li').height(max);
           
           $('#colors input').keyup(function () {
               var count = 0;               
               $('#colors input').each(function () {
                   var number = parseInt($(this).val(), 10);
                   if (isNaN(number) === false) {
                       count += number;
                   }                   
               });
               
               $('#addToCartColors span').html(count);
               if (count > 0) {
                   $('#addToCartColors').removeClass('disabled');
               } else {
                   $('#addToCartColors').addClass('disabled');
               }
           });
        });
    });
   
   
    $('#addToCartColors:not(.disabled)').live('click', function () {
        var id = $("div[id^='product-']").attr('id').split('-')[1];
        var price = getPrice($('#productInfo .price').text());        
        
        var amount = 0;
        $('#colors input').each(function () {
            var number = parseInt($(this).val(), 10);
            if (isNaN(number) === false && number > 0) {
                amount += number;
                
                $.post(URL + 'e-shop/addToCart', { id: id, amount: number, color: $(this).attr('id').split('-')[1] });
            }  
        });
        
        if (amount === 0 || amount*1 !== amount) {
            return false;
        }
        
        var cart = {
            price: getPrice($('#cartPrice').text())
        };

        $('#cartPrice').html(setPrice(cart.price + amount * price) +' &euro;');
                       

        dialog.close();

        var text = "bolo pridaných do košíka.";
        if (amount === 1) {
            text = "bol pridaný do košíka.";
        } else if (amount < 5) {
            text = "boli pridané do košíka.";
        }
        alert(amount + ' ks '+ text);
                
    });
});
