var quotes = [];
var qm_formats = {
  storage: "yyyy-MM-dd'T'HH:mm:ss",
  display_short: "MM'/'dd'/'yyyy KK:mm a",
  display_long: "EEE, MMM d, yyyy 'at' KK:mm a"
};
var qm_product_cache = {};
var qm_json_buffer = '';
var cookie_settings = {
    expires: 30,
    path: '/',
    domain: 'atlasuhv.com'
  };
var $qm_table = {};
var $qm_total= {};
var $toast = {};
var current_quote = 0;

qm_get_object();

function qm_build_page(){
  var columns = ['<input type="checkbox"/>', '', 'Description', 'Part Number', 'Qty', 'USD', 'Line Total']

  var $t = $('<table>').addClass('qm-main').append('<thead><tr></thead>').append('<tbody>');

  // Setup the product table headers
  $.each(columns, function(i, val){
    $('<th>').addClass('qm-head-'+(i+1)).html(val).appendTo($('thead tr', $t));
  });

  // Push table to the active DOM
  $('#content .quote-table-bar:first').after($t);
  $('#content .quote-table-bar:first').before()
  $qm_table = $('table.qm-main');


  // Bind Remove checked
  $('.qm-remove-checked.unprocessed').click(qm_remove_checked).removeClass('unprocessed');

  // Bind select/deselect all
  $('.qm-head-1 input.unprocessed').click(function(){
    $('.qm-part-select input').attr('checked', $(this).is(':checked'));
  })

  // Bind header buttons
  $('#quote_buttons.unprocessed a').click(function(event){

    if ($(this).is('.save')){qm_save_close_quote(true);}

    if ($(this).is('.print')){window.print();}

    if ($(this).is('.email')){

    }

    if ($(this).is('.delete')){qm_delete_quote(true);}

    event.preventDefault();
  });
  $('#quote_buttons.unprocessed').removeClass('unprocessed');

  qm_load_quote(current_quote);
}

function qm_save_close_quote(is_interactive){
  if (is_interactive){
    // If there's no items in the current quote, don't close it
    if (quotes[current_quote].items.length && quotes[current_quote].status){
      // Are you sure?
      $("#qm-dialog-confirm-close" ).dialog({
          resizable: false,
          height:200,
          width: 420,
          modal: true,
          buttons: {
          Cancel: function() {
            $(this).dialog( "close" );
          },
          "Save & Close quote": function() {
            $(this).dialog( "close" );
            qm_save_close_quote(false);
          }
        }
      });
      $('.ui-dialog button:last').css({'float': 'right', marginRight: '-5px'});
    }else if(!quotes[current_quote].status){
      // If the quote is already closed, you can't do that!
      $( "#qm-dialog-close-alert" ).dialog({
        resizable: false,
        height: 140,
        modal: true
      });
    }else{ // No items in open quote
      $( "#qm-dialog-close-alert-empty" ).dialog({
        resizable: false,
        height: 130,
        modal: true
      });
    }
  }else{ // Non-interactive.. just do it!
    quotes[current_quote].status = 0; // Disable current
    quotes.unshift(qm_get_empty_default()[0]); // Add new default
    quotes[0].name = "Custom Quote #" + quotes.length; // Change its name
    qm_render_load_list();
    qm_load_quote(0);
    qm_save_cookie();
    return true;
  }
}

function qm_render_rows(quote_id){
  $('tbody', $qm_table).empty();

  // Setup the product table data row placeholders
  $.each(quotes[quote_id].items, function(i, val){
    if (val.num){ // If it's an invalid entry, ignore it
      $('tbody', $qm_table).append($('<tr>').data('part', val).addClass('part-' + val.num + ' part-loading'));
      $('<td>')
        .attr('colspan', 7)
        .text('Loading ' + val.num)
        .appendTo($('tbody tr:last', $qm_table));
    }
  });

  //qm_table_striping();

  // Defered AJAX loading of the contents
  $('tr.part-loading').each(function(){
    var part = $(this).data('part');

    // If the product isn't in the cache, try and get it
    if (qm_product_cache[part.num] == undefined){
      $.getJSON("/products/product-json/" + part.num, function(data, status, xhr){
        if (data.status == 'valid'){
          qm_product_cache[data.part] = data;
          qm_render_row(data);
        }else{
          $('tr.part-' + data.part)
            .removeClass('part-loading')
            .html('Error loading part');
        }
      });
    }else{
      // Otherwise, load it from the cache
      qm_render_row(qm_product_cache[part.num]);
    }

  });
}

