function setContentManagementStatus(status) {
  var url = "/esuite/control/setContentManagementStatus";
  var pars = new Object();
  pars.timestamp = '1258789576584';
  pars.contentManagementStatus = escape(status);
  var myAjax = new Ajax.Request(
    url, 
    {method: 'get', parameters: pars, onComplete: showContentManagementResponse}
  );
}

function showContentManagementResponse(originalRequest) {
  window.location.reload(true);
}

var windowHandle;

/**
 * This will disable an anchor tag that is around a cms editable tag.
 */
function disableAnchor(obj) {
  if(obj != null) {
    var parentObj = obj.parentNode;
    if(parentObj.nodeName.toUpperCase() == "A") {
      parentObj.href = "javascript: void(0);";
    }
  }
}

var adminLinkOverrideTemplate = new Template('<p>#{link}<\/p>');
	
function disableAnchors(){
  $$("div.admin").each( replaceLinksForAdmin );
  $$("div.powerImage").each( disablePowerImageAnchor );
}

function disablePowerImageAnchor(obj) {
  if(obj != null) {
    if(obj.parentNode != null) {
      if(obj.parentNode.parentNode != null) {
        disableAnchor(obj.parentNode.parentNode);
      }
    }
  }
}

function replaceLinksForAdmin(adminDiv) {
  var linksTotal = adminDiv.getElementsBySelector("a");
  if (linksTotal.length > 0) {
    var linkButton = adminDiv.getElementsByClassName("link")[0];
    if (linkButton) {
      linkButton.style.visibility = "visible";
      linksTotal.each(
        function (anchorElement) {
          anchorElement.onclick = function(){ return false; }
          var linkElement = adminLinkOverrideTemplate.evaluate( { link: anchorElement.href } );	                       
          var linkList = getLinkListOfThisAdminChunk(adminDiv);
          if (linkList) { new Insertion.Bottom(linkList, linkElement) };
        }
      );
    }
  }
}

function addFunctionalityForCMSLinkDisplay() {
  $$("div.admin div.link").each(
    function (linkButton) {
      linkButton.onclick = displayLinkList;
    }
  );
}

function displayLinkList(thisEvent) {
  stopEventBubble(thisEvent);
  var linkList = getLinkListOfThisAdminChunk($(this.parentNode));
  linkList.getElementsByTagName("button")[0].onclick = hideLinkList;
  linkList.onclick = stopEventBubble;

  new Effect.BlindDown(linkList, {duration: .3});  
}
    

    
function hideLinkList(thisEvent) {
  stopEventBubble(thisEvent);
  new Effect.BlindUp($(this.parentNode.parentNode), {duration: .3});
}

function stopEventBubble(thisEvent) {
  //Block event bubbling
  if (!thisEvent) { var thisEvent = window.event };
  thisEvent.cancelBubble = true;
  if (thisEvent.stopPropagation) { thisEvent.stopPropagation() };
}

function getLinkListOfThisAdminChunk(element) {
  return element.getElementsByClassName("linkList")[0];
}

function displayLink() {
}

Event.observe(window, "load", disableAnchors);
Event.observe(window, "load", addFunctionalityForCMSLinkDisplay);

/**
 * Opens the CMS edit window.
 */
function openAdminWindow(contentName, contentChunkToEdit, contentType, obj) {
  if(typeof(obj) != "undefined") {
    disableAnchor(obj);
  }
  if(windowHandle && !windowHandle.closed) { windowHandle.focus() };
  windowHandle = window.open ("/esuite/cms/ContentMain.soa?controller=cms/Content&callBackFunction=updatePage&content.name="+contentName+
                              "&contentType=" + contentType +  "&contentChunkToEdit=" + contentChunkToEdit, 
                              "adminWindow", "status=1,toolbar=0,width=800,height=600,scrollbars=1,resizable=1");
  return false;
}
  
