function in_array(needle, haystack, strict) {
    // http://kevin.vanzonneveld.net
        // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
	// *     returns 1: true
		
	var found = false, key, strict = !!strict;
	for (key in haystack) {
		if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
			found = true;
			break;
		}
	}
								       
	return found;
}

var original_forms = new Array;
function getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};
function getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
};
function checkPageHeight($stretchy_elem){
	//use menu for reference height...?
//	alert("checkPageHeight called with : "+$stretchy_elem.attr("id"));
	var menu_height = $(".mrda_left").height();
	if($(".mrda_left").attr("clientheight")){
		menu_height = $(".mrda_left").attr("clientheight");
	}
	var old_height = menu_height + $(".mrda_left").offset().top;
	var min_height = 576;

	if(!isNaN($stretchy_elem)){ //a shrinky call will give us a number (generally just before removing an element)
		var stretchy_height = 0 - $stretchy_elem;
	}else{
		var myHeight=20;
		if($.browser.msie){
			if(/6.0/.test(navigator.userAgent))
				myHeight = $stretchy_elem.attr("offsetHeight");
			else
				myHeight = $stretchy_elem.attr("scrollHeight");
		}else{

//			myHeight = $stretchy_elem.attr("scrollHeight");
			$stretchy_elem.children().each(function(){
				myHeight +=parseInt($(this).css("margin-bottom").replace("px",""));
				myHeight+= $(this).outerHeight();
			});
		}
/*		alert(
			"offsetHeight: "+$stretchy_elem.attr("offsetHeight")+"\n"+
			"clientHeight: "+$stretchy_elem.attr("clientHeight")+"\n"+
			"outerHeight(): "+$stretchy_elem.outerHeight()+"\n"+
			"height(): "+$stretchy_elem.height()+"\n"+
			"scrollHeight: "+$stretchy_elem.attr("scrollHeight")+"\n"+
			"myHeight: "+myHeight
		);
*/	
		stretchy_height = myHeight;
	}
	var mrda_page_height = 576;
	var stretched_height;
	if(!isNaN($stretchy_elem)){
		mrda_page_height = $(".mrda_page").height();
		if($(".mrda_page").attr("clientheight")){
			mrda_page_height = $(".mrda_page").attr("clientheight");
		}
		stretched_height = stretchy_height + mrda_page_height;
	}else{
		if($stretchy_elem.attr("class").length>0 && $stretchy_elem.attr("class").match(/edit/)){
			mrda_page_height = $(".mrda_page").height();
			if($(".mrda_page").attr("clientheight")){
				mrda_page_height = $(".mrda_page").attr("clientheight");
			}
			stretched_height = stretchy_height + mrda_page_height;
		}else{
			
			stretched_height = stretchy_height + $(".mrda_left").offset().top;
		}
	}
//	alert(stretched_height+" > "+old_height);
	if(stretched_height > old_height){
//		alert("new_page_height = "+mrda_page_height+" + "+(stretched_height-old_height)+" + 20");
		new_page_height = mrda_page_height + (stretched_height-old_height);
		new_body_height = new_page_height + 20;
		$("body").height(new_body_height);
	}else{
		new_page_height = 576;
		if($("body").height() > 596){
			new_body_height = new_page_height;	
			$("body").height(new_body_height);
		}
	}
	

	$(".mrda_page").height(new_page_height).css({backgroundColor:"#fff"});

	setBackgroundImageSize();
	return stretched_height;
}

function setBackgroundImageSize(){
		//Get current img dimensions
		var img_w = Number($("#mrda_background").css("width").replace(/[^\d]+/,""));
		var img_h = Number($("#mrda_background").css("height").replace(/[^\d]+/,""));
		var arrPageSizes = getPageSize();
		var page_w = arrPageSizes[0];
		var page_h = arrPageSizes[3]-10;//$(window).height()
//		alert( "image dimensions : "+img_w+"x"+img_h+"\n window dimensions: "+page_w+"x"+page_h);

//If either aspect is greater than its min dimension calculate gaps
		if(page_w > 1024 ||  page_h > 768){		
			var gap_w = page_w - img_w;
			var gap_h = page_h - img_h;
			//add the higher gap value to both aspects to make sure atio is retained and gaps are covered
			if(gap_w >= gap_h){
				img_w += gap_w;
				img_h += gap_w;
			}else{
				img_w += gap_h;
				img_h += gap_h;
			}
		}
//		alert( "image dimensions : "+img_w+"x"+img_h+"\n window dimensions: "+page_w+"x"+page_h);

		//If window width is greater than or equal to img min dimensions set to new img width
		if(page_w  >= 1024 || page_h >= 768){		
			$("#mrda_background").css("width",img_w+"px");
			$("#mrda_background").css("height",img_h+"px");
		//otherwise do nowt unless a user has shrunk the window through the min dimensions so the img dimensions need set back to the minimum
		}else{
			if (img_w > 1024 || img_h > 768){
				$("#mrda_background").css("width","1024px");
				$("#mrda_background").css("height","768px");
			}
		}
		
}
function toggle_sub_menu($span){
	var $li = $span.parent();
	if($li.children("ul:hidden").length>0){
		var $ul = $li.children("ul");
		$li.children("ul").show('slow',function(){
			if($(".mrda_person_list").length>0){
				var sh1 = checkPageHeight($(".mrda_person_list"));
				var sh2 = checkPageHeight($(".mrda_person_text"));
				if(sh1 > sh2)
					checkPageHeight($(".mrda_person_list"));
			}
		});
		if($li.siblings("li").children("ul:visible").length>0){
			$li.siblings("li").children("ul").hide(500);
			$li.siblings("li").children("span").removeClass("menu_highlight");
		}
		$li.children("span").addClass("menu_highlight");
	}else{
	        $li.children("ul").hide('slow', function(){
			if($(".mrda_person_list").length>0){
				var sh1 = checkPageHeight($(".mrda_person_list"));
				var sh2 = checkPageHeight($(".mrda_person_text"));
				if(sh1 > sh2)
					checkPageHeight($(".mrda_person_list"));
			}
		});
	}

}
function setLeftMenu(){
   $(".left_menu > li > ul").hide();
   $(".content").hide();
   $(".left_menu > li > span").hover(
	function(){
		$(this).addClass("menu_highlight");
   	},
	function () {
		if($(this).siblings("ul:visible").length==0){
			$(this).removeClass("menu_highlight");
		}
      });

   $(".left_menu > li > span ").click(
	function(){
		toggle_sub_menu($(this));
   	});
   $(".left_menu > li > ul > li > span").hover(
	function(){
		$(this).addClass("menu_highlight");
	},
	function(){
		$(this).removeClass("menu_highlight");
	});
   $(".left_menu > li > ul > li > span").click( 
	function(){
		var $li = $(this).parent();
		$li.parents(".left_menu").find(".menu_selected").removeClass("menu_selected");	
		$(this).addClass("menu_selected");

   	});

}
function setPeopleMenu(){

   	$(".mrda_person_list > ul > li > ul").hide();
   	$(".mrda_person_list > ul > li > span").hover(
	function(){
		$(this).addClass("menu_highlight");
   	},
	function () {
		if($(this).siblings("ul:visible").length==0){
			$(this).removeClass("menu_highlight");
		}
      });

   $(".mrda_person_list > ul > li > span ").click(
	function(){
		toggle_sub_menu($(this));
   	});
   $(".mrda_person_list > ul > li > ul > li > span").hover(
	function(){
		$(this).addClass("menu_highlight");
	},
	function(){
		$(this).removeClass("menu_highlight");
	});
   $(".mrda_person_list > ul > li > ul > li > span").click( 
	function(){
		var $li = $(this).parent();
		$li.parents(".mrda_person_list").find(".menu_selected").removeClass("menu_selected");	
		$(this).addClass("menu_selected");
   	});

}

