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

function getEmailUpdates(){        
	if (isBlank($F('subscriber_email'))){
		alert('Please enter your email address');
    } else {              
	    $('email_updates_indicator').show();
		new Effect.Pulsate('email_updates_indicator', {duration:5.0, pulses:5.0});  
	    $('email_updates_button').disabled = 'disabled';                                                                                    
		var target = 'email_updates_area'  
		var url = '/subscribers'; 
		var pars =  {'subscriber[email]':$F('subscriber_email')};  
		new Ajax.Updater(target, url, {onFailure:genericFailureMessage, parameters:params(pars)});
	}
}

function carouselNavClick(nav_link_name, index){   
	if (!horiz_car.animating){
		selectLink($('nav_link_'+nav_link_name));
		goToCarouselItem(index); 
	}
}

function signoff(){   
	showLogIndicator();                        
	var target = 'time_logging_area'  
	var url = '/time_logs/sign_off'; 
	var pars =  {'_method':'put', 'time_log[day]':$F('time_log_day')};  
	new Ajax.Updater(target, url, {onFailure:genericFailureMessage, parameters:params(pars), evalScripts:true, onComplete:afterGetLog});  
}
function signoffForDay(day_string){   
	showLogIndicator();                        
	var target = 'log_day_status_'+day_string;  
	var url = '/time_logs/sign_off_day'; 
	var pars =  {'_method':'put', 'time_log[day]':day_string};  
	new Ajax.Updater(target, url, {onFailure:genericFailureMessage, parameters:params(pars), onComplete:afterSignoffForDay});  
}                                                                                                                                              
function afterSignoffForDay(){
	hideLogIndicator();
}
  
function showLogIndicator(){   
	$('logs_indicator').show();  
	new Effect.Pulsate('logs_indicator', {duration:5.0, pulses:5.0}); 
}     
function hideLogIndicator(){
	$('logs_indicator').hide();
}

function getLogForThisMonth(){   
	showLogIndicator();
	var url = '/time_logs/this_month'; 
	var pars = { '_method':'get' };   
	new Ajax.Updater('time_logging_area', url, {parameters:params(pars), onComplete:hideLogIndicator, evalScripts:true}); 
}       

function getLogForLastMonth(){  
	showLogIndicator();          
	var url = '/time_logs/last_month'; 
	var pars = { '_method':'get' };   
	new Ajax.Updater('time_logging_area', url, {parameters:params(pars), onComplete:hideLogIndicator, evalScripts:true}); 
}     

function getLogForDay(day){                                           
	$('time_log_day').value=day;
	getLog();
}

function changeDefaultProject(){     
	p_id = $('user_last_logged_project_id').value; 
	updateLastLoggedProject(p_id);          
	     
	last = $$('#timers_area .timer').last();   
	timer_id = last.getAttribute('timer_id'); 
	$('timer_'+timer_id+'_project_id').value = p_id;
	                                                                                    
	last_tf = $$('#time_frames_area .time_frame').last()  
	tf_id = last_tf.getAttribute('time_frame_id'); 
	$('time_frame_'+tf_id+'_project_id').value = p_id; 
	
	$('user_last_logged_project_id').blur();
}

function stopAllTimersAccept(timer_id){ 
	$$('#timers_area .timer').each(function(t){  
		current_timer_id = t.getAttribute('timer_id');
	    if (current_timer_id != timer_id){
		    if (Element.visible('timer_'+current_timer_id+'_stop')){                                      
				$('timer_'+current_timer_id+'_stop').click();          
			}
		}
	});
}

function startJavascriptTimer(timer_id){
	stopAllTimersAccept(timer_id);                  
	ss(timer_id);
	$('timer_'+timer_id+'_start').hide();
	$('timer_'+timer_id+'_stop').show();
}   
function stopJavascriptTimer(timer_id){ 
	ss(timer_id);
	$('timer_'+timer_id+'_stop').hide();
	$('timer_'+timer_id+'_start').show();
}

