// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// templating
String.prototype.template = function (o) {
  return this.replace(/{([^{}]*)}/g,
    function (a, b) {
      var r = o[b];
      return typeof r === 'string' || typeof r === 'number' ? r : a;
    }
  );
};

String.prototype.repeat = function( num ) {
	for( var i = 0, buf = ""; i < num; i++ ) buf += this;
	return buf;
}

String.prototype.rjust = function( width, padding ) {
	padding = padding || " ";
	padding = padding.substr( 0, 1 );
	if( this.length < width )
		return padding.repeat( width - this.length ) + this;
	else
		return this;
}

String.prototype.minutes = function(){
	var minutes = 0;
	
	// If the user forgets a space between 'h' and minutes, add one for them.
	var input = this.toLowerCase().replace(/h(?=\d)/, "h ");
	
	if(input.match(/[dhm]/)) {
		// look for '1h 15m' format
		var segments = input.split(" ");
		$j.each(segments, function(){
			if(this.toLowerCase().endsWith("d")) {
				minutes += parseInt(this,10) * 60*24
			}
			if(this.toLowerCase().endsWith("h")) {
				minutes += parseInt(this,10) * 60
			}
			if(this.toLowerCase().endsWith("m")) {
				minutes += parseInt(this,10)
			}
		});
	}
	else if(this.toLowerCase().match(/:/)) {
		// look for '1:15.23' format

    var segments = this.replace(/[^0-9:]/, "").split(":").reverse();
		for (var x = 0; x < 2; x++) {
			if (segments[x]) {
				minutes += parseInt(segments[x],10) * (Math.pow(60,x));
			}
		}
	}
	else {
		return parseInt(this,10)
	}
	return minutes;
}


Number.prototype.minutesToFormattedTime = function() {
	if (isNaN(this)) {
		return "00:00";
	}
	var segments = new Array();
  	segments.push((parseInt(this / 60)).toString().rjust(2, '0'));
	segments.push((parseInt(this % 60)).toString().rjust(2, '0'));
	return segments.join(":");
}

String.prototype.seconds = function(){
	var seconds = 0;
	if(this.toLowerCase().match(/[dhms]/)) {
		// look for '1h 15m' format
		var segments = this.split(" ");
		$j.each(segments, function(){
			if(this.toLowerCase().endsWith("d")) {
				seconds += parseInt(this,10) * 60*60*24
			}
			if(this.toLowerCase().endsWith("h")) {
				seconds += parseInt(this,10) * 60*60
			}
			if(this.toLowerCase().endsWith("m")) {
				seconds += parseInt(this,10) * 60
			}
			if(this.toLowerCase().endsWith("s")) {
				seconds += parseInt(this,10)
			}
		});
	}
	else if(this.toLowerCase().match(/(:|\.)/)) {
		// look for '1:15.23' format

    var segments = this.replace(/[^0-9:\.]/, "").replace(".", ":").split(":").reverse();
		for (var x = 0; x < 3; x++) {
			if (segments[x]) {
				seconds += parseInt(segments[x],10) * (Math.pow(60,x));
			}
		}
	}
	else {
		return parseInt(this)
	}
	return seconds;
}

Number.prototype.secondsToFormattedTime = function() {
	if (isNaN(this)) {
		return "00:00";
	}
	var segments = new Array();
  segments.push((parseInt(this / 3600)).toString().rjust(2, '0'));
	segments.push((parseInt((this / 60) % 60)).toString().rjust(2, '0'));
	segments.push((parseInt(this % 60)).toString().rjust(2, '0'));
	// if (this < 3600)
	// 	segments.shift();
	return segments.join(":");
}




