// Variables
var currentAnchor = null;

//On load page, init the timer which check if the there are anchor changes each 300 ms
$(document).ready(function(){
	$("#notificationMessage").corners();
	$("#mediaPane").corners();

	//setInterval("getPage()", 300);	
	$("#uploadForm").validate();
	$('#loginLink').click(function() { 
		var email = $("#email"),
		password = $("#password"),
		allFields = $([]).add(email).add(password),
		tips = $("#validateTips");

	function updateTips(t, errmsgId) {
		$("#"+errmsgId).css("display","none");
		tips.text(t).effect("highlight",{},1500);
	}

	function checkLength(o,n,min,max,errmsgId) {

		if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			updateTips("Length of " + n + " must at least be "+min+" characters.",errmsgId);
			return false;
		} else {
			return true;
		}
	}

	function checkRegexp(o,regexp,n,errmsgId) {

		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass('ui-state-error');
			updateTips(n,errmsgId);
			return false;
		} else {
			return true;
		}

	}
								   
	$("#loginDialog").dialog({
		bgiframe: true,
		autoOpen: false,
		width: 475,
		modal: true,
		buttons: {
			'Log In': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');

				bValid = bValid && checkLength(email,"email",5,50,"validateTips");
				
				//				bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
				// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
				bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"E-mail: username@domain.com","validateTips");
				bValid = bValid && checkLength(password,"password",5,50,"validateTips");
				bValid = bValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allows : a-z and 0-9","validateTips");
				
				if (bValid) {										
					var credentials=new Object();
					credentials.email = email.val();	
					credentials.password = password.val();
					
					$.ajax({
					  type: "POST",
					  url: "index.cfm?/login/",
					  data: $("#loginForm").serialize(),  /* could just pass credentials variable*/
					  cache: false,
					  success:  function(data)
								{	
									$('#dumpData').html(data);
									if($("#userLogged").val() == 1)
									{
										$(this).dialog('close');							
										window.location.reload();
									}
									else
									{
										updateTips("Invalid Log in, please try again.","validateTips");
									}

									
									//$("span#loginStatus").html(data);
									//document.getElementById('loginStatus').innerHTML=data;
								},
						  error: function(XMLHttpRequest, textStatus, errorThrown)
								 {
									$(this).dialog('close');
									alert("Unable to log in");
								 }
					});
				}
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
				$(this).dialog('destroy');
		}
	});
		 }); 
	  $('#uploadLink').click(function() {  
			 $("#uploadDialog").dialog('open');
		 }); 
	 $('#editUrlLink').click(function() {  
			 $("#linkDialog").dialog('open');
		 }); 
	 $('#uploadLink').click(function() {  
			 $("#mediaInfoDialog").dialog('open');
		 }); 
	 
	 $("#AddOption").selectbox();
	 
	 //$("#userTable").tablesorter(); 
	 $("#userTable").tablesorter().tablesorterPager({container: $("#userpager"), size: 20});  
	 
 	 $("#adminMediaTable").tablesorter().tablesorterPager({container: $("#adminMediapager"), size: 20});  
});

function openUploadBox()
{
	var pageId = $("#pageId").val();
	$("#uploadDialog").dialog({
		bgiframe: true,
		autoOpen: true,
		//height: 350,
		width: 475,
		modal: true,
		buttons: {
			'Upload': function() {				
				$.ajaxFileUpload
				  (
					 {
						url:'index.cfm?/saveMedia/' + pageId + '/',
						fileElementId:'uploadfile',
						dataType: 'text',
						success: function (data, status)
						{
							//function is used by each page template and by the picture library
							window.location.reload(); 
							//$("#mediaPageListing").load('index.cfm?/getMediaListforPage/' + $("#pageId").val() + '/', function(data){}); 
							//Old solution to allow info edit after upload
	//						$('#addData').html(data);
//							openMediaInfoDialog();
						},
						error: function (data, status, e)
						{
							alert("Issue Occurred During Upload");
		//					$("#uploadLink").bind("click", openUploadBox);
						}
					 }
				  )
				$("#uploadDialog").dialog('close');
			}, //end upload button
			Cancel: function() {

//				$("#uploadLink").bind("click", openUploadBox);
				$("#uploadDialog").dialog('close');
				//$("#uploadDialog").dialog({ autoOpen: false });
			}
		},//end buttons
		close: function() {
//			 $("#uploadLink").bind("click", openUploadBox);
			 $("#uploadDialog").dialog('destroy');
			//window.location.reload();
//			$("#uploadDialog").dialog('close');
		}
	});

}