function qm_render_row(json){
  var $row = $('tr.part-' + json.part);
  var closed = !quotes[current_quote].status;
  var price = parseInt(json.price.substr(1));

  $row.html('')
   .append(
     $('<td>').addClass('qm-part-select').append($('<input>').attr('type', 'checkbox').attr('disabled', (closed ? 'disabled' : '')))
   )
   .append(
     $('<td>').addClass('qm-part-image').append($('<img>').attr('src', json.image.thumb).attr('largesrc', json.image.large))
   )
   .append(
     $('<td>').addClass('qm-part-desc').append(json.title)
   )
   .append(
     $('<td>').addClass('qm-part-num').text(json.part)
   )
   .append(
     $('<td>').addClass('qm-part-qty').append((closed ? $row.data('part').qty : $('<input>').attr('type', 'text').attr('value', $row.data('part').qty)))
   )
   .append(
     $('<td>').addClass('qm-part-price').data('price', price).text(json.price)
   )
   .append(
     $('<td>').addClass('qm-part-total').text((price ? '$ ' + $.format.number(price * $row.data('part').qty, '#,###') : 'N/A'))
   )
     .removeClass('part-loading');


   // Bind change and numeric only for qty textbox
  $('.qm-part-qty input', $row).keydown(function(event) {
    var $qty = $(this);
    if ( event.keyCode == 38 ) { // Up Arrow
      var u = parseInt($(this).val())+1;
      if (u >= 9999) u = 9999;
      $qty.val(u).change();
    }

    if (event.keyCode == 40 ) { // Down Arrow
      var d = parseInt($(this).val())-1;
      if (d <= 1) d = 1;
      $qty.val(d).change();
    }

    if ( $.inArray(event.keyCode, [36, 35, 46, 8, 9, 37, 39]) != -1 ) {
      // Do nothing!
      window.setTimeout(function(){$qty.change()}, 1);
    } else {
      if (event.keyCode < 95) {
        if (event.keyCode < 48 || event.keyCode > 57 ) {event.preventDefault();}else{window.setTimeout(function(){$qty.change()}, 1);
        }
      } else {
        if (event.keyCode < 96 || event.keyCode > 105 ) {event.preventDefault();}else{window.setTimeout(function(){$qty.change()}, 1);
        }
      }
    }
   }).bind('change', function(){
     // Update the total if the price is valid
     if (isNaN($(this).val())){$(this).val(0);}

     var qty = $(this).val();
     var total = $('.qm-part-price', $row).data('price') * qty;
     if (total){
       $('.qm-part-total', $row).text('$ ' + $.format.number(total, '#,###'));
     }

     // Update the quote object and save the cookie
     $.each(quotes[current_quote].items, function(i, part){
       if (part.num == json.part){
         part.qty = qty;
       }
     });
     qm_update_tally();
     qm_save_cookie();
   }).focus(function(){this.select();});

   $('.qm-part-qty input', $row).change();
}

function qm_render_load_list(){
  $('#quote_list').empty();

  $.each(quotes, function(i, quote){
    $('<a>')
      .attr('href', '#quote_'+i)
      .data('id', i)
      .attr('title', 'Click to load this quote')
      .addClass('quote_'+i)
      .click(function(e){e.preventDefault();qm_load_quote($(this).data('id'))})
      .html(quote.name +
        ' - ' +
        $.format.date(new Date(Date.parse(quote.date)), qm_formats.display_short) +
        (quote.status ? ' [open] ' : ' [closed] ') +
        '<strong title="Edit quote name">(edit)</strong>'
      )
      .appendTo($('#quote_list'));
  });

  $('#quote_list strong').click(function(event){
    var id = $(this).parent().data('id');
    qm_edit_quote(true, id, quotes[id].name);
    event.preventDefault();
  });
}

function qm_delete_quote(is_interactive){
  if (is_interactive){ // Show the confirmation dialogs
    if (quotes[current_quote].items.length){
      $("#qm-dialog-confirm" ).dialog({
          resizable: false,
          height:195,
          modal: true,
          buttons: {
          Cancel: function() {
            $(this).dialog( "close" );
          },
          "Delete quote": function() {
            $(this).dialog( "close" );
            qm_delete_quote(false);
          }
        }
      });

      $('.ui-dialog button:last').css({'float': 'right', marginRight: '-5px'});
    }else{
     // Don't let them delete an open quote with no items
     $( "#qm-dialog-delete-alert-empty" ).dialog({
        resizable: false,
        height: 130,
        modal: true
      });
    }
  }else{ // Actually delete the quote
    quotes.splice(current_quote, 1);
    if (quotes.length == 0){
      quotes = qm_get_empty_default();
    }else if(current_quote == 0){
      // If deleting the current (but not the only), create a new one
      qm_save_close_quote(false);
    }
    qm_render_load_list();
    qm_load_quote(0);
  }
}

