/*
 * Lifetick iPhone Application
 * Javascript
 * Version 1.2 2009.01.02
 * (c) 2009 Meridian 86 IP
 * Written by Tim Wilson
 *
 */

/* Declare Variables */
var goalID;
var goalTasks;

var goalDetailParent = ''; // The parent screen of the goal detail. Either 'goalList' or 'taskList'
var currentGoalListRowReference;
var currentGoalListItem;
var currentGoalIndex;

var coreValues;

var taskCompleteInProgress = false; // Prevents User from Tapping twice on a task while waiting for a server response.

var editTaskMode; // either ADD or EDIT
var currentTask;

var entryMode = ''; // journal screen has two uses. 'journal' or 'feedback'

var setJournalCategoriesList = false;
var journalCategories = new Array(); // active only
var journalAllCategories = new Array();

function load()
{
	var browserType = navigator.userAgent;
	
	if((navigator.userAgent.match(/iPhone/i))||navigator.userAgent.match(/webOS/i)||(navigator.userAgent.match(/iPad/i))||(navigator.userAgent.match(/iPod/i))||(navigator.userAgent.match(/Android/i)))
	{
	}
	else 
	{ 
	
//	    window.location = '../index.html';
		window.location = 'http://lifetick.com/help-iphone.html';
	}
	
	dashcode.setupParts();
	
	username = getCookie('user');
	password = getCookie('xyz');
	
	if (username != null && username != "" && username != '-')
	{
		setTextInputValue('email',username);
		setTextInputValue('password_txt',password);
	}
	else if (username == "-")
	{
	    rememberMe_chk.checked = false;
	}  
	
	if (window.applicationCache.status == window.applicationCache.UPDATEREADY)
	{
		alert('update ready');
	}
}

/* Core Values */

function getCoreValues()
{
	serverRequest(LIBRARY_GOALS, 'getCoreValues', [{name: "userID",value: userID}], gotCoreValues);
}

function gotCoreValues(xml)
{
	coreValues = new Array();
	
	for(i=0;i<xml.firstChild.childNodes.length;i++)
    {
		var obj = new Object();
		obj.id = xml.firstChild.childNodes[i].getAttribute('id');
		obj.name = xml.firstChild.childNodes[i].getAttribute('name');
		obj.colour = xml.firstChild.childNodes[i].getAttribute('colour');
					
		var test = obj.colour.split('0x');
		obj.colour = test[1];
		
		coreValues.push(obj);
    }
    
    document.getElementById('browser').style.display="block";
        document.getElementById('stackLayout').style.display = 'block';
}

function getCoreValueColour(name)
{
	var index = getIndex('name', name, coreValues);
	if(index == -1)
	{
		return '666';
	}
	else
	{
		return coreValues[index].colour;
	}
}


/* Goals List */

var myGoalsListData;

var currentSortField = 'date';

function getGoalsList()
{
    serverRequest(LIBRARY_GOALS, 'getGoalsSummary', [{name: "userID",value: userID},{name:"includeCompleted",value: "0"}], gotGoalsData);
}

function gotGoalsData(xml)
{
    myGoalsListData = new Array();
    
    for(i=0;i<xml.firstChild.childNodes.length;i++)
    {
		var obj = new Object();
		obj.id = xml.firstChild.childNodes[i].getAttribute('id');
		obj.shortName = xml.firstChild.childNodes[i].getAttribute('shortName');
		obj.activeTasksCount = xml.firstChild.childNodes[i].getAttribute('numberOfActiveTasks');
		
		obj.dueDate = xml.firstChild.childNodes[i].getAttribute('estCompletionDate');
		obj.dueDateObject = generateDate( xml.firstChild.childNodes[i].getAttribute('estCompletionDate'));
		obj.coreValue = xml.firstChild.childNodes[i].getAttribute('coreValue');
		obj.priority = xml.firstChild.childNodes[i].getAttribute('priorityID');
		//obj.coreValueColour = getCoreValueColour(obj.coreValue);		
		
		myGoalsListData.push(obj);
    }
    
    if(myGoalsListData.length == 0)
    {
        alert('Sorry, you do not have any active goals at the moment.');
    }
    else
    {
    sortGoalsList(currentSortField, true);
   // myGoalsListData.sort(compareDate);    
        var listObj = document.getElementById('goalsList-ul').object;
        
    }
    
}

var goalsDataSource = {	
	numberOfRows: function() { return myGoalsListData.length; },
	prepareRow: function(rowElement, rowIndex, templateElements)
	{    
        var listItem = myGoalsListData[rowIndex];
        var goalID = listItem.id;        
        var rowReference = templateElements;
        
        templateElements.goalList_row_label.innerText = listItem.shortName;
        templateElements.goalList_row_sublabel.innerHTML = formatCoreValue(listItem.coreValue)+' '+formatPriority(listItem.priority)+' '+formatDate(listItem.dueDate);
        templateElements.goalList_row_progress.innerText = listItem.activeTasksCount;        

		rowElement.onclick = function(event)
		{		
            currentGoalListRowReference = rowReference;
            currentGoalListItem = listItem;
            currentGoalIndex = rowIndex;
            goalDetailParent = 'goalList';
            getGoal(goalID);           
		};
	}
};

function sortGoalsList(field, setData)
{
	currentSortField = field;
	document.getElementById('sort_date').className = '';
	document.getElementById('sort_priority').className = '';
	document.getElementById('sort_coreValue').className = '';
	switch(field)
	{
		
		
		case 'priority':
			document.getElementById('sort_priority').className = 'current';
			myGoalsListData.sort(comparePriority);
			break;
		
		case 'coreValue':
			document.getElementById('sort_coreValue').className = 'current';
			myGoalsListData.sort(compareCoreValues);
			break;
			
		default:
			document.getElementById('sort_date').className = 'current';
			myGoalsListData.sort(compareDate);
			break;
	}	
	
	var t=setTimeout(resortList,100);
	
	function resortList()
	{	
		var listObj = document.getElementById('goalsList-ul').object;
		if(setData == true)
		{
			listObj.setDataSource(goalsDataSource);        
        	setView('myGoals','Goals');
		}
		else
		{		
			listObj.reloadData();
		}
	}
}

/* View Goal - Displays a Goal with all its Tasks. */

function getGoal(goalID)
{
    serverRequest(LIBRARY_GOALS, 'getGoal', [{name: "id",value: goalID},{name:"includeTasks",value: "1"}], gotGoalData);
}

