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];}

//************************************************
//payments
//************************************************


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(',','');
  float  = parseFloat(string);

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

function deposit_total() {
  return num_or_zero( jq('#deposit_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_payment 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);
  
  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) {
  jq(sender).parents('.split_payment').blindUp(SLIDE_SPEED, function() {
    jq(this).remove();
    check_split_payment_count();
  });
}

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) {
  jq(sender).closest('.split_payment').
    find('.payment_summary').show().
    siblings('.payment_detail').blindUp()
}

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() {
  debug("check");
  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_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 a').html(val);
    });
  
  jq('.payment_detail input.amount, #deposit_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
//************************************************





//************************************************
//expense
//************************************************
 function EXPENSE_PAGE_hide_all(){
   EXPENSE_PAGE_hide("#expense_contractor_div");
   EXPENSE_PAGE_hide("#expense_employee_div");
   EXPENSE_PAGE_show("#expenses_payee_div");
   EXPENSE_PAGE_show("#expenses_title_div");
 }
 function EXPENSE_PAGE_hide(id){
   if (id.length == 0)
   return;
   if (jq(id).css('display') != 'none')
   togger(id)
 }

 function EXPENSE_PAGE_show(id){
   if (id.length == 0)
   return;
   if (jq(id).css('display') == 'none')
   togger(id)
 }


 function main_init(){
   var LAST_EXPENSE_CATEGORY = '';
   jq("#expense_expense_category_id").change(function(){
     id = '';
     if (this.options[this.selectedIndex].text == "Contract Labor")
       {id = "#expense_contractor_div";}
     else if (this.options[this.selectedIndex].text == "Wages") 
       {id = "#expense_employee_div";}
     if (id == '')
       {EXPENSE_PAGE_hide_all();}
     else {
       EXPENSE_PAGE_hide(LAST_EXPENSE_CATEGORY);
       togger(id);
       if (jq("#expenses_payee_div").css('display') != 'none') {togger("#expenses_payee_div"); togger('#expenses_title_div')}
     }
     LAST_EXPENSE_CATEGORY = id; 
   });

   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();
 }


 function init_expense_form(){
   jq("#expense_is_paid").click(function(){ jq("#paid_date_div").slideToggle(SLIDE_SPEED)});
   jq("#expense_is_paid").click(function(){ jq("#due_date_div").slideToggle(SLIDE_SPEED)});
   setup_fancy_selects();
   setup_add_contacts_select();
   main_init();
 }


 jq(function(){
   init_expense_form();
 })
//************************************************
//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).parent().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 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);
    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) {jq('#create_contact_contractor').show(); jq('#create_contact_form_contractor').attr("checked","checked")}
      else {jq('#create_contact_contractor').hide();}
      if (data.employee) {jq('#create_contact_employee').show();}
      else {jq('#create_contact_employee').hide();}
      TB_show('Create Contact', "#TB_inline?height=200&width=500&inlineId=create_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(){
  params = "contact[name]=" + jq('#create_contact_form_name').val().replace('&', '%26') + 
    "&contact[company_name]=" + jq('#create_contact_form_company_name').val().replace('&', '%26') + 
    "&contact[phone_number_1]=" + jq('#create_contact_form_phone_number').val().replace('&', '%26') + 
    "&contact[email]=" + jq('#create_contact_form_email').val().replace('&', '%26') + 
    "&contact[is_contractor]=" +( jq('#create_contact_form_contractor').checked() ? jq('#create_contact_form_contractor').val() : 0) + 
    "&contact[is_employee]=" +( jq('#create_contact_form_employee').checked() ? jq('#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);}
    }
  )
}
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>', onblur: 'ignore'}, options));
}





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('Less Accounting', '#TB_inline?height=150&width=300&inlineId=confirm_expense_category')
}





$.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
  });
}









//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();

  setup_fancy_selects();
  setup_add_contacts_select();
  $('.delete_from_list').shiftClick();
  
  //tooltips
  tooltips();
  search_input();
  
  more_or_less();
	jq('#fixed').bgiframe();
  
  $('.sorting_table').tablesorter();
  
  //waiter
	jQuery("#waiter").ajaxStart(function(){jq(this).show();}).ajaxStop(function(){jq(this).hide(); datepicker_init();}).ajaxError(function(){jq(this).hide();});

  datepicker_init();

  $('.nav_dropdowns').nav_dropdowns();
  
  $('.inlinesparkline').sparkline('html', {height: '25px'}); 
  
  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);
    }
  })
});
//startup startup

function update_date_options_if_necessary() {
  if ($('#repeater_frequency_period').val() == "months") {
    $.ajax({data:'date=' + $('#repeater_start_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);
	}
}