function qm_load_quote(quote_id){
  current_quote = quote_id;

  $('#qm-print-date').text(quotes[quote_id].date);

  var closed = !quotes[quote_id].status;

  $('a.qm-remove-checked').toggle(!closed);
  $('.qm-head-1 input').attr('disabled', (closed ? 'disabled' : ''));


  $('#quote_list a').removeClass('selected');
  $('#quote_list a.quote_'+quote_id).addClass('selected')

  $('#quote_details h3').text(quotes[quote_id].name);

  $('#qm-quote-title span.name').text(quotes[quote_id].name);

  qm_update_tally();
  qm_render_rows(quote_id);
  qm_save_cookie();
}

function qm_table_striping(){
  $('tbody tr', $qm_table).removeClass('odd');
  $('tbody tr:nth-child(odd)', $qm_table).addClass('odd');
}

function qm_get_example_data(){
  return [
    {
      name: 'Custom Quote #2',
      date: '2011-04-12T06:05:53',
      status: 1,
      items: [{num: 'ATCRBI-BW5010', qty: 1, price: '20'}, {num: 'ATCRBI-BW6010', qty: 10, price: '40'}, {num:'ATCRBI-SW9030', qty: 22, price: '64'}, {num: 'CFNW-0133-01', qty: 1, price: '128'}]
    },
    {
      name: 'Custom Quote #1',
      date: '2010-12-12T09:28:53',
      status: 0,
      items: [{num: 'ATCRBI-SW9030', qty: 12, price: '40'}, {num: 'CFBI-0133-04', qty: 10, price: '65'}, {num:'CFNW-0133-01', qty: 3, price: '42'}]
    }
  ];
}

function qm_get_empty_default(){
  return [
    {
      name: 'Custom Quote #1',
      date: $.format.date(new Date(), qm_formats.storage),
      status: 1,
      items: []
    }
  ];
}