function stopAndRemoveTimer(name){
	if (isBlank(name)) return;
	 
	$$('#timers_area .timer').each(function(t){  
		current_timer_id = t.getAttribute('timer_id');
		if ($F('timer_'+current_timer_id+'_name') == name){    
		    if (Element.visible('timer_'+current_timer_id+'_stop'))                                      
				$('timer_'+current_timer_id+'_stop').click();         
			unloadTimer(current_timer_id);  
			return;
		} 
	});
}

function startLastTimer(name){
	last = $$('#timers_area .timer').last();   
	timer_id = last.getAttribute('timer_id'); 
	enableTimer(timer_id);
	$('timer_'+timer_id+'_project_id').value = $('user_last_logged_project_id').value;
	$('timer_'+timer_id+'_name').value = name;                                   
	$('timer_'+timer_id+'_start').click();        
}

function updateLastLoggedProject(id){ 
	showTicketIndicator();  
	var url = '/account/last_logged_project'; 
	var pars = { '_method':'put', 'last_logged_project_id':id };   
	new Ajax.Request(url, {parameters:params(pars), onComplete:refreshTicketsNoFetch});   
} 

function showTicketIndicator(){  
	$('tickets_indicator').show();
	new Effect.Pulsate('tickets_indicator', {duration:5.0, pulses:5.0});  
}

function refreshTickets(){
	showTicketIndicator();                              	
	var url = '/account/tickets'; 
	var pars = { '_method':'get' };   
	new Ajax.Request(url, {parameters:params(pars), onComplete:updateTickets});   
} 
function refreshTicketsNoFetch(){                       	
	var url = '/account/tickets'; 
	var pars = { '_method':'get', 'no_fetch':true };   
	new Ajax.Request(url, {parameters:params(pars), onComplete:updateTickets});   
}   

function markTicketAsDone(id){ 
	stopAndRemoveTimer("(ticket "+$('ticket_link_'+id).innerHTML);   
	showTicketIndicator();  
	new Effect.Fade('ticket_'+id);        	
	var url = '/account/tickets/'+id+'/done'; 
	var pars = { '_method':'put' };   
	new Ajax.Request(url, {parameters:params(pars), onComplete:updateTickets});
}

function markTicketAsNotDone(id){                                   
	showTicketIndicator();   
	new Effect.Fade('ticket_'+id);     	
	var url = '/account/tickets/'+id+'/not_done'; 
	var pars = { '_method':'put' };   
	new Ajax.Request(url, {parameters:params(pars), onComplete:updateTickets});
} 

function acceptTicket(id){
	startLastTimer("(ticket "+$('ticket_link_'+id).innerHTML);   
	                                        
	showTicketIndicator();  
	new Effect.Fade('ticket_'+id);     	
	var url = '/account/tickets/'+id+'/accept'; 
	var pars = { '_method':'put' };   
	new Ajax.Request(url, {parameters:params(pars), onComplete:updateTickets}); 
} 

function unacceptTicket(id){  
	showTicketIndicator();         
	new Effect.Fade('ticket_'+id);    	
	var url = '/account/tickets/'+id+'/unaccept'; 
	var pars = { '_method':'put' };   
	new Ajax.Request(url, {parameters:params(pars), onComplete:updateTickets}); 
} 

function unassignTicket(id){  
	showTicketIndicator();         
	new Effect.Fade('ticket_'+id);    	
	var url = '/account/tickets/'+id+'/unassign'; 
	var pars = { '_method':'put' };   
	new Ajax.Request(url, {parameters:params(pars), onComplete:updateTickets}); 
}     

function updateTickets(req){
	$('tickets_indicator').hide(); 
	json = parseJSON(req.responseText);
	['open_tickets', 'my_tickets', 'accepted_tickets', 'resolved_tickets', 'commits'].each(function(e){
		$(e).update(json[e]);              
		$(e+"_count").update(json[e+"_count"]);                                                               
	});
}

function getNewTimeFrame(time_log_id){    	
	var url = '/time_frames/new'; 
	var pars = { 'time_log_id':time_log_id };   
	new Ajax.Updater('time_frames_area', url, {insertion:Insertion.Bottom, parameters:params(pars), evalScripts:true}); 
} 

