$(document).ready(function() {

  // admin override clicks on row or col links
  $('.rt_admin_link a').live('click', function(){

    // show busy cursor
    //$('#rack_pockets').addClass('wait');

    if ($(this).hasClass('col')){
      var clicked = 'col';

    } else if ($(this).hasClass('row')){
      var clicked = 'row';

    } else if ($(this).hasClass('rack')){
      var clicked = 'rack';

    }
    // do we turn all pockets on or off?
    var status = $(this).attr('status');
    // toggle status
    var new_status = "on";
    if (status == "on")  new_status = "off";

    // do processing
    // depending on whether col, row or rack clicked ... create a list of pockets to add/remove from cart
    switch(clicked){
      case 'col':
        var col = $(this).attr('col');
        $('td.col_'+col+' a.pocket').addClass('wait');

        //console.log('build list of pockets in col '+col);
        $('td.col_'+col+' a.pocket').each(function(){
          //console.log('pocket '+$(this).find('.pocketCellRef').text());
          pocket_to_cart(new_status, $(this));
        });
        $('td.col_'+col+' a.pocket').removeClass('wait');
        break;

      case 'row':
        var row = $(this).attr('row');
        //console.log('build list of pockets in row '+row);
        $('td.row_'+row+' a.pocket').addClass('wait');
        $('td.row_'+row+' a.pocket').each(function(){
          //console.log('pocket '+$(this).find('.pocketCellRef').text());
          pocket_to_cart(new_status, $(this));
        });
        $('td.row_'+row+' a.pocket').removeClass('wait');
        break;
      case 'rack':
        var rack = $(this).attr('rack');
        //console.log('build list of pockets in rack '+rack);
        $('a.pocket').addClass('wait');
        $('a.pocket').each(function(){
          //console.log('pocket '+$(this).find('.pocketCellRef').text());
          pocket_to_cart(new_status, $(this));
        });
        $('a.pocket').removeClass('wait');
        break;
    }


    $(this).attr('status', new_status).toggleClass('on').toggleClass('off');

    // if we just toggled the whole rack .... set all row and column links to the same
    if (clicked == "rack"){
      $('a.col, a.row').each(function(){
        // set status attr to new_status
        // & set class to ne new_status
        $(this).attr('status', new_status);
        // only toggle class if it's not how it 'should' be
        if (!$(this).hasClass(new_status))
          $(this).toggleClass('on').toggleClass('off');
      })
    }

    // cursor back to normal
    $('#rack_pockets').removeClass('wait');
    return false;
  });







  $('#rack_pockets a').live('click', function(){

    var pocket_link = $(this);
    var pocket_cell_ref = pocket_link.find('.pocketCellRef').text();
    //alert('rack_pockets a clicked: '+pocket_cell_ref);
    var redline_cell = pocket_link.find('.pocketCell');
    var customerId = $('#customerId').text();
    document.getElementById('pocketAddNarrative').innerHTML = '';
    redline_cell.removeClass('refillIssue');

    // success must check that product truly added before toggle class & show model
    if ($(this).hasClass('notInCart')){
      //alert('adding to cart');
      add_pocket_to_cart(pocket_link);

    } else if ($(this).hasClass('inCart')){
      //alert('removing from cart');
      remove_pocket_from_cart(pocket_link);
     }
    return false;
  });


  $('#switch_racks a.rack_letter').live('click', function(){
    // switch to display the selected rack
    var new_rack = $(this).text();
    var customerId = $('#customerId').text();
   // alert('new_rack: '+new_rack+'; customerId: '+customerId);
    //console.log('About to ajax get layout for customer id '+customerId+' new rack = '+new_rack);

     $.ajax({
                      type: 'POST',
                      url: 'ajax.php',
                      async: false,
                      data: 'handler=rt_ordering&action=rt_switch_rack&cust='+customerId+'&rack='+new_rack,
                      success: function(response){
                        //alert('success: '+response.html);
                        $('#rt_order_racks').html(response.html);
                      },
                      complete: function(jqXHR, textStatus ){
                        //console.log('jqXHR: '+dump(jqXHR, 5));
                        //console.log('textStatus: '+textStatus);
                        //alert('complete');
                      },
                      dataType: "json"
                    });

//      $.post('ajax.php', 'handler=rt_ordering&action=rt_switch_rack&cust='+customerId+'&rack='+new_rack, function(response) {
//        $('#rt_order_racks').replaceWith(response.html);
//      }, "json");

    return false;
  });






  $('a.clear_refill_order').live('click',function(){
    // delete all rows in the order
    var customerId = $('#customerId').val();
    //alert('clearing all lines for customer: '+customerId);
    $.post('ajax.php', 'handler=rt_ordering&action=remove_all_lines&cust='+customerId, function(response) {}, "json");
    $('#rt_order_summary tbody tr').remove();
    return false;
  });




  // remove line from pocket re-order table
//  $('#rt_order_summary a:contains(Remove)').live('click',function() {
  $('a.rtRemoveLine').live('click',function() {
    // get the id of the line clicked
    var customerId = $('#customerId').val();
    //console.log('customer: '+customerId)
    var lineId=$(this).attr('name');
    //console.log('line: '+lineId);
    //alert('clearing line '+lineId+' for customer: '+customerId);
    var table_row = $(this).parentsUntil('tbody');

    //console.log('Removing line '+lineId+' for customer Id : '+customerId);
    //alert('Removing line '+lineId+' for customer Id : '+customerId);

    $.post('ajax.php', 'handler=rt_ordering&action=remove_line&cust='+customerId+'&line='+lineId, function(response) {
      // replace the 'order' display
      //console.log('database updated');
      // now remove the row just deleted from the table
//      $('#rt_order').html(response.html);
    }, "json");
    table_row.remove();
    return false;
  });


  $('#clear_RT_prods_in_cart a').click(function(){
//    $.post('ajax.php', 'handler=rt_ordering&action=clear_rt_products_in_cart', function(response) { }, "json");
    // again we want to be synchronous - so use $.ajax
    $(this).parentsUntil('tbody').css('cursor', 'wait');
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        async: false,
        data: 'handler=rt_ordering&action=clear_rt_products_in_cart',
        dataType: "json"
      });
    $(this).parentsUntil('tbody').css('cursor', 'normal');
      //return false;
  });



  $('#rt_empty_main_cart a').click(function(){
//    $.post('ajax.php', 'handler=rt_ordering&action=rt_empty_main_cart', function(response) {}, "json");
    // again we want to be synchronous - so use $.ajax
    $(this).parentsUntil('tbody').css('cursor', 'wait');
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        async: false,
        data: 'handler=rt_ordering&action=rt_empty_main_cart',
        dataType: "json"
      });
    $(this).parentsUntil('tbody').css('cursor', 'normal');