$(function() {

/*	This code is if you hide a loading icon on the page */
/*	$("#loading")
      .ajaxStart(function(){
         $(this).show();
      })
      .ajaxComplete(function(){
         $(this).hide();
      });*/		   
});

function AddMedia()
{
	switch($('#AddOption').val())
	{
		case "0":
			alert("Please Select a valid option.");
			break; 
		case "1":
			editMedia(0);
			break;    
		case "2":
			openUploadBox();
			break;
		case "3":
			getExistingMedia();
			break;
		default:
			alert("Please Select a valid option.");
	}
}

function editMedia(mediaId)
{
	$.get('index.cfm?/getMedia/' + mediaId + '/', function(data){
		$('#addData').html(data);
		openMediaInfoDialog();
	});
}

function openMediaInfoDialog()
{
	$("div#mediaInfoDialog").dialog({
		bgiframe: true,
		autoOpen: true,
		//height: 350,
		width: 475,
		modal: true,
		buttons: {
			'Save': function() {	
				$.blockUI();
				var mediaId = $("#mediaId").val();
				$.post('index.cfm?/saveMedia/'+ $("#pageId").val() +'/',$("#mediaInfoForm").serialize(),function(data,status){
					if ($("#pageId").val() == undefined)
					{
						window.location.reload();
					}
					else
					{
						$("#mediaPageListing").load('index.cfm?/getMediaListforPage/' + $("#pageId").val() + '/', function(data){});
					}
				});
				$(this).dialog('destroy').remove();
				$.unblockUI();
			}, //end upload button
			Cancel: function() {
				$(this).dialog('destroy').remove();
			}
		},//end buttons
		close: function() {
			$(this).dialog('destroy').remove();
		}
	});

}

function openLinkDialog()
{
	$("#linkDialog").dialog({
		bgiframe: true,
		autoOpen: true,
		//height: 350,
		width: 475,
		modal: true,
		buttons: {
			'Submit': function() {				
				$.post('index.cfm?/saveMedia/'+$("#pageId").val()+'/',$("#editLinkForm").serialize(),function(data,status){
					//document.getElementById('pageWrapper').innerHTML=data;
					$("#mediaPageListing").load('index.cfm?/getMediaListforPage/' + $("#pageId").val() + '/', function(data){}); 
				});
				$(this).dialog('destroy').remove();
			}, //end upload button
			Cancel: function() {
				$(this).dialog('destroy').remove();
			}
		},//end buttons
		close: function() {
			 $(this).dialog('destroy').remove();
		}
	});

}


function getExistingMedia()
{
/* pass the page id so that existing media doesn't bring back what is already on the page */
	$.get('index.cfm?/getExistingMedia/' + $("#pageId").val() + '/', function(data){
		$('#addData').html(data);
		openExistingMediaDialog();
	});
}

function openExistingMediaDialog()
{
	thisHeight = 550;
	if ($.browser.msie) {
		thisHeight = 900; /* Make is 600 when i deploy */
	}
	
	$("#existingMediaDialog").dialog({
		bgiframe: true,
		autoOpen: true,
		height: thisHeight,
		width: 700,
		modal: true,
		buttons: {
			'Done': function() {
				$(this).dialog('destroy').remove(); 
			}
		},//end buttons
		close: function() {
			$(this).dialog('destroy').remove(); 
		}
	});

}

function AddMediaToPage(mediaId,title)
{
	var thisObject=new Object();
	thisObject.mediaId = mediaId;	

	$.ajax({
	  type: "POST",
	  url: rootDirectory + "index.cfm?/AddMediaToPage/"+$("#pageId").val()+"/",
	  data: thisObject,
	  cache: false,
	  success:  function(data)
				{
					title = title.replace("THISISWHATTOREPLACE","'");
					$("#addedResources").css("display","block");
					$("#existingMediaItem"+mediaId).fadeOut();
					$("#addedResources").append(" | " + title);
					$("#mediaPageListing").load('index.cfm?/getMediaListforPage/' + $("#pageId").val() + '/', function(data){});
				},
	  error: function(XMLHttpRequest, textStatus, errorThrown)
			 {
				 alert("Error adding media to page:"+textStatus+":"+errorThrown);
			 }
	});
}

