SLIDE_SPEED = 500;

Array.prototype.blank = function(){return this.length == 0;}
Array.prototype.empty = function(){return this.length == 0;}
Array.prototype.last = function(){return this[this.length-1];}

less = {}
//************************************************
//payments
//************************************************

// add your functions here
function hide_show_payment_categories(clicked){
 if (clicked == 'payment_payment_type_regular_income' && jq('#payment_expense_categories_selector').is(':visible')){ jq('#payment_expense_categories_selector').slideToggle();}
 if (clicked == 'payment_payment_type_regular_income' && jq('#payment_invoice_selector').is(':hidden')){ jq('#payment_invoice_selector').slideToggle();}
 if (clicked == 'payment_payment_type_other_income' && jq('#payment_expense_categories_selector').is(':visible')){ jq('#payment_expense_categories_selector').slideToggle();}
 if (clicked == 'payment_payment_type_other_income' && jq('#payment_invoice_selector').is(':visible')){ jq('#payment_invoice_selector').slideToggle();}
 if (clicked == 'payment_payment_type_interest_income' && jq('#payment_expense_categories_selector').is(':visible')){ jq('#payment_expense_categories_selector').slideToggle();}
 if (clicked == 'payment_payment_type_interest_income' && jq('#payment_invoice_selector').is(':visible')){ jq('#payment_invoice_selector').slideToggle();}
 if (clicked == 'payment_payment_type_expense_refund' && jq('#payment_expense_categories_selector').is(':hidden')){ jq('#payment_expense_categories_selector').slideToggle();}
 if (clicked == 'payment_payment_type_expense_refund' && jq('#payment_invoice_selector').is(':visible')){ jq('#payment_invoice_selector').slideToggle();}
}

function init_payment(){
   jq('#payment_payment_type_regular_income').unbind('click.init_payment').bind('click.init_payment', function(){if (this.checked){hide_show_payment_categories('payment_payment_type_regular_income')}})
   jq('#payment_payment_type_other_income').unbind('click.init_payment').bind('click.init_payment', function(){if (this.checked){hide_show_payment_categories('payment_payment_type_other_income')}})
   jq('#payment_payment_type_interest_income').unbind('click.init_payment').bind('click.init_payment', function(){if (this.checked){hide_show_payment_categories('payment_payment_type_interest_income')}})
   jq('#payment_payment_type_expense_refund').unbind('click.init_payment').bind('click.init_payment', function(){if (this.checked){hide_show_payment_categories('payment_payment_type_expense_refund')}})

   if (jq('#payment_payment_type_regular_income').get(0).checked){hide_show_payment_categories('payment_payment_type_regular_income')}
   if (jq('#payment_payment_type_other_income').get(0).checked){hide_show_payment_categories('payment_payment_type_other_income')}
   if (jq('#payment_payment_type_interest_income').get(0).checked){hide_show_payment_categories('payment_payment_type_interest_income')}
   if (jq('#payment_payment_type_expense_refund').get(0).checked){hide_show_payment_categories('payment_payment_type_expense_refund')}
   if (!jq('#payment_payment_type_regular_income').get(0).checked &&
     !jq('#payment_payment_type_other_income').get(0).checked &&
     !jq('#payment_payment_type_interest_income').get(0).checked &&
     !jq('#payment_payment_type_expense_refund').get(0).checked) {
       jq('#payment_payment_type_other_income').click();
   }

 tooltips();
 setup_fancy_selects();
}
//************************************************
//payments
//************************************************




//************************************************
//deposits
//************************************************
function check_split_payment_count() {
  if( SPLIT_MODE ) jq('#deposit_total, .total_amount_label, #deposit_remainder, .amount_row').show();
  
  if( jq('.split_payment').length > 1 ) {
    jq('.split_payment_tools').show();
  } else {
    jq('.split_payment_tools').hide();
  }
  retotal_payments();
}

function num_or_zero(number) {
  string = new String(number).replace(/[^0-9\.]/g,'');
  f  = parseFloat(string);

  if(isNaN(f))
    return 0;
  else
    return f;
}

function deposit_total() {
  return num_or_zero( jq('#total_amount').val() );
}

function in_cents(dollars) {
  return Math.round(dollars * 100)
}

function in_dollars(cents) {
  return cents / 100;
}

function payment_total() {
  var total = 0;
  jq('.split input.amount').each(function() {
    total += in_cents( num_or_zero(jq(this).val()) );
  })
  return in_dollars(total);
}

function remainder_amount() {
  return in_dollars( in_cents(deposit_total()) - in_cents(payment_total()) );
}

function fmt_currency(number) {
  return number_to_currency(number, {'unit': CURRENCY});
}

function retotal_payments() {
  var actual    = deposit_total();
  var remainder = remainder_amount();
  
  var fmt_actual    = fmt_currency(actual);
  var fmt_remainder = fmt_currency(remainder);
  
  if(SPLIT_MODE) jq('#total_amount').val(payment_total());
  jq('#deposit_total     .amount').html(fmt_actual);
  jq('#deposit_remainder .amount').html(fmt_remainder);
  
  if(remainder == 0) {
    jq('#deposit_remainder').addClass('good').removeClass('bad');
  } else {
    jq('#deposit_remainder').addClass('bad').removeClass('good');
    if(SPLIT_MODE) jq('#deposit_remainder:hidden').blindDown();
  }
  return remainder;
}



function remove_split_payment(sender) {
	var obj = jq(sender).parents('.split_payment');
	var obj_parent = obj.parent();
  obj_parent.fadeOut(function() {
    jq(this).remove();
    check_split_payment_count();
		obj_parent.hide();
  });
}

function expand_split_payment(sender) {
  jq(sender).closest('.split_payment').
    find('.payment_summary').hide().
    siblings('.payment_detail').
    blindDown(SLIDE_SPEED, function() {
      $(this).find('input:first').focus();
    });
    
}

function collapse_split_payment(sender) {
  $(sender).closest('.split_payment').
    find('.payment_summary').show().
    siblings('.payment_detail').blindUp().
    find('.split_payment_form').removeClass('multiple_split_payments');    
}

