﻿var Basket = {
  Init: function(container){
    this.container = $(container);
    this.renderBasket();
  },
  
  renderBasket: function(){
    new Ajax.Request('/Ajax/BasketAjax.ashx?m=getproducts', {
      onComplete:this.handleProducts.bindAsEventListener(this),
      onUninitialized: this.handleProductsError.bind(this),
      onFailure: this.handleProductsError.bind(this),
      onException: this.handleProductsError.bind(this)
    });
  },
  
  handleProductsError: function(){
    Event.observe(window, 'load',  function(){
      var elm = new Element('script', {'type': 'text/javascript', src: '/Ajax/BasketAjax.ashx?m=getproducts&ajaxDisabled=true&cache=' + new Date().getTime()});
      document.body.appendChild(elm);
      this.observeProductsAjaxComplete(elm);
    }.bind(this));
  },
  
  observeProductsAjaxComplete: function(elm){
    if(window.ajaxScriptResponse){
      var response = window.ajaxScriptResponse;
      window.ajaxScriptResponse = null;
      elm.remove();
      this.handleProducts({responseText: response}, true);
    }
    else{
      setTimeout(this.observeProductsAjaxComplete.bind(this, elm), 50);
    }
  },
  
  handleProducts: function(response, noEval){
    var list = noEval ? response.responseText : eval('(' + response.responseText + ')');
    this.setBasket(list);
  },
  
  setBasket: function(list){
    this.container.update();
    if(list.length > 0){
      for(var i = 0; i < list.length; i++){
        var obj = list[i];
        this.container.appendChild(this.getProductElm(obj.product, obj.quantity));
      }
      var hr = document.createElement('hr');
      hr.className = 'seperation';
      this.container.appendChild(hr);
      this.container.appendChild(this.getTotal(list));
      this.container.appendChild(this.getGotoImage());
    }
    else{
      this.renderNoProducts();
    }
  },
  
  getProductElm: function(obj, count){
    var table = document.createElement('table');
    table.cellPadding = '0';
    table.cellSpacing = '0';
    table.className = 'productWrapper';
    var tbody = document.createElement('tbody');
    var tr = document.createElement('tr');
    
    var nameCell = new Element('td', {'class': 'productCell'});
    var nameWrapper = new Element('div').setStyle({
      width: '120px',
      height: '16px',
      overflow: 'hidden'
    });  

    var link = document.createElement('a');
    link.className = 'product';
    if(obj.ManufacturerName != 'NULL'){
      link.href = '/p/' + obj.GroupName.replace(/\s/g, '_') + '/' + obj.ManufacturerName.replace(/\s/g,'_') + '/' + obj.Name.replace(/\s/g,'_') + '/' + obj.ID;
    }
    else{
      link.href = 'javascript:void(0);';
    }
    var nobreak = new Element('nobr');
    var textnode;
    if(obj.ManufacturerName != 'NULL'){
      textnode = document.createTextNode(obj.Name);
    }
    else{
      textnode = document.createTextNode(obj.Name);
    }
    nobreak.appendChild(textnode);
    link.appendChild(nobreak);
    nameWrapper.appendChild(link);
    
    nameCell.appendChild(nameWrapper);
    tr.appendChild(nameCell);
    
    var countCell = document.createElement('td');
    countCell.className = 'count';
    countCell.appendChild(document.createTextNode(count));
    tr.appendChild(countCell);
    
    tbody.appendChild(tr);
    table.appendChild(tbody);
    return table;
  },
  
  getTotal: function(list){
    var table = document.createElement('table');
    table.cellPadding = '0';
    table.cellSpacing = '0';
    table.className = 'subtotalTable';
    var tbody = document.createElement('tbody');
    var tr = document.createElement('tr');

    var totalCell = document.createElement('td');
    totalCell.className = 'subtotalLabel';
    totalCell.appendChild(document.createTextNode('Subtotal'));
    tr.appendChild(totalCell);
    
    var amountCell = document.createElement('td');
    amountCell.className = 'amount';
    amountCell.appendChild(document.createTextNode(this.getTotalAmount(list)));
    tr.appendChild(amountCell);

    tbody.appendChild(tr);
    table.appendChild(tbody);
    return table;
  },
  
  getTotalAmount: function(list){
    var totalamount = 0;
    for(var i = 0; i < list.length; i++){
      var amount = (list[i].price > 0) ? list[i].price : list[i].product.ListPrice;
      totalamount += amount * list[i].quantity;
    }
    return GlobalFunc.FormatPrice(totalamount, true);
  },
  
  getGotoImage: function(){
    var div = document.createElement('div');
    div.className = 'gotoWrapper';
    
    var link = document.createElement('a');
    link.title = 'Gå til kurven';
    link.href = '/Basket.aspx';
    var img = new Image();
    img.className = 'gotoImage';
    img.alt = 'Gå Til Kurv';
    img.rel = 'nofollow';
    img.src = '/gfx/button/gotobasket.jpg';
    link.appendChild(img);
    div.appendChild(link);
    
    return div;
  },
  
  renderNoProducts: function(){
    var div = document.createElement('div');
    div.className = 'noProducts';
    div.appendChild(document.createTextNode('Du har ingen varer i kurven'));
    this.container.appendChild(div);
  },
  
  AddProduct: function(productID){
    this.AddProducts(productID, 1);
//    new Ajax.Request('/Ajax/BasketAjax.ashx?m=addproduct&id=' + productID, {
//      onComplete:this.handleProductAdded.bindAsEventListener(this),
//      onUninitialized: this.handleAjaxError.bind(this),
//      onFailure: this.handleAjaxError.bind(this),
//      onException: this.handleAjaxError.bind(this)
//    });
  },
  
  AddProducts: function(productID, count){
    if(count > 0){
      new Ajax.Request('/Ajax/BasketAjax.ashx?m=addproduct&id=' + productID + '&count=' + count, {
        onComplete: this.handleProductAdded.bindAsEventListener(this),
        onUninitialized: this.handleAjaxError.bind(this, productID, count),
        onFailure: this.handleAjaxError.bind(this, productID, count),
        onException: this.handleAjaxError.bind(this, productID, count)
      });
    }
    else{
      alert('Du skal vælge et antal som du vil tilføje til kurven.');
    }
  },
  
  handleAjaxError: function(productID, count){
    var elm = new Element('script', {'type': 'text/javascript', src: '/Ajax/BasketAjax.ashx?m=addproduct&ajaxDisabled=true&id=' + productID + '&count=' + count + '&cache=' + new Date().getTime()});
    document.body.appendChild(elm);
    this.observeAjaxComplete(elm);
  },
  
  observeAjaxComplete: function(elm){
    if(window.ajaxScriptResponse){
      var response = window.ajaxScriptResponse;
      window.ajaxScriptResponse = null;
      elm.remove();
      this.handleProductAdded({responseText: response}, true);
    }
    else{
      setTimeout(this.observeAjaxComplete.bind(this, elm), 50);
    }
  },
  
  handleProductAdded: function(response, noEval){
    var list = noEval ? response.responseText : eval('(' + response.responseText + ')');
    this.setBasket(list);
    var elm = $('basketAddedBox');
    var docDim = document.viewport.getDimensions();
    var scrollPos = document.viewport.getScrollOffsets();
    var pos = {
      x: Math.floor((docDim.width / 2) + scrollPos.left - (elm.getWidth() / 2)),
      y: Math.floor((docDim.height / 2) + scrollPos.top - (elm.getHeight() / 2))
    };
    try{
      pos.x = pos.x - ((window.innerWidth - document.body.getWidth()) / 2);
    }catch(e){}
    $('basketAddedBox').setStyle({
      position: 'absolute',
      top: pos.y + 'px',
      left: pos.x + 'px'
    });
    Effect.Appear('basketAddedBox');
  }
};