function removeMediaFromPage(pageId, mediaId)
{
	var thisObject=new Object();
	thisObject.mediaId = mediaId;	

//	return confirm('Are you sure you want to remove this item from the page?');

	$.ajax({
	  type: "POST",
	  url: rootDirectory + "index.cfm?/removeMediaFromPage/"+pageId+"/",
	  data: thisObject,
	  cache: false,
	  success:  function(data)
				{
					$("#mediaItem"+mediaId).fadeOut();
				},
	  error: function(XMLHttpRequest, textStatus, errorThrown)
			 {
				 alert("Error removing media:"+textStatus+":"+errorThrown);
			 }
	});
}

function removeMedia(mediaId)
{
	var thisObject=new Object();
	thisObject.mediaId = mediaId;	
	
	$.ajax({
	  type: "POST",
	  url: rootDirectory + "index.cfm?/removeMedia/",
	  data: thisObject,
	  cache: false,
	  success:  function(data)
				{
					$("#mediaItem"+mediaId).fadeOut();
				},
	  error: function(XMLHttpRequest, textStatus, errorThrown)
			 {
				 alert("Error removing media:"+textStatus+":"+errorThrown);
			 }
	});
}

function editUser(userId)
{
	$.get('index.cfm?/getUser/' + userId + '/', function(data){
		$('#addData').append(data);
		openUserInfoDialog(userId);
	});
}

function updateTips(t, errmsgId) {
	$("#"+errmsgId).css("display","none");
	$("#"+errmsgId).text(t).effect("highlight",{},5000);
}

function checkLength(o,n,min,max,errmsgId) {
	if ( o.val().length > max || o.val().length < min ) {
		o.addClass('ui-state-error');
		updateTips("Length of " + n + " must at least be "+min+" characters.",errmsgId);
		return false;
	} else {
		return true;
	}
}

function checkRegexp(o,regexp,n,errmsgId) {
	if ( !( regexp.test( o.val() ) ) ) {
		o.addClass('ui-state-error');
		updateTips(n,errmsgId);
		return false;
	} else {
		return true;
	}

}

function openUserInfoDialog(userId)
{
	thisHeight = 450; /*firefox height*/
	if ($.browser.msie) {
		thisHeight = 600; /*IE height*/
	}
	
	var email = $("#email"),
		password = $("#password"),
		allFields = $([]).add(email).add(password);
	
	$("#userInfoDialog").dialog({
		bgiframe: true,
		autoOpen: true,
		//height: thisHeight,
		width: 475,
		modal: true,
		buttons: {
			'Save': function() {	
				var uValid = true;
					allFields.removeClass('ui-state-error');
	
					uValid = uValid && checkLength(email,"email",5,50,"errorMessage");
					
					//				uValid = uValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Username may consist of a-z, 0-9, underscores, begin with a letter.");
					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					uValid = uValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"E-mail: username@domain.com","errorMessage");
					uValid = uValid && checkLength(password,"password",5,50,"errorMessage");
					uValid = uValid && checkRegexp(password,/^([0-9a-zA-Z])+$/,"Password field only allows : a-z and 0-9","errorMessage");
			
				if(uValid)
				{
					$.post('index.cfm?/saveUser/'+ userId +'/',$("#userInfoForm").serialize(),function(data,status){
						$('#dumpData').html(data);
						if($("#isValidEmail").val() == 0)
						{
							updateTips("Email address is already assigned to an account.","errorMessage");
						}
						else
						{
							$(this).dialog('close');							
							window.location.reload();
						}
					});
				}
			}, //end upload button
			Cancel: function() {
				$(this).dialog('destroy').remove();
			}
		},//end buttons
		close: function() {
			$(this).dialog('destroy').remove();
		}
	});
				




}




function openDialogBox(id)
{
	$('#'+id).dialog('open');
}