function qm_get_object(){

  // TODO: Initiate a transfer handoff from anon to logged in
  if (logged_in){
    // Serverside data
    var data = '';

    try {
      data = $.parseJSON(data.replace(/&#123;/g, "{").replace(/&#125;/g, "}"));
    }catch(err){}

    if (data instanceof Array){
      quotes = data;
    }else{
      quotes = qm_get_empty_default();
      qm_save_cookie();
    }

    /*$.get('/quote/jsonio', function(data) {
      data = $.parseJSON(data.replace(/&#123;/g, "{").replace(/&#125;/g, "}"));
      if (data[0].name){
        quotes = data;
      }else{
        quotes = qm_get_empty_default();
        qm_save_cookie();
      }
    });*/
  }else{
    // If we fail at loading our previous quotes, clear the bad cookie
    try {
      quotes = $.parseJSON($.cookie('quote_manager'));
    }catch(err){}

    // Invalid or inparsable cookie
    if (!quotes) {
      qm_delete_cookie();
      quotes = qm_get_empty_default();
      qm_save_cookie();
    }
  }

}

function qm_save_cookie(){
  var quotes_json_string = JSON.stringify(quotes);

  // Only update if there's an actual change
  if (qm_json_buffer != quotes_json_string){
    if (logged_in){
      $.post("/quote/jsonio", {json: quotes_json_string});
    }else{
      $.cookie('quote_manager', quotes_json_string, cookie_settings);
    }
    qm_update_tally();
    qm_json_buffer = quotes_json_string;
    return true;
  }
  return false;
}

function qm_delete_cookie(json_object){
  if (!logged_in){
    $.cookie('quote_manager', null, cookie_settings);
  }
}

function qm_remove_part(part_num, skip_save){
  var part_index = -1;
  $.each(quotes[current_quote].items, function(i, part){
    if (part.num == part_num) {
      part_index = i;
    }
  });

  if (part_index !=-1) {
    quotes[current_quote].items.splice(part_index, 1);
    if (!skip_save){qm_save_cookie();}
  }
}

// Bound function for remove checked click
function qm_remove_checked(event){
  if (!quotes[current_quote].status){return;}

  event.preventDefault();

  var removed = [];
  var part_num = '';

  $('.qm-part-select input:checked').each(function(){
    part_num = $(this).parents('tr').data('part').num;
    qm_remove_part(part_num, true);
    removed.push(part_num);
  });
  if (removed.length){
    qm_render_rows(current_quote);
    qm_set_toast('Removed ' + removed.length + ' item' + (removed.length !=1 ? 's' : '' ) + ' from quote', removed.join(', '));
    qm_save_cookie(); // Save the lot -after- removing all of them
  }else{
    qm_set_toast('Select at least one item to remove it', '');
  }
}

function qm_add_part(part_num, price, skip_save){
  if (qm_no_dupes(part_num)){
    quotes[current_quote].items.push({num: part_num, qty: 1, price: parseFloat(price)});
    if (!skip_save){qm_save_cookie();}
    return true;
  }else{
    return false;
  }
}

function qm_no_dupes(pn) {
  var no_dupe = true;
  $.each(quotes[current_quote].items, function(i, part){
    if (part.num == pn){
      no_dupe = false;
    }
  });
  return no_dupe;
}

// Update the running tally on the top
function qm_update_tally(){
  var total_price = 0;
  var cprice = 0;
  var exact_price = true;

  if (!quotes[current_quote]){
    quotes = qm_get_empty_default();
  }

  var plural = (quotes[current_quote].items.length != 1 ? 's' : '');

  $.each(quotes[current_quote].items, function(i, part){
    if (qm_product_cache[part.num]){
      cprice = parseInt(qm_product_cache[part.num].price.substr(1));

      if (cprice > 0){
        total_price+= part.qty * cprice;
      }

    }else{
      if (part.price){
        total_price+= part.qty * part.price;
      }
    }
  });

  total_price = '$ ' + $.format.number(total_price, '#,###');

  // Top tally
  $('.num', $qm_total).text(quotes[current_quote].items.length + ' item' + plural);
  $('.price', $qm_total).text((exact_price ? '' : '~') + total_price)
    .attr('title', (exact_price ? 'Current Quote' : 'Click to load precise total price'));

  // Table header tally
  $('.quote-table-bar-top span.num').text(quotes[current_quote].items.length);

  // Quote desc tally
  $('#quote_details div').text("This budgetary quote was generated on %date.\n\
  It consists of %num line item%plural totaling %price. Please note that this amount\n\
  does not include applicable sales tax or shipping charges. Contact an Atlas Sales\n\
  representative for a firm and fixed price and delivery information."
    .replace(/%date/gi, $.format.date(new Date(Date.parse(quotes[current_quote].date)), qm_formats.display_long))
    .replace(/%num/gi, quotes[current_quote].items.length)
    .replace(/%price/gi, total_price)
    .replace(/%plural/gi, plural)
    );

}

// Bound to dropdown in product pages, adds all selected products
function qm_quote_batch_add(){
  var added = [];
  $('.product-list-item .product-checkbox input:checked').each(function(){
    var part = $(this).parent().siblings('.part-number').text();
    var price = parseInt($('#prod_'+part+' .product-price').text().replace('$', ''));
    if (qm_add_part(part, price, true)){added.push(part);}
  });

  if (added.length){
    qm_set_toast(added.length + ' item' + (added.length !=1 ? 's' : '') + ' added to current quote', added.join(', '));
    qm_save_cookie(); // Save the lot -after- adding all of them
  }else{
    qm_set_toast('Select at least one product to add it to the current quote', '');
  }
}

// Bound function for product add to quote link clicks
function qm_quote_link_click(){
  var part = $(this).attr('href').split('_')[1];
  var name = $('#prod_'+part+' .product-name').text();
  var price = parseInt($('#prod_'+part+' .product-price').text().replace('$', ''));
  if (qm_add_part(part, price)){
    qm_set_toast(part + ' added to current quote', name + ' added');
  }else{
    qm_set_toast(part + ' already exists in current quote', '');
  }
  return false; // Cancel Click
}

// General Toast message function
function qm_set_toast(title, desc){
  $('h2', $toast).text(title);
  $('div', $toast).html(desc);

  $toast.slideDown('slow', function(){window.setTimeout(function(){$toast.slideUp('slow');}, 3000);
  });
}

function qm_edit_quote(is_interactive, index, name){
  if (is_interactive){ // Show the confirmation dialogs
      $("#qm-dialog-edit-quote" ).dialog({
          resizable: false,
          height:175,
          modal: true,
          buttons: {
          Cancel: function() {
            $(this).dialog( "close" );
          },
          "Update quote": function() {
            $(this).dialog( "close" );
            qm_edit_quote(false, index, $('input', this).val());
          }
        }
      });
      $('.ui-dialog button:last').css({'float': 'right', marginRight: '-5px'});
      $('.ui-dialog input').val(name).select();
  }else{ // Actually delete the quote
    if ($.trim(name)){ // Fail silently on empty name
      quotes[index].name = name;
      qm_render_load_list();
      qm_load_quote(current_quote);
    }
  }
}
