/***
 * myRepLunch
 * 
 * 
 */

/***
 * home 
 */


var n;
var p;
var p1;

function ValidatePhoneOffice(){
p=p1.value

if(p.length==3){
	pp=p;
	d4=p.indexOf('(')
	d5=p.indexOf(')')
	if(d4==-1){
		pp=""+pp;
	}

	if(d5==-1){
		pp=pp+"-";
	}
	$('office_phone').value="";
	$('office_phone').value=pp;
}

if(p.length>3){
	d1=p.indexOf('-')
	d2=p.indexOf('-')
	if (d2==-1){
		l30=p.length;
		p30=p.substring(0,4);
		p30=p30+"-"
		p31=p.substring(4,l30);
		pp=p30+p31;
		$('office_phone').value="";
		$('office_phone').value=pp;
	}
	}

if(p.length>5){
	p11=p.substring(d1+1,d2);
	if(p11.length>3){
	p12=p11;
	l12=p12.length;
	l15=p.length
	p13=p11.substring(0,3);
	p14=p11.substring(3,l12);
	p15=p.substring(d2+1,l15);
	$('office_phone').value="";
	pp=""+p13+"-"+p14+p15;
	$('office_phone').value=pp;
	}
	l16=p.length;
	p16=p.substring(d2+1,l16);
	l17=p16.length;
	if(l17>3&&p16.indexOf('-')==-1){
		p17=p.substring(d2+1,d2+4);
		p18=p.substring(d2+4,l16);
		p19=p.substring(0,d2+1);
    pp=p19+p17+"-"+p18;
	$('office_phone').value="";
	$('office_phone').value=pp;
	//obj1.value="";
	//obj1.value=pp;
	}
}
//}
setTimeout(ValidatePhoneOffice,100)
}

function ValidatePhone(){
p=p1.value

if(p.length==3){
	pp=p;
	d4=p.indexOf('(')
	d5=p.indexOf(')')
	if(d4==-1){
		pp=""+pp;
	}

	if(d5==-1){
		pp=pp+"-";
	}
	//$('rep_phone').value="";
	//$('rep_phone').value=pp;
}

if(p.length>3){
	d1=p.indexOf('-')
	d2=p.indexOf('-')
	if (d2==-1){
		l30=p.length;
		p30=p.substring(0,4);
		p30=p30+"-"
		p31=p.substring(4,l30);
		pp=p30+p31;
		//$('rep_phone').value="";
		//$('rep_phone').value=pp;
	}
	}

if(p.length>5){
	p11=p.substring(d1+1,d2);
	if(p11.length>3){
	p12=p11;
	l12=p12.length;
	l15=p.length
	p13=p11.substring(0,3);
	p14=p11.substring(3,l12);
	p15=p.substring(d2+1,l15);
	$('rep_phone').value="";
	pp=""+p13+"-"+p14+p15;
	$('rep_phone').value=pp;
	}
	l16=p.length;
	p16=p.substring(d2+1,l16);
	l17=p16.length;
	if(l17>3&&p16.indexOf('-')==-1){
		p17=p.substring(d2+1,d2+4);
		p18=p.substring(d2+4,l16);
		p19=p.substring(0,d2+1);
    pp=p19+p17+"-"+p18;
	$('rep_phone').value="";
	$('rep_phone').value=pp;
	//obj1.value="";
	//obj1.value=pp;
	}
}
//}
setTimeout(ValidatePhone,100)
}

function getIt(m){
n=m.name;
p1=m
ValidatePhone()
}
function getItOffice(m){
n=m.name;
p1=m
ValidatePhoneOffice()
}



function showOverlay(type) {
  var types = [ 'reps', 'offices', 'restaurants' ]
  jQuery.each(types, function(k, v) {
    if (type == v) { jQuery('#' + v + '-overlay').show(); }
    else { jQuery('#' + v + '-overlay').hide(); }
  });
  return
} 

/***
 * offices/new
 */