function gotGoalData(xml)
{
	goalID = xml.firstChild.getAttribute('id');
	goalTasks = new Array();      
	
	// Extract data from xml response
	var goalName = xml.firstChild.getAttribute('shortName');
	var coreValue = xml.firstChild.getAttribute('coreValue');
	var dueDate = formatDate(xml.firstChild.getAttribute('estCompletionDate'));
	var priority = xml.firstChild.getAttribute('priorityID');
	
	for(i=0;i<xml.firstChild.firstChild.childNodes.length;i++)
	{
	    var obj = new Object();
	    obj.id = xml.firstChild.firstChild.childNodes[i].getAttribute('id');	    
	    obj.name = xml.firstChild.firstChild.childNodes[i].getAttribute('name');
	    obj.dueDate = formatDate(xml.firstChild.firstChild.childNodes[i].getAttribute('dueDate'));
	    obj.dueDateObject = generateDate(xml.firstChild.firstChild.childNodes[i].getAttribute('dueDate'));
	    obj.reminder = xml.firstChild.firstChild.childNodes[i].getAttribute('reminderType');
		obj.notes = xml.firstChild.firstChild.childNodes[i].getAttribute('notes');
		
		
		if(xml.firstChild.firstChild.childNodes[i].getAttribute('completed') == '1')
		{
		    obj.completed = true;
			obj.completionDate = generateDate(xml.firstChild.getAttribute('completionDate'));
		}
		else 
		{
		    obj.completed = false;
		}

		if(xml.firstChild.firstChild.childNodes[i].getAttribute('recurringID') != '')
		{
		    obj.isRecurring = true;
			obj.recurringID = xml.firstChild.firstChild.childNodes[i].getAttribute('recurringID');
			
			obj.repeatInterval = xml.firstChild.firstChild.childNodes[i].firstChild.getAttribute('interval');
			
			obj.recurringInstances = xml.firstChild.firstChild.childNodes[i].getAttribute('recurringInstances');
			obj.recurringInstancesCompleted = xml.firstChild.firstChild.childNodes[i].getAttribute('recurringInstancesCompleted');			
		}
		else 
		{
		    obj.isRecurring = false;
			obj.recurringID = '';
		}

	    goalTasks.push(obj);
	}
	
	// Populate form
	document.getElementById('goalName_txt').innerHTML = goalName;
	document.getElementById('goalCoreValue_txt').innerHTML = formatCoreValue(coreValue, true)+' '+formatPriority(priority, true)+' '+dueDate;
	
	
	completeGoalCheck();
	    
	var listObj = document.getElementById('goalTasksList-ul').object;
	listObj.setDataSource(goalTasksDataSource);
	    
	setView('goalDetail','Goal', 'Add Task', openAddTask);    
}

/** Check if the goal is complete (also called on checkbox check) */

function completeGoalCheck()
{
    var incompleteCount = 0;
    
    for(i=0; i<goalTasks.length; i++)
    {
        if(goalTasks[i].completed == false)
        {
            incompleteCount++;
            break;
        }
    }
    
    var completedBar = document.getElementById('goalDetailsComplete');
    
    completedBar.style.visibility = 'visible';
    
    if(incompleteCount == 0)
    {
        completedBar.style.height = 'auto';
        completedBar.style.marginTop = '9px';
        completedBar.style.opacity = 1;        
        window.scrollTo(0, 1);
    }
    else
    {
       completedBar.style.opacity = 0;
       completedBar.style.height = '0px';
       completedBar.style.marginTop = '0px';
    }
    
        
}

var currentRecurringTask;
var goalTasksDataSource = {
		
	numberOfRows: function() { return goalTasks.length; },
	
	prepareRow: function(rowElement, rowIndex, templateElements)
	{
		var listItem = goalTasks[rowIndex];
		var taskID = listItem.id;   
		var recurringID = listItem.recurringID;     
		var checkValue = listItem.completed;
		var checkBox = templateElements.goalTasksList_row_checkbox;
		var recurring_btn = templateElements.goalTasksList_row_recurringCheckbox;
		
		templateElements.goalTasksList_row_label.innerText = listItem.name;
		
		if(listItem.isRecurring == true && checkValue == false)
		{
			checkBox.style.display = 'none';
			recurring_btn.style.display = '';
			
			templateElements.goalTasksList_row_dueDate.innerHTML = listItem.dueDate+". "+listItem.recurringInstancesCompleted +' of '+listItem.recurringInstances+" completed.";
		}
		else
		{
			checkBox.style.display = '';
			recurring_btn.style.display = 'none';
			
			templateElements.goalTasksList_row_dueDate.innerHTML = listItem.dueDate;
		}
		
		checkBox.checked = checkValue;
		       
		styleRow();
		
		templateElements.goalTasksList_row_checkbox.onclick = onClickEvent;
		templateElements.goalTasksList_row_label.onclick = onClickEvent;
		templateElements.goalTasksList_row_recurringCheckbox.onclick = onClickEvent;
		
		templateElements.goalTaskList_row_editBtn.onclick = onEditEvent;
		
		function onClickEvent(event)
		{
		    if(taskCompleteInProgress == false)
		    {
				if(recurringID != "" && checkValue == false)
				{
					currentRecurringTask = listItem;
					showCompleteRecurringTaskView();
				}
				else
				{
					taskCompleteInProgress = true;
					var sendValue = '0';
					if(checkValue == false) sendValue = '1';
					serverRequest(LIBRARY_GOALS, 'setTaskCompletionStatus', [{name: "id",value: taskID},{name:"completed",value: sendValue}], onServerResponse);
				}
		                        	        
		    }
		}	
		
		function onServerResponse(xml)
		{
		    taskCompleteInProgress = false;
		    
		    checkValue = !checkValue;
		    checkBox.checked = checkValue;
		    goalTasks[rowIndex].completed = checkValue
		    styleRow();
		
			if(recurringID != "" && checkValue == false)
			{
				listItem.recurringInstancesCompleted = Number(listItem.recurringInstancesCompleted) - 1;
			}
		
			refreshGoalTasksList();
		    
		    updateListsAfterTaskCompleted(checkValue);
		
		}
		
		function onEditEvent(event)
		{
			currentTask = listItem;
			openEditTask(event);
		}
		       
		function styleRow()
		{
		    if(checkValue == true)
		    {
		        templateElements.goalTasksList_row_label.style.color = '#999';
		        templateElements.goalTasksList_row_label.style.top = '6px';
		        templateElements.goalTasksList_row_dueDate.style.visibility = 'hidden';
		        templateElements.goalTaskList_row_editBtn.style.visibility = 'hidden';
		    }
		    else
		    {
		        templateElements.goalTasksList_row_label.style.color = '#000';
		        templateElements.goalTasksList_row_label.style.top = '1px';
		        templateElements.goalTasksList_row_dueDate.style.visibility = 'visible';
		        templateElements.goalTaskList_row_editBtn.style.visibility = 'visible';
		    }
		}        
	}
};


/* Complete a Goal (and remove from parent list) */

function completeGoal()
{
    serverRequest(LIBRARY_GOALS, 'setGoalCompletionStatus', [{name: "id",value: goalID},{name:"completed",value: '1'}], onCompletedGoal);
}