function hide_show_payment_categories(clicked){
  $('.payment_type_selector').each(function(obj, index){
    var val = jq(this).val().toLowerCase();
    var parent = jq(this).closest('.split_payment');
    switch(val) {
    case 'regular income':
      parent.find(
        '.payment_expense_categories_selector:visible, ' +
        '.payment_invoice_selector:hidden'
      ).slideToggle();
      break;
    case 'interest income':
      parent.find(
        '.payment_expense_categories_selector:visible, ' +
        '.payment_invoice_selector:visible'
      ).slideToggle();
      break;
    case 'expense refund':
      parent.find(
        '.payment_expense_categories_selector:hidden, ' +
        '.payment_invoice_selector:visible'
      ).slideToggle();
      break;
    case 'other income':
    default:
      parent.find(
        '.payment_expense_categories_selector:visible, ' +
        '.payment_invoice_selector:visible'
      ).slideToggle();
    }
  })
}

function toggle_is_paid_fields() {
  var split_payment = jq(this).parents('.split_payment');
  var is_paid_row = split_payment.find('.is_paid_row');
  var invoice_id = split_payment.find('.payment_invoice_id').val();
  
  // hide it back if we're no longer under regular income or no invoice is selected
  if (split_payment.find('.payment_type_selector').val() != 'regular income'
      || invoice_id == ""
      || !invoice_uses_different_currency(invoice_id) ) {
    is_paid_row.hide();
  } else {
    is_paid_row.show();
  }
}

function update_amount(query, amount) {
  jq(query).val(amount).parents('.split_payment').find('.payment_summary .amount').html( fmt_currency(amount) );
}

function split_payment(insert_payment) {
  if( SPLIT_MODE ) {
    collapse_split_payment(jq('#split_payments .payment_detail:visible').parents('.split_payment'));
    insert_payment();
    expand_split_payment(jq('#split_payments .split_payment:last'));
    update_amount('#split_payments input.amount:last', remainder_amount() );
    init_deposits();
  } else {
    SPLIT_MODE = true;
    insert_payment();
    expand_split_payment(jq('#split_payments .split_payment:last'));
    update_amount('#split_payments input.amount:last', remainder_amount() );
    init_deposits();
    check_split_payment_count();
  }
}

function check_deposit_form() {
  if(SPLIT_MODE){
    var remainder = remainder_amount();
    if( Math.abs(remainder) >= 0.01 ) {
      alert(
        'Your split transactions must add up to the total deposit amount of ' + fmt_currency( deposit_total() ) + '. ' +
        'Instead, they add up to ' + fmt_currency( payment_total() ) + '. ' +
        'You are off by ' + fmt_currency( remainder ) + '.'
      );
      return false;
    }
  } else {
    jq('.payment_detail input.amount').val( deposit_total() );
  }
  return true;
}

function init_tasks() {
  if (jq('.task').length == 0) {
    jq('#tasks_list').html('Hoorey -- nothing to do, now get back to work!')
  }
}

function init_deposits(){
  jq('.payment_type_selector').
    unbind('change.payment_type_selector').
    bind('change.payment_type_selector', hide_show_payment_categories);
  
  jq('.is_paid_toggler').
    unbind('change.is_paid_toggler').
    bind('change.is_paid_toggler', toggle_is_paid_fields);
  
  jq('.payment_detail input.title').
    unbind('change.update_title').
    bind('change.update_title', function() {
      val = $(this).val() || 'Untitled';
      $(this).parents('.split_payment').find('.payment_summary .title').html(val);
    });
  
  jq('.payment_detail input.amount, #total_amount').
    unbind('keyup.update_amount').
    bind('keyup.update_amount', function() {
      val = fmt_currency($(this).val());
      $(this).parents('.split_payment').find('.payment_summary .amount').html(val);
      retotal_payments();
    });
  
  hide_show_payment_categories();
  toggle_is_paid_fields();
  check_split_payment_count();
  tooltips();
  setup_fancy_selects();
}
//************************************************
//deposits
//************************************************



function formatCurrency(num, currency, no_negative) {
    num = isNaN(num) || num === '' || num === null ? 0.00 : num;
    if (no_negative) {
      num = num < 0 ? num * -1 : num
    }
    return currency + '' + parseFloat(num).toFixed(2);
}




//************************************************
//expense
//************************************************

 function main_init(){
   jq("#expense_expense_category_id").change(function(){
     jq("#expense_contractor_div").hide();
     jq("#expense_employee_div").hide();
     jq("#expenses_payee_div").hide();
     if (this.options[this.selectedIndex].text == "Contract Labor") {
       jq("#expense_contractor_div").show();
			 jq("#expense_payee_id").val(0);
			 jq("#expense_employee_id").val(0);
     } else if (this.options[this.selectedIndex].text == "Wages") {
       jq("#expense_employee_div").show();
			 jq("#expense_contractor_id").val(0);
			 jq("#expense_payee_id").val(0);
     } else {
       jq("#expenses_payee_div").show();
			 jq("#expense_contractor_id").val(0);
			 jq("#expense_employee_id").val(0);
     }
   });

   jq("#expense_expense_category_id").change();


   jq("#expense_bank_account_id").change(function(){
     if (this.options[this.selectedIndex].text.toLowerCase().indexOf("check") > -1){
       if (jq("#expense_check_number").css('display') == 'none'){
         togger("#expense_check_number");
       }
     }
     else {
       if (jq("#expense_check_number").css('display') != 'none'){
         togger("#expense_check_number");
       }
     }
   });
   jq("#expense_bank_account_id").change();
 }


 jq(function(){
   less.expense_form.init();
 })
//************************************************
//expense
//************************************************










$.fn.nav_dropdowns = function(){
  return this.each(function(){
    var list;
    if ($(this).parent().is('li')) {list = $(this).parent().children('ul');}
    else if ($(this).parent().is('legend')) {list = $(this).parent().parent().children('ul');}
    $(this).children('img').attr('src', '/images/arrow.png');
    $(this).click(function(){
      if ($(this).children('img').attr('src').indexOf('down_arrow') > -1){
        $(this).children('img').attr('src', '/images/arrow.png');
      }
      else {
        $(this).children('img').attr('src', '/images/down_arrow.png');
      }
      list.slideToggle();
    });
  })
}



//function expand_parent(id){
//  $('#' + id).parnt().parent().parent().children('.nav_dropdowns').click();
//}




$.fn.check_toggle = function(){
  return this.each(function(){
    if ($(this).checked()) {$(this).attr({checked: false})}
    else{$(this).attr({checked: true})}
  })
}

jQuery.fn.check = function(){
  return this.each(function(){
    jQuery(this).checker(true);
  })
}
jQuery.fn.uncheck = function(){
  return this.each(function(){
    jQuery(this).checker(false);
  })
}
jQuery.fn.checker = function(check){
  jQuery('#waiter').show();
  var x = this.each(function(){
    jQuery(this).attr({checked: check}).children().checker(check);
  })
  jQuery('#waiter').hide();
  return x
}