function getNewTimer(){    	
	var url = '/timers/new'; 
	var pars = { '_method':'get' };   
	new Ajax.Updater('timers_area', url, {insertion:Insertion.Bottom, parameters:params(pars), evalScripts:true}); 
}     

function refreshTimeFrames(){   
	var url = '/time_logs/1234567890';    
	var pars =  { 	'_method':'put',    
					'time_log[desc]':$F('time_log_desc'),                 
					'time_log[day]':$F('time_log_day') }; 
					
	new Ajax.Updater('time_frames_area', url, {onFailure:genericFailureMessage, parameters:params(pars)} );  
}  

function getLog(){                                                    
	showLogIndicator();
	var target = 'time_logging_area'      
	var url = '/log';    
	var pars =  {'_method':'get', 'time_log[day]':$F('time_log_day')};  
	new Ajax.Updater(target, url, {onFailure:genericFailureMessage, parameters:params(pars), evalScripts:true, onComplete:afterGetLog}); 
}           
function afterGetLog(){                                                     
	hideLogIndicator();  
}     

function convertTimeToLabel(time){     
	var d = new Date(time);
	$('time_log_day_label').update(d.toDateString());
}
      
function persistChanges(){    
	var query_string = $('time_log').serialize()+"&_method=put"; 
	var url = '/time_logs/1234567890';                                     
	new Ajax.Request(url, {onFailure:genericFailureMessage, parameters:query_string, onComplete:afterPersistChanges} );   
}       
function persistTimerChanges(index){        
	var pars =  {'_method':'put'};
	           
	all = $$("div#timer_"+index+" select, div#timer_"+index+" input"); 
	all.each(function (e){  
		pars[e.name] = e.value;
	});          
	                                                             
	var url = '/timers/bulk_update';                                     
	new Ajax.Request(url, {onFailure:genericFailureMessage, parameters:params(pars)} );   
}                                                                                                                

function afterPersistChanges(req){   
	json = parseJSON(req.responseText);             
	$('time_log_desc').value = json.desc;  
	if (noElementsDisabled()){                  
    	Element.insert('time_frames_area', {bottom:json.new_time_frame});  
	}
}
       
function debug(str){
	$('debug_area').update(str);
}

function adjustTime(index){ 
       
	n = parseInt($F('time_frame_'+index+'_minutes')); 
	
	hours = Math.floor(n/60);
	minutes = n%60; 
	                   
	
	var today = new Date();   
	today.setHours(parseInt($F('time_frame_'+index+'_start_hour'), 10)); 
	today.setMinutes(parseInt($F('time_frame_'+index+'_start_minute'), 10)); 
	var minutes = today.getMinutes();     
	minutes += n; 
	today.setMinutes(minutes);   
	                                         
	new_end_hour = today.getHours()%12;         
	new_end_minute = today.getMinutes();
		
	if (new_end_hour < 10)
		new_end_hour = "0"+new_end_hour; 
	if (new_end_minute < 10)
		new_end_minute = "0"+new_end_minute;    
				
	$('time_frame_'+index+'_end_hour').value = ""+new_end_hour;//""+current_hour+hours; 
	$('time_frame_'+index+'_end_minute').value = ""+new_end_minute;//""+current_minute+minutes;     
	
}

function adjustMinutes(index){      
	year = 2008;
	month = 11;         
	day = 20;      
	
	start_hours = parseInt($F('time_frame_'+index+'_start_hour'), 10);
	start_minutes = parseInt($F('time_frame_'+index+'_start_minute'), 10); 
	start_utc = Date.UTC(year,month,day,start_hours,start_minutes,0,0);
	
	end_hours = parseInt($F('time_frame_'+index+'_end_hour'), 10);
	end_minutes = parseInt($F('time_frame_'+index+'_end_minute'), 10);  
	end_utc = Date.UTC(year,month,day,end_hours,end_minutes,0,0)
   
	$('time_frame_'+index+'_minutes').value = ((end_utc - start_utc)/60000);                       
}         