function openAdminPersonalTagWindow(contentName, contentChunkToEdit, contentPartyId, contentAction, contentType, toolset, transitive, maxLength, superUser, runtimeProps, obj, type) {
  if(typeof(obj) != "undefined") {
    disableAnchor(obj);
  }
  if(windowHandle && !windowHandle.closed) windowHandle.focus();
  
  url = "/esuite/cms/ContentMain.soa";
  url = url + "?controller=cms/Content";
  url = url + "&callBackFunction=updatePage";
  url = url + "&content.name="+contentName;
  url = url + "&contentType=" + contentType;
  url = url + "&contentPartyId=" + contentPartyId;
  url = url + "&contentAction=" + contentAction;
  url = url + "&contentChunkToEdit=" + contentChunkToEdit;
  url = url + "&toolset=" + toolset;
  url = url + "&transitive=" + transitive;
  url = url + "&maxLength=" + maxLength;
  url = url + "&superUser=" + superUser;
  url = url + "&type=" + type;
  	  
  for(i=0;i<runtimeProps.length;i+=2) {
    url = url + "&"+runtimeProps[i]+"="+runtimeProps[i+1];
  }
  
  windowHandle = window.open (url,"adminWindow", "status=1,toolbar=0,width=800,height=600,scrollbars=1,resizable=1");
  return false;
}

function updatePage() {
  window.location.reload();
}

function drawCmsEditButtons() {
  // cmsSelectNodeArray is a global value that is created as cms options are added
  for (var cmsI = 0; cmsI < cmsSelectNodeArray.length; cmsI++) {
    var thisSelectNode = cmsSelectNodeArray[cmsI];
    new Insertion.After(thisSelectNode, getCmsEditButton(thisSelectNode.getAttribute("id")));
  }
}

function cmsEditFromSelectField(selectFieldId) {
  var selectField = $(selectFieldId);
  var cmsKeyName  = selectField.options[selectField.selectedIndex].getAttribute("cmsTag");
  var contentChunkToEdit = selectField.options[selectField.selectedIndex].getAttribute("cmsContentChunkToEdit");
  var contentType = selectField.options[selectField.selectedIndex].getAttribute("cmsContentType");
  if (cmsKeyName) {
    openAdminWindow(cmsKeyName, contentChunkToEdit, contentType);
  } else {
    alert("The selected option does not have\na cms key associated with it. \n\nIf this element should be CMS driven,\nplease speak to the administrator.");  
  }
}

function getCmsEditButton(selectFieldId) {
  var callCmsFuntion = "cmsEditFromSelectField('"+selectFieldId+"')";
  return '<div class="edit" style="padding:0 5px;margin:0 8px 0 0;cursor:pointer;border:1px solid #000;display:inline;color:#fff;background:#f00" onclick="'+callCmsFuntion+'">Edit<\/div>';
}

function handleCmsValue(cmsKey, cmsValue, contentChunkToEdit, contentType) {
  var selectNode  = null;
  var selectNodes = document.getElementsByTagName("SELECT");
  var optionNode  = null;
  var oldTextNode = null;

  /**
   * First we need to crawl through the DOM and find this option. 
   */
  for (var i = 0; i < selectNodes.length; i++) {
    selectNode = selectNodes[i];
    var optionNodes = selectNode.options;
    for (var j = 0; j < optionNodes.length; j++) {
      optionNode = optionNodes[j];
      if (optionNode.firstChild && optionNode.firstChild.nodeValue.indexOf(cmsKey) > -1) { 
        oldTextNode = optionNode.firstChild;
        break;
      }
    }
  }

  /**
   * Next, we add a cmsTag attribute to the HTML option tag. 
   * For Example <option value="someValue" cmsTag="my.cms.key">test<\/option>
   */
  optionNode.setAttribute("cmsTag", cmsKey);
  optionNode.setAttribute("cmsContentChunkToEdit", contentChunkToEdit);
  optionNode.setAttribute("cmsContentType", contentType);
    
  /** 
   * Now, we replace our old <option>label<\/option> with the new cms translated value.
   */
  var newTextNode = document.createTextNode(cmsValue);
  optionNode.replaceChild(newTextNode, oldTextNode); 
  
  /** 
   * Next, we check for a duplicate and if none is found, add this option's selectNode to our global selectNode array.
   */
  if (typeof(cmsSelectNodeArray) == "undefined") {
    cmsSelectNodeArray = new Array();
  }
  var selectNodeNotAddedYet = true;
  for (var i = 0; i < cmsSelectNodeArray.length; i++) {
    if (cmsSelectNodeArray[i] == selectNode) {
      selectNodeNotAddedYet = false; 
      break;
    }
  }
  if (selectNodeNotAddedYet) {
    var selectIndex = cmsSelectNodeArray.length;
    cmsSelectNodeArray[selectIndex] = selectNode;
    /** 
     * We must ensure that this <select> field contains an ID that our edit button can call.
     */
    if (!selectNode.getAttribute("id")) {
      selectNode.setAttribute("id", "cmsSelectNodeId."+selectIndex);
    }
  }
    
  /** 
   * Now we must check to ensure that the we don't wipe out any
   * preset onload functions while adding our own. We have to add
   * our edit button in the onload, because of browser rendering issues
   * if we don't wait for the entire page to load.
   */
  if (typeof(cmsOnloadAdded) == "undefined") {
    Event.observe(window, 'load', drawCmsEditButtons);
//    oldOnload = window.onload;
//    window.onload = function () { drawCmsEditButtons(); if (oldOnload) oldOnload(); }
    cmsOnloadAdded = true;
  }
}