jQuery.fn.checked = function(){
  return this.is(':checked');
}


function wait(){$('#waiter').show();}


function recalc_checkbox_clicked(){
  highlight_statement_rows();
  recalc_statement_totals();
}



function highlight_statement_rows(){
	jQuery("#statement_reconcile input[type='checkbox']").parent().parent().css({'background-color': '#ddd'});
	jQuery("#statement_reconcile input:checked").parent().parent().css({'background-color': '#fff'});
}

function number_to_currency(number, options) {
try{
    var options   = options || {};
    var precision = options["precision"] || 2;
    var unit      = options["unit"] || "$";
    var separator = precision > 0 ? options["separator"] || "." : "";
    var delimiter = options["delimiter"] || ",";
  
    var parts = parseFloat(number).toFixed(precision).split('.');
    return unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].toString();

  } catch(e) {
    return number
  }
}

function number_with_delimiter (number, delimiter, separator) {
  try {
    var delimiter = delimiter || ",";
    var separator = separator || ".";
    
    var parts = number.toString().split('.');
    parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter);
    return parts.join(separator);
  } catch(e) {
    return number
  }
}




//fancyselect
function fancy_select(div, clicker, cancel, input_name, input_id, select, url, label, select_id){
  jq('#' + div).prependTo("body");	
  var cleanup_UNIQ_select_creator = function (changeSelection){
    if (changeSelection){
      jQuery("#" + select).val('');
    }
    jQuery("#" + input_id).val('');
    TB_remove();
  }
  jQuery("#" + clicker).click(function(){
	jQuery.ajax({
      url: url + ".js", 
      type: "POST", 
	  data: input_name +'=' + jQuery("#" + input_id).val() + '&select_id=' + select_id, 
      success: function(res){eval(res); cleanup_UNIQ_select_creator(false);},
      error: function(req, status){eval(req.responseText);}
    });
    return false;
  });
  fancy_select_respond_to_change(div, select, label, input_id);
  fancy_select_key_bind(input_id, clicker, cancel);
  fancy_select_cleanup(cancel, cleanup_UNIQ_select_creator, true);
}

function fancy_select_respond_to_change(div, select, label, input_id, height, width){
  if (height == null)
  height = 140; 
  if (width == null)
  width = 500;
  jq("#" + select).change(function(){
    if (jq(this).val() == "add") {
      TB_show(label, "#TB_inline?height="+ height +"&width="+ width +"&inlineId=" + div);
	  try
	  {
        jq("#" + input_id)[0].focus();
	  }
	  catch(e){};
    }
  });
}  



function fancy_select_key_bind(input_id, clicker, cancel){
  jq("#" + input_id).keypress(function(e){
    switch (e.keyCode){
      case 13:
      jQuery("#" + clicker).click();
      return false;
      case 27:
      jQuery("#" + cancel).click();
      break;
    }	
  });
}

function fancy_select_cleanup(cancel, callback, params){
  jq("#" + cancel).click(function(){
    callback(params);
    return false;
  });
}

//fancyselect

















function setup_do_stuff_menu() {
  jq(".do_stuff_pending").each(function() {
    jq(this).removeClass('do_stuff_pending').addClass('do_stuff_menu');
    var menu = jq(this).find('.menu');
    if( menu.length == 1 ) {
      menu.find('.close_submenu_link').click(function() { return close_submenus(); });
      var show_link = menu.parent().find('span').find('a.show_do_stuff_link')
      show_link.click(function() {
        if( menu.is(":hidden") ) {
          close_submenus();
          menu.show();
          show_link.html('<img src="/images/arrow_up.gif" alt="Hide" />').addClass('open');
          jq('#window_click_receiver').show().click(function() { return close_submenus(); });
        } else {
          close_submenus();
        }
        return false;
      });
    }
  });
}

function close_submenus(){
  //document.onclick = null;
  jq('.menu').each(function(){
    var menu = jq(this);
    if (!menu.is(":hidden")){
      menu.toggle();
      menu.parent().find('span').find('a.show_do_stuff_link').html('<img src="/images/arrow_down.gif" alt="Show" />').removeClass('open');
    }
  })
  //jq('#window_click_receiver').hide();
  return false;
}



// TODO: Remove this once jQuery is updated.
jQuery.fn.wrapAll = function(html) {
  if( typeof this[0] == 'undefined' ) { return }
  jQuery(html, this[0].ownerDocument)
  .clone()
  .insertBefore(this[0])
  .map(function(){
    var elem = this;
    while ( elem.firstChild )
      elem = elem.firstChild;
    return elem;
  })
  .append(this);
};

// TODO: Remove this once jQuery is updated.
jQuery.fn.map = function(fn) {
  return this.pushStack(jQuery.map( this, function(elem,i){
    return fn.call( elem, i, elem );
  }));
};







//small aninmations
function highlight(selector, fade){
  if (fade)
  jq(selector).highlightFade({color:'yellow', speed:5000});
  else
  jq(selector).addClass("highlight")
}

function remove(selector){
  highlight(selector);
  jq(selector).fadeOut(SLIDE_SPEED)
}
//small aninmations











