var backpack = []; // array: product records in backpack

////////////////////////////////////////////////////////////////////////////////

/**
 * Show backpack window (ThickBox)
 */
function showBackpack() {
  var width = 0;
  
  if      (backpack.length == 1) { width = 500; }
  else if (backpack.length == 2) { width = 600; }
  else if (backpack.length == 3) { width = 780; }
  else if (backpack.length == 4) { width = 950; }
  
  if (width) {
    switch (producttype_id) {
      case producttypes.CREDIT_CARD:
        tb_show_compare_backpack(null, '/productpicker/overlayCreditCard?height=1400&width=' + width, null);
        //tb_show(null, '/productpicker/overlayCreditCard?height=700&width=' + width, null);
        break;
      case producttypes.CD:
        tb_show_compare_backpack(null, '/productpicker/overlayCD?height=1400&width=' + width, null);
        //tb_show(null, '/productpicker/overlayCD?height=700&width=' + width, null);
        break;
    }
  }
}

/**
 * Update page elements based on the current state of the backpack.
 */
function updateBackpackPageElements() {
  $('#backpackqty').text(backpack.length);
  
  // Enable/disable compare button's functionality based on backpack state
  if (backpack.length > 0) {
    $('#backpackButton').attr('class', 'compare-all');
    // Unbind any pre-existing click events to avoid double-binding
    $('#backpackButton').unbind('click');
    $('#backpackButton').click(function(){ showBackpack(); });
  } else {
    $('#backpackButton').attr('class', 'compare-all-disabled');
    $('#backpackButton').unbind('click');
  }
  
  // Activate checkboxes of any products both in the backpack and page
  jQuery.each(backpack, function(i, product){
    $('#compare-checkbox-' + product.id).attr('checked', true);
  });
}

/**
 * Prepare a backpack slot's display content and events.
 *
 * @param integer slot
 * @param integer id   Product identifier
 * @param string  name Product name
 */
function prepareBackpackSlot(slot, id, name) {
  $('#backpackslot' + slot)
    .addClass('filled')
    .removeClass('empty')
    .attr('title', name + '. Click to remove.')
    .tooltip({ track: true, delay: 0, showURL: false, showBody: ' - ', fade: 250 })
    .click(function(){ slotRemoveCall(id); });
  $('#bp-overlay' + slot).click(function(){ slotRemoveCall(id); });
}

/**
 * Clear a backpack slot's display content and events.
 *
 * @param integer slot
 */
function clearBackpackSlot(slot) {
  $('#backpackslot' + slot)
    .addClass('empty')
    .removeClass('filled')
    .attr('title', 'Select products below to compare')
    .tooltip({ track: true, delay: 0, showURL: false, showBody: ' - ', fade: 250 })
    .unbind('click');
  $('#bp-overlay' + slot).unbind('click');
  $('#bp-overlay' + backpack.length)
    .css('display', 'none')
    .empty();
}

/**
 * Event handler for clicking a compare checkbox.  Adds or removes a product
 * from the backpack accordingly.
 *
 * @param integer id   Product identifier
 * @param string  name Product name
 */
function compareCheckboxCall(id) {
  var data;
  
  var checkboxObj = $('#compare-checkbox-' + id);
  
  if (checkboxObj.length) {
    // If checkbox is checked, the product should be added to the backpack
    if (checkboxObj.is(':checked')) {
      // Fetch name from the product name displayed in the listing
      var name = $('h3#product-name-'+id).text();
      
      // Attempt to add the product to the backpack
      if (addProductToBackpack(id, name)) {
        data = { id: id, name: name, producttype_id: producttype_id };
        jQuery.get('/productpicker/backpackAdd', data);
        
        // Display message if this is the first product to go into the backpack
        if (backpack.length == 1) {
          tb_show(null, '#TB_inline?height=380&width=600&inlineId=productpicker-backpackFirst', null);
        }
      } else {
        // Adding to backpack failed, display an error
        tb_show(null, '#TB_inline?height=270&width=600&inlineId=productpicker-backpackError', null);
        // Ensure the calling checkbox is left unchecked
        $('#compare-checkbox-' + id).attr('checked', false);
      }
    } else {
      // Checkbox became unchecked, so remove the product from the backpack
      if (removeProductFromBackpack(id)) {
        data = { id: id, producttype_id: producttype_id };
        jQuery.get('/productpicker/backpackRemove', data);
      }
    }
  }
  
  updateBackpackPageElements();
}

/**
 * Event handler for clicking a backpack slot to remove a product.
 *
 * @param integer id   Product identifier
 */
function slotRemoveCall(id) {
  id = parseInt(id, 10);
  
  var checkboxObj = $('#compare-checkbox-' + id);
  
  if (removeProductFromBackpack(id)) {
    checkboxObj.attr('checked', false);
    var data = { id: id, producttype_id: producttype_id };
    jQuery.get('/productpicker/backpackRemove', data);
  }
  
  updateBackpackPageElements();
}

/**
 * Add a product to the backpack.
 *
 * @param integer id   Product identifier
 * @param string  name Product name
 * @return boolean True if product was successfully added, false otherwise
 */
function addProductToBackpack(id, name) {
  // Cannot add more than 4 products at a time
  if (backpack.length >= 4) {
    return false;
  }
  
  backpack.push({ id: id, name: name });
  prepareBackpackSlot(backpack.length, id, name);
  
  return true;
}

/**
 * Removes a product from the backpack.
 *
 * @param integer id Product identifier
 * @return boolean True if product was found and removed, false otherwise
 */
function removeProductFromBackpack(id) {
  var removed = false;
  
  // Clear all backpack slots
  for (var i = 0; i < backpack.length; i++) {
    clearBackpackSlot(i + 1);
  }
  
  // Search for the matching product and remove it
  for (i = 0; i < backpack.length; i++) {
    if (backpack[i].id == id) {
      backpack.splice(i, 1);
      removed = true;
      break;
    }
  }
  
  // Reconstruct backpack slots
  for (i = 0; i < backpack.length; i++) {
    prepareBackpackSlot(i + 1, backpack[i].id, backpack[i].name);
  }
  
  return removed;
}

/**
 * Imports a backpack from the session.  The sessionBackpack array should be
 * composed of special 'product' objects containing only id and name properties.
 *
 * @param array sessionBackpack Backpack JSON from session
 */
function importSessionBackpack(sessionBackpack) {
  if (typeof(sessionBackpack) == 'object') {
    jQuery.each(sessionBackpack, function(i, product){
      addProductToBackpack(product.id, product.name);
    });
  }
  
  updateBackpackPageElements();
}