function blurOnEnter (event){  
	if (Event.KEY_RETURN == event.keyCode) {  
		var target = event.target || event.srcElement;
		target.blur();                       
	}       
}


function projectCompleterUpdater(selectedElement) { customUpdateElement(project_completer, selectedElement);} 
function dayCompleterUpdater(selectedElement) { customUpdateElement(day_completer, selectedElement);} 
function monthCompleterUpdater(selectedElement) { customUpdateElement(month_completer, selectedElement);}   
function customUpdateElement(auto_completer, selectedElement){   
	value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
	$(auto_completer.element).value = value; 
    
    if (auto_completer.options.afterUpdateElement)
      auto_completer.options.afterUpdateElement(auto_completer.element, selectedElement);                                  
}      

function noElementsInFocus(index){ 
	none = true;   
	                      
	all = $$("div#time_frame_"+index+" select, div#time_frame_"+index+" input"); 
	all.each(function (e){  
		if (e.in_focus)
		 none = false;
	});             
	
	return none;
}        
function noTimerElementsInFocus(index){ 
	none = true;   
	                      
	all = $$("div#timer_"+index+" select, div#timer_"+index+" input, div#timer_"+index+" button"); 
	all.each(function (e){  
		if (e.in_focus)
		 none = false;
	});             
	
	return none; 
}       

function showDeleteLink(index){                         
	if ('timer_'+index != $$('#timers_area .timer').last().id)
		$('timer_'+index+'_delete_link').show();
}       
function hideDeleteLink(index){    
	$('timer_'+index+'_delete_link').hide();                
}

function noElementsDisabled(){    
	var re = new RegExp("[0-9]+");
  	var m = re.exec(""+$$('#time_frames_area .time_frame').last().id);                                                  
	return !notYetValid(m);
}  
function noTimerElementsDisabled(){    
	var re = new RegExp("[0-9]+");                         
  	var m = re.exec($$('#timers_area .timer').last().id); 
	return !timerNotYetValid(parseInt(m));
}  
function enableTimeFrame(index){                                  
	all = $$("div#time_frame_"+index+" select, div#time_frame_"+index+" input, div#time_frame_"+index+" .label"); 
	all.each(function (e){ e.disabled=''; e.removeClassName('disabled'); });   
}  
function enableTimer(index){                                  
	all = $$("div#timer_"+index+" select, div#timer_"+index+" input, div#timer_"+index+" button, div#timer_"+index+" .label"); 
	all.each(function (e){ e.disabled=''; e.removeClassName('disabled'); });   
}                       
function disableTimeFrame(index){ 
	disableAllForReal(index); 
	//setTimeout("disableAllForReal("+index+")", 3000);         
}                        
function disableTimer(index){ 
	disableTimerAllForReal(index);                                   
}   
function notYetValid(index){  
	desc = $F('time_frame_'+index+'_desc');        
	minutes = $F('time_frame_'+index+'_minutes');                     
	return (minutes == '0' || isBlank(desc) || desc == $('time_frame_'+index+'_desc').defaultValue);
}    
function timerNotYetValid(index){ 
	    
	return !(getT(index)[7] > 1 || getT(index)[2] == 1);
}             
function disableIfNecessary(e, index){ 
	var mouseX = Event.pointerX(e);
    var mouseY = Event.pointerY(e);    
                               
	if (!Element.hasPosition('time_frame_'+index, mouseX, mouseY) && noElementsInFocus(index)){                        
		if (notYetValid(index)){
			disableTimeFrame(index);
		} else {
			persistChanges();
		}                                           
	}
}                    
function disableTimerIfNecessary(e, index){   
	var mouseX = Event.pointerX(e);
	var mouseY = Event.pointerY(e);    

	if (!Element.hasPosition('timer_'+index, mouseX, mouseY) && noTimerElementsInFocus(index)){                                                   
		if (timerNotYetValid(index)){
			disableTimer(index);
		}            
	}
}  
function clearIfNecessary(el){     
	if (el.value == 'Click here to add a description')
		el.value = '';
}     
                         