function setTabSwitch(){
	var orig_img;
	$("#i1").fadeIn(1500);
	$(".mrda_project_tab > div:first").addClass("selected");
	$(".mrda_project_tab > div").hover(function(){
		var tab_num = $(this).text();
		$(this).addClass("highlighted");
		orig_img = $(".mrda_project_image img:visible").attr("id");
		//tab_num--;
		$("#i"+tab_num).parent().siblings("a").find("img").hide();
		$("#i"+tab_num).show();
		
	}, function(){
		if(!$(this).hasClass("selected")){
			$(this).removeClass("highlighted");
			var sel_tab = $(".selected").text();
		//	sel_tab--;
			$("#i"+sel_tab).parent().siblings("a").find("img").hide();
			$("#i"+sel_tab).show();
		}else{
			$(this).show();
		}

	});
	$(".mrda_project_tab > div").click(function(){
		var tab_num = $(this).text();
//		tab_num--;
		$(this).siblings("div").removeClass("selected");
		$(this).siblings("div").removeClass("highlighted");
		$(this).addClass("selected");
		$("#i"+tab_num).siblings("img").hide();
		$("#i"+tab_num).show();
		$(".mrda_view_images > a").empty();
		$(".mrda_view_images > a:nth-child("+tab_num+")").text("View images as slide show");
	});
}
function setProjectsEdit(){
	$(".mrda_projects_display_row").each(function(){
		setProjectEdit($(this));
	});
}
function setProjectEdit($row){
	$row.click(function(){
		$(this).unbind("click");
		var this_row = $(this);
		var projectid = $(this).attr("id").split(/_/)[1];
		var url = "/edit_project.php?projectid="+projectid;
		$.ajax({
			url: url,
			success: function(response){
				$(this_row).after($(response).html());
				checkPageHeight($(".mrda_projects_all"));
				initEditActions(projectid);
			}
		});
	});
}

function setMulti($project_div){
	$project_div.find("input.mrda_projects_edit_upload_input").change(function(){
		if($(this).val().length>0){
			multiFile($(this));
		}
		//empty input value in readiness for next go...
		$(this).val("");
	});
	$project_div.find(".mrda_project_form").submit(function(){
		$(this).find(".mrda_projects_edit_upload_input").attr("disabled","disabled");
	});
}
var n=0;
var captionText = "Enter a caption and press enter";
function multiFile (input){
	var id;
	n++;
	id = "new"+n;
	var file = $(input).val().match(/[^\/\\]+$/gi);
	var name = $(input).attr("name");
	var newLabel = $('<li>'+file+'</li>');
	newLabel.attr("id","l_"+id);
	newLabel.attr("class","mrda_unsaved");
	var newCaption = $('<li>'+captionText+'</li>');
	newCaption.attr("id","c_"+id);
	if(!$.browser.mozilla){
		if($.browser.safari){
			alert("To upload a single file, you can use use Friefox or Internet explorer. To upload multiple files, please use Firefox.");
			return false;
		}else
			alert("Unless you use a mozilla browser (firefox, etc) you can only save one image at a time.");
		$(input).attr("name","imageu_"+id);
		$(input).addClass("fileToUpload");
	}else{
		var newInput = $(input).clone();
		newInput.attr("id","u_"+id);
		newInput.attr("name","imageu_"+id);
		newLabel.attr("id","l_"+id);
		newLabel.attr("class","mrda_unsaved");
		newInput.attr("class","mrda_hid_file");
		newInput.addClass("fileToUpload");
		$(input).after($(newInput));
	}

//	if($(input).parent("div").find("ul.mrda_project_images > li").length==0){
//		newLabel.addClass("selected");
//	}

	$(input).parent("div").find("> ul.mrda_project_images").append(newLabel);
	$(input).parent("div").find("> ul.mrda_project_image_comments").append(newCaption);
	setListSwitchFunctions(newLabel);
	if($(input).parent("div").find("ul.mrda_project_images > li").length==1){
		newLabel.trigger("click");
	}
/*	$("input[type=file]").each(function(){
		alert($(this).attr("name")+" *"+$(this).val()+"*");
	});
*/
}

function setListSwitchFunctions($li, $project_div){
	$li.hover(function(){
		var hi_num = $(this).attr("id").split(/_/)[1];
		$(this).addClass("highlighted");
		$("div.mrda_projects_comment_changed").fadeOut("slow");
		if($("#e_"+hi_num).length>0){
			$("#e_"+hi_num).siblings("img").hide();
			$("#e_"+hi_num).show();
		}else{
			$("#mrda_place_holder_thumb").siblings("img").hide();
			$("#mrda_place_holder_thumb").show();
		}
		if($("#c_"+hi_num).length>0){
			var caption = $("#c_"+hi_num).text();
			$(this).parent().siblings(".mrda_projects_edit_comment").find("input").val(caption);
		}else{
			$(this).parent().siblings(".mrda_projects_edit_comment").find("input").val("");
		}


		
	}, function(){
		if(!$(this).hasClass("selected")){
			$("div.mrda_projects_comment_changed").fadeOut("slow");
			$(this).removeClass("highlighted");
			var sel_num = $project_div.find(".mrda_projects_edit_upload_div ul > li.selected").attr("id").split(/_/)[1];
			if($("#e_"+sel_num).length>0){
				$("#e_"+sel_num).siblings("img").hide();
				$("#e_"+sel_num).show();
			}else{
				$project_div.find("#mrda_place_holder_thumb").siblings("img").hide();
				$project_div.find("#mrda_place_holder_thumb").show();
			}
			if($("#c_"+sel_num).length>0){
				var caption = $("#c_"+sel_num).text();
				$(this).parent().siblings(".mrda_projects_edit_comment").find("input").val(caption);
			}else{
				$(this).parent().siblings(".mrda_projects_edit_comment").find("input").val("");
			}

		}else{
	//		$(this).show();
		}

	});
	$li.click(function(){
		$(this).siblings("li").removeClass("selected");
		$(this).siblings("li").removeClass("highlighted");
		$(this).addClass("selected");
		var sel_num = $(this).attr("id").split(/_/)[1];
		if($("#e_"+sel_num).length>0){
			$("#e_"+sel_num).siblings("img").hide();
			$("#e_"+sel_num).show();
		}else{
			$("#mrda_place_holder_thumb").siblings("img").hide();
			$("#mrda_place_holder_thumb").show();
		}
		if($("#c_"+sel_num).length>0){
			var caption = $("#c_"+sel_num).text();
			$(this).parent().siblings(".mrda_projects_edit_comment").find("input").val(caption);
		}else{
			$(this).parent().siblings(".mrda_projects_edit_comment").find("input").val("");
		}
	});

}
function setListSwitch($project_div){
	var orig_img;
	var $first_li = $project_div.find(".mrda_projects_edit_upload_div ul.mrda_project_images > li:first");
	if($first_li.length>0){
		$first_li.addClass("selected");
		var first_num = $first_li.attr("id").split(/_/)[1];
		$project_div.find("#e_"+first_num).show();
		var caption = $project_div.find("#c_"+first_num).text();
		$first_li.parent().siblings(".mrda_projects_edit_comment").find("input").val(caption);
		
		$project_div.find(".mrda_projects_edit_upload_div ul.mrda_project_images > li").each(function(i){
			setListSwitchFunctions($(this), $project_div);
		});
	}
}

