/*================================================================================================================
 * JavaScript functions for the Meeting Success Strategic Action Plan (SAP)
 * Author: Bryan Soh-Lim
 * Year:   2007
 *
 * For use strictly as part of the SAP
 *===============================================================================================================*/

function doDropdown(elementId)
{
	if(dropdown == '')
	{
		document.getElementById(elementId).style.display = 'none';
	}
}

/*==========================================Local Data Preservation==============================================*/
//document.write(document.cookie);
/**/
function setSaved()
{
	saved = true;
	eraseAllCookies();
	//alert('erased');
}

/**/
function askToSave(saveTimer)
{
	if(!saved)
	{
		if(!saveTimer) var asktoSave=confirm("You still have unsaved data on this page!\n\nSelect OK to save your data and continue on the requested page.\nSelect Cancel to discard changes on this page.");
		else var asktoSave=true;
		
		if(asktoSave)
		{
			var inputs = document.getElementsByTagName('input');
			var textAreas = document.getElementsByTagName('textarea');
			var selects = document.getElementsByTagName('select');
			
			var testingArray = new Array();
			
			for(var i = 0; i < inputs.length; i++)
			{
				if(inputs[i].name.indexOf('_') == -1 || !saveTimer) 
				testingArray[testingArray.length] = inputs[i];
			}
			
			for(var i = 0; i < textAreas.length; i++)
			{
				if(textAreas[i].name.indexOf('_') == -1 || !saveTimer)
				testingArray[testingArray.length] = textAreas[i];
			}
			
			for(var i = 0; i < selects.length; i++)
			{
				if(selects[i].name.indexOf('_') == -1 || !saveTimer)
				testingArray[testingArray.length] = selects[i];
			}
			
			var testingData = '';
			for(i=0;i<testingArray.length;i++)
			{
				//DO NOT submit the 'savenew' request - this would cause a new plan rather than an update
				if(testingArray[i].name != 'saveNew' 
				   && !(testingArray[i].type == 'checkbox' && !testingArray[i].checked) 
				   && !(testingArray[i].name == 'submit' && (testingArray[i].value == 'Add New Branch' || testingArray[i].value == ' Go '))) 
				{
					if(i > 0) testingData += '&';
					testingData += testingArray[i].name + '=' + testingArray[i].value;
				}
			}
			
			if(!saveTimer)
			{
				var response = '';
				if(response = loadXMLDoc(thisHref.replace('index.php', 'backgroundSaver.php')+'&', testingData, false)) 
				{	
					eraseAllCookies();
					alert(response);
				}
				else
				{
					alert('There has been an error while saving your data. Your data should still be stored in memory. Please go back to the previous page and click \'Save Changes\' to save your data.');
				}
			}
			else
			{
				loadXMLDoc(thisHref.replace('index.php', 'backgroundSaver.php')+'&', testingData, false);
			}
		}
		else
		{
			eraseAllCookies();
		}
	}
	
	if(!saveTimer) saved = true; //Because this method could potentially be called twice (in browsers that support the onbeforeunload event), set saved=true so that it won't run a second time.
	
	if(saveTimer) setTimer(); //1 minute autosave
}


/**/
function getInputsByClass(className)
{
	var inputs = document.getElementsByTagName('input');
	var textAreas = document.getElementsByTagName('textarea');
	var selects = document.getElementsByTagName('select');
	
	var toReturn = new Array();
	
	for(var i = 0; i < inputs.length; i++)
	{
		if(inputs[i].className.indexOf(className) != -1 && inputs[i].id != 'infoCell' && inputs[i].id != 'columnTitle')
		{
			toReturn[toReturn.length] = inputs[i];
		}
	}
	
	for(var i = 0; i < textAreas.length; i++)
	{
		if(textAreas[i].className.indexOf(className) != -1 && textAreas[i].id != 'infoCell' && textAreas[i].id != 'columnTitle')
		{
			toReturn[toReturn.length] = textAreas[i];
		}
	}
	
	for(var i = 0; i < selects.length; i++)
	{
		if(selects[i].className.indexOf(className) != -1 && selects[i].id != 'infoCell' && selects[i].id != 'columnTitle')
		{
			toReturn[toReturn.length] = selects[i];
		}
	}
	
	return toReturn;
}

/**/
function addInputDetectors(className)
{
	var inputs = getInputsByClass(className);
	
	for(var i = 0; i < inputs.length; i++)
	{
		addInputDetector(inputs[i]);
	}
}

/**/
function addInputDetector(input)
{
	if(input.type == 'checkbox')
	{
		input.onmouseup = function(e)
		{
			if(!this.checked)
			{
				//COOKIERE setCookie('pt_'+this.name,'true',1);
			}
			else
			{
				//COOKIERE setCookie('pt_'+this.name,'false',1);
			}
				
			if(saved)
			{
				saved = false;
			}
			
			if(activityUpdate)
			{
				actionNotify();
			}
		}
	}
	else if(input.tagName == 'SELECT')
	{
		input.onchange = function(e)
		{
			if(saved)
			{
				saved = false;
			}
			
			if(activityUpdate)
			{
				actionNotify();
			}
		}
	}
	else
	{
		input.onkeyup = function(e)
		{
			if(window.event)
			{
				e = window.event;
			}			
	
			//COOKIERE setCookie('pt_'+this.name,this.value,1);
			
			if(saved && e.which != 13)
			{
				saved = false;
			}		
			
			if(activityUpdate)
			{
				actionNotify();
			}
		}
	}
	
	if(input.type == 'checkbox' || input.type == 'text')
	{
		input.onkeypress = function(e)
		{
			if(window.event)
			{
				e = window.event;
			}			
			
			if(e.which == 13) //Enter
			{
				saved = true;
				eraseAllCookies();			
			}				
		}
	}
	
	/*Help Popups*/
	input.onmouseover = function()
	{
		if(showHelp)
		{
			var label = document.getElementById('helpLabel');
			label.style.display = 'block';
			
			if(this.name.indexOf('branchItem') != -1)
			{
				label.innerHTML = getHelpContent(this.value);
			}
			else if(this.name.indexOf('addDirectionList') != -1)
			{
				label.innerHTML = getHelpContent(this.options[this.selectedIndex].text);
			}
			else
			{
				label.innerHTML = getHelpContent(this.name);
			}
			
		}
	}
	
	input.onmousemove = function(e)
	{
		if(showHelp)
		{
			var myWidth = 0;
			
			if(typeof(window.innerWidth) == 'number') //window.innerWidth is not supported by IE browsers
			{
				myWidth = window.innerWidth;
			} 
			else if(document.documentElement && document.documentElement.clientWidth) //documentElement seems to be used by IE
			{
				myWidth = document.documentElement.clientWidth;
			} 
			else if(document.body) //IE 4 and 5 can use document.body to determine window size
			{
				myWidth = document.body.clientWidth;
			}		
			
			var label = document.getElementById('helpLabel');
			var offset = 5;
			
			if(window.event)
			{	
				e = window.event;
			}
			
			if(e.clientX+350 > myWidth)
			{
				offset = -325;
			}	
			
			var scrollY = 0;
			if(document.body.scrollTop) 
			{
				scrollY = document.body.scrollTop;
			}
			else if(document.documentElement.scrollTop) 
			{
				scrollY = document.documentElement.scrollTop;
			}
			
			var scrollX = 0;
			if(document.body.scrollLeft) 
			{
				scrollX = document.body.scrollLeft;
			}
			else if(document.documentElement.scrollLeft) 
			{
				scrollX = document.documentElement.scrollLeft;
			}			
			
			label.style.top = (e.clientY+scrollY) + 'px';
			label.style.left = (e.clientX+scrollX+offset) + 'px';
		}
	}
	
	input.onmouseout = function()
	{
		if(showHelp)
		{
			var label = document.getElementById('helpLabel');
			label.style.display = 'none';
			label.innerHTML = ' ';
		}
	}
}