function disableAllForReal(index){           
	all = $$("div#time_frame_"+index+" select, div#time_frame_"+index+" input, div#time_frame_"+index+" .label"); 
	all.each(function (e){ e.disabled='disabled'; e.addClassName('disabled'); });  
}       
                         
function disableTimerAllForReal(index){ 
	all = $$("div#timer_"+index+" select, div#timer_"+index+" input, div#timer_"+index+" button, div#timer_"+index+" .label"); 
	all.each(function (e){ e.disabled='disabled'; e.addClassName('disabled'); });  
} 

function startTimer(timer_id){        
	var url = '/timers/'+timer_id+'/start';    
	var pars =  { 	'_method':'put', 'timer[name]':$F('timer_'+timer_id+'_name'), 'timer[project_id]':$F('timer_'+timer_id+'_project_id') };  
	new Ajax.Request(url, {onFailure:genericFailureMessage, parameters:params(pars), onComplete:afterStartTimer} );               
}                                                                                                                

function afterStartTimer(){                
	if (noTimerElementsDisabled())               
    	getNewTimer();
}    

function stopTimer(timer_id){                                                                                            
	var pars =  { 	'_method':'put', 'timer[name]':$F('timer_'+timer_id+'_name'), 'timer[project_id]':$F('timer_'+timer_id+'_project_id') };  
	var url = '/timers/'+timer_id+'/stop';    
	new Ajax.Request(url, {onFailure:genericFailureMessage, parameters:params(pars), onComplete:function(r){afterStopTimer(r,timer_id);} } );  
}                                                                                                                     

function afterStopTimer(req, timer_id){             
	json = parseJSON(req.responseText);  
	if (!isBlank(json.message)){    
		note_el = $('timer_notification_message_'+timer_id);
		note_el.update(json.message);
		new Effect.Fade(note_el, {duration:3.0});
	} else {                                                                          
		getLog();
	}                   
}




var timers_hash = new Hash();
// 0/1 = start/end
// 2 = state
// 3 = length, ms
// 4 = timer
// 5 = epoch
// 6 = disp el
// 7 = lap count
                               
function getT(index){
	return timers_hash.get('timer_'+index);
}

function ss(index) {   
	var t = getT(index);
	
	t[t[2]]=(new Date()).valueOf();
	t[2]=1-t[2];

	if (0==t[2]) {
		clearInterval(t[4]);
		t[3]+=t[1]-t[0];
		document.getElementById('lap').innerHTML+=
			'<tr><td>'+(t[7]++)+'</td><td>'+
			format(t[1]-t[0], index)+'</td><td>'+
			format(t[3], index)+'</td></tr>';
		t[4]=t[1]=t[0]=0;
		disp(index);           
		
		stopTimer(index); 
		
	} else {
		t[4]=setInterval("disp("+index+")", 73);
		startTimer(index);
	}
}
function r(index) {   
	var t = getT(index);  
	
	if (t[2]) ss(index);
	t[4]=t[3]=t[2]=t[1]=t[0]=0;
	disp(index);
	document.getElementById('lap').innerHTML='';
	t[7]=1;
}

function disp(index) { 
	var t = getT(index);  
	if (t[2]) t[1]=(new Date()).valueOf();
	t[6].update(format(t[3]+t[1]-t[0], index));
}
function format(ms, index) {  
	var t = getT(index);  
	// used to do a substr, but whoops, different browsers, different formats
	// so now, this ugly regex finds the time-of-day bit alone  
	var d=new Date(ms+t[5]).toString()
		.replace(/.*([0-9][0-9]:[0-9][0-9]:[0-9][0-9]).*/, '$1');
	var x=String(ms%1000);
	while (x.length<3) x='0'+x;
	d+='.'+x;
	return d.substr(3);
}

function loadTimer(id) {         
	var t=[0, 0, 0, 0, 0, 0, 0, 1];  
	t[5]=new Date(1970, 1, 1, 0, 0, 0, 0).valueOf();
	t[6]=document.getElementById('timer_display_'+id);  
	timers_hash.set('timer_'+id, t);   
	disp(id); 
}
function unloadTimer(id){     
	timers_hash.unset('timer_'+id); 
	new Effect.Fade('timer_'+id);
	var url = '/timers/'+id;    
	var pars =  { '_method':'delete' };  
	new Ajax.Request(url, {onFailure:genericFailureMessage, parameters:params(pars)} );               
}


