var TAX_RATE = 0.0975;

function formatCurrency(amount) {
    var i = parseFloat(amount);
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}

$(function() {
  // textile
  $('.textile a').attr('target', '_blank')
  
  // New account (customer)
  $('form#new_customer').submit(function(){
    if ($.trim($(this).find('#customer_first_name').val()) == '') {
      alert('Please enter your first name');
      return false;
    }
    if ($.trim($(this).find('#customer_last_name').val()) == '') {
      alert('Please enter your last name');
      return false;
    }
    if ($.trim($(this).find('#customer_email').val()) == '') {
      alert('Please enter your email');
      return false;
    }
    if ($.trim($(this).find('#customer_password').val()) == '') {
      alert('Please enter your password');
      return false;
    }
    if ($.trim($(this).find('#customer_password_confirmation').val()) == '') {
      alert('Please confirm your password');
      return false;
    }
    if ($.trim($(this).find('#address_street').val()) == '') {
      alert('Please enter your address');
      return false;
    }
    if ($.trim($(this).find('#address_city').val()) == '') {
      alert('Please enter your city');
      return false;
    }
    if ($.trim($(this).find('#address_zip_code').val()) == '') {
      alert('Please enter your zip code');
      return false;
    }
    if ($.trim($(this).find('#customer_am_phone').val()) == '') {
      alert('Please enter your AM phone');
      return false;
    }
    if ($.trim($(this).find('#customer_pm_phone').val()) == '') {
      alert('Please enter your PM phone');
      return false;
    }
    if ($.trim($(this).find('#customer_cell_phone').val()) == '') {
      alert('Please enter your cell phone');
      return false;
    }
  })
  
  // update shopping cart total
  $('select.cart-quantity').change(function() {
    total = 0;
    $('select.cart-quantity').each(function() {
      quantity = $(this).val();
      price = $(this).attr('price');
      dependent_price = $(this).attr('dependent_price');
      total += quantity * price + quantity * dependent_price;
    });
    $('#total').text('$' + formatCurrency(total));
  })
  
  // ajaxify CRUD delete links
  $('.crud_delete_link').click(function() {
    if (!confirm('Are you sure?'))
      return false
    var return_url = $(this).attr('data-return_url');
    $.ajax({
      url: $(this).attr('href'), 
      data: { _method: 'delete' },
      type: 'POST',
      success: function() {
        if (return_url != null) {
          window.location = return_url;
        } else {
          // trim off record identifer and return to "index" page or refresh page
          // example: /admin/clusters/1 => /admin/clusters
          var parts = window.location.pathname.match(/^(.*)\/(\d+)$/)
          window.location = (parts == null) ? window.location : parts[1]
        }
      }
    })
    return false
  })
  
  // Delete menu items from menu
  $('.crud_delete_in_list').click(function() {
    if (!confirm('Are you sure?'))
      return false
    var self = this
    $.ajax({
      url: $(this).attr('href'), 
      data: { _method: 'delete' },
      type: 'POST',
      success: function() {
        $(self).parents('li').hide();
      }
    })
    return false
  })
  
  // sort menu items
  $('#sortable_menu_items').sortable({
    update: function() {
     $.ajax({
       url: window.location.pathname + '/sort_menu_items',
       data: $(this).sortable('serialize', { key: 'menu_item_ids' }),
       type: 'POST'
     })
    }
  })
  
  // search
  $('.search_button').click(function(){
    $('form#search').attr('action', $(this).attr('data-action'))
    $('form#search').submit();
  })
  
  // transactions
  $('a#transactions_show_all').click(function(){
    $('table.transactions tr:not(:first)').show()
    return false
  })
  
  $('a#transactions_show_orders').click(function(){
    $('table.transactions tr:not(:first)').hide()
    $('table.transactions tr.order').show()
    return false
  })
  
  $('a#transactions_show_invoices').click(function(){
    $('table.transactions tr:not(:first)').hide()
    $('table.transactions tr.invoice').show()
    return false
  })
  
  $('a#transactions_show_payments').click(function(){
    $('table.transactions tr:not(:first)').hide()
    $('table.transactions tr.payment').show()
    return false
  })
  
  $('a#transactions_show_credit_memos').click(function(){
    $('table.transactions tr:not(:first)').hide()
    $('table.transactions tr.credit_memo').show()
    return false
  })
  
  // quickbooks
  $('a#sync_settings_advanced_instructions_link').click(function(){
    $('#sync_settings_advanced_instructions').toggle()
    return false
  })
  
  $('a.approve_select_all').click(function(){
    $('table.to_approve').find(':checkbox').attr('checked', 'checked')
    return false
  })
  
  $('a.approve_unselect_all').click(function(){
    $('table.to_approve').find(':checkbox').attr('checked', '')
    return false
  })
  
  // clusters
  $('form#add_customer_to_cluster_form select').change(function(){
    $(this).parents('form').attr('action', '/admin/customers/' + $(this).val())
  })
  
  $('#add_customer_to_cluster_form').ajaxForm({
    type: 'POST',
    resetForm: true,
    success: function(data) {
      window.location = window.location
    }
  })
  
  $('table#cluster_members a.remove').click(function(){
    var self = this
    if (!confirm('Are you sure?'))
      return false
    $.ajax({
      url: $(this).attr('href'), 
      data: { _method: 'put', 'customer[cluster_id]': '' },
      type: 'POST',
      success: function() {
        $(self).parents('tr').hide();
      }
    })
    return false
  })
  
  // focus first element in form
  $(':text:visible:enabled:first').focus();

	// inventory
	$.each($('#inventory_menus li.inventory_menu'), function(index, element){
		if (index > 5) {
			$(this).hide()
		}
	})
	
	$('a#show_all_inventory_menus').click(function(){
		$('#inventory_menus li.inventory_menu').show()
		$(this).hide()
		return false
	})
  
  // reporting selects
  $('select#menu_id, select#product_id', 'form.report_form').change(function(){
    $(this).parents('form').submit()
  })
  
  $('div.number_in_stock').click(function(){
    var theDiv = $(this)
    var box = $('<input>').addClass('small_inplace').val($(this).text())
    box.appendTo($(this).empty())
    box.blur(function(){
      var number = parseInt($(this).val());
      var product_id = $(this).parents('tr').attr('data-product_id')
      $(theDiv).parents('td').addClass('indicator')
      $(this).hide()
      $.ajax({
        url: '/admin/products/' + product_id,
        data: { _method: 'put', 'product[number_in_stock]': number },
        type: 'POST',
        success: function() {
          $(theDiv).parents('td').removeClass('indicator');
          $(theDiv).text(number).effect('highlight');
          
          // recalculate remaining in stock
          var row = theDiv.parents('tr');
          var total_sold = 0;
          row.find('a.number_sold').each(function(){
            total_sold = total_sold + parseInt($(this).text());
          })
          var new_remaining_in_stock = number - total_sold;
          row.find('.remaining_in_stock').text(new_remaining_in_stock).effect('highlight');
          if (new_remaining_in_stock >= 0)
            row.find('td').removeClass('warning');
        }
      })
    }).focus()
  })
  
  $('div.number_to_sell').click(function(){
    var theDiv = $(this)
    var box = $('<input>').addClass('small_inplace').val($.trim($(this).text()))
    box.appendTo($(this).empty())
    box.blur(function(){
      var number = parseInt($(this).val());
      var menu_id = $(theDiv).attr('data-menu_id')
      var menu_item_id = $(theDiv).attr('data-menu_item_id')
      $(theDiv).parents('td').addClass('indicator')
      $(this).hide()
      $.ajax({
        url: '/admin/menus/' + menu_id + '/menu_items/' + menu_item_id,
        data: { _method: 'put', 'id': menu_id, 'menu_item[number_to_sell]': box.val() },
        type: 'POST',
        success: function() {
          var td = $(theDiv).parents('td');
          td.removeClass('indicator');
          $(theDiv).text(number).effect('highlight');
          
          // recalculate remaining to sell
          new_remaining_to_sell = number - parseInt(td.next().find('a').text());
          td.next().next().find('.remaining_to_sell').text(new_remaining_to_sell).effect('highlight');
        }
      })
    }).focus()
  })
  
  $('form.balance_sync_form select').change(function(){
    $(this).parents('form').submit();
  })
  
  // credit memos
  $('select.credit_memo_product_price').livequery('change', function(){
    var parts = $('option:selected', this).text().match(/- \((.*)\/(.*)\/(.*)\)$/);
    if (parts != null) {
      var total = parseFloat(parts[1]) + parseFloat(parts[2]);
      if (parts[3] == 'T') {
        total = total + (TAX_RATE * total)
      }
      $(this).parents('tr:first').find('.credit_memo_rate').val(formatCurrency(total))
    }
  })
  
  $('a#new_credit_memo_line_item').click(function(){
    var last_line_item = $('#credit_memos .credit_memo:last')
    last_line_item.after(last_line_item.clone());
    return false;
  })
  
  $('form#new_credit_memo').submit(function(){
    if ($(this).find('input.initials').length > 0) {
      if ($.trim($(this).find('input.initials:first').val()) == '') {
        alert('Initial please!');
        return false;
      }
    }
  })
  
  // reset password
  $('a#reset_password').click(function(){
    $('form#reset_password_form')
      .toggle()
      .find('#new_password').focus();
    return false;
  })
  
  $('form#reset_password_form').submit(function(){
    if ($(this).find('input#new_password').val().length < 5) {
      alert('Please type in a password with 5 or more characters.');
      return false;
    }
  })
  
  // orders
  $('td.order_notes a.edit').click(function(){
    $(this).parents('td')
      .find('.order_note, form')
        .toggle()
        .end()
      .find('textarea').focus();
    return false;
  })
  
  $('td.order_notes form').ajaxForm({
  	dataType: 'json',
    success: function(data, status, $form){
			var note = data['note'];
			$form.parents('td')
        .find('.order_note, form')
				  .toggle()
				  .end()
				.find('.note')
					.html(note.replace(/\n/g, '<br/>'))
					.end()
				.find('textarea')
					.text(note)
					.end();
		}
  })
  
  $('td.order_notes a.cancel').click(function(){
    $(this).parents('td').find('.order_note, form').toggle();
    return false;
  })
  
  // admin order screen selects
  $('form.admin_order_form select#customer_id').change(function(){
		var url = '/admin/customers/' + $(this).val() + '.json';
		$('img.ajax_indicator').show();
    $.getJSON(
			url,
			function(data){
				$('img.ajax_indicator').hide();
				var id = data['id'];
				
				// reset current customer
				$('#last_order_info').hide();
				$('input#customer_id, input#order_customer_id', 'form.new_order').val(id);
				$('form.new_credit_memo #customer_id').val(id);
				
				// replace balance info
				$('span.realtime_balance').text('$' + formatCurrency(parseFloat(data['realtime_balance'])));
				$('#admin_order_credit').attr('data-credit', parseFloat(data['realtime_balance']));

				// replace email
				$('span.email').text(data['email']);
				
				// replace addresses
				var options = $.map(data['addresses'], function(a){
					return '<option value="' + a['id'] + '">' + a['street'] + ', ' + a['city'] + ' ' + a['state'] + ' ' + a['zip_code'] + '</option>';
				}).join('\n');
				$('select#order_address_id')
					.empty()
					.append(options);
				
				// replace urls
				$('a[data-url_replace]').filter(function(){
					$(this).attr('href', $(this).attr('data-url_replace').replace(':id', id));
				})
				$('input[data-url_replace]').filter(function(){
					$(this).val($(this).attr('data-url_replace').replace(':id', id));
				})
				
				$('table#customer_vitals').effect('highlight');
			}
		)
  })

  $('form.admin_order_form select#menu_id').change(function(){
    $(this).parents('form').submit();
  })
  $('form#orders_form select#menu_id').change(function(){
    $(this).parents('form').submit();
  })
  
  $('select.admin_order_product_quantity').livequery('change', function(){
    update_admin_order_totals();
  })
  
  $('select.admin_order_product').livequery('change', function(){
    var price = '';
    var deposit_price = '';
    var tax = '';
  
    var parts = $('option:selected', this).text().match(/- \((.*)\/(.*)\/(.*)\)$/);
    if (parts != null) {
      price = parts[1];
      deposit_price = parts[2];
      tax = parts[3] == 'T' ? 'T' : '';
    }
    
    $(this).parents('tr:first')
     .find('.admin_order_product_price').val(price)
     .end()
    .find('.admin_order_product_dependent_price').text(deposit_price)
    .end()
    .find('.admin_order_product_tax').text(tax);
    update_admin_order_totals();
  })
  
  $('input.admin_order_product_price').livequery('blur', function(){
    update_admin_order_totals();
  })
  
  function update_admin_order_totals() {
    var subtotal = 0;
    var deposits = 0;
    var tax = 0;
    var credit = parseFloat($('#admin_order_credit').attr('data-credit'));
    
    // calculate totals
    $('table#admin_order tr.menu_item').each(function(index){
      var quantity = parseFloat($(this).find('select.admin_order_product_quantity option:selected').text());
      var price = parseFloat($(this).find('input.admin_order_product_price').val());
      var dependent_price = parseFloat($(this).find('span.admin_order_product_dependent_price').text());
      var taxable = $(this).find('span.admin_order_product_tax').text();
      if (!isNaN(quantity) && !isNaN(price) && !isNaN(dependent_price)) {
        subtotal = subtotal + (parseFloat(quantity) * parseFloat(price));
        deposits = deposits + (parseFloat(quantity) * parseFloat(dependent_price));
        if (taxable == 'T') {
          tax = tax + (TAX_RATE * parseFloat(quantity) * parseFloat(price))
        }
      }
    })
    
    var total = subtotal + tax +  deposits;
    var net_total = total + credit;
    if (net_total < 0)
      net_total = 0;

    $('#admin_order_subtotal').text('$' + formatCurrency(subtotal));
    $('#admin_order_tax').text('$' + formatCurrency(tax));
    $('#admin_order_deposits').text('$' + formatCurrency(deposits));
    $('#admin_order_total').text('$' + formatCurrency(total));
    $('#admin_order_net_total').text('$' + formatCurrency(net_total));
  }
  
  $('a#override_payment_amount').click(function(){
    $('#order_payment_amount').val('');
    $('#auto_calculate_payment_amount, #manual_payment_amount').toggle();
    return false;
  })
  
  $('a.delete_line_item').click(function() {
    if (!confirm('Are you sure?'))
      return false
    $.ajax({
      url: $(this).attr('rel'), 
      data: { _method: 'delete' },
      type: 'POST',
      success: function() {
        window.location = window.location
      }
    })
    return false
  })
  
  $('a#new_admin_order_line_item').click(function(){
    var last_line_item = $('#admin_order .menu_item:last')
    last_line_item.after(last_line_item.clone());
    return false;
  })
  
  $('form#new_order').submit(function(){
    if ($(this).find('input.initials').length > 0) {
      if ($.trim($(this).find('input.initials:first').val()) == '') {
        alert('Initial please!');
        return false;
      }
    }
    
    if (!confirm('Process order?'))
      return false;
  })
  
  $('form#send_email_template_form').submit(function(){
    if (!confirm('Send email?'))
      return false;
    $(':submit', $(this)).attr('disabled', true);
  })
  
  $('ul#admin_order_screens').tabs()
  
  $('table.sortable').tablesorter() 
});

// http://henrik.nyh.se/2008/05/rails-authenticity-token-with-jquery
$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return;
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
})

// http://ozmm.org/posts/jquery_and_respond_to.html
$.ajaxSetup({'beforeSend':function(xhr){xhr.setRequestHeader("Accept","text/javascript")}})