// create form fields for prescribers and nurses
function createEmployeeFields(type) {
  var existing = jQuery('[class=' + type + '_fields]').length;
  var requested = jQuery('#num_' + type).val();
  var count = requested - existing;
  
  // get rid of any existing rows
  for (j = count; j < 0; j++) {
    i = existing + j;
    jQuery('#' + type + '_fields_' + i).remove();
  }
  
  // add new rows
  for (j = count; j > 0; j--) {
    i = requested - j;
    
    var pfname = jQuery('#clone_' + type + '_first_name').clone();
    pfname.attr('id', type + '_first_name_' + i);
    pfname.attr('name', type + '_first_name[]');
    jQuery('#clone_' + type).before(pfname);
    
    var plname = jQuery('#clone_' + type + '_last_name').clone();
    plname.attr('id', type + '_last_name_' + i);
    plname.attr('name', type + '_last_name[]');
    jQuery('#clone_' + type).before(plname);
    
    var ptitle = jQuery('#clone_' + type + '_title').clone();
    ptitle.attr('id', type + '_title_' + i);
    ptitle.attr('name', type + '_title[]');
    jQuery('#clone_' + type).before(ptitle);
    
    var pdesc = jQuery('#clone_' + type + '_description').clone();
    pdesc.attr('id', type + '_description_' + i);
    pdesc.attr('name', type + '_description[]');
    jQuery('#clone_' + type).before(pdesc);
    
    // create a row out of newly created fields
    jQuery('[id^=' + type + '_][id$=_' + i + ']').wrap('<div class="' + type + '_cell_' + i + '"></div>');
    jQuery('[class=' + type + '_cell_' + i + ']').wrapAll('<div id="' + type + '_fields_' +  i + '" class="' + type + '_fields"></div>');
  }
  
  return;
}

/***
 * reps/new
 */

function addProduct() {
  var num_products = jQuery('input[type=hidden][name^=products]').length;
  var product_name = jQuery('#product_name').val();
  jQuery('#product_name').val('');
  jQuery('#products').prepend('<li id="product_' + num_products + '"></li>');
  jQuery('#product_' + num_products).prepend('<input name="products[]" type="hidden" value="' + product_name + '" />');
  jQuery('#product_' + num_products).prepend(product_name + ' <a href="#" onclick="deleteProduct(' + num_products + '); return false;">Delete</a>');
  return;
}

function deleteProduct(i) {
  return jQuery('#product_' + i).remove();
}

function copyRepCreditCard() {
  jQuery('#rep_card_first_name').val(jQuery('#rep_first_name').val());
  jQuery('#rep_card_last_name').val(jQuery('#rep_last_name').val());
  jQuery('#rep_billing_address').val(jQuery('#rep_address').val());
  jQuery('#rep_billing_city').val(jQuery('#rep_city').val());
  jQuery('#rep_billing_state_id').val(jQuery('#rep_state_id').val());
  jQuery('#rep_billing_zip').val(jQuery('#rep_zip').val());
  return;
}

function clearRepCreditCard() {
  jQuery('#rep_card_first_name').val('');
  jQuery('#rep_card_last_name').val('');
  jQuery('#rep_card_type').val('');
  jQuery('#rep_card_number').val('');
  jQuery('#rep_card_expiration_month').val('');
  jQuery('#rep_card_expiration_year').val('');
  jQuery('#rep_card_cvv').val('');
  jQuery('#rep_billing_address').val('');
  jQuery('#rep_billing_city').val('');
  jQuery('#rep_billing_state_id').val('');
  jQuery('#rep_billing_zip').val('');
  return;
}

/***
 * lunches/new
 */

