//various functions to support live 'in-page' editing
//for now this is only included in workspace pages
dojo.require('dijit.Editor');
dojo.require("dijit._editor.plugins.FontChoice");
dojo.require("dijit._editor.plugins.AlwaysShowToolbar");
 dojo.require("dijit.InlineEditBox");
dojo.require('dojo.parser');
 dojo.require("dijit.Dialog");


function activateWorkspaceEditing(){
        //wrapper for things that need to be done
        //when folks enter editing mode in a workspace
        swapInAllEditableContent();
        collapseForEdit();
        resizeForWorkspace();
}

function displayLiveEditControls(){
//activates liveediting on the current page
//returning a dialog box with either login information
//or the editing controls
        
        ie6Check();        
        dojo.disconnect(liveEditLinkConnect);
        var currentPage = location.href;
        currentPage = escape(currentPage);
        
        var liveEditLink = this;
        var liveEditLinkId = this.id;	
        var pageId = liveEditLinkId.substring(10);
        
        var ajax_url = '/admin/ajax/ajax_handler.php?action=get_liveedit_controls&page_id='+pageId;
        ajax_url = ajax_url + '&current_url='+currentPage;

	var kw = {
        url:    ajax_url,
                handleAs:"json-comment-filtered",
        load: function(response){
                error_message = response.error_message;
		 valid_return = response.valid_return;
			  if(error_message){
			      display_error_dialog(error_message);
			  }
			  if(valid_return){
                          //make it no longer clickable
                          dojo.disconnect(liveEditLinkConnect);
                          hasAccess = valid_return['has_access'];
                          controlDiv = valid_return['control_div'];
			  liveEditLink.innerHTML = controlDiv;
                          
                           dojo.addClass(liveEditLink, 'live-edit-box');
                           dojo.removeClass(liveEditLink, 'live-edit-link');
                           

                         
                          if(hasAccess == 1){
                          //hookup the content divs for editing
                                 hookupContentBits();
                                 //hook up items in the new liveedit interface
                           hookupFileUploadDialog();
                           hookupCloseButtons();
                           displayFileList();
                           //squeeze the main content div and the nav over to make room for the liveedit box
                          collapseForEdit();

                          }

              }


        },
        error: function(data){
                alert("There was an error getting editing controls.");
        },
        timeout: 5000
        };

dojo.xhrGet(kw); 

	

}
function makeTextAreaWYSIWYG(contentId){
					// changes  textarea into an wysiwyg one
					//dojo.query('.editFormSubmit').connect('onclick', postEdit);
					var textAreaId = 'textarea'+contentId;
					thiseditFormTextArea =dojo.byId(textAreaId)
				    //console.error(textAreaId);
						    //get the content bit number off this and use it to generate
						    //the id for the rich text box
				var richTextAreaId = 'richTextArea' + contentId;
                                 //for Safari formatBlock doesn't work if we use alwayshowtoolbar
                                if(dojo.isSafari){
                                var newEditor = new dijit.Editor({id: richTextAreaId,
				plugins: ['formatBlock','bold', 'italic','insertOrderedList','insertUnorderedList','indent', 'outdent','subscript', 'superscript'
				], 
				styleSheets: '/styles/editor_style.css'},
				thiseditFormTextArea);
                                }
                                else{
				var newEditor = new dijit.Editor({height: '', id: richTextAreaId,
				plugins: ['formatBlock','bold', 'italic','insertOrderedList','insertUnorderedList','indent', 'outdent','subscript', 'superscript',
				{name: 'dijit._editor.plugins.AlwaysShowToolbar'}], 
				styleSheets: '/styles/editor_style.css'},
				thiseditFormTextArea
				);
                                }

				//then hook up onChange monitorin

				 dojo.connect(newEditor,'onChange',editorHasChanged);
    					 
}

function makeTextAreaHTML(contentId){
//changes textarea into an automatically sized dojo textarea
		dojo.require('dijit.form.Textarea');
	var textAreaId = 'textarea'+contentId;
	thiseditFormTextArea =dojo.byId(textAreaId)
	var richTextAreaId = 'richTextArea' + contentId;

	var newEditor = new dijit.form.Textarea({id:richTextAreaId}, thiseditFormTextArea );
    dojo.connect(newEditor,'onChange',editorHasChanged);

}


function swapInAllEditableContent(){
//this function swaps all divs with class serc-editable
// and id's of form contentId### with an editable version
//of that content
    //dojo.require('dojo.parser');
	dojo.query('.serc-editable').forEach(
		function(thisdiv) {
			thisdiv.activate = swapInEditableContent;
			thisdiv.activate();
		}
	); 
	//end of foreach
	//switch modes for the  liveedit display
	dojo.query(".activateLiveEdit").style("display", "none");
	dojo.query(".deactivateLiveEdit").style("display", "inline");
}