/**/
function getHelpContent(inputName)
{
	if(inputName.indexOf('planTitle') != -1)
	{
		return '<strong>Plan Title</strong><br />Type the name of your organisation.<br />This will appear on the cover of your Strategic Plan.';
	}
	else if(inputName.indexOf('planStartDate') != -1)
	{
		return '<strong>Start Date</strong><br />Enter the first year of your plan.';
	}
	else if(inputName.indexOf('planEndDate') != -1)
	{
		return '<strong>End Date</strong><br />Enter the year that the plan will end.<br />Three years is an effective Strategic Plan period.';
	}
	else if(inputName.indexOf('planApprovalDate') != -1)
	{
		return '<strong>Approval Date</strong><br />The date that this Plan was approved by the Board. Enter the date through the calendar by clicking the calendar button.';
	}
	else if(inputName.indexOf('planReviewDate') != -1)
	{
		return '<strong>Review Date</strong><br />A reminder to review the plan. If this field is cleared or left empty, the SAP will automatically enter a date one year after the approval date above.';
	}
	
	
	else if(inputName.indexOf('planContextStatement') != -1)
	{
		return '<strong>CONTEXT STATEMENT</strong><br />In a paragraph give a few facts and figures to describe the organisation, a little of its history, current work and environment. Mention major issues, pressures and events that affect it with just enough information to create understanding of the organisation and the issues that affect it now and in the future.';
	}
	else if(inputName.indexOf('planVisionStatement') != -1)
	{
		return '<strong>VISION STATEMENT</strong><br />Devise a very short ‘big-picture’ statement of what could result from the work of the organisation if it had limitless power and resources.<br /><br />Some Vision Statements examples are:<ul><li>‘Feed the world’</li><li>‘Amaze the world’</li><li>‘No child living in Poverty.’</li><li>A world free from HIV</li></ul>These grand statements ‘pull the organisation forward’ encouraging it to continually improve.';
	}
	else if(inputName.indexOf('planMission') != -1)
	{
		return '<strong>MISSION STATEMENT</strong><br />Create a broad statement that aligns with the organisation’s constitutional objects and states:<ul><li>The purpose of the organisation</li><li>Who the organisation serves in broad terms. (Specific lists of who the organisation serves appears in the later Community of Focus category)</li><li>How the organisation will work to achieve its Vision Statement</li></ul>';
	}
	else if(inputName.indexOf('planFocusCommunity') != -1)
	{
		return '<strong>Community of Focus</strong><br />The organisation’s clients, customers or consumers.';
	}
	else if(inputName.indexOf('planValuesAndPrinciples') != -1)
	{
		return '<strong>Values and Principles</strong><br />A set of short statements about the:<ul><li><em>Values</em> important to the organisation</li><li><em>Principles</em> that guide its service delivery.</li></ul>';
	}
	else if(inputName.indexOf('planStrategicPartners') != -1)
	{
		return '<strong>Strategic Partners</strong><br />These are organisations or people with whom there are formal agreements about joint service delivery. Don’t include funders such as government departments. They purchase services from organisations and are usually included as stakeholders.';
	}
	else if(inputName.indexOf('planStakeholders') != -1)
	{
		return '<strong>Stakeholders</strong><br />These people or organisations may be affected by service provision and actions of the organisation or business and its consumers.  They can include individuals, organisations or businesses, all levels of governments, clients and their families, even neighbours of the service or neighbours of clients, customers or consumers.';
	}
	
	
	else if(inputName.indexOf('directionDescription') != -1)
	{
		return '<strong>Directions</strong><br /><em>Directions</em> are clear statements stating specific program or service delivery goals or outcomes to be achieved in the plan period.<br /><br />To focus the plan and keep it achievable we recommended that you define 6 <em>Directions</em>, despite the plan capacity to create 10 <em>Directions</em>.';
	}
	
	
	else if(inputName.indexOf('strategyDescription') != -1)
	{
		return '<strong>Strategy</strong><br />A <em>Strategy</em> is an action to be used to achieve a <em>Direction</em> (or goal).<br /><br />Every <em>Direction</em> has at least one <em>Strategy</em>, but usually more.<br /><br />The Plan allows for 8 <em>Strategies</em> per <em>Direction</em>.';
	}
	else if(inputName.indexOf('strategyObjective') != -1)
	{
		return '<strong>Objectives</strong><br />Objectives (targets) describe the measured outcome (evidence) required to show that a strategy has been successfully completed.<br /><br />Include quantities, dates, money amounts, places and specific client or customer groups.';
	}
	
	
	else if(inputName.indexOf('taskDone') != -1)
	{
		return '<strong>Done?</strong><br />Tick this box after a <em>Task</em> has been completed.<br /><br />‘Sort’ to separate tasks <em>Done</em> and <em>Not Done</em>.';
	}
	else if(inputName.indexOf('taskDescription') != -1)
	{
		return '<strong>Task Description</strong><br />List the specific tasks required to achieve the Objective and Strategy.<br /><br />You may list up to 20 tasks per Strategy.';
	}
	else if(inputName.indexOf('taskPersonResponsible') != -1)
	{
		return '<strong>Person Responsible</strong><br />Name a person responsible to ensure that the task is implemented.';
	}
	else if(inputName.indexOf('taskReportsTo') != -1)
	{
		return '<strong>Reports To</strong><br />Name the person or position to which the Person Responsible reports. ';
	}
	else if(inputName.indexOf('taskStartDate') != -1)
	{
		return '<strong>Start Date</strong><br />Using the calendar, insert the proposed starting date of this task.<br /><br />You can edit and sort all fields either on this page or the Tasks and Timelines page.';
	}
	else if(inputName.indexOf('taskCompleteDate') != -1)
	{
		return '<strong>Complete Date</strong><br />Insert the date you plan to have this task finished. <br /><br />You can later amend dates if they later appear unreasonable or if delays occur.';
	}
	else if(inputName.indexOf('taskMonitoring') != -1)
	{
		return '<strong>Monitoring</strong><br />Insert comments about monitoring processes, such as: Monitor in ‘support & supervision’ sessions, Report to Team meetings, 3 monthly Board Report.<br /><br />See examples in <em>Try It Out</em> (on the Log in page).';
	}
	else if(inputName.indexOf('taskMoneyAllocated') != -1)
	{
		return '<strong>Money Allocated</strong><br />Insert or edit the amount of money required (and/or approved) for this task.';
	}
	else if(inputName.indexOf('taskMoneySpent') != -1)
	{
		return '<strong>Money Spent</strong><br />Use this sheet to monitor money spent on Strategies<br /><br />Update the amount of money spent to date on this Task.'
	}
	else if(inputName.indexOf('taskTimeAllocated') != -1)
	{
		return '<strong>Hours Allocated</strong><br />Estimate the time (in hours) required for the task.';
	}
	else if(inputName.indexOf('taskOtherResources') != -1)
	{
		return '<strong>Other Resources</strong><br />List people, organisations, equipment, websites, processes required to achieve this <em>Task</em>.';
	}
	else if(inputName.indexOf('taskProgress') != -1)
	{
		return '<strong>Task Progress</strong><br />Use this field to record task progress. When you’ve finished the task, click the ‘Task Done’ box.  Use the Gantt chart to see the tasks by timeline and done/not-done.';
	}
	else if(inputName.indexOf('branchDescription') != -1)
	{
		return '<strong>Branch Description</strong><br />Enter some text describing this <em>Branch</em>.';
	}
	else if(inputName.indexOf('branchManager') != -1)
	{
		return '<strong>Branch Manager</strong><br />Select the sub-user you want to manage this <em>Branch</em>. They will have priviliges to edit the branch contents as well as view the entire plan.';
	}
	else if(inputName.indexOf('Direction ') != -1)
	{
		return '<strong>'+inputName+' Description</strong><br />'+directionDescriptionsArray[inputName];
	}
}