function onCompletedGoal(xml)
{
	if(goalDetailParent == 'goalList')
	{
		myGoalsListData.splice(currentGoalIndex, 1);
		var listObj = document.getElementById('goalsList-ul').object;
		listObj.reloadData();
	}
	else
	{
		tasksListData.splice(currentGoalIndex, 1);
		var listObj = document.getElementById('tasksList-ul').object;
		listObj.reloadData();
	}     
	
	var browser = document.getElementById('browser').object; 
	var currentView = browser.goBack();
}

/* Add / Edit task functions */

function openAddTask(event)
{
	editTaskMode = 'ADD';	
	viewTaskEditor();
}

function openEditTask(event)
{
	editTaskMode = 'EDIT';	
	viewTaskEditor();
}


function viewTaskEditor()
{
	var today;
	
	if(editTaskMode == 'EDIT')
	{
		today = currentTask.dueDateObject;
		document.getElementById('taskName_txt').value = currentTask.name;
		document.getElementById('addTask-nameLabel').style.display = 'none';
		if(currentTask.isRecurring == true)
		{
			document.getElementById('dueDateContainer').style.display = 'none';
		}
		else
		{
			document.getElementById('dueDateContainer').style.display = 'block';
			
		}
		//document.getElementById('reminder_select').value = currentTask.reminder;
		document.getElementById('deleteTaskButton').style.display = 'block';
		document.getElementById('taskNotes_txt').value = currentTask.notes;
	}
	else
	{
		today = new Date();
		document.getElementById('taskName_txt').value = '';
		document.getElementById('addTask-nameLabel').style.display = 'block';
		document.getElementById('deleteTaskButton').style.display = 'none';
		document.getElementById('dueDateContainer').style.display = 'block';
		document.getElementById('taskNotes_txt').value = '';
	}
	
	document.getElementById('month_select').selectedIndex = today.getMonth();
	populateDates(today.getMonth());
	document.getElementById('date_select').selectedIndex = today.getDate()-1;	
	document.getElementById('year_txt').value = today.getFullYear();
	
	
	var listControl = document.getElementById('reminder_select');
	
	listControl.innerHTML = '';
	
    var remindersDP = new Array();

	//
	
	remindersDP.push({id:'', label:"None"});
	remindersDP.push({id:'0D', label:"On the day"});
	
	if(currentTask != null)
	{
		if(currentTask.isRecurring == true)
		{
			if(currentTask.repeatInterval == "M" || currentTask.repeatInterval == "W")
			{ 
				remindersDP.push({id:'1D', label:"1 day before"});
				remindersDP.push({id:'3D', label:"3 days before"});
			}
		
			if(currentTask.repeatInterval == "M")
			{
				remindersDP.push({id:'1W', label:"1 week before"});
			}
		}
		else
		{
			remindersDP.push({id:'1D', label:"1 day before"});
			remindersDP.push({id:'3D', label:"3 days before"});
			remindersDP.push({id:'1W', label:"1 week before"});
			remindersDP.push({id:'D', label:"Daily"});
			remindersDP.push({id:'W', label:"Weekly"});
			remindersDP.push({id:'F', label:"Fortnightly"});
			remindersDP.push({id:'M', label:"Monthly"});
		}
	}
	else
	{
		remindersDP.push({id:'1D', label:"1 day before"});
		remindersDP.push({id:'3D', label:"3 days before"});
		remindersDP.push({id:'1W', label:"1 week before"});
		remindersDP.push({id:'D', label:"Daily"});
		remindersDP.push({id:'W', label:"Weekly"});
		remindersDP.push({id:'F', label:"Fortnightly"});
		remindersDP.push({id:'M', label:"Monthly"});
	}
    
    for(var i=0;i<remindersDP.length;i++)
    {
        optionElement = document.createElement("OPTION");
        listControl.options.add(optionElement);
        optionElement.value = remindersDP[i].id;
        optionElement.innerText = remindersDP[i].label;	
		
   }
	
	if(editTaskMode == 'EDIT')
	{
		document.getElementById('reminder_select').value = currentTask.reminder;
		setView('addTask','Edit Task', 'Save Task', saveTask);
	}
	else
	{		
		setView('addTask','Add Task', 'Save Task', saveTask);
		document.getElementById('taskName_txt').focus();
	}
	
}

/* Add / Edit task view event listeners */

function onEnterTaskName(event)
{
	document.getElementById('addTask-nameLabel').style.display = 'none';	
}

function onMonthSelect(event)
{
	var monthControl = document.getElementById('month_select');
	populateDates(monthControl.selectedIndex);
	var dateControl = document.getElementById('date_select');
	dateControl.selectedIndex = 0;
}

/* Save task to server */

function saveTask()
{
	var taskName = getTextInputValue('taskName_txt');
	var taskNotes = getTextInputValue('taskNotes_txt');
	var dueDateString
	var reminderString
	
	var isRecurring = false;
	if(editTaskMode == 'EDIT') isRecurring = currentTask.isRecurring;
	
	taskCompleteInProgress = true;
    
    if(taskName == '')
    {
        alert('Please enter a task name');
    }
    else if(getTextInputValue('year_txt') < 1950 && isRecurring == false)
    {
        alert('Please enter a valid year. (YYYY)');
    }
    else
    {        
		dueDateString = getTextInputValue('year_txt');
		var monthControl = document.getElementById('month_select');
		var monthValue = monthControl.selectedIndex +1;
		dueDateString += '-'+monthValue+'-';
		var dateControl = document.getElementById('date_select');
		dueDateString += dateControl.selectedIndex +1;
		
		var reminderControl = document.getElementById('reminder_select');
		reminderString = reminderControl.value;
		
		
		
		
		var sendArray = [{name: "name",value: taskName},{name: "reminderType",value: reminderString},{name: "notes",value: taskNotes}]
		sendArray.push({name:"goalID",value: goalID});
		
		if(isRecurring == false)
		{
			sendArray.push({name:"dueDate",value: dueDateString});
		}
		else
		{
			sendArray.push({name:"recurringID",value: currentTask.recurringID});
		}
		
		var serverFunction;
		
		if(editTaskMode == 'EDIT')
		{
			if(isRecurring == true)
			{
				serverFunction = 'updateRecurringTask';
			}
			else
			{
				serverFunction = 'updateTask';
			}
			
			sendArray.push({name:"id",value: currentTask.id});
		}
		else
		{
			serverFunction = 'addTask';
			sendArray.push({name:"userID",value: userID});
		}		
		
		serverRequest(LIBRARY_GOALS, serverFunction, sendArray, savedTask);
    }
    
    function savedTask(xml)
	{
		taskCompleteInProgress = false;
		
		var browser = document.getElementById('browser').object; 
		var currentView = browser.goBack();
		
		if(currentGoalListItem != null && editTaskMode == 'ADD')
		{
			currentGoalListItem.activeTasksCount++;
			if(currentGoalListRowReference.goalList_row_progress != null) currentGoalListRowReference.goalList_row_progress.innerText = currentGoalListItem.activeTasksCount;
		}
		
		if(editTaskMode == 'ADD')
		{
			var obj = new Object();
			obj.id = xml.firstChild.getAttribute('id');
			obj.name = taskName;
			obj.dueDate = formatDate(dueDateString);
			obj.completed = false;
			obj.dueDateObject = generateDate(dueDateString);
			obj.isRecurring = false;
			obj.recurringID = "";
			obj.notes = taskNotes;
			
			var itemAdded = false;
			
			for(i=0;i<goalTasks.length;i++)
			{
				if(obj.dueDateObject < goalTasks[i].dueDateObject)
				{
					goalTasks.splice(i,0,obj);
					itemAdded = true;
					break;
				}
			} 
			
			if(itemAdded == false) goalTasks.push(obj);    
		}
		else
		{
			currentTask.name = taskName;
			currentTask.dueDateObject = generateDate(dueDateString);
			currentTask.dueDate = formatDate(dueDateString);			
			currentTask.reminder = reminderString;
			currentTask.notes = taskNotes;
		}
		
		completeGoalCheck();
		
		
		var listObj = document.getElementById('goalTasksList-ul').object;
		listObj.reloadData();
		
	}

}

