var ChoiceContentModel = Class.create();
ChoiceContentModel.prototype = {
    initialize: function (id, name, actionUrl, mode, type, instructionKey, escapedContentValue, transitive, superUser, listKey, showAlternative, defaultChoiceKey, callback) {
        this.id = id;
        this.chunkName = name;
        this.url = actionUrl;
        this.mode = mode;
        this.type = type;
        this.instructionKey = instructionKey;
        this.actualContent = escapedContentValue;
        this.transitive = transitive;
        this.superUser = superUser;
        this.listKey = listKey;
        this.showAlternative = showAlternative;
        this.callback = callback;
        this.defaultChoiceKey = defaultChoiceKey;
    },
    
    getQueryString: function() {
        
        var hashedValues = $H({
            id: this.id,
            chunkName: this.chunkName,
            url: this.url,
            mode: this.mode,
            type: this.type,
            instructionKey: this.instructionKey,
            transitive: this.transitive,
            superUser: this.superUser,
            showAlternative: this.showAlternative,
            defaultChoiceKey: this.defaultChoiceKey
        });
        if (this.listKey != null) hashedValues.listKey = this.listKey;
        if (this.callback) hashedValues.callback = this.callback;
        return hashedValues.toQueryString();
    }
}

// ie hack - for some reason an _extended="true" attribute is appended to the actualContent when IE's innerHTML is called
// just sanitizing it.
function _extendedIESanitize(serializedHtml) {
  var serializedHtml = serializedHtml.replace(/_extended="true"/g, "");
  return serializedHtml;
}


var ChoiceResponseHandler = Class.create();
ChoiceResponseHandler.prototype = {
    initialize: function(callbackFunction) {
        this.callback = callbackFunction;
    },
    execute: function(returnValue) {
         Dialog.closeInfo();
         var xmlDoc = returnValue.responseXML.documentElement;
         var statusNode = xmlDoc.getElementsByTagName("status")[0];
         var messageNode = xmlDoc.getElementsByTagName("message")[0];
         var statusValue = statusNode.firstChild.nodeValue;
         if(statusValue=='success'){
                if (!(this.callback instanceof Function)) {
                    this.callback = eval(this.callback+"(returnValue)");
                } else { 
                 this.callback(returnValue)
                }
         } else {
           var messageNodeFirstChild = messageNode.firstChild;
                 if(messageNodeFirstChild != null) {
             alert(messageNodeFirstChild.nodeValue);
           }
         }
    }
    
}

function setContentManagementStatus(status, context, sysTimeInMillis) {
  var url = context+"/control/setContentManagementStatus";
  var pars = new Object();
  pars.timestamp = sysTimeInMillis;
  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;
  /*
  var lis = linkListUL.getElementsByTagName("p");
  for (var i = 0; i < lis.length; i++) {
    lis[i].onclick = getURLWhileSquashingEventBubble;
    }
  */
  new Effect.BlindDown(linkList, {duration: .3});  
}
    
/*
function getURLWhileSquashingEventBubble(thisEvent) {
  stopEventBubble(thisEvent);
  alert(this.firstChild.textContent);
  document.location.href = this.firstChild.textContent;
}
*/
    
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);
  }
  var windowUrl = "/esuite/cms/ContentMain.soa?controller=cms/Content&callBackFunction=updatePage&content.name=" + contentName + "&contentType=" + contentType +  "&contentChunkToEdit=" + contentChunkToEdit + "&type=text";
  windowHandle = prototypeWindowUrl("adminWindow","CMS Admin",800,525,windowUrl);
  return false;
}
  
function openAdminPersonalTagWindow(contentName, contentChunkToEdit, contentPartyId, contentAction, contentType, toolset, transitive, maxLength, superUser, runtimeProps, obj, type) {
  if(typeof(obj) != "undefined") {
    disableAnchor(obj);
  }
  
  /*
  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;
  */
  url = "/esuite/cms/ContentMain.soa?controller=cms/Content&callBackFunction=updatePage&content.name="+contentName+ "&contentType=" + contentType + "&contentPartyId=" + contentPartyId + "&contentAction=" + contentAction + "&contentChunkToEdit=" + contentChunkToEdit + "&toolset=" + toolset + "&transitive=" + transitive + "&maxLength=" + maxLength + "&superUser=" + superUser + "&type=" + type;
      
  var runtimePropsLen = runtimeProps.length;
  for(i=0; i < runtimePropsLen; i += 2) {
    url = url + "&"+runtimeProps[i]+"="+runtimeProps[i+1];
  }
  windowHandle = prototypeWindowUrl("adminWindow","CMS Admin",700,450,url);
  return false;
}

function updatePage() {
  Windows.closeAll();
  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;
  }
}


var choiceFormName='cmsChoiceForm';
/**
 * The following is for cms:choice tag.
 */
function openChoicesWindow(choiceContentModel) {
    var whandle = prototypeWindowUrl("cmsChoiceWindow","CMS Admin",800,400,choiceContentModel.url + "?" + choiceContentModel.getQueryString());
}

function addFieldIfMissing (form, fieldName, fieldId, fieldValue) {
    var elements= Form.getElements(form);
    if(!elements[fieldName]) {
        alert("field named "+fieldName+" was missing!");
        var elementHtml="<input type='hidden' id='"+fieldId+"' name='"+fieldName+"' value=''/>";
        new Insertion.Top(form,elementHtml);
    }
    document.getElementById(fieldId).value=fieldValue;
}

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

/** Couldn't find anywhere this is used - if no flags are raised in the next week, delete this - Jason - 2008-06-05
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
  <c:set var="managementOn" value="false" />
  <c:if test="cmsuser.isContentManagementOn == 'true'">
    <c:set var="managementOn" value="true" />
  </c:if>
  if (!<c:out value="${managementOn}" />) {
    func();
  }
}
**/