function setControls($project_div){
	$project_div.find(".mrda_projects_edit_remove").click(function(){
		if(confirm("Are you sure you want to remove this image?")){
			var sel_li = $project_div.find(".mrda_projects_edit_upload_div ul > li.selected");	
			var sel_num = sel_li.attr("id").split(/_/)[1];
			if($project_div.find("#u_"+sel_num).length>0){
				$project_div.find("#u_"+sel_num).remove();
			}
			if($project_div.find("#e_"+sel_num).length>0){
				$project_div.find("#e_"+sel_num).remove();
			}	
			sel_li.remove();
		}
	});
	$project_div.find(".mrda_projects_edit_up").click(function(){
		var sel_li = $project_div.find(".mrda_projects_edit_upload_div ul > li.selected");	
		var sel_num = sel_li.attr("id").split(/_/)[1];
		if(sel_li.prev("li").length>0){
			var prev = sel_li.prev("li");
			sel_li.remove().insertBefore(prev);
			setListSwitchFunctions($project_div.find("#l_"+sel_num));
		}

	});
	$project_div.find(".mrda_projects_edit_down").click(function(){
		var sel_li = $project_div.find(".mrda_projects_edit_upload_div ul > li.selected");	
		var sel_num = sel_li.attr("id").split(/_/)[1];
		if(sel_li.next("li").length>0){
			var next = sel_li.next("li");
			sel_li.remove().insertAfter(next);
			setListSwitchFunctions($project_div.find("#l_"+sel_num));
		}

	});
	$project_div.find(".mrda_projects_edit_replace").click(function(){
		var sel_li = $project_div.find(".mrda_projects_edit_upload_div ul > li.selected");	
		var sel_num = sel_li.attr("id").split(/_/)[1];
		$project_div.find(".mrda_projects_edit_upload_input").trigger("change");
	});
	$project_div.find(".mrda_projects_edit_comment > input").focus(function(){
		if($(this).val().replace(/\s$/,"") == captionText){ 
			$(this).val("");
		}
	});
	$project_div.find(".mrda_projects_edit_comment > input").keydown(function(e){
		var k = e.keyCode? e.keyCode : e.which? e.which : null;
		if (k == 13){
			e = e? e : window.event;
			if (e.preventDefault){
				e.preventDefault();
			}
		}
	});
	$project_div.find(".mrda_projects_edit_comment > input").keyup(function(e){
		var characterCode //literal character code will be stored in this variable

		characterCode = e.keyCode; //character code is contained in IEs keyCode property
		var sel_li = $project_div.find(".mrda_projects_edit_upload_div ul > li.selected");
		var sel_num = sel_li.attr("id").split(/_/)[1];

		if(characterCode == 13 || characterCode == 9){ //if generated character code is equal to ascii 13 (if enter key)
			$(this).siblings("div.mrda_projects_comment_changed").hide();
			$project_div.find("#c_"+sel_num).text($(this).val());
			$(this).siblings("div.mrda_projects_comment_stored").fadeIn("fast", function(){
				$(this).fadeOut(5000);
			});
		}else{
			if($project_div.find("#c_"+sel_num).text() != $(this).val()){
				$(this).siblings("div.mrda_projects_comment_changed").fadeIn("fast");
			}else{
				$(this).siblings("div.mrda_projects_comment_changed").fadeOut("slow");
			}
		}
		
	});

}

function setBigControls($project_div){

	$project_div.find(".mrda_project_delete").click(function(){
		var projectid = $project_div.attr("id").split(/_/)[1];
		if(projectid.match(/new/)){
//			reloadProject(projectid);
//			reloadAllProjects();
			var disp_row = $("#p_"+projectid).prev("tr");
			setProjectEdit($(disp_row));
			$("#p_"+projectid).remove();
			$("#editrow_"+projectid).remove();
			checkPageHeight($(disp_row));

			return false;
		}
		if(confirm("Are you sure you want to delete the project "+$project_div.find("h4").text().replace(/Update project /,"")+" and any associated Images?")){
			removeProject(projectid);
		}else{
			return false;
		}
	});

	$project_div.find(".mrda_project_save").click(function(){
		$(".mrda_projects_progress_msg").html("<span class=\"mrda_projects_success_msg\">Saving project changes...</span><br/>");
		if($project_div.find(".fileToUpload[name!=fake]").length>0){
			$(".mrda_projects_progress_msg").append("<span class=\"mrda_projects_success_msg\">Uploading files, this may take a few moments...</span><br/>");
		}
		$(".mrda_projects_progress_msg").fadeIn("fast");
		$project_div.find(".mrda_projects_edit").css("opacity","0.3");
		//process and send form
		var projectid = $project_div.attr("id").split(/_/)[1];
		
		$project_div.find("ul.mrda_project_images > li").each(function(i){
			var num = $(this).attr("id").split(/_/)[1];
			var caption = $project_div.find("#c_"+num).text();
			var imageInputs = $('<input type="hidden" name="imageid[]" value="'+num+'"/>\n<input type="hidden" name="caption[]" value="'+caption+'"/>\n');
			$project_div.find("form").append(imageInputs);
		});
		var projectidInput = $('<input type="hidden" name="projectid" value="'+projectid+'"/>');
		$project_div.find("form").append(projectidInput);
		if($project_div.find(".fileToUpload[name!=fake]").length>0){
			ajaxFileUpload($project_div,"/handle_upload.php");
		}else{
			nofileUpload($project_div,"/handle_upload.php");
		}
	});
	//Clone form when initEditActions is called (ie at load and reload) then we can compare for changes at closure and unload
	if($project_div.length>0){
		var projectid = $project_div.attr("id").split(/_/)[1];
		original_forms[projectid] = $project_div.find("form").clone();
		// IE seems to forget what has been selected in the cloned form... so we need to remember for it
		original_forms[projectid]["selected"] = $project_div.find("select").val();
	}
	$project_div.find(".mrda_project_close").click(function(){
		var projectid = $project_div.attr("id").split(/_/)[1];
		$form_now = $project_div.find("form");
		$form_then = original_forms[projectid];
		var change=0;
		$form_now.find("input,textarea,select,li").each(function(){
			if($(this).is("li")){
				value_now = $(this).text();
				original_value = $form_then.find("#"+$(this).attr("id")).text();
				if(value_now != original_value){
//					alert($form_then.find("#"+$(this).attr("id"))+": *"+value_now+"* ?= *"+original_value+"*");
					change=1;
				}

			}else{
				if($(this).is("select")){
					value_now = $(this).find(":selected").val();
					original_value = original_forms[projectid]["selected"];
					if($(this).attr("name").length>0 && 
							!$(this).attr("name").match(/\[\]/) && 
									value_now != original_value){
//						alert($(this).attr("name")+": *"+value_now+"* ?= *"+original_value+"*");
						change=1;
					}
				}else{
					value_now = $(this).val();
					original_value = $form_then.find("[name="+$(this).attr("name")+"]").val();
					if($(this).attr("name").length>0 && 
							!$(this).attr("name").match(/\[\]/) && 
									value_now != original_value){
//						alert($(this).attr("name")+": *"+value_now+"* ?= *"+original_value+"*");
						change=1;
					}
				}
			}

		});
		if(change){
			if(confirm("This project has been changed!!\n To save the changes press \"ok\".\nTo discard any changes press \"cancel\".")){
				$project_div.find(".mrda_project_save").trigger("click");
			}else{
				var disp_row = $("#p_"+projectid).prev("tr");
				setProjectEdit($(disp_row));
				$("#p_"+projectid).remove();
				$("#editrow_"+projectid).remove();
				checkPageHeight($(".mrda_projects_all"));
//				checkPageHeight($(disp_row));
			}

		}else{
			var disp_row = $("#p_"+projectid).prev("tr");
			setProjectEdit($(disp_row));
			$("#p_"+projectid).remove();
			$("#editrow_"+projectid).remove();
			checkPageHeight($(".mrda_projects_all"));
			//checkPageHeight($(disp_row));
		}

	});
	$(window).unload(function(){
		$project_div.find(".mrda_project_close").trigger("click");
	});

}
     