function deleteTask()
{

	var answer = confirm("Are you sure?");
	if (answer == true)
	{
		serverRequest(LIBRARY_GOALS, 'deleteTask', [{name: "id", value:currentTask.id}], onDeletedTask);
	}
	
	function onDeletedTask(xml)
	{
		var index = getIndex('id', currentTask.id, goalTasks);
       goalTasks.splice(index,1);
		
		// Update the Active Goals counter on the main Goal List
		if(goalDetailParent == 'goalList')
		{
			currentGoalListItem.activeTasksCount--;	        
			currentGoalListRowReference.goalList_row_progress.innerText = currentGoalListItem.activeTasksCount;			
		}
		else
		{
			// Remove item from task list.
			tasksListData.splice(currentGoalIndex, 1);
			var listObj = document.getElementById('tasksList-ul').object;
			listObj.reloadData();
		}
		
		completeGoalCheck();
		
		var listObj = document.getElementById('goalTasksList-ul').object;
		listObj.reloadData();
		
		
		var browser = document.getElementById('browser').object; 
		var currentView = browser.goBack();
	}
}

function showCompleteRecurringTaskView()
{
	setView('completeRecurringTaskView','Recurring', 'Complete', completeRecurringInstances);
	document.getElementById('recurringCount_txt').innerHTML = currentRecurringTask.recurringInstancesCompleted +' of '+currentRecurringTask.recurringInstances+" completed";
	// Go to recurring completion page.
	
}

function completeRecurringInstances()
{
	var instancesToComplete
	if(document.getElementById('recurringInstances_rad').checked == true)
	{
		instancesToComplete = getTextInputValue('instancesCount_txt');
	}
	else if(document.getElementById('recurringSkip_rad').checked == true)
	{
		instancesToComplete = 'skip';
	}
	else
	{
		instancesToComplete = '-1';
	}
	
	serverRequest(LIBRARY_GOALS, 'completeRecurringTask', [{name: "id",value: currentRecurringTask.id},{name:"instancesToComplete",value: instancesToComplete}], onServerResponse);
	
	function onServerResponse(xml)
	{
	    taskCompleteInProgress = false;
	    
		if(xml.firstChild.getAttribute('allCompleted') == '1')
		{
			var date = new Date();
			currentRecurringTask.completionDate = date;
			currentRecurringTask.completed = true;
		}						

		currentRecurringTask.id = xml.firstChild.getAttribute('nextTaskID');
		if(instancesToComplete == '-1')
		{
			currentRecurringTask.recurringInstancesCompleted = currentRecurringTask.recurringInstances;
		}
		else if(instancesToComplete == 'skip')
		{
			currentRecurringTask.recurringInstances = currentRecurringTask.recurringInstances -1;
		}
		else
		{
			currentRecurringTask.recurringInstancesCompleted = Number(currentRecurringTask.recurringInstancesCompleted) + Number(instancesToComplete);
		}
		
		currentRecurringTask.dueDate = formatDate(xml.firstChild.getAttribute('nextDueDate'));
	    currentRecurringTask.dueDateObject = generateDate(xml.firstChild.getAttribute('nextDueDate'));
	    
		refreshGoalTasksList();
	
		updateListsAfterTaskCompleted(true);
		var browser = document.getElementById('browser').object; 
		var currentView = browser.goBack();
	}
}

function refreshGoalTasksList()
{
	goalTasks.sort(compareCompletionDate);

	var listObj = document.getElementById('goalTasksList-ul').object;
    listObj.reloadData();
}

function updateListsAfterTaskCompleted(isCompleted)
{
	// Update the Active Goals counter on the main Goal List
    if(goalDetailParent == 'goalList')
    {
        if(isCompleted == true)
        {
            currentGoalListItem.activeTasksCount--;
        }
        else
        {
            currentGoalListItem.activeTasksCount++;
        }
        
        currentGoalListRowReference.goalList_row_progress.innerText = currentGoalListItem.activeTasksCount;
    }
    else
    {
        // Remove item from task list.
        tasksListData.splice(currentGoalIndex, 1);
        var listObj = document.getElementById('tasksList-ul').object;
        listObj.reloadData();
    }
    
    completeGoalCheck();
}

/* Journal Entry */

function gotoJournalEntry()
{
	entryMode = 'journal';
	openEntryView('Journal entry');
}

/* Feedback Entry */

function provideFeedback()
{
	entryMode = 'feedback';
	openEntryView('Feedback'); 
}

/* Message input */

function openEntryView(title)
{
	setView('genericEntry',title, 'Submit', saveEntry);
	var journalInput = document.getElementById('messageInput_txt').focus();	
	var t=setTimeout(resetScrollPosition,200);
}

/* Save Entry */
    
function saveEntry()
{
	var message = getTextInputValue('messageInput_txt');
	
	if(entryMode == 'journal')
	{
	    serverRequest(LIBRARY_COMMON, 'addUserJournalEntry', [{name: "message",value: message}], onAddedEntry);
	}
	else{
	    serverRequest(LIBRARY_COMMON, 'submitHelpRequest', [{name: "message",value: message},{name: "category",value: 'iphone'}], onAddedEntry);
	}
	
	function onAddedEntry()
	{    
		var browser = document.getElementById('browser').object; 
		var currentView = browser.goBack();
		setTextInputValue('messageInput_txt','');	
	}
}


/* Get Task List */

var taskListMode = ''; // Either 'due' or 'overdue';
var tasksListData;
var currentStartPosition;

function showOverdueTasks()
{
	taskListMode = 'overdue';
	getTaskList('0');
}

