var Shop = new Class({
  cart: false,
  startPos: false,
  
  initialize: function()
  {
    window.addEvent("scroll", this.positionCart.bind(this));
  },

  showFull: function (id)
  {
    if (googleTracking) {
      var elementName = "item_"+id.substring(11); 
      var name = $(elementName).value;
      pageTracker._trackEvent("readmore",name);
    }

    var parentElement = $(id).getParent();
    parentElement.innerHTML = $(id).innerHTML;
  },

  positionCart: function ()
  {
    if (!$("shopBlock")) return false;
    var elPos = $("shopBlock").getPosition();
    if (!this.startPos) this.startPos = elPos.y;
    var scrollPos = window.getScrollTop();
    var menuPos = $("cardTop").getPosition();
    var y = scrollPos;

    if (y < this.startPos) y = this.startPos;
    $("shopBlock").setStyle("top",y+"px");
  },
  
  itemSelect: function(itemId, over)
  {
    var elements = $ES(".itemId"+itemId);
    
    elements.each(function(element) {
      if (over) 
        element.addClass("hover");
      else
        element.removeClass("hover");
        element.removeClass("selected");
    });
  },
  
  itemDown: function(itemId, down)
  {
    var elements = $ES(".itemId"+itemId);
    
    elements.each(function(element) {
      if (down) 
        element.addClass("selected");
      else
        element.removeClass("selected");
    });
  },
  
  buttonSelect: function(className, over)
  {
    var elements = $ES("."+className);
    
    elements.each(function(element) {
      if (over) 
        element.addClass("hover");
      else
        element.removeClass("hover");
    });
  },
  
  getCart: function ()
  {
    var url = "/verhuur/winkelwagen.html";
    var json = new Json.Remote( url, {
      onComplete: function (data) {
        if (data) shop.updateCart(data.cart);
      },
      method: "POST"
    });
    
    json.send({"action": "cart"});
  },
  
  toCart: function (itemId)
  {
    if (googleTracking) {
      var elementName = "item_"+itemId;
      var name = $(elementName).value;
      pageTracker._trackEvent("winkelwagen",name);
    }

    var url = "/verhuur/winkelwagen.html";
    var json = new Json.Remote( url, {
      onComplete: function (data) {
        if (data) {
          shop.updateCart(data.cart);
          if (googleTracking) {
            var pageTracker = _gat._getTracker("UA-5170062-1");
            pageTracker._trackPageview("/verhuur/to_cart/"+itemId);
          } 
          alert("Het product ligt in de winkelwagen. (Zie links onderin)");
        } else {
          shop.updateCart([]);
        }
      },
      method: "POST"
    });

  
    
    $("shopBlock").getElements("td").each(function(cell) {
      if (cell.getStyle("background-color") == "#38635c") {
        var times = 0;
        var fx = new Fx.Style(cell, 'background-color',{
          duration: 200,
          onComplete: function() {
            if (times < 1) fx.start("#ffffff","#38635C");
            times++;
          }
        });
        fx.start("#38635C","#ffffff");
      }

      if (cell.getStyle("background-color") == "#133736") {
        var times = 0;
        var fx = new Fx.Style(cell, 'background-color',{
          duration: 200,
          onComplete: function() {
            if (times < 1) fx.start("#aaaaaa","#133736");
            times++;
          }
        });
        fx.start("#133736","#aaaaaa");
      }
    });
    json.send({"action": "save", "id": itemId});
  },
  
  fromCart: function (itemId)
  {
    var url = "/verhuur/winkelwagen.html";
    var json = new Json.Remote( url, {
      onComplete: function (data) {
        if (data) {
          shop.updateCart(data.cart);
        } else {
          shop.updateCart([]);
        }
      },
      method: "POST"
    });
    
    json.send({"action": "delete", "id": itemId});
  },
  
  updateCart: function (cart)
  {
    this.cart = cart;
    if ($("shopOrderTotal")) this.updatePrice();
    if (!$("shopOrderButton")) return;
    var buffer = "<table>";
    var items = 0;
    var add = "";
    for (var i in cart) {
      if (typeof(cart[i]) == "function") continue;
      items+=cart[i].amount;
      buffer += "<tr><td width='20'><span class='amount'>"+cart[i].amount+"x</span></td>" +
                "<td width='82'><a href='"+cart[i].url+"' class='name'>"+cart[i].name+"</a></td>" +
                "<td width='13' class='deleteCartCell'>" +
                "<a href='javascript:shop.fromCart(\""+i+"\");' class='deleteCart'>&nbsp;&nbsp;&nbsp;&nbsp;</a>" +
                "</td></tr>";
                
//                <img src='/skins/fragma/icons/shopdelete.gif' onclick='shop.fromCart(\""+i+"\");' class='icon' /></td></tr>";
                /*
      buffer += "<li><span class='amount'>"+cart[i].amount+"x</span> "+
                "<a href='javascript:shop.fromCart(\""+i+"\");' class='name'>"+cart[i].name+"</a>" +
                "<img src='/skins/fragma/icons/delete.gif' onclick='shop.fromCart(\""+i+"\");' class='icon' /></li>";
                */
    }
    buffer += "</table>";
    if (items > 1) {
      buffer += "<span class='info'>Er liggen "+items+" producten in uw winkelwagen</span>";
      $("shopOrderButton").removeClass("disabled");
    } else if (items == 1) {
      buffer += "<span class='info'>Er ligt "+items+" product in uw winkelwagen</span>";
      $("shopOrderButton").removeClass("disabled");
    } else if (items == 0) {
      buffer = "Winkelwagen is leeg";
      $("shopOrderButton").addClass("disabled");
    }
    $("shopCartBlock").innerHTML = buffer;
  },
  
  order: function()
  {
    document.location.href = "/verhuur/winkelwagen.html";
  },
  
  updatePrice: function (itemId, price, add)
  {
    if (itemId) {
      var amountEl = $("amount["+itemId+"]");
      var totalEl = $("itemTotal["+itemId+"]");
      if (!amountEl || !totalEl) return false;
      var amount = parseInt(amountEl.innerHTML);
  
      amount += add;
      
      if (isNaN(amount)) amount = 0;
      if (amount < 0) amount = 0;
      if (amount > 99) amount = 99;
      this.updateAmount(itemId, amount);
      amountEl.innerHTML = amount;
      totalEl.innerHTML = "&euro; "+ this.formatPrice(parseFloat(price)*amount, true);
      $("inputAmount["+itemId+"]").value = amount;

      if (amount == 0) this.hideItem(itemId);
    }
        
    var grandTotal = 0;
    var cart = this.cart;
    for (var i in cart) {
      if (typeof(cart[i]) == "function") continue;
      if (itemId && i == itemId) 
        grandTotal+=amount*cart[i].price;
      else {
        var itemAmount = $("amount["+i+"]").innerHTML;
        itemAmount = parseInt(itemAmount);
        grandTotal+=itemAmount*cart[i].price;
      }
    }
    var discount = 0;
    if (grandTotal > 150) discount = 2.5;
    if (grandTotal > 300) discount = 5;
    if (grandTotal > 450) discount = 7.5;
    if (grandTotal > 600) discount = 10;
    if (grandTotal > 750) discount = 12.5;
    if (grandTotal > 1000) discount = 15;
    
    $("grandTotalExcl").innerHTML = this.formatPrice(grandTotal);
    if (discount > 0) {
      $("grandDiscountExclRow").setStyle("display", "");
      $("totalDiscountPercentage").innerHTML = discount;
      $("grandDiscountExcl").innerHTML = this.formatPrice(grandTotal*((100-discount)/100));
      grandTotal = grandTotal*((100-discount)/100);
    } else {
      $("grandDiscountExclRow").setStyle("display", "none");
    }
    $("grandTotalBTW").innerHTML = this.formatPrice(parseFloat(grandTotal*0.19));
    $("grandTotalIncl").innerHTML = this.formatPrice(parseFloat(grandTotal+grandTotal*0.19));
  },
  
  formatPrice: function (price, roundEuro)
  {
    price += "";
    var priceSplitted = price.split(".");
    if (!priceSplitted[0]) priceSplitted[0] = 0;
    if (!priceSplitted[1]) priceSplitted[1] = (roundEuro == true?"-":"00");
    else while (priceSplitted[1].length < 2) priceSplitted[1] += "0";

    if (priceSplitted[1].length > 2) priceSplitted[1] = priceSplitted[1].substring(0,2);
    
    return priceSplitted[0]+"."+priceSplitted[1];
  },
  
  hideItem: function (itemId)
  {
    var itemSize = $("shopItem_"+itemId).getSize();
    $("shopItem_"+itemId).setStyle("overflow", "hidden");
    var hideFx = new Fx.Slide("shopItem_"+itemId, {duration: 500});
    hideFx.slideOut(); //hmmstart(itemSize.size.y,0);
  },
  
  updateAmount: function (itemId, amount)
  {
    var url = "/verhuur/winkelwagen.html";
    var json = new Json.Remote( url, {
      onComplete: function (data) { },
      method: "POST"
    });
    
    json.send({"action": "update", "id": itemId, "amount": amount});
  },
  
  typeChange: function ( )
  {
    if ($("orderPickup").checked) {
      $("orderPickupOptions").setStyle("display", "");
      $("orderBringOptions").setStyle("display", "none");
    } else if ($("orderBring").checked) {
      $("orderBringOptions").setStyle("display", "");
      $("orderPickupOptions").setStyle("display", "none");
    } else {
      $("orderPickupOptions").setStyle("display", "none");
      $("orderBringOptions").setStyle("display", "none");
    }
  },
    
  validateForm: function()
  {
    var form = $("bestelForm");
    var result = true;
    
    for (var i = 0; i < form.elements.length; i++) {
      if (form.elements[i].id.substring(0,5) != "order") continue;
      var element = $(form.elements[i].id);
      
      if (element.hasClass("required")) {
        var valid = true;
        
        if (element.value.length <= 0) valid = false;
        switch (element.name) {
          case "email":
            if (!element.value.contains("@")) valid = false;
          break;
          default:
          break;
        }
        if (!valid) {
          element.addClass("error");
          result = false;
        } else {
          element.removeClass("error");
        }
      }
    }
    if (result) form.submit();
    return false;
  }
});

var shop;
var shopCallback = function() { 
  if (!shop) {
    shop = new Shop(); 
  }else { 
    shop.getCart();
    shop.positionCart();
  } 
};
window.addEvent('domready', shopCallback);
window.addEvent('load', shopCallback);