function ajaxFileUpload($project_div,upload_script, wym_index)
{

	// Can't get anything other than inputs to get tagged on so everything is turned into an input...
	if(wym_index==undefined){
		var awkwardInputs = $project_div.find("select,textarea");
		$(awkwardInputs).each(function(){
			if($(this).is("select")){
				value = $(this).find(":selected").val();
			}else{
				if($(this).val().length>0){
					value = $(this).val();
				}else{
					value = $(this).text();
				}
				value = value.replace(/"/g,'&quot;');
			}
//			alert("*"+$(this).attr("name") +" "+value);
			var newInput = $('<input type="hidden" name="' + $(this).attr("name") + '" id="' + $(this).attr("id") + '" value="' + value + '"/>');	
			$project_div.find("form").append(newInput);
		});
	
		var extraInputs = $project_div.find("input,textarea,select");
	}else{
		if(wym_index.length>1){		
			var newInput = $('<textarea name="content_col1" class="content" style="display: none;">' + jQuery.wymeditors(wym_index[0]).html() + '</textarea>');	
			$project_div.find("form").append(newInput);
			newInput = $('<textarea name="content_col2" class="content" style="display: none;">' + jQuery.wymeditors(wym_index[1]).html() + '</textarea>');	
			$project_div.find("form").append(newInput);
			extraInputs = $project_div.find("input,textarea.content,select");
		}else{
			if(jQuery.wymeditors(wym_index[0]).html().length>0){
				var newInput = $('<textarea name="content" id="content" style="display: none;">' + jQuery.wymeditors(wym_index[0]).html() + '</textarea>');	
				$project_div.find("form").append(newInput);
				extraInputs = $project_div.find("input,textarea#content,select");
			}
		}
	}
/*
	extraInputs.each(function(){
		alert($(this).attr("name") +" "+$(this).attr("value"));
	});
*/	
	$.ajaxFileUpload({
		url:upload_script,
		secureuri:false,
		fileElementId:'fileToUpload', 
		extraInputs : extraInputs,
		dataType: 'xml',
		success: handleResponse,
		error: function (data, status, e){
			alert(e);
		}
	});       
	return false;
}       
function nofileUpload($project_div,upload_script,wym_index){
	if(wym_index != undefined){

		if(wym_index.length==1){		
			var wym = jQuery.wymeditors(wym_index[0]);
			if(wym && wym.html().length>0){
				var newInput = $('<textarea name="content" id="content" style="display: none;">' + wym.html() + '</textarea>');	
				$project_div.find("form").append(newInput);
			}
		}else{
			var wym1 = jQuery.wymeditors(wym_index[0]);
			var wym2 =  jQuery.wymeditors(wym_index[1]);
			if(wym1 && wym1.html().length>0){
				var newInput = $('<textarea name="content_col1" class="content" style="display: none;">' + wym1.html() + '</textarea>');	
				$project_div.find("form").append(newInput);
			}
			if(wym2 && wym2.html().length>0){
				newInput = $('<textarea name="content_col2" class="content" style="display: none;">' + wym2.html() + '</textarea>');	
				$project_div.find("form").append(newInput);
			}
		}
	}

		var data = $project_div.find("form").serialize();
		//alert(data);
		$.ajax({
		   type: "POST",
		   url: upload_script,
		   processData: false,
		   data: data,
		   success: handleResponse,
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			$(this).text("Ajax related error: "+errorThrown);
			$(this).fadeOut(5000);
	   	   }
		});
}
function removePerson(personid){
	$(".mrda_projects_progress_msg").html("<span class=\"mrda_projects_success_msg\">Removing person...</span><br/>");
	$(".mrda_projects_progress_msg").fadeIn("fast");

	$.ajax({
	   type: "POST",
	   url: "/handle_person_upload.php",
	   data: {remove: personid },
	   success: handleResponse,
	   error: function(XMLHttpRequest, textStatus, errorThrown){
		$(this).text("Ajax related error: "+errorThrown);
		$(this).fadeOut(5000);
	   }
	});
}
function removeArticle(articleid,page){
	$(".mrda_projects_progress_msg").html("<span class=\"mrda_projects_success_msg\">Removing article...</span><br/>");
	$(".mrda_projects_progress_msg").fadeIn("fast");

	$.ajax({
	   type: "POST",
	   url: "/handle_article_upload.php",
	   data: {remove: articleid, page: page},
	   success: handleResponse,
	   error: function(XMLHttpRequest, textStatus, errorThrown){
		$(this).text("Ajax related error: "+errorThrown);
		$(this).fadeOut(5000);
	   }
	});
}
function removeProject(projectid){
	$(".mrda_projects_progress_msg").html("<span class=\"mrda_projects_success_msg\">Removing project...</span><br/>");
	$(".mrda_projects_progress_msg").fadeIn("fast");

	$.ajax({
	   type: "POST",
	   url: "/handle_upload.php",
	   data: {remove: projectid },
	   success: handleResponse,
	   error: function(XMLHttpRequest, textStatus, errorThrown){
		$(this).text("Ajax related error: "+errorThrown);
		$(this).fadeOut(5000);
	   }
	});
}

function handleResponse(response, textStatus){
   	if($(".mrda_projects_progress_msg:visible").length==0){
		$(".mrda_projects_progress_msg").fadeIn("fast");
	}
	var script = $("response > script",response).text();
	var page = $("response > page",response).text();

	if(script == "projects"){
		var id = $("response > id", response).text();
		$project_div = $("#p_"+id);
	}
	//alert($("response", response).text());

	$("response", response).children().each(function(){
		if($(this).is("progress[debug_level=2]")){
			$(".mrda_projects_progress_msg").append($(this).text()+"<br/>");
			$(".mrda_projects_progress_msg").scrollTo('+=50',50);
		}
		if($(this).is("error[debug_level=2]")){
			msg = '<span class="mrda_projects_error_msg">'+$(this).text()+'</span><br/>';
			$(".mrda_projects_progress_msg").append(msg);	
		}
		if($(this).is("fatal[debug_level=2]")){
			msg = '<span class="mrda_projects_fatal_msg">'+$(this).text()+'</span><br/>';
			$(".mrda_projects_progress_msg").append(msg);	
		}
		if($(this).is("success[debug_level=2]")){
			msg = '<span class="mrda_projects_success_msg">'+$(this).text()+'</span><br/>';
			$(".mrda_projects_progress_msg").append(msg);	
		}	
		if($(this).is("finished")){
			var id = $("response > id",response).text();
			if(script == "static"){
				_loadPage("static",page);
				overLay();
				window.location.reload(); //reload to avoid double wym-ing
				return;
			}
			if(script == "articles"){
				_loadPage(script,page,id);
				overLay();
				window.location.reload(); //reload to avoid double wym-ing
				return;
			}
			if(script == "people"){
				_loadPage(script,page,id);
				overLay();
				var reload_url =  "/#"+script+"/"+page;
				if(id)
					reload_url +="/"+id;
				window.location= reload_url //reload(ish) to avoid double wym-ing
				return;
			}
			if(script == "projects"){
				if($("response > removed",response).length>0){
					reloadAllProjects();
				}else{
					reloadAllProjects();
				}
			}
			msg = '<span class="mrda_projects_success_msg">Project reloaded</span><br/>';
			$(".mrda_projects_progress_msg").append(msg);	
			if($("response > error",response).length==0){
				$(".mrda_projects_progress_msg").fadeOut(3000,function(){
					$project_div.find(".mrda_projects_edit").css("opacity","1");
				});
			}
		}
	});
	if($("response > finished",response).length>0){

	}
}
function reloadProject(projectid){
	var snippet = $.ajax({
		url: "/project_row.php?projectid="+projectid,
		async: false
		}).responseText;
	
	var row_height = $("tr#editrow_"+projectid).height();
	if($("tr#editrow_"+projectid).attr("clientheight")){
		row_height = $("tr#editrow_"+projectid).attr("clientheight");
	}
	$("tr#editrow_"+projectid).remove();
	checkPageHeight(row_height);

	$("tr#row_"+projectid).replaceWith($(snippet));
	initEditActions(projectid);
	
}
function reloadAllProjects(){
	var page = $.ajax({
		url: "/projects.php?q=all",
		async: false
		}).responseText;
	$(".mrda_content").html($(page));
	
}
function removeProjectRow(projectid){
	$("tr#row_"+projectid).remove();
	$("tr#editrow_"+projectid).remove();
}
function setSectorMenu(){
	if($.browser.msie && /6.0/.test(navigator.userAgent))
		$(".mrda_sector_menu li").hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover')});

	$(".mrda_sector_menu li").click(function(){
		overLay();
		if(window.location.hash){
			hash_parts=window.location.hash.split("/");
			script = hash_parts[0].replace("#","");
			page = hash_parts[1];
		}else{
			script = "projects";
			page = "sectors";
		}

		var sectorid = $(this).text();
		_loadPage(script,page,sectorid);
	
/*		var $li = $(this);
		var content_height = $(".mrda_content").height();
		var content_width = $(".mrda_content").width();
		var content_offset = $(".mrda_page").offset().left;
		if(!content_height){
			content_height = $(".mrda_page").attr("clientHeight");
		}
		$('.mrda_page').after('<div id="jquery-overlay">&nbsp;<div class="mrda_content_loading_msg"><br/><br/><br/>Please Wait...</div></div>');

		// Get page sizes
		// Style overlay and show it
		$('#jquery-overlay').css({
			backgroundColor: "#fff",
			opacity:	0.5,
			width:		content_width,
			height:		content_height,
			left:		content_offset,
			zindex:	100
		}).fadeIn('fast');
		// need to use setTimeout to avoid the asynchronous ajax request stopping the overlay working...
		setTimeout("loadSectorPage('"+$li.attr("id")+"')",500);

		$li.parents(".mrda_sector_menu").find(".menu_selected").removeClass("menu_selected");	
		$li.addClass("menu_selected");
		setSectorMenu();
		setProjectLinks();
		*/
	});
	setProjectLinks();
}


