﻿function swap(imageId) {
    if($(imageId).src.indexOf('/gfx/layout/checkbox_unchecked.gif')>-1) {
      checkImage(imageId);
    } 
    else {
      uncheckImage(imageId);
    }
}

function checkImage(id){
  $(id).src = "/gfx/layout/checkbox_checked.gif";
  $(id).alt = 'checked';
}
function uncheckImage(id){
  $(id).src = "/gfx/layout/checkbox_unchecked.gif";
  $(id).alt = 'unchecked';
}


window.dhtmlHistory.create({
  toJSON: function(o) {
    return Object.toJSON(o);
  },
  
  fromJSON: function(s) {
    return s.evalJSON(false);
  }
});

var dhtmlListener;
Event.observe(window, 'load', function(){
  dhtmlHistory.initialize();
  dhtmlHistory.addListener(HistoryListener);
});
function HistoryListener(loc, data){
  dhtmlListener(loc, data);
}



var ProductList = Class.create();
ProductList.prototype = {
  initialize: function(products, container, options){
    this.options = Object.extend({
      itemCount: 20,
      manufactorType: '',
      specialSelection: false
    }, options);
    this.orgProducts = products;
    this.container = $(container);
    
    dhtmlListener = this.historyChanged.bind(this);
    this.filterPage = 1;
    
    this.renderedProducts = new Array();
    this.currentProducts = this.orgProducts;
    this.setPageBar();
    
    this.filterObjs = new Hash();
    this.filterTypes = new Hash();
    
    this.itemWrapper = new Element('div');
    this.container.appendChild(this.itemWrapper);
    
//    if(window.location.hash && window.location.hash != ''){
//      this.setBottomPageBar();
//      this.filter(null, null, true);
//    }
//    else{
      this.renderProducts();
      this.setBottomPageBar();
    //}
  },
  
  historyChanged: function(loc, data){
    //Kig nærmere på dette: javascript:alert($H($H({1:[2]}).toJSON().evalJSON(false)).values());
    if(this.pageBar){
      var pfData = getHistoryValue('pf', loc, data);
      //alert(data[0] instanceof Hash);
//      alert($H(pfData).values().each);
//      alert($H(data[0]).values());
      //pfData.each(function(p){alert(p);});
      if(pfData){
        $$C('.checkboximage').each(function(elm){uncheckImage(elm);});
        if(data != null){
          var fData = $H(pfData); //$H(pfData); //$H(pfData.evalJSON(false)); //$H(pfData); //$H(data);
          fData.each(function(pair){
            pair.value.each(function(id){
              swap(id);
            });
          });
          this.filter(null, null, false, fData)
        }
        else{
          this.filter(null, null, false, new Hash())
        }
      }
    }
    var paNumber = getHistoryValue('pa', loc, data);
    if(paNumber){
      //this.pageBar.switchPage(null, loc.substr(2,1));
      this.pageBar.switchPage(null, paNumber);
    }
  },
  
  setPageBar: function(){
    this.pageBarOptions = options = {
      count: this.currentProducts.length,
      onPaging: this.handlePaging.bindAsEventListener(this),
      onSortClicked: this.handleSortClicked.bindAsEventListener(this)
    }
    this.pageBar = PageBarManager.CreatePageBar(this.container, this.pageBarOptions);
  },
  
  setBottomPageBar: function(){
    this.bottomPageBar = PageBarManager.CreatePageBar(this.container, Object.extend({enableSort:false}, options));
  },
  
  renderProducts: function(){
    this.removeProducts();
    var topBR = document.createElement('br')
    topBR.className = 'productDistanceTop';
    this.itemWrapper.appendChild(topBR);
    this.renderedProducts.add(topBR);
    var count = 0;
    for(var i = this.getStartIndex(); i < this.currentProducts.length && count < this.options.itemCount; i++){
      var obj = this.currentProducts[i];
      var product = new Product(obj);
      
      var domProduct = product.getProduct()
      this.renderedProducts.add(domProduct);
      this.itemWrapper.appendChild(domProduct);
      product.setImage();
      
      var br = document.createElement('br')
      br.className = 'productDistance';
      this.itemWrapper.appendChild(br);
      this.renderedProducts.add(br);
      count++;
    }
  },
  
  removeProducts: function(){
    for(var i = 0; i < this.renderedProducts.length; i++){
      this.itemWrapper.removeChild($(this.renderedProducts[i]));
    }
    this.renderedProducts = new Array();
  },
  
  getStartIndex: function(){
    return (this.pageBar.currentPage - 1) * this.options.itemCount;
  },
  
  handlePaging: function(page){
		ScrollToTop();
    this.renderProducts();
  },
  
  filter: function(detail, filter, useCookie, data){
    if(data){
      this.filterTypes = data;
    }
    else if(useCookie){
      this.filterTypes = $H(CookieManager.getObject('pl'));
      this.filterTypes.each(function(pair){
        pair.value.each(function(id){
          swap(id);
        });
      });
    }
    else if(filter){
      if(!this.filterTypes.get(detail.type)){
        this.filterTypes.set(detail.type, new Array());
      }
      this.filterTypes.get(detail.type).add(detail.id);
    }
    else{
      this.filterTypes.get(detail.type).remove(detail.id);
      var arr = this.filterTypes.get(detail.type);
      if(arr.length == 0){
        this.filterTypes.unset(detail.type);
      }
    }
    if(this.filterTypes.keys().length == 0){
      this.currentProducts = this.orgProducts;
      $$C('.detailRow').each(function(elm){ elm.show(); });
      $$C('.detailHeader').each(function(elm){ elm.show(); });
    }
    else{
      var selProducts = new Hash();
      var successCount = 0;
      
      var specielDetails = new Array();
      if(!this.options.specialSelection){
        $$C('.detailRow').each(function(elm){ elm.hide(); });
        $$C('.detailHeader').each(function(elm){ elm.hide(); });
      }
      else{
        $$C('.checkboximage').each( function(elm){ uncheckImage(elm); });
        this.filterTypes.each(function(pair){ 
          pair.value.each(function(elm){
            specielDetails.add(elm);
            checkImage(elm)
          });
        });
        if(filter){
          checkImage(detail.id);
        }
      }

      for(var i = 0; i < this.orgProducts.length; i++){
        var prod = this.orgProducts[i];
        if(this.options.specialSelection){
          for(var ii = 0; ii < specielDetails.length; ii++){
            var sDetail = specielDetails[ii];
            for(var iii = 0; iii < prod.Details.length; iii++){
              var prodDetail = prod.Details[iii];
              if(prodDetail.id == sDetail){
                successCount++;
                break;
              }
            }
          }
        }
        else{
          for(var ii = 0; ii < this.filterTypes.values().length; ii++){
            var typeArr = this.filterTypes.values()[ii];
            for(var iii = 0; iii < prod.Details.length; iii++){
              var prodDetail = prod.Details[iii];
              if(typeArr.contains(prodDetail.id)){
                successCount++;
                break;
              }
            }
          }
        }
        if(this.options.specialSelection && successCount > 0){
          selProducts.set(prod.ID, prod);
        }
        else if(successCount == this.filterTypes.values().length){
          selProducts.set(prod.ID, prod);
          prod.Details.each(function(obj){
            $('r' + obj.id).show(); 
            $('dh' + obj.typeID).show();
//            if(obj.typeID != detail.type){
//              checkImage(obj.id);
//            }
          });
        }
        successCount = 0;
      }
      this.currentProducts = selProducts.values();
    }
    
    this.pageBar.reset(this.currentProducts.length);
    this.renderProducts();
    this.bottomPageBar.reset(this.currentProducts.length);
    CookieManager.set('pl', this.filterTypes);
    if(!data){
//    alert(this.filterTypes.toJSON() + ', ' + this.filterTypes.keys().length);
      //dhtmlHistory.add('p' + this.filterPage, this.filterTypes.toJSON().evalJSON());// Object.clone(this.filterTypes));
      setHistory('pf', this.filterPage, this.filterTypes);
      this.filterPage++;
    }
    //window.location.hash = 'uc';
  },
  
  handleSortClicked: function(sort){
    switch(sort){
      case 'manufactur':
        this.orgProducts.sort(this.manufacturSort);
        this.currentProducts.sort(this.manufacturSort);
        break;
      case 'topprice':
        this.orgProducts.sort(this.priceSort);
        this.currentProducts.sort(this.priceSort);
        break;
      case 'lowprice':
        this.orgProducts.sort(this.reversePriceSort);
        this.currentProducts.sort(this.reversePriceSort);
        break;
    }
    this.pageBar.reset();
    //this.orgProducts.sort(this.manufacturSort);
    this.renderProducts();
  },
  
  manufacturSort: function(a,b){
    return a.ManufacturerName > b.ManufacturerName ? 1 : a.ManufacturerName < b.ManufacturerName ? -1 : a.Name > b.Name ? 1 : a.Name < b.Name ? -1 : 0;
  },
  
  priceSort: function(a,b){
    if(a.Price > 0){
      if(b.Price > 0){
        return (a.Price > b.Price) ? -1 : (b.Price > a.Price) ? 1 : 0;
      }
      else{
        return (a.Price > b.ListPrice) ? -1 : (b.ListPrice > a.Price) ? 1 : 0;
      }
    }
    else{
      if(b.Price > 0){
        return (a.ListPrice > b.Price) ? -1 : (b.Price > a.ListPrice) ? 1 : 0;
      }
      else{
        return (a.ListPrice > b.ListPrice) ? -1 : (b.ListPrice > a.ListPrice) ? 1 : 0;
      }
    }
  },
  
  reversePriceSort: function(a,b){
    if(a.Price > 0){
      if(b.Price > 0){
        return (a.Price > b.Price) ? 1 : (b.Price > a.Price) ? -1 : 0;
      }
      else{
        return (a.Price > b.ListPrice) ? 1 : (b.ListPrice > a.Price) ? -1 : 0;
      }
    }
    else{
      if(b.Price > 0){
        return (a.ListPrice > b.Price) ? 1 : (b.Price > a.ListPrice) ? -1 : 0;
      }
      else{
        return (a.ListPrice > b.ListPrice) ? 1 : (b.ListPrice > a.ListPrice) ? -1 : 0;
      }
    }
  }
}