/**/
function loadCookieData(className)
{
	/*=============================================================================================
	 *
	 *	Performing row removals and additions for standard plan pages
	 *
	 *============================================================================================*/
	//removal of 'existing' rows
	var removeNum = 0;
	var removeArgs = getCookie('pt_removeRow'+removeNum);
	while(removeArgs != null && removeArgs != "")
	{
		var argsArray = removeArgs.split('|');
		removeRow(argsArray[0], argsArray[1], argsArray[2]);

		removeNum++;
		removeArgs = getCookie('pt_removeRow'+removeNum);
	} 
	
	
	//adding ALL rows that were added to the plan, including those that were deleted
	var newRowsArray = new Array();
	for(var parentIndex = 0; parentIndex < Math.max(maxDirections, maxStrategies); parentIndex++)
	{
		for(var parentNum = 0; parentNum < maxTasks; parentNum++)
		{
			var addedRow = getCookie('pt_newRow'+parentIndex+'_'+parentNum);
			
			if(addedRow != null && addedRow != "")
			{
				var argsArray = addedRow.split('|');
				newRowsArray[newRowsArray.length] = addField(argsArray[0], argsArray[1], argsArray[2], argsArray[3], true);	//true indicates to bypass max limits			
			}
		}
	}
	
	//check for each new added row whether it was previously removed, and if so, remove it
	for(var i = 0; i < newRowsArray.length; i++)
	{
		var removeNewRow = getCookie('pt_remove'+newRowsArray[i].id);
		if(removeNewRow != null && removeNewRow != "")
		{
			newRowsArray[i].parentNode.removeChild(newRowsArray[i]);
			//setCookie('remove'+this.parentNode.id,removeNewRow,1);
			//counters[parseInt(removeNewRow)]--;
			existingNumbers[removeNewRow]--;
		}
	}
	
	
	/*=============================================================================================
	 *
	 *	Performing row removals and additions for branch pages - requires specific functions due 
	 *	to the drop down lists that provide options
	 *
	 *============================================================================================*/
	//removal of 'existing' branch sub items - only for branch management
	removeNum = 0;
	var removeArgs = getCookie('pt_removeItem'+removeNum);
	while(removeArgs != null && removeArgs != "")
	{
		var argsArray = removeArgs.split('|');
		removeBranchItem(argsArray[0], argsArray[1], argsArray[2], argsArray[3], argsArray[4]);

		removeNum++;
		removeArgs = getCookie('pt_removeItem'+removeNum);
	} 
	
	//adding all branch sub items that were added, including those deleted
	var newItemsArray = new Array();
	var newItemIDsArray = new Array(); //array used to check against removals - to determine if a list entry should be re-added or not
	for(var branchNumber = 0; branchNumber < maxBranches; branchNumber++)
	{
		for(var itemNum = 0; itemNum < Math.max(maxDirections, numSubUsers); itemNum++)
		{
			var addedItem = getCookie('pt_newItem'+branchNumber+'_'+itemNum);
			
			if(addedItem != null && addedItem != "")
			{
				var argsArray = addedItem.split('|');
				//setCookie('pt_'+newFields.id,fieldName+'|'+parent+'|'+countersIndex+'|'+itemListID+'|'+itemName+'|'+itemID, ,1);
				newItemsArray[newItemsArray.length] = addBranchItem(argsArray[0], argsArray[1], argsArray[2], argsArray[3], true, argsArray[4], argsArray[5]);	//true indicates this is loading cookie data, the last two args are the item name and the item id (be it direction or user)	
				newItemIDsArray[newItemIDsArray.length] = argsArray[5]; //record the value/id
			}
		}
	}
	
	//check for each new added branch sub item whether it was previously removed, and if so, remove it
	var addedArray = new Array();
	for(var i = 0; i < newItemsArray.length; i++)
	{
		var removeNewItem = getCookie('pt_remove'+newItemsArray[i].id);
		
		if(removeNewItem != null && removeNewItem != "")
		{		
			var argsArray = removeNewItem.split('|');
			
			var numAdded = 0;
			var numRemoved = 0;
			
			//tally up the total number of times this list item has been added
			for(var j = 0; j < newItemIDsArray.length; j++)
			{
				if(newItemIDsArray[j] == argsArray[2]) numAdded++;
			}	
			
			//tally up the total number of times this list item has been removed
			for(var j = 0; j < newItemsArray.length; j++)
			{
				var removeCheckItem = getCookie('pt_remove'+newItemsArray[j].id);
				
				if(removeCheckItem != null && removeCheckItem != "")
				{
					var argsCheckArray = removeCheckItem.split('|');
					if(argsCheckArray[2] == argsArray[2]) numRemoved++;
				}
			}	
			
			//check if the list item has already been re-added
			var alreadyAdded = false;
			for(var j = 0; j < addedArray.length; j++)
			{
				if(addedArray[j] == argsArray[2]) alreadyAdded = true;
			}
			
			//if it has not been re-added and it should be re-added, do so
			if(numRemoved >= numAdded && !alreadyAdded)
			{
				var itemList = document.getElementById(argsArray[3]);
				
				var siblingNodes = newItemsArray[i].parentNode.childNodes;
				var thisOption = document.createElement('option');
				thisOption.value = argsArray[2];
				thisOption.text = argsArray[1];
				itemList.add(thisOption, null);		
				
				addedArray[addedArray.length] = argsArray[2]; //add value to a list of values that have already been added back
			}
			
			newItemsArray[i].parentNode.removeChild(newItemsArray[i]);
		}
	}	
	
	
	/*=============================================================================================
	 *
	 *	Retrieve data and enter into inputs by name
	 *
	 *============================================================================================*/	
	//loop through all input fields and retrieve data saved in the cookie
	var inputs = getInputsByClass(className);
	
	for(var i = 0; i < inputs.length; i++)
	{
		var cookieVar = getCookie('pt_'+inputs[i].name);
		
		if(cookieVar != null && cookieVar != "")
		{
			if(inputs[i].type == 'checkbox')
			{
				if(cookieVar == 'true')
				{
					inputs[i].checked = true;
				}
				else if(cookieVar == 'false')
				{
					inputs[i].checked = false;
				}
			}
			else
			{
				inputs[i].value = cookieVar;
			}
			
			if(saved)
			{
				saved = false;
			}			
		}
	}
}


/*================Cookies================*/

/**/
function setCookie(cookieName,value,daystoLive)
{
	if(daystoLive != -1)
	{
		if(getCookie(cookieName) == null) //if this set command is not just 'updating' a var
		{
			memoryCounter++;
		}	
		
		if(memoryCounter >= memoryCounterWarn && !memoryWarned)
		{
			alert('You have reached the limits of the Strategic Action Plan\'s temporary memory. \n\nWe recommend you pause and save your work, as continuing will mean some of your changes will not be recovered if you accidentally navigate away from this page without saving.');
			memoryWarned = true;
		}
	}
	
	var expiryDate = new Date();
	expiryDate.setTime(expiryDate.getTime()+(daystoLive*24*60*60*1000));
	document.cookie=cookieName+"="+escape(value)+";expires="+expiryDate.toGMTString()+";path=/";
	//alert('setting:'+cookieName+"="+escape(value));
}

/**/
function getCookie(cookieName)
{
	if(document.cookie.length>0)
	{
		cookieStart = document.cookie.indexOf(cookieName + "=");
		if (cookieStart != -1) //if no cookie of cookieName exists
		{ 
			cookieStart = cookieStart + cookieName.length+1; //start of the cookie value = length of name +1 for the '='
			cookieEnd = document.cookie.indexOf(";",cookieStart); //index of first ';' after the start of the cookie
			if(cookieEnd==-1) //if there is no ';'
			{
				cookieEnd=document.cookie.length;
			}
			return unescape(document.cookie.substring(cookieStart,cookieEnd));
		} 
	}
	return null;
}

/**/
function eraseCookie(cookieName) 
{
	setCookie(cookieName,"",-1);
	//alert('erased:'+cookieName);
}

/**/
function eraseAllCookies()
{
	//alert('1');
	var cookies = document.cookie.split(';');
	//alert('2');
	for(var i=0;i < cookies.length;i++)
	{
		//alert('loop '+i+' 1');
		var cookie = cookies[i].split('=');
		//alert('loop '+i+' 2');
		if(cookie[0].indexOf('pt_') != -1) //if its a cookie set by this tool
		{
			//alert('loop '+i+' 3-if');
			eraseCookie(cookie[0]);
			//alert('loop '+i+' 4-if');
			//alert('erased:'+cookie[0]);
		}
		//alert('loop '+i+' 5');
	}
}

/*==========================================Client-side activity detection and server notification==============================================*/

function actionNotify()
{
	if(!loadXMLDoc('activityUpdate.php?', 'username='+activityUpdate, false)) alert('There has been an error whilst updating your activity status. Save your changes on this page to register your activity instead.');
	activityUpdate="";
	setTimer();
}

/**/
function updateActivity(name)
{
	activityUpdate = name;
}

function activateWarning()
{
	var tempDate = new Date();
	var dateTime = tempDate.getDate() + "/" + (tempDate.getMonth()+1) + "/" + tempDate.getFullYear() + " ";
	if(tempDate.getHours() > 12)
	{
		dateTime = dateTime + (tempDate.getHours()-12) + ":" + twoDigit(tempDate.getMinutes()) + "pm";
	}
	else
	{
		dateTime = dateTime + tempDate.getHours() + ":" + twoDigit(tempDate.getMinutes()) + "am";
	}
	
	alert(dateTime + '\n\nThe system has not detected any action from you for the last 15 minutes.\n\nThe system will automatically log you out in three minutes time unless you click \'OK\' to acknowledge this message and register your activity. At this point we strongly recommend that you use the relevant save button to save any changes you have made on this page so far.');
	
	if(activityUpdate)
	{
		actionNotify();
	}
}