function setProjectLinks(){
	$(".mrda_project img").click(function(){
		if($(this).hasClass("splash_click")){
			var sector = $(this).attr("id").split("_")[1];
			overLay();
			_loadPage("projects","sectors",sector);
		}else{
			var projectid = $(this).attr("id").split("_")[1];
			if(projectid.match(/new/))
				return false;
			var project = $.ajax({
				url: "/project.php?id="+projectid,
				async: false
			}).responseText;
			$(".mrda_content").html($(project));
			checkPageHeight($(".mrda_project_text"));
			if(window.location.pathname.search("/project\/"+projectid+"$/")==-1){
				var bm = "project/"+projectid;
				window.location.hash=bm;
				recentHash = window.location.hash;
				if($("#ajaxnav").length>0){
					$("#ajaxnav").attr("src","mock_page.php?hash="+window.location.hash.replace("#",""));
				}
			}
		}
	});
	$(".mrda_project select").each(function(){
		projectCardUpdate($(this));
	});

}
function setProjectRowLinks(){
	$(".mrda_projects_live td").click(function(){
		var projectid = $(this).attr("id").split("_")[1];
		if(projectid.match(/new/))
			return false;
		var project = $.ajax({
			url: "/project.php?id="+projectid,
			async: false
		}).responseText;
		$(".mrda_content").html($(project));
		checkPageHeight($(".mrda_project_text"));
		if(window.location.pathname.search("/project\/"+projectid+"$/")==-1){
			var bm = "project/"+projectid;
			window.location.hash=bm;
			recentHash = window.location.hash;
			if($("#ajaxnav").length>0){
				$("#ajaxnav").attr("src","mock_page.php?hash="+window.location.hash.replace("#",""));
			}
		}
	});
}

function projectCardUpdate($select){
	$select.change(function(){
		//In this case what puports to be the projectid is really a marker for the position.

		var projectid = $select.parent().attr("id").split("_")[1];
		var page = $select.attr("class");
		var sel_proj = $select.val();
		var sector = "";

		if($(".mrda_projects").attr("id").length>0){
			sector = $(".mrda_projects").attr("id");
		}
		var url = "/project_card_update.php?projectid="+projectid+"&update="+page+"&selected_project="+sel_proj+"&sector="+sector;
//		alert(url);
		var project = $.ajax({
			url: url,
			async: false
		}).responseText;
		var $mrda_project = $select.parent();
		$mrda_project.html($(project));
		$mrda_project.find("img").load(function(){
			$(this).fadeIn(1000);
			center_thumbs();
		});
		projectCardUpdate($mrda_project.find("select"));
	});	
}
function initPageActions(){
	
	setBackgroundImageSize();
	if(!$.browser.msie){
		//erring on side of caution thie will break ie 6 and need to test on ie7 that I can kill
		$(window).resize(function(){
			setBackgroundImageSize();
		});
	}
	setLeftMenu();	
	setSectorMenu();
}
function setOrderTable(){
// 	$(".mrda_projects_all table").tablesorter({ headers: { 1: { sorter: false}, 2: {sorter: false}, 3: {sorter: false} } }); 
}
function _loadPage(script,page,id){
	if(!script){
		if(window.location.hash){
			hash_parts=window.location.hash.split("/");
			script = hash_parts[0].replace("#","");
			page = hash_parts[1];
		}else{
			script = "static";
			page = "";
		}
	}

	if(id){
		var url = "/"+script+".php?q="+page+"&id="+id;
	}else{
		var url = "/"+script+".php?q="+page;
	}
	//alert("ur: "+url);

	var d = new Date();
	var start = d.getTime();

	$.ajax({
		url: url,
		success: function(response){
				if($("#mrda_contactForm").length>0){
					$("#mrda_contactForm").fadeOut("fast");
				};

				$("#jquery-overlay").remove();  
				$(".mrda_content").html($(response));

				if(script == "static" && !page){
					$(".mrda_left").css("border-top","none");
				}else{
					$(".mrda_left").css("border-top","1px solid #646566");
				}
				
				if($(".mrda_text").length>0 && $(".mrda_article_list").length==0){
					checkPageHeight($(".mrda_text"));
				}
				if($(".mrda_columns_text").length>0){
					if($(".mrda_static_col2").height() > $(".mrda_static_col1").height()){
						checkPageHeight($(".mrda_static_col2"));
					}else{
						checkPageHeight($(".mrda_static_col1"));
					}
				}
				if($(".mrda_projects").length>0){
					new_page_height = 576;
					new_body_height = new_page_height;
					$(".mrda_page").height(new_page_height).css({backgroundColor:"#fff"});
					$("body").height(new_body_height);
					setBackgroundImageSize();	
				}
				if($(".mrda_projects_all").length>0){
					checkPageHeight($(".mrda_projects_all"));
				}

				setSectorMenu();
				if(page != 'all'){
					if($(".mrda_content img").length){
						$(".mrda_image").show();
						$(".mrda_content img").load(function(){
							$(this).fadeIn(1000);
							center_thumbs();
						});
					}else{
						$(".mrda_image").fadeIn(1000);
					}
				}
				if(window.location.pathname.search("/"+script+"\/"+page+"$/")==-1){
					var bm = script+"/"+page;
					if(window.location.pathname.search("/\/"+id+"$/")==-1 && id!=undefined)
						bm += "/"+id;
					window.location.hash=bm;
					recentHash = window.location.hash;
					if($("#ajaxnav").length>0){
						$("#ajaxnav").attr("src","mock_page.php?hash="+window.location.hash.replace("#",""));
					}
				}
				if(script.match("static") && (window.location.hostname.search(/edit/)>-1 || window.location.hostname.search(/dev/)>-1)){
//				if(script.match("static") && (window.location.hostname.search(/edit/)>-1)){
					setStaticEdit();
				}else{
					$(".mrda_content").unbind("click");
				}
				var d = new Date();
				var elapsed = (d.getTime() - start) / 1000;
//				alert("Elapsed: "+elapsed);
			}
		});


}
function center_thumbs(){
	//center thumbs
	if($(".thumb").length>0){
		var view_w = $(".thumb_div").width();
		var view_h = $(".thumb_div").height();

		$(".thumb").each(function(){
			if($(this).width()> $(this).height()){
				var move = ($(this).width()-view_w)/2;
				$(this).css("left","-"+move+"px");
				$(this).parent("div").css("margin-left","1px");
			}else{
			//portrait
				var move = ($(this).height()-view_h)/2;
				$(this).css("top","-"+move+"px");
				$(this).parent("div").css("margin-top","1px");
				if($(this).width()<129){
					$(this).css("width","129px");
					$(this).parent("div").css("width","129px");
				}
			}
		});
	}
}
function loadPage(span_id){
	var page = $("#"+span_id).parents("li,span").attr("id");
	var script = $("#"+span_id).parents("li,span").attr("class");
	_loadPage(script,page);

}
function loadSectorPage(li_id,sector){
	
	if(!sector){
		$li = $("#"+li_id);
		var sector=$li.text();
	}
	var projects = $.ajax({
		url: "/projects.php?q=sectors&sector="+sector,
		async: false
	}).responseText;
	$(".mrda_content").html($(projects));
	$("#jquery-overlay").remove();  

	if($(".mrda_projects").length>0){
		new_page_height = 576;
		new_body_height = new_page_height + 20;
		$(".mrda_page").height(new_page_height).css({backgroundColor:"#fff"});
		$("body").height(new_body_height);
		setBackgroundImageSize();
	}
	$li.parents(".mrda_sector_menu").find(".menu_selected").removeClass("menu_selected");	
	$li.addClass("menu_selected");
	setSectorMenu();
	setProjectLinks();
	$(".mrda_content img").load(function(){
		$(this).fadeIn(1000);
	});

	var bm = "projects/sectors/"+sector;
	window.location.hash=bm;
	recentHash = window.location.hash;
	if($("#ajaxnav").length>0){
		$("#ajaxnav").attr("src","mock_page.php?hash="+window.location.hash.replace("#",""));
	}
}
function loadArticle(page,articleid){
	if(isNaN(articleid) && articleid.search(/new/)==0){
		$(".mrda_article_text").unbind("click");
		editArticle(page,articleid);
		return false;
	}
	if($("#mrda_article_controls").length>0)
	$("#mrda_article_controls").remove();
	var article = $.ajax({
		url: "/article.php?id="+articleid+"&page="+page,
		async: false
	}).responseText;
	$(".mrda_article_text").html($(article));
	$(".mrda_article_text").attr("id","mrda_article_"+articleid);;

	$("#jquery-overlay").remove();  

//	if(window.location.hostname.search(/edit/)>-1) 
	if(window.location.hostname.search(/edit/)>-1 || window.location.hostname.search(/dev/)>-1)
		setArticleEdit();
	if($(".mrda_content img").length>0){
		$(".mrda_content img").load(function(){
			$(this).fadeIn(1000, function(){
				if($(".mrda_article_text").length>0){
					checkPageHeight($(".mrda_article_text"));
				}
			});
		});
	}else{
		if($(".mrda_article_text").length>0){
			checkPageHeight($(".mrda_article_text"));
		}
	}
	if(window.location.pathname.search("/"+page+"\/"+articleid+"$/")==-1){
		var bm = "articles/"+page+"/"+articleid;
		window.location.hash=bm;
		recentHash = window.location.hash;
		if($("#ajaxnav").length>0){
			$("#ajaxnav").attr("src","mock_page.php?hash="+window.location.hash.replace("#",""));
		}
	}
}

