// QueryString Class
var qs = new Querystring();

// XML HTTP Request Object
var xmlHttp = createXmlHttpRequestObject();

// Menu Scrolling Variables
var mySortables;

// Admin Functionalities
var isAdmin = false;

// swfUpload
var swfu;
var swfu_datasheet;

// height of project menu
var prjTimerId = 0;
var prjScrollDirection = -5;
var currentMenu = 2;
var currentPrjMenuPosY = new Array(0,0,0,0,0,0,0);
var prjMenuHeight = new Array(0,0,0,0,0,0,0);
var heightOfItems = new Array(0,0,0,0,0,0,0);
var prjScroll = new Array(Object,Object,Object,Object,Object,Object,Object);

// navigation variables
var global_current_menu_reference = '';
var global_entity_id = '';
var global_entity_name = '';
var global_sub_category_type = '';
var global_sub_category_id = '';
var global_sub_category_button = '';

/*
 * Window Behaviours
 */
window.onload = function() {
	checkLogin();
    startupAnimation();
    // Call the keepAlive function in 10 minutes
    setTimeout("keepAlive()", 600000);
}

window.addEvent('domready', function(){
		$('prjScrollUp_2').addEvent('mouseover', function(e){
			currentMenu = 2;
			prjScrollDirection = -5;
			startProjectScroll();
		});
		$('prjScrollDown_2').addEvent('mouseover', function(e){
			currentMenu = 2;
			prjScrollDirection = 5;
			startProjectScroll();
		});
		$('prjScrollUp_3').addEvent('mouseover', function(e){
			currentMenu = 3;
			prjScrollDirection = -5;
			startProjectScroll();
		});
		$('prjScrollDown_3').addEvent('mouseover', function(e){
			currentMenu = 3;
			prjScrollDirection = 5;
			startProjectScroll();
		});
		$('prjScrollUp_4').addEvent('mouseover', function(e){
			currentMenu = 4;
			prjScrollDirection = -5;
			startProjectScroll();
		});
		$('prjScrollDown_4').addEvent('mouseover', function(e){
			currentMenu = 4;
			prjScrollDirection = 5;
			startProjectScroll();
		});
		$('prjScrollUp_5').addEvent('mouseover', function(e){
			currentMenu = 5;
			prjScrollDirection = -5;
			startProjectScroll();
		});
		$('prjScrollDown_5').addEvent('mouseover', function(e){
			currentMenu = 5;
			prjScrollDirection = 5;
			startProjectScroll();
		});
		$('prjScrollUp_6').addEvent('mouseover', function(e){
			currentMenu = 6;
			prjScrollDirection = -5;
			startProjectScroll();
		});
		$('prjScrollDown_6').addEvent('mouseover', function(e){
			currentMenu = 6;
			prjScrollDirection = 5;
			startProjectScroll();
		});
		$('prjScrollUp_7').addEvent('mouseover', function(e){
			currentMenu = 7;
			prjScrollDirection = -5;
			startProjectScroll();
		});
		$('prjScrollDown_7').addEvent('mouseover', function(e){
			currentMenu = 7;
			prjScrollDirection = 5;
			startProjectScroll();
		});
		
		for(var i = 2; i <= 7; i++){
			$('prjScrollUp_' +i).addEvent('mouseout', function(e){
				stopProjectScroll();
			});
			$('prjScrollDown_' +i).addEvent('mouseout', function(e){
				stopProjectScroll();
			});
		}
	
	
	/*
	$('prjScrollUp_2').addEvent('mouseover', function(e){
		prjScrollDirection = -5;
		startProjectScroll();
	});
	$('prjScrollUp_2').addEvent('mouseout', function(e){
		stopProjectScroll();
	});
	$('prjScrollDown_2').addEvent('mouseover', function(e){
		prjScrollDirection = 5;
		startProjectScroll();
	});
	$('prjScrollDown_2').addEvent('mouseout', function(e){
		stopProjectScroll();
	});
	
	$('prjScrollUp_2').addEvent('click', function(e){
		e.stop();
		stopProjectScroll();
		
		currentPrjMenuPosY -= 100;
		
		if(currentPrjMenuPosY >= 0){
			prjScroll.start(0, currentPrjMenuPosY);
		}else{
			prjScroll.start(0, 0);
			currentPrjMenuPosY = 0;
		}
		//startProjectScroll();
	});
	
	$('prjScrollDown_2').addEvent('click', function(e){
		e.stop();
		stopProjectScroll();
		
		currentPrjMenuPosY += 100;
		
		if(currentPrjMenuPosY <= prjMenuHeight){
			prjScroll.start(0, currentPrjMenuPosY);
		}else{
			prjScroll.start(0, prjMenuHeight);
			currentPrjMenuPosY = prjMenuHeight;
		}
		//startProjectScroll();
	});
	*/
});

function startProjectScroll(){
	//40ms = 25 fps
	prjTimerId = setInterval("scrollProject()", 40);
}

function stopProjectScroll(){
	clearInterval(prjTimerId);
}

function scrollProject(){
	currentPrjMenuPosY[currentMenu] += prjScrollDirection;
	
	if(currentPrjMenuPosY[currentMenu] <= prjMenuHeight[currentMenu]){
		prjScroll[currentMenu].set(0, currentPrjMenuPosY[currentMenu]);
	}else{
		prjScroll[currentMenu].set(0, prjMenuHeight[currentMenu]);
		currentPrjMenuPosY[currentMenu] = prjMenuHeight[currentMenu];
	}
}

/*
 * Common Functions
 */
function nl2br(str) {
    return str.replace(/([^>])\n/g, '$1<br />');
}

function br2nl(str) {
    return str.replace(/<br\s*\/?>/mg,"\n");
}

function addslashes(str) {
    str=str.replace(/\'/g,'\'');
    str=str.replace(/\"/g,'\"');
    str=str.replace(/\\/g,'\\\\');
    //str=str.replace(/\0/g,'\\0');
    return str;
}

function stripslashes(str) {
    str=str.replace(/\\'/g,'\'');
    str=str.replace(/\\"/g,'"');
    str=str.replace(/\\\\/g,'\\');
    str=str.replace(/\\0/g,'\0');
    return str;
}

function getMenuReference(menu_id) {
	var menu_reference = '';
	switch(menu_id) {
		case "1":
			menu_reference = "m3architecture_title";
			break;
		case "2":
			menu_reference = "projects_title";
			break;
		case "3":
			menu_reference = "project_types_title";
			break;
		case "4":
			menu_reference = "people_title";
			break;
		case "5":
			menu_reference = "date_title";
			break;
		case "6":
			menu_reference = "location_title";
			break;
		case "7":
			menu_reference = "ideas_title";
			break;
		default:
			menu_reference = "";
			break;
	}
	return menu_reference;
}

/**
 * The initial startup animation
 */
function startupAnimation() {
    $('projects').setStyle('opacity', 0);
    $('project_types').setStyle('opacity', 0);
    $('people').setStyle('opacity', 0);
    $('date').setStyle('opacity', 0);
    $('location').setStyle('opacity', 0);
    $('ideas').setStyle('opacity', 0);
	
    $('top_menu').style.borderBottom = '0px';

    $('projects').set('tween', {duration: 'long'});
    $('project_types').set('tween', {duration: 'long'});
    $('people').set('tween', {duration: 'long'});
    $('date').set('tween', {duration: 'long'});
    $('location').set('tween', {duration: 'long'});
    $('ideas').set('tween', {duration: 'long'});
    /*$('top_menu').set('tween', {duration: 'long'});*/
	$('menu_content').set('tween', {duration: 'long'});
    
    (function() {$('projects').tween('opacity', '0', '1')}).delay(2000);
    (function() {$('project_types').tween('opacity', '0', '1')}).delay(2500);
    (function() {$('people').tween('opacity', '0', '1')}).delay(3000);
    (function() {$('date').tween('opacity', '0', '1')}).delay(3500);
    (function() {$('location').tween('opacity', '0', '1')}).delay(4000);
    (function() {$('ideas').tween('opacity', '0', '1')}).delay(4500);
    /*(function() {$('top_menu').tween('borderBottom', '0px solid #2A2A2A', '1px solid #2A2A2A')}).delay(5000);*/
    (function() {$('menu_content').tween('borderTop', '0px solid #2A2A2A', '1px solid #2A2A2A')}).delay(5000);
}

/*
 * Keeps the PHP session alive on the server
 * 600000 = 10 Minutes
 */
function keepAlive() {
    /*if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            xmlHttp.open("POST", "includes/ajax/ping.ajax", true);
            xmlHttp.onreadystatechange = handleXMLHttpReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("ping"));
            
            setTimeout("keepAlive()", 600000);
        } catch(e) {
            alert("keepAlive() Can't connect to the server:\n" + e.toString());
        }
    } else {
        // Don't want to interfere with any processing forms at the time etc
        setTimeout("keepAlive()", 20000);
    }*/
	
	var request = new Request({
		method: 'post', 
		url: 'includes/ajax/ping.ajax'
	}).send('request=ping');
}

function checkLogin() {
    /*if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            xmlHttp.open("POST", "includes/ajax/secure.ajax", true);
            xmlHttp.onreadystatechange = handleLoginReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("check"));
        } catch(e) {
            alert("checkLogin() Can't connect to the server:\n" + e.toString());
        }
    }*/
	var request = new Request({
		method: 'post', 
		url: 'includes/ajax/secure.ajax', 
		onSuccess: function(responseText) {
			handleLoginReturn(responseText);
		}
	}).send('request=check');
}

function handleLoginReturn(responseText) {
	if (responseText == "true") {
		isAdmin = true;
	}
}
/*
 * XML HTTP Request Object
 */
function createXmlHttpRequestObject() {
	var xmlHttp;
	try {
		xmlHttp = new XMLHttpRequest();
	} catch(e) {
		var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
										'MSXML2.XMLHTTP.5.0',
										'MSXML2.XMLHTTP.4.0',
										'MSXML2.XMLHTTP.3.0',
										'MSXML2.XMLHTTP',
										'Microsoft.XMLHTTP');
		for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
			try {
				xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
			} catch (e) {
				// do nothing
			}
		}
	}
	
	if (!xmlHttp) {
		alert("Error creating the XMLHttpRequest object.");
	} else {
		return xmlHttp;
	}
}

/*
 * MUST BE AN ADMINISTRATOR!
 */
function initiateTinyMCE(textarea_id) {
    var tinyMCEInstance = tinyMCE.getInstanceById(textarea_id);
    if(tinyMCEInstance) {
        try {
            tinyMCE.execCommand( 'mceRemoveControl', false, textarea_id);
        } catch(e) {
            // Do Nothing
        }
    }
    tinyMCE.init({
        // General options
        mode : "textareas",
        theme : "advanced",
        plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

        // Theme options
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime,preview",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Drop lists for link/image/media/template dialogs
        template_external_list_url : "lists/template_list.js",
        external_link_list_url : "lists/link_list.js",
        external_image_list_url : "lists/image_list.js",
        media_external_list_url : "lists/media_list.js"
    });
}

function initSWFUpload(article_item_id) {
	var settings = {
		flash_url : "../swfupload/swfupload_f9.swf",
		upload_url: "../admin/uploadImages.php",	// Relative to the SWF file
		post_params: {"article_id" : article_item_id},
		file_size_limit : "2 MB",
		file_types : "*.jpg",
		file_types_description : "JPG Images",
		file_upload_limit : 0,
		file_queue_limit : 10,
		custom_settings : {
			progressTarget : "fsUploadProgress", 
			cancelButtonId : "btnCancel"
		},
		debug: false,

		// The event handler functions are defined in handlers.js
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,
		queue_complete_handler : queueComplete	// Queue plugin event
	};

	swfu = new SWFUpload(settings);
}

function initProjectPhotoSWFUpload(project_id) {
    var settings = {
        flash_url : "../swfupload/swfupload_f9.swf",
        upload_url: "../admin/uploadImages.php",    // Relative to the SWF file
        post_params: {"project_id" : project_id, "projectPhoto" : "true"},
        file_size_limit : "2 MB",
        file_types : "*.jpg",
        file_types_description : "JPG Images",
        file_upload_limit : 0,
        file_queue_limit : 1,

        custom_settings : {
            progressTarget : "fsUploadProgress"
        },
        
        debug: false,

        file_queued_handler : projectFileQueued,
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : projectFileDialogComplete,
        
        //upload_start_handler : uploadStart,    // I could do some client/JavaScript validation here, but I don't need to.
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : projectUploadComplete
    };
    swfu = new SWFUpload(settings);
}

/*
 * The PDF Datasheet Uploader
 */
function initPDFDatasheetSWFUpload(project_id, sub_category_id, PHPSESSID) {
    var settings = {
        flash_url : "../swfupload/swfupload_f9.swf",
        upload_url: "../admin/uploadPDFDatasheet.php",    // Relative to the SWF file
        post_params:    {"project_id" : project_id, 
                        "sub_category_id" : sub_category_id,
                        "PHPSESSID" : PHPSESSID},
        file_size_limit : "25 MB",
        file_types : "*.pdf",
        file_types_description : "PDF Documents",
        file_upload_limit : 1,
        file_queue_limit : 1,
        custom_settings : {
            progressTarget : "fsUploadProgress", 
            cancelButtonId : "btnCancel"
        },
        debug: false,

        // The event handler functions are defined in handlers.js
        file_queued_handler : fileQueued,
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : fileDialogComplete,
        upload_start_handler : uploadStart,
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : uploadComplete,
        queue_complete_handler : queueComplete    // Queue plugin event
    };

    swfu_datasheet = new SWFUpload(settings);
}

/*
 *
 */
function initProjectDrawingSWFUpload(project_id) {
    var settings = {
        flash_url : "../swfupload/swfupload_f9.swf",
        upload_url: "../admin/uploadProjectDrawing.php",    // Relative to the SWF file
        post_params: {"project_id" : project_id},
        file_size_limit : "10 MB",
        file_types : "*.pdf",
        file_types_description : "PDF Documents",
        file_upload_limit : 0,
        file_queue_limit : 1,

        custom_settings : {
            progressTarget : "fsUploadProgress"
        },
        
        debug: false,

        file_queued_handler : projectDrawingFileQueued,
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : projectDrawingFileDialogComplete,
        
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : projectDrawingUploadComplete
    };
    
    swfu = new SWFUpload(settings);
}

/*
 *
 */
function initProjectVideoSWFUpload(project_id) {
    var settings = {
        flash_url : "../swfupload/swfupload_f9.swf",
        upload_url: "../admin/uploadImages.php",    // Relative to the SWF file
        post_params: {"project_id" : project_id, "projectVideo" : "true"},
        file_size_limit : "2 MB",
        file_types : "*.jpg",
        file_types_description : "JPG Images",
        file_upload_limit : 0,
        file_queue_limit : 1,

        custom_settings : {
            progressTarget : "fsUploadProgress"
        },
        
        debug: false,

        file_queued_handler : projectVideoFileQueued,
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : projectVideoFileDialogComplete,
        
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : projectVideoUploadComplete
    };
    
    swfu = new SWFUpload(settings);
}

function initPeopleProfilePictureSWFUpload(person_id) {
	var settings = {
		flash_url : "../swfupload/swfupload_f9.swf",
		upload_url: "../admin/uploadImages.php",	// Relative to the SWF file
		post_params: {"person_id" : person_id},
		file_size_limit : "2 MB",
		file_types : "*.jpg",
		file_types_description : "JPG Images",
		file_upload_limit : 1,
		file_queue_limit : 1,
		custom_settings : {
            progressTarget : "fsUploadProgress", 
			cancelButtonId : "btnCancel"
        },
        
        debug: false,
		
		file_queued_handler : peopleProfileFileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,
		queue_complete_handler : peopleProfileUploadComplete
	};

	swfu = new SWFUpload(settings);
}