function logout()
{
	$.ajax({
	  type: "POST",
	  url: "index.cfm?/logout/",
	  cache: false,
	  success:  function(data)
				{
					window.location.reload();
					//$("span#loginStatus").html(data);
					//document.getElementById('loginStatus').innerHTML=data;
			
				},
		  error: function(XMLHttpRequest, textStatus, errorThrown)
				 {
					 alert("Error logging out:"+textStatus+":"+errorThrown);
				 }
	});
}

// Dynamically gets the information for the page that was clicked on
function getPage()
{
	 var queryStr;
	 //Check if it has changes  
     if(currentAnchor != document.location.hash){  
		currentAnchor = document.location.hash;  
		currentQuestionMark = document.location.search;

		if(currentQuestionMark.length)
		{
			//var skip2 = currentQuestionMark.substring(2).split('/');

			 //Get the section  
			/* var eventname = skip2[0];              			 
			 var pageId = skip2[1];
			 queryStr ="index.cfm?/"+eventname+"/"+pageId+"/";*/
		}
		else
		{
			$("#pageWrapper").html("<span id='loading'>Loading...</span>");
			//if there is not anchor, the loads the default section  
			 if(!currentAnchor)  
			 {
				// Default Home Page for the entire site
				 queryStr = "index.cfm?/content/homepage/"; 
			 }
			 else  
			 {  
				 /*if(currentQuestionMark.length)
				 {
					var splits = currentQuestionMark.substring(2).split('/');
				 }
				 else
				 {*/
					 //Creates the  string callback. This converts the url to URL/#main&id=2 in URL/?section=main&id=2
					 var splits = currentAnchor.substring(1).split('/');  
				 //}
				 
				 //Get the section  
				 var eventname = splits[0];              			 
				 var pageId = splits[1];
				 queryStr = rootDirectory +"index.cfm?/"+eventname+"/"+pageId+"/";
			 }  
			 $.ajax({
			  url: queryStr,
			  cache: false,
			  success:  function(data)
						{

							document.getElementById('pageWrapper').innerHTML=data;
						},
			  error: function(XMLHttpRequest, textStatus, errorThrown)
					 {
						 alert("Error getting page:"+textStatus+":"+errorThrown);
					 }
			});
		}//end if checking on any variables after question mark
		
		
	
	 } //end if checking on anchor
}

// Saves the page
function savePage(pageId, content)
{ 	
	var thisObject=new Object();
	thisObject.title = 	$("#pTitle").val();	
	thisObject.content = content;
	//gets the choosen parent
	thisObject.ParentId = $("#parentDropDown").val();
	thisObject.toggleArchived = $("#archivedCbx").attr('checked');

/*	var newParentId;
		 $("select#parentDropDown option:selected").each(function () {
			 newParentId= $(this).val();
		 });	*/

	//gets the array of the sorted nav
	var pageList = [];
	var items = $(".subSortedList");
		
    for(var x=0; x<items.length; x++)
    {             
		pageList.push(items[x].id);
    }
	thisObject.pageList = pageList;	

	//displays loading image
	//$("#pageWrapper").html("<span id='loading'>Saving...</span>");	

	$.ajax({
	  type: "POST",
	  data: thisObject,
	  url: rootDirectory + "index.cfm?/savePage/"+pageId+"/",
	  success:  function(data)
					{
		//				document.getElementById('pageWrapper').innerHTML=data;
						window.location.reload();
			//			$("#linkDisplay"+pageId).text(title);	

					},
		  error: function(XMLHttpRequest, textStatus, errorThrown)
				 {
					 alert("Session has expired or error occurred while saving.");
					 window.location.reload();
				 }
	});
	$('#sortNavList').sortable('destroy');
}

function saveNote()
{
	var thisObject=new Object();
	thisObject.message = $("#noteMessage").val();	
	thisObject.active = $("#showMessage").attr('checked');

	$.ajax({
	  type: "POST",
	  data: thisObject,
	  url: rootDirectory + "index.cfm?/saveNote/",
	  success:  function(data)
					{

						document.getElementById('notificationContainer').innerHTML=data;
//						$("#notificationMessage").html(data);	

					},
		  error: function(XMLHttpRequest, textStatus, errorThrown)
				 {
					 alert("Session has expired or error occurred while saving.");
					 window.location.reload();
				 }
	});
}