function showDueTasks()
{
	taskListMode = 'due';
	getTaskList('0');
}


function getTaskList(startPos)
{
	currentGoalListItem = null // so the addTask function knows if it needs to update the main list.
	currentStartPosition = startPos;
	var listID;
	
	if(taskListMode == 'due')
	{
	    listID = 'tasksDue';
	}
	else
	{
	    listID = 'tasksOverdue'
	}
	
	if(startPos == '0') tasksListData = new Array(); 
	
	serverRequest(LIBRARY_GOALS, 'getTaskList', [{name: "type",value: listID}, {name:"startPosition",value:startPos}, {name:"numberOfResults",value:'10'}], gotTaskList);
	
	function gotTaskList(xml)
	{
		
		for(i=0;i<xml.firstChild.childNodes.length;i++)
		{
			var obj = new Object();
			obj.id = xml.firstChild.childNodes[i].getAttribute('id');
			obj.type = 'task';
			obj.name = xml.firstChild.childNodes[i].getAttribute('name');
			obj.goalID = xml.firstChild.childNodes[i].getAttribute('goalID');
			obj.goalName = xml.firstChild.childNodes[i].getAttribute('goalName');
			obj.coreValue = xml.firstChild.childNodes[i].getAttribute('coreValue');
			obj.dueDate = formatCoreValue(obj.coreValue)+' <span style="color:#999999">'+ xml.firstChild.childNodes[i].getAttribute('goalShortName')+'</span>'+', '+formatDate(xml.firstChild.childNodes[i].getAttribute('dueDate'));
			
			tasksListData.push(obj);
		}
		
		if(xml.firstChild.getAttribute('more') != '0')
		{
			var moreObj = new Object();
			moreObj.type = 'more';
			moreObj.name = 'More...';
			moreObj.nextPos = xml.firstChild.getAttribute('more');
			tasksListData.push(moreObj);
		}
		
		if(tasksListData.length == 0)
		{
			if(taskListMode == 'due')
			{
				alert('Sorry, you do not have any due tasks at the moment.');
			}
			else
			{
				alert('Well Done, you have no overdue tasks!');
			}			
		}
		else
		{
			var hscroll = (document.all ? document.scrollLeft : window.pageXOffset);
			var vscroll = (document.all ? document.scrollTop : window.pageYOffset);
			var listObj = document.getElementById('tasksList-ul').object;
			listObj.setDataSource(tasksDataSource);
		
			if(currentStartPosition == '0')
			{
				var title;
				if(taskListMode == 'due')
				{
					title = 'Due Tasks';
				}
				else
				{
					title = 'Overdue'
				}
			
				setView('taskList',title);
			} 
			else 
			{
				window.scrollTo(hscroll, vscroll);
			}
		}
	}
}


var tasksDataSource = {
		
	// The List calls this method to find out how many rows should be in the list.
	numberOfRows: function() { return tasksListData.length; },
	
	// The List calls this method once for every row.
	prepareRow: function(rowElement, rowIndex, templateElements) {
		// templateElements contains references to all elements that have an id in the template row.
        
        var listItem = tasksListData[rowIndex];
        
        if (templateElements.taskListName){
            templateElements.taskListName.innerText = listItem.name;
            
            if(listItem.type == 'task')
            {
                templateElements.taskListDate.innerHTML = listItem.dueDate;
            }
            else{
                templateElements.taskListName.style.top = '15px';
                templateElements.taskListDate.style.visibility = 'hidden';
                templateElements.taskListItemArrow.style.visibility = 'hidden';
                templateElements.taskListIcon.style.visibility = 'hidden';
            }
        }
        
        var taskGoalID = listItem.goalID;        
        var rowReference = templateElements;       

		// Assign a click event handler for the row.
		rowElement.onclick = function(event)
		{
			if(listItem.type == 'task')
			{
				currentGoalListRowReference = rowReference;
				currentGoalListItem = listItem;
				currentGoalIndex = rowIndex;
				goalDetailParent = 'taskList';
				getGoal(taskGoalID);
			}
			else
			{
				tasksListData.pop();
				getTaskList(listItem.nextPos);
			}

           
		};
	}
};


/* Journal 7 days view */

var JOURNAL_DAY = 'day';
var JOURNAL_WEEK = 'week';
var JOURNAL_MONTH = 'month';

var setJournalView = false;
var journalDateString;

var journalMode = JOURNAL_WEEK;

var journalCurrentDate;

function viewJournalScreen()
{
    setJournalView = true;
    
    if(journalCurrentDate == null)
    {
    	journalCurrentDate = new Date();
    }
    
    if(setJournalView == true)
    {
    	// get data and show
    	changeJournalView(journalMode);
    }
    else
    {
    	// just show
		setView('journalView', 'Journal');
    }
    
    
    
}

/* Journal Views */

function changeJournalView(view)
{
	if(view == journalMode)
	{
		// reset to today
		journalCurrentDate = new Date();
	}
	
	
	document.getElementById('journal_day').className = '';
	document.getElementById('journal_week').className = '';
	document.getElementById('journal_month').className = '';
	
	
	
	switch(view)
	{	
		case JOURNAL_DAY:
			if(journalMode == JOURNAL_WEEK)
			{
				var endWeek = new Date();
				endWeek.setFullYear(journalCurrentDate.getFullYear(), journalCurrentDate.getMonth(), journalCurrentDate.getDate());
				endWeek.setDate(journalCurrentDate.getDate()+7);
				var now = new Date();
				if(now < endWeek && now > journalCurrentDate )
				{
					journalCurrentDate = new Date();
				}
			}
			document.getElementById('journal_day').className = 'current';			
			break;
		
		case JOURNAL_MONTH:
			journalCurrentDate.setDate(1);
			document.getElementById('journal_month').className = 'current';
			break;
			
		default:
			document.getElementById('journal_week').className = 'current';
			journalCurrentDate.setDate(journalCurrentDate.getDate()- journalCurrentDate.getDay());
			break;
	}
	journalMode = view;
	
	
	var t=setTimeout(later,50);
	
	function later()
	{
		var startDateString = generateDateString(journalCurrentDate);
		getJournalData(startDateString);	
	}
	
	
}

/* Journal Navigation */

function journalNextDay()
{
	if(journalMode == JOURNAL_WEEK)
    {
		journalCurrentDate.setDate(journalCurrentDate.getDate()+ 7);
	}
	else if(journalMode == JOURNAL_DAY)
	{
		journalCurrentDate.setDate(journalCurrentDate.getDate()+ 1);
	}
	else
	{
		journalCurrentDate.setMonth(journalCurrentDate.getMonth()+ 1);
	}
	
	var startDateString = generateDateString(journalCurrentDate);
    getJournalData(startDateString);
}