// add item to order and calculate new totals
// TODO consider using the clone/wrap approach from above
function addMenuItemToOrder(menu_item_id) {
  var num_menu_items = jQuery('input[type=hidden][name^=lunches_menu_items_id]').length;
  var row_id = 'menu_item_' + num_menu_items;
  var menu_item_name = jQuery('#menu_item_' + menu_item_id + '_name').html();
  var menu_item_price = jQuery('#menu_item_' + menu_item_id + '_price').html();
 // var menu_item_quantity = jQuery('#menu_item_' + menu_item_id + '_quantity').value();
  
  jQuery('#blank_menu_item').after('<tr id="' + row_id + '"></tr>');
  
  var quantity_cell_html = '<input name="lunches_menu_items_quantity[]" type="text" value="1" style="width: 20px;" id="menu_item_' + menu_item_id + '_quantity" class="small" onkeyup="calculateQuan(this.value, ' + menu_item_id + ', \''+row_id+'\')" />';
  jQuery('#' + row_id).append('<td>' + quantity_cell_html + '</td>');
  
 // var name_cell_html = menu_item_name + '<br /><textarea name="lunches_menu_items_description[]" rows="2"></textarea>';
  var name_cell_html = menu_item_name;
 jQuery('#' + row_id).append('<td class="small">' + name_cell_html + '</td>');
  
  var price_cell_html = menu_item_price;
  var priccy = parseFloat(menu_item_price.slice(1));  jQuery('#' + row_id).append('<td class="small" id="lunches_menu_items_price[]">' + price_cell_html + '<div style="display: none;"><span id ="' + row_id + '_upprice">' + priccy + '</span></div></td>');
  //alert ('<td class="small" id="lunches_menu_items_price[]">' + price_cell_html + '<div style="display:none;"> <input type="hidden" id ="menu_item_' + menu_item_id + '_upprice" value =' + priccy + '/> </div></td>');
  var delete_cell_html = '<input type="button" title="Remove" class="remove-button" onclick="removeMenuItemFromOrder(\'' + row_id + '\', ' + menu_item_id + ')" style="font-size: .89em; width: " />';
      delete_cell_html += '<input name="lunches_menu_items_id[]" type="hidden" value="' + menu_item_id + '" />';
  jQuery('#' + row_id).append('<td>' + delete_cell_html + '</td>');
  
  var subtotal = parseFloat(jQuery('#menu_items_subtotal').html());
  //var tip = parseFloat(jQuery('#lunch_tip').val());
  var fee = parseFloat(jQuery('#del_fee').val());
  var mins = parseFloat(jQuery('#del_min').val());
  var tax = parseFloat(jQuery('#tax').val());
    if (tax <= 0){tax = 1;}
  tax = tax / 100;
  var menu_item_price = parseFloat(menu_item_price.slice(1));
  var new_subtotal = subtotal + menu_item_price;
  var tip_amount = new_subtotal * 0.15;
  var tax_amount = new_subtotal * tax;
  var new_total = new_subtotal + tip_amount + fee + tax_amount;
  if (new_subtotal > mins) {jQuery('#lunch_submit').removeAttr("disabled");
  jQuery('#min_met').hide();
  }
  
  jQuery('#menu_items_subtotal').html(new_subtotal.toFixed(2));
  jQuery('#menu_items_tip').html(tip_amount.toFixed(2));
  jQuery('#lunch_tip').val(tip_amount.toFixed(2));
  jQuery('#menu_items_tip2').html(tip_amount.toFixed(2));
  jQuery('#menu_items_del_fee').html(fee.toFixed(2)); 
  jQuery('#menu_items_del_fee2').val(fee.toFixed(2)); 
  jQuery('#menu_items_tax_amount').html(tax_amount.toFixed(2)); 
  jQuery('#menu_items_tax_amount2').val(tax_amount.toFixed(2)); 
  jQuery('#menu_items_total').html(new_total.toFixed(2));
  
  return;
}

// remove item from order and calculate new totals
function removeMenuItemFromOrder(row_id, menu_item_id) {

  var subtotal = parseFloat(jQuery('#menu_items_subtotal').html());
  //var tip = parseFloat(jQuery('#lunch_tip').val());
  var menu_item_price = parseFloat(jQuery('#menu_item_' + menu_item_id + '_price').val());
  var fee = parseFloat(jQuery('#del_fee').val());
  var mins = parseFloat(jQuery('#del_min').val());
  var price_display = parseFloat(jQuery('#' + row_id + '_upprice').html());
  var tax = parseFloat(jQuery('#tax').val());
  var quan = parseFloat(jQuery('#menu_item_' + menu_item_id + '_quantity').val());
    if (tax <= 0){tax = 1;}
  tax = tax / 100;
  //var menu_item_price = parseFloat(menu_item_price.slice(1));
 
  var menu_deleted = menu_item_price * quan;
  var new_subtotal = subtotal - price_display;
  var tip_amount = new_subtotal * 0.15;
  var tax_amount = new_subtotal * tax;
  var new_total = new_subtotal + tip_amount + fee + tax_amount;
 // var new_total = new_subtotal + tip;
  var mins = parseFloat(jQuery('#del_min').val());
  
  //

 if (isNaN(new_subtotal)) { new_subtotal = 0; }
 if (new_subtotal <= 0) { new_subtotal = 0; }
 if (isNaN(new_total)) { new_total = 0; }
 if (isNaN(tax_amount)) { tax_amount = 0; }
 if (tax_amount <= 0) { tax_amount = 0; }
 if (new_total<= 0) { new_total = 0; }
 if (isNaN(tip_amount)) { tip_amount = 0; }
 if (tip_amount<=0) { tip_amount = 0; }
  //
  jQuery('#menu_items_subtotal').html(new_subtotal.toFixed(2));
  jQuery('#menu_items_total').html(new_total.toFixed(2));
  jQuery('#menu_items_tip').html(tip_amount.toFixed(2));
  jQuery('#lunch_tip').val(tip_amount.toFixed(2));
  jQuery('#menu_items_tip2').html(tip_amount.toFixed(2));
  jQuery('#menu_items_tax_amount').html(tax_amount.toFixed(2));
  jQuery('#menu_items_tax_amount2').val(tax_amount.toFixed(2)); 
  jQuery('#' + row_id).remove();
  
  if (new_total < mins) {jQuery('#lunch_submit').attr("disabled","disabled");
  jQuery('#min_met').show();
  }
  return;
}