//      return false;

  });

});



function add_pocket_to_cart(pocket){
  //console.log('add_to_cart');
  var pocket_cell_ref = pocket.find('.pocketCellRef').text();
  var redline_cell = pocket.find('.pocketCell');
  var customerId = $('#customerId').text();
  document.getElementById('pocketAddNarrative').innerHTML = '';
  //redline_cell.removeClass('refillIssue');

  // success must check that product truly added before toggle class & show model
  $.ajax({
        type: 'POST',
        url: 'ajax.php',
        async: false,
        data: 'handler=rt_ordering&action=rt_add_pocket_to_cart&cust='+customerId+'&pocket='+pocket_cell_ref,
        success: function(response){
          if(response.status){
            pocket.find('.pocketCellRef').after('<div class="pocketinCart">'+response.model+'</div>');
            document.getElementById('shoppingcartContent').innerHTML = response.cart;

            pocket.toggleClass('notInCart').toggleClass('inCart');
            pocket.parent().toggleClass('inCart');

            redline_cell.toggleClass('inCart');
           } else {
            // feedback to user why not added & why no substitute
            //console.log(pocket_cell_ref+response.summary);
            document.getElementById('pocketAddNarrative').innerHTML = 'Error - Pocket '+pocket_cell_ref+response.summary;
            redline_cell.addClass('refillIssue');;
           }
        },
        dataType: "json"
      });
}



function remove_pocket_from_cart(pocket){
  //console.log('remove_from_cart');
  var pocket_cell_ref = pocket.find('.pocketCellRef').text();
  var redline_cell = pocket.find('.pocketCell');
  var customerId = $('#customerId').text();
  document.getElementById('pocketAddNarrative').innerHTML = '';
  //redline_cell.removeClass('refillIssue');

  $.ajax({
        type: 'POST',
        url: 'ajax.php',
        async: false,
        data: 'handler=rt_ordering&action=rt_remove_pocket_from_cart&cust='+customerId+'&pocket='+pocket_cell_ref,
        success: function(response){
            // do this whetherthe remove was successful or not
            // possibly there are 2 pockets in template with same item -
            // once first item has been removed, second will 'fail'
            // but it still needs to be cleansed up
          //if(response.status){
            pocket.find('.pocketinCart').remove();
            document.getElementById('shoppingcartContent').innerHTML = response.cart;

            pocket.toggleClass('notInCart').toggleClass('inCart');
            pocket.parent().toggleClass('inCart');

            redline_cell.toggleClass('inCart');
          //} else {
             // feedback to user why not added & why no substitute
            //console.log(pocket_cell_ref+response.summary);
             //document.getElementById('pocketAddNarrative').innerHTML = pocket_cell_ref+response.summary;
             //redline_cell.addClass('refillIssue');
          //}
        },
        dataType: "json"
      });
}





// generic function that adds or removes (according to status) the supplied pocket to/from the cart
function pocket_to_cart(status, pocket){
  pocket_num = pocket.find('.pocketCellRef').text();
  var in_cart = pocket.hasClass('inCart');
  pocket.find('.pocketCell').removeClass('refillIssue');

  //console.log('pocket_to_cart '+pocket_num+'; status = '+status+' already in cart: '+in_cart);
  // are we adding to or removing from
  var add_to_cart = false;
  if (status == "on")
    add_to_cart = true;

  // is the current pocket already in the cart?

  if (in_cart) {
    if (add_to_cart){
      // do nothing it's already there
      //console.log('in cart + add to cart => do nothing as it\'s already there');
    } else {
      //console.log('in cart + !add to cart (i.e. remove) => add to cart');
      remove_pocket_from_cart(pocket);
    }
  } else { // pocket is not in cart
    if (!add_to_cart){
      //console.log('not in cart + !add to cart (i.e. remove) => do nothing as it\'s not in the cart to start with');
      // do nothing it's already 'not' there
      // clear the refillIssue class
      //console.log('already not in cart - refillIssue Class should already be gone for '+pocket_num);
    } else {
      //console.log('not in cart + do add to cart => add to cart');
      add_pocket_to_cart(pocket);
    }
  }
}