function swapInStaticContent(contentId){
//this function takes contentId and then
//locates the serc-editable div with id of
//contentId###
        fullContentDivId = 'contentId'+contentId;
        contentDiv = dojo.byId(fullContentDivId);
        //make sure it's already active
        contentDivClasses = contentDiv.className;
	if(contentDivClasses.match('serc-editable-active') == null){
		return('');
	}
        //make sure it doesn't have unsaved content
        if(someContentIsDirty() == '1'){
            var error_message = 'Sorry, you may not deactivate editing when you have unsaved changes. <br>';
		error_message = error_message+' Either save changes or reload the page to discard any changes you have made';
		display_error_dialog(error_message);
		return('');
	}
        
      
	//get rid of the hiddenRich field since  reactivation will create one
	//and we don't want multiple ones (as that causes confusion
	var hiddenRichId = 'hiddenRich'+contentId;
	var hiddenRichDiv = dojo.byId(hiddenRichId);
        if(hiddenRichDiv){
                hiddenRichDiv.parentNode.removeChild(hiddenRichDiv);
        }
         
         //base url for getting static content
         var ajax_url = '/admin/ajax/ajax_handler.php?action=get_static_content&content_id=' +contentId;

        //figure out if we're in the admin site
        //and so need to fill the div with a summary
        //or if we're in liveedit and need the whole
        //rendered html for the content bit
        if(contentDivClasses.match('serc-editable-admin') == null){
            //we're in live edit and so we want to get the entire static content
		ajax_url =ajax_url+'&type=fullcontent';
	}
        else{
                ajax_url =ajax_url+'&type=summarycontent';
        }
        dojo.xhrGet( { // ➂
			// The following URL must match that used to test the server.
			url: ajax_url, 
			handleAs: "json-comment-filtered",
			timeout: 10000, // Time in milliseconds
	
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) { 
			 error_message = response.error_message;
			 valid_return = response.valid_return;
			   if(error_message){
			      display_error_dialog(error_message);
			  }
			  if(valid_return){
                          
                                //we should destroy the editorwidget if there is one
                                var richTextAreaId = 'richTextArea' + contentId;
                                dijit.byId(richTextAreaId).destroy();
			 	 contentDiv.innerHTML = valid_return;
			 	 //mark the content div as having been activated so we can avoid trying to activate it again
			 	 dojo.removeClass(contentDiv, 'serc-editable-active');
			 	 
			 	 //remove the content from the hidden form field
                                 //so on future saves we don't try to save this content.
                                 //this is a duplicate of above but 
                                 var hiddenRichId='hiddenRich'+contentId;
                                 var hiddenRichInput = dojo.byId(hiddenRichId);
                                 if(hiddenRichInput){
                                         hiddenRichInput.parentNode.removeChild(hiddenRichInput);
                                 }
                                 //now that we've deactivated this bit we can connect it's onclick event again
                                editAnchorConnectionArray[contentId] = dojo.connect(contentDiv, 'onclick', swapInEditableContent);

                                //deactivate any active links the static text so that all clicks fall through to swapInEditableContent
                                 //this is relevant for liveedit pages
                        
                                 dojo.query("a",contentDiv).forEach(
                                        function(thisanchor2){
                                                thisanchor2.removeAttribute("href");
                                        }
                                )

			  }
			  
			  //return response; 
			},
	
			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) { 
			  //console.error("HTTP status code: ", ioArgs.xhr.status); 
			  return response; 
			  }
			});

         
 	

}


function swapInEditableContent(){
	//this function looks takes the div passed
	//which is either the serc-editable div that we replace
	// with the content which should have id  contentId###
	//or it's parent editanchor which will have id editanchor##
	
	//figure out whether we've got a serc-editable div or an editanchor
	if(this.className=='editanchor'){
		anArray = dojo.query('.serc-editable', this);
		contentDiv = anArray[0];
	}
	else{
		var contentDiv = this;
	}
	var fullContentDivId = contentDiv.id;	
	var contentId = fullContentDivId.substring(9);
	
	//make sure this contentDiv isn't already activated
	//if it is we can just bail
	contentDivClasses = contentDiv.className;
	if(contentDivClasses.match('serc-editable-active') != null){
		return('');
	}
	
    dojo.require('dojo.parser');
	//we'll need a form to save this into
	//check if one already exists
	if(dojo.byId('editForm') == null){
	//there's no form yet so create one
		editForm = document.createElement("form");
		editForm.id = 'editForm';
		editForm.name = 'editForm';
		dojo.addClass(editForm, 'editForm');
		editForm.innerHTML+='<input type="button" onClick="postEdit()" class ="editFormSubmit" id="editFormSubmit"  name="Save" value="Save"/>';
		//we put the editForm into an editFormContainer div that's already in the page
		var editFormContainer = dojo.byId('editFormContainer');
		dojo.place(editForm, editFormContainer, 'first');

		//make a place to track which content bits have been edited
		dirtyContentIds = new Array(0);
        }

        var ajax_url = '/admin/ajax/ajax_handler.php?action=get_content_bit_textarea&content_id=' +contentId;
	dojo.xhrGet( { // ➂
			// The following URL must match that used to test the server.
			url: ajax_url, 
			handleAs: "json-comment-filtered",
			timeout: 10000, // Time in milliseconds
	
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) { 
			 error_message = response.error_message;
			 valid_return = response.valid_return;
			   if(error_message){
			      display_error_dialog(error_message);
			  }
			  if(valid_return){
			 	 contentDiv.innerHTML = valid_return;
			 	 //mark the content div as having been activated so we can avoid trying to activate it again
			 	 dojo.addClass(contentDiv, 'serc-editable-active');
                                 dojo.addClass(contentDiv, 'tundra');

			 	 
			 	 //add a hidden form field in a our edit form labeled
			 	 //by the current contentId.  When we POST the form
			 	 //we'll copy the contents of the textarea into this hidden field
			 	 //so it gets sent with the POST
			 	 var hiddenFieldHTML = '<input type="hidden" id="hiddenRich'+contentId;
			 	 hiddenFieldHTML+= '"  name="hiddenRich'+contentId;
			 	 hiddenFieldHTML+= '" value="">';
			 	 editForm.innerHTML+=hiddenFieldHTML;
			 	 
			  //now that the textarea is in the page 
			  //we can make it wysiwyg
			  //we should make this conditional 
			  
			  dojo.require("dojo.cookie");
			 var richTextToggle = dojo.cookie('richTextToggle');
			  if(richTextToggle == 'html'){
			  	makeTextAreaHTML(contentId);
			  }
			  else{
			  	makeTextAreaWYSIWYG(contentId);
			  }
    		  
			  }
			  
			  return response; 
			},
	
			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) { 
			  //console.error("HTTP status code: ", ioArgs.xhr.status); 
			  return response; 
			  }
			});

 	//now that we've activated this bit we can disconnect it's onclick event so that
 	//it doesn't try to reactivate when people change focus to it
        var handle = editAnchorConnectionArray[contentId];
 	dojo.disconnect(handle);
}


