function scrollerInit() {
  $(".scroller").each(function() {
    setWidth(this);
  });
  
  $(".boxxsingle").serialScroll({
    target: '.viewer',
    items: '.item',
    prev: 'a.prev',
    next: 'a.next',
    // navigation: '.scrollnav li a',
    axis: 'x',
    step: 5,
    duration: 600,
    easing: 'easeOutQuart',
    stop: true,
    lock: false,
    cycle: false,
    lazy: true,
    onBefore:function(e, target, $scroll, $items, pos) {
      var id = $scroll.parents("div:first").attr("id");
      var page = (pos+1) / 5;
      
      $("#"+id+" .scrollnav a")
        .removeClass("here")
        .eq(page).addClass("here");
        
      // console.log("before: "+pos);
    }
    
  });
}

function setWidth(target) {
  var w = 0;
  $(target).children().each(function() {
    w += $(this).width();
  });
  
  $(target).width(w);  
}

function getItems(type, offset) {
  // console.log("getItems: "+offset);
  var url = "/ajax.php";
  var data = "type="+type+"&offset="+offset;
  
  $.ajax({
    url:url,
    data:data,
    type:'POST',
    dataType:'json',
    error: itemError,
    success: itemSuccess
  });
}

function itemError(xml, status, error) {
  alert("there was an error");
}

function itemSuccess(data, status) {
  if (!data.error) {
    var target;
    switch(data.type) {
      case 1:
        target = "singles";
        break;
      case 2:
        target = "albums";
        break;
      case 3:
        target = "merch";
        break;
      case 4:
        target = "special";
        break;        
    }
    if(target == 'special'){
        $(data.data).each(function(){
          var item = makeSpecialItem(this);
          $("#"+target+" .scroller").append(item);
        });    
    } else {
        $(data.data).each(function(){
          var item = makeItem(this);
          $("#"+target+" .scroller").append(item);
        });
    }  
    setWidth("#"+target+" .scroller");
  
    // force scroll
    var index = $("#"+target+" .scroller").children().length - 5;
    $("#"+target+" .scroller").trigger('goto', [index]);
  }
}

function makeItem(item) {
  var html = '<div class="item">';
  html += '<a href="/product/'+item.p_basecode+'/">';
  html += '<img src="'+item.img+'" alt="'+item.p_title+'" width="118" border="1">';
  if (item.artist) { html += '<br />'+item.artist; }
  html += '<br /><strong>'+item.p_title+'</strong><br />';
  if (item.formats) html += item.formats;
  if (item.p_subtitle) html += item.p_subtitle;
  html += '</a></div>';
  
  return html;
}

function makeSpecialItem(item) {
  var html = '<div class="item">';
  html += '<a href="/product/'+item.p_basecode+'/">';
  html += '<img src="'+item.img+'" alt="'+item.p_title+'" width="118" border="1">';
  if (item.artist) { html += '<br />'+item.artist; }
  html += '<br /><strong>'+item.p_title+'</strong><br />';
  if (item.formats) html += item.formats;
  if (item.p_subtitle) html += item.p_subtitle;
  html += item.ft_type+' - &pound;'+item.pr_value+'</a></div>';
  
  return html;
}

function scrollJump(e) {
  e.preventDefault();
  
  var id = $(this).parents("div:eq(1)").attr("id");
  var type;
  
  switch(id) {
    case "singles":
      type = 1;
      break;
    case "albums":
      type = 2;
      break;
    case "merch":
      type = 3;
      break;
    case "special":
      type = 4;
      break;      
  }
  
  var page = Number($(this).text())-1;
  var pos = page * 5;
  var items = $("#"+id+" .scroller").children();

  // console.log("scrollJump: "+pos);

  if (pos >= items.length && items.length < 20) {
    var pages = items.length / 5;
    
    for (var i=(pos/5) - pages; i >= 0; i--) {
      // console.log(page+" - "+i+" = "+(page-i));
      getItems(type, page-i);
    }
  }
  
  $("#"+id+" .scroller").trigger('goto', [pos]);
}

function loadMoreResults(e) {
  e.preventDefault();
  
  var obj = parseURLParams(this.href);
  getResults(obj['q'], obj['type'], obj['offset']);
}

function getResults(query, type, offset) {
  var url = "/search-ajax.php";
  var data = "q="+encodeURIComponent(query);
  data += "&type="+type;
  data += "&offset="+offset;
  
  $.ajax({
    url:url,
    data:data,
    type:'POST',
    dataType:'json',
    error: searchError,
    success: searchSuccess
  });
}

function searchError(xml, status, error) {
  // body...
}

