var nbCards = 0;

$(document).ready(function(){
  $('#create-card').click (doInsertCard);
  $('#continue').click (doCheckout);
});

function doInsertCard () {
  insertCard();
  return false;
}
function insertCard (amount, cardType, recipient, quantity, to_name, from_name, message) {
  nbCards++;
  $('tr.operations').before (tmpl ('card_template', {i: nbCards, a: amount, y: cardType, r: recipient, q: quantity, t: to_name, f: from_name, m: message}));

  $('#amount_'+nbCards)
    .bind ('change keyup', updateTotal)
    .select();

  $('#amount_'+nbCards+'_arrow')
    .click (displayDropdown);

  $('#amount_'+nbCards+'_dropdown')
    .click (insertValue);

  $('#message_'+nbCards)
    .bind ('change keyup', enforceLimit)
    .textCounting();
  if ($.browser.mozilla) {
    dx = 4;
    $('#message_'+nbCards)
      .css ({width: dx+$('#recipient_name_'+nbCards).width()});
  }

  $('#remove_card_'+nbCards)
    .click (deleteCard);

  if ($('#giftcard-list tr.fields').length > 1) { // more than one card shown
    $('.config-remove').show();
  }

  switchCardType (cardType, nbCards, false);

  redecorateCards();
}

function deleteCard () {
  $('#giftcard-list tr.'+this.id.replace(/remove_/, '')).remove();
  if ($('#giftcard-list tr.fields').length == 1) { // only one card shown
    $('.config-remove').hide();
  }
  redecorateCards();
}

function redecorateCards () {
  showTotal();

  $('#giftcard-list tr.even').removeClass('even');
  $('tr.fields:odd').addClass('even');
  $('tr.fields:odd').addClass('even');
  $('tr.remover:odd').addClass('even');
}

function displayDropdown () {
  $field = $('#'+this.id.replace(/_[a-z]+$/, ''));
  o1 = $field.offset();
  $d = $('#'+this.id.replace(/arrow/, 'dropdown'));
  $d.css({left: o1.left});
  if ($.browser.safari) { // why is this needed?
    $d.css({marginTop: '-2px'});
  }
  $d.toggle();
}

function insertValue () {
  $field = $('#'+this.id.replace(/_[a-z]+$/, ''));
  $field.val (this.value).change();
  $(this).hide();
}

function updateTotal () {
  if (this.value.length && (this.value.search(/[^\d]/) != -1)) {
    this.value = this.value.replace (/[^\d]/g, ''); // eliminate non-digits
    // $('#'+this.id+'_error').html('Invalid amount');
  // } else {
    // $('#'+this.id+'_error').empty();
  }
  showTotal();
}

function showTotal () {
var total = 0;
  $('input.config-amount').each(function(){
    if (this.value.length && (this.value.search(/[^\d]/) == -1)) {
      v = parseInt (this.value, 10);
      if (!isNaN(v)) {
        // TODO: take plastic card quantity into account
        // q = parseInt ($('#'+this.id.replace(/amount/, 'quantity')).val(), 10);
        total += v;
      }
    }
  });
  $('#total').html (total.toFixed (2));
}

function switchCardType (newType, cardNum, doSelect) {
  // show fields based on card type
  visible = [];
  visible [2] = true;
  visible [3] = false;
  visible [4] = true;
  visible [5] = true;
  visible [6] = true;
  for (i in visible) {
    v = visible[i] == (newType != 'plastic');
    $('#step-'+i+'-'+cardNum).css({display: v?'':'none'});
  }

  if (doSelect) {
    $('#'+(newType != 'plastic' ? 'recipient':'quantity')+'_'+cardNum).focus().select();
  }
}

function enforceLimit () {
  if (this.value.length > $(this).attr('maxlength')) {
    this.value = this.value.substr (0, $(this).attr('maxlength'));
  }
}

function doCheckout () {
  ids = $.map ($('tr.fields'), (function (c) {
    return c.className.replace (/[^\d]/g, '');
  })).join (' ');
  $('#card_enum').val (ids);
}


// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
  
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
      
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
        
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
        
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
    
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();