function switchToHtmlView(){
//this function switches the editing interface to html mode
//setting a cookie to record the switch
//and then reloading all active content bits in html, discarding unsaved changes
//in the process.

	//if we have unsaved edits don't allow the change.
	if(someContentIsDirty() == '1'){
            var error_message = 'Sorry, you may not switch between Rich Text and HTML modes when you have unsaved changes. <br>';
		error_message = error_message+' Either save changes or reload the page to discard any changes you have made';
		display_error_dialog(error_message);
		return('');
	}



	dojo.require("dojo.cookie");
	dojo.cookie('richTextToggle','html');
	
	//swap the visibility of the toggle links
	dojo.query("#htmlToggle").style("display", "none");
	dojo.query("#richTextToggle").style("display", "inline");
	
	dojo.query('.serc-editable-active').forEach(
		function(thisdiv) {
			//reset the div to not active so that we can 're' activate it
                        dojo.removeClass(thisdiv, "serc-editable-active");
                        dojo.addClass(thisdiv, "serc-editable");
			//destroy the richtext dijit in it
			var fullContentDivId = thisdiv.id;	
			var contentId = fullContentDivId.substring(9);
			richTextId = 'richTextArea'+contentId;
			richTextWidget = dijit.byId(richTextId);
			richTextWidget.destroy();
			//get rid of the hiddenRich field since the reactivation will create one
			//and we don't want multiple ones (as that causes confusion
			var hiddenRichId = 'hiddenRich'+contentId;
			var hiddenRichDiv = dojo.byId(hiddenRichId);
			hiddenRichDiv.parentNode.removeChild(hiddenRichDiv);
			//not reactivate, which will get us the html version since we've switched the cookie
			thisdiv.activate = swapInEditableContent;
			thisdiv.activate();
		}
	); 


}

function switchToRichTextView(){
//the converse of switchToHtmlView, this function
//switches back to the default richtext view, setting a cookie
//and reloading active content bits

	if(someContentIsDirty() == '1'){
		var error_message = 'Sorry, you may not switch between Rich Text and HTML modes when you have unsaved changes. <br>';
		error_message = error_message+' Either save changes or reload the page to discard any changes you have made';
		display_error_dialog(error_message);
		return('');
	}

	dojo.require("dojo.cookie");
	dojo.cookie('richTextToggle','richtext');
	
	dojo.query("#htmlToggle").style("display", "inline");
	dojo.query("#richTextToggle").style("display", "none");

	dojo.query('.serc-editable-active').forEach(
		function(thisdiv) {
			//reset the div to not active so that we can 're' activate it
			 dojo.removeClass(thisdiv, "serc-editable-active");
                        dojo.addClass(thisdiv, "serc-editable");
			//destroy the textarea dijit in it
			var fullContentDivId = thisdiv.id;	
			var contentId = fullContentDivId.substring(9);
			textareaId = 'richTextArea'+contentId;
			textAreaWidget = dijit.byId(textareaId);
			textAreaWidget.destroy();
			//get rid of the hiddenRich field since the reactivation will create one
			//and we don't want multiple ones (as that causes confusion
			var hiddenRichId = 'hiddenRich'+contentId;
			var hiddenRichDiv = dojo.byId(hiddenRichId);
			hiddenRichDiv.parentNode.removeChild(hiddenRichDiv);
			//now reactivate, which will get us the html version since we've switched the cookie
			thisdiv.activate = swapInEditableContent;
			thisdiv.activate();
		}
	); 

}
function postEdit() {
//looks for form id editForm
//fills all the hiddenrich input's within it with 
//corresponding richtext fields
//and then submits the form
var editForm = dojo.byId('editForm');



//loop through all the serc-editable content bits finding their contentId's
dojo.query('.serc-editable-active').forEach(
	function(thisdiv){
		var fullId = thisdiv.id;
		//we make this non-local so that it fall through for use by updateLastModifiedDetails
		//below which just needs one of the valid contentId's to work

	    contentId = fullId.substring(9);
		var richTextAreaId = 'richTextArea' + contentId;
		var hiddenRichId = 'hiddenRich' + contentId;
		//take their content and move it into the corresponding hiddenrich field in the form.
		var richValue = dijit.byId(richTextAreaId).getValue();
		editForm[hiddenRichId].value = richValue;
		//console.log(richValue);
		markContentClean(contentId);
	
	}
);


//display the 'saving' message
dojo.query("#saved").style("display", "none");
dojo.query(".saving").style("display", "inline");		
var ajax_url = '/admin/ajax/ajax_handler.php?action=update_content';

var kw = {
        url:    ajax_url,
                handleAs:"json-comment-filtered",
        load: function(response){
         error_message = response.error_message;
		 valid_return = response.valid_return;
			  if(error_message){
			      display_error_dialog(error_message);
			  }
			  if(valid_return){
                //display the 'saved' message
                //this assumes there's only one save/saved message for one text box
 				dojo.query(".saving").style("display", "none");
 				dojo.query("#saved").style("display", "inline");
 				dojo.query("#saved").style("opacity", "1.0");
 				//update the list of includes files/image in case we added one
 				displayFileList();
                                displayFormList();
 				updateLastModifiedDetails(contentId);
 				dojo.fadeOut({node:'saved', duration: 5000}).play();
			}
        },
        error: function(data){
                alert("There was an error saving.  Please try again. " + data);
        },
        timeout: 15000,
        form:editForm
        };

dojo.xhrPost(kw); 
}