function searchSuccess(data, status) {
  if (!data.error) {
    var results = "", div;
    
    // console.log("num results: "+data.data.length);
    
    $(data.data).each(function(i){
      if (data.type == 0) {
        results += makeTrackRow(this, (i%2));
      } else if (data.type < 3) {
        results += makeSearchRow(this, (i%2));
      } else {
        results += makeMerchItem(this);
      }
    });
    
    switch (data.type) {
      case 0:
        div = "#tracksBox";
        break;
      case 1:
        div = "#singlesBox";
        break;
      case 2:
        div = "#albumsBox";
        break;
      case 3:
        div = "#merchBox";
        break;
    }
    
    // insert results
    if (data.type < 3) {
      var tableClass = "search";
      tableClass += (data.type == 0) ? "" : " release";
      
      $(results)
        .wrapAll('<tbody></tbody>')
        .parent() // find <tbody> we just wrapped $results in
        .wrap('<table class="'+tableClass+'" cellpadding="0" cellspacing="0"></table>')
        .parent() // find <table> we just wrapped <tbody> in
        .hide()
        .insertAfter(div+" table:last") // append after last table
        .slideDown(600, "easeOutQuart");

    } else {
      $(results)
        .wrapAll('<div style="display:none; overflow:hidden"></div>')
        .parent()
        .appendTo(div)
        .slideDown(600, "easeOutQuart");
      
      // $(div).append(results);
    }
    //alert(data.data.length);
    if (data.data.length == 20) {
      // update button
      var offset = $("a.more", div).attr("href").match(/offset=(\d+)/).pop();
      var url = $("a.more", div).attr("href").replace(/offset=\d+/, "offset="+(Number(offset)+1));
      $("a.more", div).attr("href", url);
    } else {
      // hide button
      $("a.more", div).hide();
    }
  } else {
    // error
  }
}

function makeSearchRow(item, odd) {
  var date = item.p_release_date.split("-");
  date = date[2]+"/"+date[1]+"/"+date[0].substring(2);
  
  var html = '<tr';
  if (odd) html += ' class="odd"';
  html += '> <td class="artist"><a href="/artist/'+item.a_id+'">'+item.artist+'</td> ';
  html += '<td class="title"><a href="/product/'+item.p_basecode+'">'+item.i_title+'</a></td> ';
  html += '<td class="format">'+item.format+'</td> ';
  html += '<td class="release_date">'+date+'</td> ';
  html += '<td class="buy"><a href="/product/'+item.p_basecode+'">View Release</a></td></tr> ';
  
  return html;
}

function makeTrackRow(item, odd) {
  var html = '<tr';
  if (odd) html += ' class="odd"';
  html += '> <td class="artist"><a href="/artist/'+item.a_id+'">'+item.artist+'</td> ';
  html += '<td class="title"><a href="/product/'+item.p_basecode+'">'+item.i_title+'</a></td> ';
  html += '<td class="format">'+item.format+'</td> ';
  html += '<td class="album"><a href="/product/'+item.p_basecode+'">'+item.p_title+'</td> <td>';
  html += '<td><a href="/preview/'+item.i_id+'" class="preview" title="Preview '+item.i_title+'">Preview '+item.i_title+'</a></td>';
  html += '<td class="mp3">';
  if (item.track_price) html += '&pound;'+item.track_price;
  html += '</td> <td class="buy">';
  if (item.track_price) html += '<a href="/add/item/'+item.p_basecode+'/'+item.i_id+'" class="buy">Buy</a>';
  html += '</td></tr> ';

  return html;
}

function makeMerchItem(item) {
  var html ='<div class="item"> ';
  html +='<a href="/product/'+item.p_basecode+'/"> ';
  html +='<img src="'+item.img+'" alt="'+item.p_title+'" width="118" border="1"> ';
  html +='<br /><strong>'+item.p_title+'</strong></a> </div> ';
  
  return html;
}

function parseURLParams(url) {
  var obj = new Object();
  var array = url.match(/(\?|&|&amp;|&)([\w_-]+)=([^&]+)/g);
  
  for (var i=0; i<array.length; i++) {
    var key = array[i].match(/(\?|&amp;|&)([^=]+)/)[2];
    var value = array[i].match(/=(.*)/).pop();
    
    // eval("obj."+key+"='"+value+"'");
    obj[key] = value;
  }
  
  return obj;
}

function tabInit() {
  $("#tabs").tabs({
    // ajaxOptions: { type:'POST' },
    cache: true,
    selected: 0,
    show: showTab
  });
}

function showTab(e, ui) {
  var type, q = window.location.search.match(/\?q=(.*)/).pop();
  
  switch (ui.panel.id) {
    case "singlesBox":
      type = 1;
      break;
    case "albumsBox":
      type = 2;
      break;
    case "merchBox":
      type = 3;
      break;
  }
  
  if (ui.panel.id != "merchBox" && $("tbody", ui.panel).children().length == 0) {
    // singles & albums
    getResults(q, type, 0);
  } else if (ui.panel.id == "merchBox" && $(ui.panel).children().length == 1) {
    // merch
    getResults(q, type, 0);
  }
}

function previewWindow(e) {
  e.preventDefault();
  
  var windowConfig = 'height=95,width=348,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no';
  var preview = window.open(this.href,'preview',windowConfig);
  preview.focus();
}

$(document).ready(function() {
  // front page scroller
  scrollerInit();
  $(".scrollnav a").bind("click", scrollJump);

  // search results
  $("a.more").bind("click", loadMoreResults);
  
  // previews
  $("a.preview").bind("click", previewWindow);

  // tabs
  tabInit();
});