/*
 *
 */
function loadVideoPlayer(videoUrl){
    $('pjVideoPlayer').set('html', '<p class="infoBx">! - You need to update your <a href="http://www.adobe.com/go/getflash" title="get flash player">flash player</a> to view the content</p>');
    $('pjVideoPlayer').setStyle("width", "350px");
	$('pjVideoPlayer').setStyle("height", "350px");
    var infoBx = new Fx.Tween($('pjVideoPlayer').getElement('p.infoBx'));
    infoBx.set('background-color', '#C33');
    infoBx.start('background-color', '#333');
    
    var so = new SWFObject("M3VideoPlayer.swf", "videoPlayer", "350", "335", "9", "#000000");
    so.addVariable("vPath",  videoUrl);
    so.write("pjVideoPlayer");
}

/*
 * Performs a search on the given input
 */
function performSearch(search_term) {
    resetMenus();
    requestSearch(search_term, 2);
	requestSearch(search_term, 3);
    requestSearch(search_term, 4);
	requestSearch(search_term, 5);
	requestSearch(search_term, 6);
	requestSearch(search_term, 7);
}

/*
 * 
 */
function requestSearch(search_term, menu_id) {
    /*if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            xmlHttp.open("POST", "includes/ajax/search.ajax", true);
            xmlHttp.onreadystatechange = handleRequestSearch;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("performSearch") + "&search_term=" + encodeURIComponent(search_term) + "&menu_id=" + encodeURIComponent(menu_id));
        } catch(e) {
            alert("requestSearch() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("requestSearch('" + search_term + "', '" + menu_id + "')", 1);
    }*/
	
	var request = new Request({
		method: 'post', 
		url: 'includes/ajax/search.ajax', 
		onSuccess: function(responseText, responseXML) {
			handleRequestSearch(responseXML);
		}
	}).send('request=performSearch&search_term=' + search_term + '&menu_id=' + menu_id);
}

/*
 * Handles the results returned by the requestSearch() function
 */
function handleRequestSearch(responseXML) {
    /*if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseXML;
                xmlRoot = xmlResponse.documentElement;
                entityMasterIdArray = xmlRoot.getElementsByTagName("entityMasterId");
                entityLevelArray = xmlRoot.getElementsByTagName("entityLevel");
                menuReferenceArray = xmlRoot.getElementsByTagName("menureference");
                menuReference = menuReferenceArray.item(0).firstChild.data;
                parentEntityMasterIdArray = xmlRoot.getElementsByTagName("parentEntityMasterId");
                parentEntityMasterId = parentEntityMasterIdArray.item(0).firstChild.data;
                
                for(var i=0; i<entityMasterIdArray.length; i++) {
                    insertEntityItem(menuReference, entityMasterIdArray.item(i).firstChild.data, entityLevelArray.item(i).firstChild.data, '', parentEntityMasterId, false);
                }
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }*/
	
	try {
        var xmlRoot = responseXML.documentElement;
        entityMasterIdArray = xmlRoot.getElementsByTagName("entityMasterId");
        entityLevelArray = xmlRoot.getElementsByTagName("entityLevel");
        menuReferenceArray = xmlRoot.getElementsByTagName("menureference");
        menuReference = menuReferenceArray.item(0).firstChild.data;
        parentEntityMasterIdArray = xmlRoot.getElementsByTagName("parentEntityMasterId");
        parentEntityMasterId = parentEntityMasterIdArray.item(0).firstChild.data;
        
        for(var i=0; i<entityMasterIdArray.length; i++) {
            insertEntityItem(menuReference, entityMasterIdArray.item(i).firstChild.data, entityLevelArray.item(i).firstChild.data, '', parentEntityMasterId, false);
        }
    } catch(e) {
        alert("Error reading the response: " + e.toString());
    }
}

/*
 * Resets the content inside the menus
 */
function resetMenus(excludeMenu1) {
	// Destroy the admin row if it exists
	if($('adminAddEntityRow')) {
		$('adminAddEntityRow').dispose();
	}
	
	for(var i = 2; i <= 7; i++){
		$('project_scroll_' +i).setStyle('height', 'auto');
		$('prjScrollUp_' +i).setStyle('display', 'none');
		$('prjScrollDown_' +i).setStyle('display', 'none');
	
		prjScroll[i] = new Fx.Scroll('project_scroll_' +i, {
						wait: false,
						duration: 500,
						transition: Fx.Transitions.Quad.easeInOut
					});
				
		//reset
		prjScroll[i].set(0, 0);
		currentPrjMenuPosY[i] = 0;
	}
	
	if (!excludeMenu1) {
		// Main Menu
		$("menu_1").innerHTML = '';
	}
	// Projects
	$("menu_2").innerHTML = '';
	// Project Types
	$("menu_3").innerHTML = '';
	// People
	$("menu_4").innerHTML = '';
	// Date
	$("menu_5").innerHTML = '';
	// Location
	$("menu_6").innerHTML = '';
	// Ideas
	$("menu_7").innerHTML = '';
}

/*
 * Clear all buttons that have been highlighted, and sets 
 * the current button with the highlight class.
 */
function highlightButton(current_section, current_button_reference) {
	// Remove all references of the highlight class
    $(current_section).getElements('.highlight').each(function (item) {
		item.removeClass('highlight');
	});
	
	// Apply the highlight class to current_button_reference
	if(current_button_reference != undefined) {
		try {
			$(current_button_reference).addClass('highlight');
		} catch(e) {
			// do nothing
		}
	}
}

/*
function toggleMoreProjects() {
	if($('projects_more_link').innerHTML == 'more') {
		$('project_scroll_2').setStyle('overflow-y', 'auto');
		$('projects_more_link').innerHTML = 'less';
	} else {
		$('project_scroll_2').setStyle('overflow-y', 'hidden');
		$('projects_more_link').innerHTML = 'more';
	}
}
*/

/*
 * Calls for the entities for the selected menu
 */
function getEntities(current_menu_reference, entity_master_id, menu_reference) {
	/*if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			highlightButton('top_menu', current_menu_reference);
			resetDataSection();
			resetMenus();
			removeRelationshipLinkButtons();
			removeSortButtons();
			if (entity_master_id != 1) {
				showSortIcon(entity_master_id);
			}
			xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
			xmlHttp.onreadystatechange = handleGetEntities;
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttp.send("request=" + encodeURI("getEntities") + "&entityid=" + encodeURI(entity_master_id) + "&menuReference=" + encodeURI(menu_reference));
		} catch(e) {
			alert("getEntities() Can't connect to the server:\n" + e.toString());
		}
	} else {
		setTimeout("getEntities('" + current_menu_reference + "', '" + entity_master_id + "', '" + menu_reference + "')", 1);
	}*/
	
	try {
		highlightButton('top_menu', current_menu_reference);
		resetDataSection();
		resetMenus();
		removeRelationshipLinkButtons();
		removeSortButtons();
		if (entity_master_id != 1) {
			showSortIcon(entity_master_id);
		}
		var request = new Request({
			method: 'post', 
			url: 'includes/ajax/entities.ajax', 
			onSuccess: function(responseText, responseXML) {
				handleGetEntities(responseXML);
			}
		}).send('request=getEntities&entityid=' + entity_master_id + '&menuReference=' + menu_reference);
	} catch(e) {
		alert("getEntities() Can't connect to the server:\n" + e.toString());
	}
}

function showSortIcon(entity_master_id){
	var menu_reference = '';
	switch(entity_master_id) {
		case "2":
			menu_reference = 'projects';
			break;
		case "3":
			menu_reference = 'project_types';
			break;
		case "4":
			menu_reference = 'people';
			break;
		case "5":
			menu_reference = 'date';
			break;
		case "6":
			menu_reference = 'location';
			break;
		case "7":
			menu_reference = 'ideas';
			break;
	}
	
	if(isAdmin == true){
		if($(menu_reference + '_sort_button')) {
			var sortButton = $(menu_reference + '_sort_button');
		} else {
			var sortButton = new Element('a', {
				'id':menu_reference + '_sort_button'
			});
		}
		sortButton.addEvent('click', function(event) {
			sortEntities(entity_master_id, menu_reference);
		});
		sortButton.setAttribute("href", "#");
		sortButton.innerHTML = '<img src="images/sort.png" width="25" height="14" alt="Sort" />';
		$(menu_reference).appendChild(sortButton);
	}
}

/*
 * Handles the return of the entities for the selected menu
 */
function handleGetEntities(responseXML) {
	/*if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {*/
			try {
				$('menu_content').setStyle("border-bottom", "0px");
				//var xmlResponse = xmlHttp.responseXML;
				var xmlRoot = responseXML.documentElement;
				entityMasterIdArray = xmlRoot.getElementsByTagName("entityMasterId");
				entityLevelArray = xmlRoot.getElementsByTagName("entityLevel");
				menuReferenceArray = xmlRoot.getElementsByTagName("menureference");
				menuReference = menuReferenceArray.item(0).firstChild.data;
                parentEntityMasterIdArray = xmlRoot.getElementsByTagName("parentEntityMasterId");
                parentEntityMasterId = parentEntityMasterIdArray.item(0).firstChild.data;
                
				for(var i=0; i<entityMasterIdArray.length; i++) {
					insertEntityItem(menuReference, entityMasterIdArray.item(i).firstChild.data, ((entityLevelArray.item(i).firstChild)?escape(entityLevelArray.item(i).firstChild.data):'&nbsp;'), '', parentEntityMasterId, true);
				}
				
				if(parentEntityMasterId != 1){
					var maxNumMenuItem = 25;
				
					var prjMenuItems = $$('#menu_' +parentEntityMasterId+ ' li');
					var prjMenuItemsNum = prjMenuItems.length;
				
					var accordionSubNav
					heightOfItems[parentEntityMasterId] = 0;
				
					// need to get the height of 25 li items
					for(var i = 0; i < maxNumMenuItem; i++){
						if(i < prjMenuItemsNum){
							heightOfItems[parentEntityMasterId] += prjMenuItems[i].offsetHeight;
						}
					}

					prjMenuHeight[parentEntityMasterId] = $('menu_' +parentEntityMasterId).offsetHeight;
				
					prjScroll[parentEntityMasterId] = new Fx.Scroll('project_scroll_' +parentEntityMasterId, {
						wait: false,
						duration: 500,
						transition: Fx.Transitions.Quad.easeInOut
					});

					//reset
					prjScroll[parentEntityMasterId].set(0, 0);
					currentPrjMenuPosY[parentEntityMasterId] = 0;
				
					if(prjMenuHeight[parentEntityMasterId] > heightOfItems[parentEntityMasterId] + 5){
						$('project_scroll_' +parentEntityMasterId).setStyle('height', heightOfItems[parentEntityMasterId] + 'px');
						$('prjScrollUp_' +parentEntityMasterId).setStyle('display', 'block');
						$('prjScrollDown_' +parentEntityMasterId).setStyle('display', 'block');
					}else{
						$('project_scroll_' +parentEntityMasterId).setStyle('height', 'auto');
					}
				}
				
				
				if(isAdmin) {
                    if(parentEntityMasterId != '1') {
						// Create the admin row
						try {
							var adminAddEntityRow = document.createElement('div');
							adminAddEntityRow.setAttribute("id", "adminAddEntityRow");
                        } catch(e) {
                            var adminAddEntityRow = document.createElement('<div id="adminAddEntityRow"></div>');
						}
						
                        adminAddEntityRow.innerHTML = '<input type="text" id="addEntityText" name="addEntityText" /><input class="genericEntityBtn" type="button" onclick="addNewEntity(\'' + parentEntityMasterId + '\')" id="addEntityAddButton" name="addEntityAddButton" value="Add" />';
                        $('column_' + parentEntityMasterId).appendChild(adminAddEntityRow);
                    }
                    
                    // Enable sorting on the specified list
                    mySortables = new Sortables(menuReference, {
                        constrain: true,
                        clone: true,
                        opacity: .5,
                        revert: true, 
                        handle: 'handle', 
                        snap: 2,
                        transition: Fx.Transitions.Back.easeOut
                    });
                    
                    // Add the event on when sorting (dragging) is complete
                    mySortables.addEvent('complete', function () {
                        updateMenuOrder(parentEntityMasterId, mySortables.serialize());
                    });
                }
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		/*} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}*/
}

/*
 * 
 */
 function updateMenuOrder(menu_id, menu_array) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
            xmlHttp.onreadystatechange = handleXMLHttpReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("updateOrder") + "&menu_id=" + encodeURI(menu_id) + "&menu_array=" + encodeURI(menu_array));
        } catch(e) {
            alert("updateMenuOrder() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("updateMenuOrder('" + menu_id + "', '" + menu_array + "')", 1);
    }
}

/*
 * Adds a new entity under the current menu
 */