function displayPastVersions(contentId){
        //this function obtains html describing past versions of this contentId
        //and then adds it into the div contentUndoId*contentId*
        
        //first get the list of old content
          var ajax_url = '/admin/ajax/ajax_handler.php?action=get_revision_list&content_id='+contentId;
		var xhrResults = dojo.xhrGet( { // ➂
			// The following URL must match that used to test the server.
			url: ajax_url, 
			handleAs: "json-comment-filtered",
	
			timeout: 20000, // Time in milliseconds
	
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
			error_message = response.error_message;
		 	valid_return = response.valid_return;
			if(error_message){
			      display_error_dialog(error_message);
			  }
			if(valid_return){
			  var revisionList = valid_return;
                            //start with a close button
         var oldContentDisplay = "<a onClick ='hidePastVersions("+contentId+")' style='padding: 3px; background: #669; color: #fff;'>Past Versions -- close</a>";
        //then wrap th revisonList in a div
           oldContentDisplay = oldContentDisplay+'<div style="border: 2px solid #669; margin-left: 10px; margin-right: 10px; padding:10px;">';
           oldContentDisplay = oldContentDisplay+revisionList+'</div>';
        //
         
         //restyle the toggle so that it is a div
         var undoToggleId = 'contentUndoId'+contentId;
          var undoToggle = dojo.byId(undoToggleId);
          
        //move the div down
        dojo.style(undoToggle, "margin-top", "0");
        dojo.style(undoToggle, "float", "none");


        undoToggle.innerHTML = oldContentDisplay;
                          
                          
                          
                          
                          
                          
			  return revisionList; 
			  }
			},
	
			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) { // ➃
			  this.innerHTML ='Error displaying file list.';
			  return response; // ➅
			  }
			});
	

      
                                   
}

function hidePastVersions(contentId){
      //hides the past version info
       var undoToggleId = 'contentUndoId'+contentId;
       var undoToggle = dojo.byId(undoToggleId);
       
       undoToggle.innerHTML = "<a onClick ='displayPastVersions("+contentId+")'>View Past Versions</a>";
        dojo.style(undoToggle, "margin-top", "-20px");
        dojo.style(undoToggle, "float", "right"); 
                                        
}

function savePageTitle(spanId,newTitle){
//this function saves a changed page title
	var pageId = spanId.substring(9);
	
        //url escape this so things like & aren't seen as new variables in the GET
        newTitle = escape(newTitle);
        
	//display the 'saving' message
	dojo.query("#saved").style("display", "none");
	dojo.query(".saving").style("display", "inline");	
	var ajax_url = '/admin/ajax/ajax_handler.php?action=update_page_title&page_id='+pageId+'&page_title='+newTitle;
	var kw = {
        url:    ajax_url,
                handleAs:"json-comment-filtered",
        load: function(response){
         error_message = response.error_message;
		 valid_return = response.valid_return;
			  if(error_message){
			      display_error_dialog(error_message);
			  }
			  if(valid_return){
                //display the 'saved' message
                //this assumes there's only one save/saved message for one text box
 				dojo.query(".saving").style("display", "none");
 				dojo.query("#saved").style("display", "inline");
 				dojo.query("#saved").style("opacity", "1.0");
 				//update the list of includes files/image in case we added one
 				dojo.fadeOut({node:'saved', duration: 5000}).play();
			}
        },
        error: function(data){
                alert("There was an error saving.  Please try again. " + data);
        },
        timeout: 15000
        };

dojo.xhrPost(kw); 
}


function savePageUrl(spanId,newUrl){
//this function saves a changed page title
	var pageId = spanId.substring(7);
	
	//display the 'saving' message
	dojo.query("#saved").style("display", "none");
	dojo.query(".saving").style("display", "inline");	
	var ajax_url = '/admin/ajax/ajax_handler.php?action=update_page_url&page_id='+pageId+'&page_url='+newUrl;
	var kw = {
        url:    ajax_url,
                handleAs:"json-comment-filtered",
        load: function(response){
         error_message = response.error_message;
		 valid_return = response.valid_return;
			  if(error_message){
			      display_error_dialog(error_message);
			  }
			  if(valid_return){
                //display the 'saved' message
                //this assumes there's only one save/saved message for one text box
 				dojo.query(".saving").style("display", "none");
 				dojo.query("#saved").style("display", "inline");
 				dojo.query("#saved").style("opacity", "1.0");
 				//update the list of includes files/image in case we added one
 				dojo.fadeOut({node:'saved', duration: 5000}).play();
			}
        },
        error: function(data){
                alert("There was an error saving.  Please try again. " + data);
        },
        timeout: 15000
        };

dojo.xhrPost(kw); 
}