function CreatePage()
{
		$.ajax({
		  url: "index.cfm?/getPage/0/",
		  cache: false,
		  success:  function(data)
					{
						document.getElementById('pageWrapper').innerHTML=data;
						editPage();	
					},
		  error: function(XMLHttpRequest, textStatus, errorThrown)
				 {
					 alert("Error getting page:"+textStatus+":"+errorThrown);
				 }
		});
}

function editPage()
{
	$("#editPageTitle").css("display","block");
	$("#pageTitle").css("display","none");
	$("#editcontentDiv").css("display","block");
	$("#contentDiv").css("display","none");

	$("#pageArea").css("width","79%");
	$("#mediaPane").css("display","none");
	$("#editPane").css("display","block");
	
	$("#pageSaveBtn").css("display","block");
	$("#pageCancelBtn").css("display","block");
	
	$("#sortNavList").sortable({ 
		placeholder: "ui-selected", 
		revert: true
//		update: function() {alert("this is called"); getOrder(); }
	});

/*tinyMCE.init({
		mode : "textareas",
		theme : "simple",
		editor_selector : "wysiwyg"
	});*/


	$('textarea.fck').fck();
}
function cancelEditPage()
{
	$("#editPageTitle").css("display","none");
	$("#pageTitle").css("display","block");
	$("#editcontentDiv").css("display","none");
	$("#contentDiv").css("display","block");
	
	$("#pageArea").css("width","100%");
	$("#mediaPane").css("display","block");
	$("#editPane").css("display","none");

	$("#pageSaveBtn").css("display","none");
	$("#pageCancelBtn").css("display","none");
	$('#sortNavList').sortable('destroy');
}

function setPageSize(size)
{
	$("#pageArea").css("width",size);
}

/*function ArchivePage()
{
		$.ajax({
		  type: "POST",
		  url: "index.cfm?/toggleArchiveStatus/",
		  cache: false,
		  success:  function(data)
						{
							$("#archiveText").text("Un-Archive");
						},
			  error: function(XMLHttpRequest, textStatus, errorThrown)
					 {
						 alert("Error toggling archive status:"+textStatus+":"+errorThrown);
					 }
		});
}*/

function sortTopNavigation()
{	
	/*Sortable function*/
	$("#nav").sortable({ 
		placeholder: "ui-selected", 
		revert: true 
//		cursor: 'move'  //todo: this cursor isn't showing; fix
//		update: function() {alert("this is called"); getOrder(); }
	});
	$("#nav").css("border","dashed #FF0000");
	$(".top_link").css("cursor","move");
	$('#nav').append("<button id='saveButton' onclick='javascript:saveSortTopNavigation()'>Save</button><button id='exitButton' onclick='javascript:cancelSortTopNavigation()'>Exit</button>");	
}

function saveSortTopNavigation()
{
	var thisObject=new Object();
	
	var pageList = [];
	var items = $(".top");
		
    for(var x=0; x<items.length-1; x++)
    {             
		pageList.push(items[x].id);
    }
	thisObject.pageList = pageList;	

		$.ajax({
		  type: "POST",
		  url: "index.cfm?/saveSortOrder/",
		  data: thisObject,
		  cache: false,
		  success:  function(data)
						{
//							document.getElementById('pageWrapper').innerHTML=data;
						},
			  error: function(XMLHttpRequest, textStatus, errorThrown)
					 {
						 alert("Error saving page content:"+textStatus+":"+errorThrown);
					 }
		});
	
	$("#nav").css("border","none");
	$('#nav').sortable('destroy');
	$('#saveButton').remove();
	$('#exitButton').remove();
	
	$(".top_link").css("cursor","pointer");
}

function cancelSortTopNavigation()
{
	$("#nav").css("border","none");
	$('#nav').sortable('destroy');
	$('#saveButton').remove();
	$('#exitButton').remove();
	
	$(".top_link").css("cursor","pointer");
	// here, we reload the saved order
	//restoreOrder();
}