function addNewEntity(parent_entity_id) {
    var newEntityValue = $('addEntityText').value;
    if (newEntityValue.match(/^[-a-zA-Z0-9&'"()+ ]+$/)) {
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
            try {
                $('addEntityText').value = ''; // Clear the text field
                
                xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
                xmlHttp.onreadystatechange = handleAddNewEntity;
                xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xmlHttp.send("request=" + encodeURI("addEntity") + "&parent_entity_id=" + encodeURI(parent_entity_id) + "&newEntityValue=" + escape(newEntityValue));
            } catch(e) {
                alert("addNewEntity() Can't connect to the server:\n" + e.toString());
            }
        } else {
            setTimeout("addNewEntity(" + parent_entity_id + ")", 1);
        }
    } else {
        alert("The value you entered must:-\n\n* Only contain characters a-z A-Z 0-9 \" ' & () + - and spaces\n* be 1 character or more");
    }
}

/*
 * Handles the data returned by the request addNewEntity
 */
function handleAddNewEntity() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(':|||:');
				var currentMenuReference = getMenuReference(xmlResponse[0]);
                setTimeout("getEntities('" + currentMenuReference + "', '" + encodeURIComponent(xmlResponse[0]) + "', 'menu_" + xmlResponse[0] + "')", 1);
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * Inserts the entity into the given (menu_reference) menu
 */
function insertEntityItem(menu_reference, entity_id, entity_name, highlight, parentEntityMasterId, dragHandle) {
	entityItem = document.createElement('li');
	entityItem.setAttribute("id", "entity_" + entity_id);
	entityItem.innerHTML = '';
	switch(menu_reference) {
		case "menu_2":
			sub_category_type = 'project';
			break;
		case "menu_4":
			sub_category_type = 'person';
			break;
		default:
			sub_category_type = '';
			break;
	}
    if(isAdmin && dragHandle) {
        entityItem.innerHTML += '<img src="images/arrow_out.png" class="handle" id="" width="16" height="16" alt="4 Arrows" /> ';
    }
	entityItem.innerHTML += '<a href="#" id="entity_' + entity_id + '_link" onclick="loadRelatedEntities(\''+ menu_reference + '\', \'' + entity_id + '\', \'' + entity_name + '\');loadEntityPage(\'' + entity_id + '\', \'' + sub_category_type + '\')">' + decodeURIComponent(entity_name) + '</a>';
	if(isAdmin) {
		entityItem.innerHTML += ' <a onclick="editEntity(\'' + menu_reference + '\',\'' + entity_id + '\',\'entity_' + entity_id + '\', \'' + entity_name + '\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
        if(parentEntityMasterId != '1') {
            entityItem.innerHTML += ' <a onclick="deleteEntity(\'' + entity_id + '\',\'entity_' + entity_id + '\', \'' + entity_name + '\')" title="Delete"><img src="images/application_form_delete.png" width="16" height="16" alt="Delete"></a>';
        }
	}
	$(menu_reference).appendChild(entityItem);
	if(highlight != '') {
		highlightButton('menu_content', 'entity_' + entity_id + '_link');
	}
}

/*
 * Checks for related entities with the selected entity.
 */
function loadRelatedEntities(current_menu_reference, entity_id, entity_name) {
	global_current_menu_reference = current_menu_reference;
	global_entity_id = entity_id;
	global_entity_name = entity_name;
	
	menu_reference = current_menu_reference.split("_");
	highlightButton('top_menu', getMenuReference(menu_reference[1]));
    resetDataSection();
    resetMenus();
    var parentEntityMasterId = current_menu_reference.split('_');
	insertEntityItem(current_menu_reference, entity_id, entity_name, "highlight", parentEntityMasterId[1], false);
    
	$('menu_content').setStyle("border-bottom", "1px solid #2A2A2A");
	
    if(isAdmin) {
		removeRelationshipLinkButtons();
        // Enable Related Entity Checklist Buttons
        if (current_menu_reference == "menu_2") {
			// Project Types
			if ($('project_types_checklist_entities')) {
				var relatedButton = $('project_types_checklist_entities');
			}
			else {
				var relatedButton = new Element('a', {
					'id': 'project_types_checklist_entities'
				});
			}
			relatedButton.removeEvents();
			relatedButton.addEvent('click', function(event){
				loadEntitiesChecklist(current_menu_reference, 'project_types', '3', entity_id, entity_name);
			});
			relatedButton.setAttribute("href", "#");
			relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
			$('project_types').appendChild(relatedButton);
			
			// People
			if ($('people_checklist_entities')) {
				var relatedButton = $('people_checklist_entities');
			}
			else {
				var relatedButton = new Element('a', {
					'id': 'people_checklist_entities'
				});
			}
			relatedButton.removeEvents();
			relatedButton.addEvent('click', function(event){
				loadEntitiesChecklist(current_menu_reference, 'people', '4', entity_id, entity_name);
			});
			relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
			$('people').appendChild(relatedButton);
			
			// Date
			if ($('date_checklist_entities')) {
				var relatedButton = $('date_checklist_entities');
			}
			else {
				var relatedButton = new Element('a', {
					'id': 'date_checklist_entities'
				});
			}
			relatedButton.removeEvents();
			relatedButton.addEvent('click', function(event){
				loadEntitiesChecklist(current_menu_reference, 'date', '5', entity_id, entity_name);
			});
			relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
			$('date').appendChild(relatedButton);
			
			// Location
			if ($('location_checklist_entities')) {
				var relatedButton = $('location_checklist_entities');
			}
			else {
				var relatedButton = new Element('a', {
					'id': 'location_checklist_entities'
				});
			}
			relatedButton.removeEvents();
			relatedButton.addEvent('click', function(event){
				loadEntitiesChecklist(current_menu_reference, 'location', '6', entity_id, entity_name);
			});
			relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
			$('location').appendChild(relatedButton);
			
			// Ideas
			if ($('ideas_checklist_entities')) {
				var relatedButton = $('ideas_checklist_entities');
			}
			else {
				var relatedButton = new Element('a', {
					'id': 'ideas_checklist_entities'
				});
			}
			relatedButton.removeEvents();
			relatedButton.addEvent('click', function(event){
				loadEntitiesChecklist(current_menu_reference, 'ideas', '7', entity_id, entity_name);
			});
			relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
			$('ideas').appendChild(relatedButton);
		} else if (current_menu_reference == "menu_4") {
			// Date
			if ($('date_checklist_entities')) {
				var relatedButton = $('date_checklist_entities');
			}
			else {
				var relatedButton = new Element('a', {
					'id': 'date_checklist_entities'
				});
			}
			relatedButton.removeEvents();
			relatedButton.addEvent('click', function(event){
				loadEntitiesChecklist(current_menu_reference, 'date', '5', entity_id, entity_name);
			});
			relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
			$('date').appendChild(relatedButton);
			
			// Ideas
			if ($('ideas_checklist_entities')) {
				var relatedButton = $('ideas_checklist_entities');
			}
			else {
				var relatedButton = new Element('a', {
					'id': 'ideas_checklist_entities'
				});
			}
			relatedButton.removeEvents();
			relatedButton.addEvent('click', function(event){
				loadEntitiesChecklist(current_menu_reference, 'ideas', '7', entity_id, entity_name);
			});
			relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
			$('ideas').appendChild(relatedButton);
		}
    } 
    
	if(current_menu_reference != "menu_1") {
		getRelatedEntities(current_menu_reference, '1', entity_id, 'menu_1', encodeURI(entity_name));  // m3architecture    
	}
	if(current_menu_reference != "menu_2") {
		getRelatedEntities(current_menu_reference, '2', entity_id, 'menu_2', encodeURI(entity_name));  // Projects
	}
	if(current_menu_reference != "menu_3") {
		getRelatedEntities(current_menu_reference, '3', entity_id, 'menu_3', encodeURI(entity_name));  // Project Types
	}
	if(current_menu_reference != "menu_4") {
		getRelatedEntities(current_menu_reference, '4', entity_id, 'menu_4', encodeURI(entity_name));  // People
	}
	if(current_menu_reference != "menu_5") {
		getRelatedEntities(current_menu_reference, '5', entity_id, 'menu_5', encodeURI(entity_name));  // Date
	}
	if(current_menu_reference != "menu_6") {
		getRelatedEntities(current_menu_reference, '6', entity_id, 'menu_6', encodeURI(entity_name));  // Location
	}
	if(current_menu_reference != "menu_7") {
		getRelatedEntities(current_menu_reference, '7', entity_id, 'menu_7', encodeURI(entity_name));  // Ideas
	}
}

function removeRelationshipLinkButtons() {
	// Remove Related Entity Checklist Buttons
	if($('projects_checklist_entities')) {
        $('projects').removeChild($('projects_checklist_entities'));
    }
    if($('project_types_checklist_entities')) {
        $('project_types').removeChild($('project_types_checklist_entities'));
    }
    if($('people_checklist_entities')) {
        $('people').removeChild($('people_checklist_entities'));
    }
    if($('date_checklist_entities')) {
        $('date').removeChild($('date_checklist_entities'));
    }
    if($('location_checklist_entities')) {
        $('location').removeChild($('location_checklist_entities'));
    }
    if($('ideas_checklist_entities')) {
        $('ideas').removeChild($('ideas_checklist_entities'));
    }
}

function removeSortButtons() {
	if($('projects_sort_button')) {
        $('projects').removeChild($('projects_sort_button'));
    }
    if($('project_types_sort_button')) {
        $('project_types').removeChild($('project_types_sort_button'));
    }
    if($('people_sort_button')) {
        $('people').removeChild($('people_sort_button'));
    }
    if($('date_sort_button')) {
        $('date').removeChild($('date_sort_button'));
    }
    if($('location_sort_button')) {
        $('location').removeChild($('location_sort_button'));
    }
    if($('ideas_sort_button')) {
        $('ideas').removeChild($('ideas_sort_button'));
    }
}

function sortEntities(parent_entity, menu_reference) {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            $('menu_' + parent_entity).innerHTML = '';
    
            // Get all the entities under the current menu
            xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
            xmlHttp.onreadystatechange = handleSortEntities;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("sortEntities") + "&masterid=" + encodeURI(parent_entity) + "&menu_reference=" + encodeURI(menu_reference));
        } catch(e) {
            alert("sortEntities() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("sortEntities('" + parent_entity + "', '" + menu_reference + "')", 1);
    }
}

function handleSortEntities() {
	if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
				var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(':|||:');
				setTimeout("getEntities('" + xmlResponse[1] + "_title', '" + xmlResponse[0] + "', 'menu_" + xmlResponse[0] + "')", 2);
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * Brings up the list of entities that are related to the current entity
 */
function loadEntitiesChecklist(selected_menu, menu, parent_entity, current_entity, entity_value) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            // Clear the menu and change the onclick action of the related entities button
            $('menu_' + parent_entity).innerHTML = '';
            relatedButton = $(menu + '_checklist_entities');
			relatedButton.removeEvents();
            relatedButton.addEvent('click', function(event) {
				revertRelatedEntitiesButton(selected_menu, menu, parent_entity, current_entity, 'menu_' + parent_entity, entity_value);
			});
    
            // Get all the entities under the current menu
            xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
            xmlHttp.onreadystatechange = handleLoadRelatedEntitiesChecklist;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("getRelatedEntitiesChecklist") + "&masterid=" + encodeURI(parent_entity) + "&entityid=" + encodeURI(current_entity) + "&menuReference=" + encodeURI('menu_' + parent_entity));
        } catch(e) {
            alert("loadEntitiesChecklist() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("loadEntitiesChecklist('" + selected_menu + "', '" + menu + "', '" + parent_entity + "', '" + current_entity + "', '" + entity_value + "')", 1);
    }
}

/*
 * Handles the data returned from loadEntitiesChecklist
 */
function handleLoadRelatedEntitiesChecklist() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(':|||:');
                $(xmlResponse[0]).innerHTML = xmlResponse[1];
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * Sends the new relationship status between a project entity and another entity
 */
function changeEntityRelationship(project_id, entity_id, checked) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
            xmlHttp.onreadystatechange = handleXMLHttpReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("saveEntityRelationship") + "&project_id=" + encodeURI(project_id) + "&entity_id=" + encodeURI(entity_id) + "&checked=" + encodeURI(checked));
        } catch(e) {
            alert("changeEntityRelationship() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("changeEntityRelationship('" + project_id + "', '" + entity_id + "', '" + checked + "')", 1);
    }
}

/*
 * Reverts the menu back to normal and removes the related entities checklist
 */
function revertRelatedEntitiesButton(selected_menu, menu, parent_entity, current_entity, entity_value) {
    $('menu_' + parent_entity).innerHTML = '';
    relatedButton = $(menu + '_checklist_entities');
    relatedButton.setAttribute("onclick", "loadEntitiesChecklist('" + selected_menu + "', '" + menu + "', '" + parent_entity + "', '" + current_entity + "', '" + entity_value + "')");
    getRelatedEntities(selected_menu, parent_entity, current_entity, 'menu_' + parent_entity, entity_value);
}

/*
 * Calls for the entities related to the selected entity.
 */
function getRelatedEntities(current_menu_reference, entity_master_id, entity_id, menu_reference, entity_name) {
	/*if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			removeSortButtons();
			var peopleMenu = false;
			var dateIdeasMenu = false;
			if(
				(current_menu_reference == 'menu_4' && (menu_reference == 'menu_5' || menu_reference == 'menu_7')) || 
				(current_menu_reference == 'menu_5' && menu_reference == 'menu_4') || 
				(current_menu_reference == 'menu_7' && menu_reference == 'menu_4')
			) {
				peopleMenu = true;
				dateIdeasMenu = true;
			}
			
			xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
			xmlHttp.onreadystatechange = handleLoadRelatedEntities;
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttp.send("request=" + encodeURI("getRelatedEntities") + "&masterid=" + encodeURI(entity_master_id) + "&entityid=" + encodeURI(entity_id) + "&menuReference=" + encodeURI(menu_reference) + "&peopleMenu=" + encodeURI(peopleMenu) + "&dateIdeasMenu=" + encodeURI(dateIdeasMenu));
		} catch(e) {
			alert("getRelatedEntities() Can't connect to the server:\n" + e.toString());
		}
	} else {
		setTimeout("getRelatedEntities('" + current_menu_reference + "', '" + entity_master_id + "', '" + entity_id + "', '" + menu_reference + "', '" + encodeURIComponent(entity_name) + "')", 1);
	}*/
	
	try {
		removeSortButtons();
		var peopleMenu = false;
		var dateIdeasMenu = false;
		if(
			(current_menu_reference == 'menu_4' && (menu_reference == 'menu_5' || menu_reference == 'menu_7')) || 
			(current_menu_reference == 'menu_5' && menu_reference == 'menu_4') || 
			(current_menu_reference == 'menu_7' && menu_reference == 'menu_4')
		) {
			peopleMenu = true;
			dateIdeasMenu = true;
		}
		var request = new Request({
			method: 'post', 
			url: 'includes/ajax/entities.ajax', 
			onSuccess: function(responseText, responseXML) {
				handleLoadRelatedEntities(responseXML);
			}
		}).send('request=getRelatedEntities&masterid=' + entity_master_id + '&entityid=' + entity_id + '&menuReference=' + menu_reference + '&peopleMenu=' + peopleMenu + '&dateIdeasMenu=' + dateIdeasMenu);
	} catch(e) {
		alert("getRelatedEntities() Can't connect to the server:\n" + e.toString());
	}
}

/*
 * Handles the return of the entities relating to the selected entity
 */
function handleLoadRelatedEntities(responseXML) {
	/*
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
	*/
			try {
				/*
				var xmlResponse = xmlHttp.responseXML;
				*/
				
				var xmlResponse = responseXML;
				//var xmlRoot = responseXML.documentElement;
				var xmlRoot = xmlResponse.documentElement;
				entityMasterIdArray = xmlRoot.getElementsByTagName("entityMasterId");
				entityLevelArray = xmlRoot.getElementsByTagName("entityLevel");
				menuReferenceArray = xmlRoot.getElementsByTagName("menureference");
				menuReference = menuReferenceArray.item(0).firstChild.data;
				for(var i=0; i<entityMasterIdArray.length; i++) {
                    var parentEntityMasterId = menuReference.split('_');
					insertEntityItem(menuReference, entityMasterIdArray.item(i).firstChild.data, escape(entityLevelArray.item(i).firstChild.data), '', parentEntityMasterId[1], false);
				}
				
                parentEntityMasterIdArray = xmlRoot.getElementsByTagName("parentEntityMasterId");
                parentEntityMasterId = parentEntityMasterIdArray.item(0).firstChild.data;
				
				if(parentEntityMasterId != 1 && entityMasterIdArray.length != 0) {
					var maxNumMenuItem = 15;

					var prjMenuItems = $$('#menu_' +parentEntityMasterId+ ' li');
					var prjMenuItemsNum = prjMenuItems.length;

					var accordionSubNav;
					heightOfItems[parentEntityMasterId] = 0;

					// need to get the height of 25 li items
					for(var i = 0; i < maxNumMenuItem; i++){
						if(i < prjMenuItemsNum){
							heightOfItems[parentEntityMasterId] += prjMenuItems[i].offsetHeight;
						}
					}

					prjMenuHeight[parentEntityMasterId] = $('menu_' +parentEntityMasterId).offsetHeight;

					prjScroll[parentEntityMasterId] = new Fx.Scroll('project_scroll_' +parentEntityMasterId, {
						wait: false,
						duration: 500,
						transition: Fx.Transitions.Quad.easeInOut
					});

					//reset
					prjScroll[parentEntityMasterId].set(0, 0);
					currentPrjMenuPosY[parentEntityMasterId] = 0;

					if(prjMenuHeight[parentEntityMasterId] > heightOfItems[parentEntityMasterId] + 5){
						$('project_scroll_' +parentEntityMasterId).setStyle('height', heightOfItems[parentEntityMasterId] + 'px');
						$('prjScrollUp_' +parentEntityMasterId).setStyle('display', 'block');
						$('prjScrollDown_' +parentEntityMasterId).setStyle('display', 'block');
					}else{
						$('project_scroll_' +parentEntityMasterId).setStyle('height', 'auto');
					}
				}
			
			
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		/*
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
	*/
}

/*
 * Changes the text to an input field and submit button
 */
function editEntity(menu_reference, entity_id, entity_reference, entity_value) {
	$(entity_reference).innerHTML = '<input type="text" class="txt" id="text_' + entity_reference + '" name="text_' + entity_reference + '" value="" /><input class="genericEntityBtn" type="button" onclick="saveEntity(\'' + menu_reference + '\',\'' + entity_id + '\', \'text_' + entity_reference + '\', \'' + entity_reference + '\');" id="submit_' + entity_reference + '" name="submit_' + entity_reference + '" value="Edit" />';
	$('text_' + entity_reference).value = decodeURIComponent(entity_value);
}

/*
 * Saves the new change to the database and converts the entity back to normal state.
 * MUST BE ADMINISTRATOR
 */
function saveEntity(menu_reference, entity_id, text_entity_reference, entity_reference) {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			var entity_value = $(text_entity_reference).value;
			$(entity_reference).innerHTML = '';
        	//$(entity_reference).innerHTML += '<img src="images/arrow_out.png" class="handle" id="" width="16" height="16" alt="4 Arrows" /> ';
			$(entity_reference).innerHTML += ' <a onclick="loadRelatedEntities(\''+ menu_reference + '\', \'' + entity_id + '\', \'' + entity_value + '\');loadEntityPage(\'' + entity_id + '\');">' + decodeURI(entity_value) + '</a>';
            $(entity_reference).innerHTML += ' <a onclick="editEntity(\'' + menu_reference + '\',\'' + entity_id + '\',\'entity_' + entity_id + '\', \'' + decodeURI(entity_value) + '\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
            $(entity_reference).innerHTML += ' <a onclick="deleteEntity(\'' + entity_id + '\',\'entity_' + entity_id + '\', \'' + decodeURI(entity_value) + '\')" title="Delete"><img src="images/application_form_delete.png" width="16" height="16" alt="Delete"></a>';
			xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
			xmlHttp.onreadystatechange = handleSaveEntity;
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttp.send("request=" + encodeURI("saveEntity") + "&entityid=" + encodeURI(entity_id) + "&entityvalue=" + encodeURIComponent(entity_value));
		} catch(e) {
			alert("saveEntity() Can't connect to the server:\n" + e.toString());
		}
	} else {
		setTimeout("saveEntity('" + menu_reference + "', '" + entity_id + "', '" + text_entity_reference + "', '" + entity_reference + "')", 1);
	}
}

