// RIMUOVE UN ARTICOLO DAL CARRELLO
removeCart = function() {
  $(this).attr("title", "");
  updateCart();
  
  $(this).parent().fadeOut("slow", function() {
    $(this).remove();
  });

  return false;
}

checkCartQuantity = function() {
  var s = this.text || "1";
  s = s.match(/\d+/) || "1";
  $(this).val(s);
  updateCart();
}

// CENTRA TUTTO NELLA PAGINA (NON USATA)
centerAll = function() {
  var bgpos = (window.innerHeight - $("#wrapper").height()) / 2;
  $("body").css("background-position", "center " + bgpos + "px");
  $("#wrapper").css("top", bgpos);
}

updateCart = function() {
  var a = new Object();
  a.rnd = "xx" + Math.round(Math.random() * 100000000);
  $("#cartBasket .cartItem").each(function(i) {
      eval("a.item" + i + '="' + $(this).find("a.icoBin").attr("title") + '";');
      eval("a.qnt" + i + '="' + $(this).find("input[@type=text]").val() + '";');
  });
  $.get("/juventuscollection/Ajax/UpdateCart.ashx", a, function(cartData) {
    if ($("#bottomTotalFld").size() > 0) {
      location.reload();
    } else {
      var count = cartData.split(":")[0];
      var total = cartData.split(":")[1];
      $("#countFld").text(count);
      $("#totalFld").text(total);
      $("#grandTotalFld").text(total);
    }
  });
}