function getSubNavElements(pageId, oParentId)
{
	var thisTitle = ($("#pTitle").val());

	if(thisTitle.length == 0)
	{
		thisTitle = "* Current Page *";
	}
	var thisObject = new Object;
	parentIdSelection = $("#parentDropDown").val();
	
	//if invalid option in dropdown is selected, switch to the orginal
	if (parentIdSelection == "notvalid")
	{
		parentIdSelection = oParentId
		alert("Invalid selection for Parent Page. Selection cannot be items with background color");
		$("#parentDropDown").val(oParentId);
	}

	//If the selected ParentId is equal to the callin page's oParentId
	if (parentIdSelection == oParentId)
	{
		thisObject.pageId = pageId
	}
	else
	{
		thisObject.pageId = parentIdSelection
	}

		$.ajax({
		  type: "POST",
		  url: "index.cfm?/getSubNavElements/",
		  data: thisObject,
		  cache: false,
		  success:  function(data)
						{	
							$("#subNavElements").html(data);
							$("#sortNavList").sortable({ 
								placeholder: "ui-selected", 
								revert: true
						//		update: function() {alert("this is called"); getOrder(); }
							});

							//if parent selection is not itself, then add it as a subnav
							if (parentIdSelection != pageId || parentIdSelection == 0)
							{
								$("#noElements").remove();
								if (oParentId != parentIdSelection || parentIdSelection == 0)
								{
									$("#subNavHeader").text("Sort Order of New Location");
									$('#sortNavList').append("<li class='subSortedList' id='"+pageId+"'>"+ thisTitle + "</li>");
								}
							}
						},
			  error: function(XMLHttpRequest, textStatus, errorThrown)
					 {
						 alert("Error saving page content:"+textStatus+":"+errorThrown);
					 }
		});
}

function addAdminActionsMenu()
{
	$('#nav').append("<li id='actionMenu' class='top'><a href='' id='products' class='top_link'><span class='down'>Page Actions</span></a><ul class='sub'><li><a href='javascript:CreatePage()' >Create Page</a><li><a href='javascript:editPage();' >Edit Page</a><li><a href='javascript:sortTopNavigation()' >Order Navigation</a><li><a href='javascript:ArchivePage()' >Archive Page</a></ul></li>");
//href='#content/0'
}
/************************** Universal Functions ****************************/
function clearInput(id)
{
	$("#"+id).val(""); 
}
function showDiv(id)
{
	$("#"+id).css("display","block");
}
function hideDiv(id)
{
	$("#"+id).css("display","none");
}
/************************** End Universal Functions ****************************/


















/*
// set the cookie name
var setCookieName = "listOrder";
// set the cookie expiry time (days):
var setCookieExpiry = 1;



// function that writes the list order to a cookie
function getOrder() {
	// save custom order to cookie
	alert("ingetorder");
	$.cookie(setCookieName, $("#nav").sortable("toArray"), { expires: setCookieExpiry, path: "/" });
}

// function that restores the list order from a cookie
function restoreOrder() {
	var list = $("#nav");
	if (list == null) return
		alert("restoreorder");
	// fetch the cookie value (saved order)
	var cookie = $.cookie(setCookieName);
	if (!cookie) return;
	
	// make array from saved order
	var IDs = cookie.split(",");
	
	// fetch current order
	var items = list.sortable("toArray");
	
	// make array from current order
	var rebuild = new Array();
	for ( var v=0, len=items.length; v<len; v++ ){
		rebuild[items[v]] = items[v];
	}
	
	for (var i = 0, n = IDs.length; i < n; i++) {
		
		// item id from saved order
		var itemID = IDs[i];
		
		if (itemID in rebuild) {
		
			// select item id from current order
			var item = rebuild[itemID];
			
			// select the item according to current order
			var child = $("ul.ui-sortable").children("#" + item);
			
			// select the item according to the saved order
			var savedOrd = $("ul.ui-sortable").children("#" + itemID);

			// remove all the items
			child.remove();
			
			// add the items in turn according to saved order
			// we need to filter here since the "ui-sortable"
			// class is applied to all ul elements and we
			// only want the very first!  You can modify this
			// to support multiple lists - not tested!
			$("ul.ui-sortable").filter(":first").append(savedOrd);
		}
	}
}*/
/*
function showResponse(responseText, statusText) {
        alert(responseText);
//				document.getElementById('pageWrapper').innerHTML=r;
        return false;
} 


function showRequest(formData, jqForm, options) {
        var queryString = $.param(formData);
        alert('About to submit: \n\n' + queryString);
        return true;
} */