/*
 * Handles the return statement about saving the entity
 */
function handleSaveEntity() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				var xmlResponse = xmlHttp.responseXML;
				xmlRoot = xmlResponse.documentElement;
				entitySaveResponse = xmlRoot.firstChild.data;
				if(!entitySaveResponse) {
					alert("There was an error updating the database.");
				}
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

/*
 * Delete the entity given
 */
function deleteEntity(entity_id, entity_reference, entity_name) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            if(confirm("Are you sure you want to delete '" + decodeURI(entity_name) + "'?")) {
                xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
                xmlHttp.onreadystatechange = handleXMLHttpReturn;
                xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xmlHttp.send("request=" + encodeURI("deleteEntity") + "&entity_id=" + encodeURI(entity_id) + "&entity_reference=" + encodeURI(entity_reference) + "&entity_name=" + encodeURI(entity_name));
                $(entity_reference).dispose();
            }
        } catch(e) {
            alert("deleteEntity() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("deleteEntity('" + entity_id + "', '" + entity_reference + "', '" + entity_name + "')", 1);
    }
}

/*
 * Resets the data elements at the bottom of the page
 */
function resetDataSection() {
	$('additional_details_menu').setStyle('display', 'none');  // Hide the sub navigation menu
	if ($('people_profile_picture')) {
		$('people_profile_picture').dispose();
	}
	$("additional_details_list").innerHTML = '';
    additionalDetailsAdminData = $('additional_details_admin_data');
    if(additionalDetailsAdminData != null) {
        $('additional_details_admin_data').innerHTML = '';
        $('additional_details').removeChild(additionalDetailsAdminData); // remove the admin div
    }
	$("additional_details_body").innerHTML = '';
	$("additional_details").style.visibility = 'hidden';
}

/*
 * Loads the page content related to the entity selected
 */
function loadEntityPage(entity_master_id, sub_category_type) {
	global_sub_category_type = sub_category_type;
	
	window.addEvent('domready', function() {
		resetDataSection();
		document.getElementById("additional_details").style.visibility = 'visible';
		document.getElementById("additional_details_menu").style.visibility = 'visible';
		document.getElementById("additional_details_list").style.visibility = 'visible';
		document.getElementById("additional_details_body").style.visibility = 'visible';
	
		if(sub_category_type) {
			getSubCategories(entity_master_id, sub_category_type);
		}
		
		getData(entity_master_id, '0');  // Gets default data that does not require a sub menu click
		
		if(sub_category_type == 'person') {
			loadProfilePicture(entity_master_id);
		}
	});
}

/**
 * 
 * @param {Object} entity_master_id
 */
function loadProfilePicture(entity_master_id) {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			xmlHttp.open("POST", "includes/ajax/peopleProfilePicture.ajax", true);
			xmlHttp.onreadystatechange = handleLoadProfilePicture;
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttp.send("request=" + encodeURI("getPeopleProfilePicture") + "&person_id=" + encodeURI(entity_master_id));
		} catch(e) {
			alert("loadProfilePicture() Can't connect to the server:\n" + e.toString());
		}
	} else {
		setTimeout("loadProfilePicture('" + entity_master_id + "')", 1);
	}
}

function handleLoadProfilePicture() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				var xmlResponse = xmlHttp.responseText;
				xmlResponse = xmlResponse.split(':|||:');
				if ($('profile_picture_div')) {
					$('profile_picture_div').dispose();
				}
				if(isAdmin) {
					xmlResponseDiv = new Element('div', {id: 'profile_picture_admin_div'});
				}else{
					xmlResponseDiv = new Element('div', {id: 'profile_picture_div'});
				}
				
				xmlResponseDiv.innerHTML = xmlResponse[1];
				if(isAdmin) {
					$('additional_details').appendChild(xmlResponseDiv);
				}else{
					xmlResponseDiv.inject($('additional_details_body'), 'before');
				}
				if(isAdmin) {
					initPeopleProfilePictureSWFUpload(xmlResponse[0]);
				}
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

/*
 * Loads the photos page content related to the entity selected
 */
function loadEntityPhotosPage(entity_master_id, sub_category_type) {
	resetDataSection();
	document.getElementById("additional_details").style.visibility = 'visible';
	document.getElementById("additional_details_menu").style.visibility = 'visible';
	document.getElementById("additional_details_list").style.visibility = 'visible';
	document.getElementById("additional_details_body").style.visibility = 'visible';

	if(sub_category_type) {
		getSubCategories(entity_master_id, sub_category_type);
	}
	getData(entity_master_id, '2', 'project', 'sub_category_link_2');  // Gets default data that does not require a sub menu click
}

/*
 * Gets the categories of the data
 */
function getSubCategories(entity_master_id, sub_category_type) {
	/*if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			xmlHttp.open("POST", "includes/ajax/data.ajax", true);
			xmlHttp.onreadystatechange = handleGetSubCategories;
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttp.send("request=" + encodeURI("getSubCategories") + "&masterid=" + encodeURI(entity_master_id) + "&subCategoryType=" + encodeURI(sub_category_type));
		} catch(e) {
			alert("getSubCategories() Can't connect to the server:\n" + e.toString());
		}
	} else {
		setTimeout("getSubCategories('" + entity_master_id + "', '" + sub_category_type + "')", 1);
	}*/
	try {
		var request = new Request({
			method: 'post', 
			url: 'includes/ajax/data.ajax', 
			onSuccess: function(responseText) {
				handleGetSubCategories(responseText);
			}
		}).send('request=getSubCategories&masterid=' + entity_master_id + '&subCategoryType=' + sub_category_type);
	} catch(e) {
		alert("getSubCategories() Can't connect to the server:\n" + e.toString());
	}
}

/*
 * Handles the return statement of the data's sub categories
 */
function handleGetSubCategories(responseText) {
	/*if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {*/
			try {
				$('additional_details_menu').setStyle('display', 'block');  // Show the sub navigation menu
				//var xmlResponse = xmlHttp.responseText;
				$('additional_details_list').innerHTML = decodeURI(responseText);
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		/*} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}*/
}

/*
 * Requests for the designated data from the server
 */
function getData(entity_id, sub_category_id, sub_category_type, sub_category_button) {
	global_entity_id = entity_id;
	global_sub_category_id = sub_category_id;
	global_sub_category_type = sub_category_type;
	global_sub_category_button = sub_category_button;
	
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			highlightButton('additional_details_menu', sub_category_button);
			
            // Clear any admin panels
            if(isAdmin) {
                adminDiv = $('additional_details_admin_data');
                if(adminDiv != null) {
                    $('additional_details').removeChild(adminDiv);
                }
            }
        
			$('additional_details_body').innerHTML = '';
			// If the sub_category_id is equal to 0 then it must be a left menu selection.
			if(sub_category_id == 0) {
				switch(entity_id) {
					/*
					 * Left Menu
					 */
					case "17": // News
						xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
						xmlHttp.onreadystatechange = handleGetArticleData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + entity_id + "&project_id=0");
						break;
					case "6": // Awards
						xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
						xmlHttp.onreadystatechange = handleGetArticleData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + entity_id + "&project_id=0");
						break;
					case "7": // Publications
						xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
						xmlHttp.onreadystatechange = handleGetArticleData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + entity_id + "&project_id=0");
						break;
					case "22": // Talks & Lectures
						xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
						xmlHttp.onreadystatechange = handleGetArticleData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + entity_id + "&project_id=0");
						break;
					case "8": // Exhibitions
						xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
						xmlHttp.onreadystatechange = handleGetArticleData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + entity_id + "&project_id=0");
						break;
					/*
						switch(entity_id) {
							case "4": // News
								entity_id = "17";
								break;
							case "5": // Awards
								entity_id = "6";
								break;
							case "6": // Publications
								entity_id = "7";
								break;
							case "8": // Talks & Lectures
								entity_id = "16";
								break;
							case "9": // Exhibitions
								entity_id = "8";
								break;
						}
						xmlHttp.open("POST", "includes/ajax/articles.php", true);
						xmlHttp.onreadystatechange = handleGetArticleData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + entity_id + "&project_id=0");
						break;
					*/

					case "18": // Gallery
						xmlHttp.open("POST", "includes/ajax/gallery.ajax", true);
						xmlHttp.onreadystatechange = handleGalleryData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getGalleryData") + "&project_id=0");
						break;
					
					case "10": // Contact Us
						xmlHttp.open("POST", "includes/ajax/contactus.ajax", true);
						xmlHttp.onreadystatechange = handleContactUsData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getContactUsData"));
						break;
                        
                    case "145": // Search
                        showSearchForm();
                        break;
				
					/*
					 * Default
					 */
					default:
						xmlHttp.open("POST", "includes/ajax/data.ajax", true);
						xmlHttp.onreadystatechange = handleGetData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getData") + "&entityid=" + encodeURI(entity_id) + "&subcategoryid=" + encodeURI(sub_category_id));
						break;
				}
			} else {
				switch(sub_category_id) {
					/* 
					 * Categories for Projects
					 */
					case "1": // Concept
						xmlHttp.open("POST", "includes/ajax/data.ajax", true);
						xmlHttp.onreadystatechange = handleProjectConcept;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getData") + "&entityid=" + encodeURI(entity_id) + "&subcategoryid=" + encodeURI(sub_category_id));
						break;
					case "2": // Photos
						xmlHttp.open("POST", "includes/ajax/projectPhotos.ajax", true);
						xmlHttp.onreadystatechange = handlePhotosData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getPhotosData") + "&project_id=" + encodeURI(entity_id));
						break;
					case "3": // Data
						xmlHttp.open("POST", "includes/ajax/projectData.ajax", true);
						xmlHttp.onreadystatechange = handleProjectData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getProjectData") + "&project_id=" + encodeURI(entity_id));
						break;
					case "4": // Drawings
						xmlHttp.open("POST", "includes/ajax/projectDrawings.ajax", true);
						xmlHttp.onreadystatechange = handleProjectDrawings;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getProjectDrawings") + "&project_id=" + encodeURI(entity_id));
						break;
					case "5": // Videos
						xmlHttp.open("POST", "includes/ajax/projectVideos.ajax", true);
						xmlHttp.onreadystatechange = handleProjectVideos;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getProjectVideos") + "&project_id=" + encodeURI(entity_id));
						break;
					case "6": // Awards
					case "7": // Publications
					case "8": // Exhibitions
						xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
						xmlHttp.onreadystatechange = handleGetArticleData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						/*if(sub_category_type == "project") {*/
							xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + encodeURI(sub_category_id) + "&project_id=" + encodeURI(entity_id));
						/*} else {
							xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + encodeURI(sub_category_id) + "&person_id=" + encodeURI(entity_id));
						}*/
						break;
					case "9": // Download PDF Datasheet
						xmlHttp.open("POST", "includes/ajax/projectDatasheet.ajax", true);
						xmlHttp.onreadystatechange = handleProjectDatasheet;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getPDFDatasheet") + "&project_id=" + encodeURI(entity_id) + "&sub_category_id=" + encodeURI(sub_category_id));
						break;
						
					/* 
					 * Categories for People
					 */
					case "10": // About
						xmlHttp.open("POST", "includes/ajax/data.ajax", true);
						xmlHttp.onreadystatechange = handlePeopleAbout;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getData") + "&entityid=" + encodeURI(entity_id) + "&subcategoryid=" + encodeURI(sub_category_id));
						break;
					/*case "11": // CV
						xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
						xmlHttp.onreadystatechange = handleGetArticleData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						//xmlHttp.send("request=" + encodeURI("getPeopleCV") + "&person_id=" + encodeURI(entity_id));
						xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + encodeURI(sub_category_id) + "&project_id=" + encodeURI(entity_id));
						break;*/
					case "cv": // CV
					case "13": // Qualifications
					case "14": // Affiliations
					case "15": // Experience
					case "19": // Awards
					case "20": // Exhibitions
					case "21": // Publications
						xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
						xmlHttp.onreadystatechange = handleGetArticleData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + encodeURI(sub_category_id) + "&project_id=" + encodeURI(entity_id));
						break;
					case "16": // Lectures
						xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
						xmlHttp.onreadystatechange = handleGetArticleData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getArticleData") + "&entity_master_id=" + encodeURI(sub_category_id) + "&project_id=" + encodeURI(entity_id));
						break;
					case "12": // Other
						xmlHttp.open("POST", "includes/ajax/data.ajax", true);
						xmlHttp.onreadystatechange = handlePeopleOther;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getData") + "&entityid=" + encodeURI(entity_id) + "&subcategoryid=" + encodeURI(sub_category_id));
						break;
					
					/*
					 * Default for both Projects and People
					 */
					default:
						xmlHttp.open("POST", "includes/ajax/data.ajax", true);
						xmlHttp.onreadystatechange = handleGetData;
						xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
						xmlHttp.send("request=" + encodeURI("getData") + "&entityid=" + encodeURI(entity_id) + "&subcategoryid=" + encodeURI(sub_category_id));
						break;
				}
			}
		} catch(e) {
			alert("getData() Can't connect to the server:\n" + e.toString());
		}
	} else {
		//setTimeout("getData('" + entity_id + "','" + sub_category_id + "')", 1);
		setTimeout("getData('" + entity_id + "','" + sub_category_id + "','" + sub_category_type + "','" + sub_category_button + "')", 1);
	}
}

function showSearchForm() {
    document.getElementById("additional_details_body").innerHTML = '<div class="search_div">' +
            '<input type="text" onkeypress="if (event.keyCode==13) performSearch($(\'search_value\').value);" id="search_value" name="search_value" value="" /> <input type="button" onclick="performSearch($(\'search_value\').value);" id="search_submit" name="search_submit" value="Search" />' +
        '</div>';
    $('search_value').focus();
}