function journalPreviousDay()
{
	if(journalMode == JOURNAL_WEEK)
    {
		journalCurrentDate.setDate(journalCurrentDate.getDate()- 7);
	}
	else if(journalMode == JOURNAL_DAY)
	{
		journalCurrentDate.setDate(journalCurrentDate.getDate()- 1);
	}
	else
	{
		journalCurrentDate.setMonth(journalCurrentDate.getMonth()- 1);
	}
	
	var startDateString = generateDateString(journalCurrentDate);
    getJournalData(startDateString);
}

/* Journal Data */

function getJournalData(dateString)
{
    // dateString must be YYYY-MM-DD 00:00:00
    journalDateString = dateString;
    getJournalCategories(nowGetJournalData);
}

function nowGetJournalData()
{
	if(journalMode == JOURNAL_MONTH)
	{
		var endDate = new Date();
		endDate.setFullYear(journalCurrentDate.getFullYear(), journalCurrentDate.getMonth(), journalCurrentDate.getDate());
		endDate.setMonth(endDate.getMonth()+1);
		endDate.setDate(0);
		var endDateString = generateDateString(endDate);
		serverRequest(LIBRARY_COMMON, 'getJournalMonthSummary', [{name: "startDate",value: journalDateString}, {name: "endDate",value: endDateString}, {name:"lightMode",value: "1"}], gotJournalData);
	}
	else
	{
		if(journalMode == JOURNAL_DAY)
		{
			numberOfDays = '1';
		}
		else
		{
			numberOfDays = '7';
		}
	    serverRequest(LIBRARY_COMMON, 'getJournal', [{name: "startDate",value: journalDateString}, {name: "numberOfDays",value: numberOfDays}, {name:"lightMode",value: "1"}], gotJournalData);
    }
}

function gotJournalData(xml)
{
	var mainString = '';
	
	if(setJournalView == true)
	{
		setJournalView = false;
		setView('journalView', 'Journal');
	}
	
	if(journalMode == JOURNAL_MONTH)
	{
		processMonthDate(xml);
	}
	else
	{
	
		if(xml.firstChild.childNodes.length == 0)
		{
			mainString = '<em style="color:#999">no entries...</em>';
		}
		else
		{
			if(journalMode == JOURNAL_WEEK)
	    	{
	    		
	    		document.getElementById('dateHeader').innerText = 'Week of '+formatDateString(xml.firstChild.childNodes[0].getAttribute('date'), false);
			}
			else if(journalMode == JOURNAL_DAY)
			{
				document.getElementById('dateHeader').innerText = getDay(journalCurrentDate.getDay()) +' '+formatDateString(xml.firstChild.childNodes[0].getAttribute('date'), false);
			}
			
			for(i=0;i<xml.firstChild.childNodes.length;i++)
			{
				// days...
				var dateString = xml.firstChild.childNodes[i].getAttribute('date');
				mainString += '<span class="journalDateHeading">'+formatDateString(dateString, false)+'</span>';
				
				if(xml.firstChild.childNodes[i].childNodes.length == 0)
				{
					mainString += '<span class="journalFirstItem"><em style="color:#999">no entries...</em></span>';
				}
				else
				{
					for(a=0;a<xml.firstChild.childNodes[i].childNodes.length;a++)
					{
						var entryType = xml.firstChild.childNodes[i].childNodes[a].getAttribute('entryType');
						
						var style = "";
						
						if(entryType == DUE_GOAL || entryType == DUE_TASK) style = 'style="background-color:#E2EAF2"';
						
						if(a ==0)
						{
						    mainString += '<span class="journalFirstItem" '+style+'>';
						}
						else
						{
						    mainString += '<span class="journalItem" '+style+'>';
						}
						
						mainString += getJournalIcon(xml.firstChild.childNodes[i].childNodes[a].getAttribute('entryType'), xml.firstChild.childNodes[i].childNodes[a].getAttribute('categoryID'));
						
						mainString += getJournalMessage(
						                                entryType, 
					                                xml.firstChild.childNodes[i].childNodes[a].getAttribute('categoryID'), 
					                                xml.firstChild.childNodes[i].childNodes[a].getAttribute('message')
					                                
					                                ) + '</span>';
					} 
				}
			}        	
		}
		
		var textAreaObj = document.getElementById('journalTextContent');
		textAreaObj.innerHTML = mainString;
	}
}

/* Journal Month display */

function processMonthDate(xml)
{

	var days = new Array();
	for(i=0;i<xml.firstChild.childNodes.length;i++)
	{
	
		var day = Object();
		day.date = xml.firstChild.childNodes[i].getAttribute('date')+' 00:00:00';
		day.categories = new Array();
		for(var b=0;b < xml.firstChild.childNodes[i].childNodes.length;b++)
		{
		
			var category = new Object();
			category.id = xml.firstChild.childNodes[i].childNodes[b].getAttribute('id');
			category.count = xml.firstChild.childNodes[i].childNodes[b].getAttribute('count');
			category.entryType = String(xml.firstChild.childNodes[i].childNodes[b].getAttribute('entryType'));
			category.categoryID = String(xml.firstChild.childNodes[i].childNodes[b].getAttribute('categoryID'));
			
			day.categories.push(category);
		}
		
		days.push(day);
		
	}
	
	var textAreaObj = document.getElementById('journalTextContent');
	textAreaObj.innerHTML = '';
	var cellCount = 0;
	var buildDate = new Date();
	var started = false;
	buildDate.setFullYear(journalCurrentDate.getFullYear(), journalCurrentDate.getMonth(), 1, 0, 0, 0, 0);
	var continueBuilding = true;
	
	document.getElementById('dateHeader').innerText = getMonth(buildDate.getMonth())+' '+buildDate.getFullYear();
	
	var table = document.createElement('table');
	table.className = 'journalMonth-table';
	table.cellSpacing = '0';
	table.cellPadding = '0';
	table.border = 'none';
	table.height= "100%";
	table.width = '100%';
	textAreaObj.appendChild(table);
	
	while(continueBuilding)
	{
		
		if(cellCount == 0 || cellCount == 7 || cellCount == 14 || cellCount == 21 || cellCount == 28 || cellCount == 35)
		{
			var tr = document.createElement('tr');
			tr.height = '100%';
			table.appendChild(tr);
		}
		
		if(buildDate.getDay() == cellCount || started == true)
		{
			// start
			started = true;	
			
			var dayBox = document.createElement('td');
			dayBox.className = 'journalMonth-day';
			dayBox.valign='top';
			dayBox.height = '100%';
			var dayObject = getDayObject(buildDate);
			
			if(dayObject != null)
			{
				var string = buildDate.getDate()+'<br>';
				
				for(var f=0; f<dayObject.categories.length;f++)
				{
					string += getJournalIcon(dayObject.categories[f].entryType, dayObject.categories[f].categoryID, false);
				}
				
				dayBox.innerHTML = string;
				dayBox.lt_date = dayObject.date
				var string2 = dayObject.date
				dayBox.onclick = function(event)
				{
					
					journalCurrentDate = generateDate(event.currentTarget.lt_date);
					changeJournalView(JOURNAL_DAY);					
				}
			}
			else
			{
				dayBox.innerHTML = buildDate.getDate();
			}
					 
			tr.appendChild(dayBox);
			buildDate.setDate(buildDate.getDate()+1);
			if(buildDate.getMonth() != journalCurrentDate.getMonth()) continueBuilding = false;
			
		}
		else
		{
			var dayBox = document.createElement('td');
			dayBox.className = 'journalMonth-dayHolder';	
			tr.appendChild(dayBox);
		}
		
		cellCount++;
		
		if(cellCount > 60) continueBuilding = false;
		
	}
	
	function getDayObject(date)
	{
		//var test = generateDateString(date);
		date.setHours(0,0,0,0);
		
		for(var i=0; i<days.length;i++)
		{
			var date2 = generateDate(days[i].date)
			if(formatDateString(generateDateString(date), false) == formatDateString(generateDateString(date2), false))
			{
				
				return days[i];
				break;
			}
		}
		
		return null;
	}

}