jq.fn.less_tabs = function(){
  return this.each(function(){
    var tabs = jq("a", this);
    var div_ids = [];
    var i = 0;
    tabs.each(function(i, a){
	div_ids.push(a.href.split('#')[1]);
    });
	
    jq.each(div_ids,function() {
      var anchor = window.location.href.replace(/^.*\#/,'')
      if (jq(tabs.get(i)).is('.on,.viewing') || anchor == this || anchor == this.replace(/tab_/,'')  ){
        jq(tabs).removeClass('on').removeClass('viewing');
        jq('#' + div_ids.join(',#')).hide();
        jq('#'+ jq(tabs.get(i)).get(0).href.split('#')[1]).show();
        jq(tabs.get(i)).addClass('on').addClass('viewing');
        return false;
      }

      if (i == 0) {jq('#' + this).show(); jq(tabs.get(i)).addClass('on').addClass('viewing');}
      else { jq('#' + this).hide(); jq(tabs[i]).removeClass('on').removeClass('viewing'); }
      i++;
    });

    tabs.each(function(i,a){
      jq(a).bind('click.less_tabs', function(){
        jq(tabs).removeClass('on').removeClass('viewing');
        jq(this).addClass('on').addClass('viewing');
        jq('#' + div_ids.join(',#')).hide();
        jq('#'+ a.href.split('#')[1]).show(); 
        return false;})
    })
  })
}








//message
function async_message(m, d){message(m, d);}
function messages(m, d){message(m, d);}
function msg(m, d){message(m, d);}
function message(message, duration){
    if (duration == undefined){ duration = 3000;}
    if (jq.browser.msie) { jq("#message").css({position: 'absolute'}); }
    jq("#message").text(message).show().check_width();//.center();
    setTimeout('jq("#message").hide().css("width", "");',duration);
    return false;
}
//message


function debug(m){if (typeof console != 'undefined'){console.log(m);}}
function puts(m){debug(m);}


jQuery.fn.center = function(){
  return this.each(function(){
    var win = jq(window).width();
    var width = jQuery(this).width();
    jq(this).css({width: width +'px', left: (win/2 - width/2) + 'px'});
  })
}


jQuery.fn.check_width = function(){
  return this.each(function(){
    var win = jq(window).width();
    var width = jQuery(this).width();
    var height = jQuery(this).height();
    if (width/2 > height || width*2 >= win){ return; }
    jq(this).css({width: width*2 +'px'});
  })
}












//help file
//jq(function(){
  //	jq("#help_file").width(jq(document.body).width()).height(jq(document.body).height()).show();
//})
//help file






















//optional fields
jq(function(){
  if (jq("#options_1_clicker").length > 0) {
    optional_fields("#options_1_clicker", "#options_1", jq('#show_options').val());
  }
})
function optional_fields(clicker, optionals, open){

  if (open.length > 0) {
    jq(optionals).css('display', '')
    jq(clicker).html("Hide Optional Fields:")
  }
  else {
    jq(optionals).css('display', 'none')
    jq(clicker).html("Show Optional Fields:")
  }	
  tog(clicker, optionals, function(){
    if (jq(optionals).css('display') == 'none'){
      jq("#show_options").val('');
      jq(clicker).html("Show Optional Fields:")
    }
    else{
      jq("#show_options").val('1');	
      jq(clicker).html("Hide Optional Fields:")
    }
  });

}
//optional_fields







// 
// 
// //top selector tabs
// function top_selector_tabs(selector){
//     jq('#top_box .tabbr a.active').removeClass('active').hide();
//     jq(selector).addClass('active').show();
// }





//tog
function tog(clicker, toggler, callback, speed){
  if (speed == undefined)
  speed = SLIDE_SPEED
  if (callback)
    jQuery(clicker).bind('click',function(){jQuery(toggler).slideToggle(speed, callback); return false;});
  else                       
    jQuery(clicker).bind('click',function(){jQuery(toggler).slideToggle(speed); return false;});
}
function togger(j, callback, speed){
  if (speed == undefined)
    speed = SLIDE_SPEED
  if(callback)
    jq(j).slideToggle(speed, callback); 
  else 
    jq(j).slideToggle(speed); 
}
//tog









function highlight_fade(id){
  jq("#" + id).animateClass('highlight','', SLIDE_SPEED)
}





//more_or_less
function more_or_less(){
  jq(".more_or_less").each(function(){
    var x = jq(this).attr('id').split('_');
    if (x.length != 4)
      return;
      

    jq(this).click(function(){jq('#_' + x[2]).toggle(); return false;});
    jq(this).click(function(){jq('#_' + x[1]).toggle(); return false;});
//    tog(jq(this), '_' + x[1]);
    
  });
}









//tooltips
function tooltips(){
  jq(".tooltip[title]").map(function (index) {
    jq(this).qtip({content: $(this).attr("title")});
    jq(this).removeAttr('title');
  });
  jq('textarea').autogrow({lineHeight:12});
}





//borders
function draw_borders(){
    return;
  jq(".border").removeClass('border');
//  jq(".border").unwrap().remove();
  jq(".border, :input:not(.no_border):not([type=hidden]):not([type=checkbox]):not([type=button]):not([type=submit]):not([type=image])").wrap("<span class='border'></span>");
}











function debug(m){if (typeof console != 'undefined'){console.log(m);}}
function puts(m){debug(m);}





//business header
function business_header(){

  jq("#change_business_link").change(function(){
    var x = jQuery("#change_business_link").val();
    if (x.length == 0)
    return;
    location.href = x;
  });
  
  var CHANGE_BUSINESS_TEXT = 'Change Business';
  jq('#change_business_clicker').click(function(){
    if (jq('#change_business_selector').is(':visible')){
      jq('#change_business_selector').hide();
      jq("#change_business_clicker").html(CHANGE_BUSINESS_TEXT);
    }
    else {
      jq('#change_business_selector').show();
      CHANGE_BUSINESS_TEXT = jq("#change_business_clicker").html()
      jq("#change_business_clicker").html('Cancel');
    }
  })
}  





var LAST_SELECT_TO_CREATE_CONTACT = '';
function setup_add_contacts_select(){
  jq('.add_contact').each(function(){
    var sel = jq(this);
		var parent = jq(this).parents('form').siblings('#new_contact');
		if (sel.size() < 1) {return;}
    var data = sel.metadata();
    var id = data.id;
    sel.unbind('change.setup_add_contacts_select').bind('change.setup_add_contacts_select', function(){
      if (sel.val() != 'add') {return;}
      LAST_SELECT_TO_CREATE_CONTACT = sel.attr('id');
      if (data.contractor) {parent.find('#create_contact_contractor').show(); parent.find('#create_contact_form_contractor').attr("checked","checked")}
      else {parent.find('#create_contact_contractor').hide();}
      if (data.employee) {parent.find('#create_contact_employee').show();}
      else {parent.find('#create_contact_employee').hide();}
      TB_show('Create Contact', "#TB_inline?height=200&width=500&inlineId=new_contact");
    })
  })
}

function create_contact_complete(){
  if (!TBREMOVING) { TB_remove(); }
  try{ jq('#create_contact_form').get(0).reset(); }
  catch(e){}
  try{
    jq('#' + LAST_SELECT_TO_CREATE_CONTACT).get(0).selectedIndex = 0;
  }
  catch(e){}
}
function create_contact_submit(form){
	var form = jq(form).parents('#create_contact');
  params = "contact[name]=" + form.find('#create_contact_form_name').val().replace('&', '%26') + 
    "&contact[company_name]=" + form.find('#create_contact_form_company_name').val().replace('&', '%26') + 
    "&contact[phone_number_1]=" + form.find('#create_contact_form_phone_number').val().replace('&', '%26') + 
    "&contact[email]=" + form.find('#create_contact_form_email').val().replace('&', '%26') + 
    "&contact[is_contractor]=" +( form.find('#create_contact_form_contractor').checked() ? form.find('#create_contact_form_contractor').val() : 0) + 
    "&contact[is_employee]=" +( form.find('#create_contact_form_employee').checked() ? form.find('#create_contact_form_employee').val() : 0) +
    "&select_to_replace=" + LAST_SELECT_TO_CREATE_CONTACT;
//  params = {contact: {name: jq('#create_contact_form_name').val(), company_name: jq('#create_contact_form_company_name').val(), phone_number_1: jq('#create_contact_form_phone_number').val(), email: jq('#create_contact_form_email').val(), is_employee: ( jq('#create_contact_form_employee').checked() ? jq('#create_contact_form_employee').val() : 0), is_contractor: ( jq('#create_contact_form_contractor').checked() ? jq('#create_contact_form_contractor').val() : 0)}, select_to_replace: LAST_SELECT_TO_CREATE_CONTACT}
  contacts_ajax(
    'ajax', 
    'post', 
    params, 
    {success: function(e){
      var c = less_json_eval(e); 
      var last = LAST_SELECT_TO_CREATE_CONTACT;
      create_contact_complete();
      jq('#'+last).addOption(c.id, c.f, true); 
      }, 
    error: function(e){alert(e.responseText);}
    }
  )
  return false;
}
var TBREMOVING = false;
function TB_Removing(){
  if (LAST_SELECT_TO_CREATE_CONTACT.length == 0 || TBREMOVING){return;}
  else {
    TBREMOVING = true;
    create_contact_complete();
    LAST_SELECT_TO_CREATE_CONTACT = "";
    TBREMOVING = false;
  }
}



function setup_fancy_selects(){
  jq('.add_selector').setup_xxx_selects();
}

jQuery.fn.setup_xxx_selects = function(){
  return this.each(function(){
    var sel = jq(this);
    var data = sel.metadata();
    var name = data.name;
    var id = data.id;
    var param = data.param
    var question = data.question;
    var path = data.path;
    sel.addOption('xxx', name, false, 1).change(function(){
      if (sel.val() == 'xxx'){
        var val = prompt(question).replace(/\'/g,'\\\'');
        if (val == null){
          sel.get(0).selectedIndex = 0;
          return;
        }
        var err = false;
        try{
          var p = eval(path +"('json', 'POST', '"+param+"=" + escape(val) +"', {error: function(e){alert(e.responseText); sel.get(0).selectedIndex = 0; err = true;}})");
          if (err) {return;}
          jq(this).addOption(p.id, p.name, true)
        }
        catch (e){}
      }
    })
  })
}



function show_add_new_line_item() {
  setTimeout('jq("#add_new_line_item").click()', 100);
}




function check_hide_system_messages(){
  if (jq('#system_messages .system_message').size() == 0){
    jq('#system_messages').hide();
  }
}



function hide_if_same_currency(id) {
	if (jq('#invoice_currency_id').val() != id && jq('#invoice_currency_id').val() != "") {
	  jq('#is_paid').show();
	 } else {
	   jq('#is_paid').hide();
	 }
}

$.fn.less_editable = function(url, options){
  return $(this).editable(url, $.extend({ 
	submit: '<input type="submit" class="editor_ok_button" value="Save" />', 
	cancel: '<a href="javascript:void(0);" onclick="jq(this.form).hide();">cancel</a>', 
	cssclass: 'editable',
	onblur: 'ignore'}, options));
}

function update_balance(value, id, balance, currency, past_val, klass) {
	var val = parseFloat(balance.replace(/\,/g,'')) + parseFloat(value.replace(/\,/g,'')) - parseFloat(past_val.replace(/\,/g,''));
	update_s_balance(value, klass);
	nstring = val.toFixed(2) + ''
	x = nstring.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
	string_val = x1 + x2;
	jq(id).text(string_val);
}

  
function update_s_balance(value, klass) {
  jQuery(klass).text(value)
}









$.fn.toggle_tag = function(tag){
  var input = $(this);
  var tags = input.val().split(/,\s*/);
  
  if (tags.length == 1 && tags[0] == "") tags = [];
  
  if ((i = tags.indexOf(tag)) == -1)
    tags.push(tag);
  else
    tags.splice(i, 1);
  
  return input.val(tags.join(', '));
}




function search_input(){
  $('#q')
  .focus(function(){
    if ($(this).val() == 'Search') {$(this).val('');}
  })
  .blur(function(){
    if ($(this).val() == '') {$(this).val('Search');}
  })
}




function datepicker_init(){
  $('.datepicker').datepicker({
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: DATE_FORMAT
  });
}




function init_step_tabs() {
  $('#steps').bind('tabsselect', function(event, ui) {
    form = $('#steps .ui-tabs-panel:visible form.auto_save');
    if (form.length > 0) {
      action = form.attr('action');
      $.ajax({data:$.param(form.serializeArray()) + '&tab=' + ui.index, dataType:'script', type:'post', url:action, async:false});
      return false;
    }
    return true;
  });
}


function init_stars(){
  jQuery('.star').live('click', function(){
    jQuery.ajax({
      url:jQuery(this).attr('href'),
      type:'POST',
      success:function(data){
        eval(data);
      }
    });
    return false;
  })
}


less.startup = {};
less.startup.highlight_navigation = function() {
  var found = null;
  var second_best = null;

  $('#left_column_pad a').each(function(index, link) { 
    if ($(link).text() === "Last Report Viewed" || found) {
    } else if ($(link).text() === "Payables" && window.location.search.match(/depreciating_only=true/) !== null) {
    } else if ($(link).text() === "Fixed Assets" && window.location.search.match(/depreciating_only=true/) === null) {
    } else if (link.href === window.location.href) {
      found = link;
    } else if (link.pathname === window.location.pathname) {
      second_best = link;
    };
  });

  if (found === null && second_best !== null) {
    found = second_best;
  }

  $(found).addClass('selected'); 
  $(found).parent().parent().parent().children('.nav_dropdowns').click();
};

//startup stuff
jq(function(){

//  TB_init();

//  jq(".flashnotice").fadeOut(5000);
  jq(".hide").hide();
  $(".report_filter").each(function(){
    var id = $(this).attr('id');
    tog('#' + id, '#' + id.replace('_clicker', ''))
  })

  
  
  
  jq(".highlight_row").hover(function(){jq(this).addClass('js_row_highlighter_hover')}, function(){jq(this).removeClass('js_row_highlighter_hover')})


  //business header
  business_header();
  
  init_stars();

  setup_fancy_selects();
  setup_add_contacts_select();
  try{
    $('.delete_from_list').shiftClick();
  }
  catch(ex){puts(ex);}

  try{
    tooltips();
  }
  catch(ex){puts(ex);}
  
  search_input();
  
  more_or_less();
  try{
	  jq('#fixed').bgiframe();
  }
  catch(ex){puts(ex);}

  try{  
    $('.sorting_table').tablesorter();
  }
  catch(ex){puts(ex);}
  
	function get_message() {
		var messages = ["I love that shirt you're wearing!",
		"I can tell you've been working out. Nice arms!",
		"You're the best looking user on LessAccounting, but don't tell anyone I said that.",
		"I hope your day has gone well.",
		"You have a great taste in music.",
		"Smarty Pants is probably your nickname.",
		"You're my favorite user, but shhhh don't tell anyone I said that.",
		"Hey great seeing you today.",
		"You look tired do you need coffee?",
		"Dang you have a great smile.",
		"If I had arms I'd give you a high five!",
		"We should hug more often."]
		var message = messages[Math.floor(Math.random()*messages.length)]
		jq('#nice_message').text(message)
	}

  //waiter
	jQuery("#waiter").ajaxStart(function(){ 
		jq(this).show();
		//get_message();
	}).ajaxStop(function(){jq(this).hide(); datepicker_init();}).ajaxError(function(){jq(this).hide();});

  try{
    datepicker_init();
  }
  catch(ex){puts(ex);}

  $('.nav_dropdowns').nav_dropdowns();
  
  try{
    $('.inlinesparkline').sparkline('html', {height: '25px'}); 
  }
  catch(ex){puts(ex);}
  
  function refresh() {
    window.location.reload(false);
  }
  $("#qwc-download").submit(function() {
    setTimeout(refresh, 1000);
  });
  

  // textile formatting tips
  jq('.formatting_tips_clicker').live('click', function(){
    puts("clicking clicker");
    togger(jq(this).parents('small').next('.formatting_div'));
    return false;
  });
  
  //delete from list
  $('#delete_from_list_button').live('click', function(){
    var ids = [];
    $('.delete_from_list').each(function(){
      if ($(this).checked()){ids.push($(this).metadata().id);}
    })
    if (ids.empty()){alert('Oops, you didn\'t select anything to delete.'); return;}
    if (!confirm('Are you sure you want to delete these?')) {return;}
    ajax = eval($(this).metadata().func + '_ajaxx');
    ajax('js', 'delete', {ids: ids.join(',')})
  })
  
  $('table.classic tr:odd').addClass('row_odd');
  $('table.classic tr:even').addClass('row_even');
  
  $('#repeater_start_on').live('keyup',function(event) {
    kc = event.keyCode
    if (kc != 16 && kc != 27 && kc != 37 && kc != 39) {
    update_date_options_if_necessary();
    }
  });

  $(".ui-datepicker-calendar").live('click', function(event) {
    update_date_options_if_necessary();
  });
 
  
  $('#system_messages #toggler a').click(function(){
    if ($('#system_messages #toggler a img').attr('src').indexOf("/images/maximize.png") == -1){
      $('#system_messages .system_message').hide();
      $('#system_messages').animate({width: '15px'}, 400) 
      $('#system_messages #toggler a img').attr('src', "/images/maximize.png");
    }
    else {
      $('#system_messages').animate({width: '250px'}, 400);
      $('#system_messages #toggler a img').attr('src', "/images/minimize.png");
      setTimeout("$('#system_messages .system_message').show()", 500);
    }
  })

  less.startup.highlight_navigation();
});
//startup startup

function update_date_options_if_necessary() {
  if ($('#repeater_next_on').val() == "") {
    $('#repeater_frequency').hide();
    $('#repeater_ends_on').val('');
  } else {
    $('#repeater_frequency').show();
  }
  if ($('#repeater_frequency_period').val() == "months") {
    $.ajax({data:'date=' + $('#repeater_next_on').val(), dataType: 'script', method: 'GET', url: '/repeater_change_date'});
  }
}

function update_sent_at(dom_id, sent_at) {
	jq(dom_id).text(sent_at);
}

function show_if_invoice() {
	if (jq('#payment_payment_type_regular_income').checked() && jq('#payment_invoice_id').val() != "") {
		jq('#is_paid').show();
	} else {
		jq('#is_paid').hide();
	}
}

function show_repeater_date_select_if_monthly() {
  if (jq('#repeater_frequency_period').val() == "months") {
    jq('#repeater_date_option').show();
  } else {
    jq('#repeater_date_option').hide();
  }
}

function updateOwed(id, amount){
	var invoice_id = "#da_invoice_" + id
	if(jq(invoice_id).length > 0){
		jq(invoice_id).text(amount);
	}
}

function new_bank_statement_select(partial) {
	if (jQuery('#bank_statement_select').length == 0) {
		jQuery(partial).insertBefore('#bank_statement_form');
	}
}




$(function () {
  $('.toggleable').click(function() {
    if ($(this).text() == 'Show') {
      $(this).text('Hide');
    } else {
      $(this).text('Show');
    }
    $('div', $(this).parent()).toggle();
  });
});

jq(function($){
	$('.batch_delete a').live('click', function() {
		var meta_data = $(this).metadata();
		if(meta_data.id != null) {
			$('#'+meta_data.id +' > table').find('.delete_it').slideToggle(100);
		}else {
			$('.delete_it').slideToggle(100);
		}
    return false;
	});
	
  $('#bank_search').submit(function() {
    $('#searchbanks .spinner').show();
    $('#results').hide();
    loadBankSearchResults($('#bank_name').val());
    return false;
  });

  function loadBankSearchResults(bank_name) {
    $.getJSON('/bank-integration', {q:bank_name}, function(data) {
      $('#searchbanks .spinner').hide();
      if (data.length == 0) {
        alert("We couldn't find any banks matching that query.");
      } else {
        $('#results').html('');
        $.each(data, function(i, item) {
          $('#results').append(
            '<div class="bank">' + 
              '<div class="name">' + item.display_name + '</div>' +
              '<div class="url">'  + item.home_url     + '</div>' +
            '</div>');
        });
        $('#results').show();
      }
    });
  }
  
  
  //// wufoo form on the support tab
  $('#form_hide').hide();
  $('.suggest a').click(function() {
    $('#form_hide').toggle();
  });

  
  
});

function unselect_invoices(id) {
	jq(id).find('input:radio:first').attr('checked', true)
	return false;
}

var ExpenseCategoryId = '';
var ExpenseId = '';
var ExpenseDomId = '';
function confirm_expense_category_change(select){
  var data = $(select).metadata()
  ExpenseCategoryId = data.expense_category_id;
  ExpenseId  = data.expense_id;
  ExpenseDomId = data.dom_id;
  TB_show('LessAccounting', '#TB_inline?height=150&width=300&inlineId=confirm_expense_category')
}

function setup_expense_category_changes() {
  jq(".expense_category_id").change(function() {
    parent = jq(this).parent().parent();
    id = '';
    jq(".toggleablex", parent).hide();
    if (this.options[this.selectedIndex].text == "Contract Labor") {
      jq(".contractor", parent).show();
      jq(".employee select", parent).val('');
      jq(".payee select", parent).val('');
    } else if (this.options[this.selectedIndex].text == "Wages") {
      jq(".employee", parent).show();
      jq(".contractor select", parent).val('');
      jq(".payee select", parent).val('');
    } else {
      jq(".payee", parent).show();  
      jq(".employee select", parent).val('');
      jq(".contractor select", parent).val('');
    }
    
  });
  jq(".expense_category_id").change();
}

function setup_add_remove_expense_item() {
  jq('.remove_row').click(function() { 
    row = jq(this).parents('.split_payment_form');
    row.fadeOut(function() {
      row.removeClass('addable');
      jq('.delete', row).val("1");
      jq('.expense_item_attribute', row).val("");
      jq('.expense_item_amount', row).val("");
      $('#total_amount').val(payment_total());
      if (jq('.split:visible').length == 1) {
        jq('.remove_row').show();
        jq('.split:visible .remove_row').hide();
      }
    }); 
  });
  
  jq('.add_row').click(function() { 
    jq('.remove_row').show();
    if (jq('.many_items_option:visible').length == 0) {
      jq('#expense_expense_items_attributes_0_amount').val(jq('#total_amount').val());
      jq('#expense_expense_items_attributes_0_notes').val(jq('#expense_notes').val());
      jq('#expense_expense_items_attributes_0_tag_list').val(jq('#expense_tag_list').val());
      jq('#expense_expense_items_attributes_0_title').val(jq('#expense_title').val());
      jq('#expense_expense_items_attributes_0_expense_category_id').html(jq('#expense_expense_category_id').html());
      jq('#expense_expense_items_attributes_0_expense_category_id').val(jq('#expense_expense_category_id').val());
      jq('#expense_expense_items_attributes_0_expense_category_id').change();
      jq('#expense_expense_items_attributes_0_payee_id').html(jq('#expense_payee_id').html());
      jq('#expense_expense_items_attributes_0_payee_id').val(jq('#expense_payee_id').val());
      jq('#expense_expense_items_attributes_0_employee_id').html(jq('#expense_employee_id').html());
      jq('#expense_expense_items_attributes_0_employee_id').val(jq('#expense_employee_id').val());
      jq('#expense_expense_items_attributes_0_contractor_id').html(jq('#expense_contractor_id').html());
      jq('#expense_expense_items_attributes_0_contractor_id').val(jq('#expense_contractor_id').val());
    }
    $('.one_item_option').hide(); 
    $('.many_items_option').show();
    $('#expense_ignore_parent_attrs').val('true');

    less.expense_form.make_read_only('#total_amount');

    row = jq('#split_payments .addable:hidden:first');
    jq('.delete', row).val("0");
    jq('.amount', row).val("0.00");
    if (jq('.split:visible').length > 1) {
      jq('.payment_detail').hide();
      jq('.payment_summary').show();
    }
    jq('.payment_summary', row).hide();
    jq('.payment_detail', row).show();
    update_expense_items();
    row.blindDown(SLIDE_SPEED, function() {
      $(this).find('input:first').focus();
    });
  });
}


function expand_split_expense(obj) {
  update_expense_items();
  jq('.payment_detail').hide();
  jq('.payment_summary').show();
  expand_split_payment(obj); 
  jq(this).closest('.payment_summary').addClass('been_split');
}

function update_expense_items() {
  jq('.split_payment').each(function() {
    jq('.payment_summary .amount', $(this)).html(fmt_currency(jq('.payment_detail .amount', $(this)).val()));
    title = jq('.payment_detail .expense_category_id :selected', $(this)).text();
    if (title == '') { title = 'Uncategorized' }
    jq('.payment_summary .title', $(this)).html(title);
  });
}

function init_autocomplete(path) {
	jQuery('.complete').autocomplete({
    appendTo: "#autocompleteul",
    source: function( request, response ) {
      var url = path + request.term;
      jQuery.getJSON(url , function(data) {
        response(data);
      });
    },
  	minLength: 3,
  	select: function( event, ui ) {
  	  jQuery('#line_item_line').val(ui.item.line);
  	  jQuery('#line_item_quantity').val(ui.item.quantity);
			if (event.keyCode != 9) {
				jQuery('#line_item_quantity').focus();
			};
			jQuery('#line_item_additional_description').val(ui.item.additional_description);
  	  jQuery('#line_item_unit_price').val(ui.item.unit_price);
    },
  }).data( "autocomplete" )._renderItem = function( ul, item ) {
    return $( "<li></li>" )
    .data( "item.autocomplete", item )
    .append( "<a>" + item.line + ' - ' + ' Quantity: ' +  item.quantity + ' Price: ' + item.unit_price + "</a>" )
    .appendTo( ul );
  };
}






 // budgeting
 $.fn.fade_out_and_in = function(speed) {
   var s = null;
   if (_(speed).isUndefined()) {
     s = 100;
   } else {
     s = speed;
   }
   this.fadeOut(s);
   this.fadeIn(s);
 }
 
 $.fn.toggle_image = function(img1, img2) {
   if (this.attr('src').indexOf(img1) >= 0) {
     this.attr('src', img2);
   } else if(this.attr('src').indexOf(img2) >= 0) {
     this.attr('src', img1);
   }
 }
 
 
 
less.budget = {}
less.budget.load_data = function(row, src) {
  var dest = row.find('.budget_history_data');

  _(_(src).keys()).each(function(key) {
    dest.data(key, src[key]);
  });
}

less.budget.get_data = function(row) {
  var data_source = row.find('.budget_history_data');
  var d = {
    name:                         data_source.data('name'),
    budget:                       data_source.data('budget'),
    percentage:                   data_source.data('percentage'),
    uncapped_percentage:          data_source.data('uncapped_percentage'),
    budget_with_currency:         data_source.data('budget_with_currency'),
    category_total_with_currency: data_source.data('category_total_with_currency'),
    history:                      data_source.data('history')
  };
  return d;
}

less.budget.render_graph_for = function(row, animation) {
  var data        = less.budget.get_data(row);
  var categories  = data.history.dates;
  var amounts     = data.history.amounts;
  var infos       = data.history.infos;
  var currency    = data.history.currency;

  $('#detailed_budget_info #budget_title').text(data.name);

  var report_link = row.find('.budget_report_link').html();
  $('#detailed_budget_info #report_link').html(report_link);

  Highcharts.theme = { colors: ['#4572A7'] };

  var all_amounts = _(amounts).clone();
  all_amounts.push(data.budget);
  var graph_end   = _(all_amounts).max() * 1.2;
  if (graph_end == 0.0) {
    graph_end = 1.0;
  }

  var budget_graph = new Highcharts.Chart({
    chart: { 
      renderTo: 'budget_chart', 
      defaultSeriesType: 'bar',
      marginRight: 30,
      style: {
        fontFamily: "arial"
      }
      //plotBorderColor: '#ddd',
      //plotBorderWidth: 1
    },
    title: { 
      text: null
    },   
    xAxis: { 
      categories: categories, 
      gridLineColor: '#ddd',
      gridLineWidth: 1,
      tickWidth: 0,
      labels: {
       style: {
        color: "#999",
        ///fontFamily: "arial"
        }
      } 
       
    },
    yAxis: { 
      plotBands: [{from: 0, to: data.budget, color: '#eee'}],
      min: 0, 
      max: graph_end,
      title: { 
        text: 'Amount (' + currency + ')',
        style: {
              margin: 60,
              color: "#999",
              fontFamily: "arial"
          }
        },
      gridLineColor: 'white',
      gridLineWidth: 0,
      labels: {
       style: {
        color: "#999",
        ///fontFamily: "arial"
        }
      }
    },
    tooltip: { 
      formatter: function() { 
        var index = categories.indexOf(this.x);
        return infos[index]; 
      },  
      borderWidth: 0,
      style: {
        fontFamily: "arial",
        padding: "10px"
      }     
    },
    plotOptions: { 
      series: {
          groupPadding: 0,
          marker: {
              fillColor: '#FFFFFF',
              lineWidth: 2,
              lineColor: null // inherit from series
          }
      },
      bar: { 
        animation: animation, 
        color: "#7fb2d1",
        dataLabels: { 
          formatter: function() { return Highcharts.numberFormat(this.y, 2); },
         enabled: true
          }, 
          zIndex: 0, 
          shadow: false, 
          borderWidth: 0
        }
    }, 
    legend: { enabled: false },
    credits: { enabled: false },
    series: [
      { name: null, data: amounts, pointPadding: 0.0, groupPadding: 0, borderWidth: 0, shadow: false }]
  }); 

  $('#detailed_budget_info').show();
}

less.budget.show_form_for = function(row) {
  row.find('.edit_budget_form').toggle();
  row.find('.expense_category_budget_dropdown').toggle_image('/images/arrow.png', '/images/down_arrow.png')
}

less.budget.hide_form_for = function(row) {
  row.find('.edit_budget_form').hide();
}

less.budget.update_budget_amount = function(row, data) {
  var budget = row.find('.budget');
  budget.text(data.budget_with_currency);
}

less.budget.update_category_total = function(row, data) {
  var category_total = row.find('.category_total');
  category_total.text(data.category_total_with_currency);
}


less.budget.update_percentage = function(row, data) {
  row.find('.number_percent').html(data.uncapped_percentage + "     <span></span>");
}

less.budget.update_progressbar = function(row, data) {
  row.find('.budget_amount_spent').css('width', data.percentage + '%');
}

less.budget.highlight_row_updates = function(row) {
  row.fade_out_and_in();
}

less.budget.highlight_graph_updates = function() {
  $('#detailed_budget_info').fade_out_and_in();
}

less.budget.set_on_class_for_date_filters = function() {
  var current_url = window.location.pathname + window.location.search;
  var match = _($('#inline_filters a')).detect(function(link) { return $(link).attr('href') === current_url });

  if (_(match).isUndefined()) {
    match = _($('#inline_filters a')).first();
  }
  match = $(match);
  match.addClass('on');
}

less.budget.update_row = function(row) {
  var data = less.budget.get_data(row);

  less.budget.update_category_total(row, data);
  less.budget.update_budget_amount(row, data);
  less.budget.update_percentage(row, data);
  less.budget.update_progressbar(row, data);
  less.budget.mark_if_over_budget(row);
  less.budget.highlight_row_updates(row);
}

less.budget.mark_if_over_budget = function(row) {
  if (parseInt(row.find('.number_percent').text()) > 100) {
    row.addClass('over_budget');
  }  else {
    row.removeClass('over_budget');
  }
}

less.expense_form = {};
less.expense_form.init =  function (){
  $("#expense_is_paid").click(function(){ 
    $("#paid_date_div").toggle();
    $("#due_date_div").toggle()
    $("#fixed_asset_dropdown").toggle(); 
  });
  setup_fancy_selects();
  setup_add_contacts_select();
  main_init();
  setup_expense_category_changes();
  setup_add_remove_expense_item();

  if ($('.split_payment_form:visible').size() > 1) {
    $('.one_item_option').hide();
  } else {
    $('.many_items_option').hide();
  }

  less.expense_form.live_update_amount({from: 'input.amount',              to: '#total_amount'});
}

less.expense_form.live_update_amount = function(options) {
  $('.been_split ' + options.from).live('keyup', function() {
    var total = less.expense_form.total_from(options.from);
    $(options.to).val(total);
  });

  $('.been_split ' + options.from).bind('paste', function() {
    var total = less.expense_form.total_from(options.from);
    $(options.to).val(total);
  });
}

less.expense_form.total_from = function(selector) {
  var total = 0;
  jq('.split ' + selector).each(function() {
    total += in_cents(num_or_zero(jq(this).val()) );
  })
  debug(total);
  return in_dollars(total);
}

less.expense_form.make_read_only = function(x) {
  $(x).attr("readonly", true);
  $(x).addClass("readonly");
}



less.expense_form.setup_depreciated_values = function() {
  $('.depreciated_value_toggler').click(function(ev) { 
    var target = $(ev.target).parent().find('.depreciated_value_fields');
    var text_field = target.find('.years_holding_value');
    target.toggle();
    if (text_field.val() !== '0') {
      text_field.val('0');
    }
  });
};