$(function() {
  // TEMPLATE DEL CARRELLO
  cartTemplate = $("#cartBasket .cartItem:last").removeClass("dummy").remove();
  $(".cartItem").find(".icoBin").click(removeCart).end().hide().fadeIn("fast");
  
  $("#cartBasket .cartItem input").typeWatch({
    callback: checkCartQuantity,
    wait: 750,
    highlight: true,
    enterkey: false
  });
  
  // DROPDOWN MENU: LINK PRINCIPALI
  $(".catMenu>li>a").click(function() {
    var current = $(this).blur().parent().find("ul");
    $(".catMenu ul").not(current).hide();
    current.slideToggle("fast");
    return false;
  });

  // DROPDOWN MENU: Z-INDEX MENU A COMPARSA
  $(".catMenu>li").each(function(i) {
    $(this).css("z-index", 10 - i);
  });

  // DROPDOWN MENU (COLONNA SINISTRA): IMPOSTAZIONE TESTO DI DEFAULT
  $(".catMenu ul a.selected").each(function() {
    var txt = $(this).text();
    $(this).parents(".catMenu").find(">li>a").text(txt);
  });

  // SLIDER (RANGE PREZZI)
  $(".slider").Slider(
    {
      accept : ".indicator",
      restricted: true,
      onSlide : function(procx, procy, x, y) {
        price = parseInt((parseInt(5000 * x / 212)) / 10) * 10;
        var prices = $("#pricerange strong");
        prices.eq(this.SliderIteration).text("" + price);
        $(".slider input").eq(this.SliderIteration).val("" + x);
        
        $(".applyRange").attr("href", $(".applyRange").attr("href")
          .replace(/[\d\-]+/, prices.eq(0).text() + "-" + prices.eq(1).text() +
          "-" + $(".slider input:first").val() + "-" + $(".slider input:last").val()));

        if (this.SliderIteration == 1 && $("#indicator1").position().left > 210) {
          $("#indicator1").css("left", 206);
        }
      },
      values: [
        [parseInt($(".slider input:first").val()), 0],
        [parseInt($(".slider input:last").val()), 0]
      ]
    }
  );

  // EFFETTO HOVER PER IE6 SU PRODOTTI
  $(".prodSmall").hover(function() {
    $(this).addClass("prodHover");
  }, function() {
    $(this).removeClass("prodHover");
  });

  $(".prodMid").hover(function() {
    $(this).addClass("prodMidHover");
  }, function() {
    $(this).removeClass("prodMidHover");
  });

  // PRODOTTI TRASCINABILI
  if ($("#cartBasket").size()) {
    $(".draggable").Draggable({
      ghosting: true,
      opacity: 0.5,
      revert: true,
      zIndex: 1000,
      snapDistance: 10
    });
  }

  // AGGIUNTA AL CARRELLO
  function addToCart(elm) {
    var pending = true;

    $("#cartBasket .cartItem").each(function() {
      if ($(this).find(".icoBin").attr("title") == $(elm).find("input[@type=hidden]:last").val()) {
        pending = false;

        $(this).fadeOut("fast", function() {
          $(this).find("input").val((parseInt($(this).find("input[@type=text]").val()) || 0) + 1).end().fadeIn("fast");
          updateCart();
        });
      }
    });

    if (pending) {
      var newItem = cartTemplate.clone()
        .find(".icoBin").click(removeCart).attr("title", $(elm).find("input[@type=hidden]:last").val()).end()
        .find("img").attr("src", $(elm).find("p.prodPic img").attr("src").replace(/width=\d+/, "width=42").replace(/height=\d+/, "height=36")).end()
        .find(".prodName").text($(elm).find(".prodName").eq(0).text()).end()
        .find(".price").text($(elm).find(".price").text()).end()
        .find("input").each(function() {
					$(this).typeWatch({
						callback: checkCartQuantity,
						wait: 750,
						highlight: true,
						enterkey: false
					});
				}).end();
        
      var s = $(elm).find("ul.catMenu:last>li>a");
      
      if (s.size() > 0) {
        newItem.find("p.size").text(s.eq(0).text());
      }

      $("#cartBasket").append(newItem.hide());
      newItem.fadeIn("slow");
      updateCart();
    }
  }

  // CARRELLO
  $("#cartBasket").Droppable({
    accept: "draggable",
    ondrop: function(dragged) {
      var link = $(dragged).find("a.icoCart");
      if (link.attr("href")) {
        if (link.attr("href").match("addcart")) {
          addToCart(dragged);
          $(".prodSmall").removeClass("prodHover");
          $(".prodMid").removeClass("prodMidHover");
        } else {
          location.href = link.attr("href");
        }
      }
    }
  });

  // AGGIUNGE L'ARTICOLO AL CARRELLO
  $("a.icoCart").click(function() {
    if (this.href.match("addcart")) {
      if ($("#cartBasket").size() > 0) {
        var elm = $(this);

        while(!elm.is("div")) {
          elm = elm.parent();
        }

        addToCart(elm.get(0));
        return false;
      }
//    } else {
//      $("#msglink").click();
//      return false;
    }
  });

  // NASCONDE IL MESSAGGIO POPUP AL CLICK SUL BOTTONE OK
  $(".cmdCloseBox").click(tb_remove);
  
  $("a.icoCart, a.icoDet, del.icoNoCart").each(function() {
    $(this).attr("title", $(this).text());	
  });

  // HOVER PER MENU SUPERIORE CON LINK ESTERNI
  $("#utils li").hover(function() {
    $(this).addClass("utilsHover");
  }, function() {
    $(this).removeClass("utilsHover");
  });
  
  $(".prodMid ul.catMenu ul a").click(function() {
    var elm = $(this);
    
    elm.addClass("selected").parent().siblings("li").find(">a").removeClass("selected");

    while(!elm.is("div")) {
      elm = elm.parent();
    }
    
    elm.find("p.prodPic img").attr("src", $(this).attr("href"));
    $(this).blur().parent().parent().slideUp("fast");
    return false;
  });
  
  // COPIA L'ALT NEL TITLE DELLE IMMAGINI SE IL TITLE E' MANCANTE
  $("img").each(function() {
    $(this).attr("title", $(this).attr("title") || $(this).attr("alt"));
  });
  
  // VISUALIZZA GLI AVVISI DI PRODOTTO NON DISPONIBILE
  $(".prodNotAvail").each(function() {
    $(this).hide().fadeTo("fast", 0.8);
  });

  // RIABILITA I LINK SUGLI AVVISI DI PRODOTTO NON DISPONIBILE
  $(".prodSmall .prodNotAvail").add(".prodMid .prodNotAvail").click(function() {
    location.href = $(this).siblings(".prodPic").find("a").attr("href");
  }).css("cursor", "pointer");

  // NON CONFERMA L'ORDINE SE IL CARRELLO E' VUOTO  
  $(".shopBtn").click(function() {
    return $("#cartBasket .cartItem").size() > 0;
  });
});

function bodyLoad() {
  setTimeout(function() {
    $(".autoPopup").each(function() {
      $(this).find(".thickbox").click();
    });
  }, 500);
}