function createNewPage(formArray){;
	var ajax_url = '/admin/ajax/ajax_handler.php?action=create_page';
	var newPageDialog = dojo.byId('newPageDialog');
	var newPageAlert = dojo.byId('workspace-newpage-alert');

	var kw = {
        url:    ajax_url,
                handleAs:"json-comment-filtered",
        load: function(response){
         error_message = response.error_message;
		 valid_return = response.valid_return;
			  if(error_message){
			      display_error_dialog(error_message);
			  }
			  if(valid_return){
               //should call something here to update an on-screen display of pages
               //in current module
               //should display a dialog like fileUpload does with the results (url) or some such
			  dojo.style(newPageDialog, "display", "none");
			  dojo.style(newPageAlert, "display", "block");
			  newPageAlert.innerHTML =  "<div class='closeButton'><a>Close</a> <img src='/images/close.png'></div>" + valid_return;
              hookupCloseButtons();
              displayPageList();
              updateLocalNav();
              }


        },
        error: function(data){
                alert("There was an error creating this new page.  Trying again with a different name may be fruitful");
        },
        timeout: 5000,
        form: dojo.byId('newPageForm')
        };

dojo.xhrPost(kw); 

	
}

function uploadFile(){;
//need to fix this url
dojo.require("dojo.io.iframe");

var uploadForm = dojo.byId('uploadForm');
//display an 'upload message
var uploadAlert = dojo.byId('workspace-uploadbox-alert');
uploadAlert.innerHTML = "Uploading File <img src='/images/ajax-loader.gif'>";
dojo.style(uploadAlert, "display", "block");
var fileUploadDialog = dojo.byId('fileUploadDialog');
dojo.style(fileUploadDialog, "display", "none");

//note that the json transport doesn't work here so just use text
	var ajax_url = '/admin/ajax/ajax_handler.php?action=file_upload';
	var kw = {
	    url:    ajax_url,
            handleAs:"text",
        load: function(valid_return){
                                        if(valid_return){
               
			   uploadAlert.innerHTML =  "<div class='closeButton'><a>Close</a> <img src='/images/close.png'></div>" + valid_return;
               hookupCloseButtons();
               displayFileList();
             }
        },
        error: function(data){
                alert("An error occured while uploading.");
        },
        //10 minute upload time out.
        //matches max_input_time for php
        timeout: 600000,
        method: "post",
        form: dojo.byId('uploadForm')
        };
dojo.io.iframe.send(kw); 

	
}



function enlivenPage(pageId){
  //starts the page enlivening process
  //gets info about the envlivening process and
  //displays that along with a link to commit the enlivening
  
  
  var enlivenDivArray = dojo.query('.serc-enliveninfo');
  var enlivenDiv = enlivenDivArray[0];
  var oldEnlivenText = enlivenDiv.innerHTML;
  enlivenDiv.innerHTML = "<img src='/images/ajax-loader.gif'> Making the Page Live";
  
  
  var ajax_url = '/admin/ajax/ajax_handler.php?action=enliven_page&page_id='+pageId;
	var kw = {
        url:    ajax_url,
                handleAs:"json-comment-filtered",
        load: function(response){
         error_message = response.error_message;
		 valid_return = response.valid_return;
			  if(error_message){
			      display_error_dialog(error_message);
                              enlivenDiv.innerHTML = oldEnlivenText;
			  }
			  if(valid_return){
                                 enlivenDiv.innerHTML = valid_return;
			   
			}
        },
        error: function(data){
                alert("There was an error making this page live.  Please try again. " + data);
        },
        timeout: 15000
        };

dojo.xhrGet(kw); 

  
}
function displayFileList(){
//this function fills the <div class='serc-filelist' id='filelist$page_id'></div>
//with a list of file related to this page which it gets from
//via ajax

thisdiv = dojo.query('.serc-filelist').forEach(
	function(thisdiv){

		//display a loading message message

		thisdiv.innerHTML = "<img src='/images/ajax-loader.gif'>";
		var fullId = thisdiv.id;
		var pageId = fullId.substring(8);
                var ajax_url = '/admin/ajax/ajax_handler.php?action=get_file_list&page_id='+pageId;
		
		dojo.xhrGet( { // ➂
			// The following URL must match that used to test the server.
			url: ajax_url, 
			handleAs: "json-comment-filtered",
	
			timeout: 40000, // Time in milliseconds
	
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
			error_message = response.error_message;
		 	valid_return = response.valid_return;
			if(error_message){
			      display_error_dialog(error_message);
			  }
			if(valid_return){
			  thisdiv.innerHTML = valid_return; 
			  return response; 
			  }
			},
	
			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) { // ➃
			  this.innerHTML ='Error displaying file list.';
			  return response; // ➅
			  }
			});
			}
     );

}