var Product = Class.create();
Product.prototype = {
    initialize: function(obj) {
        this.obj = obj;
    },

    getProduct: function() {
        var wrapper = document.createElement('div');
        wrapper.className = 'productWrapper';

        var table = document.createElement('table');
        table.className = 'productTable';
        table.setAttribute('cellPadding', '0');
        table.setAttribute('cellSpacing', '0');
        var tbody = document.createElement('tbody');
        tbody.appendChild(this.getTopRow());
        table.appendChild(tbody);
        wrapper.appendChild(table);

        if (this.obj.Awards.length > 0) {
            table = document.createElement('table');
            table.className = 'productTable';
            table.setAttribute('cellPadding', '0');
            table.setAttribute('cellSpacing', '0');
            tbody = document.createElement('tbody');
            tbody.appendChild(this.getAwardsRow());
            table.appendChild(tbody);
            wrapper.appendChild(table);
        }

        table = document.createElement('table');
        table.className = 'productTable';
        table.setAttribute('cellPadding', '0');
        table.setAttribute('cellSpacing', '0');
        tbody = document.createElement('tbody');
        tbody.appendChild(this.getBottomRow());
        table.appendChild(tbody);
        wrapper.appendChild(table);


        //var bargainText = this.obj.bargain ? ' (Priskup)' : '';
        var infoBox = new InfoBox('<a href="' + 'p'.toValidUrl(this.obj.GroupName, this.obj.ManufacturerName, this.obj.Name, this.obj.ID) + '" style="color:#FFFFFF;text-decoration:none;font-weight:bold;">' + this.obj.ManufacturerName + ' - ' + this.obj.Name + '</a>', wrapper);
        //var infoBox = new InfoBox(this.obj.ManufacturerName + ' - ' + this.obj.Name + bargainText, wrapper);

        return infoBox.getInfoBox();
    },

    getTopRow: function() {
        var tr = document.createElement('tr');

        tr.appendChild(this.getStatsCell());
        tr.appendChild(this.getImageCell());

        return tr;

    },

    getStatsCell: function() {
        var statsCell = new Element('td');
        statsCell.className = 'statsCell';
        for (var i = 0; i < this.obj.Details.length; i++) {
            var detail = this.obj.Details[i];
            if (detail.visible) {
                var wrapper = new Element('div');
                var type = new Element('span', { 'class': 'detailType' });
                type.appendChild(document.createTextNode(detail.type + ":"));
                wrapper.appendChild(type);
                wrapper.appendChild(document.createTextNode(' '));
                var value = new Element('span', { 'class': 'detailValue' });
                value.appendChild(document.createTextNode(detail.value));
                wrapper.appendChild(value);
                statsCell.appendChild(wrapper);
            }
        }
        statsCell.appendChild(this.getBottomText());
        return statsCell;
    },

    getImageCell: function() {
        var imageCell = document.createElement('td');
        imageCell.className = 'imageCell';
        this.image = new Element('img'); //new Image();
        this.image.observe('click', this.imageClicked.bind(this));
        this.image.className = 'productImage cursorHand';
        this.image.src = '/ProductImage.ashx?id=' + this.obj.ImageID + '&w=140&h=250&m=1&nocache=' + new Date().getTime();
        if (Prototype.Browser.IE6) {
            setTimeout(this.setImage.bind(this), 500);
        }
        imageCell.appendChild(this.image);
        return imageCell;
    },

    imageClicked: function() {
        location.href = 'p'.toValidUrl(this.obj.GroupName + '-' + this.obj.ManufacturerName + '-' + this.obj.Name, this.obj.ID);
        //location.href = '/p/' + this.obj.GroupName.replace(/\s/g, '_') + '/' + this.obj.ManufacturerName.replace(/\s/g, '_') + '/' + this.obj.Name.replace(/\s/g, '_').replace('+', '') + '/' + this.obj.ID;
    },

    setImage: function() {
        if (this.obj.GotImage) {
            this.image.src = '/ProductImage.ashx?id=' + this.obj.ImageID + '&w=140&h=250&m=1&nocache=' + new Date().getTime();
        }
    },

    getAwardsRow: function() {
        var tr = new Element('tr');
        var td = new Element('td', { 'cellspan': '2' });
        td.className = 'awardsCell';
        for (var i = 0; i < this.obj.Awards.length; i++) {
            var award = this.obj.Awards[i];
            var awardLink = new Element('a', {
                href: award.url,
                target: '_blank',
                title: award.name
            }).setStyle({ marginLeft: '10px' });
            var awardIcon = new Element('img', { src: '/AwardImage.ashx?id=' + award.id + '&w=75' }).setStyle({ width: '75px', borderWidth: '0px' });
            awardLink.appendChild(awardIcon);
            td.appendChild(awardLink);
        }
        tr.appendChild(td);
        return tr;
    },

    getBottomRow: function() {
        var tr = document.createElement('tr');
        tr.className = 'bottomRow';
        tr.appendChild(this.getPriceCell());
        tr.appendChild(this.getOrderCell());
        return tr;
    },

    getOrderCell: function() {
        var td = document.createElement('td');
        td.className = 'priceCell';

        var table = document.createElement('table');
        table.className = 'priceTable';
        table.cellPadding = '0';
        table.cellSpacing = '0';
        table.align = 'right';
        var tbody = document.createElement('tbody');

        if (this.obj.Price > 0) {
            var bottomRow = document.createElement('tr');
            var bargain = new Element('td');
            bargain.className = 'bargainPrice';
            bargain.appendChild(document.createTextNode(GlobalFunc.FormatPrice(this.obj.Price, true)));
            bottomRow.appendChild(bargain);
            tbody.appendChild(bottomRow);
        }

        //if (this.obj.ListPrice != this.obj.Price) {
        //    var tr = document.createElement('tr');
        //    var normal = new Element('td', { 'nowrap': 'nowrap' });
        //    normal.className = 'normalPrice';
        //    normal.appendChild(document.createTextNode('Vejledende ' + GlobalFunc.FormatPrice(this.obj.ListPrice, true)));
        //    tr.appendChild(normal);
        //    tbody.appendChild(tr);
        //}

        table.appendChild(tbody);
        td.appendChild(table);
        return td;
    },


    getOrderCell: function() {
        var td = document.createElement('td');
        td.className = 'orderCell';

        var img1Link = new Element('a', { title: 'Læs mere om produktet', href: 'p'.toValidUrl(this.obj.GroupName + '-' + this.obj.ManufacturerName + '-' + this.obj.Name, this.obj.ID) });
        var img1 = new Element('img', { 'class': 'orderImage cursorHand', src: '/gfx/button/readmore_productlist.jpg' }).setStyle({ borderWidth: '0px' });
        //    img1.className = 'orderImage cursorHand';
        //    img1.useMap = '#imagemap' + this.obj.ID;
        //    img1.src = '/gfx/button/readmore_productlist.jpg';
        img1Link.appendChild(img1);

        td.appendChild(img1Link);

        var imgLink = new Element('a', { href: 'javascript:void(0);' });
        var img = new Element('img', { 'class': 'orderImage cursorHand', src: '/gfx/button/addtocart_productlist.jpg' }).setStyle({ borderWidth: '0px' });
        //    img.className = 'orderImage cursorHand';
        //    img.useMap = '#imagemap' + this.obj.ID;
        //    img.src = '/gfx/button/addtocart_productlist.jpg';
        imgLink.observe('click', this.orderClicked.bindAsEventListener(this));
        imgLink.appendChild(img);

        td.appendChild(imgLink);

        var map = document.createElement('map');
        map.id = 'imagemap' + this.obj.ID;
        map.name = 'imagemap' + this.obj.ID;

        //    var readArea = document.createElement('area');
        //    readArea.href = 'p'.toValidUrl(this.obj.GroupName, this.obj.ManufacturerName, this.obj.Name, this.obj.ID)
        //    readArea.shape = 'rect';
        //    readArea.coords = '0,0,80,30';
        //    readArea.alt = 'Læs mere om produktet';
        //    map.appendChild(readArea);

        //    var orderArea = document.createElement('area');
        //    orderArea.href = 'javascript:void(0);';
        //    Event.observe(orderArea, 'click', this.orderClicked.bindAsEventListener(this));
        //    orderArea.shape = 'rect';
        //    orderArea.coords = '81,0,189,30';
        //    orderArea.alt = 'Læg i kurven';
        //    map.appendChild(orderArea);

        //    td.appendChild(map);

        return td;
    },

    orderClicked: function() {
        Basket.AddProduct(this.obj.ID);
    },

    imageClickedRead: function() {
        location.href = 'p'.toValidUrl(this.obj.GroupName + '-' + this.obj.ManufacturerName + '-' + this.obj.Name, this.obj.ID);
        //location.href = '/p/' + this.obj.GroupName.replace(/\s/g, '_') + '/' + this.obj.ManufacturerName.replace(/\s/g, '_') + '/' + this.obj.Name.replace(/\s/g, '_').replace('+', '') + '/' + this.obj.ID;
    },

    getPriceCell: function() {
        var td = document.createElement('td');
        td.className = 'priceCell';

        var table = document.createElement('table');
        table.className = 'priceTable';
        table.cellPadding = '0';
        table.cellSpacing = '0';
        table.align = 'right';
        var tbody = new Element('tbody');

        if (this.obj.bargain) {
            tbody.insert(
        new Element('tr').insert(
          new Element('td', { 'class': 'bargainNotice' }).update('ET GODT KØB')
        )
      );
        }

        if (this.obj.Price > 0) {
            var bottomRow = document.createElement('tr');
            var bargain = new Element('td');
            bargain.className = 'bargainPrice';
            bargain.appendChild(document.createTextNode(GlobalFunc.FormatPrice(this.obj.Price, true)));
            bottomRow.appendChild(bargain);
            tbody.appendChild(bottomRow);
        }

        //if (this.obj.ListPrice != this.obj.Price) {
        //    var tr = document.createElement('tr');
        //    var normal = new Element('td', { 'nowrap': 'nowrap' });
        //    normal.className = 'normalPrice';
        //    normal.appendChild(document.createTextNode('Vejledende ' + GlobalFunc.FormatPrice(this.obj.ListPrice, true)));
        //    tr.appendChild(normal);
        //    tbody.appendChild(tr);
        //}
        table.appendChild(tbody);
        td.appendChild(table);
        return td;
    },

    getBottomText: function() {
        var div = document.createElement('div');
        div.className = 'bottomText';
        if (this.obj.deliveryTime.to == 1 || this.obj.stock > 0) {
            if (this.obj.stockamount == 1) {
                div.appendChild(Element('img', { 'alt': '1 stk på eget lager!', 'style': 'Float:left;', src: '/gfx/stock/one.jpg' }));
            }
            if (this.obj.stockamount == 2) {
                div.appendChild(Element('img', { 'alt': '2 stk på eget lager!', 'style': 'Float:left;', src: '/gfx/stock/two.jpg' }));
            }
            if (this.obj.stockamount == 3) {
                div.appendChild(Element('img', { 'alt': '3 stk på eget lager!', 'style': 'Float:left;', src: '/gfx/stock/three.jpg' }));
            }
            if (this.obj.stockamount == 4) {
                div.appendChild(Element('img', { 'alt': '4 stk på eget lager!', 'style': 'Float:left;', src: '/gfx/stock/four.jpg' }));
            }
            if (this.obj.stockamount == 5) {
                div.appendChild(Element('img', { 'alt': '5 stk på eget lager!', 'style': 'Float:left;', src: '/gfx/stock/five.jpg' }));
            }
            if (this.obj.stockamount > 5) {
                div.appendChild(Element('img', { 'alt': 'Mere end 5 stk på eget lager!', 'style': 'Float:left;', src: '/gfx/stock/fiveplus.jpg' }));
            }
            div.appendChild(document.createTextNode('Bestil i dag inden 15:00 og få dette produkt leveret til døren imorgen...'));
        }
        else if (this.obj.longBackorder) {
            div.appendChild(Element('img', { 'alt': 'Restordre!', 'style': 'Float:left;', src: '/gfx/stock/soldout.jpg' }));
            div.appendChild(document.createTextNode('Forventet levering: Ukendt, Kontakt salg for nærmere info.'));
        }
        else if (this.obj.backorder) {
            div.appendChild(Element('img', { 'alt': 'Restordre!', 'style': 'Float:left;', src: '/gfx/stock/soldout.jpg' }));
            div.appendChild(document.createTextNode('Forventet levering ' + this.obj.deliveryTime.from + '-' + this.obj.deliveryTime.to + ' dage, Bemærk dette produkt er i restordre, leveringstiden kan svinge både frem og tilbage. Kontakt salg for nærmere info'));
        }
        else {
            div.appendChild(document.createTextNode('Forventet levering: ' + this.obj.deliveryTime.from + '-' + this.obj.deliveryTime.to + ' dage'));
        }
        return div;
    }
}