function adjustDomainArea(){   
	var existing_site = $F('project_existing_site');
	if (!isBlank(existing_site)){       
	    $('domain_name_area').show();
		if (existing_site == 'true'){
			$('existing_domain_name').show();
			$('brand_new_domain_name').hide();  
		} else {                              
			$('existing_domain_name').hide();
			$('brand_new_domain_name').show();
		}	
	} else {
		$('domain_name_area').hide();
	}
}

function toggleSetupView(setup_item_id){     
	if (Element.visible('setup_item_show_'+setup_item_id)){
		new Effect.Appear('dependencies_'+setup_item_id, {duration:0.3}); 
   		$('setup_item_show_'+setup_item_id).hide(); 
   		$('setup_item_hide_'+setup_item_id).show();   
	} else {
		$('dependencies_'+setup_item_id).hide();  
   		$('setup_item_hide_'+setup_item_id).hide();  
		$('setup_item_show_'+setup_item_id).show();
	}
}

function itemComplete(id, button){     
	if (isExecuting()){ 
		alert("Please wait until other task is complete.");
	} else {     
		$('item_done_'+id).hide();
		$('item_complete_notification_'+id).show();
		var url = '/admin/project_setup_items/'+id+"/complete";      
		var target = 'setup_items_area';  
		var pars =  { '_method':'put' };      
		new Ajax.Updater(target, url, {onFailure:genericFailureMessage, parameters:params(pars), evalScripts:true, onComplete:notExecuting } );   
	}  
}     

function itemNotComplete(id, button){   
	if (isExecuting()){ 
		alert("Please wait until other task is complete.");
	} else {         
		$('item_not_done_'+id).hide();
		$('item_not_complete_notification_'+id).show();
		var url = '/admin/project_setup_items/'+id+"/not_complete";      
		var target = 'setup_items_area';  
		var pars =  { '_method':'put' };      
		new Ajax.Updater(target, url, {onFailure:genericFailureMessage, parameters:params(pars), evalScripts:true, onComplete:notExecuting } );   
	}  
}     
 
var item_executing = false; 
function isExecuting() { return item_executing; }
function executing(){ item_executing = true; }        
function notExecuting(){ item_executing = false; }

function executeItem(automation_path, id){   
	if (isExecuting()){ 
		alert("Please wait until other task is complete.");
	} else {  
		executing(); 
		$('item_execute_'+id).hide();
		$('item_execute_notification_'+id).show();
		var url = automation_path;      
		var target = 'setup_items_area';  
 		var pars =  { '_method':'put', 'project_setup_item_id':id };      
		new Ajax.Updater({success:target}, url, {onFailure:genericFailureMessage, parameters:params(pars), evalScripts:true, onComplete:notExecuting } );   
	}  
}  
function revertItem(reversion_path, id){  
	if (isExecuting()){ 
		alert("Please wait until other task is complete.");
	} else {  
		executing();  
		$('item_revert_'+id).hide();
		$('item_reverse_notification_'+id).show();
		var url = reversion_path;      
		var target = 'setup_items_area';  
		var pars =  { '_method':'put', 'project_setup_item_id':id };      
		new Ajax.Updater({success:target}, url, {onFailure:genericFailureMessage, parameters:params(pars), evalScripts:true, onComplete:notExecuting } );  
	}   
}        

function validBillingDates(day, year, month, iday){
	return true;
}

Element.addMethods({
    hasPosition : function(element, x, y){
        element = $(element);
        this.topleft = Element.cumulativeOffset(element);
        this.bottomright = [
            this.topleft[0] + element.offsetWidth,
            this.topleft[1] + element.offsetHeight,
        ];
        return (y >= this.topleft[1] &&
            y <  this.bottomright[1] &&
            x >= this.topleft[0] &&
            x <  this.bottomright[0]);
    }

}); 