login = function() {
	return  '<form onsubmit="harvest_resource.submit_credentials(this); return false;" class="form">' +
					'<label>Username</label><input type="text" id="username"/>' +
				 	'<label>Password</label><input type="password" id="password"/>' +							 			
				 	'<input type="submit" value="Login" id="submit">' +
				 	'</form>'		
}
		
application = function() {
	return '<form onsubmit="if (parseFloat(this[\'request[hours]\'].value)==NaN) {alert(\'Please enter a valid value for hours\'); return false;}; this[\'request[notes]\'].value +=\' (ticket #' + ticket_id + ')\';  harvest_resource.submit_data(this); return false;" class="form">' +
				 /* Form fields to POST to Harvest */
				 '<label>Select project</label><select name="request[project_id]" id="harvest-form-projects" onchange="tasks_selector(this.options[this.selectedIndex].value)"></select>' + 
				 '<label>Select task</label><select name="request[task_id]" id="harvest-form-tasks"></select>' +	
				 '<label>Notes</label><input type="text" name="request[notes]"/>' +		
				 '<label><b>Hours</b></label><input type="text" name="request[hours]" size="5" maxlength="5"/><br/>' +			
				 '<input type="hidden" name="request[spent_at]" value="' + Date('dd/mm/yyyy') + '">' +
				 /* Request parameter to pluck from form fields for POST*/
				 '<input type="hidden" name="pluck_param" value="request">' +					 						 
				 /* REST resource to POST to */
				 '<input type="hidden" name="resource" value="daily/add">' +				 	
				 /* Format for REST resource POST (json or xml) */				 
				 '<input type="hidden" name="media_type" value="application/xml">' +					 
				 /* Title on ticket event */
				 '<input type="hidden" name="event_reference" value="Harvest time tracking">' +
				 /* Return values from POST to log on ticket event */				 			 							 			 		 
				 '<input type="hidden" name="event_log" value="Project,Task,Notes,Hours,location,ID">' +			 				 
				 '<input type="submit" value="Submit" id="submit">' +							 
				 '<span class="link" style="font-weight:normal;margin-left:20px;" onclick="harvest_resource.logout()">(logout)</span>' +	
				 '</form>'	
}

// Harvest client selector
projects_selector = function(response) {
	// load options into the project dropdown
	var currentClient = ''
	var projectInput = $('harvest-form-projects')
	var optGroup;
	projectInput.innerHTML = '';
	projects = $A(response.projects)
  projects.sortBy(function(p){return p.client + p.name}).each(function(p){
		// if this is a new client, create the option group for it
		if (currentClient != p.client)  {				
			// add the last option group to the input selector if one has been created
			if (currentClient != '')
				projectInput.appendChild(optGroup);						
				optGroup = document.createElement("optgroup");
				optGroup.setAttribute("label", p.client)
				currentClient = p.client;
			} 
					
			// keep adding this to the option group
			var option = document.createElement("option");
			option.value = p.id;
			option.innerHTML = p.name;
			optGroup.appendChild(option);					
  });

  // tack on the final optgroup
  projectInput.appendChild(optGroup);

	// display the default
	projectInput.selectedIndex = 0;	

	// load default task list
	if (projects.length>0) tasks_selector(projects[0].id);	
}
 	
// Harvest task selector - tasks are dependant on project selected
function tasks_selector(project_id) {
	// we always start with the billable group
	var billable = false;
	var currentGroup = '';
	$('harvest-form-tasks').update();

  projects.each(function(p){  	
		// if we have a match, print out the tasks
		if (p.id == project_id) {
			$A(p.tasks).sortBy(function(t){return !t.billable + t.name}).each(function(t){
				var option = document.createElement("option");
				option.value = t.id;
				option.innerHTML = t.name;
				// if the current group matches this task's billable status, add it in
				currentTask = t.billable ? "Billable" : "Non-billable";
				if (currentGroup != currentTask) {
					// wrap up the first option group
					if (currentGroup != '') $('harvest-form-tasks').insert(optGroup); 
					// start the next one
					optGroup = document.createElement("optgroup");
					optGroup.setAttribute("label", currentTask);
					currentGroup = currentTask;
				}							
				optGroup.appendChild(option);
      });
			// add last group to option group				
			$('harvest-form-tasks').insert(optGroup);								
		}
  });	
}
																													
harvest_resource = new Zendesk.Resource(
	{title: 'Harvest time tracking',			
	 anchor: 'harvest-time-tracking',
	 domain: $('harvest-time-tracking').readAttribute('domain'),
	 use_ssl: $('harvest-time-tracking').readAttribute('use_ssl') || 'false',
	 login_content: login,
	 application_content: application, 
	 application_resources: [ {resource: 'daily', on_success: projects_selector} ]
	}
);