var ChoiceContentModel = Class.create();
ChoiceContentModel.prototype = {
    initialize: function (instanceName, id, name, actionUrl, mode, type, instructionKey, escapedContentValue, transitive, superUser, listKey, showAlternative, runtimeProps, callback) {
        this.instanceName = instanceName;
        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.runtimeProps=runtimeProps;
        this.callback = callback;
    },

		openChoicesWindow: function (cmsChoiceDialogHandle) {
		  this.dialogHandle = cmsChoiceDialogHandle;
		  this.window = jQuery('#'+cmsChoiceDialogHandle).dialog("open");
          jQuery(".ui-dialog-overlay").bgiframe();
		  setTimeout(this.instanceName + "._buildFormAndPost()",100);
		},

	  _buildFormAndPost: function() {
	  var urlWithRuntimeProps=this.url+'?';
	  var runtimePropsLen = this.runtimeProps.length;
	  for(i=0; i < runtimePropsLen; i += 2) {
	    urlWithRuntimeProps = urlWithRuntimeProps + 'rpName'+i+'='+this.runtimeProps[i]+"&rpValue"+i+'='+this.runtimeProps[i+1]+"&";
	  }
	  
      var form = new Element('form', {
        style: "display:none",
        method: "POST",
        action: urlWithRuntimeProps,
        target: this.dialogHandle
      });
      form = jQuery(form);

      form.append("<input type='hidden' name='id' value='"+this.id+"'/>");
      form.append("<input type='hidden' name='chunkName' value='"+this.chunkName+"'/>");
      form.append("<input type='hidden' name='url' value='"+this.url+"'/>");
      form.append("<input type='hidden' name='mode' value='"+this.mode+"'/>");
      form.append("<input type='hidden' name='type' value='"+this.type+"'/>");
      form.append("<input type='hidden' name='instructionKey' value='"+this.instructionKey+"'/>");
      form.append("<input type='hidden' name='actualContent' value='"+this.actualContent+"'/>");
      form.append("<input type='hidden' name='transitive' value='"+this.transitive+"'/>");
      form.append("<input type='hidden' name='superUser' value='"+this.superUser+"'/>");
      form.append("<input type='hidden' name='listKey' value='"+this.listKey+"'/>");
      form.append("<input type='hidden' name='showAlternative' value='"+this.showAlternative+"'/>");
      form.append("<input type='hidden' name='callback' value='"+this.callback+"'/>");

      var dialogHandle = this.dialogHandle;
      // bind to the form's submit event
      form.submit(function() {
      	   var options = {
             target: '#'+dialogHandle
           };
          jQuery(this).ajaxSubmit(options);
          return false;
      });

      return form.submit();
    }
};

function getCmsChoiceObjectName(name) {
  return "choiceObject_"+ name.replace(/\./g,"_");
}

// 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) {
         var xmlDoc = jQuery(returnValue);
         if(xmlDoc.find("status").text() == "success"){
           if (!(this.callback instanceof Function)) {
               this.callback = eval(this.callback+"(returnValue)");
           } else {
            this.callback(returnValue)
           }
         } else {
           alert("There was a problem with the item you chose.");
           alert(xmlDoc.find("message").text());
         }
    }

}

function choiceUpdatePage() {
  jQuery(".cmsChoiceDialog").dialog("close");
  window.location.reload();
}

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("cmsEditWindow","Please edit your selection",800,400,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("cmsEditWindow","Please edit your selection",800,380,url);
  return false;
}

function closeCmsPopup() {
	var prototypeWindowManager = UI.defaultWM;
	if(prototypeWindowManager) {
		var editWindow = prototypeWindowManager.getWindow('cmsEditWindow');
		if(editWindow) {
			editWindow.close();
		}
	}
}

function updatePage(alertText) {
  var editWindowClosed=false;
	var prototypeWindowManager = UI.defaultWM;
	if(prototypeWindowManager) {
		var editWindow = prototypeWindowManager.getWindow('cmsEditWindow');
		if(editWindow) {
			editWindow.close();
			editWindowClosed=true;
		}
	}
  	
  if(alertText != null) {
  	if(editWindowClosed) {
  		if(jQuery('#cmsFilteredMsg').length <= 0) {
  			var divElement = document.createElement('div');
  			divElement.setAttribute("id","cmsFilteredMsg");
  			var txtNode = document.createTextNode(alertText);
  			divElement.appendChild(txtNode);
  			document.body.appendChild(divElement)
  			jQuery('#cmsFilteredMsg').dialog({modal:true,
  												resizable: true,
  												overlay: {opacity: 0.5,background: "black"},
        										close:function() {
  																	window.location.reload();
        														  }
    										});
  		} else {
  			jQuery('#cmsFilteredMsg').dialog('open');
  		}
  	} else {
  		alert(alertText);
  		window.location.reload();
  	}
  } else {
  	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';

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;
  }
}

function cmsImageJsUpload(upload_field)
{
    var re_text = /\.jpg|\.png|\.bmp|\.gif/i;
    var filename = upload_field.value;

    /* Checking file type */
    if (filename.search(re_text) == -1)
    {
        alert(CmsText.badFileExtension);
        upload_field.form.reset();
        return false;
    }

    upload_field.form.submit();
    return true;
}

function highlightContainer(container) {
  var selectButton = getNodeWithClassNamed(container,'button');
      selectButton.style.top = container.offsetTop + "px";
      selectButton.style.left = container.offsetLeft + "px";
      selectButton.style.visibility = "visible";
      container.style.border = "1px dashed #f00";

}

function dimContainer(container) {
  var selectButton = getNodeWithClassNamed(container,'button');
      selectButton.style.visibility = "hidden";
      container.style.border = "1px solid black";
}

function getNodeWithClassNamed(container, className) {
  var node = container.firstChild;
  do {
    if (node.className == className) {
        return node;
        break;
      }
  } while (node = node.nextSibling);
}

/** 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();
  }
}
**/