function editArticle(page,articleid){
	$(".mrda_article_text").unbind("click");
	var article = $.ajax({
		url: "/article.php?id="+articleid+"&page="+page+"&edit=1",
		async: false
	}).responseText;
	$(".mrda_article_text").html($(article));
	$(".mrda_article_text").attr("id",articleid);
	if($("input[name=date]").val().length>0){
		$('.datepick').datePicker({startDate:'01/01/1996'}).val($("input[name=date]").val()).trigger('change');
	}else{
		$('.datepick').datePicker({startDate:'01/01/1996'}).val(new Date().asString()).trigger('change');
	}

	var wym_index = [do_wym($("#mrda_article_edit_text"))];
	if($(".mrda_download_pdf").length>0)
		$(".mrda_download_pdf").remove();

	$(".mrda_content").append("<div id=\"mrda_article_controls\"><span id=\"mrda_article_save\">Save</span> / <span id=\"mrda_article_reset\">Close</span> / <span id=\"mrda_article_delete\">Delete</span></div>");
	if($.browser.msie && /6.0/.test(navigator.userAgent))
		$(".mrda_article_controls span").hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover')});

	$("#mrda_article_save").click(function(){
		overLay();
		if($(".mrda_content").find("input[name=pdf]").val().length>0){
			//alert("File");
			ajaxFileUpload($(".mrda_content"),"/handle_article_upload.php",wym_index);
		}else{
			//alert("nofile");
			nofileUpload($(".mrda_content"),"/handle_article_upload.php",wym_index);
		}
		return false;
	});
	$("#mrda_article_reset").click(function(){
		overLay();
		_loadPage('articles',page,articleid);
		return false;
	});
	$("#mrda_article_delete").click(function(){
		overLay();
		if(articleid.match(/new/)){
			$("#mrda_article_reset").trigger("click");
			return false;
		}
		if(confirm("Are you sure you want to delete the article "+$(".mrda_article_list .menu_selected .mrda_article_title ").text()+" and any associated pdfs?")){
			removeArticle(articleid,page);
		}else{
			$("#jquery-overlay").remove();  
			return false;
		}
	});

/*	if($(".mrda_article_text").length>0){
		checkPageHeight($(".mrda_article_text"));
	}
*/
	$(".mrda_content img").load(function(){
		$(this).fadeIn(1000);
	});

	if(window.location.pathname.search("/"+page+"\/"+articleid+"$/")==-1){
		var bm = "articles/"+page+"/"+articleid;
		window.location.hash=bm;
		recentHash = window.location.hash;
		if($("#ajaxnav").length>0){
			$("#ajaxnav").attr("src","mock_page.php?hash="+window.location.hash.replace("#",""));
		}
	}
}
function setArticleEdit(){
	$(".mrda_article_text").click(function(){
		$(this).unbind();
		if(window.location.hash){
			hash_parts=window.location.hash.split("/");
			script = hash_parts[0].replace("#","");
			page = hash_parts[1];
		}else{
			script = "articles";
			page = "articles";
		}
		var articleid = $(this).attr("id").replace("mrda_article_","");;
		editArticle(page,articleid);
	});
}
function loadPerson(page,personid){
	//alert("IN L_PERSON - page: "+page+", id: "+personid);

	$(".mrda_person_text").css("background-image","");

	if(isNaN(personid) && personid.search(/new/)==0){
		$(".mrda_person_text").unbind("click");
		editPerson(page,personid);
		return false;
	}
	var url= "/person.php?id="+personid;
//	alert(url);
	var person = $.ajax({
		url: url,
		async: false
	}).responseText;
	$(".mrda_person_text").html($(person));
	$(".mrda_person_text").attr("id",personid);

	if(personid==0){
		var image_url = $(".mrda_person_image").attr("src");
		$(".mrda_person_text").empty();
		$(".mrda_person_text").css("background-image","url("+image_url+")");
		$(".mrda_person_text").css("background-position","center");
		$(".mrda_person_text").css("background-repeat","no-repeat");
	}
	
	$("#jquery-overlay").remove();  

//	if(window.location.hostname.search(/edit/)>-1)
	if(window.location.hostname.search(/edit/)>-1 || window.location.hostname.search(/dev/)>-1){
		setPersonEdit();
	}
	if($(".mrda_content img").length>0){
		$(".mrda_content img").load(function(){
			$(".mrda_content img").fadeIn(1000,function(){
				if($(".mrda_person_text").length>0){
					checkPageHeight($(".mrda_person_text"));
				}
			});
		}).error(function(){
			if($(".mrda_person_text").length>0){
				checkPageHeight($(".mrda_person_text"));
			}
		});
	}else{
		if($(".mrda_person_text").length>0){
			checkPageHeight($(".mrda_person_text"));
		}
	}
	var page = "people";
	if($("#"+personid).length)
		page = $("#"+personid).parents("li").attr("id");

	if(window.location.pathname.search("/"+page+"\/"+personid+"$/")==-1){
		var bm = "people/"+page+"/"+personid;
		window.location.hash=bm;
		recentHash = window.location.hash;
		if($("#ajaxnav").length>0){
			$("#ajaxnav").attr("src","mock_page.php?hash="+window.location.hash.replace("#",""));
		}
	}
}