function handleGetArticleData() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(":|||:");
				document.getElementById("additional_details_body").innerHTML += xmlResponse[2];
                
				if((isAdmin && xmlResponse[1] == 0) || (isAdmin && (xmlResponse[0] == 11 || xmlResponse[0] == 13 || xmlResponse[0] == 14 || xmlResponse[0] == 15 || xmlResponse[0] == 16 || xmlResponse[0] == 19 || xmlResponse[0] == 20 || xmlResponse[0] == 21))) {
                    dataAdminDiv = document.createElement("div");
                    dataAdminDiv.setAttribute("id", "additional_details_admin_data");
                    dataAdminDiv.innerHTML = '<a class="addItemLink" onclick="addArticle(\'' + xmlResponse[0] + '\', \'' + xmlResponse[1] + '\');" title="Add Article"><img src="images/application_form_add.png" width="16" height="16" alt="Add" /> Add New Item</a>';
                    $("additional_details").appendChild(dataAdminDiv);
                }
                
				// Add events to the Article Items
				window.addEvent('domready', function() {
					titlesBehaviours(xmlResponse[0], xmlResponse[1]);
					sbxStartScan(); //scan the content for slimbox, function in slimbox.js
				});
			} catch(e) {
				alert("Error reading the response: " + e.toString());
				//console.log(e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

/*
 * Inserts an empty form for the administrator to add an article
 */
function addArticle(entity_master_id, entity_id) {
    randomId = Math.floor(Math.random() * 1111111111);
    var tinyMCEInstance = tinyMCE.getInstanceById('article_new_content_' + randomId);
    if(tinyMCEInstance != null) {
        try {
            tinyMCE.execCommand( 'mceRemoveControl', false, 'article_new_content_' + randomId);
        } catch(e) {
            // Do Nothing
        }
    }
	window.addEvent('domready', function() {
		new_article_item_content = '<div id="new_article_' + randomId + '">' +
	                                    '<div class="itemYr"><label>Date:</label>' +
	                                    '<span><input type="text" id="article_new_date_' + randomId + '" name="article_new_date_' + randomId + '" value="" /></span></div>' +
	                                    '<div class="itemDesc">' +
	                                        '<h1 class="itemHeading"><label>Heading:</label>' +
	                                        '<input type="text" id="article_new_heading_' + randomId + '" name="article_new_heading_' + randomId + '" value="" /></h1>' +
	                                        '<p class="itemShrtDesc"><label>Brief Overview:</label>' +
	                                        '<input type="text" id="article_new_brief_overview_' + randomId + '" name="article_new_brief_overview_' + randomId + '" value="" /></p>' +
	                                        '<div class="itemLongDescWrapper">' +
	                                            '<div class="itemLongDesc">' + 
	                                                '<textarea id="article_new_content_' + randomId + '" name="article_new_content_' + randomId + '"></textarea>' +
	                                            '</div>' +
	                                            '<input class="genericSubmitBtn" type="submit" onclick="addArticleItem(\'' + randomId + '\', \'' + entity_master_id + '\', \'' + entity_id + '\');" id="article_submit" name="article_submit" value="Add" />' +
	                                        '</div>' +
	                                    '</div>' +
	                                '</div>' +
	                                '<br class="clear" />';
	    $('additional_details_body').innerHTML += new_article_item_content;
	    initiateTinyMCE('article_new_content_' + randomId);
	});
}

/*
 * Sends the new article to the server to save.
 */
function addArticleItem(new_article_id, entity_master_id, entity_id) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            tinyMCE.triggerSave(false,true);
            tiny_mce_editor = tinyMCE.get('article_new_content_' + new_article_id);
            newContent = tiny_mce_editor.getContent();
            
            xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
            xmlHttp.onreadystatechange = handleAddArticleItem;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("addArticleItem") + "&entityMasterId=" + encodeURI(entity_master_id) + "&project_id=" + encodeURI(entity_id) + "&article_timestamp=" + encodeURI($('article_new_date_' + new_article_id).value) + "&article_title=" + encodeURI($('article_new_heading_' + new_article_id).value) + "&article_overview=" + encodeURI($('article_new_brief_overview_' + new_article_id).value) + "&article_content=" + escape(newContent));
            
            tinyMCE.execCommand( 'mceRemoveControl', false, 'article_new_content_' + new_article_id );
            $('new_article_' + new_article_id).innerHTML = '';
        } catch(e) {
            alert("addArticleItem() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("addArticleItem('" + new_article_id + "', '" + entity_master_id + "', '" + entity_id + "')", 1);
    }
}

/*
 *
 */
function handleAddArticleItem() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
				window.addEvent('domready', function() {
					//loadRelatedEntities(global_current_menu_reference, global_entity_id, global_entity_name);
					//loadEntityPage(global_entity_id, global_sub_category_type);
					
					getData(global_entity_id, global_sub_category_id, global_sub_category_type, global_sub_category_button);
				});
                /*var xmlResponse = xmlHttp.responseText;
                document.getElementById("additional_details_body").innerHTML += xmlResponse;
                
                // Add events to the Article Items
                window.addEvent('domready', function() {
                    titlesBehaviours();
                    sbxStartScan(); //scan the content for slimbox, function in slimbox.js
                });*/
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * Handles the data and actions for the gallery.
 */
function handleGalleryData() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				var xmlResponse = xmlHttp.responseText;
				document.getElementById("additional_details_body").innerHTML += xmlResponse;
                
                if(isAdmin) {
                    dataAdminDiv = document.createElement("div");
                    dataAdminDiv.setAttribute("id", "additional_details_admin_data");
                    dataAdminDiv.innerHTML = '<p><a class="addItemLink" onclick="addGalleryItem()" title="Add"><img src="images/application_form_add.png" width="16" height="16" alt="Add" /> Add Photo</a></p>';
                    dataAdminDiv.innerHTML += '<div style="visibility: hidden;" id="add_gallery_item_form"><label>Project:</label><select id="gallery_projects_select" name="gallery_projects_select" onchange="getGalleryProjectPhotos();"></select><div id="gallery_project_images" style="visibility: hidden;">Images</div></div>';
                    document.getElementById("additional_details").appendChild(dataAdminDiv);
                }
				initSlideshow();
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

/*
 * Brings up the options to add a Gallery Item
 */
function addGalleryItem() {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            $('add_gallery_item_form').style.visibility = 'visible';
            $('gallery_projects_select').options.length = 0;
            $('gallery_projects_select').options[0] = new Option('Downloading list of projects...','0');
            xmlHttp.open("POST", "includes/ajax/gallery.ajax", true);
            xmlHttp.onreadystatechange = handleGalleryProjectList;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("getGalleryProjects") + "&entityid=" + encodeURI('2') + "&menuReference=" + encodeURI('menu_2'));
        } catch(e) {
            alert("addGalleryItem() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("addGalleryItem()", 1);
    }
}

/*
 * Handles the return of the list of projects for the gallery
 */
function handleGalleryProjectList() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseXML;
                xmlRoot = xmlResponse.documentElement;
                entityMasterIdArray = xmlRoot.getElementsByTagName("entityMasterId");
                entityLevelArray = xmlRoot.getElementsByTagName("entityLevel");
                
                // Clear the select box
                $('gallery_projects_select').options.length = 0;
                $('gallery_projects_select').options[0] = new Option('Please select project...','0');
                
                // Fill the select box with the project listings
                for(var i=0; i<entityMasterIdArray.length; i++) {
                    $('gallery_projects_select').options[i+1] = new Option(entityLevelArray.item(i).firstChild.data,entityMasterIdArray.item(i).firstChild.data);
                }
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 *
 */
function getGalleryProjectPhotos() {
    var project_id = $('gallery_projects_select').options[$('gallery_projects_select').selectedIndex].value;
    $('gallery_project_images').style.visibility = 'visible';
    if(project_id > 0) {
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
            try {
                $('gallery_project_images').innerHTML = '<p>Downloading Project\'s Images</p>';
                xmlHttp.open("POST", "includes/ajax/projectPhotos.ajax", true);
                xmlHttp.onreadystatechange = handleGetGalleryProjectPhotos;
                xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xmlHttp.send("request=" + encodeURI("getGalleryPhotosData") + "&project_id=" + encodeURI(project_id));
            } catch(e) {
                alert("getGalleryProjectPhotos() Can't connect to the server:\n" + e.toString());
            }
        } else {
            setTimeout("getGalleryProjectPhotos()", 1);
        }
    } else {
        $('gallery_project_images').innerHTML = '';
    }
}

/*
 * NORMAL RETURN
 */
function handleGetGalleryProjectPhotos() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                $('gallery_project_images').innerHTML = xmlResponse;
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * Sends details of the selected photo to the database
 */
function sendNewGalleryItem(project_id, photo_id) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            $('gallery_project_images').style.visibility = 'hidden';
            $('add_gallery_item_form').style.visibility = 'hidden';
            xmlHttp.open("POST", "includes/ajax/gallery.ajax", true);
            xmlHttp.onreadystatechange = handleSendNewGalleryItem;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("addGalleryItem") + "&project_id=" + encodeURI(project_id) + "&photo_id=" + encodeURI(photo_id));
        } catch(e) {
            alert("sendNewGalleryItem() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("sendNewGalleryItem('" + project_id + "', '" + photo_id + "')", 1);
    }
}

/*
 * Handles the return of sendNewGalleryItem
 */
function handleSendNewGalleryItem() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                setTimeout('loadEntityPage("7", "")', 1);  // refresh the Gallery Data
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * Deletes the Gallery Item
 */
function deleteGalleryItem(photo_id) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            $('imgContainer').removeChild($('gallery_item_' + photo_id));
            xmlHttp.open("POST", "includes/ajax/gallery.ajax", true);
            xmlHttp.onreadystatechange = handleXMLHttpReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("deleteGalleryItem") + "&photo_id=" + encodeURI(photo_id));
        } catch(e) {
            alert("deleteGalleryItem() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("deleteGalleryItem('" + photo_id + "')", 1);
    }
}

/*
 * Handle the response of the reqested Contact Us data from the server.
 */
function handleContactUsData() {
	
	var map = null;
	var geocoder = null;

    /*
     * Initialise Google Maps
     */
	function google_maps_initialise() {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("google_map_canvas"));
			map.setCenter(new GLatLng(-27.293689, 133.066406), 3);  // Co-ordinates for map of Australia
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			geocoder = new GClientGeocoder();
		}
	}

    /*
     * Show the address given in the 'address' argument
     */
	function showAddress(address) {
		if (geocoder) {
			geocoder.getLatLng(
				address,
				function(point) {
					if (!point) {
						alert(address + " not found");
					} else {
						map.setCenter(point, 15);
						var marker = new GMarker(point);
						map.addOverlay(marker);
					}
				}
			);
		}
	}
	
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				var xmlResponse = xmlHttp.responseXML;
				xmlRoot = xmlResponse.documentElement;
				physicalAddressArray = xmlRoot.getElementsByTagName("PHYSICAL_ADDRESS");
				physicalSuburbArray = xmlRoot.getElementsByTagName("PHYSICAL_SUBURB");
				physicalStateArray = xmlRoot.getElementsByTagName("PHYSICAL_STATE");
				physicalPostcodeArray = xmlRoot.getElementsByTagName("PHYSICAL_POSTCODE");
				physicalCountryArray = xmlRoot.getElementsByTagName("PHYSICAL_COUNTRY");
				postalAddressArray = xmlRoot.getElementsByTagName("POSTAL_ADDRESS");
				postalSuburbArray = xmlRoot.getElementsByTagName("POSTAL_SUBURB");
				postalStateArray = xmlRoot.getElementsByTagName("POSTAL_STATE");
				postalPostcodeArray = xmlRoot.getElementsByTagName("POSTAL_POSTCODE");
				postalCountryArray = xmlRoot.getElementsByTagName("POSTAL_COUNTRY");
				phoneArray = xmlRoot.getElementsByTagName("PHONE");
				faxArray = xmlRoot.getElementsByTagName("FAX");
				emailArray = xmlRoot.getElementsByTagName("EMAIL");
				
				contactUsPageContent = '<div id="contactDetail">' +
					'<table id="tblContact">' +
				    	'<tbody>' +
							'<tr>' +
				        		'<td class="contactTblHeading">Address:</td>' +
				        		'<td><span id="PHYSICAL_ADDRESS_ROW"><span id="PHYSICAL_ADDRESS">' + physicalAddressArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'PHYSICAL_ADDRESS\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span></td>' +
                            '</tr>' +
				    		'<tr>' +
				        		'<td class="contactTblHeading"></td>' +
				        		'<td><span id="PHYSICAL_SUBURB_ROW"><span id="PHYSICAL_SUBURB">' + physicalSuburbArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'PHYSICAL_SUBURB\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span> <span id="PHYSICAL_STATE_ROW"><span id="PHYSICAL_STATE">' + physicalStateArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'PHYSICAL_STATE\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span> <span id="PHYSICAL_POSTCODE_ROW"><span id="PHYSICAL_POSTCODE">' + physicalPostcodeArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'PHYSICAL_POSTCODE\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span></td>' +
				        	'</tr>' +
							'<tr>' +
				        		'<td class="contactTblHeading"></td>' +
				        		'<td><span id="PHYSICAL_COUNTRY_ROW"><span id="PHYSICAL_COUNTRY">' + physicalCountryArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'PHYSICAL_COUNTRY\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span></td>' +
				        	'</tr>' +
							'<tr>' +
				        		'<td class="contactTblHeading">Mail Address:</td>' +
				        		'<td><span id="POSTAL_ADDRESS_ROW"><span id="POSTAL_ADDRESS">' + postalAddressArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'POSTAL_ADDRESS\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span></td>' +
				        	'</tr>' +
				    		'<tr>' +
				        		'<td class="contactTblHeading"></td>' +
				        		'<td><span id="POSTAL_SUBURB_ROW"><span id="POSTAL_SUBURB">' + postalSuburbArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'POSTAL_SUBURB\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span> <span id="POSTAL_STATE_ROW"><span id="POSTAL_STATE">' + postalStateArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'POSTAL_STATE\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span> <span id="POSTAL_POSTCODE_ROW"><span id="POSTAL_POSTCODE">' + postalPostcodeArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'POSTAL_POSTCODE\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span></td>' +
				        	'</tr>' +
							'<tr>' +
				        		'<td class="contactTblHeading"></td>' +
				        		'<td><span id="POSTAL_COUNTRY_ROW"><span id="POSTAL_COUNTRY">' + postalCountryArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'POSTAL_COUNTRY\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span></td>' +
				        	'</tr>' +
				    		'<tr>' +
				        		'<td class="contactTblHeading">Phone:</td>' +
				        		'<td><span id="PHONE_ROW"><span id="PHONE">' + phoneArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'PHONE\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span></td>' +
				        	'</tr>' +
				    		'<tr>' +
				        		'<td class="contactTblHeading">Fax:</td>' +
				        		'<td><span id="FAX_ROW"><span id="FAX">' + faxArray.item(0).firstChild.data + '</span>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="editContactItem(\'FAX\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span></td>' +
				        	'</tr>' +
							'<tr>' +
				        		'<td class="contactTblHeading">Email:</td>' +
				        		'<td><span id="EMAIL_ROW"><a href="mailto:' + emailArray.item(0).firstChild.data + '"><span id="EMAIL">' + emailArray.item(0).firstChild.data + '</span></a>';
                                if(isAdmin) {
                                    contactUsPageContent += ' <a onclick="alert(\'Warning: Changing this value will change the address the email form (to the right) will send the email to.\');editContactItem(\'EMAIL\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                                }
                contactUsPageContent += '</span></td>' +
				        	'</tr>' +
				    	'</tbody>' +
					'</table>' +
				    '<div id="google_map_canvas" style="width: 290px; height: 160px"></div>' +
				'</div>' +
				'<div id="contactForm">' +
				    '<form id="fmContactUs" name="contactUs" action="" onsubmit="sendContactUsEmail();return false;" method="post">' +
						'<input type="hidden" id="sendTo" name="sendTo" value="' + emailArray.item(0).firstChild.data + '" />' +
				    	'<label>Name</label><input class="contactUsTxtfld" id="senderName" name="senderName" type="text">' +
				    	'<label>Email</label><input class="contactUsTxtfld" id="senderEmail" name="senderEmail" type="text">' +
				    	'<label>Subject</label><input class="contactUsTxtfld" id="senderSubject" name="senderSubject" type="text">' +
				    	'<label>How did you hear about us</label>' +
				        '<select id="hearFrom" name="hearFrom">' +
				            '<option value="referral">Referral</option>' +
				            '<option value="google">Google</option>' +
				            '<option value="yahoo">Yahoo</option>' +
				            '<option value="ninemsn">Ninemsn</option>' +
				            '<option value="yellowPagesOnline">Yellow Pages Online</option>' +
				            '<option value="sensis">Sensis</option>' +
				            '<option value="streetSign">Street sign</option>' +
				            '<option value="clientLink">Link from client website</option>' +
				            '<option value="other">Other</option>' +
				        '</select>' +
				    	'<label>Message</label>' +
				        '<textarea id="senderMessage" name="senderMessage"></textarea>' +
				    	'<p class="infoBx"></p>' +
				        '<input class="contactUsBtn" value="send" name="send" type="submit">' +
				    '</form>' +
				'</div>' +
				'<br class="clear"></div>';
				document.getElementById("additional_details_body").innerHTML = contactUsPageContent;
	
				window.addEvent('domready', function() {
					google_maps_initialise();
				});
	
				window.addEvent('onunload', function() {
					GUnload();
				});

				window.addEvent('domready', function() {
					showAddress(physicalAddressArray.item(0).firstChild.data + ', ' + physicalSuburbArray.item(0).firstChild.data + ', ' + physicalStateArray.item(0).firstChild.data + ', ' + physicalPostcodeArray.item(0).firstChild.data + ', ' + physicalCountryArray.item(0).firstChild.data);
				});
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

/*
 * Edit a field on the Contact Us page
 */
function editContactItem(contact_us_reference) {
    oldContent = $(contact_us_reference).innerHTML;
    newContent = '<input type="text" id="' + contact_us_reference + '_text" name="' + contact_us_reference + '_text" value="' + oldContent + '" /> <input onclick="saveContactInfo(\'' + contact_us_reference + '\')" type="submit" id="' + contact_us_reference + '_submit" name="' + contact_us_reference + '_submit" value="Edit" />';
    $(contact_us_reference + '_ROW').innerHTML = newContent;
}

/*
 * Sends the new contact information to the server to save
 */
function saveContactInfo(contact_us_reference) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            newContactValue = $(contact_us_reference + '_text').value;
            // Add the anchor for the email information
            if(contact_us_reference != 'EMAIL') {
                $(contact_us_reference + '_ROW').innerHTML = '<span id="' + contact_us_reference + '">' + newContactValue + '</span>';
            } else {
                $(contact_us_reference + '_ROW').innerHTML = '<a href="mailto:' + newContactValue + '"><span id="' + contact_us_reference + '">' + newContactValue + '</span></a>';
            }
            $(contact_us_reference + '_ROW').innerHTML += ' <a onclick="editContactItem(\'' + contact_us_reference + '\')" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit"></a>';
                        
            xmlHttp.open("POST", "includes/ajax/contactus.ajax", true);
            xmlHttp.onreadystatechange = handleXMLHttpReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURIComponent("saveContactInfo") + "&contact_us_reference=" + encodeURIComponent(contact_us_reference) + "&newContactValue=" + encodeURIComponent(newContactValue));
        } catch(e) {
            alert("saveContactInfo() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("saveContactInfo('" + contact_us_reference + "')", 1);
    }
}