/* Journal Display */

var GOAL_ADJUST_EST_DUE_DATE = 'goalAdjustEstDueDate';
var GOAL_CREATE = 'createGoal';
var GOAL_ABORT = 'deletedGoal';
var GOAL_COMPLETED = 'completedGoal';
var TASK_CREATE = 'addTask';
var TASK_DELETE = 'deletedTask';
var TASK_COMPLETED = 'completedTask';
var TASK_UNCOMPLETED = 'uncompletedTask';
var USER_NOTE = 'userNote';
var USER_CUSTOM = 'userCustom';

var TASK_RECURRING_CREATE = 'addRecurringTask';
var TASK_RECURRING_SKIP = 'skippedRecurringTask';
var TASK_RECURRING_COMPLETED = 'completedRecurringTask';

var DUE_GOAL = 'dueGoal';
var DUE_TASK = 'dueTask';

function getJournalIcon(entryType, categoryID, formatType)
{
//	return '';
	var returnImage = '';
	
	
	switch(entryType)
    {
				
		case TASK_UNCOMPLETED:
			returnImage = 'addTask';
			break;
		
		case TASK_RECURRING_SKIP:
			returnImage = 'deletedTask';
			break;
			
		case TASK_CREATE:
		case TASK_COMPLETED:
		case TASK_DELETE:
		case GOAL_CREATE:		
		case GOAL_COMPLETED:
		case GOAL_ABORT:
		case GOAL_ADJUST_EST_DUE_DATE:	
		case USER_NOTE: 		
		case TASK_RECURRING_CREATE:		
		case TASK_RECURRING_COMPLETED:
		case DUE_GOAL:
		case DUE_TASK:		
			returnImage = entryType; 			             
			break;

		case USER_CUSTOM:
			var index = getIndex('id',categoryID, journalAllCategories);
			returnImage = 'categories/'+journalAllCategories[index].icon; 
   			break; 
   			
        
        default:
            returnImage = ''; 
        
       
    }
    
    if(returnImage == '')
    {
    	return '';
    }
    else
    {
    	if(formatType != null)
    	{
    		if(entryType == USER_CUSTOM)
	    	{
	    		return '<img src="https://www.lifetick.com/iPhone/journalIcons/'+returnImage+'.png" />';
	    	}
	    	else
	    	{
	    		return '<img src="https://www.lifetick.com/iPhone/journalIcons/'+returnImage+'.png" />';
	    	}
    	}
    	else
    	{
    		
	    	return '<div style="width:20px;padding-top:-1px;padding-right:6px;float:left"><img src="journalIcons/'+returnImage+'.png" /></div>';
	    	
    	}
    }

}

function getJournalMessage(entryType, categoryID, _message)
{
	var returnTitle = '';
	var hideMessage = false;
    switch(entryType)
    {
        case TASK_UNCOMPLETED:
            returnTitle = 'Un-Completed the task ';           
            break;				
            
        case TASK_CREATE:
            returnTitle = 'Created the task ';           
            break;				
        
        case TASK_COMPLETED:
            returnTitle = 'Completed the task ';           
            break;				
        
        case TASK_DELETE:
            returnTitle = 'Deleted the task ';           
            break;				

		case TASK_RECURRING_CREATE:
			hideMessage = true;
			var parts3 = _message.split('!_!');
			returnTitle =  "<span style=\"color:#666\">Created the recurring task </span>'"+parts3[0]+"'";
			break;
		
		case TASK_RECURRING_SKIP:
			hideMessage = true;
			var parts4 = _message.split('!_!');
			var countLabel = 'an ';
			if(parts4[1] == '1') countLabel = 'the last ';
			return "<span style=\"color:#666\">Skipped "+countLabel+"instance of the task </span>'"+parts4[0]+"'";
			break;
			
		case TASK_RECURRING_COMPLETED:
			hideMessage = true;
			var parts2 = _message.split('!_!');
			if(parts2[1] == '*') parts2[1] = 'the remaining';
			var labelType = 's';
			if(parts2[1] == '1') labelType = '';
			if(parts2[2] == '1') parts2[1] = 'the last '+parts2[1];
			if(parts2[2] == '1' && parts2[1] == '1') parts2[1] = 'the last '; // the last instance (with only 1 completed)
			returnTitle =  "<span style=\"color:#666\">Completed "+parts2[1]+" instance"+labelType+" of the task </span>'"+parts2[0]+"'";
       		break;

        case GOAL_CREATE:
            returnTitle = 'Created the goal ';           
            break;				
        
        case GOAL_COMPLETED:
            returnTitle = 'Completed the goal ';           
            break;				
        
        case GOAL_ABORT:
            returnTitle = 'Aborted goal ';           
            break;
        
        case GOAL_ADJUST_EST_DUE_DATE:
			
			hideMessage = true;
			
			var parts = _message.split('!_!');
			if(parts.length < 3)
			{
				returnTitle = '<span style="color:#666">Adjusted goal due date</span>';
			}
			else
			{
				if(parts[1] == '-')
				{
					returnTitle = "<span style=\"color:#666\">Brought forward </span>'"+parts[0]+"'<span style=\"color:#666\"> by </span>"+parts[2];
				}
				else
				{
					returnTitle = "<span style=\"color:#666\">Pushed back </span>'"+parts[0]+"'<span style=\"color:#666\"> by </span>"+parts[2];
				}
			}        	         	  
        	  break;
        case USER_CUSTOM:
			
			hideMessage = true;
			
			var index = getIndex('id',categoryID, journalAllCategories);
            
			if(index != -1)
			{
				if(journalAllCategories[index].dataType == 'counter')
				{
					returnTitle = journalAllCategories[index].name;
				}
				else if(journalAllCategories[index].dataType == 'currency')
				{
					returnTitle = '<span style="color:#666">'+journalAllCategories[index].name+":</span> "+journalAllCategories[index].unit+' '+_message;
				}
				else
				{
					returnTitle = '<span style="color:#666">'+journalAllCategories[index].name+":</span> "+_message+' '+journalAllCategories[index].unit;
				}
			}
            
            break;
                        
        case USER_NOTE:            
            returnTitle = '';
            break;
		//
		case DUE_GOAL:            
            returnTitle = 'Goal due: ';
            break;
		//
		case DUE_TASK:            
            returnTitle = 'Task due: ';
            break;
        
        default:
            returnTitle = '-';
        
       
    }
    
    if(hideMessage == true)
    {
    	return returnTitle;
    }
    else
    {
    	return '<span style="color:#666">'+returnTitle+"</span> '"+_message+"'";
    }
}