function editPerson(page,personid){
	$(".mrda_person_text").unbind("click");
	if($(".mrda_content #mrda_person_controls").length){
		$(".mrda_content #mrda_person_controls").remove();
	}
	var person = $.ajax({
		url: "/person.php?id="+personid+"&edit=1",
		async: false
	}).responseText;
	$(".mrda_person_text").html($(person));
	$(".mrda_person_text").attr("id",personid);
	if($("input[name=dob]").length>0){
		if($("input[name=dob]").val().length>0){
			$('.datepick').datePicker({startDate:'01/01/1940'}).val($("input[name=dob]").val()).trigger('change');
		}else{
			$('.datepick').datePicker({startDate:'01/01/1940'}).val(new Date().asString()).trigger('change');
		}
	}
	var wym_index = [do_wym($("#mrda_person_edit_text"))];
	$(".mrda_content").append("<div id=\"mrda_person_controls\"><span id=\"mrda_person_save\">Save</span> / <span id=\"mrda_person_reset\">Close</span></div>");
	if(personid != 0)
		$("#mrda_person_controls").append(" / <span id=\"mrda_person_delete\">Delete</span>");
	if($.browser.msie && /6.0/.test(navigator.userAgent))
		$(".mrda_person_controls span").hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover')});

	$("#mrda_person_save").click(function(){
		overLay();
		if($(".mrda_content").find("input[name=profile_image]").val().length>0){
			ajaxFileUpload($(".mrda_content"),"/handle_person_upload.php", wym_index);
		}else{
			nofileUpload($(".mrda_content"),"/handle_person_upload.php", wym_index);
		}
		return false;
	});
	$("#mrda_person_reset").click(function(){
		overLay();
		_loadPage('people',page,personid);
		return false;
	});
	$("#mrda_person_delete").click(function(){
		overLay();
		if(personid.match(/new/)){
			$("#mrda_person_reset").trigger("click");
			return false;
		}
		if(confirm("Are you sure you want to delete the person "+$(".mrda_person_list span.menu_selected b").text().replace(",","")+" and any associated Images?")){
			removePerson(personid);
		}else{
			$("#jquery-overlay").remove();  
			return false;
		}
	});

	if($(".mrda_person_text").length>0){
		checkPageHeight($(".mrda_person_text"));
	}

	$(".mrda_content img").load(function(){
		$(this).fadeIn(1000);
	});

	if(window.location.pathname.search("/"+page+"\/"+personid+"$/")==-1){
		var bm = "people/"+page+"/"+personid;
		window.location.hash=bm;
		recentHash = window.location.hash;
		if($("#ajaxnav").length>0){
			$("#ajaxnav").attr("src","mock_page.php?hash="+window.location.hash.replace("#",""));
		}
	}
}
function setPersonEdit(){
	$(".mrda_person_text").click(function(){
		$(this).unbind();
		if(window.location.hash){
			hash_parts=window.location.hash.split("/");
			script = hash_parts[0].replace("#","");
			page = hash_parts[1];
		}else{
			script = "people";
			page = "partners";
		}
		if($(this).attr("id")=="")
			var personid = 0;
		else	
			var personid = $(this).attr("id");
		editPerson(page,personid);
	});
}