/*
 * Sends the contact form details to the server to email
 */
function sendContactUsEmail() {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			sendTo = $('sendTo').value;
			senderName = $('senderName').value;
			senderEmail = $('senderEmail').value;
			senderSubject = $('senderSubject').value;
			hearFrom = $('hearFrom').value;
			senderMessage = $('senderMessage').value;
			
			xmlHttp.open("POST", "includes/ajax/contactus.ajax", true);
			xmlHttp.onreadystatechange = handleSendContactUsEmail;
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttp.send("request=" + encodeURIComponent("sendEmail") + "&sendTo=" + encodeURIComponent(sendTo) + "&senderName=" + encodeURIComponent(senderName) + "&senderEmail=" + encodeURIComponent(senderEmail) + "&senderSubject=" + encodeURIComponent(senderSubject) + "&hearFrom=" + encodeURIComponent(hearFrom) + "&senderMessage=" + encodeURIComponent(senderMessage));
			
			$('contactForm').innerHTML = "... sending email";
		} catch(e) {
			alert("sendContactUsEmail() Can't connect to the server:\n" + e.toString());
		}
	} else {
		setTimeout("sendContactUsEmail()", 1);
	}
}

/*
 * NORMAL HANDLER
 */
function handleSendContactUsEmail() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				var xmlResponse = xmlHttp.responseText;
				$('contactForm').innerHTML = xmlResponse;
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

/*
 * Handles the response of the requested data from the server
 */
function handleGetData() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				var xmlResponse = xmlHttp.responseXML;
				xmlRoot = xmlResponse.documentElement;
				dataArray = xmlRoot.getElementsByTagName("data");
				entityIdArray = xmlRoot.getElementsByTagName("entityId");
				subCategoryIdArray = xmlRoot.getElementsByTagName("subCategoryId");
				
				entity_id = entityIdArray.item(0).firstChild.data;
				sub_category_id = subCategoryIdArray.item(0).firstChild.data;
				
				dataDiv = document.createElement("div");
				dataDiv.setAttribute("id", "additional_details_data");
				
				if(dataArray.length > 0) {
					var data = '';
					try {
						data = dataArray.item(0).firstChild.data;
					} catch(e) {
						
					}
					//@michaelmocan: removed decodeURI from the line below - need not decode as it's not being encoded on the way down.
					dataDiv.innerHTML = stripslashes(data);
				}
				
				var defaultDataDiv = document.createElement('div');
				defaultDataDiv.setAttribute('id', 'defaultDataDiv');
				defaultDataDiv.appendChild(dataDiv);
				$('additional_details_body').appendChild(defaultDataDiv);
				
				if(isAdmin) {
                    adminDiv = $('additional_details_admin_data');
                    if(adminDiv != null) {
                        adminDiv.innerHTML = '';
                        $("additional_details").removeChild(adminDiv);
                    }
					dataAdminDiv = document.createElement("div");
					dataAdminDiv.setAttribute("id", "additional_details_admin_data");
					dataAdminDiv.innerHTML = '<p><a onclick="editData(\'' + entity_id + '\', \'' + sub_category_id + '\');" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit" /></a></p>';
					$("additional_details").appendChild(dataAdminDiv);
				}
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

function handleProjectConcept() {
	if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseXML;
				xmlRoot = xmlResponse.documentElement;
				dataArray = xmlRoot.getElementsByTagName("data");
				entityIdArray = xmlRoot.getElementsByTagName("entityId");
				subCategoryIdArray = xmlRoot.getElementsByTagName("subCategoryId");
				
				entity_id = entityIdArray.item(0).firstChild.data;
				sub_category_id = subCategoryIdArray.item(0).firstChild.data;
				
				dataDiv = document.createElement("div");
				dataDiv.setAttribute("id", "additional_details_data");
				
				if(dataArray.length > 0) {
					var data = '';
					try {
						data = dataArray.item(0).firstChild.data;
					} catch(e) {
						
					}
					//@michaelmocan: removed decodeURI from the line below - need not decode as it's not being encoded on the way down.
					dataDiv.innerHTML = stripslashes(data);
				}
				
				var projectConceptDiv = document.createElement('div');
				projectConceptDiv.setAttribute('id', 'projectConceptDiv');
				projectConceptDiv.appendChild(dataDiv);
				$('additional_details_body').appendChild(projectConceptDiv);
				
				if(isAdmin) {
                    adminDiv = $('additional_details_admin_data');
                    if(adminDiv != null) {
                        adminDiv.innerHTML = '';
                        $("additional_details").removeChild(adminDiv);
                    }
					dataAdminDiv = document.createElement("div");
					dataAdminDiv.setAttribute("id", "additional_details_admin_data");
					dataAdminDiv.innerHTML = '<p><a onclick="editData(\'' + entity_id + '\', \'' + sub_category_id + '\');" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit" /></a></p>';
					$("additional_details").appendChild(dataAdminDiv);
				}
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 *
 */
function handlePhotosData() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
                additionalDetailsAdminData = $('additional_details_admin_data');
                if(additionalDetailsAdminData != null) {
                    $('additional_details').removeChild(additionalDetailsAdminData);
                }
				var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(":|||:")
                var project_id = xmlResponse[0];
				$('additional_details_body').innerHTML += xmlResponse[1];
                
                if(isAdmin) {
                    dataAdminDiv = document.createElement("div");
                    dataAdminDiv.setAttribute("id", "additional_details_admin_data");
					/*var htmlContent;
					
					htmlContent = '<div id="add_photo_form" class="pjPhotoBxAdmin">';
						htmlContent += "<h1>Add New Photo</h1>"
                        htmlContent += '<form id="add_project_photo_form" action="" enctype="multipart/form-data" method="post" onsubmit="false;">';
                            htmlContent += '<fieldset class="flash" id="fsUploadProgress"><legend>Upload Queue</legend></fieldset>';
                            htmlContent += '<div id="divStatus">0 Files Uploaded</div>';
                            htmlContent += '<label>Upload Photo:</label><input type="button" class="pjPhotoSubmitBtn" id="btnBrowse" name="btnBrowse" value="Browse" onclick="fileBrowse.apply(swfu);" /><input type="hidden" class="txtFldHidden" id="txtFileName" name="txtFileName" value="" /><br class="clear" />';
                            htmlContent += '<label>Copyright:</label><input type="text" id="photo_copyright" name="photo_copyright" value="" /><br class="clear" />';
                            htmlContent += '<input type="hidden" class="txtFldHidden" id="project_id" name="project_id" value="' + project_id + '" /><input type="submit" onclick="doSubmit()" class="pjPhotoSubmitBtn" id="photo_submit" name="photo_submit" value="Upload" />';
                        htmlContent += '</form>';
                    htmlContent += '</div>';
					
					dataAdminDiv.innerHTML = htmlContent;*/
					
                    /*dataAdminDiv.innerHTML = '<div id="add_photo_form">';
                        dataAdminDiv.innerHTML += '<form id="add_project_photo_form" action="" enctype="multipart/form-data" method="post" onsubmit="false;">';
                            dataAdminDiv.innerHTML += '<fieldset class="flash" id="fsUploadProgress"><legend>Upload Queue</legend></fieldset>';
                            dataAdminDiv.innerHTML += '<div id="divStatus">0 Files Uploaded</div>';
                            dataAdminDiv.innerHTML += '<div id="prjPhotoBrowseBtn"><span>Upload Photo:</span><input type="button" id="btnBrowse" name="btnBrowse" value="Browse" onclick="fileBrowse.apply(swfu);" /><input type="hidden" id="txtFileName" name="txtFileName" value="" /><br class="clear" /></div>';
                            dataAdminDiv.innerHTML += '<div id="prjPhotoCopyrightFld"><span>Copyright:</span><input type="text" id="photo_copyright" name="photo_copyright" value="" /><br class="clear" /></div>';
                            dataAdminDiv.innerHTML += '<div id="prjPhotoSubmit"><input type="hidden" id="project_id" name="project_id" value="' + project_id + '" /><input type="submit" onclick="doSubmit()" id="photo_submit" name="photo_submit" value="Upload" /></div>';
                        dataAdminDiv.innerHTML += '</form>';
                    dataAdminDiv.innerHTML += '</div>';*/
					dataAdminDiv.innerHTML = '<iframe src="project_photo_frame.php?project_id=' + project_id + '&sub_category=2" id="" name="" frameborder="0" scrolling="auto" width="630px" height="200px"></iframe>';
                    document.getElementById("additional_details").appendChild(dataAdminDiv);
                }
                // Add events to the Article Items
                window.addEvent('domready', function() {
                    sbxStartScan(); //scan the content for slimbox, function in slimbox.js
                    initSlideshow();
                    if(isAdmin) {
                        //initProjectPhotoSWFUpload(project_id);
                    }
                });
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

/*
 * Deletes the specified photo
 */
function delete_project_photo(photo_id) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            $('project_photo_' + photo_id).innerHTML = ''; // Remove it from the page

            xmlHttp.open("POST", "includes/ajax/projectPhotos.ajax", true);
            xmlHttp.onreadystatechange = handleXMLHttpReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("deleteProjectPhoto") + "&photo_id=" + encodeURI(photo_id));
        } catch(e) {
            alert("delete_project_photo() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("delete_project_photo('" + photo_id + "')", 1);
    }
}

/*
 * NORMAL HANDLER
 */
function handleProjectData() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				var xmlResponse = xmlHttp.responseText;
				document.getElementById("additional_details_body").innerHTML += xmlResponse;
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

/*
 * Changes the project data field to a edit text field to allow editing
 */
function editProjectDataItem(project_data_id) {
    $('project_data_' + project_data_id + '_options').style.visibility = 'hidden';
    var oldProjectDataValue = $('project_data_' + project_data_id).innerHTML;
    $('project_data_' + project_data_id).innerHTML = '<input type="text" id="project_data_' + project_data_id + '_text" name="project_data_' + project_data_id + '_text" value="' + oldProjectDataValue + '" /> <input type="button" class="pjDataAddBtn" onclick="updateProjectData(\'' + project_data_id + '\')" id="project_data_' + project_data_id + '_submit" name="project_data_' + project_data_id + '_submit" value="Edit" />';
}

/*
 * Sends the updated project data to the server
 */
function updateProjectData(project_data_id) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            var newProjectDataValue = $('project_data_' + project_data_id + '_text').value;
            $('project_data_' + project_data_id + '_options').style.visibility = 'visible';
            $('project_data_' + project_data_id).innerHTML = newProjectDataValue;
    
            xmlHttp.open("POST", "includes/ajax/projectData.ajax", true);
            xmlHttp.onreadystatechange = handleXMLHttpReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURIComponent("updateProjectData") + "&project_data_id=" + encodeURIComponent(project_data_id) + "&project_data_value=" + encodeURIComponent(newProjectDataValue));
        } catch(e) {
            alert("updateProjectData() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("updateProjectData('" + project_data_id + "')", 1);
    }
}

/*
 * Request a confirmation from the user to delete the project data item
 */
function deleteProjectDataItem(project_data_id) {
    if(confirm("Are you sure you want to delete this item?")) {
        confirmedDeleteProjectDataItem(project_data_id);
    }
}

/*
 * Delete the specified project data item
 */
function confirmedDeleteProjectDataItem(project_data_id) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            $('project_data_' + project_data_id + '_row').innerHTML = '';
            xmlHttp.open("POST", "includes/ajax/projectData.ajax", true);
            xmlHttp.onreadystatechange = handleXMLHttpReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURIComponent("deleteProjectData") + "&project_data_id=" + encodeURIComponent(project_data_id));
        } catch(e) {
            alert("confirmedDeleteProjectDataItem() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("confirmedDeleteProjectDataItem('" + project_data_id + "')", 1);
    }
}

/*
 * Adds a new data type for the current project
 */