/**/
function activateTimeout()
{
	activityUpdate = "";
}

/**/
function twoDigit(number)
{
	if(number < 10)
	{
		return "0"+number;
	}
	else
	{
		return number;
	}
}

/*xmlhttprequest*/
function loadXMLDoc(url, data, async)
{
	xmlhttp=null;
	
	if(window.XMLHttpRequest) //Firefox etc...
	{
		xmlhttp = new XMLHttpRequest();
	}
	else if(window.ActiveXObject) //IE
	{
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if(xmlhttp != null)
	{
		var tempDate = new Date();
		//Date object to obtain a unique timestamp for the url. This is a method of working around the caching of results from the page (mainly in IE) which was bypassing the script on the server, meaning that no 'lastaction' updates were getting through
		
		xmlhttp.open("POST",url+'date='+tempDate.getTime(),async); //false = non-asynchronous, true = asymchronous
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send(data);
		
		if(xmlhttp.status == 200) return xmlhttp.responseText; //OK
		else return false; //Not OK
			
	}
	else
	{
		//alert("Your browser does not support XMLHTTP and couldn't carry out the requested action.");
		return false;
	}
}

/*==========================================Dynamic Form Stuff==============================================*/

function removeRow(rowID, killFieldID, countersIndex)
{
	var targetRow = document.getElementById(rowID);
	targetRow.parentNode.removeChild(targetRow); 

	var killField = document.getElementById(killFieldID);
	killField.value = 'remove';
	existingNumbers[countersIndex]--;
	
	//COOKIERE setCookie('pt_removeRow'+removalCounter,rowID+"|"+killFieldID+"|"+countersIndex,1);
	removalCounter++;
	
	if(saved)
	{
		saved = false;
	}	
	
	/**/
	if(activityUpdate)
	{
		actionNotify();
	}	
	
	//===================
	updateFloatingMenu();
}


/**/
function addField(fieldName, parent, countersIndex, maxFields, cookieWork)
{
	if(existingNumbers[countersIndex] < maxFields || cookieWork == true)
	{
		var newFields = document.getElementById('templateField').cloneNode(true);
		
		newFields.id = 'newRow'+countersIndex+'_'+counters[countersIndex];
		newFields.style.display = 'block';
		
		var newField = newFields.childNodes;
		
		for(var i=0;i<newField.length;i++) 
		{
			var theName = newField[i].name;

			//progress field
			if(newField[i].id != null && (newField[i].className.indexOf('progressField') != -1))
			{
				var newNewField = newField[i].childNodes;
				for(var j=0;j<newNewField.length;j++) 
				{
					var theName = newNewField[j].name;
					//newNewField[j].className += " newField";
					
					if(theName)
					{
						newNewField[j].name = parent + theName + counters[countersIndex];
					}
				}
			}

			//divs for dropdowns etc.
			if(newField[i].id != null && (newField[i].id.indexOf('ResponsibleDiv') != -1 || newField[i].id.indexOf('ReportsToDiv') != -1))
			{
				var newNewField = newField[i].childNodes;
				for(var j=0;j<newNewField.length;j++) 
				{
					var theName = newNewField[j].name;
					
					if(theName)
					{
						newNewField[j].name = parent + theName + counters[countersIndex];
						//newNewField[j].className += " newField";
						
						if(newNewField[j].name.indexOf('Responsible') != -1)
						{
							newNewField[j].id = newNewField[j].name;
							
							newNewField[j].onfocus = function()
							{
								document.getElementById(this.name.replace("taskPersonResponsible", "taskResponsibleDropdown")).style.display = 'block';
							}
							
							newNewField[j].onblur = function()
							{
								doDropdown(this.name.replace("taskPersonResponsible", "taskResponsibleDropdown"));
							}
						}
						
						if(newNewField[j].name.indexOf('ReportsTo') != -1)
						{
							newNewField[j].id = newNewField[j].name;
							
							newNewField[j].onfocus = function()
							{
								document.getElementById(this.name.replace("taskReportsTo", "taskReportsToDropdown")).style.display = 'block';
							}
							
							newNewField[j].onblur = function()
							{
								doDropdown(this.name.replace("taskReportsTo", "taskReportsToDropdown"));
							}
						}
						
						if(newNewField[j].className)
						{
							if(newNewField[j].className.indexOf('usableInput') != -1) 
							{
								addInputDetector(newNewField[j]);
							}
						}
					}
					
					//dropdown
					if(newNewField[j].id != null && (newNewField[j].id.indexOf('taskResponsibleDropdown') != -1))
					{
						newNewField[j].id = parent + 'taskResponsibleDropdown' + counters[countersIndex];
						
						dropdownNodes = newNewField[j].childNodes;
						for(var k=0;k<dropdownNodes.length;k++)
						{
								dropdownNodes[k].onclick = function()
								{
									document.getElementById(this.parentNode.id.replace("taskResponsibleDropdown", "taskPersonResponsible")).value=this.id; 
									document.getElementById(this.parentNode.id.replace("taskResponsibleDropdown", "taskPersonResponsible")).value=this.innerHTML; 
									this.parentNode.style.display = 'none';
								}
						}
					}
					
					
					//dropdown
					if(newNewField[j].id != null && (newNewField[j].id.indexOf('taskReportsToDropdown') != -1))
					{
						newNewField[j].id = parent + 'taskReportsToDropdown' + counters[countersIndex];
						
						dropdownNodes = newNewField[j].childNodes;
						for(var k=0;k<dropdownNodes.length;k++)
						{
								dropdownNodes[k].onclick = function()
								{
									document.getElementById(this.parentNode.id.replace("taskReportsToDropdown", "taskReportsTo")).value=this.id; 
									document.getElementById(this.parentNode.id.replace("taskReportsToDropdown", "taskReportsTo")).value=this.innerHTML; 
									this.parentNode.style.display = 'none';
								}
						}
					}
					
				}
			}
			
			if(theName)
			{
				newField[i].name = parent + theName + counters[countersIndex];
				//newField[i].className += " newField";
				
				if(newField[i].name.indexOf('taskStartDate') != -1)
				{
					newField[i].id = newField[i].name;

					var calendarButtonSD = newFields.getElementsByTagName('img')[0];
					calendarButtonSD.id = 'calendarButtonSD' + counters[countersIndex];

					calendarButtonSD.onclick = function()
					{
						toggleCalendar(this.parentNode.getElementsByTagName('input')[2].id, 'Task Start Date');
					}

					calendarButtonSD.onmousedown = function()
					{
						calendarButtonDown(this.id);
					}

					calendarButtonSD.onmouseup = function()
					{
						calendarButtonUp(this.id);
					}

					calendarButtonSD.onmouseout = function()
					{
						calendarButtonUp(this.id);
					}
				}
				
				if(newField[i].name.indexOf('taskCompleteDate') != -1)
				{
					newField[i].id = newField[i].name;
					
					var calendarButtonCD = newFields.getElementsByTagName('img')[1];
					calendarButtonCD.id = 'calendarButtonCD' + counters[countersIndex];
					
					calendarButtonCD.onclick = function()
					{
						toggleCalendar(this.parentNode.getElementsByTagName('input')[3].id, 'Task Complete Date');
					}
					
					calendarButtonCD.onmousedown = function()
					{
						calendarButtonDown(this.id);
					}
					
					calendarButtonCD.onmouseup = function()
					{
						calendarButtonUp(this.id);
					}
					
					calendarButtonCD.onmouseout = function()
					{
						calendarButtonUp(this.id);
					}
				}
			}
			
			if(newField[i].className)
			{
				if(newField[i].className.indexOf('usableInput') != -1) 
				{
					addInputDetector(newField[i]);
				}
			}
			
			if(newField[i].type == 'button')
			{
				newField[i].onclick = function()
				{
					this.parentNode.parentNode.removeChild(this.parentNode);
					//COOKIERE setCookie('pt_remove'+this.parentNode.id,''+countersIndex,1);
					//counters[countersIndex]--;
					existingNumbers[countersIndex]--;
					
					//===================
					updateFloatingMenu();
				}
			}
		}
		var insertHere = document.getElementById(fieldName);
		insertHere.parentNode.insertBefore(newFields,insertHere);
		
		//COOKIERE setCookie('pt_'+newFields.id,fieldName+'|'+parent+'|'+countersIndex+'|'+maxFields,1);
		if(!cookieWork) eraseCookie('pt_remove'+newFields.id);
		
		existingNumbers[countersIndex]++;
		counters[countersIndex]++;	
		
		var counterField = document.getElementById(parent+'counter');
		counterField.value = counters[countersIndex];
		//additionCounters[countersIndex]++; //this is used to generate unique IDs
		
		if(saved)
		{
			saved = false;
		}	
		
		return newFields;
	}
	else
	{
		alert("Maximum number reached.");
		return null;
	}
	
	/**/
	if(activityUpdate)
	{
		actionNotify();
	}	
	
	//===================
	updateFloatingMenu();
}


/*Add/Remove for branch pages reqire special functons because of the dynamic lists - also note that an existingNumbers counter is not required because there is no hard limit to the number of users and directions that can be added*/
function removeBranchItem(rowID, killFieldID, itemName, itemID, itemListID)
{	
	var itemList = document.getElementById(itemListID);
	var thisOption = document.createElement('option');
	thisOption.value = itemID;
	thisOption.text = itemName;
	itemList.add(thisOption, null);	
	
	var targetRow = document.getElementById(rowID);	
	targetRow.parentNode.removeChild(targetRow); 

	var killField = document.getElementById(killFieldID);
	killField.value = 'remove';
	
	//COOKIERE setCookie('pt_removeItem'+removalCounter,rowID+"|"+killFieldID+"|"+itemName+"|"+itemID+"|"+itemListID,1);
	removalCounter++;	
	
	if(saved)
	{
		saved = false;
	}	
	
	/**/
	if(activityUpdate)
	{
		actionNotify();
	}	

	//===================
	updateFloatingMenu();
}


function addAllBranchItem(fieldName, parent, countersIndex, itemListID)
{
	var itemList = document.getElementById(itemListID);
	var sLength = itemList.options.length;
	
	for($i=0;$i<sLength;$i++)
	{
		addBranchItem(fieldName, parent, countersIndex, itemListID);
	}
}

/*Add/Remove for branch pages reqire special functons because of the dynamic lists - also note that an existingNumbers counter is not required because there is no hard limit to the number of users and directions that can be added*/
function addBranchItem(fieldName, parent, countersIndex, itemListID, cookieWork, cookieItemName, cookieItemID)
{
	var itemList = document.getElementById(itemListID);
	//the itemList is what manages whether anything can be added
	
	if(itemList.length > 0 || cookieWork)
	{
		var newFields = document.getElementById('templateField').cloneNode(true);
		
		newFields.id = 'newItem'+countersIndex+'_'+counters[countersIndex];
		newFields.style.display = 'block';
		
		var newField = newFields.childNodes;
		
		for(var i = 0; i < newField.length; i++) 
		{
			var theName = newField[i].name;
			
			if(theName)
			{
				newField[i].name = parent + theName + counters[countersIndex];
				
				//when this function is called through loadcookies, it will bypass the list limitations and thus is required to use supplied ids and names
				if(theName == 'branchItemID')
				{
					if(cookieWork) newField[i].value = cookieItemID
					else newField[i].value = itemList.options[itemList.selectedIndex].value;
				}
				else if(theName == 'branchItemName')
				{
					if(cookieWork) newField[i].value = cookieItemName;
					else newField[i].value = itemList.options[itemList.selectedIndex].text;
				}
				
				newField[i].name = parent + theName + counters[countersIndex];
			}
			
			if(newField[i].className)
			{
				if(newField[i].className.indexOf('usableInput') != -1) 
				{
					addInputDetector(newField[i]);
				}
			}
			
			if(newField[i].type == 'button')
			{
				newField[i].onclick = function()
				{
					//re-add the item to the list
					var siblingNodes = this.parentNode.childNodes;
					var thisOption = document.createElement('option');
					for(var j = 0; j < siblingNodes.length; j++)
					{
						if(siblingNodes[j].name)
						{
							if(siblingNodes[j].name.indexOf('branchItemID') != -1)
							{
								thisOption.value = siblingNodes[j].value;
							}
							else if(siblingNodes[j].name.indexOf('branchItemName') != -1)
							{
								thisOption.text = siblingNodes[j].value;
							}
						}
					}
					itemList.add(thisOption, null);					
					
					//remove the row and set the removal cookie
					this.parentNode.parentNode.removeChild(this.parentNode);

					//COOKIERE setCookie('pt_remove'+this.parentNode.id,countersIndex+'|'+thisOption.text+'|'+thisOption.value+'|'+itemListID,1);
					
					//===================
					updateFloatingMenu();
				}
			}
		}
		var insertHere = document.getElementById(fieldName);
		insertHere.parentNode.insertBefore(newFields,insertHere);
		
		//the last two args stored in this cookie will come from different sources depeding on whether this function was called through the loadcookies function or a user button press
		/*if(cookieWork) setCookie('pt_'+newFields.id,fieldName+'|'+parent+'|'+countersIndex+'|'+itemListID+'|'+cookieItemName+'|'+cookieItemID,1);
		else setCookie('pt_'+newFields.id,fieldName+'|'+parent+'|'+countersIndex+'|'+itemListID+'|'+itemList.options[itemList.selectedIndex].text+'|'+itemList.options[itemList.selectedIndex].value,1);
		//remove any 'removal' cookies for this id - prevents the field being removed more than intended in reloading data from cookies
		if(!cookieWork) eraseCookie('pt_remove'+newFields.id);*/
		
		counters[countersIndex]++;	
		
		var counterField = document.getElementById(parent+'counter');
		counterField.value = counters[countersIndex];
		
		//the list item removal works differently if this function was called from loadcookies - the item to remove must be found 'manually'
		if(cookieWork)
		{
			for(var i = 0; i < itemList.options.length; i++)
			{
				if(itemList.options[i].value == cookieItemID)
				{
					itemList.remove(i);
				}
			}
		}
		else
		{
			itemList.remove(itemList.selectedIndex);
		}
		
		if(saved)
		{
			saved = false;
		}	
		
		return newFields;
	}
	else
	{
		alert("No more items to add.");
		return null;
	}
	
	/**/
	if(activityUpdate)
	{
		actionNotify();
	}	
	
	//===================
	updateFloatingMenu();
}



/*==========================================Miscellaneous==============================================*/

function submitPageForm()
{
	setSaved();
	var pageFormSubmit = document.getElementById('pageFormSubmit');
	pageFormSubmit.click();
}

/**/
function setSortField(sortValue)
{
	var sortField = document.getElementById('searchVar');
	sortField.value = sortValue;
}

/**/
function openwindow(pagenum) 
{
	var agree = true;
	if(!saved)
	{	
		var agree=confirm("Changes will not show on the printable version until you have saved the plan.\nSelect Cancel to return to your page, then 'Save' your work.\nSelecting OK will mean the printable version may not show any recent changes.");
	}
	
	if (agree)
	{
		 newWindow = window.open(printable+pagenum,'newwindow','HEIGHT=650,WIDTH=1030,scrollbars=yes,toolbar=no,status=no,menubar=yes,location=yes,resizable=yes');
		 newWindow.focus();
	}
}

/**/
function opengenericwindow(address)
{
	newWindow = window.open(address,'newwindow','HEIGHT=650,WIDTH=1030,scrollbars=yes,toolbar=no,status=no,menubar=yes,location=yes,resizable=yes');
	newWindow.focus();	
}

/**/
function openHelp(vars) 
{
	helpWindow = window.open('help.php?'+vars,'helpwindow','HEIGHT=650,WIDTH=760,scrollbars=yes,toolbar=no,status=no,menubar=yes,location=yes,resizable=yes');
	helpWindow.focus();	
}

/**/
function openFieldGuide(vars) 
{
	fieldGuideWindow = window.open('fieldkey.php?'+vars,'fieldguidewindow','HEIGHT=475,WIDTH=760,scrollbars=yes,toolbar=no,status=no,menubar=yes,location=yes,resizable=yes');
	fieldGuideWindow.focus();	
}

/**/
function openDirections(vars) 
{
	directionsWindow = window.open('directions.php?'+vars,'directionswindow','HEIGHT=475,WIDTH=760,scrollbars=yes,toolbar=no,status=no,menubar=yes,location=yes,resizable=yes');
	directionsWindow.focus();	
}

/**/
function setPrintableDisplay(displayField)
{
	if(printable.indexOf(displayField) == -1)
	{
		printable += displayField;
	}
	else
	{
		printable = printable.replace(displayField, '');
	}
}

/**/
function confirmDelete(message)
{
	var agree=confirm(message);
	if (agree) return true;
	else return false;
}

/**/
function toggleHelp()
{
	var toggle = document.getElementById('helpToggle');
	
	if(showHelp)
	{
		showHelp = false;
		toggle.innerHTML = '[Show Help Popups]';
	}
	else
	{
		showHelp = true;
		toggle.innerHTML = '[Hide Help Popups]';
	}
}

/**/
function toggleDirectionDescriptions()
{
	var toggle = document.getElementById('directionDescriptionsToggle');
	
	if(showHelp)
	{
		showHelp = false;
		toggle.innerHTML = '[Show Direction Description Popups]';
	}
	else
	{
		showHelp = true;
		toggle.innerHTML = '[Hide Direction Description Popups]';
	}
}

/**/
function toggleMenu()
{
	var toggle = document.getElementById('menuToggle');
	
	if(floatMenu)
	{
		floatMenu = false;
		toggle.innerHTML = '[Float Menu]';
		var floatingMenu = document.getElementById('floatingMenu');
		floatingMenu.style.top = '86px';
	}
	else
	{
		floatMenu = true;
		toggle.innerHTML = '[Unfloat Menu]';
	}
}

/**/
function toggleMenuShift()
{
	var toggleA = document.getElementById('menuShiftToggleA');
	var toggleB = document.getElementById('menuShiftToggleB');
	
	if(menuShift)
	{
		toggleA.innerHTML = "[&#923;]";
		toggleB.innerHTML = "";
		menuShift = 0;
	}
	else
	{
		toggleA.innerHTML = "[V]";
		toggleB.innerHTML = "[V]";
		menuShift = 350;
	}
	
	updateFloatingMenu();
}

/**/
function updateFloatingMenu()
{
	if(floatMenu)
	{
		var scrollY = 0;
		if(document.body.scrollTop) scrollY = document.body.scrollTop;
		else if(document.documentElement.scrollTop) scrollY = document.documentElement.scrollTop;
		
		var floatingMenu = document.getElementById('floatingMenu');
		//var editConflict = document.getElementById('editConflicts');

		if(scrollY-menuShift > 80) 
		{	
			floatingMenu.style.top = (scrollY+6-menuShift)+'px';
			//editConflict.style.top = floatingMenu.style.top;
		}
		else 
		{
			floatingMenu.style.top = '86px';
			//editConflict.style.top = '86px';
		}
	}
}

/**/
function collapseSubMenu(menuID, menuTitle)
{
	var menuTitleLine = document.getElementById(menuID);
	var menuList = document.getElementById(menuID+'Menu');
	
	if(menuList.style.display == 'none')
	{
		menuTitleLine.innerHTML = '[-] '+menuTitle;
		menuList.style.display = 'block';		
	}
	else
	{
		menuTitleLine.innerHTML = '[+] '+menuTitle;
		menuList.style.display = 'none';
	}
}

/**/
function switchUploadExisting(hideID, showID, eraseID, fillID, fillValue)
{
	var hide = document.getElementById(hideID);
	var show = document.getElementById(showID);
	var erase = document.getElementById(eraseID);
	var fill = document.getElementById(fillID);
	
	hide.style.display = 'none';
	show.style.display = 'inline';
	
	if(erase.tagName == 'INPUT') 
	{
		erase.value = '';
	}
	
	if(erase.id.indexOf('taskExistingSelect') != -1)
	{
		saved = false;
	}
	
	if(fill.id.indexOf('taskExistingSelect') != -1)
	{
		fill.value = fillValue;
	}
}

/**/
function fileUploadAlert()
{
	var agree=confirm('This page needs to be saved to upload this file.\n\nDo you want to save the changes made on this page?');
	if(agree) submitPageForm();
}

/*==========================================Gantt Chart==============================================*/
function setBarFunctions()
{
	var allCells = document.getElementsByTagName('td');
	
	var barCells = new Array();
	
	for(var i = 0; i < allCells.length; i++)
	{
		if(allCells[i].className.indexOf('ganttChartBarCell') != -1)
		{
			barCells[barCells.length] = allCells[i];
		}
	}
	
	for(var i = 0; i < barCells.length; i++)
	{
		barCells[i].onmousemove = function(e)
		{
			var myWidth = 0;
	
			if(typeof(window.innerWidth) == 'number') //window.innerWidth is not supported by IE browsers
			{
				myWidth = window.innerWidth;
			} 
			else if(document.documentElement && document.documentElement.clientWidth) //documentElement seems to be used by IE
			{
				myWidth = document.documentElement.clientWidth;
			} 
			else if(document.body) //IE 4 and 5 can use document.body to determine window size
			{
				myWidth = document.body.clientWidth;
			}		
			
			var label = document.getElementById('helpLabel');
			var offset = 5;
			
			if(window.event)
			{	
				e = window.event;
			}
			
			if(e.clientX+350 > myWidth)
			{
				offset = -325;
			}	
			
			var scrollY = 0;
			if(document.body.scrollTop) 
			{
				scrollY = document.body.scrollTop;
			}
			else if(document.documentElement.scrollTop) 
			{
				scrollY = document.documentElement.scrollTop;
			}
			
			var scrollX = 0;
			if(document.body.scrollLeft) 
			{
				scrollX = document.body.scrollLeft;
			}
			else if(document.documentElement.scrollLeft) 
			{
				scrollX = document.documentElement.scrollLeft;
			}			
			
			label.style.top = (e.clientY+scrollY) + 'px';
			label.style.left = (e.clientX+scrollX+offset) + 'px';
		}
	}
}

/**/
function toggleTaskInfo()
{
	var toggleLink = document.getElementById('taskInfoToggle');
	
	if(showDescriptions)
	{
		toggleLink.innerHTML = '[Show Task Info Popups]';
		showDescriptions = false;
	}
	else
	{
		toggleLink.innerHTML = '[Hide Task Info Popups]';
		showDescriptions = true;
	}
}

/**/
function barOver(content, cellID, barID, doneID, highlightColourID)
{
	var doneField = document.getElementById(doneID);
	
	if(showDescriptions)
	{
		var label = document.getElementById('helpLabel');
		label.style.display = 'block';
		label.innerHTML = content.replace('!Done!', '<strong>'+doneField.value+'</strong>');
	}
	
	var chartCell = document.getElementById(cellID);
	chartCell.style.background = '#ECECEC';
	
	var chartBar = document.getElementById(barID);
	var highlightField = document.getElementById(highlightColourID);
	chartBar.style.background = highlightField.value;
}

/**/
function barOut(cellID, barID, originalColourID)
{
	var label = document.getElementById('helpLabel');
	label.style.display = 'none';
	label.innerHTML = ' ';
	
	var chartCell = document.getElementById(cellID);
	chartCell.style.background = 'none';
	
	var chartBar = document.getElementById(barID);
	var originalField = document.getElementById(originalColourID);
	chartBar.style.background = originalField.value;
}

/**/
function ganttChartSetDone(taskID, trial)
{
	var doneField = document.getElementById('taskDone'+taskID);
	var doneValue = 0;
	if(doneField.value == 'Not Done') doneValue = 1;
	
	if(response = loadXMLDoc('ganttChartSetDone.php?', 'taskID='+taskID+'&done='+doneValue+'&trial='+trial, false)) 
	{
		if(response.indexOf('Status changed successfully') != -1)
		{
			if(doneValue) //was not done, set to done
			{
				doneField.value = 'Done';
				var originalColourField = document.getElementById('barColour'+taskID);
				var highlightColourField = document.getElementById('highlightColour'+taskID);
				
				switch(originalColourField.value)
				{
					case '#777777': originalColourField.value = '#5E5EA5';
						highlightColourField.value = '#7070C7';
						break;
					case '#999999': originalColourField.value = '#7070C7';
						highlightColourField.value = '#9393EA';
						break;
					case '#BBBBBB': originalColourField.value = '#9D9DEC';
						highlightColourField.value = '#C0C0FF';
						break;
				}
			}
			else //was done, set to not done
			{
				doneField.value = 'Not Done';
				var originalColourField = document.getElementById('barColour'+taskID);
				var highlightColourField = document.getElementById('highlightColour'+taskID);
				
				switch(originalColourField.value)
				{
					case '#5E5EA5': originalColourField.value = '#777777';
						highlightColourField.value = '#959595';
						break;
					case '#7070C7': originalColourField.value = '#999999';
						highlightColourField.value = '#BCBCBC';
						break;
					case '#9D9DEC': originalColourField.value = '#BBBBBB';
						highlightColourField.value = '#DEDEDE';
						break;
				}
			}
			
			var descriptionRow = document.getElementById('taskDescriptionRow'+taskID);
			descriptionRow.onmouseover();
		}
	}
	else
	{
		alert('The system was unable to send your request to change the task\'s status.');
	}
}

/*==========================================Calendar==============================================*/

/**/
function toggleCalendar(dateCellName, dateCellTitle)
{
	/**/
	if(activityUpdate)
	{
		actionNotify();
	}	
	
	if(showingCalendar && currentCalendar == dateCellName)
	{
		closeCalendar();
	}
	else
	{
		//record which calendar is being shown
		currentCalendar = dateCellName;
		
		//set the title to the one provided
		var calendarTitle = document.getElementById('calendarTitle');
		calendarTitle.innerHTML = "<h3>" + dateCellTitle + "</h3>"
		
		var calendar = document.getElementById('calendarBox');
		
		//positioning calculations
		var myWidth = 0;
		var myHeight = 0;
		
		if(typeof(window.innerWidth) == 'number') //window.innerWidth is not supported by IE browsers
		{
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} 
		else if(document.documentElement && document.documentElement.clientWidth) //documentElement seems to be used by IE
		{
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} 
		else if(document.body) //IE 4 and 5 can use document.body to determine window size
		{
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}		
		
		var scrollY = 0;
		if(document.body.scrollTop) 
		{
			scrollY = document.body.scrollTop;
		}
		else if(document.documentElement.scrollTop) 
		{
			scrollY = document.documentElement.scrollTop;
		}
		
		var scrollX = 0;
		if(document.body.scrollLeft) 
		{
			scrollX = document.body.scrollLeft;
		}
		else if(document.documentElement.scrollLeft) 
		{
			scrollX = document.documentElement.scrollLeft;
		}	
			
		calendar.style.top = (scrollY+(myHeight/2)-160) + 'px';
		calendar.style.left = (scrollX+(myWidth/2)-200) + 'px';		
		
		/*var calendar_odiv = document.getElementById('calendarDiv');
		var calendar_div = document.getElementById(dateCellName+'_div');
		calendar_div.innerHTML = calendar_odiv.innerHTML;
		var calendar = document.getElementById('calendarBox');*/
		
		//if a date is already entered into the cell, select it in the calendar. otherwise, select today
		var sourceCell = document.getElementById(dateCellName);

		if(sourceCell.value != null && sourceCell.value != "")
		{
			var dateArrayTemp = sourceCell.value.split("-");
			
			if(dateArrayTemp.length == 3) //correct length
			{
				date.setFullYear(parseInt(dateArrayTemp[2]));
				
				if(dateArrayTemp[1].charAt(0) == "0")
				{
					date.setMonth(parseInt(dateArrayTemp[1].substr(1,1)) - 1);
				}
				else
				{
					date.setMonth(parseInt(dateArrayTemp[1]) - 1);
				}
				
				date.setDate(parseInt(dateArrayTemp[0]));					
			}
		}		
		else
		{
			if(dateDay != 0 && dateMonth != 0 && dateYear != 0)
			{
				date.setFullYear(dateYear, dateMonth-1, dateDay);
			}
			else date = new Date();
		}
		
		setCalendar();
		
		//Stuff for the button that enters the date selected in the calendar
		var enterButton = document.getElementById('enterDate');
		
		enterButton.onclick = function()
		{
			/**/
			if(activityUpdate)
			{
				actionNotify();
			}			
			
			var enterCell = document.getElementById(dateCellName);
			
			var day = date.getDate();
			var month = date.getMonth() + 1;
			var year = formatYear(date.getFullYear());
			
			var completeNotBefore = true;
			
			if(dateCellName.indexOf('taskStartDate') != -1)
			{
				var otherCell = document.getElementById(dateCellName.replace("taskStartDate", "taskCompleteDate"));
				var otherDate = otherCell.value;
				
				if(otherDate) // != null && otherDate != ""
				{
					var dateArray = otherDate.split("-"); //representing the complete date - this should be AFTER the start date
					
					if(dateArray[2] == year)
					{
						if(dateArray[1] == month)
						{
							if(dateArray[0] < day)
							{
								completeNotBefore = false;
							}
						}
						else if(dateArray[1] < month)
						{
							completeNotBefore = false;
						}
					}
					else if(dateArray[2] < year)
					{
						completeNotBefore = false;
					}
				}
			}
			else if(dateCellName.indexOf('taskCompleteDate') != -1)
			{
				var otherCell = document.getElementById(dateCellName.replace("taskCompleteDate", "taskStartDate"));
				var otherDate = otherCell.value;
				
				if(otherDate) // != null && otherDate != ""
				{
					var dateArray = otherDate.split("-"); //representing the start date - this should be BEFORE the start date
					
					if(dateArray[2] == year)
					{
						if(dateArray[1] == month)
						{
							if(dateArray[0] > day)
							{
								completeNotBefore = false;
							}
						}
						else if(dateArray[1] > month)
						{
							completeNotBefore = false;
						}
					}
					else if(dateArray[2] > year)
					{
						completeNotBefore = false;
					}
				}				
			}

			if(completeNotBefore)
			{
				if(day < 10)
				{
					day = "0" + day;
				}
	
				if(month < 10)
				{
					month = "0" + month;
				}
				
				enterCell.value = day + "-" + month + "-" + year;
				
				dateDay = day;
				dateMonth = month;
				dateYear = year;
				
				result = loadXMLDoc('dateSetVariables.php?', 'dateDay='+day+'&dateMonth='+month+'&dateYear='+year, false);
				
				//the "local memory" for the calendar function - exactly the same as the attached input detector
				//COOKIERE setCookie('pt_'+enterCell.name,enterCell.value,1);
				
				if(saved)
				{
					saved = false;
				}
				
				closeCalendar();
			}
			else
			{
				alert("Please make sure that the Start Date is before (or the same as) the Complete Date.");
			}
		}
		
		var closeButton = document.getElementById('closeButton')
		closeButton.onclick = function()
		{
			closeCalendar();
		}
		
		calendar.style.display = 'block';
		//calendar.style.top = '15px';
		showingCalendar = true;
	}
}

/**/
function closeCalendar()
{
	var calendar = document.getElementById('calendarBox');
	calendar.style.display = 'none';
	showingCalendar = false;
	/*var calendar_div = document.getElementById(currentCalendar+'_div');
	calendar_div.innerHTML = '';
	showingCalendar = false;*/
}

/**/
function setCalendar()
{
	var calendarYear = document.getElementById('calendarYear');
	var calendarMonth = document.getElementById('calendarMonth');
	
	calendarYear.innerHTML = formatYear(date.getFullYear());
	calendarMonth.innerHTML = nameMonth(date.getMonth());
	
	var rowCounter = date.getDay() - ((date.getDate() % 7) - 1);
	if(rowCounter < 0) rowCounter += 7;	
	var dayCounter = 0;
	var maxDays = getMaxDays(date.getMonth(), formatYear(date.getFullYear()));
	
	
	var dayTableBody = document.getElementById('dayTable').getElementsByTagName("tbody")[0];
	var dayTableTRList = dayTableBody.getElementsByTagName("tr");
	
	
	for(var i = 1; i < dayTableTRList.length; i++)
	{
		for(var j = 0; j < dayTableTRList[i].getElementsByTagName("td").length; j++)
		{
			dayTableTRList[i].getElementsByTagName("td")[j].innerHTML = "";
			dayTableTRList[i].getElementsByTagName("td")[j].style.border = "2px solid #EEEEEE";
		}
	}
	
	while(dayCounter < maxDays)
	{
		var rowNum = ((rowCounter - (rowCounter % 7)) / 7)+1;			
		var row = dayTableTRList[rowNum];
		var cell = row.getElementsByTagName("td")[rowCounter % 7];
		
		cell.innerHTML = '<input name="day'+(dayCounter+1)+'" type="button" value="'+(dayCounter+1)+'" onClick="setDay(this.value);" />';
		
		if(dayCounter+1 == date.getDate())
		{
			cell.style.border = "2px solid #DB820E";
		}
		
		rowCounter++;
		dayCounter++;
	}	
}

/**/
function clearCalendar(fieldName)
{
	calendarField = document.getElementById(fieldName);
	calendarField.value = "";
}

/**/
function formatYear(year)
{
	var yearSmall = year % 100; //remove the front portion, e.g. 2007 becomes 7 
		//this is to counteract a problem encountered in Firefox on a Mac, where the year was being reported as "7" instead of "2007" as it should be by getFullYear()
	if(yearSmall < 70) //"epoch" starts in 1970 - if the year is less than "70" then its 2069. However, there isn't a hard restriction in the date object - 1970 seemed a convenient yaer to use
	{
		return 2000 + yearSmall;
	}
	else
	{
		return 1900 + yearSmall;
	}	
}

/**/
function changeYear(changeNum)
{
	date.setFullYear(formatYear(date.getFullYear()+changeNum));
	
	setCalendar();
}

/**/
function changeMonth(changeNum)
{
	date.setMonth(date.getMonth()+changeNum);
	
	setCalendar();
}

/**/
function setDay(dayNum)
{
	date.setDate(dayNum);
	
	setCalendar();
}

/**/
function calendarButtonDown(buttonId)
{
	var button = document.getElementById(buttonId);
	button.style.borderLeft = "1px solid #D9D9D9";
	button.style.borderTop =  "1px solid #D9D9D9";
	button.style.borderRight = "none";
	button.style.borderBottom = "none";
}

/**/
function calendarButtonUp(buttonId)
{
	var button = document.getElementById(buttonId);
	button.style.borderRight = "1px solid #D9D9D9";
	button.style.borderBottom =  "1px solid #D9D9D9";
	button.style.borderLeft = "none";
	button.style.borderTop = "none";
}

/**/
function nameMonth(monthNum)
{
	switch(monthNum)
	{
		case 0: return "January";
		case 1: return "February";
		case 2: return "March";
		case 3: return "April";
		case 4: return "May";
		case 5: return "June";
		case 6: return "July";
		case 7: return "August";
		case 8: return "September";
		case 9: return "October";
		case 10: return "November";
		case 11: return "December";
	}
}

/**/
function getMaxDays(monthNum, year)
{
	switch(monthNum)
	{
		case 0: return 31;
		case 1: if(isLeapYear(year)) return 29; else return 28;
		case 2: return 31;
		case 3: return 30;
		case 4: return 31;
		case 5: return 30;
		case 6: return 31;
		case 7: return 31;
		case 8: return 30;
		case 9: return 31;
		case 10: return 30;
		case 11: return 31;
	}	
}

/**/
function isLeapYear(yearNum)
{
	if(yearNum % 4 == 0) //evenly divisible by 4
	{
		if(yearNum % 100 == 0 && yearNum % 400 != 0) //centennial year not evenly divisible by 400
		{
			return false;
		}
		
		return true;
	}
	
	return false;
}

/*========ATTACHMENT FIELD BUTTON HELP POPUPS========*/
/*Help Popups*/
function showpopup(text)
{
		var label = document.getElementById('helpLabel');
		label.style.display = 'block';
		
		label.innerHTML = text;
}
	
function movepopup(input)
{
	input.onmousemove = function(e)
	{
			var myWidth = 0;
			
			if(typeof(window.innerWidth) == 'number') //window.innerWidth is not supported by IE browsers
			{
				myWidth = window.innerWidth;
			} 
			else if(document.documentElement && document.documentElement.clientWidth) //documentElement seems to be used by IE
			{
				myWidth = document.documentElement.clientWidth;
			} 
			else if(document.body) //IE 4 and 5 can use document.body to determine window size
			{
				myWidth = document.body.clientWidth;
			}		
			
			var label = document.getElementById('helpLabel');
			var offset = 5;
			
			if(window.event)
			{	
				e = window.event;
			}
			
			if(e.clientX+350 > myWidth)
			{
				offset = -325;
			}	
			
			var scrollY = 0;
			if(document.body.scrollTop) 
			{
				scrollY = document.body.scrollTop;
			}
			else if(document.documentElement.scrollTop) 
			{
				scrollY = document.documentElement.scrollTop;
			}
			
			var scrollX = 0;
			if(document.body.scrollLeft) 
			{
				scrollX = document.body.scrollLeft;
			}
			else if(document.documentElement.scrollLeft) 
			{
				scrollX = document.documentElement.scrollLeft;
			}			
			
			label.style.top = (e.clientY+scrollY) + 'px';
			label.style.left = (e.clientX+scrollX+offset) + 'px';
	}
}
	
function hidepopup()
{
		var label = document.getElementById('helpLabel');
		label.style.display = 'none';
		label.innerHTML = ' ';
}

function selectSAPMonthWarnings()
{
	var inputs = document.getElementsByTagName('input');
	
	for(var i = 0; i < inputs.length; i++)
	{
		var input = inputs[i];
		
		if(input.id.indexOf("sap_w_") != -1 && input.value != 0) //value field for warning
		{
			var checkbox = document.getElementById('checksend_'+input.id.substr(6));
			checkbox.checked = 'checked';
		}
	}
	
	//alert(document.getElementById('lastreminder_Andy CBB').value);
}

function selectPMMonthWarnings()
{
	var inputs = document.getElementsByTagName('input');
	
	for(var i = 0; i < inputs.length; i++)
	{
		var input = inputs[i];
		
		if(input.id.indexOf("pm_w_") != -1 && input.value != 0) //value field for warning
		{
			var checkbox = document.getElementById('checksend_'+input.id.substr(5));
			checkbox.checked = 'checked';
		}
	}
}

function selectUnreminded()
{
	var inputs = document.getElementsByTagName('input');
	
	for(var i = 0; i < inputs.length; i++)
	{
		var input = inputs[i];
		
		if(input.id.indexOf("lastreminder_") != -1 && input.value != 0) //value field for warning
		{
			var checkbox = document.getElementById('checksend_'+input.id.substr(13));
			checkbox.checked = 'checked';
		}
	}
}

function selectSAP()
{
	var inputs = document.getElementsByTagName('input');
	
	for(var i = 0; i < inputs.length; i++)
	{
		var input = inputs[i];
		
		if(input.id.indexOf("sap_") != -1 && input.value != 0) //value field for warning
		{
			var checkbox = document.getElementById('checksend_'+input.id.substr(4));
			checkbox.checked = 'checked';
		}
	}
}

function selectPM()
{
	var inputs = document.getElementsByTagName('input');
	
	for(var i = 0; i < inputs.length; i++)
	{
		var input = inputs[i];
		
		if(input.id.indexOf("pm_") != -1 && input.value != 0) //value field for warning
		{
			var checkbox = document.getElementById('checksend_'+input.id.substr(3));
			checkbox.checked = 'checked';
		}
	}
}

function selectAll()
{
	var inputs = document.getElementsByTagName('input');
	
	for(var i = 0; i < inputs.length; i++)
	{
		var input = inputs[i];
		
		if(input.id.indexOf("checksend_") != -1) //value field for warning
		{
			input.checked = 'checked';
		}
	}
}

function deselectAll()
{
	var inputs = document.getElementsByTagName('input');
	
	for(var i = 0; i < inputs.length; i++)
	{
		var input = inputs[i];
		
		if(input.id.indexOf("checksend_") != -1) //value field for warning
		{
			input.checked = null;
		}
	}
}

function generateMailLink()
{
	var inputs = document.getElementsByTagName('input');
	var addresses = '';
	
	for(var i = 0; i < inputs.length; i++)
	{
		var input = inputs[i];
		
		if(input.id.indexOf("checksend_") != -1 && input.checked) //value field for warning
		{
			if(addresses != '') addresses+=', ';
			addresses += input.value;
		}
	}
	
	document.getElementById('sendemailform').action = 'mailto:?bcc='+addresses+'&subject=Meeting Success - Quarterly Newsletter and Reminder&body=Hi there. This is your quarterly Meeting Success action reminder and newsletter.%0d%0d%0dThank you,%0d%0dMeeting Success';
	document.getElementById('sendemailbutton').click();
	
	document.getElementById('updatesubmit').click();
}