/* Journal Category entry */

function getJournalCategories(callBack)
{
    if(journalCategories.length == 0)
    {
        serverRequest(LIBRARY_COMMON, 'getJournalCategories', [], gotJournalCategories);
    }
    else
    {
        callBack();
    }
    
    function gotJournalCategories(xml)
    {
        journalCategories = new Array();
        journalAllCategories = new Array();
        
        for(var i=0;i<xml.firstChild.childNodes.length;i++)
        {            
            var obj = new Object();
            obj.name = xml.firstChild.childNodes[i].getAttribute('name');
            obj.id = xml.firstChild.childNodes[i].getAttribute('id');
            obj.dataType = xml.firstChild.childNodes[i].getAttribute('dataType');
            obj.unit = xml.firstChild.childNodes[i].getAttribute('unit');
            obj.active =  xml.firstChild.childNodes[i].getAttribute('active');
            obj.icon = xml.firstChild.childNodes[i].getAttribute('icon');
            
            journalAllCategories.push(obj);
            if(obj.active == '1') journalCategories.push(obj);            
        }
        
        callBack();
    }
}

function gotoJournalCategoryEntry(event)
{
    getJournalCategories(nowGotoJournalCategoryEntry);
}

function nowGotoJournalCategoryEntry()
{
    
    if(setJournalCategoriesList == false)
    {
        setJournalCategoriesList = true;
        var listControl = document.getElementById('jCat_cmb');
        
        var optionElement = document.createElement("OPTION");
        listControl.options.add(optionElement);
        optionElement.value = '';
        optionElement.innerText = 'Select category';
        
        for(var i=0;i<journalCategories.length;i++)
        {
            optionElement = document.createElement("OPTION");
            listControl.options.add(optionElement);
            optionElement.value = journalCategories[i].id;
            optionElement.innerText = journalCategories[i].name;
       }
   }
   
   onJCatSelect();
    
   setView('journalCategoryEntry', 'Category entry', 'Submit', submitJournalCategory);
    
}

function onJCatSelect()
{
	var listControl = document.getElementById('jCat_cmb');
	var catLabel = document.getElementById('jCatValue_lbl');
	var catInput = document.getElementById('jCatValue_txt'); // empty on save
	
	if(listControl.selectedIndex == 0)
	{
		catLabel.style.visibility = 'hidden';
		catInput.style.visibility = 'hidden';
	}
	else
	{
		var index = listControl.selectedIndex-1;
		var catType = journalCategories[index].dataType;
			
		switch(catType)
		{
			case 'counter':
				catLabel.style.visibility = 'visible';
				catLabel.innerText = '+1';
				catInput.style.visibility = 'hidden';
				break;
			
			case 'text':
				catLabel.style.visibility = 'visible';
				catInput.style.visibility = 'visible';
				catLabel.innerText = 'Value';
				catInput.style.width = '255px';
				break;
			
			case 'numeric':
				catLabel.style.visibility = 'visible';
				catInput.style.visibility = 'visible';
				catLabel.innerText = journalCategories[index].unit;
				catInput.style.width = '100px';
				break;
			
			case 'currency':
				catLabel.style.visibility = 'visible';
				catInput.style.visibility = 'visible';
				catLabel.innerText = journalCategories[index].unit;
				catInput.style.width = '100px';
				
				break;
		}
		
		catInput.blur();
		if(catType != 'counter') catInput.focus();
			
		
	}
	
	
    
}

function onEnterJournalCatValue(event)
{
	document.getElementById('jCatValue_lbl').style.display = 'none';	
}

function submitJournalCategory()
{
	var listControl = document.getElementById('jCat_cmb');
	if(listControl.selectedIndex == 0)
	{
		alert('Please select a category');
	}
	else
	{
		
		var index = listControl.selectedIndex-1;
		var catType = journalCategories[index].dataType;
		var catID = journalCategories[index].id;
		var catInput = document.getElementById('jCatValue_txt');
		
		if(catType != 'counter' && getTextInputValue('jCatValue_txt') == '')
		{
			alert('Please enter a value before continuing');
		}
		else
		{
			var valid = true;
			if(catType == 'currency' || catType == 'numeric')
			{
				var test = parseFloat(getTextInputValue('jCatValue_txt'));			
				if(isNaN(test) == true)
				{
					alert('Please enter a numeric value');
					valid = false;
				}
			}
		
			if(valid == true)
			{
				serverRequest(LIBRARY_COMMON, 'addCustomJournalEntry', [{name: "categoryID",value: catID}, {name:"value",value: getTextInputValue('jCatValue_txt')},{name: "dateTime",value: ''}], addedJournalCategory);
			}
		}
	}
    
    function addedJournalCategory(xml)
    {
        var control = document.getElementById('jCatValue_txt');
        control.blur();
        var browser = document.getElementById('browser').object; 
        var currentView = browser.goBack();
        setTextInputValue('jCatValue_txt','');
    }
}

/* Main menu counters */

function getCounters()
{
    serverRequest(LIBRARY_GOALS, 'getGoalCounters', [], gotCounters);
}

function gotCounters(xml){
    var goalCounterBox = document.getElementById('goalCounter_box');
    goalCounterBox.innerHTML =  xml.firstChild.getAttribute('activeGoals');
    var dueCounterBox = document.getElementById('dueCounter_box');
    dueCounterBox.innerHTML =  xml.firstChild.getAttribute('dueTasks');
    var overdueCounterBox = document.getElementById('overdueCounter_box');
    overdueCounterBox.innerHTML =  xml.firstChild.getAttribute('overdueTasks');
    
    if(xml.firstChild.getAttribute('overdueTasks') == '0')
    {
    	overdueCounterBox.style.backgroundColor = 'rgb(154, 171, 186)';
    	overdueCounterBox.style.borderColor = 'rgb(154, 171, 186)';
    }
    else
    {
    	overdueCounterBox.style.backgroundColor = '#ff0000';
    	overdueCounterBox.style.borderColor = '#ff0000';
    }
}