function addProjectData(project_id, data_type_type) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            if(data_type_type == "project") {
                var data_type_id = $('project_details_select').value;
                var project_data_value = $('project_details_text').value;
				var project_new_datatype = $('project_details_new_datatype').value;
            } else {
                var data_type_id = $('project_team_select').value;
                var project_data_value = $('project_team_text').value;
				var project_new_datatype = $('project_team_new_datatype').value;
            }
            
            xmlHttp.open("POST", "includes/ajax/projectData.ajax", true);
            xmlHttp.onreadystatechange = handleAddProjectData;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURIComponent("addProjectData") + "&project_id=" + encodeURIComponent(project_id) + "&data_type_type=" + encodeURIComponent(data_type_type) + "&data_type_id=" + encodeURIComponent(data_type_id) + "&project_data_value=" + encodeURIComponent(project_data_value) + "&project_new_datatype=" + encodeURIComponent(project_new_datatype) + "&data_type_type=" + encodeURIComponent(data_type_type));
            
            $('project_details_select').selectedIndex = '0';
            $('project_details_text').value = '';
        } catch(e) {
            alert("addProjectData() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("addProjectData('" + project_id + "', '" + data_type_type + "')", 1);
    }
}

/*
 * Handles the return of addProjectData
 */
function handleAddProjectData() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(":|||:");
                setTimeout("getData(" + xmlResponse[0] + ", '3', 'project')", 10);
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * 
 */
function handleProjectDrawings() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(":|||:");
				document.getElementById("additional_details_body").innerHTML += xmlResponse[1];
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

/**
 * 
 * @param {Object} project_drawing_id
 */
function editProjectDrawing(project_drawing_id) {
	document.getElementById('project_drawing_iframe').src = 'project_drawings_frame.php?project_drawing_id=' + project_drawing_id;
}

/*
 *
 */
function deleteProjectDrawing(project_drawing_id) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            $('project_drawing_' + project_drawing_id).innerHTML = '';
            
            xmlHttp.open("POST", "includes/ajax/projectDrawings.ajax", true);
            xmlHttp.onreadystatechange = handleXMLHttpReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURIComponent("deleteProjectDrawing") + "&project_drawing_id=" + encodeURIComponent(project_drawing_id));
        } catch(e) {
            alert("deleteProjectDrawing() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("deleteProjectDrawing('" + project_drawing_id + "')", 1);
    }
}

/*
 * Handles the data return for project videos
 */
function handleProjectVideos() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			try {
				var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(":|||:");
				document.getElementById("additional_details_body").innerHTML += xmlResponse[1];
                
                /*window.addEvent('domready', function() {
					if(isAdmin) {
                    	initProjectVideoSWFUpload(xmlResponse[0]);
					}
                });*/
			} catch(e) {
				alert("Error reading the response: " + e.toString());
			}
		} else {
			alert("There was a problem accessing the server: " + xmlHttp.statusText);
		}
	}
}

/**
 * 
 * @param {Object} project_video_id
 */
function editProjectVideo(project_video_id) {
	document.getElementById('project_video_iframe').src = 'project_videos_frame.php?project_video_id=' + project_video_id;
}

/**
 * 
 * @param {Object} project_video_id
 */
function deleteProjectVideo(project_video_id) {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            if (confirm("Are you sure you want to delete this video?")) {
				$('project_video_' + project_video_id).dispose();
				
				xmlHttp.open("POST", "includes/ajax/projectVideos.ajax", true);
				xmlHttp.onreadystatechange = handleXMLHttpReturn;
				xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				xmlHttp.send("request=" + encodeURIComponent("deleteProjectVideo") + "&project_video_id=" + encodeURIComponent(project_video_id));
			}
        } catch(e) {
            alert("deleteProjectVideo() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("deleteProjectVideo('" + project_video_id + "')", 1);
    }
}

/*
 * 
 */
function handleProjectDatasheet() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(":|||:");
                document.getElementById("additional_details_body").innerHTML += xmlResponse[3];
                window.addEvent('domready', function() {
                    initPDFDatasheetSWFUpload(xmlResponse[0], xmlResponse[1], xmlResponse[2]);
                });
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * NORMAL HANDLER
 */
function handlePeopleAbout() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseXML;
				xmlRoot = xmlResponse.documentElement;
				dataArray = xmlRoot.getElementsByTagName("data");
				entityIdArray = xmlRoot.getElementsByTagName("entityId");
				subCategoryIdArray = xmlRoot.getElementsByTagName("subCategoryId");
				
				entity_id = entityIdArray.item(0).firstChild.data;
				sub_category_id = subCategoryIdArray.item(0).firstChild.data;
				
				dataDiv = document.createElement("div");
				dataDiv.setAttribute("id", "additional_details_data");
				
				if(dataArray.length > 0) {
					var data = '';
					try {
						data = dataArray.item(0).firstChild.data;
					} catch(e) {
						
					}
					dataDiv.innerHTML = decodeURI(stripslashes(data));
				}
				
				var peopleAboutDiv = document.createElement('div');
				peopleAboutDiv.setAttribute('id', 'peopleAboutDiv');
				peopleAboutDiv.appendChild(dataDiv);
				$('additional_details_body').appendChild(peopleAboutDiv);
				
				if(isAdmin) {
                    adminDiv = $('additional_details_admin_data');
                    if(adminDiv != null) {
                        adminDiv.innerHTML = '';
                        $("additional_details").removeChild(adminDiv);
                    }
					dataAdminDiv = document.createElement("div");
					dataAdminDiv.setAttribute("id", "additional_details_admin_data");
					dataAdminDiv.innerHTML = '<p><a onclick="editData(\'' + entity_id + '\', \'' + sub_category_id + '\');" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit" /></a></p>';
					$("additional_details").appendChild(dataAdminDiv);
				}
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * NORMAL HANDLER
 */
function handlePeopleCV() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                document.getElementById("additional_details_body").innerHTML += xmlResponse;
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

function handlePeopleOther() {
	if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseXML;
				xmlRoot = xmlResponse.documentElement;
				dataArray = xmlRoot.getElementsByTagName("data");
				entityIdArray = xmlRoot.getElementsByTagName("entityId");
				subCategoryIdArray = xmlRoot.getElementsByTagName("subCategoryId");
				
				entity_id = entityIdArray.item(0).firstChild.data;
				sub_category_id = subCategoryIdArray.item(0).firstChild.data;
				
				dataDiv = document.createElement("div");
				dataDiv.setAttribute("id", "additional_details_data");
				
				if(dataArray.length > 0) {
					var data = '';
					try {
						data = dataArray.item(0).firstChild.data;
					} catch(e) {
						
					}
					dataDiv.innerHTML = decodeURI(stripslashes(data));
				}
				
				var peopleOtherDiv = document.createElement('div');
				peopleOtherDiv.setAttribute('id', 'peopleOtherDiv');
				peopleOtherDiv.appendChild(dataDiv);
				$('additional_details_body').appendChild(peopleOtherDiv);
				
				if(isAdmin) {
                    adminDiv = $('additional_details_admin_data');
                    if(adminDiv != null) {
                        adminDiv.innerHTML = '';
                        $("additional_details").removeChild(adminDiv);
                    }
					dataAdminDiv = document.createElement("div");
					dataAdminDiv.setAttribute("id", "additional_details_admin_data");
					dataAdminDiv.innerHTML = '<p><a onclick="editData(\'' + entity_id + '\', \'' + sub_category_id + '\');" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit" /></a></p>';
					$("additional_details").appendChild(dataAdminDiv);
				}
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * Behaviours for article items to show the description of the article item when the user clicks on the title
 */
function titlesBehaviours(entity_master_id, project_id) {
    // Had to put a try catch on this as this function is in some cases called twice when
    // an article is edited and refreshed.
    try {
		
	    $$('h1.itemHeading').each(function(item) {
			var articleId = item.getNext('.articleId').innerHTML;
			item.removeEvents('click');
			// Add Click Event to the Title
		    item.addEvent('click', function(e) {
				e.stopPropagation();
				highlightButton("additional_details_body", item);
				// Do not do the following on People / Project Sub Category Articles
				if (entity_master_id != 'cv' && entity_master_id != '13' && entity_master_id != '14' && entity_master_id != '15' && entity_master_id != '19' && entity_master_id != '20' && entity_master_id != '21' && project_id == '0') {
					resetMenus(true);
					if (isAdmin) {
						showArticleRelationshipButtons(articleId);
					}
					getAllRelatedArticleEntities(articleId);
				}
			});
			
	    });
		
		var myAccordion = new Accordion($$('h1.itemHeading'), $$('.itemLongDescWrapper'), {
			display: -1
		});
    } catch(e) {
    }
}

/*
 * MUST BE AN ADMINISTRATOR!
 * Edit Ordinary Data
 */
function editData(entity_id, sub_category_id) {
	var originalData = '';
	if ($('additional_details_data')) {
		originalData = $("additional_details_data").innerHTML;
		originalData = stripslashes(originalData);
	}
    
	$("additional_details_data").innerHTML = '<textarea id="additional_details_data_textarea" name="additional_details_data_textarea" class="textarea_description">' + br2nl(originalData) + '</textarea>';
	$("additional_details_admin_data").innerHTML = '<input type="button" onclick="saveData(\'' + entity_id + '\', \'' + sub_category_id + '\');" id="additional_details_data_save" name="additional_details_data_save" value="Save" />';
	initiateTinyMCE('additional_details_data_textarea');
}

/*
 * MUST BE AN ADMINISTRATOR!
 * Sends the data to the server to save.
 */
function saveData(entity_id, sub_category_id) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            tinyMCE.triggerSave(false,true);
            tiny_mce_editor = tinyMCE.get('additional_details_data_textarea');
            newData = tiny_mce_editor.getContent();
            tinyMCE.execCommand( 'mceRemoveControl', false, 'additional_details_data_textarea' );
            //var newData = nl2br($('additional_details_data_textarea').value);
            $("additional_details_data").innerHTML = newData;
            $("additional_details_admin_data").innerHTML = '<p><a onclick="editData(\'' + entity_id + '\', \'' + sub_category_id + '\');" title="Edit"><img src="images/application_form_edit.png" width="16" height="16" alt="Edit" /></a></p>';

            xmlHttp.open("POST", "includes/ajax/data.ajax", true);
            xmlHttp.onreadystatechange = handleSaveData;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("saveData") + "&entityid=" + encodeURI(entity_id) + "&subcategoryid=" + encodeURI(sub_category_id) + "&data=" + escape(newData));
        } catch(e) {
            alert("saveData() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("saveData(" + entity_id + ", " + sub_category_id + ")", 1);
    }
}

/*
 * Handles the normal data save request
 * This function could be bunched with others as it has no special features.
 * NORMAL HANDLER
 */                                                                                                                                     
function handleSaveData() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseXML;
                xmlRoot = xmlResponse.documentElement;
                dataSaveResponse = xmlRoot.firstChild.data;
                if(!dataSaveResponse) {
                    alert("There was an error updating the database.");
                }
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

/*
 * MUST BE AN ADMINISTRATOR!
 * Edit Article Item
 */
function editArticleItem(article_item_id, article_item_date, article_order, article_item_heading, article_item_brief_overview, article_item_content, article_item_image_ids_array, article_item_thumbs_array, article_item_images_array, article_item_link_ids_array, article_item_links_url_array, article_item_links_title_array) {
	edit_article_item_content =	'<div class="itemYr"><label>Date:</label>' +
								'<span><input type="text" id="article_' + article_item_id + '_date" name="article_item_date" value="' + article_item_date + '" /></span><br />' +
								'Order: <br />' + 
								'<input type="text" id="article_' + article_item_id + '_order" name="article_' + article_item_id + '_order" value="' + article_order + '" /></div>' + 
							    '<div class="itemDesc">' +
							    	'<h1 class="itemHeading"><label>Heading:</label>' +
									'<input type="text" id="article_' + article_item_id + '_heading" name="article_item_heading" value="' + article_item_heading + '" /></h1>' +
									'<p class="itemShrtDesc"><label>Brief Overview:</label>' +
									'<input type="text" id="article_' + article_item_id + '_brief_overview" name="article_item_brief_overview" value="' + article_item_brief_overview + '" /></p>' +
									'<div class="itemLongDescWrapper">' +
							        	'<div class="itemLongDesc">' + 
											'<textarea id="article_' + article_item_id + '_content" name="article_item_content">' + article_item_content + '</textarea>' +
										'</div>' +
                                        '<input type="submit" onclick="saveArticleItem(\'' + article_item_id + '\')" id="article_submit" class="genericSubmitBtn" name="article_submit" value="Update" />' +
										'<div id="article_' + article_item_id + '_images" class="itemImages">';
										for(i=0; i<article_item_image_ids_array.length;i++) {
											article_id_image_id = 'article_image_' + article_item_id + '_' + article_item_image_ids_array[i];
											edit_article_item_content +=	'<span id="' + article_id_image_id + '"><a href="images/article_images/full_size/' + article_item_images_array[i] + '" title="' + article_item_heading + '" rel="lightbox[article_item_images_' + article_item_id + ']"><img class="itemImage" src="images/article_images/thumbnail/' + article_item_thumbs_array[i] + '" alt="' + article_item_heading + '" /></a><a class="removeImgBtn" onclick="deleteArticleItemImage(\'' + article_item_id + '\', \'' + article_item_image_ids_array[i] + '\')"><img src="images/application_form_delete.png" width="16" height="16" alt="Delete" /></a></span>';
										}
	edit_article_item_content +=		'</div>' +
										'<br class="clear" />' +
										'<h2>Upload Images:</h2>' +
										'<iframe src="article_photo_frame.php?article_id=' + article_item_id + '" width="630px" height="75px" frameborder="0"></iframe>' +
										'<div class="itemLinkAdmin">' +
											'<h2>Links:</h2>';
											for(i=0; i<article_item_link_ids_array.length;i++) {
												article_id_link_id = 'article_link_' + article_item_id + '_' + article_item_link_ids_array[i];
												edit_article_item_content += '<span id="' + article_id_link_id + '"><a href="' + article_item_links_url_array[i] + '" target="_blank">' + article_item_links_title_array[i] + '</a><a onclick="deleteArticleItemLink(\'' + article_item_id + '\', \'' + article_item_link_ids_array[i] + '\')"><img src="images/application_form_delete.png" width="16" height="16" alt="Delete" /></a></span>';
											}
	edit_article_item_content +=			'<h2>Add Link:</h2>' +
											'<label>Title:</label><input type="text" id="article_' + article_item_id + '_title_add_link" name="add_article_item_link_title" value="" />' +
											'<label>URL:</label><input type="text" id="article_' + article_item_id + '_url_add_link" name="add_article_item_link_url" value="" />' +
											'<input type="submit" class="genericSubmitBtn" onclick="addArticleItemLink(\'' + article_item_id + '\', \'article_' + article_item_id + '_title_add_link\', \'article_' + article_item_id + '_url_add_link\')" id="article_' + article_item_id + '_add_link_submit" name="add_article_item_link_submit" value="Add Link" />' +
										'</div>' +
									'</div>' +
							    '</div>' +
							    '<br class="clear" />';
	$('article_item_' + article_item_id).innerHTML = edit_article_item_content;
	
	initiateTinyMCE('article_' + article_item_id + '_content');
	window.addEvent('domready', function() {
		sbxStartScan(); //scan the content for slimbox, function in slimbox.js
		//initSWFUpload(news_item_id, news_item_date, news_item_heading, news_item_brief_overview, news_item_content, news_item_image_ids_array, news_item_thumbs_array, news_item_images_array, news_item_link_ids_array, news_item_links_url_array, news_item_links_title_array); //initiate SWFUpload
		initSWFUpload(article_item_id); //initiate SWFUpload
	});
}

/*
 * MUST BE AN ADMINISTRATOR
 * Saves the article to the server
 */