var PageBarManager = {
  CreatePageBar: function(container, options){
    var pageBar = new PageBar(container, options);
    this.entries.add(pageBar);
    return pageBar;
  },
  
  RenderPageBars: function(trigger){
    this.entries.each(function(pagebar){
      if(pagebar != trigger){
        pagebar.currentPage = trigger.currentPage;
        pagebar.renderPageBar();
      }
    });
  }
}
PageBarManager.entries = new Array();

var PageBar = Class.create();
PageBar.prototype = {
  initialize: function(container, options){
    this.options = Object.extend({
      count: 0,
      pageCount: 20,
      visiblePageCount: 9,
      enableSort: true,
      onPaging: Prototype.emptyFunction,
      onSortClicked: Prototype.emptyFunction
    }, options);
    this.container = $(container);
    this.setStats();
    
    this.boxWrapper = new Element('div');
    this.container.appendChild(this.boxWrapper);
    
    this.renderPageBar();
  },
  
  setStats: function(){
    this.currentPage = 1;
    this.totalPageCount = Math.floor(this.options.count / this.options.pageCount);
    if(this.options.count % this.options.pageCount > 0){
      this.totalPageCount++;
    }
    this.staticListener = {
      manufacturClick: this.sort.bindAsEventListener(this, 'manufactur'),
      topPriceClick: this.sort.bindAsEventListener(this, 'topprice'),
      lowPriceClick: this.sort.bindAsEventListener(this, 'lowprice'),
      forwardClick: this.goForward.bindAsEventListener(this),
      backClick: this.goBack.bindAsEventListener(this)
    }
  },
  
  renderPageBar: function(){
    try{
    if(!GlobalFunc.IsNull(this.box) && this.boxRemoved != true){
      $(this.box).remove();
      this.boxRemoved = true;
    }
    }
    catch(e){}
    this.box = document.createElement('div');
    this.box.className = this.options.enableSort ? 'pagingBox' : 'pagingBox noTopPadding';
    
    if(this.options.enableSort){
      var topTable = this.getTopTable();
      this.box.appendChild(topTable);
    }
    
    if(this.totalPageCount > 1){
      var bottomTable = this.getBottomTable();
      this.box.appendChild(bottomTable);
    }
    
    if(this.options.enableSort || this.totalPageCount > 1){
      this.boxWrapper.appendChild(this.box);
      this.boxRemoved = false;
    }
  },
  
  getTopTable: function(){
    var table = document.createElement('table');
    table.className = 'topTable';
    var tbody = document.createElement('tbody');
    var tr = document.createElement('tr');
    
    var firstCell = document.createElement('td');
    firstCell.className = 'pageLabel';
    firstCell.appendChild(document.createTextNode('Side ' + this.currentPage + ' af ' + this.totalPageCount));
    tr.appendChild(firstCell);
    
    var lastCell = document.createElement('td');
    lastCell.align = 'right';
    lastCell.className = 'sortOptions';
    lastCell.appendChild(this.getSortOptions());
    tr.appendChild(lastCell);
    
    tbody.appendChild(tr);
    table.appendChild(tbody);
    return table;
  },
  
  getSortOptions: function(){
    var wrapper = document.createElement('div');
    
    var title = document.createElement('span');
    title.className = 'title';
    title.appendChild(document.createTextNode('Sortering: '));
    wrapper.appendChild(title);
    
    var manufactur = document.createElement('a');
    manufactur.className = 'option';
    manufactur.appendChild(document.createTextNode('Producent'));
    manufactur.href = 'javascript:void(0);';
    Event.observe(manufactur, 'click', this.staticListener.manufacturClick);
    wrapper.appendChild(manufactur);
    wrapper.appendChild(document.createTextNode(' - '));
    
    var topPrice = document.createElement('a');
    topPrice.className = 'option';
    topPrice.appendChild(document.createTextNode('Højeste pris'));
    topPrice.href = 'javascript:void(0);';
    Event.observe(topPrice, 'click', this.staticListener.topPriceClick);
    wrapper.appendChild(topPrice);
    wrapper.appendChild(document.createTextNode(' - '));
    
    var lowPrice = document.createElement('a');
    lowPrice.className = 'option';
    lowPrice.appendChild(document.createTextNode('Laveste pris'));
    lowPrice.href = 'javascript:void(0);';
    Event.observe(lowPrice, 'click', this.staticListener.lowPriceClick);
    wrapper.appendChild(lowPrice);
    
    return wrapper;
  },
  
  getBottomTable: function(){
    var table = document.createElement('table');
    table.className = 'bottomTable';
    var tbody = document.createElement('tbody');
    var tr = document.createElement('tr');
    
    var firstCell = document.createElement('td');
    firstCell.align = 'left';
    firstCell.className = 'previous';
    firstCell.appendChild(this.getPreviousAnchor());
    tr.appendChild(firstCell);
    
    var middleCell = document.createElement('td');
    middleCell.align = 'center';
    middleCell.className = 'pageCount';
    middleCell.appendChild(this.getPageNumbers());
    tr.appendChild(middleCell);
    
    var lastCell = document.createElement('td');
    lastCell.align = 'right';
    lastCell.className = 'next';
    lastCell.appendChild(this.getNextAnchor());
    tr.appendChild(lastCell);
   
    tbody.appendChild(tr);
    table.appendChild(tbody);
    return table;
  },
  
  getPreviousAnchor: function(){
    if(this.currentPage > 1){
      var anchor = document.createElement('a');
      var nobreak = new Element('nobr');
      nobreak.appendChild(document.createTextNode('Forrige side'));
      anchor.appendChild(nobreak);
      anchor.href = 'javascript:void(0)';
      Event.observe(anchor, 'click', this.staticListener.backClick);
      return anchor;
    }
    else{
      return document.createTextNode(' ');
    }
  },
  
  getPageNumbers: function(){
    var wrapper = document.createElement('div');
    var start = 1;
    var middle = Math.ceil(this.options.visiblePageCount / 2);
    var end = this.totalPageCount;
    if(this.totalPageCount > this.options.visiblePageCount){
      if(middle >= this.currentPage){
        start = 1;
        end = (this.totalPageCount > this.options.visiblePageCount) ? this.options.visiblePageCount : this.totalPageCount;
      }
      else if(middle + this.currentPage > this.totalPageCount){
        start = this.totalPageCount - this.options.visiblePageCount + 1;
        end = this.totalPageCount;
      }
      else{
        start = this.currentPage - (middle - 1);
        end = this.currentPage + (middle - 1);
      }
    }
    var count = 1;
    for(var i = start; i <= end; i++){
      if(i != this.currentPage){
        var anchor = document.createElement('a');
        anchor.className = 'number';
        anchor.appendChild(document.createTextNode(i));
        anchor.href = 'javascript:void(0)';
        Event.observe(anchor, 'click', this.switchPage.bindAsEventListener(this, i));
        wrapper.appendChild(anchor);
      }
      else{
        var span = document.createElement('span');
        span.className = 'selPage';
        span.appendChild(document.createTextNode(i));
        wrapper.appendChild(span);
      }
      if (count < end) {
          wrapper.appendChild(document.createTextNode(' - '));
      }
      count++;
    }
    return wrapper;
  },
  
  getNextAnchor: function(){
    if(this.currentPage < this.totalPageCount){
      var anchor = document.createElement('a');
      var nobreak = new Element('nobr');
      nobreak.appendChild(document.createTextNode('Næste side'));
      anchor.appendChild(nobreak);
      anchor.href = 'javascript:void(0)';
      Event.observe(anchor, 'click', this.staticListener.forwardClick);
      return anchor;
    }
    else{
      return document.createTextNode(' ');
    }
  },
  
  reset: function(count){
    this.currentPage = 1;
    if(typeof count != 'undefined'){
      this.options.count = count;
      this.totalPageCount = Math.floor(this.options.count / this.options.pageCount);
      if(this.options.count % this.options.pageCount > 0){
        this.totalPageCount++;
      }
    }
    this.renderPageBar();
  },
  
  sort: function(e, type){
    this.options.onSortClicked(type);
  },
  
  goBack: function(){
    this.currentPage--;
    this.renderPageBar();
    this.invokeOnPaging();
  },
  
  switchPage: function(e, page){
    this.currentPage = page;
    this.renderPageBar();
    this.invokeOnPaging();
  },
  
  goForward: function(){
    this.currentPage++;
    this.renderPageBar();
    this.invokeOnPaging();
  },
  
  invokeOnPaging: function(){
    PageBarManager.RenderPageBars(this);
    this.options.onPaging(this.currentPage);
    //dhtmlHistory.add('pa' + this.currentPage, this.currentPage)
    setHistory('pa', this.currentPage, this.currentPage);
  }
};

function setHistory(prefix, key, value){
  var currentLoc = dhtmlHistory.getCurrentLocation();
  var locElms = currentLoc.strip().split('|:|');
  var locStr = '';
  var vals = new Array();
  if(locElms.length > 0 && !locElms[0].empty()){
    var isset = false;
    for(var i = 0; i < locElms.length; i++){
      var elm = locElms[i];
      if(elm.startsWith(prefix)){
        locStr += prefix + key + '|:|';
        vals[vals.length] = value;
        isset = true;
      }
      else{
        locStr += elm + '|:|';
        var sVals = historyStorage.get(elm);
        if(sVals){
          vals[vals.length] = sVals[0];
        }
      }      
    }
    if(!isset){
      locStr += prefix + key + '|:|';
      vals[vals.length] = value;
    }
    locStr = locStr.substr(0, locStr.length - 3);
  }
  else{
    locStr += prefix + key;
    vals[vals.length] = value;
  }
  dhtmlHistory.add(locStr, vals);
}

function getHistoryValue(prefix, loc, data){
  var result = null;
  var locList = loc.split('|:|');
  for(var i = 0; i < locList.length; i++){
    if(locList[i].startsWith(prefix)){
      result = data[i];
      break;
    }
  }
  return result;
}