function displayFormList(){
//this function fills the <div class='serc-formlist' id='formlist$page_id'></div>
//with a list of forms related to this page which it gets from
//via ajax

thisdiv = dojo.query('.serc-formlist').forEach(
	function(thisdiv){

		//display a loading message message

		thisdiv.innerHTML = "<img src='/images/ajax-loader.gif'>";
		var fullId = thisdiv.id;
		var pageId = fullId.substring(8);
	var ajax_url = '/admin/ajax/ajax_handler.php?action=get_form_list&page_id='+pageId;
		
		dojo.xhrGet( { // ➂
			// The following URL must match that used to test the server.
			url: ajax_url, 
			handleAs: "json-comment-filtered",
	
			timeout: 20000, // Time in milliseconds
	
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
			error_message = response.error_message;
		 	valid_return = response.valid_return;
			if(error_message){
			      display_error_dialog(error_message);
			  }
			if(valid_return){
			  thisdiv.innerHTML = valid_return; 
			  return response; 
			  }
			},
	
			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) { // ➃
			  this.innerHTML ='Error displaying form list.';
			  return response; // ➅
			  }
			});
			}
     );

}

function displayResourceList(){
//this function fills the <div class='serc-resourcelist' id='resourcelist$page_id'></div>
//with a list of cataloged resources referred to in this page which it gets from
//via ajax

thisdiv = dojo.query('.serc-resourcelist').forEach(
	function(thisdiv){

		//display a loading message message

		thisdiv.innerHTML = "<img src='/images/ajax-loader.gif'>";
		var fullId = thisdiv.id;
		var pageId = fullId.substring(12);
	var ajax_url = '/admin/ajax/ajax_handler.php?action=get_resource_list&page_id='+pageId;
		
		dojo.xhrGet( { // ➂
			// The following URL must match that used to test the server.
			url: ajax_url, 
			handleAs: "json-comment-filtered",
	
			timeout: 20000, // Time in milliseconds
	
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
			error_message = response.error_message;
		 	valid_return = response.valid_return;
			if(error_message){
			      display_error_dialog(error_message);
			  }
			if(valid_return){
			  thisdiv.innerHTML = valid_return; 
			  return response; 
			  }
			},
	
			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) { // ➃
			  this.innerHTML ='Error displaying form list.';
			  return response; // ➅
			  }
			});
			}
     );

}
function displayBrowseList(){
//this function fills the <div class='serc-browselist' id='browselist$page_id'></div>
//with a list of cataloged resources referred to in this page which it gets from
//via ajax



thisdiv = dojo.query('.serc-browselist').forEach(
	function(thisdiv){
		//display a loading message message

		thisdiv.innerHTML = "<img src='/images/ajax-loader.gif'>";
		var fullId = thisdiv.id;
		var pageId = fullId.substring(10);
	var ajax_url = '/admin/ajax/ajax_handler.php?action=get_browse_list&page_id='+pageId;
		
		dojo.xhrGet( { // ➂
			// The following URL must match that used to test the server.
			url: ajax_url, 
			handleAs: "json-comment-filtered",
	
			timeout: 20000, // Time in milliseconds
	
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
			error_message = response.error_message;
		 	valid_return = response.valid_return;
			if(error_message){
			      display_error_dialog(error_message);
			  }
			if(valid_return){
			  thisdiv.innerHTML = valid_return; 
			  return response; 
			  }
			},
	
			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) { // ➃
			  this.innerHTML ='Error displaying form list.';
			  return response; // ➅
			  }
			});
			}
     );

}



function displayPageList(){
//this function fills the <div class='serc-pagelist' id='pagelist$page_id'></div>
//with a list of page in this module
//via ajax

thisdiv = dojo.query('.serc-pagelist').forEach(
	function(thisdiv){

		//display a loading message message

		thisdiv.innerHTML = "<img src='/images/ajax-loader.gif'>";
		var fullId = thisdiv.id;
		var pageId = fullId.substring(8);
		//var ajax_url = '/admin/ajax/create_page.php?page_id=' +pageId+'&page_list=yes';
		var ajax_url = '/admin/ajax/ajax_handler.php?action=get_page_list&page_id='+pageId;

		dojo.xhrGet( { // ➂
			// The following URL must match that used to test the server.
			url: ajax_url, 
			handleAs: "json-comment-filtered",
	
			timeout: 10000, // Time in milliseconds
	
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) { 
			
			 error_message = response.error_message;
		 	valid_return = response.valid_return;
			  if(error_message){
			      display_error_dialog(error_message);
			  }
			  if(valid_return){
			  	thisdiv.innerHTML = valid_return; 
			 	 dojo.require('dojo.parser');
			  }
			  return response; 
			},
	
			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) { // ➃
			  this.innerHTML ='Error displaying page list.';
			  return response; // ➅
			  }
			});
			}
     );

}


function updateLastModifiedDetails(contentId){
//this function makes an ajax call to get an array info 
//the last modified date/user for all content bits and the page
//and then updates their display on the current page
	
var ajax_url = '/admin/ajax/ajax_handler.php?action=get_last_modified&content_id='+contentId;

		dojo.xhrGet( { // ➂
			// The following URL must match that used to test the server.
			url: ajax_url, 
			handleAs: "json-comment-filtered",
	
			timeout: 10000, // Time in milliseconds
	
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) { 
			
			 error_message = response.error_message;
		 	valid_return = response.valid_return;
			  if(error_message){
			      display_error_dialog(error_message);
			  }
			  if(valid_return){
			  	//thisdiv.innerHTML = valid_return; 
			  	//need to pull apart the json and fill in the values on the page
			  	lastModifiedArray = valid_return;
			  	for( var index in lastModifiedArray){
			  		var displayString =lastModifiedArray[index];
			  		if(index == 'page'){
			  			//update the last modified info about the page
			  			var pageModifiedSpan = dojo.byId('lastModifiedPageDetails');
			  			pageModifiedSpan.innerHTML = displayString;
			  		}
			  		else{
			  			//index in this case is the contentId
			  			var contentModifiedSpanId = 'lastModified'+index;
			  			var contentModifiedSpan =  dojo.byId(contentModifiedSpanId);
			  		    contentModifiedSpan.innerHTML = displayString;
			  			
			  		}
			  		
			  	}//end loop across lastModifiedArray
			  }
			  return response; 
			},
	
			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) { // ➃
			  this.innerHTML ='Error displaying page list.';
			  return response; // ➅
			  }
			});

}