/**
 * The following is for cms:choice tag.
 */
function openChoicesWindow(actionUrl,choiceKeyName, mode, chunkType, instructionKey, actualContentValue, transitive, superUser, listKey, showAlternative) {
	changeCmsChoiceFormAction(actionUrl);
	addFieldToCmsChoiceForm('chunkName',choiceKeyName);
	addFieldToCmsChoiceForm('url',actionUrl);
	addFieldToCmsChoiceForm('mode',mode);
	addFieldToCmsChoiceForm('type',chunkType);
	addFieldToCmsChoiceForm('transitive', transitive);
	addFieldToCmsChoiceForm('instructionKey', instructionKey);
	addFieldToCmsChoiceForm('actualContent',actualContentValue);
	addFieldToCmsChoiceForm('superUser', superUser);
	addFieldToCmsChoiceForm('showAlternative', showAlternative);
	if(listKey != null) {
	  addFieldToCmsChoiceForm('listKey', listKey);
	}
    var whandle = window.open('/esuite/shared/blank.html', 'win1',"status=1,toolbar=0,width=800,height=600,scrollbars=1,resizable=1");
  	var form = document.getElementById(choiceFormName)
  	if(form) {
  		form.target='win1';
		var submitString = "document.getElementById(choiceFormName).submit()";
		setTimeout(submitString,1000);
  	}
}

function chooseIt(choiceName, contentName, partyId, openerUrl) {
  //alert("choiceName: " + choiceName + " contentName: " + contentName);
  
    window.location = "/esuite/cms/ContentMain.soa?controller=cms/StoreChoice&choiceName=" + 
                      choiceName +"&contentName="+contentName+"&partyId="+partyId;
    opener.location = openerUrl;
  
}

var choiceFormName='cmsChoiceForm';

function addFieldToCmsChoiceForm(fieldName, fieldValue) {
	var choiceForm = document.getElementById(choiceFormName);
	if(choiceForm) {
		addFieldIfMissing(choiceForm,fieldName, choiceForm.id+fieldName, fieldValue);
	}
}

function changeCmsChoiceFormAction(actionUrl) {
	var choiceForm = addFormIfMissing(choiceFormName);
	if(choiceForm) {
		choiceForm.action=actionUrl;
	}
}

function addFormIfMissing(formName) {
	var form = document.getElementById(formName);
	if(form == null) {
		var formHtml="<form id='"+formName+"' name='"+formName+"' action='' method='POST'><\/form>";
		new Insertion.Top(document.body, formHtml);
	}
	return document.getElementById(formName);
}

function addFieldIfMissing (form, fieldName, fieldId, fieldValue) {
	var elements= Form.getElements(form);
	var found = false;
	for(i=0;i<elements.length;i++) {
		if(elements[i].name==fieldName) {
			found=true;
		}
	}
	if(!found) {
		var elementHtml="<input type='hidden' id='"+fieldId+"' name='"+fieldName+"' value=''/>";
		new Insertion.Top(form,elementHtml);
	}
	document.getElementById(fieldId).value=fieldValue;
}

function cmsFunction(func) {
  // used to "work around" onclicks on elements that wrap the admin div
  // using this method to prevent the need to traverse the entire DOM
  
  if (!false) {
    func();
  }
}