$j(document).ready(function() {
	
	$j("a.select-all").click(function() {
		$j("table.entries-list input[type=checkbox]").attr("checked", true);
		return false;
	});
	
	$j("a.select-none").click(function() {
		$j("table.entries-list input[type=checkbox]").attr("checked", false);
		return false;
	});
	
	$j(".time-entries a.delete-selected").click(function() {
		
		$j(this).parents("form").submit();
	});
	
	$j("form.batch-entries").submit(function() {
		var entries = $j.map($j("table.entries-list input[type=checkbox]:checked"), function(e) {
			return $j(e).val();
		});
		
		$j(this).find("input[name=entries]").val(entries);
		return $j("table.entries-list input[type=checkbox]:checked").size() > 0 && confirm("Are you sure you want to delete the selected entries?\nThis action cannot be undone.");
	});
	
	// report filters
	$j("a.select-all").click(function() {
		$j(this).parents("fieldset").find("input[type=checkbox]").attr("checked", true);
		return false;
	});
	
	$j("a.select-none").click(function() {
		$j(this).parents("fieldset").find("input[type=checkbox]").attr("checked", false);
		return false;
	});
	
	
	
	$j("legend").css({cursor: "default"}).click(function() {
		$j(this).parent("fieldset").find("input").select().focus();
	});
	
	// hide unneeded <br> on some pages
	$j("form ~ br").remove();
	
	// hide an empty sidebar
	$j("#sidebar:has(ul:empty)").each(function() {
		$j(this).remove();
		$j("#content").addClass("full");
	});
	
	$j(".reflect").reflect({height: 0.3, opacity: 0.3});

	$j('a[rel*=facebox]').livequery(function(){  
	 		$j(this).facebox(); 
	 });
	
	$j("#facebox form").attach(Remote.Form, {dataType: 'script'});
	
	$j("input#starts_at").livequery("blur", function() {
		var entry_date = $j("input#entry_entry_date").val()
		var start_time = $j(this).val()
		var date = Date.parse(entry_date + " " + start_time);
		if (date) {
			// update the hidden field 
			$j("#entry_starts_at").val(date.toString("yyyy/MM/dd HH:mm:ss"));
			//update the textbox 
			$j("#starts_at").val(date.toString("HH:mm"));
			// update the help text to show the date
			$j("#starts_at ~ div.help-text").text(date.toString("yyyy/MM/dd h:mm"));
			// update end date
			var duration = $j("#duration").val().minutes();
			if (duration) {
				var endDate = date.clone().add({minutes: duration});
				
				// update the hidden
				$j("#entry_ends_at").val(endDate.toString("yyyy/MM/dd HH:mm:ss"));
				// update the text box with just time
				$j("#ends_at").val(endDate.toString("HH:mm"));
				// update the help text to show the date
				$j("#ends_at ~ div.help-text").text(endDate.toString("yyyy/MM/dd h:mm"));
			}
		}

	});
	
	$j("input#ends_at").livequery("blur", function() {
		
			var entry_date = $j("input#entry_entry_date").val()
			var end_time = $j(this).val()
			var endDate = Date.parse(entry_date + " " + end_time);
			var startDate = Date.parse($j("#entry_starts_at").val());
			if(startDate && endDate) {

				switch(endDate.clone().compareTo(startDate.clone())) {
					case -1:
					  // endDate is less than startDate -- add a day
						endDate.add({days: 1});
						break;
					case 1:
						if (((endDate - startDate) / 1000/60/60/24) > 1) {
							// endDate is more than 1 day ahead, reset it to one day ahead
							endDate.set({month: startDate.getMonth(), day: startDate.getDate(), year: startDate.getFullYear()});
						}
						break;
				}

				// update the hidden
				$j("#entry_ends_at").val(endDate.toString("yyyy/MM/dd HH:mm:ss"));
				// update the text box with just time
				$j("#ends_at").val(endDate.toString("HH:mm"));
				// update the help text to show the date
				$j("#ends_at ~ div.help-text").text(endDate.toString("yyyy/MM/dd h:mm"));
			}
			// update the duration 
			if (startDate && endDate && (endDate > startDate)) {
				var duration = parseInt((endDate - startDate) / 1000 / 60);
				$j("input#duration").val(duration.minutesToFormattedTime());
			}


	});
	
	$j("input#duration").livequery("blur", function(){
		var minutes = $j(this).val().minutes();
		$j(this).val(minutes.minutesToFormattedTime());
		var startDate = Date.parse($j("#entry_starts_at").val());
		if (startDate) {
			var endDate = startDate.add({minutes: minutes});
			if (endDate) {
				// update the hidden
				$j("#entry_ends_at").val(endDate.toString("yyyy/MM/dd HH:mm:ss"));
				// update the text box with just time
				$j("#ends_at").val(endDate.toString("HH:mm"));
				// update the help text to show the date
				$j("#ends_at ~ div.help-text").text(endDate.toString("yyyy/MM/dd h:mm"));
				
			}

		}
	});
	
	
	
	$j("#facebox a.cancel, #facebox input.cancel").livequery("click", function(){
		$j(document).trigger('close.facebox');
		return false;
	});
	
	$j("ul.tabs a").click(function() {
		$j(this).parent("li").toggleClass("current");
	});
	
	// $j(window).resize(function() {
	// 	console.log("foo");
	// });
	
	$j("div.add-more-project-users a").click(function() {
		$j("div.add-more-project-users .data-grid, div.add-more-project-users .form-buttons").toggle();
		return false;
	});

	$j(".data-grid input.check-all").click(function() {
		$j(this).parents("table.data-grid").find("td.check-column input").attr("checked", $j(this).attr("checked") == true);
	});
	
	// user entries dropdown menu
	$j("select.user-entries-menu").change(function(){
		window.location.href = $j(this).val();
	});
	
	// user report dropdown menu
	$j("select.user-report-menu").change(function(){
		window.location.href = $j(this).val();
	});

	// user report dropdown menu
	$j("select.project-report-menu").change(function(){
		window.location.href = $j(this).val();
	});
	
	// timer link
	$j("a.timer-open").click(function() {
		timerWindow = window.open($j(this).attr("href"),'tickstart_timer','resizable=1,toolbar=0,location=0,status=0,menubar=0,scrollbars=1,width=240,height=350');
		timerWindow.focus();
		return false;
	});
	
	$j("body.timer a.my-account, body.timer a#home").attr("target", "_blank");
	
	// add new fields to invites
	$j('a#add-more').click(function() {
		$j("div#invite").clone().appendTo("fieldset#invite-fieldset");
	});
	
	$j('a#use_presently').click(function() {
		$j('div#presently-setup').toggle();
		return false;
	});
	
	$j('a#fb').click(function(){
		$j('div#fb-client').slideToggle('slow');
		return false
	});
	
	$j('a#create_invoice').click(function() {
	  confirm('Are you sure you want to send the invoice to the client?')
	  $j.post('/accounting/invoices/create_invoice')
	})
	
	// service links
	$j('.service a.toggle').click(function() {
	  $j(this).parents('.service').find('.settings').slideToggle('slow');
	  return false
	});
	
	// section menu animation
	$j('#side-menu li.current').animate({backgroundPosition: '-7px center'}, 500);
	
	$j.tablesorter.defaults.widgets = ['zebra']; 
	
	$j('td.numeric:contains(-), th.numeric:contains(-)').addClass('negative');
	
	$j('input.prompt').focus(function() {
	  var textbox = $j(this);
	  if(textbox.val() == textbox.attr('title')) {
	    textbox.val('');
	  }
	});
	
	$j('input.prompt').blur(function() {
	  var textbox = $j(this);
	  if(textbox.val() == '') {
	    textbox.val(textbox.attr('title'));
	  }
	});
	
	$j('input.prompt').each(function() {
	  var textbox = $j(this);
	  if(textbox.val() == '') {
	    textbox.val(textbox.attr('title'));
	  }
	});


});

function refreshEntries() {
	$j('div.time-entries').load(window.location.href + ' div.time-entries');
}