function updateLocalNav(){
//this function makes an ajax call to get
//a up to date version of the local nav for the current url
//and then replaces the existing <div id='localnav'> innerHTML with the new
	
var thisurl = window.location.href;
var ajax_url = '/admin/ajax/ajax_handler.php?action=get_local_nav&url='+thisurl;

		dojo.xhrGet( { // ➂
			// The following URL must match that used to test the server.
			url: ajax_url, 
			handleAs: "json-comment-filtered",
	
			timeout: 10000, // Time in milliseconds
	
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) { 
			
			 error_message = response.error_message;
		 	valid_return = response.valid_return;
			  if(error_message){
			      display_error_dialog(error_message);
			  }
			  if(valid_return){
                                var localNavDiv = dojo.byId('localnav');
			  	localNavDiv.innerHTML = valid_return; 
			  }
			  return response; 
			},
	
			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) { // ➃
			  this.innerHTML ='Error updating local navigation menu.';
			  return response; // ➅
			  }
			});

}

function showNewPageDialog(){
	var newPageDialog = dojo.byId('newPageDialog');
	dojo.style(newPageDialog, "display", "block");
	dojo.query('.newpagebutton').connect('onclick', createNewPage);

}

function hookupNewPageDialog(){
		dojo.query('#openNewPageDialog').connect('onclick', showNewPageDialog);

}

function showFileUploadDialog(){
        //first close any pre-existing upload result dialog
        var uploadAlert = dojo.byId('workspace-uploadbox-alert');
        dojo.style(uploadAlert, "display", "none");

	var fileUploadDialog = dojo.byId('fileUploadDialog');
	dojo.style(fileUploadDialog, "display", "block");
	//need to hook up form
	//to an ajax submission thing
		dojo.query('.uploadbutton').connect('onclick', uploadFile);
	//probably also need to set encoding on form to work right in IE as per
	//http://dojotoolkit.org/forum/dojo-core-dojo-0-9/dojo-core-support/file-upload-iframe-not-working-ie
	//actually seems to work fine on IE7
}

function hookupFileUploadDialog(){
		dojo.query('#openFileUploadDialog').connect('onclick', showFileUploadDialog);

}


function hookupLiveEdit(){
        //this function hooks up the 'edit' button to the 
        //function that will swap in the editing panel or login info
        liveEditLinkArray = dojo.query('.live-edit-link');
        liveEditLink = liveEditLinkArray[0];
        liveEditLinkConnect = dojo.connect(liveEditLink, 'onclick', displayLiveEditControls);
        }
				
function hookupEditAnchors(){
//this function attaches all editanchor divs to the swapInEditableContent(contentId) call
//for use on admin site.
	editAnchorConnectionArray = new Array();
	dojo.query('.editanchor').forEach(
		function(thisdiv) {
			var fullId = thisdiv.id;
			var contentId = fullId.substring(10);
			editAnchorConnectionArray[contentId] = dojo.connect(thisdiv, 'onclick', swapInEditableContent);
		}
    );

}
function hookupContentBits(){
//an alternative to hookupEditAnchors this hooks serc-editable
//areas directly for use in liveEdit interfaces
	editAnchorConnectionArray = new Array();
	dojo.query('.serc-editable').forEach(
		function(thisdiv) {
			var fullId = thisdiv.id;
			var contentId = fullId.substring(9);
			editAnchorConnectionArray[contentId] = dojo.connect(thisdiv, 'onclick', swapInEditableContent);
                        //also give 'em a black border
                        dojo.addClass(thisdiv, 'serc-editable-clickable');
                        
                        //and there may be active links in the div.  Deactivate them so that clicking swaps in the editable stuff
                        //rather than taking us to a different page
                        dojo.query("a", thisdiv).forEach(
                         function(thisanchor){
                                     thisanchor.removeAttribute("href");
                                }
                        )
		}
    );

}

function closeThis(){
	//just sets the parent div of the caller to display:none;
	//useful for close buttons
        console.log('closing');
	var parentNode = this.parentNode;
	dojo.style(parentNode, "display", "none");
	
}
function hookupCloseButtons(){
	dojo.query('.closeButton').connect('onclick', closeThis);

}

function hookupRichTextToggle(){
 	dojo.query('#htmlToggle').connect('onclick', switchToHtmlView);
 	dojo.query('#richTextToggle').connect('onclick', switchToRichTextView);

}