//
function calculateTip() {
  var subtotal = parseFloat(jQuery('#menu_items_subtotal').html());
  //var tip = parseFloat(jQuery('#lunch_tip').val());
  if (isNaN(tip)) { tip = 0; }
  var fee = parseFloat(jQuery('#del_fee').val());
  var tax = parseFloat(jQuery('#tax').val());
    if (tax <= 0){tax = 1;}
  tax = tax / 100;
  var tax_amount = subtotal * tax;
  var total = subtotal + tip + fee + tax_amount;
  jQuery('#menu_items_total').html(total.toFixed(2));
  return;
}

function calculateQuan(qut, menu_item_id, row_id)  {
  var subtotal = parseFloat(jQuery('#menu_items_subtotal').html());
  var quan = (Math.round(qut));
  var menu_item_price = parseFloat(jQuery('#menu_item_' + menu_item_id + '_price').html().slice(1));
  var price_display = parseFloat(jQuery('#' + row_id + '_upprice').html());
  if (isNaN(subtotal)) { subtotal = 0; }

  var fee = parseFloat(jQuery('#del_fee').val());
  var mins = parseFloat(jQuery('#del_min').val());
  var tax = parseFloat(jQuery('#tax').val());
    if (tax <= 0){tax = 1;}
  tax = tax / 100;
  

  //calculate totals

//get other item totals  
 
  //var new_total = new_subtotal + tip + fee + tax_amount;
 // var new_total = new_subtotal + tip;

  if (isNaN(quan)) { quan = 0; }
  if (quan <=0) { quan = 0; }
  
  var new_subtotal = subtotal - price_display;
  
  //takes the existing subtotal out of the price
   if (isNaN(new_subtotal)) { new_subtotal = 0; }
   if (new_subtotal <= 0 ) { new_subtotal = 0; }
  
  var new_price = menu_item_price * quan;
  //calculates new total * price
 

  //var total = new_subtotal + new_price;
  //var tip = parseFloat(jQuery('#lunch_tip').val());
  var subbs = new_price + new_subtotal;
  //adds new price to subtotal
  var tax_amount = subbs * tax;
  var tip_amount = subbs * 0.15;
  var total = tip_amount + fee + tax_amount + subbs;
  
  if (total <= 0) {total = 0;}
   
  jQuery('#menu_items_subtotal').html(subbs.toFixed(2));
  jQuery('#menu_items_total').html(total.toFixed(2));
  jQuery('#' + row_id + '_upprice').html(new_price.toFixed(2));
  jQuery('#menu_items_tip').html(tip_amount.toFixed(2));
  jQuery('#menu_items_tip2').html(tip_amount.toFixed(2));
  jQuery('#lunch_tip').val(tip_amount.toFixed(2));
  jQuery('#menu_items_tax_amount').html(tax_amount.toFixed(2)); 
  jQuery('#menu_items_tax_amount2').val(tax_amount.toFixed(2)); 
    if (total < mins) {jQuery('#lunch_submit').attr("disabled","disabled");
  jQuery('#min_met').show();
  }
  if (total > mins) {jQuery('#lunch_submit').removeAttr("disabled");
  jQuery('#min_met').hide();
  }
  return;
}

//
function selectOffice() {
  var officeId = jQuery('#office_id').val();
  if (officeId != '') {
    var date = jQuery('#lunch_date').val();
    location.href = '/lunches/new?date=' + date + '&office_id=' + officeId;
  }
}

//
function selectOfficesByTime(token) {
  var time = jQuery('#lunch_time').val(); 
  new Ajax.Request('/offices/search', 
                   {asynchronous:true, evalScripts:true, 
                    parameters:'search[conditions][arrival_time]=' + time + '&authenticity_token=' + encodeURIComponent(token)}
                  );
  return false;
}

//
function newOffice() {
  jQuery('#office_id').hide();
  jQuery('#lunch_office_fields').show();
}