function saveArticleItem(article_item_id) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            articleDate = $('article_' + article_item_id + '_date').value;
			articleOrder = $('article_' + article_item_id + '_order').value;
            articleHeading = $('article_' + article_item_id + '_heading').value;
            articleBriefOverview = $('article_' + article_item_id + '_brief_overview').value;
            tinyMCE.triggerSave(false,true);
            tiny_mce_editor = tinyMCE.get('article_' + article_item_id + '_content');
            articleContent = tiny_mce_editor.getContent();
            tinyMCE.execCommand( 'mceRemoveControl', false, 'article_' + article_item_id + '_content');
            
            xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
            xmlHttp.onreadystatechange = handleSaveArticleItem;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("saveArticle") + "&article_item_id=" + encodeURI(article_item_id) + "&article_date=" + encodeURI(articleDate) + "&article_order=" + encodeURI(articleOrder) + "&article_heading=" + encodeURI(articleHeading) + "&article_brief_overview=" + encodeURI(articleBriefOverview) + "&article_content=" + escape(articleContent));
        } catch(e) {
            alert("saveArticleItem() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("saveArticleItem('" + article_item_id + "')", 1);
    }
}

/*
 * MUST BE AN ADMINISTRATOR
 * Handles the return of saving the article item.
 */
 function handleSaveArticleItem() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
				//resetDataSection();
				//resetMenus();
				window.addEvent('domready', function() {
					//loadRelatedEntities(global_current_menu_reference, global_entity_id, global_entity_name);
					//loadEntityPage(global_entity_id, global_sub_category_type);
					
					getData(global_entity_id, global_sub_category_id, global_sub_category_type, global_sub_category_button);
				});
                /*var xmlResponse = xmlHttp.responseText;
                // Split the response back into an array to get the article id and the article content.
                xmlResponse = xmlResponse.split(":|||:");
                $('article_item_' + xmlResponse[0]).innerHTML = xmlResponse[1];
                window.addEvent('domready', function() {
                    // Give the article the image slimbox behaviour again
                    sbxStartScan();
                    // Give the article title the open/close behaviour again
                    titlesBehaviours();
                });*/
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
 }
 
 /*
  * Deletes the article item.
  */
 function deleteArticle(article_item_id) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            if(confirm("Are you sure you want to delete this article?")) {
                xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
                xmlHttp.onreadystatechange = handleXMLHttpReturn;
                xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xmlHttp.send("request=" + encodeURI("deleteArticle") + "&article_item_id=" + encodeURI(article_item_id));
                $('article_item_' + article_item_id).innerHTML = '';
            }
        } catch(e) {
            alert("deleteArticle() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("deleteArticle('" + article_item_id + "')", 1);
    }
 }

/*
 * MUST BE AN ADMINISTRATOR
 * Add a link to the article
 */
function addArticleItemLink(article_item_id, article_link_title, article_link_url) {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			articleLinkTitle = $(article_link_title).value;
			articleLinkURL = $(article_link_url).value;
			$(article_link_title).value = '';
			$(article_link_url).value = '';
			
			xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
			xmlHttp.onreadystatechange = handleXMLHttpReturn;
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttp.send("request=" + encodeURI("addArticleItemLink") + "&article_id=" + encodeURI(article_item_id) + "&article_link_title=" + encodeURI(articleLinkTitle) + "&article_link_url=" + encodeURI(articleLinkURL));
		} catch(e) {
			alert("addArticleItemLink() Can't connect to the server:\n" + e.toString());
		}
	} else {
		setTimeout("addArticleItemLink('" + article_item_id + "', '" + article_link_title + "', '" + article_link_url + "')", 1);
	}
}

/*
 * Removes the Article Item Image from the DOM
 */
function deleteArticleItemImage(article_item_id, article_image_id) {
	article_id_image_id = 'article_image_' + article_item_id + '_' + article_image_id;
	
	var fadeOutImage = new Fx.Tween(article_id_image_id, {property: 'opacity', duration: 'long'});
	fadeOutImage.start(1,0).chain(function() {
		$(article_id_image_id).destroy();
	});
	
	deleteArticleItemImageFromDB(article_image_id);	
}

/*
 * Removes the Article Item Image from the Database
 */
function deleteArticleItemImageFromDB(article_image_id) {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
			xmlHttp.onreadystatechange = handleXMLHttpReturn;
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttp.send("request=" + encodeURI("deleteArticleItemImage") + "&article_image_id=" + encodeURI(article_image_id));
		} catch(e) {
			alert("deleteArticleItemImageFromDB() Can't connect to the server:\n" + e.toString());
		}
	} else {
		setTimeout("deleteArticleItemImageFromDB(" + article_image_id + ")", 1);
    }
}

/*
 * Removes the Article Item Link from the DOM
 */
function deleteArticleItemLink(article_item_id, article_item_link_id) {
	article_id_link_id = 'article_link_' + article_item_id + '_' + article_item_link_id;
	
	var fadeOutLink = new Fx.Tween(article_id_link_id, {property: 'opacity', duration: 'long'});
	fadeOutLink.start(1,0).chain(function() {
		$(article_id_link_id).destroy();
	});
	
	deleteArticleItemLinkFromDB(article_item_link_id);
}

/*
 * Removes the Article Item Link from the Database
 */
function deleteArticleItemLinkFromDB(article_item_link_id) {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			xmlHttp.open("POST", "includes/ajax/articles.ajax", true);
			xmlHttp.onreadystatechange = handleXMLHttpReturn;
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttp.send("request=" + encodeURI("deleteArticleItemLink") + "&article_item_link_id=" + encodeURI(article_item_link_id));
		} catch(e) {
			alert("deleteArticleItemLinkFromDB() Can't connect to the server:\n" + e.toString());
		}
	} else {
		setTimeout("deleteArticleItemLinkFromDB(" + article_item_link_id + ")", 1);
	}
}

/**
 * 
 */
function showArticleRelationshipButtons(article_id) {
	// Projects
    if($('projects_checklist_entities')) {
        var relatedButton = $('projects_checklist_entities');
    } else {
        var relatedButton = new Element ('a', {
			'id':'projects_checklist_entities'
		});
    }
	relatedButton.removeEvents();
	relatedButton.addEvent('click', function(event) {
		loadArticleEntitiesChecklist(article_id, 'projects', '2');
	});
    relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
    $('projects').appendChild(relatedButton);
	
	// Project Types
    if($('project_types_checklist_entities')) {
        var relatedButton = $('project_types_checklist_entities');
    } else {
        var relatedButton = new Element ('a', {
			'id':'project_types_checklist_entities'
		});
    }
	relatedButton.removeEvents();
	relatedButton.addEvent('click', function(event) {
		loadArticleEntitiesChecklist(article_id, 'project_types', '3');
	});
    relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
    $('project_types').appendChild(relatedButton);
    
    // People
    if($('people_checklist_entities')) {
        var relatedButton = $('people_checklist_entities');
    } else {
        var relatedButton = new Element ('a', {
			'id':'people_checklist_entities'
		});
    }
	relatedButton.removeEvents();
	relatedButton.addEvent('click', function(event) {
		loadArticleEntitiesChecklist(article_id, 'people', '4');
	});
    relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
    $('people').appendChild(relatedButton);
    
    // Date
    if($('date_checklist_entities')) {
        var relatedButton = $('date_checklist_entities');
    } else {
        var relatedButton = new Element ('a', {
			'id':'date_checklist_entities'
		});
    }
	relatedButton.removeEvents();
	relatedButton.addEvent('click', function(event) {
		loadArticleEntitiesChecklist(article_id, 'date', '5');
	});
    relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
    $('date').appendChild(relatedButton);
    
    // Location
    if($('location_checklist_entities')) {
        var relatedButton = $('location_checklist_entities');
    } else {
        var relatedButton = new Element ('a', {
			'id':'location_checklist_entities'
		});
    }
	relatedButton.removeEvents();
	relatedButton.addEvent('click', function(event) {
		loadArticleEntitiesChecklist(article_id, 'location', '6');
	});
    relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
    $('location').appendChild(relatedButton);
    
    // Ideas
    if($('ideas_checklist_entities')) {
        var relatedButton = $('ideas_checklist_entities');
    } else {
        var relatedButton = new Element ('a', {
			'id':'ideas_checklist_entities'
		});
    }
	relatedButton.removeEvents();
	relatedButton.addEvent('click', function(event) {
		loadArticleEntitiesChecklist(article_id, 'ideas', '7');
	});
    relatedButton.innerHTML = '<img src="images/link.png" class="linkBtn" title="link" />';
    $('ideas').appendChild(relatedButton);
}

/**
 * 
 * @param {Object} article_id
 * @param {Object} menu
 * @param {Object} parent_entity
 */
// function loadEntitiesChecklist(selected_menu, menu, parent_entity, current_entity, entity_value) {
function loadArticleEntitiesChecklist(article_id, menu, parent_entity) {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
			
            $('menu_' + parent_entity).innerHTML = '';
            relatedButton = $(menu + '_checklist_entities');
			relatedButton.removeEvents();
            relatedButton.addEvent('click', function(event) {
				event.stop();
				revertArticleEntitiesChecklist(article_id, menu, parent_entity);
			});

            // Get all the entities under the current menu
            xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
            xmlHttp.onreadystatechange = handleLoadRelatedEntitiesChecklist;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("getRelatedArticlesChecklist") + "&articleId=" + encodeURI(article_id) + "&masterid=" + encodeURI(parent_entity) + "&menuReference=" + encodeURI('menu_' + parent_entity));
			
        } catch(e) {
            alert("loadArticleEntitiesChecklist() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("loadArticleEntitiesChecklist('" + article_id + "', '" + menu + "', '" + parent_entity + "')", 1);
    }
}

function handleLoadRelatedEntitiesChecklist() {
	if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(':|||:');
                $(xmlResponse[0]).innerHTML = xmlResponse[1];
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

function changeArticleRelationship(article_id, entity_id, checked) {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
            xmlHttp.onreadystatechange = handleXMLHttpReturn;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("saveArticleRelationship") + "&article_id=" + encodeURI(article_id) + "&entity_id=" + encodeURI(entity_id) + "&checked=" + encodeURI(checked));
        } catch(e) {
            alert("changeArticleRelationship() Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("changeArticleRelationship('" + article_id + "', '" + entity_id + "', '" + checked + "')", 1);
    }
}

function revertArticleEntitiesChecklist(article_id, menu, parent_entity) {
    $('menu_' + parent_entity).innerHTML = '';
    relatedButton = $(menu + '_checklist_entities');
	relatedButton.removeEvents();
	relatedButton.addEvent('click', function(event) {
		event.stop();
		loadArticleEntitiesChecklist(article_id, menu, parent_entity);
	});

    getRelatedArticleEntities(article_id, parent_entity, menu);
}

function getAllRelatedArticleEntities(article_id) {
	getRelatedArticleEntities(article_id, '2', 'projects');
	getRelatedArticleEntities(article_id, '3', 'project_types');
	getRelatedArticleEntities(article_id, '4', 'people');
	getRelatedArticleEntities(article_id, '5', 'date');
	getRelatedArticleEntities(article_id, '6', 'location');
	getRelatedArticleEntities(article_id, '7', 'ideas');
}

function getRelatedArticleEntities(article_id, entity_id, menu_reference) {
	/*
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
		try {
			xmlHttp.open("POST", "includes/ajax/entities.ajax", true);
			xmlHttp.onreadystatechange = handleLoadRelatedEntities;
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttp.send("request=" + encodeURI("getRelatedArticleEntities") + "&masterid=" + encodeURI(entity_id) + "&articleid=" + encodeURI(article_id) + "&menuReference=menu_" + encodeURI(entity_id));
		} catch(e) {
			alert("getRelatedArticleEntities() Can't connect to the server:\n" + e.toString());
		}
	} else {
		setTimeout("getRelatedArticleEntities('" + article_id + "', '" + entity_id + "', '" + menu_reference + "')", 1);
	}
	*/
	
	try {
		var request = new Request({
			method: 'post', 
			url: 'includes/ajax/entities.ajax', 
			onSuccess: function(responseText, responseXML) {
				handleLoadRelatedEntities(responseXML);
			}
		}).send('request=getRelatedArticleEntities&masterid=' + entity_id + '&articleid=' + article_id + '&menuReference=menu_' + entity_id);
	} catch(e) {
		alert("getRelatedArticleEntities() Can't connect to the server:\n" + e.toString());
	}
}

/*
 *
 */
function handleXMLHttpReturn() {
	//TODO: alert for an error                             
}

//slideshow
//============================================================================================
//new version here
/*
function initSlideshow(){
}
*/

//default vals
var scroll;
var timerId = 0;
var centerX = 1024;
var offset = 150;
var offsetLeft = centerX - offset;
var offsetRight = centerX + offset;
var mouseX = 0;
var scrollX = 0;
var scrollSpeed = 10;

//functions
function getMouseX(e){
	if(navigator.appName == "Netscape"){
		mouseX = e.pageX;
		
	}else if(navigator.appName.indexOf("Microsoft") != -1){
		mouseX = window.event.x + document.body.scrollLeft;
	}
}

function startSlidShow(){
	//40ms = 25 fps
	timerId = setInterval("mousePos()", 40);
}

function stopSlidShow(){
	clearInterval(timerId);
}


function mousePos(){
	if((mouseX - offsetLeft) < 0){
		scrollX -= scrollSpeed;
	}else if((mouseX - offsetRight) >= 0){
		scrollX += scrollSpeed;
	}
	
	if(scrollX < 0){
		scrollX = 0;
	}
	
	scroll.set(scrollX, 0);
}

function initSlideshow(){
	/*var imgTagAry = $$('#slideshowList img.thumb');
	var currentPhoto = 0;
	var currentX = 0;
    var scrollState = false;
	
	var scroll = new Fx.Scroll('slideshowContainer', {
		wait: false,
		duration: 500,
		transition: Fx.Transitions.Quad.easeInOut
	});
	
	$('slideshowLftArrow').addEvent('mouseover', function(e){
		e.stop();
		scrollState = true;
        startScrollingLeft();
	});
    
    $('slideshowLftArrow').addEvent('mouseleave', function(e){
        e.stop();
        scrollState = false;
    });
    
    function startScrollingLeft() {
        if(currentPhoto > 0){
            currentX -= imgTagAry[currentPhoto - 1].offsetWidth + 5;
        }
        
        if(currentX >= 0 && currentPhoto > 0){
            currentPhoto--;
        }else if(currentX < 0){
            currentX = 0;
        }
        
        scroll.start(currentX, 0);
        
        if(scrollState === true) {
            //TODO delay call to call startScrollingLeft again
        }
    }
	
	$('slideshowRightArrow').addEvent('mouseenter', function(e){
		e.stop();
        scrollState = true;
		startScrollingRight();
	});
    
    $('slideshowRightArrow').addEvent('mouseleave', function(e){
        e.stop();
        scrollState = false;
    });
    
    function startScrollingRight() {
        var slMaxX = $('slideshowList').offsetWidth;
        var scMaxX = $('slideshowContainer').offsetWidth;
        var maxX = slMaxX - scMaxX;
        
        currentX += imgTagAry[currentPhoto].offsetWidth + 5;
        
        if(currentX <= maxX){
            currentPhoto++;
        }else if(currentX > maxX){
            currentX -= imgTagAry[currentPhoto].offsetWidth + 5;
        }
        
        scroll.start(currentX, 0);
        
        if(scrollState === true) {
            //TODO delay call to call startScrollingRight again
        }
    }*/
	clearInterval(timerId);
	mouseX = 0;
	scrollX = 0;

    scroll = new Fx.Scroll('slideshowWrapper', {
        wait: false,
        duration: 500,
        transition: Fx.Transitions.Quad.easeInOut
    });
    
    centerX = $('slideshowWrapper').offsetWidth / 2;        
    offsetLeft = centerX - offset;
    offsetRight = centerX + offset;
    
    document.onmousemove = getMouseX;
    
    $('slideshowWrapper').addEvent('mouseover', function(){
        startSlidShow();
    });
    $('slideshowWrapper').addEvent('mouseout', function(){
        stopSlidShow();
    });
}