// @auth ghunt
// @name dropdown.js
// @desc displays and builds the dropdown menu
// @change
//   2011-10-06 ghunt
//     created the file

jQuery(document).ready(function() {
  
  var browseNodes = {
    'luggage': 2235704011,
    'business-laptops': 2235705011,
    'backpack-messenger': 2235706011, 
    'duffles-sport-bags': 2235707011,
    'accessories': 2235708011,
    'collections': 2235709011,
    'sale': 2235711011
  };
  
  jQuery('#navigation li a').mouseenter(function() {
    var node = browseNodes[jQuery(this).attr('name')];
    jQuery('#dropNode').val(node);    
    showDropdownMenu();    
    loadMenu(node);
    loadProducts(node, 'Top Sellers', 'salesrank');
  });
  
  jQuery('#dropdown').mouseleave(function() {
    hideDropdownMenu();
  });
  
  jQuery('body').click(function() {
    if(jQuery('#dropdown').is(':visible'))
      hideDropdownMenu();
  });
  
  jQuery('div.leftSec a').click(function(e) {
    e.preventDefault();
    var node = jQuery('#dropNode').val();
    var title = jQuery(this).text();
    var rank = jQuery(this).attr('name');
    loadProducts(node, title, rank);
    return false;
  });
});

function showDropdownMenu() {
  var j = jQuery.noConflict();
  j('#dropdown').show('fast');
}

function hideDropdownMenu() {
  var j = jQuery.noConflict();
  j('#dropdown').hide('fast');
}

function loadMenu(node) {
  var j = jQuery.noConflict();
  j('#dropMiddle').html('');
    
  var url = '/api/browse/' + node;
  var div = j('<div />').addClass('subnav').hide();
  
  j.getJSON(url, function(data) {
    var children = data.childNode;
    var sorted = sortChildCategories(children);
    for(var i in sorted) {
      var child = sorted[i];
      var seoName = child.name.replace(/ /g, '-');
      var link = j('<a />').attr('href', '/' + seoName + '/b/' + child.id);
      link.text(child.name);      
      var linkWrap = j('<div />').addClass('link').append(link);
      div.append(linkWrap);
    }
    j('#dropMiddle').html(div);
    div.fadeIn('fast');
  });
}

function sortChildCategories(categories) {
  // "sorts" items so that the ordering changes like this:
  // 0  1        0  4
  // 2  3   ==>  1  5
  // 4  5   ==>  2  6
  // 6           3
  

  var listA = [];
  var listB = [];
  var listC = [];

  var len = categories.length;
  var midIndex = Math.ceil(len / 2.0);
  var i = 0;
  var j = 0;
  var k = 0;
  
  for(i=0; i<midIndex; i++)
    listA.push(categories[i]);
  for(i=midIndex; i<len; i++)
    listB.push(categories[i]);
    
  for(i=0; i<len; i++) {
    if(i%2 == 0) {
      listC.push(listA[j]);
      j++;
    } else {
      listC.push(listB[k]);
      k++;
    }
  }

  return listC;
}

function loadProducts(node, title, sorting) {
  var j = jQuery.noConflict();
  j('#dropRight .subnav').html('');
  
  var url = '/api/search/product?query=browse:' + node + '&count=4&sort=' + sorting;
  var pdiv = j('<div />').addClass('dropProducts').hide();
  
  j('#dropRight h2').text(title);
  
  j.getJSON(url, function(data) {
    var products = data.results.product;
    for(var i in products) {
      var product = products[i];
      var prod = j('<div />').addClass('product');
      var title = product.attributes[0].title;
      var seoTitle = title.replace(/ /g, '-');
      var url = '/' + seoTitle + '/dp/' + product.identifiers.asin;
      var link = j('<a />').attr('href', url).addClass('link');
      link.html(title);
      var imgUrl = 'http://ecx.images-amazon.com/images/P/';
      imgUrl += product.identifiers.asin; 
      imgUrl += '.01-A31B5X10R828KF._SX80_SCLZZZZZZZ_V177022426_.jpg';
      var img = j('<img />').attr('src', imgUrl);
      var imgLink = j('<a />').attr('href', url);
      imgLink.html(img);

      var listRange = product.offers.variationalOfferSummary.regularPriceRange;
      var saleRange = product.offers.variationalOfferSummary.buyingPriceRange;
      var listText = '';
      var saleText = '';
      
      if(listRange.max == listRange.min)
        listText = '$' + listRange.min.toFixed(2);
      else
        listText = '$' + listRange.min.toFixed(2) + ' - $' + listRange.max.toFixed(2);
      
      if(saleRange.max == saleRange.min)
        saleText = '$' + saleRange.min.toFixed(2);
      else
        saleText = '$' + saleRange.min.toFixed(2) + ' - $' + saleRange.max.toFixed(2);

      var saleLbl = j('<div />').addClass('saleLbl').text('Sale');      
      var saleAmt = j('<div />').addClass('saleAmt').text(saleText);
      var sale = j('<div />').addClass('salePrice').append(saleLbl).append(saleAmt);
      
      var listLbl = j('<div />').addClass('listLbl').text('Orig.');
      var listAmt = j('<div />').addClass('listAmt').text(listText);
      var list = j('<div />').addClass('listPrice').append(listLbl).append(listAmt);

      // var sale = j('<div />').addClass('salePrice').text('Sale ' + saleText);
      // var list = j('<div />').addClass('listPrice').text('Orig. ' + listText);

      prod.append(imgLink);
      prod.append(link);
      prod.append(list);
      
      if(listText != saleText)
        prod.append(sale);

      pdiv.append(prod);
    }
    j('#dropRight .subnav').html(pdiv);
    pdiv.fadeIn('fast');
  });
}