function display_error_dialog(error_message){
	//function pops up a modalDialog with the error message
	//need to handle the error on the server side (e.g. not logged in or
    //whatnot) in an appropriate way.
    //make a div with the error message in it
    var modalDialogPlaceholder = document.createElement("div");
    dojo.addClass(dojo.body(), "tundra");
	//!!!!need to set style here to tundra so we get right style
	//this doesn't actually place it in the page but making it into a dialog will
	modalDialogPlaceholder.innerHTML = "<p>"+error_message+"</p><div class='modalCloseButton'><a>Close</a> <img src='/images/close.png'></div>";
	//and then turn it into a dijit Dialog
     modalDialog = new dijit.Dialog( {title:"Error", style:"margin:100px; font-size: 11px;"}, modalDialogPlaceholder);
        dojo.query('.modalCloseButton').connect('onclick', modalDialogclose);
    modalDialog.show();
}
function display_alert_dialog(alert_message, title){
	//function pops up a modalDialog with the error message
	//need to handle the error on the server side (e.g. not logged in or
    //whatnot) in an appropriate way.
    //make a div with the error message in it
    var modalDialogPlaceholder = document.createElement("div");
    dojo.addClass(dojo.body(), "tundra");
	//!!!!need to set style here to tundra so we get right style
	//this doesn't actually place it in the page but making it into a dialog will
	modalDialogPlaceholder.innerHTML = "<p>"+alert_message+"</p><div class='modalCloseButton'><a>Close</a> <img src='/images/close.png'></div>";
	//and then turn it into a dijit Dialog
    modalDialog = new dijit.Dialog( {title:title, style:"margin:100px; font-size: 11px;"}, modalDialogPlaceholder);
    dojo.query('.modalCloseButton').connect('onclick', modalDialogclose);
    modalDialog.show();
}

function modalDialogclose(){
 modalDialog.hide();
}
function editorHasChanged(){

	var editorId = this.id
	var contentId = editorId.substring(12);
	markContentDirty(contentId);
}

function markContentDirty(contentId){
//marks the div containing the content as having unsaved changes
//check to make sure it's not already marked as dirty
    if(dojo.indexOf(dirtyContentIds,contentId) == -1){
	//use dojo indexof as IE is borked
        dirtyContentIds.push(contentId);

	
    
        var editanchorId = 'editanchor'+contentId;
        var editanchor = dojo.byId(editanchorId);

        if(!editanchor){
        //for live edit we don't have an editanchor id
             editanchorId = 'contentId'+contentId;
             var editanchor = dojo.byId(editanchorId);
        }
        
        dojo.style(editanchor,"border", "2px solid #f00");
        dojo.style(editanchor,"background", "#ffeaea");
    
        var editFormSubmit = dojo.byId('editFormSubmit');
        dojo.style(editFormSubmit,"border", "3px solid #f00");
        dojo.style(editFormSubmit,"color", "#f00");
    }
        


}

function markContentClean(contentId){
//marks the div containing the content as no longer having unsaved changes

	if(dojo.indexOf(dirtyContentIds,contentId) != -1){
	//use dojo indexof as IE is borked
		var index  = dojo.indexOf(dirtyContentIds,contentId);
		dirtyContentIds.splice(index, 1);
	}
   var editanchorId = 'editanchor'+contentId;
   var editanchor = dojo.byId(editanchorId);
   var inLiveEdit = 'no';
   if(!editanchor){
        //for live edit we don't have an editanchor id
             var inLiveEdit = 'yes';
             editanchorId = 'contentId'+contentId;
             var editanchor = dojo.byId(editanchorId);
        }
   if (editanchor != null){
	dojo.style(editanchor,"border", "2px solid #709670");
	dojo.style(editanchor,"background", "#fff");
        if(inLiveEdit == 'yes'){
             dojo.style(editanchor,"background", "#f3f3f3");
        }
   }

        //reset the color of the save button back to normal
        //if there is no longer any dirty content
        if(someContentIsDirty() == -1){
            var editFormSubmit = dojo.byId('editFormSubmit');
            dojo.style(editFormSubmit,"border", "3px solid #5a5");
            dojo.style(editFormSubmit,"color", "#5a5");
             
        }
                                        
                                        
}

function someContentIsDirty(){
	//this function returns a 1 if we have unsaved changes
	//and -1 if we have no unsaved changes
	
	//first check to see if the dirtyContentIds array exists
	
	if (typeof dirtyContentIds != 'object'){
		//no array for storing dirty content info
		//so we must have no active content bits
		//so we're safe
		return('-1');
	}
	else{
		if(dirtyContentIds.length == 0){
				return('-1');

		}
	}
	return('1');
}
function  ie6Check(){
//this puts up a pop-up with a warning if they are using ie6.
//sets a cookie so that it only happens on the first visit

  if( dojo.isIE && dojo.isIE < 7 ){
  
        dojo.require("dojo.cookie");
        var hasGivenIEWarning = dojo.cookie('hasGivenIEWarning');
        if(hasGivenIEWarning != 'yes'){
			 
  
       var message='We noticed you are using an old version of Internet Explorer . While this page will work with that browser it will be a bit clunky and slow. ';
       message = message+"We recommend you upgrade to a modern browser:";
         message = message+"<a target='_blank' href='http://firefox.org'>Firefox</a>, <a  target='_blank' href='http://www.apple.com/safari/'>Safari</a>, ";
          message = message+"<a  target='_blank' href='http://www.microsoft.com/ie'>Internet Explorer 7</a> etc..). ";
       message = message+="This site and many others will work more smoothly and quickly. We'll wait while you upgrade. It's free and it will save you time in the long run.";
       display_alert_dialog(message, 'Your web browser is ready for retirement');
        dojo.cookie('hasGivenIEWarning','yes');
         }
  }      


}