// RIMUOVE UN ARTICOLO DALLA COMPARAZIONE
removeCompare = function() {
  $(this).attr("title", "");
  updateCompare();
  
  $(this).parent().fadeOut("slow", function() {
    $(this).remove();
  });
  
  return false;
}

// 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);
}

// AGGIORNA LA COMPARAZIONE
updateCompare = function() {
  var a = new Object();
  a.rnd = "xx" + Math.round(Math.random() * 100000000);
  $("#compareBasket a.icoBin").each(function(i) {
      eval("a.item" + i + '="' + $(this).attr("title") + '";');
  });
  $.get("../../../Ajax/UpdateCompare.ashx", a);
}

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("../../../Ajax/UpdateCart.ashx", a, function(cartData) {
    if ($("#HiddenBottomBar").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 DELLA COMPARAZIONE
  compareTemplate = $("#compareBasket .comparable:last").remove();
  $(".comparable").find(".icoBin").click(removeCompare);

  // 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
  $(".draggable").Draggable({
    ghosting: true,
    opacity: 0.5,
    revert: true,
    zIndex: 1000,
    snapDistance: 10
  });

  // AGGIUNTA AL CARRELLO DI CONFRONTO PRODOTTI
  function addToCompare(elm) {
    if ($("#compareBasket .comparable").size() < 4) {
      var pending = true;

      $("#compareBasket .comparable").each(function() {
        if ($(this).find(".icoBin").attr("title") == $(elm).find("input[@type=hidden]:first").val()) {
          $(this).hide().fadeIn("slow");
          pending = false;
        }
      });

      if (pending) {
        var newItem = compareTemplate.clone()
          .find(".icoBin").click(removeCompare).attr("title", $(elm).find("input[@type=hidden]:first").val()).end()
          .find("img").attr("src", $(elm).find("p.prodPic img").attr("src").replace(/width=\d+/, "width=20").replace(/height=\d+/, "height=20")).end()
          .find(".prodName").text($(elm).find(".prodName").eq(0).text()).end()
          .find(".price").text($(elm).find(".price").text()).end();

        $("#compareBasket").append(newItem.hide());
        newItem.fadeIn("slow");
        updateCompare();
      }
    }
  }

  // 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 DI CONFRONTO
  $("#compareBasket").Droppable({
    accept: "draggable",
    ondrop: function(dragged) {
      addToCompare(dragged);
      $(".prodSmall").removeClass("prodHover");
      $(".prodMid").removeClass("prodMidHover");
    }
  });

  // CARRELLO
  $("#cartBasket").Droppable({
    accept: "draggable",
    ondrop: function(dragged) {
      var link = $(dragged).find("a.icoCart");
      if (link.attr("href")) {
        if (link.attr("href").match("addcart") || link.attr("href").match("Cart.aspx")) {
          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") || this.href.match("Cart.aspx")) {
      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;
    }
  });

  // NO COMPARAZIONE SENZA ARTICOLI  
  $(".compareLink").click(function() {
    if (!$("#compareBasket .comparable").size()) {
      $(".warnClick").click();
      return false;
    }
  });
  
  // NASCONDE IL MESSAGGIO POPUP AL CLICK SUL BOTTONE OK
  $(".cmdCloseBox").click(tb_remove);
  
  $("a.icoCart, a.icoCompare, a.icoDet, del.icoNoCart").each(function() {
    $(this).attr("title", $(this).text());	
  });

  // AGGIUNGE IL PRODOTTO AL CARRELLO DELLA COMPARAZIONE
  $("a.icoCompare").click(function() {
    if ($("#compareBasket").size() > 0) {
      var elm = $(this);

      while(!elm.is("div")) {
        elm = elm.parent();
      }

      addToCompare(elm.get(0));
      return false;
    }

    return true;
  });

  // 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).parent().parent().prev().text($(this).text());
    $(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;
  });
  
  // BACKOFFICE: SPOSTA BOTTONI
  $(".cmdPrepend").each(function() {
    $(this).prev().find(".gridFooter:first td:last").prepend("&nbsp;").prepend($(this));
  });
  
  $(".cmdAppend").each(function() {
    $(this).prev().find(".gridFooter:first td:last").append("&nbsp;").append($(this));
  });
  
  // BACKOFFICE: CONFERME CANCELLAZIONI
  $("input[@type=image]").each(function() {
    var alt = $(this).attr("alt") || "";
    
    if (alt.toLowerCase().indexOf("delete") >= 0) {
      var ev = this.onclick;
      this.onclick = null;
      
			$(this).click(function() {
			  if (confirm("Delete this item?")) {
			    ev();
			  } else {
			    return false;
			  }
			});
    }
  });
});

function bodyLoad() {
  setTimeout(function() {
    $(".autoPopup").each(function() {
      $(this).find(".thickbox").click();
    });
  }, 500);
}


function arsFileBrowser(field_name, url, type, win) {
  mcefld = win.document.getElementById(field_name);
  
  // alert("Field_Name: " + field_name + "\nURL: " + url + "\nType: " + type + "\nWin: " + win); // debug/testing

  /* var cmsURL = window.location.pathname;      // script URL
  var searchString = window.location.search;  // possible parameters
  if (searchString.length < 1) {
      // add "?" to the URL to include parameters (in other words: create a search string because there wasn't one before)
      searchString = "?";
  } */

  // newer writing style of the TinyMCE developers for tinyMCE.openWindow

  tinyMCE.openWindow({
      // file : cmsURL + searchString + "&type=" + type, // PHP session ID is now included if there is one at all
      file : "../../../filebrowser.aspx?caller=mce&filter="+type,
      title : "File Browser",
      width : 660,
      height : 520,
      close_previous : "no"
  }, {
      window : win,
      input : field_name,
      resizable : "yes",
      inline : "yes",  // This parameter only has an effect if you use the inlinepopups plugin!
      editor_id : tinyMCE.getWindowArg("editor_id")
  });

  return false;
}

function openPopup()
{

Page=arguments[0];
Name=arguments[1];
w=parseInt(arguments[2]);
h=parseInt(arguments[3]);

          if (arguments.length>4)
             sb=arguments[4];
         else
                 sb='yes';

          if (arguments.length>5)
             rsz=arguments[5];
         else
                 rsz='yes';

      mywidth = w;
      myheight = h;
      x = (screen.width - mywidth)/2;
      y = (screen.height - myheight)/2;
      newwin = window.open(Page, Name, "scrollbars=" + sb + ",resizable=" + rsz + ",left="+x+",top="+y+",width=" + w + ",height=" + h );
      newwin.creator=self;
}