








// [0,1,2,3].remove(1) => [0,2,3]
// [0,1,2,3].remove(1,1) => [0,2,3]
// [0,1,2,3].remove(1,2) => [0,3]
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};







//tog
function tog(clicker, toggler, callback, speed){
  if (speed == undefined) {speed = SLIDE_SPEED;}
  if (callback) {jq(clicker).click(function(){jq(toggler).slideToggle(speed, callback); return false;});}
  else {jq(clicker).click(function(){jq(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














//message
function msg(m, d){message(m, d);}
function async_message(m, d){message(m, d);}
function messages(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()',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 > height || width*2 >= win){ return; }
    jq(this).css({width: width*2 +'px'});
  })
}




function prompt_for_new_project(){
  return prompt('Name of new project?');
}
function add_project_to_list(){
  var name = prompt_for_new_project();
  if (name == null) {return;}
  formatted_projects_ajax('js', 'POST', "project[name]=" + name, {async:true, success: function(e){eval(e)}});
}




function setup_project_selects(){
  jq('#expense_project_id, #timer_project_id').addOption('xxx', 'Create New Project', false).change(function(){
    var sel = jq(this);
    if (sel.val() == 'xxx'){
      var name = prompt_for_new_project();
      if (name == null){
        sel.get(0).selectedIndex = 0;
        return;
      }
      var p = formatted_projects_ajax('json', 'POST', "project[name]=" + name, {error: function(e){
        alert(e.responseText);
        sel.get(0).selectedIndex = 0;
        return;
      }});
      jq(this).addOption(p.id, p.name, true)
    }
  })
}




var TIMER_RUNNING = false;
var TIMER;
var standardTitle = "Less Time Spent -- Track Time Make Money";
function start_timer(){
if (TIMER_RUNNING) {return;}
//  puts('starting')
  TIMER_RUNNING = true;
  check_timer();
}
function stop_timer(){
 // puts('stoping')
  if (!TIMER_RUNNING) {return;}
  if (document.title.match(/(\d\d.){3}/)){ document.title = "[stopped]" + " " + currentProjectTitle; }
  TIMER_RUNNING = false;
  clearTimeout(TIMER);
}
function check_timer(){
//  puts('checking')
  if (!TIMER_RUNNING) {return;}
//  puts('check_start')
  TIMER_RUNNING = true;
  clearTimeout(TIMER);
  TIMER = setTimeout(tick_timer, 1000);
}

function tick_timer(){
  jq('.active_timer').tick_timer();
}
  
jQuery.fn.tick_timer = function(){
  if (jq("#footer_timer").length){
    currentProjectTitle = jq("#footer_timer h2").html().replace(/(is\s*Running)|(is\s*Not\s*Running)/,"");
  }
  if (jq(this).size() > 0) {check_timer();}
  else {stop_timer();}
  return this.each(function(count, tick){
//    puts( 'tick')
    var o = jq(this);
    var data = o.metadata();
    var sec = data.seconds;
    o.text(formatTime(sec +1));
    data.seconds = sec+1;
    if(o.hasClass('running_project')){ document.title = '[' + formatTime(data.seconds) + '] ' + currentProjectTitle; }
  });
}

function formatTime(seconds)
{
  var ret = ''; 
  if (seconds > 3600) {
    var num = Math.floor(seconds/3600);
    seconds -= num * 3600;
    ret += fixLen(num);
  }
  else { ret = '00';}
  if (seconds >= 60) {
   var  num = Math.floor(seconds/60);
    seconds -= (num * 60);
    ret += ':' + fixLen(num);
  }
  else { ret += ':00';}
  
  ret += ':' + fixLen(seconds);
  return ret;
}

function fixLen(num)
{
  num += '';
  if (num.length == 1)
    return '0' + num;
  
  return num;
}

function bind_projects_row() {
  if (jq('.projects_row').size() <= 1) {return}
	jq('.projects_row')
		.unbind('mouseover.bind_projects_row')
		.bind('mouseover.bind_projects_row',
 		  function(){
 				jq('.tab_list', this).attr('style','opacity: 1.0; -moz-opacity: 1.0; filter:alpha(opacity=100);')
 			})
		.unbind('mouseout.bind_projects_row')
		.bind('mouseout.bind_projects_row',
			function(){
				if (jq('.tab_list .on', this).size() > 0 ||
					jq(this).is('.timer_on')) {return;}
				jq('.tab_list', this).attr('style','opacity: 0.2; -moz-opacity: 0.2; filter:alpha(opacity=20);')
		})
}

function project_summary(source, path){
  tab = jq(source).parent();
  is_on = tab.is('.on');
  id = tab.attr('id').match(/\d+$/)[0];
  turn_off_project_tab(id);
  if (is_on) { 
    jq("#summary_project_" + id).slideUp();
  } else {
    path(id, 'js', 'get');
  }
}

function turn_off_project_tab(id) {
  jq('#row_project_' + id + ' .project_action .on').removeClass('on');
}

// select an item form the accomplish_list and populate the text area
function accomplish_list_selector(project_id){
	jq('#accomplish_list').unbind('change.accomplish_list').bind('change.accomplish_list', function(){
		jq('#timer_note').val(jq('#timer_note').val() + "\n" + decodeBase64(jq(this).val())).focus();
	});
}
// end select accomplish_list



// la_business_observer
function la_business_observer(){
	jq('#person_la_password').unbind('change.la_auth_provided').bind('change.la_auth_provided', function(){
		var la_login = jq('#person_la_login').val();
		var la_password = jq('#person_la_password').val();
		formatted_update_la_businesses_person_ajaxx(jq(this).attr('person_id'), 'js', 'GET', {'la_login': la_login.toString(), 'la_password': la_password.toString()});
	});
}
// la_business_observer



var paying = [[],[]]
function my_account_init(){
  jq(".pay_for").unbind('click.pay_for').bind('click.pay_for', function(){
    jq(this).html('Stop paying for').removeClass('pay_for').addClass('paying_for').parent().remove().appendTo('#paying_for_people_list');
    add_paying_for(jq(this));
    my_account_init();
  })
  jq(".paying_for").unbind('click.paying_for').bind('click.paying_for', function(){
    jq(this).html('Pay for').removeClass('paying_for').addClass('pay_for').parent().remove().appendTo('#pay_for_people_list');
    removing_paying_for(jq(this));
    my_account_init();
  })
}
function add_paying_for(j){
  var data = j.metadata();
  var found_it = false;
  for (var i=0; i<paying[0].length; i++){
    if (paying[0][i].user_id == data.user_id){paying[0].remove(i); found_it = true; break;}
  }
  if (!found_it) {
    paying[1].push(data);
  }
  jq('#paying_for_people_list').append('<input type="hidden" name="paying_for[]" value="'+data.user_id+'" id="paying_for_'+data.user_id+'">');
  write_paying_deascription();
}
function removing_paying_for(j){
  var data = j.metadata();
  var found_it = false;
  for (var i=0; i<paying[1].length; i++){
    if (paying[1][i].user_id == data.user_id){
      paying[1].remove(i); 
      found_it = true; 
      puts( data);
      break;
    }
  }
  jq('#paying_for_' + data.user_id).remove();
  if (!found_it) {paying[0].push(data);}
  write_paying_deascription();
}

function write_paying_deascription(){
  if (paying[0].length == 0 && paying[1].length == 0){
    jq('#pay_for_changes').html('No changes.');
    return;
  }
  var str = '<h2></h2>Changes:<br />';
  for (var i=0; i<paying[0].length; i++){ str += "Stop paying for " + paying[0][i].name + ". <br />";}
  for (var i=0; i<paying[1].length; i++){ str += "Start paying for " + paying[1][i].name + ".<br /> ";}
  jq('#pay_for_changes').html(str);
}





function delayed_start_up(){
	bind_projects_row();
	la_business_observer();
	my_account_init()
}

function start_up(delay){
  if (delay == null) {delay = 50;}
 setTimeout(delayed_start_up, delay); 
}



function saved_overlay(){
  x = jq("<div class='message'>Saved</div>");
  jq('body').append(x); x.fadeOut(3000);
}

function hide_hint() {
	jq('#super_hint').hide();
}

//startup
jq(function(){
	jq('#nav').droppy();
	jQuery("#waiter").ajaxStart(function(){jq(this).show();}).ajaxStop(function(){jq(this).hide();}).ajaxError(function(){jq(this).hide();});
  setup_project_selects();
  start_timer();
  tick_timer();
  start_up();
})
//startup