function doLeftMenu($span){
	overLay();
	// need to use setTimeout to avoid the asynchronous ajax request stopping the overlay working...
	setTimeout("loadPage('"+$span.attr("id")+"')",500);
}
function overLay(){
	var content_height = $(".mrda_content").height();
	var content_width = $(".mrda_content").width();
	var content_offset = $(".mrda_page").offset().left;
	if(!content_height){
		content_height = $(".mrda_page").attr("clientHeight");
	}
	$('.mrda_page').after('<div id="jquery-overlay">&nbsp;<div class="mrda_content_loading_msg"><br/><br/><br/>Please Wait...</div></div>');

	// Get page sizes
	// Style overlay and show it
	$('#jquery-overlay').css({
		backgroundColor: "#fff",
		opacity:	0.5,
		width:		content_width,
		height:		content_height,
		left:		content_offset,
		zindex: 700
	}).fadeIn('fast');
}
function do_wym(textarea){
	$(textarea).wymeditor({logoHtml: '',
		     skin: "default",
			toolsItems: [
			    {'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'}, 
			    {'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
			    {'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'},
			    {'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'},
			    {'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'},
			    {'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste'},
			    {'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'}
			],
			containersItems: [
	/*		    {'name': 'p', 'title': 'paragraph', 'css': 'wym_containers_p'},
			    {'name': 'h2', 'title': 'heading_2', 'css': 'wym_containers_h2'},
			    {'name': 'h1', 'title': 'heading_1', 'css': 'wym_containers_h1'}*/
			],
			classesHtml: ''
	//		dialogLinkHtml: "<body class='wym_dialog wym_dialog_link' onload='WYMeditor.INIT_DIALOG(0)'><form><fieldset><input type='hidden' class='wym_dialog_type' value='Link' /><legend>Link</legend><div class='row'><label>URL</label><input type='text' class='wym_href' value='http://' size='40' /></div><div class='row'><label>Title</label><input type='text' class='wym_title' value='' size='40' /></div><div class='row row-indent'><input class='wym_submit' type='button' value='Submit' /><input class='wym_cancel' type='button'value='Cancel' /></div></fieldset></form></body>"
	});
	var wym_index = WYMeditor.INSTANCES.length-1;
//	WYMeditor.INDEX = "something else";
//	return WYMeditor.INDEX;
	return wym_index;
}
function setStaticEdit(){
	$(".mrda_content").click(function(){
		$(this).unbind();
		if(window.location.hash){
			hash_parts=window.location.hash.split("/");
			script = hash_parts[0].replace("#","");
			page = hash_parts[1];
		}else{
			script = "static";
			page = "";
		}

		var heading = $(".mrda_content h1").html();
		var pageid = $(".mrda_content h1").attr("id");
		var template = $("#template").text();
		var main_menu_item = $(".left_menu li ul:visible").parents("li").attr("id");
		if(heading.length ==0 && template != "home")
			heading = "Enter a page title";
		$(".mrda_content").wrapInner("<form></form>");
		var image_src = "/images/default_image.png";
		if($(".mrda_image img").length > 0 && $(".mrda_image img").attr("src").length > 0){
			image_src = $(".mrda_image img").attr("src");
		}else if($(".mrda_image").length > 0 && $(".mrda_image").css("background-image").length > 0)
			image_src = $(".mrda_image").css("background-image");
		
		$(".mrda_content h1").replaceWith("<input name=\"pagename\" value=\""+heading+"\" class=\"mrda_static\" />");
		if($(".mrda_text").length>0){
			var content = $(".mrda_text").html();

			if(template=="text_right"){
				$(".mrda_text").replaceWith("<div class=\"mrda_text_right_edit\"><textarea id=\"editContent\" name=\"content\" class=\"mrda_static\" cols=\"37\" rows=\"18\" >"+content+"</textarea></div>");
				$(".mrda_image img").replaceWith("<div class=\"mrda_image_left_edit\"><div>&nbsp;</div></div><div class=\"mrda_image_left_edit_input\">Upload an image file: <input name=\"static_image\" type=\"file\" class=\"fileToUpload\"/></div>");
				if($(".mrda_email_us").length>0)
					$(".mrda_email_us").remove();
				$(".mrda_image_left_edit").css("background","url("+image_src+") no-repeat");
				$(".mrda_image_left_edit > div").css("background","#fff");
				$(".mrda_image_left_edit > div").css("height","100%");
				$(".mrda_image_left_edit > div").css("width","100%");
				$(".mrda_image_left_edit > div").fadeTo("slow",0.5);
			}else{
				$(".mrda_text").replaceWith("<div class=\"mrda_text_left_edit\"><textarea id=\"editContent\" name=\"content\" class=\"mrda_static\" cols=\"37\" rows=\"18\">"+content+"</textarea></div>");
				$(".mrda_image span").replaceWith("<div class=\"mrda_image_right_edit\"><div>&nbsp;</div></div><div class=\"mrda_image_right_edit_input\">Upload an image file: <input name=\"static_image\" type=\"file\" class=\"fileToUpload\"/></div>");
//				$(".mrda_image_right_edit").css("background","url("+image_src+") no-repeat");
				$(".mrda_image_right_edit > div").css("background","#fff");
				$(".mrda_image_right_edit > div").css("height","100%");
				$(".mrda_image_right_edit > div").fadeTo("slow",0.5);
			}
			var wym_index = [do_wym($('#editContent'))];

// alt=\"Once saved, your uploaded image will appear here\"

		}else{
			if(template=="home"){
				$(".mrda_image_home span").replaceWith("<div class=\"mrda_image_home_edit\"><div>&nbsp;</div></div>");
				$(".mrda_image_home").append("<div class=\"mrda_image_home_edit_input\">Add an image to homepage rotation: <br/><input name=\"static_image\" type=\"file\" class=\"fileToUpload\"/><ul></ul></div>");
				if(wheel.length > 0){
					if(int != undefined)
						window.clearInterval(int);
					for(i=0; i<wheel.length; i++){
						var image = wheel[i].substr(wheel[i].lastIndexOf("/")+1);
						$(".mrda_image_home_edit_input > ul").append("<li id='"+wheel[i]+"'>"+image+"<span> x </span></li>");
					}
					$(".mrda_image_home_edit_input > ul > li > span").click(function(){
						$(this).parent("li").remove();
					});
				}

				$(".mrda_image_home").append("<div class=\"mrda_image_background_edit\">&nbsp;</div><div class=\"mrda_image_background_edit_input\">Upload a background image file: <br/><input name=\"background_image\" type=\"file\" class=\"fileToUpload\"/></div>");
//				$(".mrda_image_home_edit").css("background","url("+image_src+") no-repeat");
				$(".mrda_image_home_edit > div").css("background","#fff");
				$(".mrda_image_home_edit > div").css("height","100%");
				$(".mrda_image_home_edit > div").fadeTo("slow",0.5);

			}else{

				var col_1 = $(".mrda_columns_text .mrda_static_col1").html();
				var col_2 = $(".mrda_columns_text .mrda_static_col2").html();
				$(".mrda_columns_text .mrda_static_col1").replaceWith("<div class=\"mrda_static_col1\"><textarea id=\"editContent1\" name=\"content_col1\" class=\"mrda_static\" cols=\"37\" rows=\"18\">"+col_1+"</textarea></div>");
				$(".mrda_columns_text .mrda_static_col2").replaceWith("<div class=\"mrda_static_col2 mrda_static_col2_edit\"><textarea id=\"editContent2\" name=\"content_col2\" class=\"mrda_static\" cols=\"37\" rows=\"18\">"+col_2+"</textarea></div>");
				var wym_index = [do_wym($('#editContent1')),do_wym($('#editContent2'))];

				// Cheap and dirty fix for ajax uploading screwing up stuff with its namby pamby serialisation...
				// use ajaxFileupload (with an iframe and proper submit) for that to work we need a file input...
				$(".mrda_content form").append("<input name=\"fake\" type=\"file\" class=\"fileToUpload\" style=\"display: none;\"/>");
			}
		}
		$(".mrda_content").append("<div id=\"mrda_static_controls\"><span id=\"mrda_static_save\">Save</span> / <span id=\"mrda_static_reset\">Close</span><!-- / <span id=\"mrda_static_delete\">Delete</span>--></div>");
		if($.browser.msie && /6.0/.test(navigator.userAgent))
			$(".mrda_static_controls span").hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover')});

		if($.browser.msie && /6.0/.test(navigator.userAgent)){
			$(".wym_tools ul").css({'margin-bottom' : '0px', 'padding-bottom' : '0px'});
			$(".wym_iframe iframe").css({'height' : '350px'});
		}

		$(".mrda_content form").append("<input name=\"pageid\" value=\""+pageid+"\" type=\"hidden\"/>");
		$(".mrda_content form").append("<input name=\"template\" value=\""+template+"\" type=\"hidden\"/>");
		$(".mrda_content form").append("<input name=\"page_place\" value=\""+main_menu_item+"\" type=\"hidden\"/>");
		
	/*	if(!$(".left_menu li ul").is(":visible") && page){
			var blinkCount = 4*2;// two blinks, 4*2 for four blinks
			do {
			   $('.left_menu')['fade'+(blinkCount%2==0?'Out':'In')]('slow');
			} while (--blinkCount);
		}
*/
		$("#mrda_static_save").click(function(){
			overLay();
			if($(".mrda_image_home_edit_input > ul > li").length>0){
				var home_images = jQuery.makeArray($(".mrda_image_home_edit_input > ul > li"));
                  		home_images = jQuery.map(home_images, function(n){
					return $(n).attr("id");
				});
				$(".mrda_content form").append("<input name=\"home_images\" value=\""+home_images.join(":")+"\" type=\"hidden\"/>");
			}
			if($(".mrda_content form input.fileToUpload").val() || template=="home"){
				ajaxFileUpload($(".mrda_content"),"/handle_static_upload.php",wym_index);
			}else{
				nofileUpload($(".mrda_content"),"/handle_static_upload.php",wym_index);
			}
			return false;
		});
		$("#mrda_static_reset").click(function(){
			overLay();
			_loadPage(script,page);
			return false;
		});

	});
}
function setContactForm(){
	$("a#email").toggle(function(){
		$("#mrda_contactForm").slideDown("slow");
		$(this).text("Show map");
		return false;
	},function(){
		$("#mrda_contactForm").slideUp("slow");
		$(this).text("Use our contact form");
		return false;
	});

	$("input#sendMail").click(function(){
		$(this).attr("disabled","disabled");
		var str = $("#mrda_contactForm form").serialize();
		var msg = false;
		$.ajax({
			type: "POST",
			url: "email.php",
			data: str,
			success: function(msg){
				// Message Sent? Show the 'Thank You' message and hide the form
				if(msg == 'OK'){
					$("#mrda_contact_messageSent").html('Thank you, your message has been sent to MRDA.');
					$("#mrda_contact_messageSent").css("color","#2a2");
					$("#mrda_contact_messageSent").show("slow");
					setTimeout('$("#mrda_contact_messageSent").hide();$("#mrda_contactForm").slideUp("slow");$("#jquery-overlay").remove();$("a#email").trigger("click");$("#mrda_contactForm input[type=text],textarea").val("");$("input#sendMail").removeAttr("disabled");', 3000);
				}else{
					$("#mrda_contact_messageSent").css("color","#d22");
					$("#mrda_contact_messageSent").html(msg);
					$("#mrda_contact_messageSent").show("slow");
					$("input#sendMail").removeAttr("disabled");
				}
			}
		});
		return false;
	});
	

}
function initEditActions(projectid){
	$project_div = $("#p_"+projectid);
	setListSwitch($project_div);
	setMulti($project_div);
	setControls($project_div);
	setBigControls($project_div);

}

$(document).ready(function(){

	initPageActions();
//        fix = new AjaxIframesFixer('ajaxnav');
});
/*
function AjaxIframesFixer(iframeid) {
	this.iframeid = iframeid;
	if (document.getElementById('ajaxnav')) {
		this.fixLinks();

		this.locator = new PageLocator("document.frames['"+this.iframeid+"'].getLocation()", "?hash=");
		this.windowlocator = new PageLocator("window.location.href", "#");
		this.timer = new Timer(this);

		this.delayInit(); // required or IE doesn't fire
	}
}

AjaxIframesFixer.prototype.fixLinks = function (iframeid) {
	var links = document.getElementsByTagName("A");
	for(var i=0; i<links.length; i++) {
		var href = links[i].getAttribute("href");
		var hash = href.substr(href.indexOf("hash=")+5);
		links[i].setAttribute("href", "Javascript:document.getElementById('"+this.iframeid+"').setAttribute('src', 'mock-page.php?hash="+hash+"');");
	}
}

AjaxIframesFixer.prototype.delayInit = function(){
	this.timer.setTimeout("checkBookmark", 100, "");
}
AjaxIframesFixer.prototype.checkBookmark = function(){
	window.location = this.windowlocator.makeNewLocation(this.locator.getHash());
	this.checkWhetherChanged(0);
}
AjaxIframesFixer.prototype.checkWhetherChanged = function(location){
	if(this.locator.getHash() != location) {
		doGetPage(this.locator.getHash());
		window.location = this.windowlocator.makeNewLocation(this.locator.getHash());
	}
	this.timer.setTimeout("checkWhetherChanged", 200, this.locator.getHash());
}
*/
