var sideScroller = (function($) {
  var animSpeed = 800,
      timerHandle,
      startPage = 1,
      itemsPerPage = 8,
      autoDelayTime = 8000;
      directions = {previous: {increment: -1, test: function(i, b, m, l) { m.hide(); if (i == l) { $(b).hide(); } return (i >= l); }},
                    next: {increment: 1, test: function(i, b, m, l) {
                                                 if (i == l) {
                                                   m.show();
                                                   $(b).hide();
                                                 }
                                                 return (i <= l);
                                               }}};
  
  function changePage(e, btn, direction) {
    var tab = $(btn).parents('.tabbody:first'), 
        page = tab.data('page') + direction.increment,
        more = $('.more', tab),
        l = (direction === directions.next)?tab.data('numPages'):startPage;
    
    if (direction.test(page, btn, more, l)) {
      tab.data('page', page);
      $('.container', tab).animate({left: '-' + ((page - 1) * 100) + '%'}, 1000);
      $('.prevnext', tab).not(btn).show();
    }
    e.preventDefault();
  }
  
  function init() {
    $('#maincats .prevnext.next').click(function(e) { changePage(e, this, directions.next); }); 
    $('#maincats .prevnext.prev').click(function(e) { changePage(e, this, directions.previous); }).hide();
    $('#maincats .more').hide();
    
    $('#maincats .tabbody').data('page', startPage).each(function() {
      $(this).data('numPages', Math.ceil($('.product', this).length / itemsPerPage));
    })
    self.reinit();
    $('#maincats').mouseover(cancelTimer).mouseleave(startTimer);
    startTimer();
  }
  
  function cancelTimer() {
    if (timerHandle) {
      window.clearTimeout(timerHandle);
    }
  }
  
  function startTimer() {
    cancelTimer();
    timerHandle = window.setTimeout(autoScroll, autoDelayTime);
  }
  
  function setTabPosition(tab, animate) {
    var page = tab.data('page'),
        maxPage = tab.data('numPages');
    
    if (page < maxPage) {
      tab.data('page', ++page);
      if (animate) {
        $('.container', tab).animate({left: '-' + ((page - 1) * 100) + '%'}, 1000);
      } else {
        $('.container', tab).css('left', '-' + ((page - 1) * 100) + '%');
      }
      $('.prev', tab).show(); 
      
      if (page == maxPage) {
        $('.more', tab).show();
        $('.next', tab).hide();
      } else {
        $('.more', tab).hide();
        $('.next', tab).show();        
      }
    }
    else {
      tab.data('page', page = startPage);
      if (animate) {
        $('.container', tab).animate({left: '-' + ((page - 1) * 100) + '%'}, 1000);
      } else {
        $('.container', tab).css('left', '-' + ((page - 1) * 100) + '%');
      }
      $('.prev', tab).hide();
      $('.more', tab).hide(); 
      $('.next', tab).show();
    }
  }
  
  function autoScroll() {
    var tab = $('#maincats .tabbody.active'); 
    
    if (tab.data('numPages') == 0) {
      startTimer();
      return;
    }
    setTabPosition(tab, true);
    startTimer();
  }
  
  this.reinit = function() {
    $('#maincats .tabbody').each(function() {
      var count = $('.product', this).length,
          numPages = Math.ceil(count / itemsPerPage);
      
      $(this).data('page', startPage);
      $(this).data('itemCount', count);
      $(this).data('numPages', numPages);
      $('.prev', this).hide();
      $('.more', this).hide(); 
      $('.container', this).css('left', 0);
      if (numPages > 1) {
        $('.next', this).show();
      } else {
        $('.next', this).hide();
      }
    });
  }
  
  $(document).ready(init);
  
  return this;
}(jQuery));

var categories = (function($) {
  var self = this;
  this.readmore = 'Read more';
  
  function wordwrap(str, width, brk, cut) {
    brk = brk || '\n';
    width = width || 75;
    cut = cut || false;
  
    if (!str) {
      return str;
    }
    var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
    return str.match( RegExp(regex, 'g') ).join( brk );
  }
  
  function stripTags(html) {
    var tmp = document.createElement('div');
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText;
  }
  
  function activateBlurb(id) {
    active = ($('li.ct.active').length === 1);
    $('.ct').addClass('hidden').removeClass('active');
    $('#ct' + id).removeClass('hidden');
    $('a[href=#ct' + id + ']').parents('li:first').removeClass('hidden');
    if (active) {
      $('#ct' + id).addClass('active');
      $('a[href=#ct' + id + ']').parents('li:first').addClass('active');
    }    
  }
  
  function tabActivated() {    
    var strlen = 128,
        active = false,
        id = $(this).attr('href').replace('#cattab', ''),
        txt = stripTags($('#ct' + id + ' .cols').html()),
        short = txt.substr(0, strlen);

    short = wordwrap(short, 56, '<br />', false);
    if (txt.length > strlen) {
      short += '…';
    }
    $('#bubble td').html('<h1>' + $(this).html() + '</h1><div>' + short + '</div>');
    activateBlurb(id);
    if (allowCufon && typeof Cufon == 'function') {
      Cufon.replace('#bubble h1', {fontFamily: 'Arial Black', color: '-linear-gradient(#51ed62, #16e5c3)'});
    }
    
  }
  
  function init() {
    var id = $('#maincats ul.tabs li:first a').attr('href').replace('#cattab', '');
    
    activateBlurb(id);
    $('#maincats ul.tabs li').each(function() {
      tabs.tabActivate($('a', this).attr('href').slice(1), tabActivated, true);
    });
  }
  $(document).ready(init);
  return this;
}(jQuery));

(function($) {
  var timerHandle = null;
  var queue = [];
  
  function sendAjaxRequest() {
    var vis, params;
    if (queue.length === 0) {
      $("div.product").fadeTo(200, 0.1);
      $('#warning')[(narrowDownSliders.filtered())?'removeClass':'addClass']('hidden');
    }

    queue.push(1 + queue.length);
    params = narrowDownSliders.getParams();
    ajaxpost('ajax/multilist', rh, params);
  }

  function rh(o) {
    var i, response;

    queue.pop();
    if ((queue.length === 0) && (o.xmlhttp.status == 200)) {
      response = ((typeof(JSON) == 'object') && (typeof(JSON.parse) == 'function'))?JSON.parse(o.responseText):eval(o.responseText);

      $('#maincats .tabbody .pg').add('#maincats .tabbody div.clear').remove();
      for (i in response.Items) {
        $('#cattab' + response.Items[i].ID + ' .container').append(response.Items[i].Products);
        $('#cattab' + response.Items[i].ID + ' .noresults').css('display', (response.Items[i].Count < 1)?'block':'none');
      }
      $('#maincats .tabbody .product').css('width', response.Width); 

      sideScroller.reinit();
    }
  }

  function changeFunc() {
    if (timerHandle !== null) {
      clearTimeout(timerHandle);
    }
    timerHandle = setTimeout(sendAjaxRequest, 400);
  }

  function init() {
    narrowDownSliders.changeFuncs.quantity = changeFunc;
    narrowDownSliders.changeFuncs.budget = changeFunc;
    narrowDownSliders.changeFuncs.deliveryTime = changeFunc;
    narrowDownSliders.colourSearch.onChange = changeFunc;
    
    $('#warning')[(narrowDownSliders.filtered())?'removeClass':'addClass']('hidden');
    $('#btnoff').click(narrowDownSliders.reset);
  }

  $(document).ready(init);
}(jQuery));

