var apos = "'";
function popupPrompt(title, msg1, msg2, prompt, type, path, admin)
{
  var actionUrl = admin;
  if (admin == null || admin == '') {
    actionUrl = 'admin';
  }
  strAttr = "status:no;dialogWidth:400px;dialogHeight:300px;help:no;scrollbar:no;";
  strAction = actionUrl + "?action=popup&popupTitle="+title
    + "&popupMsg1=" + msg1
    + "&popupMsg2=" + msg2
    + "&popupPrompt=" + prompt
    + "&popupType=" + type
    + "&path=" + path;
  return showModalDialog(strAction, document, strAttr);
  //return window.open(url, 'modal', params);
}



function appendParam(param, openWindow) {
 var loc = '' + location;
 if (loc.indexOf('?')!= -1) {
   loc = loc + '&' + param ;
 }
 else {
   loc = loc + '?' + param ;
 }
 if (openWindow) {
   window.open(loc,'_blank','status=no,location=no,menubar=no.menubar=no,width=1024,height=768,scrollbars=yes,resizable=yes');
 }
 else {
  location = loc;
 }
}



/* the next 3 methods are new and currently only used on advanced search results page */
function getURLParam(strParamName){
 var strReturn = "";
 var strHref = window.location.href;
 if ( strHref.indexOf("?") > -1 ){
   var strQueryString = strHref.substr(strHref.indexOf("?"));
   var aQueryString = strQueryString.split("&");
   for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
     if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
       var aParam = aQueryString[iParam].split("=");
       strReturn = aParam[1];
       break;
     }
   }
 }
 return unescape(strReturn);
}

function setNewParamVal(url, param, newVal){
var paramIndex = url.indexOf(param) + param.length;
var temp = url.substring(paramIndex);
var tempIndex = temp.indexOf('&');
if(tempIndex > -1){
  url = url.substring(0,paramIndex) + newVal + temp.substring(tempIndex);
}
else{
  url = url.substring(0,paramIndex) + newVal;
}
return url;
}

function sortColumn(sortField,swapDefaultSortOrder){
  var url = window.location.href;
  var firstSortOrder =  (sortField=='ModificationDate' || swapDefaultSortOrder !='false')? 'descending' : 'ascending';  //the default
  var secondSortOrder = (sortField=='ModificationDate' || swapDefaultSortOrder !='false')? 'ascending' : 'descending';
  
 if(getURLParam("sortField") != ''){
   if(getURLParam("sortField") == sortField){
     var currentSO = getURLParam("sortOrder");
     if(currentSO == firstSortOrder){
       url = setNewParamVal(url, '&sortOrder=', secondSortOrder);
     }
     else{
       url = setNewParamVal(url, '&sortOrder=', firstSortOrder);
     }
   }
   else{
     url = setNewParamVal(url, '&sortField=', sortField);
     url = setNewParamVal(url, '&sortOrder=', firstSortOrder);
   }

   if(url.indexOf("&optimize=") > -1){
     if(sortField == 'WfState'){
       url = setNewParamVal(url, '&optimize=', 'yes');
     }
     else{
       url = setNewParamVal(url, '&optimize=', '');
     }
   }
   else{
     if(sortField == 'WfState'){
       url = url + '&optimize=yes';
     }
   }
 }
 else{
   /* by default, search results are already sorted down by score  */
   url = url + '&sortField=' + sortField + '&sortOrder=' + firstSortOrder;

   if(sortField == 'WfState'){
     url = url + '&optimize=yes';
   }
 }
 location.href = url;
}

/* JJ-2008.1.23: this function is used for search result column only to submit a form.  used byte sortable column links only.*/
function sortSearchResultCol(sortField,swapDefaultSortOrder){
  var firstSortOrder =  (sortField=='ModificationDate' || swapDefaultSortOrder !='false')? 'descending' : 'ascending';  //the default
  var secondSortOrder = (sortField=='ModificationDate' || swapDefaultSortOrder !='false')? 'ascending' : 'descending';
  var preSortField = document.doc_search_results.sortField.value;
  
 if(preSortField != ''){
   if(preSortField == sortField){
     var currentSO = document.doc_search_results.sortOrder.value;
     if(currentSO == firstSortOrder){
       document.doc_search_results.sortOrder.value = secondSortOrder;
     }
     else{
       document.doc_search_results.sortOrder.value = firstSortOrder;
     }
   }
   else{
     document.doc_search_results.sortField.value = sortField;
     document.doc_search_results.sortOrder.value = firstSortOrder;
   }

   if(sortField == 'WfState'){
     document.doc_search_results.optimize.value = 'yes';
   }
   else{
     document.doc_search_results.optimize.value = '';
   }
 }
 else{
   /* by default, search results are already sorted down by score  */
   document.doc_search_results.sortField.value = sortField;
   document.doc_search_results.sortOrder.value = firstSortOrder;

   if(sortField == 'WfState'){
     document.doc_search_results.optimize.value = 'yes';
   }
 }
 
/*  var ttt = 'path';
 var pppp = 'value';
 var ueMode = 'getCheckedItems'; */
 
 /* JJ-2008.2.5: get a list of checked items separated by | in a string and set it to hidden field, "checkboxDoc" */
 var serCheckBoxes = cmsUI.serializeCheckedBoxes({name:'path', property:'value' , ueMode:'getCheckedItems'}); 
 if($('cbRootbox_Search').checked == true){
   serCheckBoxes = $('cbRootbox_Search').id + "|"+ serCheckBoxes;
 }
 document.doc_search_results.checkboxDoc.value = serCheckBoxes;
 document.doc_search_results.submit();
}


function encodeRedirect()
{
  var str = "" + window.location;
  str = str.replace(new RegExp("\&","g"),"\|");
  str = str.replace(/=/g,"~");
  str = str.replace(/\?/g,"!");
  return str;
}


function displayPopup(path, params, o) {
  xShowDialog('/staging'+path, o, params);
}

function getMultiValue(sel, req)
{
  var result = "";
  for (var i=0; i<sel.length; i++) {
    if (sel[i].selected && sel[i].value != '') {
      result += sel[i].value + " | ";
    }
  }
  return result;
}

function getMultiValueCheckbox(element)
{
  return getMultiValueCheckboxWithForm(element.form, element.name);
}

function getMultiValueCheckboxWithForm(f,name)
{
  var result = "";
  for (var i=0; i<f.elements.length; i++) {
    if (f.elements[i].name == name && f.elements[i].checked) {
      result += f.elements[i].value + " | ";
    }
  }
  return result;
}

function updateParentOrNew(url)
{
  if (window.opener != null) {
    window.opener.location = url;
  }
  else {
    open(url,'_blank');
  }
}

function validFilename(path)
{
  if (path == null || path == '') {
    alert("The supplied filename is invalid, it cannot be empty.");
    return false;
  }
  return true;
}

function validDirectoryName(path)
{
  return validFilename(path);
}

function validBranchname(form,string,field,showAlert)
{
  var path = field.value;

  if (path == null ||
      path == ''   ||
      path.indexOf('"') != -1 ||
      path.indexOf("'") != -1 ||
      path.indexOf('<') != -1 ||
      path.indexOf('>') != -1 ||
      path.indexOf('#') != -1 ||
      path.indexOf('&') != -1 ||
      path.indexOf(':') != -1 ||
      path.indexOf('@') != -1 ||
      path.indexOf('*') != -1 ||
      path.indexOf('[') != -1 ||
      path.indexOf(']') != -1 ||
      path.indexOf('/') != -1 ||
      path.indexOf('\\') != -1 ||
      path.indexOf('(') != -1 ||
      path.indexOf(')') != -1 ||
      path.indexOf('%') != -1 ||
      path.indexOf(' ') != -1 ||
      path.indexOf('_') != -1 ||
      path.indexOf('|') != -1
      )  {
    Element.addClassName(field,'warning');

    if (showAlert!='0') {
      alert("The supplied Branch Name is invalid. Please remove any special characters and try again.");
      //new Form.Observer (form, 2, validBranchname(form,string,field,0) );
    }

    return false;
  }
  Element.removeClassName(field,'warning');
  return true;
}


var newWin;
function appendParam(param, openWindow) {
  loc = cmsUI.buildUrlParams(param);
  if (openWindow) {
   newWin = window.open(loc,'newWin','status=no,location=no,menubar=no.menubar=no,width=800,height=600,scrollbars=yes,resizable=yes');
  }
  else {
  location = loc;
  }
  
  /* AT:Not quite ready yet
  Event.observe(newWin, 'unload', function(){
  window.console.dir(newWin);
  if(newWin.document.URL!='about:blank'){
    //alert('closed fo sho!!');
    //setCMSSiteVar('preview','');
  }
  }); */
}


//{{{ var branchAjaxActions = {
var branchAjaxActions = {
  updateStatus:'',
  getClassName:'',
  successUpdateFromAjax:false,
  
  branchQuickChange:function(obj){
    var branchId = obj.id;
    var thisUid = CoreSiteVars.this_user.substr(CoreSiteVars.this_user.indexOf('-')+1);
    var changeUp = cmsUI.sendAsync({
      params:'action=UA-update-user&uid='+thisUid+'&refreshURL=&cmfcurrentBranch='+branchId,
      onLoad:function(){
        var msgArea = $('lightbox_msg');
        msgArea.innerHTML = "Changing branch, please wait...";
        msgArea.style.color = '#333';
        msgArea.style.background = '#fff';
      },
      onSuccess:function(){
        location.reload();
        //window.close();
      }
    });
  },
  
  //{{{ branchAjaxHandler:function(options){
  branchAjaxHandler:function(options){
    /*
      options is currently set to accept the following:
       - url                     - (used for Ajax.Request url - defaults to /admin)
       - params                  - (used for Ajax.Request parameters)
       - evalScripts             - (whether or not you want to do anything with the js that gets returned in the admin action response)
       - onLoad|onSuccess|onFail - (can be passed as functions on those events)
    */
    var adminUrl = (options.url)? options.url : '/admin';
    var params   = (options.params)? options.params : 'action=update-branch';

    if($('branchAdminActions')){
      try{
        $('branchAdminActions').disable()
      }
      catch(err){
        try{
          Form.disable($('branchAdminActions'))
        }
        catch(err){
          if(window.console)console.log(err);
        }
      }
    }

    var branchAction = new Ajax.Request(adminUrl,{
        asynchronous:true,
        method:'post',
        evalScripts:options.evalScripts,
        parameters:params,
        onLoading:(options.onLoad) ? options.onLoad : cmsUI.showAlert('Performing Branch Action'),
        onSuccess:(options.onSuccess) ? options.onSuccess : cmsUI.showAlert(),
        onFailure:function(){
          if(options.onFail){
            options.onFail;
          }
          else{;
            alert("the branch action has failed");
          }
        }
      });
  }, //}}}

  //{{{ branchSummaryQuery:function(options)
  branchSummaryQuery:function(options){
    /*
      options is currently set to accept the following:
       - updateContainer         - (html element for Periodic Update function)
       - url                     - (used for Ajax.Request url - defaults to /admin)
       - params                  - (used for Ajax.Request parameters)
       - evalScripts             - (whether or not you want to do anything with the js that gets returned in the admin action response)
       - freq                    - (how often the updater gets called)
       - decay                   - (the rate of decay for the frequency of the calls)
    */
    var adminUrl   = (options.url)? options.url : '/admin';
    var params     = (options.params)? options.params : 'action=branch-info-summary&ajaxBranchAction=yes';
    var freq       = (options.frequency)? options.frequency : 15;
    var decay      = (options.decay)? options.decay : 1;
    var evScripts  = (options.evalScripts==false)? false : true;
    var periodic   = (options.periodic==true)? true : false;
    var async      = (options.async)? options.async : true;

    switch(periodic) {
      case true:
        branchAjaxActions.updateStatus = new Ajax.PeriodicalUpdater(options.updateContainer, adminUrl, {
          asynchronous:async,
          evalScripts:evScripts,
          parameters:params,
          method:'post',
          frequency:freq,
          decay:decay
        });

        break

      case false:
        if(typeof(branchAjaxActions.updateStatus) == 'object') branchAjaxActions.updateStatus.stop();
        cmsUI.sendAsync(options);
        break

    }
  }, //}}}

  //{{{ branchAutomaticMessager:function(options)
  branchAutomaticMessager:function(options){
    
    branchAjaxActions.getClassName    = options.getClass;
    var allMessageAreas = $$('.'+branchAjaxActions.getClassName);
    var hasParams       = (options.params)?options.params:false;
    var buildAsync      = (options.buildAsync)?options.buildAsync : true;
    //console.log(allMessageAreas);
    $A(allMessageAreas).each(function(noticeArea){
      var messageElem   = $(noticeArea.id);
      var branchId      = messageElem.id.substr(messageElem.id.indexOf('_')+1);
      messageElem.branchId = branchId
      options.params     = (hasParams) ? options.params+messageElem.branchId : 'action=branch-details&tag='+messageElem.branchId+'&ajaxBranchAction=yes';
      messageElem.params = options.params;
      options.updateElem = messageElem;
      options.async      = true;
      
      if(!options.onLoad){
        options.onLoad = function(){};
      }
      if(!options.onSuccess){
        options.onSuccess = function(){};
      }
      if(!options.onFail){
        options.onFail = function(){
          if(typeof(messageElem.async.stop == 'function')){messageElem.async.stop();}
        };
      }
      if(!options.onException){
        options.onException = function(){
          if(typeof(messageElem.async.stop == 'function')){messageElem.async.stop();}
        };
      }
      
      if(buildAsync == true) {messageElem.async  =  new cmsUI.sendAsync(options);}
      
      messageElem.addToQueue = function(event){
        //RT-30300 - check thatw this is always happening
        event.cancelBubble   = true;
        messageElem.updateReady = $('cb_'+branchId).checked;
        if(messageElem.updateReady == true){
          Element.addClassName(messageElem, 'addtoqueue');
          messageElem.async.stop();
        }
        else{
          Element.removeClassName(messageElem, 'addtoqueue');
          messageElem.async.start();
        }
        
      }
      
      messageElem.updateBranch = function(updatedOptions){
        
        var timeout = (updatedOptions.timeout)? updatedOptions.timeout : false;
        var chained = (updatedOptions.chained)? updatedOptions.chained : false;
        
        updatedOptions.onSuccess = function(){
          messageElem.updateReady = false;
          if(Element.hasClassName(messageElem, 'addtoqueue')){
            Element.removeClassName(messageElem, 'addtoqueue');
            Element.addClassName(messageElem, 'updateinprogress');
            messageElem.updateInProgress = true;
          }
          
          if(messageElem.lastinqueue){
            if(updatedOptions.refreshOnSuccess){
              console.log("refreshing");
              location.href = updatedOptions.refreshOnSuccess;
            }
            else{
              if(timeout && chained){
                branchAjaxActions.vars.rebuildOptions = options;
                window.setTimeout('branchAjaxActions.branchAutomaticMessager(branchAjaxActions.vars.rebuildOptions)',timeout);
              }
              else{
                branchAjaxActions.branchAutomaticMessager(options);
              }
            }
          }
          else{
            branchAjaxActions.updateCheckedBranches({
              getClass:'addtoqueue',
              stopAll:'no',
              timeout:timeout,
              chained:true,
              refreshOnSuccess:updatedOptions.refreshOnSuccess
            });
          }
        }
        updatedOptions.onLoad = function(){
          Element.addClassName(messageElem, 'branchactivity');
          if($('branchNotice_'+branchId)){
            $('branchNotice_'+branchId).innerHTML = 'Updating Branch, please wait...';
          }
        }
        updatedOptions.onException = function(){}

        if(timeout && chained){
          branchAjaxActions.vars.branchCheckoutOptions = updatedOptions;
          window.setTimeout('cmsUI.sendAsync(branchAjaxActions.vars.branchCheckoutOptions)',timeout);
        }
        else{
          var update = new cmsUI.sendAsync(updatedOptions);
        }
      }
      
      options.params = (hasParams) ?  hasParams : null;
    });
  }, //}}}
  
  //{{{ addAlltoQueue:function(options){
  addAlltoQueue:function(options){
    branchAjaxActions.getClassName    = options.getClass;
    var allMessageAreas = $$('.'+branchAjaxActions.getClassName);
    var checked         = options.checked;
    var stopAll         = (options.stopAll)? options.stopAll : true;
    //console.log("adding all to queue");
    //console.log(allMessageAreas);
    
    $A(allMessageAreas).each(function(noticeArea){
      var messageElem   = $(noticeArea.id);
      var branchId      = messageElem.id.substr(messageElem.id.indexOf('_')+1);
      
      messageElem.updateReady = checked;
      Element.addClassName(messageElem, 'addtoqueue');

        if(stopAll==true){
          if(messageElem.updateReady == true){
            messageElem.async.stop();
          }
          else{
            messageElem.async.start();
          }
        }
    });
  }, //}}}
  
  //{{{ updateCheckedBranches:function(options)
  updateCheckedBranches:function(options){
    var params              = (options.params)? options.params : '/admin?action=update-branch&tag='
    var stopAll             = (options.stopAll)? options.stopAll : true;
    var allMessageAreas     = $$('.'+options.getClass);
    var refreshOnSuccess    = (options.refreshOnSuccess)? options.refreshOnSuccess : false;
    var timeout             = (options.timeout)? options.timeout : false;
    var chained             = (options.chained)? options.chained : false;
    
    if(stopAll==true){
      cmsUI.stopAllAjax({
        getClass:branchAjaxActions.getClassName,
        suspend:true
      });
    }
    
    var x = 0;
    if(allMessageAreas){
      $A(allMessageAreas).each(function(noticeArea){
        
        var messageElem  = $(noticeArea.id);
        var branchId     = messageElem.id.substr(messageElem.id.indexOf('_')+1);
        
        if(x == allMessageAreas.length-1){
          messageElem.lastinqueue = true;
        }
        
        if($('branchNotice_'+branchId)){
          $('branchNotice_'+branchId).innerHTML = 'Added to queue, please wait...';
        }
        
        if(x == 0 || allMessageAreas[x-1].updateInProgress || allMessageAreas[x].updateSuccess){
          if(messageElem.updateReady){
            messageElem.updateBranch({
              params:params+branchId,
              refreshOnSuccess:refreshOnSuccess,
              timeout:timeout,
              chained:chained,
              stopAll:'no'
            })
          }
        }
        x++;
      });
    }
    
  }, //}}}
  
  //{{{ updateSelectBranches:function(options)
  updateSelectBranches:function(options){
    var classNames      = options.classNames;
    var useId           = (options.useId)? options.useId : false;
    var useImg          = (options.useImg)? options.useImg : false;
    var messageElem     = (options.messageElem)? options.messageElem : false;
    var allBranches     = (useId)? new Array(document.getElementById(useId)) : $A($$('.'+classNames));
    var refresh         = (options.refreshOnSuccess)?options.refreshOnSuccess:false;
    var updatedBranches = 0;
    
    
    //cmsmessage('Updating All Branches, please wait...')
    
    allBranches.each(function(branch){
      var branchId = branch.id;
      options.params = 'action=update-branch&tag='+branchId;
      options.periodic = true
      switch(useImg){
        case true:
          branch.update = new cmsUI.createElement({element:'img'});
          branch.update.src = '/admin?action=update-branch&tag='+branchId
          if($('branchNotice_'+branchId)){
            $('branchNotice_'+branchId).innerHTML = 'Updating Branch, please wait...';
          }
          updatedBranches++;
          if(updatedBranches == allBranches.length ){
            location.href = refresh;
          }
        break;
        default:
          if(refresh){
            options.onSuccess=function(){
              updatedBranches++;
              if(updatedBranches == allBranches.length ){
                location.href = refresh;
              }
            }
          }
          else{
            options.onSuccess = function(){}
          }
          options.onLoad = function(){
            if($('branchNotice_'+branchId)){
              $('branchNotice_'+branchId).innerHTML = 'Updating Branch, please wait...';
            }
          }
          options.onException = function(){}
          branch.update = new cmsUI.sendAsync(options);
          update = null;
        break;
      }
    });

  }, //}}}

  //{{{ stopAction:function(options)
  stopAction:function(options){
    /* var refreshUrl = (options.refreshUrl)? options.refreshUrl : '/admin?action=branch-info'; */

    branchAjaxActions.updateStatus.stop();
    //window.location.reload();
  }, //}}}
  vars:{
    branchCheckoutOptions:'',
    rebuildOptions:''
  }
} //}}}

/* New Branch Details II actions */
//{{{ var cmsBranchActions
var cmsBranchActions = {

  //{{{ showItemDetails:function(path)
  showItemDetails:function(path,containerId){

    Element.toggle(containerId);
    
    
    var adminUrl     = '/admin?action=content-metainfo&path='+path;
    var params       = '&xslt=/metainfo.xsl';
    var updateTarget = 'details_' + containerId;

    //if(window.console) console.log('requesting: ' +adminUrl + ' ' + params);
    var getDetailsRequest = new Ajax.Updater(updateTarget, adminUrl, {
      asynchronous:true,
      method:'post',
      evalScripts:true,
      parameters:params
    });

  }, //}}}

  //{{{ hideItemDetails:function(path)
  hideItemDetails:function(){
   /*  var menuDiv = $('cmsContextMenuDiv');
    var textDiv = $('cmsDropShadow');
    menuDiv.removeChild(textDiv);
    Element.toggle(menuDiv); */
  }, //}}}

  //{{{ showUpdateDetails:function(path)
  showUpdateDetails:function(container){

    Element.toggle(container);

    var adminUrl = '/admin?action=branch-details';
    var params   = '&includeUpdateStatus=true&includeContentStatus=true&includeConflictSearch=true';

    //if(window.console) console.log('requesting: ' +adminUrl + ' ' + params);
    var getDetailsRequest = new Ajax.Updater(container, adminUrl, {
      asynchronous:true,
      method:'post',
      evalScripts:true,
      parameters:params
    });

  }, //}}}

  //{{{ checkout:function()
  checkout:function(options){

    var theForm = $(options.form)
    var jsCurrentBranch = options.jsCurrentBranch;

    cmsUI.cleanErrors({form:theForm});

    var checkoutBoxes = cmsUI.grabSelectedCheckBoxes({name:'path'});
    var errorMsg = ''
    if(checkoutBoxes.length == 0){
      alert('Please select at least one item to activate');
    }
    else{
      var notBranch     = cmsUI.validateChecklist({name:'path',cbClass:'branch-builtin'});
      var notLocalised  = cmsUI.validateChecklist({name:'path',cbClass:'localisedontrunk'});

      if(notBranch!=''){
        errorMsg+= 'The following items are already checked out on this branch \n \n';
        errorMsg+= notBranch + '\n \n';
      }
      if(notLocalised!=''){
        errorMsg+= 'The following items have been localised on the Trunk \nand need to be checked out individually \n \n';
        errorMsg+= notLocalised + '\n \n';
      }

      if(errorMsg!=''){
        alert(errorMsg);
      }
      else{

        var paths = cmsUI.serializeCheckedBoxes({name:'path'});

        branchAjaxActions.branchSummaryQuery({
          periodic:false,
          updateElem:'branchNotice_'+jsCurrentBranch,
          url:'/admin',
          params:'action=activate'+paths+'&refreshURL=admin!action~branch-details',
          evalScripts:false,
          onLoad:function(){ 
            cmsUI.disableActionButtons({
              getClassName:'activecontentaction'
            });
            var noticeArea = $('branchNotice_'+jsCurrentBranch);
            Element.addClassName(noticeArea, 'branchactivity');
            if(typeof(noticeArea.async.stop == 'function')){
              noticeArea.async.stop();
            }
            noticeArea.innerHTML = 'Activating files, please wait ...'; 
            
          }, 
          onSuccess:function(){
            cmsUI.updateCheckBoxes(false); 
            location.reload();
          }
        });
      }

    }
    //cmsUI.submitCheckedItems({admin:'action=activate', parameters:'&amp;refreshURL=admin!action~branch-info', ueMode:'performAction', wfAction:'activate', actionTxt:'checkout'});
  }, //}}}

  //{{{ splitFileByChanges:function(options)
  splitFileByChanges:function(options){

    var theForm         = $(options.form);
    var jsCurrentBranch = options.jsCurrentBranch;

    cmsUI.cleanErrors({form:theForm});

    var checkoutBoxes = cmsUI.grabSelectedCheckBoxes({name:'path'}); //Update!!!
    var errorMsg = ''
    if(checkoutBoxes.length == 0){
      alert('Please select at least one item to split');
    }
    else{
      var targetBranchName = prompt('File Split: Enter target Branch name');
      var paths = cmsUI.serializeCheckedBoxes({name:'path'});
      if (targetBranchName != null && targetBranchName != ''){

        //if(typeof(branchAjaxActions.updateStatus) == 'object') branchAjaxActions.updateStatus.stop();

        branchAjaxActions.branchSummaryQuery({
          periodic:false,
          updateElem:'branchNotice_'+jsCurrentBranch,
          url:'/admin',
          params:'action=split-branch&sourceBranch='+jsCurrentBranch+'&targetBranch='+targetBranchName+'&splitMode=allChanges'+paths+'&refreshURL=admin!action~branch-details',
          evalScripts:false,
          onLoad:function(){ 
            cmsUI.disableActionButtons({
              getClassName:'activecontentaction'
            });
            var noticeArea = $('branchNotice_'+jsCurrentBranch);
            Element.addClassName(noticeArea, 'branchactivity');
            if(typeof(noticeArea.async.stop == 'function')){
              noticeArea.async.stop();
            }
            noticeArea.innerHTML = 'Splitting files, please wait ...'; 
            
          }, 
          onSuccess:function(){
            cmsUI.updateCheckBoxes(false);
            location.reload();
          }
        });

        /* cmsUI.sendAsync({
          url:'/admin',
          params:'action=split-branch&sourceBranch='+jsCurrentBranch+'&targetBranch='+targetBranchName+'&splitMode=allChanges'+paths+'&refreshURL=admin!action~branch-details',
          onLoad:function(){cmsUI.showAlert('Splitting Branch, please wait ...');}, //cmsShowContextMessage('Splitting Branch, please wait ...', true);
          onSuccess:function(){
            cmsUI.updateCheckBoxes(false);
            location.reload();
          }
        }); */

    }
     /*

      cmsUI.submitCheckedItems({admin:'action=split-branch', parameters:'&sourceBranch='+jsCurrentBranch+'&targetBranch='+targetBranchName+'&splitMode=allChanges', wfAction:'split', actionTxt:'split',ueMode:'performAction'});

    */
    }
  }, //}}}

  //{{{ splitFileByLocales:function(options)
  splitFileByLocales:function(options){

    var theForm         = $(options.form);
    var jsCurrentBranch = options.jsCurrentBranch;

    cmsUI.cleanErrors({form:theForm});

    var checkoutBoxes = cmsUI.grabSelectedCheckBoxes({name:'path'});
    var errorMsg = ''
    if(checkoutBoxes.length == 0){
      alert('Please select at least one item to split');
    }
    else{
      var targetBranchName = prompt('File Split: Enter target Branch name');
      if (targetBranchName != null && targetBranchName != ''){
        //alert('not yet setup');
        cmsUI.utils.filterGroup = cmsUI.serializeCheckedBoxes({name:'path'});
        cmsUI.utils.noticeArea = $('branchNotice_'+jsCurrentBranch);
        clwin = window.open(CoreSiteVars.adminTool+'?action=locale-selector&tab=1&localiseAction=split-branch&sourceBranch='+jsCurrentBranch+'&targetBranch='+targetBranchName+cmsUI.utils.filterGroup+'&splitMode=locale&refreshURL='+CoreSiteVars.adminTool+'!action~branch-details|refreshOpenerandCloseOnSubmit~yes','splitbranch','status=no,location=no,menubar=no.menubar=no,width=640,height=480,scrollbars=no,resizable=yes');
      }

    }

  }, //}}}

  //{{{ revertItem:function(path)
  revertItem:function(options){
    var theForm = $(options.form)
    var jsCurrentBranch = options.jsCurrentBranch;
    cmsUI.cleanErrors({form:theForm});

    var checkoutBoxes = cmsUI.grabSelectedCheckBoxes({name:'path'});
    var errorMsg = ''
    if(checkoutBoxes.length == 0){
      alert('Please select at least one item to revert');
    }
    else{

      if (confirm('Are you sure you would like to revert the selected items from this branch?')) {
      var paths = cmsUI.serializeCheckedBoxes({name:'path'});
      branchAjaxActions.branchSummaryQuery({
          periodic:false,
          updateElem:'branchNotice_'+jsCurrentBranch,
          url:'/admin',
          params:'action=revert-to-trunk'+paths+'&refreshURL=admin!action~branch-details',
          evalScripts:false,
          onLoad:function(){ 
            cmsUI.disableActionButtons({
              getClassName:'activecontentaction'
            });
            var noticeArea = $('branchNotice_'+jsCurrentBranch);
            Element.addClassName(noticeArea, 'branchactivity');
            if(typeof(noticeArea.async.stop == 'function')){
              noticeArea.async.stop();
            }
            noticeArea.innerHTML = 'Reverting files, please wait ...'; 
            
          },
          onSuccess:function(){
            cmsUI.updateCheckBoxes(false);
            location.reload();
          }
        });
      }
    }
  }, //}}}

  //{{{ viewPage:
  viewPage:function(path,apu){
    window.location = '/staging'+path+'?pageInfoMode=view';
  } //}}}

} //}}}

//{{{ var branchCheckoutWizard = {
var branchCheckoutWizard = {
  wizardAction:'', //general global container for handling ajax requests
  branchId:'', //list elem and branch id must be the same
  refreshURL:'',
  contentPath:'',
  isCheckedOut:false,
  workflowLoaded:false,
  totalSteps:'',
  currentStep:'',
  changeBranch:'',
  updateBranchWorkFlow:'',
  branchSet:function(obj){

    if(branchCheckoutWizard.branchId!='' && branchCheckoutWizard.branchId!=obj.id){
      $(branchCheckoutWizard.branchId).style.backgroundColor = '#ffffff';
    }
    $(obj.id).style.backgroundColor = '#B3DCEA';
  },
  branchOut:function(obj, color){
    if(branchCheckoutWizard.branchId=='' || branchCheckoutWizard.branchId!=obj.id){
      $(obj.id).style.backgroundColor = color;
    }
  },
  listBranches:function(options){

    var adminUrl = (options.url)? options.url : '/admin';
    var params   = (options.params)? options.params : 'action=branch-selector&hideSideContent=true&hideTopToolbar=true&mode=wizardFrame&path='+branchCheckoutWizard.contentPath;

    branchCheckoutWizard.wizardAction = new Ajax.Updater(options.updateContainer, adminUrl, {
      asynchronous:true,
      method:'post',
      evalScripts:true,
      parameters:params
    });
  },
  getWorkflow:function(options){
    //action=workflow&path=/xml_content/baseline/test/pages/localisedordering/MC/.10_0701121053-286.xml/root&tag=mikeh001&display-xml=true
    var adminUrl = (options.url)? options.url : '/admin';
    var params   = (options.params)? options.params : 'action=workflow&path='+branchCheckoutWizard.contentPath+'&tag='+branchCheckoutWizard.branchId+'&mode=wizardFrame';

    var workflow = new Ajax.Updater(options.worklfowContainer, adminUrl, {
      asynchronous:true,
      method:'post',
      evalScripts:true,
      parameters:params
    });
  },
  createTabs:function(options){

  },
  stepForward:function(options){

  },
  stepBack:function(options){

  },
  checkSelection:function(event){

    if(branchCheckoutWizard.branchId==''){
      alert("Please select a branch");
      return false;
      if(event){
        Event.stop(event);
      }
    }
    else{
      return true;
    }
  },
  finish:function(options){
    var locMode    = (options.locMode!='') ? '&locMode='+options.locMode : '';
    var adminUrl   = (options.url)? options.url : '/admin';
    var operation  = (options.operation)? options.operation : '';
    var branchUser = CoreSiteVars.this_user.substring(CoreSiteVars.this_user.indexOf('-')+1);

    var checkMe =  branchCheckoutWizard.checkSelection();
    if(checkMe != false){

      //set users branchStatus to branchId
      cmsUI.showAlert('Checking out content item.');
      branchCheckoutWizard.wizardAction = new Ajax.Request(adminUrl,{
        asynchronous:true,
        method:'post',
        evalScripts:false,
        parameters:'action=UA-update-user&uid='+branchUser+'&cmfcurrentBranch='+branchCheckoutWizard.branchId,
        onSuccess:function(){
          var workflowinfo = $('workflowinfo').serialize();
          $('workflowinfo').disable();
          //activate content item

          //adjust worklfow 2 options:
          /* 1 - if its already checked out - just changing the workflow and then opening the editor on the right branch
             2 - activating the document with the specified workflow and opening the editor
          */
          if(branchCheckoutWizard.isCheckedOut == true){
            cmsUI.sendAsync({
              url:'/admin?action=update-wf&path='+branchCheckoutWizard.contentPath,
              params:'&'+workflowinfo,
              evalScripts:false,
              onLoad:function(){
                //empty function - therre is allreday a status message
              },
              onSuccess:function(){
                branchCheckoutWizard.loadEditor(adminUrl, locMode);
              }
            });
          }
          else {
            var daisy_1 = new Ajax.Request(adminUrl,{
              asynchronous:true,
              method:'post',
              evalScripts:false,
              parameters:'action=activate&path='+branchCheckoutWizard.contentPath,
              onSuccess:function(){
                if(branchCheckoutWizard.workflowLoaded == true){
                  cmsUI.sendAsync({
                    url:'/admin?action=update-wf&path='+branchCheckoutWizard.contentPath,
                    params:'&'+workflowinfo,
                    evalScripts:false,
                    onLoad:function(){
                      //empty function - therre is allreday a status message
                    },
                    onSuccess:function(){
                      branchCheckoutWizard.loadEditor(adminUrl, locMode);
                    }
                  });
                }
                else{
                  branchCheckoutWizard.loadEditor(adminUrl, locMode);
                }
              }
            });
          }
        }
      });
    }
  },
  loadEditor:function(adminUrl,locMode){
    cmsUI.hideAlert();
    window.close();
    window.opener.location.href=adminUrl+'?action=custom_edit_form&path='+branchCheckoutWizard.contentPath+'&refreshURL='+branchCheckoutWizard.refreshURL+locMode;

  }
} //}}}

//{{{ var branchCreatorWizard = {
var branchCreatorWizard = {
  wizardAction:'', //general global container for handling ajax requests
  refreshURL:'',
  contentPath:'',
  totalSteps:'',
  currentStep:'',
  changeBranch:'',
  updateBranchWorkFlow:'',
  updateItemWorkflow:'',
  branchId:'',
  branchTitle:'',
  branchDesc:'',
  createTabs:function(options){

  },
  stepForward:function(options){

  },
  stepBack:function(options){

  },
  checkSelection:function(branchWFForm){

    var primAuthB  =  Form.getInputs(branchWFForm, 'text', 'primary_author');
    var secAuthB   =  Form.getInputs(branchWFForm, 'hidden', 'num_secAuth');
    var revUserB   =  Form.getInputs(branchWFForm, 'hidden', 'num_reviewers');
    var revRoleB   =  Form.getInputs(branchWFForm, 'hidden', 'num_role_reviewers');
    var primPubB   =  Form.getInputs(branchWFForm, 'text', 'primary_publisher');
    var secPubB    =  Form.getInputs(branchWFForm, 'hidden', 'num_secPub');

    if(window.console)console.log(primAuthB);

    var validName = validBranchname($('branchDetails'),$('newBranchName').value,$('newBranchName'))
    if(branchCreatorWizard.branchId=='' || validName==false){
      return false;
    }
    else if((primAuthB[0].value =='' && primPubB[0].value =='' && secAuthB[0].value == 0 && secPubB[0].value == 0) || (revUserB[0].value == 0 && revRoleB[0].value == 0) ){
      alert("Please complete the branch workflow details");
      return false;
    }
    else{
      return true;
    }
  },
  finish:function(options){
    var locMode       = (options.locMode!='') ? '&locMode='+options.locMode : '';
    var detailsForm   = $('branchDetails');
    var branchWFForm  = $('branchWorkflow');
    var contentWFForm = $('contentItemWorkflow');

    var serialDetails = Form.serialize(detailsForm);
    var serialWorklfow = Form.serialize(branchWFForm);
    var serialContentItem = Form.serialize(contentWFForm);

    var adminUrl = (options.url)? options.url : '/admin';
    var operation = (options.operation)? options.operation : '';
    var branchUser = CoreSiteVars.this_user.substring(CoreSiteVars.this_user.indexOf('-')+1);

    //TODO - proper validation on branchId
    var checkMe =  branchCreatorWizard.checkSelection(branchWFForm);
    if(checkMe != false){
      cmsUI.showAlert('Creating new branch and checking out content item.');
      Form.disable(detailsForm);
      Form.disable(branchWFForm);
      Form.disable(contentWFForm);
      //create new branch (is user switch happennin automagically here?, is workflow happening here?
      //set users branchStatus to branchId
      //using an ajax method to send the form data
      //set notice
      var sendDetailsForm = new Ajax.Request(adminUrl,{
        asynchronous:true,
        method:'post',
        evalScripts:false,
        parameters:serialDetails+'&'+serialWorklfow,
        onSuccess:function(){
          //alert("created new branch");
          //set the branch workflow if not handled already
          //activate content item
          //set the content item workflow if needed.
          var daisy_1 = new Ajax.Request(adminUrl,{
            asynchronous:true,
            method:'post',
            evalScripts:false,
            parameters:'action=UA-update-user&uid='+branchUser+'&cmfcurrentBranch='+branchCreatorWizard.branchId,
            onSuccess:function(){
              //alert("created new branch, moved user, about to activate item");
              var daisy_2 = new Ajax.Request(adminUrl,{
                asynchronous:true,
                method:'post',
                evalScripts:false,
                parameters:'action=activate&path='+branchCreatorWizard.contentPath,
                onSuccess:function(){
                  //alert("should have activated item");

                  var primAuthC  =  Form.getInputs(contentWFForm, 'text', 'primary_author');
                  var secAuthC   =  Form.getInputs(contentWFForm, 'hidden', 'num_secAuth');
                  var revUserC   =  Form.getInputs(contentWFForm, 'hidden', 'num_reviewers');
                  var revRoleC   =  Form.getInputs(contentWFForm, 'hidden', 'num_role_reviewers');
                  var primPubC   =  Form.getInputs(contentWFForm, 'text', 'primary_publisher');
                  var secPubC    =  Form.getInputs(contentWFForm, 'hidden', 'num_secPub');
                  //console.log(primAuth[0].value == '');!
                  if((primAuthC[0].value !='' || primPubC[0].value !='' || secAuthC[0].value > 0 || secPubC[0].value > 0) && (revUserC[0].value > 0 || revRoleC[0].value > 0) ){

                    cmsUI.sendAsync({
                      url:'/admin?action=update-wf&path='+branchCreatorWizard.contentPath,
                      params:'&'+serialContentItem,
                      evalScripts:false,
                      onLoad:function(){
                        //empty function - therre is allreday a status message
                      },
                      onSuccess:function(){
                        branchCreatorWizard.loadEditor(adminUrl, locMode);
                      }
                    });

                    /* var daisy_3 = new Ajax.Request(adminUrl,{
                      asynchronous:true,
                      method:'post',
                      evalScripts:false,
                      parameters:serialContentItem,
                      onSuccess:function(){
                        branchCreatorWizard.loadEditor(adminUrl,locMode);
                      }
                    }); */
                  }
                  else{
                    branchCreatorWizard.loadEditor(adminUrl,locMode);
                  }
                }
              });
            }
          });
        }
      });
    }
  },
  loadEditor:function(adminUrl,locMode){
    cmsUI.hideAlert();
    window.close();
    window.opener.location.href=adminUrl+'?action=custom_edit_form&path='+branchCreatorWizard.contentPath+'&refreshURL='+branchCreatorWizard.refreshURL+locMode;

  }
} //}}}

//{{{ Branch Export events
if(typeof(Prototype)!='undefined'){
Event.observe(window, 'load', function(){ 
  if($('ExportForm')){
    var adminForm = ($('branchAdminActions'))? $('branchAdminActions') : $('ExportForm');
    var noticeArea =($('branchNotice_'+CoreSiteVars.currentBranch))? $('branchNotice_'+CoreSiteVars.currentBranch) : '';
    var testBtn    = $('testregex');
    var exportBtn  = $('exportbranch');
    var regexfield = $('regexfield');
    var regex      = $('regex');
    var select     = $('selectlocales');
    
    var localeSelector = $('LocaleSelector');
    var localeBox = $('locale_list_box');
    Event.observe(localeSelector, 'click', function(e){
      select.checked = true;
    });
    Event.observe(localeBox, 'click', function(e){
      select.checked = true;
    });
    
    Event.observe(regexfield, 'focus', function(e){
      regex.checked = true;
    });
    
    Event.observe(testBtn, 'click', function(e){
      regex.checked = true;
      var regexresults = $('regexresults');
      var testoptions  = {
        params:'action=branch-export&testRegex=true&regex='+regexfield.value,
        updateElem:regexresults,
        onLoad:function(){
          Element.addClassName(regexresults, 'branchactivity');
          regexresults.innerHTML = 'Loading results...'
        },
        onSuccess:function(){
          Element.removeClassName(regexresults, 'branchactivity');
        },
        onException:function(){}
      }
      cmsUI.sendAsync(testoptions);
      Event.stop(e);
    });
    
    //if (confirm('Are you sure you want to export {$jsCurrentBranch}'));
    Event.observe(exportBtn, 'click', function(e){
      var container     = $('updateText');
      var activecontent = ($('activecontent')) ? $('activecontent') : '';
      
      try{
        window.scrollTo(0,0);
      }
      catch(e){
        
      }
      
      var alllocales    = $('alllocales');
      var params  = 'action=branch-export';
      params += (activecontent.checked)? '&pageSet=activeContent' : '&pageSet=regex&regex='+regexfield.value;
      
      if(select.checked){
        params += '&localeSet='+$('locale_list_box').value;
      }
      else if(alllocales.checked){
        params += '&localeSet=all';
      }
      else{
        params += '&localeSet=current';
      }
      
        
        //params += (alllocales.checked)? '&localeSet=all' : '&localeSet=current';
        
      var submitoptions = {
        params:params,
        evalScripts:true,
        onLoad:function(){
          Form.disable(adminForm);
          Element.addClassName(noticeArea, 'branchactivity');
          if((typeof(noticeArea)=='object') && (typeof(noticeArea.async.stop == 'function'))){
            noticeArea.async.stop();
            noticeArea.innerHTML = 'Exporting Branch, this may take a few minutes...';
          }
          else if(typeof(noticeArea)=='string'){
            cmsUI.showAlert('Exporting Trunk, this may take a few minutes...');
          }
        },
        onSuccess:function(){
          Form.enable(adminForm);
          if(typeof(noticeArea)=='object') { 
            noticeArea.async.start(); 
            Element.removeClassName(noticeArea, 'branchactivity');
          }
          else if(typeof(noticeArea)=='string'){
            cmsUI.hideAlert();
          }
        }
      }
      //console.dir(submitoptions);
      cmsUI.sendAsync(submitoptions);
      Event.stop(e);
    });
  }
});
}//}}}

var fn_exportSelectLocales=function(){ //Called from top tool bar -> developer -> Export - select
  var L11nList = $('locale_list_box').value;
  //console.log(L11nList);
  //if (confirm('Are you sure you want to export this page for the following locales:'+L11nList+'?')) {
    cmsUI.showAlert('Exporting Page, please wait ...');
    window.location.href = CoreSiteVars.adminTool+'?action=PLUGIN-pagemanager&method=exportPages&arg1='+CoreSiteVars.this_url+'&arg2='+L11nList;
  //}
  
  return false;
}

//Starting general cms UI function framework

var cmsUI = {
  //{{{ showAlert:function(msg)
  showAlert:function(msg){
    //alert('window.screenY = '+window.screenY + '\n' + 'window.pageYOffset = '+window.pageYOffset + '\n' + 'document.body.scrollTop = '+document.body.scrollTop);

    var menuDiv = $('cmsContextMenuDiv');
    if(menuDiv){
      //cmsUI.hideAlert();
    }
    else{
      menuDiv = cmsUI.createElement({
        element:'div',
        elemId:'cmsContextMenuDiv'
      });
    }

    menuDiv.innerHTML = '<div class="cmsDropShadow" id="cmsDropShadow"><div class="cmsContextMessage" id="cmsContextMessage" ><span id="cmsTextMessage">'+msg+'</span></div></div>';

    //set position
    menuDiv.quirksmode = cmsUI.ieBackCompat(menuDiv);
    cmsUI.center(menuDiv);
    
    menuDiv.style.visibility = 'visible';
    menuDiv.style.display = 'block';
    
    showingMessage = true;
  }, //}}}

  //{{{ hideAlert:function()
  hideAlert:function(){
    var menuDiv = $('cmsContextMenuDiv');
    var textDiv = $('cmsDropShadow');
    if (menuDiv){
      if (textDiv){ 
        menuDiv.removeChild(textDiv); 
      }
      Element.toggle(menuDiv);
    }
    if(typeof(Lightbox)!='undefined'){Lightbox.hideAll()}//console.dir(Lightbox) }
    showingMessage = false;
  }, //}}}

  //{{{ center:function(elem)
  center:function(elem){
    var my_width  = 0;
		var my_height = 0;
		
		if ( typeof( window.innerWidth ) == 'number' ){
			my_width  = window.innerWidth;
			my_height = window.innerHeight;
		}else if ( document.documentElement && 
				 ( document.documentElement.clientWidth ||
				   document.documentElement.clientHeight ) ){
			my_width  = document.documentElement.clientWidth;
			my_height = document.documentElement.clientHeight;
		}
		else if ( document.body && 
				( document.body.clientWidth || document.body.clientHeight ) ){
			my_width  = document.body.clientWidth;
			my_height = document.body.clientHeight;
		}
		
		elem.style.position = 'absolute';
		elem.style.zIndex   = 1000;
		
		var scrollY = 0;
		
		if ( document.documentElement && document.documentElement.scrollTop ){
			scrollY = document.documentElement.scrollTop;
		}else if ( document.body && document.body.scrollTop ){
			scrollY = document.body.scrollTop;
		}else if ( window.pageYOffset ){
			scrollY = window.pageYOffset;
		}else if ( window.scrollY ){
			scrollY = window.scrollY;
		}
		
		var elementDimensions = Element.getDimensions(elem);
		
		var setX = ( my_width  - elementDimensions.width  ) / 2;
		var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;
		
		setX = ( setX < 0 ) ? 0 : setX;
		setY = ( setY < 0 ) ? 0 : setY;
		
		elem.style.left = setX + "px";
		elem.style.top  = setY + "px";
    
  }, //}}}

  
  //{{{ buildUrlParams:function()
  buildUrlParams:function(param){
    var loc = '' + location;
    if(loc.indexOf('#')!= -1){
     loc = loc.substr(0, loc.indexOf('#'))
    }
    if (loc.indexOf('?')!= -1) {
     loc = loc + '&' + param ;
    }
    else {
     loc = loc + '?' + param ;
    }
    return loc;
  }, //}}}
  
  //{{{ buildCheckboxSets:function()
  buildCheckboxSets:function(options){
    
    var useClass = ((options) && (options.cbClass)) ? options.cbClass : 'cbactivecontent' ;
    
    var allInputs = $A(document.getElementsByTagName('INPUT'))
    var revInputs = allInputs.reverse();

    var setNum = 0
    allInputs.each(function(cb) {
      var attType = Element.readAttribute(cb, 'type');
      var attName = Element.readAttribute(cb, 'name');
      if(attType.toLowerCase() == 'checkbox') {
        if(attName.toLowerCase() == 'root' && Element.hasClassName(cb, 'absroot')) {
          setNum++;
          var newSet = new cmsUI.createCheckboxSet({element:cb.id, cbClass:useClass, setNumber:setNum})
          cmsUI.utils.allCheckboxSets.push(newSet);
        }
        if(attName.toLowerCase() == 'root') {
          setNum++;
          var newSet = new cmsUI.createCheckboxSet({element:cb.id, setNumber:setNum})
          cmsUI.utils.allCheckboxSets.push(newSet);
        }
      }

    });
    //console.dir(cmsUI.utils.allCheckboxSets);
  }, //}}}

  //{{{ createCheckboxSet:function(options)
  createCheckboxSet:function(options){
    this.setNum          = options.setNumber;
    this.rootBox         = $(options.element);
    this.boxDescendants  = new Array();
    var cbClasses        = (options.cbClass)? options.cbClass : null;
    var rootDescendants;

    if(this.rootBox){

      if(cbClasses){
        rootDescendants = $$('.'+cbClasses);
      }
      else{
        var rootDiv = Element.nextSiblings(this.rootBox.parentNode);
        Element.cleanWhitespace(rootDiv[0]);
        rootDescendants = rootDiv[0].descendants();
      }
      
      for(x = 0; x < rootDescendants.length; x++){
        if(rootDescendants[x].type == 'checkbox'){
          var rootDescBox = $(rootDescendants[x]);
          if(rootDescBox!=this.rootBox) this.boxDescendants.push(rootDescBox);
        }
      }

      Event.observe(this.rootBox, 'click', function(event){
        cmsUI.checkRoots({root:this.rootBox, descendants:this.boxDescendants})
        event.cancelBubble = true;
      }.bind(this));


      for(z = 0; z < this.boxDescendants.length; z++){
        var rootBox        = this.rootBox
        var boxDescendants = this.boxDescendants
        Event.observe(boxDescendants[z], 'click', function(event){
            var thisBox;
            var cbabs = $$('.absroot');
            for(a=0; a < boxDescendants.length; a++){
              if(boxDescendants[a] == this){
                thisBox = a;
              }
            }

            if(rootBox.checked && !this.checked){
              rootBox.checked = false;
              for(c=0; c < cbabs.length; c++){
                cbabs[c].checked = rootBox.checked;
              }
            }
            else if(!rootBox.checked && this.checked ){
              cmsUI.checkDescendants({root:rootBox, descendants:boxDescendants});
            }

            if(event.shiftKey){
              var shiftBox;
              var shiftSet;
              for(y=0; y < boxDescendants.length; y++){
                if(boxDescendants[y] == cmsUI.utils.mostRecentCheckedBox){
                  shiftBox = y;
                }
              }
              //splice the array so that the new set is only from a to b
              var shiftSet = (thisBox > shiftBox)? shiftSet = boxDescendants.slice(shiftBox,thisBox) : shiftSet = boxDescendants.slice(thisBox,shiftBox);
              for(c=0; c < shiftSet.length; c++){
                shiftSet[c].checked = boxDescendants[shiftBox].checked;
              }
              cmsUI.checkDescendants({root:rootBox, descendants:boxDescendants});
            }
            cmsUI.utils.mostRecentCheckedBox = this;
            event.cancelBubble = true;
        }.bind(boxDescendants[z]));

      }

    }

  }, //}}}

  //{{{ checkRoots:function(options)
  checkRoots:function(options){
    var rootBox        = options.root;
    var boxDescendants = options.descendants;
    var cbabs = $$('.absroot');

    for (i=0; i < boxDescendants.length; i++) {
      boxDescendants[i].checked = rootBox.checked;
    }

    if(Element.hasClassName(rootBox, 'absroot')){
      for(b=0; b < cbabs.length; b++){
        cbabs[b].checked = rootBox.checked;
      }
    }
  }, //}}}

  //{{{ checkParents:function(options)
  checkParents:function(options){
    //get the parent of the current rootBox
    var rootBox        = options.root;
    var boxDescendants = options.descendants;

    for(x=0; x < cmsUI.utils.allCheckboxSets.length; x++){
      if(cmsUI.utils.allCheckboxSets[x].boxDescendants.length){
        try{
          for(y=0; y < cmsUI.utils.allCheckboxSets[x].boxDescendants.length; y++){
            if(rootBox == cmsUI.utils.allCheckboxSets[x].boxDescendants[y]){
              cmsUI.checkDescendants({root:cmsUI.utils.allCheckboxSets[x].rootBox, descendants:cmsUI.utils.allCheckboxSets[x].boxDescendants});
            }
          }
        }
        catch(e){

        }
      }
    }
  }, //}}}

  //{{{ checkDescendants:function(options)
  checkDescendants:function(options){
    var rootBox        = options.root;
    var boxDescendants = options.descendants;
    var cbabs = $$('.absroot');

    var allChecked = 0;
    for(d=0; d < boxDescendants.length; d++){
      if(boxDescendants[d].checked){
        allChecked++;
      }
    }

    if(allChecked == boxDescendants.length){
      rootBox.checked = true;
      cmsUI.checkParents(options);
      cmsUI.checkRoots(options);
    }

  }, //}}}

  //{{{ addCheckBox:function(elem)
  addCheckBox:function(elem){
    cmsUI.utils.checkBoxes[cmsUI.utils.cbCount] = elem;
    cmsUI.utils.cbCount++;
  }, //}}}

  //{{{ updateCheckBoxes:function(val)
  updateCheckBoxes:function(val){
    for (i=0; i < cmsUI.utils.cbCount; i++) {
      cmsUI.utils.checkBoxes[i].checked = val;
    }
  }, //}}}

  //{{{ updateSingleBox:function(prefix, val)
  /* updateSingleBox:function(prefix, val){
    for (i=0; i < cmsUI.utils.cbCount; i++) {
      cmsUI.utils.checkBoxes[i].checked = '';
    }

    var selectAll = $('selectAllCheckBox');
    if(selectAll) selectAll.checked = '';

    for (i=0; i < cmsUI.utils.cbCount; i++) {
      var subId = cmsUI.utils.checkBoxes[i].id.substring(prefix.length);
      if(val == subId){
        if(window.console) console.log(subId);
        cmsUI.utils.checkBoxes[i].checked = 'checked';
      }
    }
  }, */ //}}}

  //{{{ grabSelectedCheckBoxes:function(options)
  grabSelectedCheckBoxes:function(options){
    var name        = options.name;
    var cbArray     = (options.cbArray)? options.cbArray : cmsUI.utils.checkBoxes;
    var classCheck  = (options.cbClass)? options.cbClass : null;
    var tryVirtual  = (options.tryVirtual)? options.tryVirtual : false;
    var returnArray = new Array();
    
    if(classCheck){
      for (i=0; i < cbArray.length; i++) {
        var ckClass = Element.hasClassName(cbArray[i], classCheck);
        if(cbArray[i].checked && ckClass==true && cbArray[i].name==name){
          var cbSiblings = cbArray[i].siblings();
          if(tryVirtual && cbSiblings[1]){
            returnArray.push(cbSiblings[1]);
          }
          else{
            returnArray.push(cbArray[i]);
          }
        }
      }
      return returnArray;
    }
    else{
      for (i=0; i < cbArray.length; i++) {
        if(cbArray[i].checked && cbArray[i].name==name ){
          var cbSiblings = cbArray[i].siblings();
          if(tryVirtual && cbSiblings[1]){
            returnArray.push(cbSiblings[1]);
          }
          else{
            returnArray.push(cbArray[i]);
          }
        }
      }
      return returnArray;
    }

  }, //}}}

  //{{{ validateChecklist:function(options)
  validateChecklist:function(options){
    var cbName       = options.name;
    var classCheck   = (options.cbClass)? options.cbClass : null;
    var checkoutBoxes = cmsUI.grabSelectedCheckBoxes({name:cbName});
    var errorMsg = ''
    if(checkoutBoxes.length == 0){
      errorMsg = 'Please select at least one item to activate'
    }
    else{
      for(x=0; x < checkoutBoxes.length; x++){

        if(checkoutBoxes[x].hasClassName(classCheck)){
          parentLI = checkoutBoxes[x].parentNode;
          parentLI.addClassName('error');
          label = parentLI.getElementsByTagName('label')[0].innerHTML;
          errorMsg += label + '\n';
        }

      }
      return errorMsg
    }
  }, //}}}

  //{{{ getUniqueArrayValues:function(options)
  getUniqueArrayValues:function(options) {
    //AT:from forum post at http://www.webdeveloper.com/forum/archive/index.php/t-9578.html
    var arrayObj    = options.arrayObj;
    var useProperty = (options.property)? options.property : null;

    var hash = {};
    for (j = 0; j < arrayObj.length; j++) {
      switch(useProperty){
        case 'value':
          hash[arrayObj[j].value] = true;
          break

        case 'id':
          hash[arrayObj[j].id] = true;
          break

        case 'name':
          hash[arrayObj[j].name] = true;
          break

        default:
          hash[arrayObj[j]] = true;
          break
      }
    }

    var array = new Array();
    for (value in hash) {array.push(value)};

    return array;

  }, //}}}

  //{{{ serializeCheckedBoxes:function(options)
  serializeCheckedBoxes:function(options){ 
    var name         = options.name;
    var useProp      = (options.property)? options.property : 'value';
    var rtrnString   = '';
    var ueMode       = (options.ueMode) ? options.ueMode : '';
    var searchQuery  = (options.searchQuery) ? options.searchQuery : '**Exact**RepositoryPath';
    var selectedCB   = cmsUI.grabSelectedCheckBoxes(options);
    var uniqueVals   = cmsUI.getUniqueArrayValues({arrayObj:selectedCB, property:useProp});

    for (i=0; i < uniqueVals.length; i++) {
      if(ueMode == 'searchTaskActions'){
        rtrnString += '"' + uniqueVals[i] + '"';
        if(i != uniqueVals.length-1){
          rtrnString += ' OR ';
        }
      }
      /* JJ-2008.2.5: added this case to gather all the checked items in search results page in pipe separated list */
      else if(ueMode == 'getCheckedItems'){
        rtrnString += uniqueVals[i] + "|";
      }
      else{
        rtrnString += '&' + name + '=' + uniqueVals[i];
      }
    }

    if(ueMode == 'searchTaskActions' && rtrnString != ''){
      /* rtrnString = '&searchTerm=' + searchQuery + ':(' + rtrnString + ')'; */
      rtrnString = searchQuery + ':(' + rtrnString.replace(/&/g,'%26') + ')';
    }
    /* alert("returnString= " + rtrnString); */
    return rtrnString;
  }, //}}}

  //{{{ submitCheckedItems:function(options)
  submitCheckedItems:function(options){
    var params      = (options.parameters)? options.parameters : '';
    var serialName  = (options.name)? options.name : 'path';
    var tryVirtual  = (options.tryVirtual)? options.tryVirtual : false;
    var popTitle    = (options.title)? options.title : '';
    var searchQuery = (options.searchQuery)? options.searchQuery : '';
    var wfAction    = (options.wfAction)? options.wfAction : '';
    var actionTxt   = (options.actionTxt)? options.actionTxt : '';// PW: added, should this replace wfAction?
    var ueMode      = (options.ueMode)? options.ueMode : 'xShowDialog';// PW, JJ added: performAction | xShowDialog | searchTaskActions
    var adminAction = options.admin;
    var checkBranch = (options.checkBranch) ? options.checkBranch : false;
    
    if(typeof(CoreSiteVars.currentBranch)!='undefined' && checkBranch){
      cmsUI.utils.serialCB = (options.cbFilter)? options.cbFilter : cmsUI.serializeCheckedBoxes({name:serialName, cbClass:'branch-builtin', tryVirtual:tryVirtual, ueMode:ueMode, searchQuery:searchQuery});
    }
    else{
      cmsUI.utils.serialCB = (options.cbFilter)? options.cbFilter : cmsUI.serializeCheckedBoxes({name:serialName, tryVirtual:tryVirtual, ueMode:ueMode, searchQuery:searchQuery});
    }
    
    //if(window.console) console.log(serialCB);
    if(cmsUI.utils.serialCB==''){
      alertTxt = "Please check the ";
      if(checkBranch){
        alertTxt += "activated ";
      }
      alertTxt += "documents you would like to " + options.wfAction + "."
      alert(alertTxt);
    }

    //new general basic version
    else if(ueMode=='performAction') {
      //if(window.console) console.log('lets '+actionTxt+' these babies');
      //if(window.console) console.log(CoreSiteVars.adminTool + '?' + adminAction + serialCB + params);
      cmsPerformAction('Performing '+actionTxt+', please wait ...',CoreSiteVars.adminTool + '?' + adminAction + cmsUI.utils.serialCB + params);
    }
    
    else if(ueMode=='Lightbox'){
      loadLightboxOptions = {
        createDraggable:true,
        type:'form',
        content:{
          heading:options.heading,
          msg:options.msg,
          inputs:options.inputs
        },
        action:{
          msg:actionTxt+', please wait ...',
          refreshOnSuccess:options.refreshOnSuccess,
          url:CoreSiteVars.adminTool, 
          params:cmsUI.utils.serialCB + params
        }
      }
      //console.dir(loadLightboxOptions);
      new Lightbox.base('cmsContextMenuDiv', loadLightboxOptions);
    }

    //temp case for new branch details situation
/*     else if(ueMode=='confirm' && actionTxt=='remove from the branch'){
      if(window.console) console.log('lets revert these suckers');
      if (confirm('Are you sure you would like to remove the selected items?')) cmsPerformAction('Reverting, please wait ...',CoreSiteVars.adminTool + '?' + adminAction + serialCB + params);
    }  */

   
    // search results actions
    else if(ueMode=='searchTaskActions') {
      if(adminAction.indexOf('task-popup') > -1){ 
         window.open('admin?' + adminAction + params,'_blank', options.windowParam);
      }
      else{
        
         cmsUI.sendAsync({
          url:'/admin?' + adminAction,
          params:'&searchTerm=' +cmsUI.utils.serialCB + params,
          onLoad:function(){cmsUI.showAlert(options.loadMsg + ', please wait ...');},
          onSuccess:function(){
            cmsUI.updateCheckBoxes(false);
            //location.reload();
            /* JJ-2008.2.5: submit a form instead of reloading the page so that sort order and checked items stay the same. */
            document.doc_search_results.submit(); 
          }
        });
      }
    }


    // original My To Do WF actions case
    else if(ueMode=='xShowDialog') {
      completeWFOptions = {
        createDraggable:true,
        type:'form',
        content:{
          heading:'<h1>Change Request Complete</h1>',
          msg:'You are marking a change request complete for selected documents',
          inputs:{
            label1:'<label for="reviewText" >Enter comment:</label>',
            field1:'<textarea id="reviewText" name="reviewText" rows="6" cols="40" style="width:100%;display:block;"></textarea>'
          }
        },
        action:{
          msg:'Completing Change Request, please wait ...',
          refreshOnSuccess:true,
          url:CoreSiteVars.adminTool +'?'+ adminAction + cmsUI.utils.serialCB + params
        }
      }
      
      // BUG - all items in todo list are being submitted - seems to be something with localised docs
      //console.log(cmsUI.utils.serialCB);
      var completeWF = new Lightbox.base('cmsContextMenuDiv',completeWFOptions);
      
      /* xShowDialog('admin?action=popup&popupTitle=Change Request Complete&popupMsg1=You are marking a change request complete for selected documents.&popupMsg2=&popupPrompt=Enter comment:&popupType=workflowRequest&useAsync=yes', new Array(adminAction + cmsUI.utils.serialCB + params) , 'status:no;dialogWidth:400px;dialogHeight:300px;help:no;scrollbar:no;center:yes;'); */
    }


  }, //}}}

  //{{{ cleanErrors:function(options)
  cleanErrors:function(options){

    var form = options.form;
    var errorList = Element.select(form, '.error');

    for(x = 0; x < errorList.length; x++){
      errorList[x].removeClassName('error');
    }
  }, //}}}

  //{{{ sendAsync:function(options)
  sendAsync:function(options){

    //options.onLoad, onSuccess, onFail need to be sent as onLoad:function(){ ... do something ...}
    //NOTE: if sending repos path info (or anything else that may get escaped by prototype) as a parameter, it may be best to send all params in the url, not as a param
    //Note: now that we're using a newer version of prototype, this may not be a problem

    var adminUrl   = (options.url)? options.url : '/admin';
    var params     = (options.params)? options.params : '';
    var evScripts  = (options.evalScripts==false)? false : true;
    var sendMethod = (options.sendMethod)? options.sendMethod : 'post';
    var async      = (options.async)? options.async : true;
    var updateElem = (options.updateElem)? $(options.updateElem) : false;
    var periodic   = (options.periodic==true)? true : false;
    var freq       = (options.frequency)? options.frequency : 15;
    var decay      = (options.decay)? options.decay : 1;

    var allParams  = {
      asynchronous:async,
      method:sendMethod,
      evalScripts:evScripts,
      parameters:params,
      onLoading:function(){
        if(typeof(options.onLoad) == 'function'){
          options.onLoad();
        }
        else{
          cmsUI.showAlert('Sending Data')
        }
      },
      onSuccess:function(req){
        if(typeof(options.onSuccess) == 'function'){
          options.onSuccess(req);
        }
        else{
          cmsUI.hideAlert();
        }
      },
      onFailure:function(){
        if(typeof(options.onFail) == 'function'){
          options.onFail();
        }
        else{
          alert("The server has returned an error.");
          try{
            if(typeof(Lightbox)!='undefined'){
              Lightbox.base.hideBox();
            }
            cmsUI.hideAlert();
          }
          catch(err){
          }
        }
      },
      onException:function(req,err){
        if(typeof(options.onException) == 'function'){
          options.onException();
        }
        else{
          if(window.console){console.log(err);}
          //alert("ajax exception caught");
        }
      }
    }
    
    if(options.onComplete){
      allParams.onComplete = function(req){
        options.onComplete(req);
      }
    }
    if(options.onLoaded){
      allParams.onLoaded = function(req){
        options.onLoaded(req);
      }
    }
    /* for(props in options){
      console.log(props);
    } */
    
    if(periodic){
      allParams.frequency = freq;
      allParams.decay     = decay;
      return new Ajax.PeriodicalUpdater(updateElem,adminUrl,allParams);
    }
    else if(updateElem){
      new Ajax.Updater(updateElem,adminUrl,allParams)
    }
    else{
      new Ajax.Request(adminUrl,allParams)
    }
  }, //}}}

  //{{{ stopAllAjax:function(options)
  stopAllAjax:function(options){
    var getClassName    = options.getClass;
    var allMessageAreas = $$('.'+getClassName);
    var suspend         = (options.suspend)? options.suspend : true
    
    $A(allMessageAreas).each(function(noticeArea){
      var messageElem  = $(noticeArea.id);
      if(suspend){
        messageElem.async.stop();
      }
      else{
        messageElem.async = '';
        messageElem.async = null;
      }
    });
    
  }, //}}}
  
  //{{{ startAllAjax:function(options)
  startAllAjax:function(options){
    var getClassName    = options.getClass;
    var allMessageAreas = $$('.'+getClassName);
    
    $A(allMessageAreas).each(function(noticeArea){
      var messageElem  = $(noticeArea.id);
      messageElem.async.start();
    });
      
  }, //}}}
  
  //{{{ disableActionButtons:function(options)
  disableActionButtons:function(options){
    var getClassName = options.getClassName
    $A($$('.'+getClassName)).each(function(button){
      if(button.nodeName.toLowerCase() == 'input' || button.nodeName.toLowerCase() == 'button'){
        button.disabled = true;
      }
    });
  }, //}}}
  
  //{{{ buildCal:function(options)
  buildCal:function(options){
    //AT: this is derived from http://www.dynamicdrive.com/dynamicindex7/basiccalendar.js - significant work was done to make all days objects in js

    //AT: changed arguments to variables from single JSON argument with defaults
    var m = options.month //required
    var y = options.year //required
    var container = options.container //required
    var mClass = (options.mClass)? options.mClass : '';
    var dClass = (options.dClass)? options.dClass : '';

    var mn=['January','February','March','April','May','June','July','August','September','October','November','December'];
    var dim=[31,0,31,30,31,30,31,31,30,31,30,31];

    var oD = new Date(y, m-1, 1); //DD replaced line to fix date bug when current day is 31st
    oD.od=oD.getDay()+1; //DD replaced line to fix date bug when current day is 31st
    var todaydate=new Date() //DD added
    var scanfortoday=(y==todaydate.getFullYear() && m==todaydate.getMonth()+1)? todaydate.getDate() : 0 //DD added

    dim[1]=(((oD.getFullYear()%100!=0)&&(oD.getFullYear()%4==0))||(oD.getFullYear()%400==0))?29:28;

    //AT: Changed string output to DOM structure for dynamic referencing
    containerObj = $(container);

    var calObj = cmsUI.createElement({element:'ul',elemClass:'calendar',elemId:'activity_calendar'});
    containerObj.appendChild(calObj);

    //Building out titles - month name, year
    //AT: TODO include option to generate select boxes for both
    var monthName = document.createTextNode(mn[m-1]+' - '+y);
    var monthNameObj = cmsUI.createElement({element:'li',elemClass:'month_name',elemId:'month_row'});
    monthNameObj.appendChild(monthName);
    calObj.appendChild(monthNameObj);

    //Building out Day Names
    for(s=0;s<7;s++){
      var dayName = document.createTextNode("SMTWTFS".substr(s,1));
      var dayNameObj = cmsUI.createElement({element:'li',elemClass:'day_name'});
      dayNameObj.appendChild(dayName);
      calObj.appendChild(dayNameObj);
    }
    var dayNameEndObj = cmsUI.createElement({element:'li',elemClass:'week_break'});
    calObj.appendChild(dayNameEndObj);

    //Building out all days in given month (will not generate text for leading/tailing days of other months)
    //AT: TODO - remove extra row if no days for current month exist
    for(i=1;i<=42;i++){
      var x=((i-oD.od>=0)&&(i-oD.od<dim[m-1]))? i-oD.od+1 : '';
      var date = document.createTextNode(x);
      var dayObj = cmsUI.createElement({element:'li',elemClass:'day'});

      if (x==scanfortoday){  dayObj.setAttribute('id','today'); }

      dayObj.appendChild(date)
      calObj.appendChild(dayObj);

      //Organizing weeks (clearing item inserted every 7 days to create row)
      if(((i)%7==0)&&(i<36)){
        var weekEndObj = cmsUI.createElement({element:'li',elemClass:'week_break'});
        calObj.appendChild(weekEndObj);
      }
    }

  }, //}}}

  //{{{ setActivityRecordCal:function()
    setActivityRecordCal:function(){

    $A(document.getElementsByTagName('UL')).each(function(calSet) {
      if(Element.hasClassName(calSet,'calendar')) {

        $A(calSet.getElementsByTagName('LI')).each(function(day) {
          if(Element.hasClassName(day,'day')) {
            Event.observe(day, 'mouseover', function(){
              day.addClassName('day_over');
            });

            Event.observe(day, 'mouseout', function(){
              day.removeClassName('day_over');
            });

            Event.observe(day, 'click', function(){
              alert('change date');
            });
          }
        });

      }
    });
    //console.dir(thisDay[16]);
  }, //}}}

  //{{{ createElement:function(options)
    createElement:function(options){
      /*
        AT: options argument has no defaults and is broken up into the following:
            - element   : required. type of element to be created
            - elemClass : optinal - given class
            - elemId    : optional - given id
            - elemTitle : optional - given title
      */
      var newElem = document.createElement(options.element);
      if(options.elemClass) {
        newElem.setAttribute('class',options.elemClass);
        newElem.className = options.elemClass; //AT: seperate class method added for IE, double usage here doesn't seem to interfere in FF or Opera
      }
      if(options.elemId) newElem.setAttribute('id',options.elemId);
      if(options.elemTitle) newElem.setAttribute('title',options.elemTitle);
      
      document.body.appendChild(newElem)
      //Return the new element as an HTMLElementObject
      return $(newElem);

  }, //}}}

  //{{{ tabs object
  tabs:{
    load:function(){
      
      //console.log('called');
      
      this.tabSets = $$('.tabs');
      if(typeof(this.tabSets)!='undefined'){
      
        this.tabSets.each(function(set){
            
          set.tabItems = Element.select(set, '.tab');
          set.tabItems.each(function(item){
              
            item.element = $(item);
            item.panel = $(item.id.substring(item.id.indexOf('tab_')+4));
            item.show = false;
            item.isDefault = Element.hasClassName(item, 'default');
            
            item.behaviour = function(){
              
              if(item.panel.title.indexOf('params:')!=-1){
                item.strtidx = item.panel.title.indexOf('params:' )+7;
                item.getAjaxDirective = {params:item.panel.title.substring(item.strtidx)};
                if(item.getAjaxDirective){
                  item.getAjaxDirective.isStatic = Element.hasClassName('static');
                  item.getAjaxDirective.onSuccess = function(){
                    cmsUI.hideAlert();
                    item.panel.style.display = 'block';
                    item.show = true;
                  };
                  item.getAjaxDirective.updateElem = item.panel.id;
                }
                item.panel.removeAttribute('title');
              }
              
              Event.observe(item.element, 'click', function(e){
                set.tabItems.each(function(allitems){
                  allitems.panel.style.display = 'none';
                  allitems.show = false;
                  Element.removeClassName(allitems, 'active');
                });
                if(item.getAjaxDirective){
                  item.getAjaxDirective.onLoad = function(){cmsUI.showAlert('Loading Content')};
                }
                item.showPanel();
              });
              
              if(item.isDefault){
                if(item.getAjaxDirective){
                  item.getAjaxDirective.onLoad = function(){};
                }
                item.showPanel();
              }
              else{
                item.panel.style.display = 'none';
              } 
            }
            
            item.showPanel = function(){
              
              Element.addClassName(item, 'active');
              
              if(item.getAjaxDirective){
                if(typeof(item.hasContent)=='undefined'){
                  cmsUI.sendAsync(item.getAjaxDirective);
                  item.hasContent = true;
                }
                else if(typeof(item.getAjaxDirective.isStatic)!='undefined' && item.hasContent == true){
                  item.panel.style.display = 'block';
                  item.show = true;
                }
              }
              else{
                item.panel.style.display = 'block';
                item.show = true;
              }
              
              var tabOptions = {
                name:set.id + 'Default',
                value:item.element.id
              }
              cmsUI.setCMSSiteVar(tabOptions);
            }
            
            item.behaviour();
            
          }.bind(this));
        }.bind(this));
      }
      
      //console.dir(this);
      
    }
  }, //}}}

  
  
  //{{{ setCMSSiteVar:(options)
  setCMSSiteVar:function(options) {
    
    var name    = options.name;
    var value   = options.value;
    var url     = (options.url)? options.url : CoreSiteVars.adminTool;
    //var refresh = (options.refreshOnComplete)? options.refreshOnComplete : false;
    
    var params  = 'action=template-cache-errors&CMSSiteVars='+name+':'+value;
    
    cmsUI.sendAsync({
      url:url,
      params:params,
      onLoad:function(){},
      onSuccess:function(){
        if(typeof(options.refreshOnComplete)=='function'){
          options.refreshOnComplete();
        }
        else if(typeof(options.refreshOnComplete)=='string'){
          location.href = unescape(options.refreshOnComplete);
        }
        else if(options.refreshOnComplete==true){
          if(location.search.indexOf(name)!=-1){ //Can't have a url param with the same name as the CMSSiteVar, values will be different
            var length = name.length;
            var searchArray = location.search.split('&');
            for(x = 0; x < searchArray.length; x++){
              if(searchArray[x].indexOf(name)!=-1){ searchArray.splice(x,1); }
            }
            location.search = searchArray.join('&');
          }
          else{
            location.reload();
          }
        }
      }
    })
  }, //}}}
  
  //{{{ toggleRows:function(){
  toggleRows:function(){
    
    this.toggleBlocks = $$('.toggleblock');
    this.quirksMode = cmsUI.ieBackCompat(this.toggleBlocks[0]);
    
    this.toggleBlocks.each(function(block){
      
      block.toggleSwitches = Element.select(block, '.toggleswitch');
      block.toggleRows = Element.select(block, '.toggle');
      
      block.toggleRows.each(function(row){
        //need to get element type - tr, li, etc
        switch(row.nodeName){
          case 'TR' :
            row.displayType = 'table-row';
            break;
            
          default:
            row.displayType = 'block';
            break;
        }
        
        if(this.quirksMode){ row.displayType = 'block'; }
        
      }.bind(this));
      
      block.toggleSwitches.each(function(tSwitch){
        Event.observe(tSwitch, 'click', function(e){
            tSwitch.show = (Element.hasClassName(tSwitch, 'show')) ? true : false
            block.toggleRows.each(function(row){
              row.style.display = (tSwitch.show) ? row.displayType : 'none';
              row.style.width   = (row.style.cssFloat!='' && tSwitch.show) ? 'auto' : null;
            });
            if(tSwitch.show){
              Element.removeClassName(tSwitch, 'show');
              Element.addClassName(tSwitch, 'Hide');
              tSwitch.innerHTML = 'hide';
            }
            else{
              Element.removeClassName(tSwitch, 'hide');
              Element.addClassName(tSwitch, 'show');
              tSwitch.innerHTML = 'Show';
            }
          e.stop();
        }.bind(block));
      });
      
    }.bind(this));
    
    //if(window.console){ console.dir(this); }

  }, //}}}

  //{{{ ieBackCompat:function()
  ieBackCompat:function(element){
    if((typeof(element.currentStyle)!='undefined')&&(typeof(element.currentStyle.hasLayout)=='boolean')&&(document.body)){ //was document.body
      
      var vIndex = window.navigator.appVersion.indexOf('MSIE');
      var ieAppVersion = parseFloat(window.navigator.appVersion.substring(vIndex+5));
      
      if(document.compatMode=='BackCompat' || ieAppVersion <= 6){
        return ieAppVersion;
      }
    }
    return false;
  }, //}}}
  
  //{{{ utils:
  utils:{
    checkBoxes: new Array(), // Update!!!
    allCheckboxSets: new Array(),
    cbCount:0,
    filterGroup:'',
    mostRecentCheckedBox:'',
    serialCB:'',
    noticeArea:'',
    isBlurred:false
  } //}}}
}

if(typeof(Prototype)!='undefined'){
  Event.observe(window,'load',function(){
    if($$('.toggleblock')[0]){
      new cmsUI.toggleRows();
    }
  }.bind(cmsUI.toggleRows));
  
  Event.observe(window,'load',function(){
    if($$('.cbroot')[0]){
      new cmsUI.checkboxes.build();
    }
  }.bind(cmsUI.checkboxes));

  Event.observe(window, 'load', function(e){
    cmsUI.tabs.load();
  }.bind(cmsUI.tabs));
}

/* AT:pulled from metainfo.xsl - may be only used in verions tab? */
function loadXMLDoc(params) {
  var versionContainer = $('cmsversions');
  var listContainer    = $('allVersions');
  var versionOptions = {
    updateElem:'cmsversions',
    params:'action=list-version-history&'+params,
    onLoad:function(){
      listContainer.innerHTML = 'Loading version history'
    },
    onSuccess:function(){}
  }
  cmsUI.sendAsync(versionOptions)
  versionContainer.removeAttribute('title');
}

//{{{ Lightbox.base.prototype = {   Override code for cms integration. Base object in /SYSTEM/template_resources/js/lightbox.js, dependant on prototype. Override dependant on scriptaculous
/*--------------------------------------------------------------------------*/
/*	Lightbox	
*	This is a script for creating modal dialog windows (like the ones your operating system uses)

  option object hierarchy:
  
   - theme: // light|{classname} - can add css themes - default is 'light'
   - closeOnOverlayClick: // false|true - behaviour setting for overlay - does as it says
   - createDraggable: // false|true - behaviour setting for message area, does not assume default
    
   - type: // msg|alert|form|async (note the fact that type:form will always submit using an ajax call)
    
   - content: // container for the dialog content presented to user
      - heading: // h1Fragment|{html} - title element for dialog, should pass html fragment as value ex: <h1>Hello</h1>, used by for all option.type values
      - msg: // inline text, used by for all option.type values
      - inputs: // only use if type:form, will loop through object properties and append to content as innerHTML
        - hidden1: // can be as many as needed, pass html fragment ex: <input type="hidden" ... />
        - label1: // form label, pass html ex: <label for="field1">Enter Text</label>
        - field1: // form field, pass html ex: <input id="field1" ... />
        
    - action: // arguments for handling the user inputs only if option.type:form - 
      - url: // will be used as form action attribute, as well as the ajax url
      - params: // extra parameters to be tacked on to the serialized form values
      - msg: // inline text
      - onLoad/onSuccess: // can pass in arbitrary functions to be performed by the cmsUI.sendAsync() call
      - refreshOnSuccess: // true|{url} if true, refreshes current page; if {url}, loads the url into location.href
      
    - asyncOptions : // object to be passed to the cmsUI.sendAsync function

*/

if(typeof(Lightbox)!='undefined'){
  Lightbox.base.prototype = {
    //{{{ initialize:function(element, options)
    initialize:function(element, options){
      //start by hiding all lightboxes, menus, etc
      Lightbox.hideAll();
      cmsMenusUI.hideAll();
      //need to also hide the content and top toolbar menus
      this.element = $(element); //Add check here to see if content exists
      this.element.innerHTML = '';
      this.quirksMode = this.isBackCompat();
      this.options = Object.extend({
        lightboxClassName : 'box',
        closeOnOverlayClick : false,
        externalControl : false
      }, options || {} )
  
      //initial setup will create the containers, and pupolate the message area with whatver is needed.
      //the positioning will be handled upon successfull completion of the content calls.
      this.createContainers();
      this.getContent();
    }, //}}}
    
    //{{{ createContainers:function()
    createContainers:function(){
      //create the overlay
      
      var theme = (this.options.theme) ? this.options.theme : 'light' ;
      
      new Insertion.Before(this.element, "<div id='overlay' class='"+theme+"overlay' style='display:none;'></div>");
      this.overlay = $('overlay');
      
      Element.addClassName(this.element, theme+this.options.lightboxClassName);
    
      //also add a default lbox class to the lightbox div so we can find and close all lightboxes if we need to
      Element.addClassName(this.element, 'lbox');
      
      var lboxContent = "<div title='close' class='lightbox_close' id='lightbox_close'></div><div class='wrapper'><div class='lightbox_head'><div class='lightbox_msg' id='lightbox_msg'></div></div></div><div class='lightbox_foot' ><div class='lightbox_foot_rt' ></div></div>";
      new Insertion.Top(this.element, lboxContent);
      
      this.messageActive = true;
      
      //console.dir(this.element);
      
      this.contentArea = $('lightbox_msg');
      
      if(this.options.createDraggable && this.quirksMode > 6 || this.quirksMode == false){
        var thisOverlay = this.overlay
        Element.addClassName(this.element, 'dragHandle');
        Event.observe(this.contentArea, 'mousedown', function(event){
          if(event.stopPropagation){
            event.stopPropagation();
          }
          else{
            event.cancelBubble = true;
          }
        });
        Event.observe(this.contentArea, 'mouseup', function(event){
          if(event.stopPropagation){
            event.stopPropagation();
          }
          else{
            event.cancelBubble = true;
          }
        });
        var dragOptions = {
          handle:'dragHandle'
        }
        new Draggable(this.element);
        
        if(this.quirksMode!=false){
          Event.observe(this.element, 'mouseout', function(event){
            //alert(document.body.scrollHeight);
            //alert(document.body.clientHeight);
            thisOverlay.style.height = (document.body.scrollHeight >= document.documentElement.clientHeight) ? document.body.scrollHeight : document.documentElement.clientHeight;
          });
        }
      }
      
      Event.observe($('lightbox_close'), 'click', this.hideBox.bindAsEventListener(this) );
      
      if (this.options.closeOnOverlayClick){
        Event.observe(this.overlay, 'click', this.hideBox.bindAsEventListener(this) );
      }
      if (this.options.externalControl){
        Event.observe($(this.options.externalControl), 'click', this.hideBox.bindAsEventListener(this) );
      }
    }, //}}}
    
    //{{{ getContent:function()
    getContent:function(){
      if(this.element.style.visibility){ this.element.style.visibility = '';}
      //this.element.style.width = 'auto'; // can get overriden later if needed.
      
      /* Choose what popup type to present */
      //{{{ switch(this.options.type){
      switch(this.options.type){
        
        //Basic message to user, not requiring any input or directives from user, will not autohide.
        case 'msg':
          $('lightbox_close').style.display = 'none';
          this.contentArea.innerHTML = this.options.content.msg;
          this.showBox();
          break;
          
        //Basic alert to user, not requiring any input aside from an ok
        case 'alert':
        
          msgElems = '<div>'+this.options.content.msg+'</div>';
          msgElems += '<div id="lbox_btn_row" class="lbox_btn_row"><button id="lbox_ok">Close</button></div>';
          new Insertion.Top(this.contentArea, msgElems);
          
          this.okbtn = $('lbox_ok');
          Event.observe(this.okbtn, 'click', this.hideBox.bindAsEventListener(this));
          this.showBox();
          break;
          
        //Any kind of simple form to be used to get user input, best for simple text fields, yes/no type of inputs etc. Anything complex and/or requiring validation should use type:async
        case 'form':
          
          var heading     = (this.options.content.heading) ? this.options.content.heading : '<h1>Your input is required</h1>';
          var refreshOnSuccess  = (this.options.action.refreshOnSuccess)? this.options.action.refreshOnSuccess : null;
          var extraParams  = (this.options.action.params)? this.options.action.params : '';
          
          this.contentArea.innerHTML = heading
          
          var formElems = '<form action="'+this.options.action.url+'" id="lbox_form" class="surveyform" ><fieldset>';
          formElems += '<legend>' + this.options.content.msg + '</legend>';
          if((this.options.content.inputs)){
            var getInputs = Object.values(this.options.content.inputs);
            for(x = 0; x < getInputs.length; x++){
              formElems += unescape(getInputs[x]);
            }
          }
          formElems += '<div id="lbox_btn_row" class="lbox_btn_row"><button type="submit" id="lbox_ok">Continue</button><button type="reset" id="lbox_cancel">Cancel</button></div>';
          formElems += '</fieldset></form>';

          new Insertion.Bottom(this.contentArea, formElems);
          
          this.form = $('lbox_form');
          this.fields = Form.getElements(this.form);
          this.fields.each(function(field){
            field.lboxField = true;
          });
          this.cancelbtn = $('lbox_cancel');
          
          Event.observe(this.form, 'submit', function(){
            Element.hide(this.element);
            
            var thisBox = this;
            
            formVals = Form.serialize(this.form, false) + extraParams;

            this.contentArea.innerHTML = unescape(this.options.action.msg);
            this.showBox();
                  
            cmsUI.sendAsync({
              url:this.options.action.url,
              params:formVals,
              onLoad:function(){
                if(typeof(thisBox.options.action.onLoad)=='function'){
                  thisBox.options.action.onLoad();
                }
              },
              onSuccess:function(req){
                if(typeof(thisBox.options.action.onSuccess)=='function'){
                  thisBox.options.action.onSuccess(req);
                }
                else if(typeof(refreshOnSuccess)=='string'){
                  if(typeof(cmsUI.utils.checkBoxes[0]) != 'undefined') { cmsUI.updateCheckBoxes(false); }
                  location.href = unescape(refreshOnSuccess);
                }
                else if(refreshOnSuccess==true){
                  if(typeof(cmsUI.utils.checkBoxes[0]) != 'undefined') { cmsUI.updateCheckBoxes(false); }
                  location.reload();
                }
                else{
                  thisBox.hideBox();
                }
              }
            });
            return false;
            
          }.bind(this));
          
          Event.observe(this.cancelbtn, 'click', this.hideBox.bindAsEventListener(this));
          
          this.showBox();
          break;
         
        //Use for any complex messages, forms, wizards, dynamic lists, etc. Will only present what is returned from the ajax call.
        case 'async':
          this.options.content.asyncOptions.updateElem = this.contentArea;
          this.options.content.asyncOptions.onLoad = function(){
            this.contentArea.innerHTML = 'Loading...';
            this.showBox();
          }.bind(this);
          this.options.content.asyncOptions.onSuccess = function(req){
            Element.hide(this.element);
            this.contentArea.innerHTML = req.responseText;
            this.element.style.width = this.options.content.width;
            this.element.style.height = this.contentArea.style.height;
            this.showBox();
          }.bind(this);
          this.asyncContent = cmsUI.sendAsync(this.options.content.asyncOptions);
          break;
        
        default:
          this.contentArea.innerHTML = 'Sorry, unknown action.';
          this.showBox();
          break;
      } //}}}
  
    }, //}}}
    
    //{{{ showBox:function()
    showBox:function(){
       //show the overlay
       var overlayOpacity = (this.options.overlayOpacity) ? this.options.overlayOpacity : 0.5;

       Element.setOpacity(this.overlay, overlayOpacity);
       Element.show(this.overlay);
       /* new Effect.Opacity(this.overlay, { from: 0.1, to: 0.75, duration: 0.2 }); */
       //center the lightbox
       this.center();
       //show the lightbox
       Element.show(this.element);
       //AT: added this to show the element (needed if using the cmsContextMenuDiv element)
       this.element.style.display = 'block';
       
       return false;
    }, //}}}
    
    //{{{ hideBox:function(evt)
    hideBox:function(evt){	
      this.messageActive = null;
      Element.removeClassName(this.element, this.options.lightboxClassName);
      this.element.setStyle({
        width:'auto',
        zIndex:'',
        left:'0',
        top:'0'
      });
      this.element.className = '';
      Element.hide(this.element);
      //remove the overlay element from the DOM completely
      Element.remove(this.overlay);
      this.element.innerHTML = '';
      if(this.quirksMode){
        var allHidden = $$('.hidden_by_lightbox');
        for(x=0; x<allHidden.length; x++){
          allHidden[x].style.visibility = 'visible';
          Element.removeClassName(allHidden[x], 'hidden_by_lightbox');
        }
      }
      return false;
    }, //}}}
      
    //{{{ center:function()
    center:function(){
      
      var my_width  = 0;
      var my_height = 0;
      
      if ( typeof( window.innerWidth ) == 'number' ){
        my_width  = window.innerWidth;
        my_height = window.innerHeight;
      }else if ( document.documentElement && 
           ( document.documentElement.clientWidth ||
             document.documentElement.clientHeight ) ){
        my_width  = document.documentElement.clientWidth;
        my_height = document.documentElement.clientHeight;
      }
      else if ( document.body && 
          ( document.body.clientWidth || document.body.clientHeight ) ){
        my_width  = document.body.clientWidth;
        my_height = document.body.clientHeight;
        
      }
      
      this.element.style.position = 'absolute';
      this.element.style.zIndex   = 9999;
      
      var scrollY = 0;
      
      if ( document.documentElement && document.documentElement.scrollTop ){
        scrollY = document.documentElement.scrollTop;
      }else if ( document.body && document.body.scrollTop ){
        scrollY = document.body.scrollTop;
      }else if ( window.pageYOffset ){
        scrollY = window.pageYOffset;
      }else if ( window.scrollY ){
        scrollY = window.scrollY;
      }
      
      //if(window.console)console.log(window);
      //if(window.console)console.dir($('contentPreview'));
      
      //need to do stuff just for IE <= 6 and IE 7 quirks mode
      if(this.quirksMode){
        
        this.overlay.style.width = my_width;
        this.overlay.style.height = (document.body.clientHeight >= document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
        
        this.contentArea.style.width = Element.getWidth(this.contentArea) + 3 + "px";
        this.contentArea.style.height = Element.getHeight(this.contentArea) + 3 + "px";
        if($('lbox_btn_row')){$('lbox_btn_row').style.width = '100%';}
        
        this.element.style.height = Element.getHeight(this.contentArea) + 70 + "px";
        this.element.style.width = 'auto';
        
        //Need to hide all select boxes, iframes which display xml trees
        var allSelects = document.getElementsByTagName('SELECT');
        for(x=0; x<allSelects.length; x++){
          if(allSelects[x].lboxField != true){
            allSelects[x].style.visibility = 'hidden';
            Element.addClassName(allSelects[x], 'hidden_by_lightbox');
          }
        }
        var allIframes = document.getElementsByTagName('IFRAME');
        for(x=0; x<allIframes.length; x++){
          if(allIframes[x].contentWindow.document.firstChild.innerText.indexOf('<?xml')!=-1){ //allIframes[x].contentWindow.document.documentElement.lastChild.innerText.indexOf('<?xml')!=-1
            allIframes[x].style.visibility = 'hidden';
            Element.addClassName(allIframes[x], 'hidden_by_lightbox');
          }
        }
        
      }
      
      var elementDimensions = Element.getDimensions(this.element);
      
      var setX = ( my_width  - elementDimensions.width  ) / 2;
      var setY = ( my_height - elementDimensions.height ) / 2.75 + scrollY;
      
      setX = ( setX < 0 ) ? 0 : setX;
      setY = ( setY < 0 ) ? 0 : setY;
      
      this.element.style.left = setX + "px";
      this.element.style.top  = setY + "px";
      
    }, //}}}
  
    //{{{ isBackCompat:function(){
    isBackCompat:function(){
      if((typeof(this.element.currentStyle)!='undefined')&&(typeof(this.element.currentStyle.hasLayout)=='boolean')&&(document.body)){ //was document.body
        
        var vIndex = window.navigator.appVersion.indexOf('MSIE');
        var ieAppVersion = parseFloat(window.navigator.appVersion.substring(vIndex+5));
        
        if(document.compatMode=='BackCompat' || ieAppVersion <= 6){
          return ieAppVersion;
        }
      }
      return false;
    } //}}}
  }
}
//}}}

//{{{ var cmsPlugin = {
var cmsPlugin = {
  load:function(){
    this.actions = new cmsPlugin.getPluginActions();
    /* if(window.console) console.dir(this); */
  },
  getPluginActions:function(){
    for(funct in this){
      if(typeof(this[funct])=='function'){
        this[funct]();
      }
    }
  }
}

if(typeof(Prototype)!='undefined'){
  Event.observe(window, 'load', function(e){
    cmsPlugin.load(); //Update!!!
  }.bind(cmsPlugin));
} //}}}

//{{{ cmsPlugin.getPluginActions.prototype.checkboxes = function(){
cmsPlugin.getPluginActions.prototype.checkboxes = function(){
  //Create the base container (don't use this, instead use this.functionname)
  boxes = this.checkboxes;
  boxes.rootClassName = 'cb-root-all';
  //ancestor index is the index location for each root's ancestor this is to grab the descendants for the checkbox group
  boxes.ancestorIndex = 0;
  //{{{ boxes.utils = {
  boxes.utils = {
    allCheckBoxes: new Array()
  } //}}}
  
  //Define all behaviour. Buildsets collects the checkboxes into groups and assigns events
  //{{{ boxes.buildSets = function()
  boxes.buildSets = function(){
    //Grab all checkbox sets. Script assumes a proper heirarchy where at least one checkbox is set to select all
    boxes.allSets = $$('.'+boxes.rootClassName);
    boxes.allLabels  = $A(document.getElementsByTagName('LABEL'));
    
    boxes.allSets.each(function(absRoot){
      //Create the absolute root for each set, define all group properties and methods
      Element.removeClassName(absRoot, boxes.rootClassName);
      $A(absRoot.classNames()).each(function(cName){
          if(cName.indexOf('ancestorIdx-')!=-1){
            absRoot.ancestorIdx = cName.substring(12);
            Element.removeClassName(absRoot, cName);
          }
      });
      absRoot.mostRecentLocation;
      absRoot.groupName = absRoot.className;
      absRoot.wholeGroup = $$('.'+absRoot.className);
      
      var indexCounter = 0;
      
      absRoot.wholeGroup.each(function(cb){
          
          boxes.utils.allCheckBoxes.push(cb);
          cb.indexLoc = indexCounter;
          //Get Label associations for all checkboxes
          boxes.allLabels.each(function(label){
              //console.log('label = '+label.htmlFor);
              //console.log('checkbox id = '+cb.id);
              if(label.htmlFor == cb.id){
                //console.log('matched');
                cb.label = label;
              }
          });
          
          //Find tiered root boxes, seperate them out into sub groups
          if(cb.className.indexOf('root-')!=-1){
            $A(cb.classNames()).each(function(cName){
                  if(cName.indexOf('root-')!=-1){
                    cb.rootOf = cName.substring(5);
                  }
              });
            //set the ancestor index, either using default(looks for immediate parent node) or runtime override
            if(cb.className.indexOf('ancestorIdx-')!=-1){
              $A(cb.classNames()).each(function(cName){
                  if(cName.indexOf('ancestorIdx-')!=-1){
                    cb.ancestorIdx = cName.substring(12);
                  }
              });
            }
            else{
              cb.ancestorIdx = boxes.ancestorIndex;
            }
            
            cb.group = Element.ancestors(cb)[cb.ancestorIdx].descendants();
            
          }
          
          Event.observe(cb, 'click', function(e){
              //console.dir(cb);
              var thisBox = cb.indexLoc
              if(cb.group){
                cb.group.each(function(child){
                    if(typeof(child.checked)=='boolean'){
                      child.checked = cb.checked;
                    }
                });
              }
              if(e.shiftKey){
                var shiftBox;
                var shiftSet;
                absRoot.wholeGroup.each(function(check){
                  if(check.indexLoc == absRoot.mostRecentLocation){
                    shiftBox = check.indexLoc;
                  }
                });
                //splice the array so that the new set is only from a to b
                var shiftSet = (thisBox > shiftBox)? shiftSet = absRoot.wholeGroup.slice(shiftBox,thisBox) : shiftSet = absRoot.wholeGroup.slice(thisBox,shiftBox);
                for(c=0; c < shiftSet.length; c++){
                  shiftSet[c].checked = absRoot.wholeGroup[shiftBox].checked;
                }
              }
              absRoot.mostRecentLocation = cb.indexLoc;
              e.cancelBubble = true;
          });
          
          indexCounter++;
      });
      
      Event.observe(absRoot, 'click', function(e){
          absRoot.wholeGroup.each(function(cb){
              if(typeof(cb.checked)=='boolean'){
                cb.checked = absRoot.checked;
              }
          });
      });
      
    });
  } //}}}

  //{{{ boxes.grabSelectedCheckBoxes = function(options)
  boxes.grabSelectedCheckBoxes = function(options){
    var name        = options.name;
    var cbArray     = (options.cbArray)? options.cbArray : boxes.utils.allCheckBoxes;
    var classCheck  = (options.cbClass)? options.cbClass : null;
    var tryVirtual  = (options.tryVirtual)? options.tryVirtual : false;
    var returnArray = new Array();
    
    if(classCheck){
      for (i=0; i < cbArray.length; i++) {
        var ckClass = cbArray[i].hasClassName(classCheck);
        if(cbArray[i].checked && ckClass==true && cbArray[i].name==name){
          var cbSiblings = cbArray[i].siblings();
          if(tryVirtual && cbSiblings[1]){
            returnArray.push(cbSiblings[1]);
          }
          else{
            returnArray.push(cbArray[i]);
          }
        }
      }
      return returnArray;
    }
    else{
      for (i=0; i < cbArray.length; i++) {
        if(cbArray[i].checked && cbArray[i].name==name ){
          var cbSiblings = cbArray[i].siblings();
          if(tryVirtual && cbSiblings[1]){
            returnArray.push(cbSiblings[1]);
          }
          else{
            returnArray.push(cbArray[i]);
          }
        }
      }
      return returnArray;
    }

  } //}}}
  
  //{{{ boxes.serializeCheckedBoxes = function(options)
  boxes.serializeCheckedBoxes = function(options){ 
    var name         = options.name;
    var useProp      = (options.property)? options.property : 'value';
    var rtrnString   = '';
    var ueMode       = (options.ueMode) ? options.ueMode : '';
    var searchQuery  = (options.searchQuery) ? options.searchQuery : '**Exact**RepositoryPath';
    var selectedCB   = boxes.grabSelectedCheckBoxes(options);
    var uniqueVals   = cmsUI.getUniqueArrayValues({arrayObj:selectedCB, property:useProp});

    //console.log(selectedCB);
    //console.log(uniqueVals);
    
    for (i=0; i < uniqueVals.length; i++) {
      if(ueMode == 'searchTaskActions'){
        rtrnString += '"' + uniqueVals[i] + '"';
        if(i != uniqueVals.length-1){
          rtrnString += ' OR ';
        }
      }
      /* JJ-2008.2.5: added this case to gather all the checked items in search results page in pipe separated list */
      else if(ueMode == 'getCheckedItems'){
        rtrnString += uniqueVals[i] + "|";
      }
      else{
        rtrnString += '&' + name + '=' + uniqueVals[i];
      }
    }

    if(ueMode == 'searchTaskActions' && rtrnString != ''){
      /* rtrnString = '&searchTerm=' + searchQuery + ':(' + rtrnString + ')'; */
      rtrnString = searchQuery + ':(' + rtrnString.replace(/&/g,'%26') + ')';
    }
    /* alert("returnString= " + rtrnString); */
    return rtrnString;
  } //}}}
  
  //{{{ boxes.getGroupByName = function(options)
  boxes.getGroupByName = function(options){
    var keyName = options.name;
    var returnGroup;
    //AT: may need to be more robust in the future
    
    //console.dir(options)
    
    boxes.allSets.each(function(set){
      if(set.groupName == keyName){
        returnGroup = set.wholeGroup;
      }
    });
    return returnGroup;
  } //}}}
  
  //{{{ boxes.updateCheckBoxes = function(checked)
  boxes.updateCheckBoxes = function(checked){
    for (i=0; i < boxes.utils.allCheckBoxes.length; i++) {
      boxes.utils.allCheckBoxes[i].checked = checked;
    }
  } //}}}

  boxes.checkParents = function(options){
    //get the parent of the current rootBox
    var rootBox        = options.root;
    var boxDescendants = options.descendants;

    /* AT:need to think about this a little further, not needed right now */
  }
  
  //Load automatically
  if($$('.'+boxes.rootClassName)[0]) boxes.buildSets();
} //}}}



//{{{ var cmsToolBar = { //AT:only set up right now to handle the collapsed toolbar in the persistent preview mode
if(typeof(CoreSiteVars)!='undefined'){
  var cmsToolBar = {
    
    build:function(){
      if((CoreSiteVars.cmscontext=='staging') && (CoreSiteVars.preview=='true') && ($('cmstoobarcollapsed'))){
        
        var collapsed = $('cmstoobarcollapsed');
        var exitLink = $('exitlink');
        
        Event.observe(collapsed, 'mouseover', function(e){
          collapsed.style.height = '21px';
          Element.show(exitLink);
        });
        Event.observe(collapsed, 'mouseout', function(e){
          collapsed.style.height = '';
          Element.hide(exitLink);
        });
      }
    }
  }
  //cmsMenusUI.buildMenus();
  if(typeof(Prototype)!='undefined'){
    Event.observe(window,'load',function(){cmsToolBar.build()});
  }
}
//}}}

/* For Search Result Actions Menu */
//{{{ var searchTermAction = {
var searchTermAction = {
  build:function(options){
   var searchTasks = $A(Element.select($('SearchActionsMenu'), '.cmsmenuitem'));

   searchTasks.each(function(node){
        Event.observe(node.id, 'mouseout', function(event){
          node.className = 'cmsmenuitem';
        }.bind(this));

        Event.observe(node.id, 'mouseover', function(event){
          node.className = 'cmsmenuitemup';
        }.bind(this));

         if(node.id == 'SA_create_patch'){
           Event.observe(node.id, 'click', function(event){
             var params = '&taskName=create-patch&includeCollectionMeta=1&tag=' + options.tag;
             cmsUI.submitCheckedItems({admin:'action=search-task', parameters:params, ueMode:'searchTaskActions', wfAction:'create patch', searchQuery:options.searchQuery, loadMsg:'Creating a patch'});
             return false;
           }.bind(this));
         }
         else if(node.id == 'SA_publish'){
           Event.observe(node.id, 'click', function(event){
             if (confirm('Publish all these items?')){
               var params = '&taskName=publish&tag=' + options.tag;
               cmsUI.submitCheckedItems({admin:'action=search-task', parameters:params, ueMode:'searchTaskActions', wfAction:'publish', searchQuery:options.searchQuery, loadMsg:'Publishing files'});
               return false;
             }
           }.bind(this));
         }
         else if(node.id == 'SA_unpublish'){
           Event.observe(node.id, 'click', function(event){
             if (confirm('Unpublish all these items?')){
               var params = '&taskName=unpublish&tag=' + options.tag;
               cmsUI.submitCheckedItems({admin:'action=search-task', parameters:params, ueMode:'searchTaskActions', wfAction:'unpublish', searchQuery:options.searchQuery, loadMsg:'Unpublishing files'});
               return false;
             }
           }.bind(this));
         }
         else if(node.id == 'SA_lock'){
           Event.observe(node.id, 'click', function(event){
             if (confirm('Lock all these items?')){
               var params = '&taskName=lock&tag=' + options.tag;
               cmsUI.submitCheckedItems({admin:'action=search-task', parameters:params, ueMode:'searchTaskActions', wfAction:'lock', searchQuery:options.searchQuery, loadMsg:'Locking files'});
               return false;
             }
           }.bind(this));
         }
         else if(node.id == 'SA_unlock'){
           Event.observe(node.id, 'click', function(event){
             if (confirm('Unlock all these items?')){
               var params = '&taskName=unlock&tag=' + options.tag;
               cmsUI.submitCheckedItems({admin:'action=search-task', parameters:params, ueMode:'searchTaskActions', wfAction:'unlock', searchQuery:options.searchQuery, loadMsg:'Unlocking files'});
               return false;
             }
           }.bind(this));
         }
         else if(node.id == 'SA_modify_security'){
           Event.observe(node.id, 'click', function(event){
             var params = '&taskName=security&tag=' + options.tag;
             cmsUI.submitCheckedItems({admin:'action=task-popup', parameters:params, ueMode:'searchTaskActions', wfAction:'modify security', searchQuery:options.searchQuery, windowParam:'status=no,height=442px,width=510px,scrollbars=no,resizable=no,menubar=no,toolbar=no'});
             return false;
           }.bind(this));
         }
         else if(node.id == 'SA_modify_owner'){
           Event.observe(node.id, 'click', function(event){
             var params = '&taskName=chown&tag=' + options.tag;
             cmsUI.submitCheckedItems({admin:'action=task-popup', parameters:params, ueMode:'searchTaskActions', wfAction:'modify owner', searchQuery:options.searchQuery, windowParam:'status=no,height=442px,width=510px,scrollbars=no,resizable=no,menubar=no,toolbar=no'});
             return false;
           }.bind(this));
         }
         else if(node.id == 'SA_modify_workflow'){
           Event.observe(node.id, 'click', function(event){
             var params = '&taskName=workflow&tag=' + options.tag;
             cmsUI.submitCheckedItems({admin:'action=task-popup', parameters:params, ueMode:'searchTaskActions', wfAction:'modify workflow', searchQuery:options.searchQuery, windowParam:'status=no,height=442px,width=510px,scrollbars=no,resizable=no,menubar=no,toolbar=no'});
             return false;
           }.bind(this));
         }
         else if(node.id == 'SA_modify_xmlprop'){
           Event.observe(node.id, 'click', function(event){
             var params = '&taskName=xmlprops&searchLocales=true&tag=' + options.tag;
             cmsUI.submitCheckedItems({admin:'action=task-popup', parameters:params, ueMode:'searchTaskActions', wfAction:'modify xml props', searchQuery:options.searchQuery, windowParam:'status=no,height=442px,width=510px,scrollbars=no,resizable=no,menubar=no,toolbar=no'});
             return false;
           }.bind(this));
         }
         else if(node.id == 'SA_propose_review'){
           Event.observe(node.id, 'click', function(event){
              var params = '&tag=' + options.tag + '&currentLocale='+options.locale;
              cmsUI.submitCheckedItems({
                checkBranch:true,
                wfAction:'review',
                tryVirtual:true,
                heading:'<h1>Review Request</h1>',
                msg:'You are proposing the review of multiple checked documents',
                inputs:{
                  hidden1:'<input type="hidden" name="action" value="review-request" />',
                  label1:'<label for="reviewText" style="display:block;">Enter comment:</label>',
                  field1:'<textarea id="reviewText" name="reviewText" rows="6" cols="50"></textarea>'
                }, 
                parameters:params, 
                refreshOnSuccess:true,
                ueMode:'Lightbox', 
                actionTxt:'Proposing review', 
                searchQuery:options.searchQuery
              });
              return false;
           }.bind(this));
         }
         else if(node.id == 'SA_accept_review'){
           Event.observe(node.id, 'click', function(event){
              var params = '&tag=' + options.tag + '&currentLocale='+options.locale;
              cmsUI.submitCheckedItems({
                checkBranch:true,
                wfAction:'accept',
                tryVirtual:true,
                heading:'<h1>Accept Review</h1>',
                msg:'You are accepting mulitple reviewed documents',
                inputs:{
                  hidden1:'<input type="hidden" name="action" value="review-response" />',
                  hidden2:'<input type="hidden" name="reviewStatus" value="accept" />',
                  label1:'<label for="reviewText" style="display:block;" >Enter comment:</label>',
                  field1:'<textarea id="reviewText" name="reviewText" rows="6" cols="50"></textarea>'
                }, 
                parameters:params, 
                refreshOnSuccess:true,
                ueMode:'Lightbox', 
                actionTxt:'Acccepting review', 
                searchQuery:options.searchQuery
              });
              return false;
           }.bind(this));
         }
         else if(node.id == 'SA_reject_review'){
           Event.observe(node.id, 'click', function(event){
              var params = '&tag=' + options.tag + '&currentLocale='+options.locale;
              cmsUI.submitCheckedItems({
                checkBranch:true,
                wfAction:'reject',
                tryVirtual:true,
                heading:'<h1>Reject Review</h1>',
                msg:'You are rejecting mulitple reviewed documents',
                inputs:{
                  hidden1:'<input type="hidden" name="action" value="review-response" />',
                  hidden2:'<input type="hidden" name="reviewStatus" value="reject" />',
                  label1:'<label for="reviewText" style="display:block;">Enter comment:</label>',
                  field1:'<textarea id="reviewText" name="reviewText" rows="6" cols="50"></textarea>'
                }, 
                parameters:params, 
                refreshOnSuccess:true,
                ueMode:'Lightbox', 
                actionTxt:'Rejecting review', 
                searchQuery:options.searchQuery
              });
              return false;
           }.bind(this));
         }
         else if(node.id == 'SA_delete'){
           Event.observe(node.id, 'click', function(event){
             if (confirm('Do you really want to permanently delete all these items (including all version history)?')){
               var params = '&taskName=delete&tag=' + options.tag;
               cmsUI.submitCheckedItems({admin:'action=search-task', parameters:params, ueMode:'searchTaskActions', wfAction:'delete', searchQuery:options.searchQuery, loadMsg:'Deleting files'});
               return false;
             }
           }.bind(this));
         }
         else if(node.id == 'SA_query_replace'){
           Event.observe(node.id, 'click', function(event){
             var params = '&taskName=query-replace&searchLocales=true&tag=' + options.tag;
             cmsUI.submitCheckedItems({admin:'action=task-popup', parameters:params, ueMode:'searchTaskActions', wfAction:'replace query', searchQuery:options.searchQuery, windowParam:'status=no,height=442px,width=510px,scrollbars=no,resizable=no,menubar=no,toolbar=no'});
             return false;
           }.bind(this));
         }
         else if(node.id == 'SA_transform'){
           Event.observe(node.id, 'click', function(event){
             var params = '&taskName=transform&searchLocales=true&tag=' + options.tag;
             cmsUI.submitCheckedItems({admin:'action=task-popup', parameters:params, ueMode:'searchTaskActions', wfAction:'transform', searchQuery:options.searchQuery, windowParam:'status=no,height=442px,width=510px,scrollbars=no,resizable=no,menubar=no,toolbar=no'});
             return false;
           }.bind(this));
         }
         else if(node.id == 'SA_checkout'){
           Event.observe(node.id, 'click', function(event){
             var params = '&taskName=activate&tag=' + options.tag;
             cmsUI.submitCheckedItems({admin:'action=search-task', parameters:params, ueMode:'searchTaskActions', wfAction:'activate', searchQuery:options.searchQuery, loadMsg:'Checking out files'});
             return false;
           }.bind(this));
         }
         else if(node.id == 'SA_revert'){
           Event.observe(node.id, 'click', function(event){
              var params = '&tag=' + options.tag + '&currentLocale='+options.locale;
              cmsUI.submitCheckedItems({
                wfAction:'revert',
                heading:'<h1>Revert Content Item</h1>',
                msg:'Revert to the current Trunk version of this content item?',
                inputs:{
                  hidden1:'<input type="hidden" name="action" value="revert-to-trunk" />'
                }, 
                parameters:params, 
                refreshOnSuccess:true,
                ueMode:'Lightbox', 
                actionTxt:'Reverting', 
                searchQuery:options.searchQuery
              });
              return false;
           }.bind(this));
         }
         else if(node.id == 'SA_change_locales'){
           Event.observe(node.id, 'click', function(event){
             var params = '&taskName=resetlocales&tag=' + options.tag;
             cmsUI.submitCheckedItems({admin:'action=task-popup', parameters:params, ueMode:'searchTaskActions', wfAction:'reset locales', searchQuery:options.searchQuery, windowParam:'status=no,height=442px,width=510px,scrollbars=no,resizable=no,menubar=no,toolbar=no'});
             return false;
           }.bind(this));
         }
         else if(node.id == 'SA_update_document'){
           Event.observe(node.id, 'click', function(event){
             if (confirm('Update all these documents?')){
               var params = '&taskName=updateDocument&tag=' + options.tag;
               cmsUI.submitCheckedItems({admin:'action=search-task', parameters:params, ueMode:'searchTaskActions', wfAction:'update', searchQuery:options.searchQuery, loadMsg:'Updating documents'});
               return false;
             }
           }.bind(this));
         }
         else if(node.id == 'SA_merge_publish_document'){
           Event.observe(node.id, 'click', function(event){
             if (confirm('Merge all these documents?')){
               var params = '&taskName=mergeDocument&publish=true&tag=' + options.tag;
               cmsUI.submitCheckedItems({admin:'action=search-task', parameters:params, ueMode:'searchTaskActions', wfAction:'update', searchQuery:options.searchQuery, loadMsg:'Merging documents'});
               return false;
             }
           }.bind(this));
         }
         else if(node.id == 'SA_merge_export_document'){
           Event.observe(node.id, 'click', function(event){
             if (confirm('Merge all these documents?')){
               var params = '&taskName=mergeDocument&publish=no&tag=' + options.tag;
               cmsUI.submitCheckedItems({admin:'action=search-task', parameters:params, ueMode:'searchTaskActions', wfAction:'update', searchQuery:options.searchQuery, loadMsg:'Merging documents'});
               return false;
             }
           }.bind(this));
         }
   });
  }
} //}}}


//function

var currentPane = null;
var currentItem = null;
var currentInfo = null;
function updatePane(id, path)
{
  updatePane2(id, path, 'admin?action=view&tag=HEAD&path=', '&ieFriendly=true'); 
  //'admin?action=document&path=', '&includeContent=yes&xslt=levelcms://HEAD/SYSTEM/stylesheets/top_level.xsl&userMenuContextMode=staging&amp;allowIncontext=false'
}
function updatePane2(id, url, urlPrefix, urlSuffix)
{
  if (currentPane != null) {
    currentPane.style.display = 'none';
  }
  currentPane = document.getElementById('pph' + id);
  currentPane.style.display = '';
  updateIFrame('contentPreview',urlPrefix + url + urlSuffix);
  if (currentItem != null) {
    currentItem.style.backgroundColor = '';
    currentItem.style.color = '';
  }
  currentItem = document.getElementById('item' + id);
  currentItem.style.backgroundColor = '#3c8ac4';
  currentItem.style.color = '#ffffff';
  if (currentInfo != null) {
    currentInfo.style.display = 'none';
    currentInfo.style.visibility = 'hidden';
  }
  currentInfo = document.getElementById('docInfo' + id);
  currentInfo.style.display = '';
  currentInfo.style.visibility = 'visible';
}

//{{{ var cmsMenusUI - AT:New menu code for ondemand menus
var cmsMenusUI = {
  
  //{{{ build:function()
  build:function(){
    
    if(window.console)console.log('= = = = building menus = = = =');
    
    var allMenus = $$('.'+cmsMenusUI.utils.containerClass);
    
    /* Note on getElementsByClassName from prototype API:
       As of Prototype 1.6, document.getElementsByClassName has been deprecated since native implementations return a NodeList rather than an Array. Please use $$ or Element#select instead.
    */
    /* AT:20080703 - changed all instances of document.getElementsByClassName to $$  */
    
    $A(allMenus).each(function(menuObj){
      var menu = $(menuObj.id);
      
      menu.contentId = menu.id.substr(cmsMenusUI.utils.containerIdPfx.length);
      menu.over      = false;
      menu.callMenu  = false;
      menu.posMenu   = false; //check to see if the menun has been moved into the proper position
      menu.subItems  = {};
      menu.ondemand  = (CoreSiteVars.cmsMenuType == 'ondemand')?true:false;
      menu.highElem  = $('item_menu'+menu.contentId+'high'); //item_menuN20EAhigh
      menu.icon      = $('item_icon'+menu.contentId);
      menu.menuWidth = cmsMenusUI.utils.menuWidth;
      menu.offside   = false; // This becomes true if too close to the left edge of document
      
      cmsMenusUI.menuActions(menu);
      
    });
    allMenus = null;
  }, //}}}
  
  //{{{ menuActions:function(menu)
  menuActions:function(menu){
    Event.observe(menu, 'mouseover', function(e){
      //console.dir(menu);
      if(menu.over==false && !menu.stayFalse){
        menu.over = true;
        var icon = $(cmsMenusUI.utils.menuIdPfx+menu.contentId);
        if(menu.options){menu.options.mcmid = menu.contentId;}
        if(menu.posMenu == false) {
          menu.posMenu = true;
          cmsMenusUI.posMenu(icon,CoreSiteVars.cmsIconType,menu, e);
          cmsMenusUI.showMenu(menu,CoreSiteVars.cmsIconType,menu.contentId);
        }
        if(menu.callMenu == false && menu.ondemand == true) {
          menu.callMenu = true;
          cmsMenusUI.loadAsyncMenu(menu.options);
        }
      }
    });
    
    Event.observe(menu, 'mouseout', function(e){
      menu.over = false;
      setTimeout("cmsMenusUI.checkMenu('"+menu.contentId+"',CoreSiteVars.cmsIconType);",1000);
    });
    
    var subMenu = $(cmsMenusUI.utils.subMenuIdPfx+menu.contentId)
    Event.observe(subMenu, 'mouseover', function(e){
      menu.over = true;
    });
    Event.observe(subMenu, 'mouseout', function(e){
      menu.over = false;
    });
  }, //}}}
  
  //{{{ showMenu:function(elem, dpyMode,name)
  showMenu:function(elem, dpyMode,name){

    if (cmsMenusUI.utils.currentMenu != '') {
      //console.dir(cmsMenusUI.utils.currentMenu);
      cmsMenusUI.utils.currentContainer.over = false;
      Element.hide(cmsMenusUI.utils.currentMenu);
    }
    var menu = $('item_Submenu'+name);
    Element.show(menu);
    menu.style.width = elem.menuWidth + 'px';

    //highlight content item
    cmsMenusUI.utils.currentMenu = $('item_Submenu'+name);
    cmsMenusUI.utils.currentContainer = $('item_menu'+name);
    var highlighted = elem.id + 'high';
    if ($(highlighted)) {
      Element.addClassName(highlighted,'cmscontentitem-'+cmsMenuType+'-up');
    }
  }, //}}}
  
  //{{{ posMenu:function(btn, dpyMode, menu)
  posMenu:function(btn, dpyMode, menu, e){
    
    Element.makePositioned(menu);
    menu.menuPos = Position.positionedOffset(menu);
    
    var submenu  = $('item_Submenu'+menu.contentId);
    var mouseX = Event.pointerX(e);
    var mouseY = Event.pointerY(e);
    menu.xPos = menu.menuPos[0];
    menu.yPos = menu.menuPos[1];
    
    if(mouseX < menu.menuWidth+16){
      menu.offside = true;
    } 
    
    var submenu  = $('item_Submenu'+menu.contentId);
    Position.absolutize(submenu);
    
    if (dpyMode == 'icon') {
      if(menu.offside){
        submenu.style.top = menu.yPos + 'px';
        submenu.style.left = menu.xPos + 16 + 'px';
      }
      else {
        submenu.style.top = menu.yPos + 'px';
        submenu.style.left = menu.xPos - menu.menuWidth + 'px';
      }
      submenu.style.zIndex = '1000000';
    }

    Element.undoPositioned(menu);
    
  }, //}}}
  
  //{{{ showSubmenu:function(elem)
  showSubmenu:function(elem, mcmid){//alert('cmsShowSubmenu');
    var submenu =  $('flyout_'+elem.id);
    var menu = $('item_menu'+mcmid)
    
    if(submenu.style && elem.childNodes[0]) {
      
      Position.absolutize(submenu);

      if(menu.offside){
        submenu.style.top = elem.style.top;
        submenu.style.left = menu.menuWidth + 'px';
      }
      else {
        submenu.style.top = elem.style.top;
        submenu.style.left =- menu.menuWidth + 'px';
      }
      
      submenu.style.width = cmsMenusUI.utils.menuWidth + 'px';
      submenu.style.height = 'auto' //submenu.childNodes.length * 25 + 'px';
      Element.show(submenu);
      
    }

  }, //}}}
  
  //{{{ hideSubmenu:function(elem)
  hideSubmenu:function(elem){//alert('cmsHideSubmenu');
    var submenu = $('flyout_'+elem.id);
    //var submenu = elem.childNodes[0];
    if(submenu.style && elem.childNodes[0]) {
      Element.hide(submenu);
    }
  }, //}}}
  
  //{{{ checkMenu:function(name, dpyMode)
  checkMenu:function(name, dpyMode){
    var menu = $('item_menu'+name);
    if((menu) && (menu.over==false)){
      var child =  $('item_Submenu'+name);
      var button =  $('item_SubmenuContnr'+name);
      cmsMenusUI.hideMenu(menu, dpyMode, child);
      button.className='cmsmenubutton';
      menu.callMenu = false;
      menu.posMenu = false;
      if (cmsMenusUI.utils.currentMenu == name && !currentMenuActive) { //!currentMenuActive - do we still need this?
        //need to find this and bring it into either the cmsUI or cmsMenusUI object
        cmsHideContextMenu(); 
      }
      
    }
  }, //}}}
  
  //{{{ hideMenu:function(elem, dpyMode, child)
  hideMenu:function(elem, dpyMode, child){
    var menu = $('item_Submenu'+elem);
    Element.hide(child);
    var highlighted = elem.id + 'high';
    if (document.getElementById(highlighted)) {
      //document.getElementById(highlighted).className='cmscontentitem-'+cmsMenuType;
      Element.removeClassName(highlighted,'cmscontentitem-'+cmsMenuType+'-up');
      //console.log('no class for you!');
    }
  }, //}}}
  
  //{{{ hideAll:function()
  hideAll:function(){
    for(itm in this){
      if(itm.indexOf('item_menu')!=-1){
        var currentItem = $(itm);
        try {
          currentItem.over = false;
          cmsMenusUI.checkMenu(currentItem.contentId,CoreSiteVars.cmsIconType);
        }
        catch(e){
          //console.log(e);
        }
      }
    }
  }, //}}}
  
  //{{{ destroyMenu:function(id)
  destroyMenu:function(id){
    var menuParent = $('item_menu'+id);
    var menu = $('item_Submenu'+id);
    
    Element.hide(menu);
    menuParent.over = false;
    cmsMenusUI.checkMenu(id, 'icon');

    var highlighted = id + 'high';
    if ($(highlighted)) {
      Element.removeClassName(highlighted,'cmscontentitem-'+cmsMenuType+'-up');
    }

    menu.innerHTML = '<div style="padding:.4em;"> loading...</div>';
  }, //}}}
  
  removeItem:function(mcmid){
    //console.dir(this);
    for(itm in this){
      if(itm.indexOf('item_menu')!=-1){
        if(itm.indexOf(mcmid)!=-1){

          delete this[itm];

        }
      }
    }
    
    /* if(typeof(control_obj)!='undefined'){
      rebuildSet = control_obj.register();
      rebuildSet = null;
    } */
    
  },
  
  //{{{ iconUpdate:function(id,filename) 
  iconUpdate:function(id,filename) {

    var imagePath = '/system_images/'+filename+'.gif';
    var menuIconParent = $('item_SubmenuContnr'+id);
    var icon = $(menuIconParent).firstDescendant();
    Element.remove(icon);
    var newMenuIcon = '<img src="'+imagePath+'" align="absmiddle" width="16" height="16" border="0" alt="" />';
    new Insertion.Bottom(menuIconParent,newMenuIcon);
  }, //}}}
  
  //{{{ folderActions:functions(options)
  folderActions:function(options){
    //var params   = options.params + '&path=' + collElem.options.path;
    if(options.confirmmsg){
      if (confirm(options.confirmmsg)){
         runAction(options);
      }
    }
    else{
      runAction(options);
    }
    
    function runAction(options){
      var collElem      = $('item_menu'+options.collId);
      var collParent    = $('item_menu'+options.collId+'high');
      var activateIcons = (options.activateIcons)? options.activateIcons : false;
      cmsUI.showAlert(options.statusmsg);
      cmsUI.sendAsync({
        params:options.params,
        onLoad:function(){
          
        },
        onSuccess:function(){
          cmsUI.hideAlert();
          if(activateIcons==true){
            var childMenus = Element.select(collParent,'.'+cmsMenusUI.utils.containerClass);
            $A(childMenus).each(function(childmenuObj){
              var childmenu = $(childmenuObj.id);
              //console.dir(childmenu)
              if(childmenu.parentId == collElem.contentId && childmenu.contentId != collElem.contentId && childmenu.options.action == 'document' ){
                childmenu.icon.src = CoreSiteVars.path_to_top+'/system_images/cms.gif'
              }
            });
          }
        }
      });
    }
  }, //}}}
  
  //{{{ loadAsyncMenu:function(options)
  loadAsyncMenu:function(options){
    var action      = options.action;
    var mcmid       = options.mcmid;
    var path        = options.path;    
    var adminUrl    = (options.url)? options.url : '/admin';
    var parameters  = (options.parameters)? options.parameters : '';
    var params      = 'action=' +action+ '&path=' +path+ '&mcmid=' +mcmid + parameters;
    
    cmsUI.sendAsync({
      updateElem:'item_Submenu'+mcmid,
      url:adminUrl,
      params:params,
      evalScripts:true,
      sendMethod:'post',
      onLoad:function(){
           
      },
      onSuccess:function(){
        //if(window.console){console.log('check for login here and other exceptions here');}
        //cmsMenusUI.menuSubItems(mcmid);
      }
    });
  }, //}}}
  
  //{{{ menuSubItems:function(mcmid)
  menuSubItems:function(mcmid){
  }, //}}}
  
  //{{{ menuItemActions:function(options)
  menuItemActions:function(options){
 
    var adminUrl   = (options.url)? options.url : '/admin';
    var confirmmsg = (options.confirmmsg) ? options.confirmmsg : null ;
    var statusmsg  = (options.statusmsg) ? options.statusmsg : null ;
    var params     = (options.params) ? options.params : null ;
    var evScripts  = (options.evScripts==false) ? false : true; 
      
    if(confirmmsg){
      new Lightbox.base('cmsContextMenuDiv', {
        createDraggable:true,
        type:'form',
        content:{
          heading:'<h1>Are you Sure?</h1>',
          msg:confirmmsg
        },
        action:{
          url:adminUrl+ '?' + params,
          msg:statusmsg,
          onLoad:options.onLoad,
          onSuccess:options.onSuccess
        }
      });
    }
    else{
      //Update!!!
      cmsUI.sendAsync({
        url:adminUrl,
        params:options.params,
        evalScripts:evScripts,
        onLoad:options.onLoad,
        onSuccess:options.onSuccess
      });
    }
  }, //}}}
  
  
  
  //{{{ utils
  utils:{
    menuClass:'cmsmenubutton',
    menuIdPfx:'item_SubmenuContnr',
    containerClass:'cmsmenutypeicon',
    containerIdPfx:'item_menu',
    subMenuIdPfx:'item_Submenu',
    currentMenu:'',
    currentContainer:'',
    menuWidth:130,
    subItemClass:'subitem',
    flyoutClass:'flyout'
  } //}}}

}
//cmsMenusUI.buildMenus();
if(typeof(Prototype)!='undefined'){
  Event.observe(window,'load',function(){cmsMenusUI.build()});
}
//}}}

/* PW 10312007: new menu function */
//{{{ new ondemand functions for menu actions


  /* used by ondemand menus */
  function cmsOndemandLock(jsDocPath,mcmid) {

    //cmsShowContextMessage('Locking document, please wait ...', true);
    cmsUI.showAlert('Locking document, please wait ...');
    
    var myAjax = new Ajax.Request(
      CoreSiteVars.adminTool,
      {
        parameters:'action=lock&path='+jsDocPath,
        onFailure:  function(req) {},
        onComplete: function(req) {
          //cmsHideContextMessage();
          cmsUI.hideAlert();
          cmsMenusUI.destroyMenu(mcmid);
        }
      }

    );

  }

  /* used by ondemand menus */
  function cmsOndemandUnlock(jsDocPath,mcmid) {

    //cmsShowContextMessage('Unlocking document, please wait ...', true);
    cmsUI.showAlert('Unlocking document, please wait ...');

    var myAjax = new Ajax.Request(
      CoreSiteVars.adminTool,
      {
        parameters:'action=unlock&path='+jsDocPath,
        onFailure:  function(req) {},
        onComplete: function(req) {
          //cmsHideContextMessage();
          cmsUI.hideAlert();
          cmsMenusUI.destroyMenu(mcmid);
        }
      }

    );

  }

  /* used by ondemand menus */
  function cmsOndemandPublish(editPath,mcmid) {

    //cmsShowContextMessage('Publishing document, please wait ...', true);
    cmsUI.showAlert('Publishing document, please wait ...');
    
    var myAjax = new Ajax.Request(
      CoreSiteVars.adminTool,
      {
        parameters:'action=publish&path='+editPath,
        onFailure:  function(req) {},
        onLoading: function(){
          showingMessage = false;
        }, //Update!!!
        onComplete: function(req) {
          cmsMenusUI.destroyMenu(mcmid);
          //cmsHideContextMessage();
          cmsUI.hideAlert();
        }
      }

    );

  }

  /* used by ondemand menus */
  function cmsOndemandUnpublish(editPath,mcmid) {

    //cmsShowContextMessage('Unpublishing document, please wait ...', true);
    cmsUI.showAlert('Unpublishing document, please wait ...');

    var myAjax = new Ajax.Request(
      CoreSiteVars.adminTool,
      {
        parameters:'action=unpublish&path='+editPath,
        onFailure:  function(req) {},
        onComplete: function(req) {
          //cmsHideContextMessage();
          cmsUI.hideAlert();
          cmsMenusUI.destroyMenu(mcmid);
        }
      }

    );

  }



  /* used by ondemand menus */
  function cmsOndemandCheckout(editPath,mcmid) {

    //cmsShowContextMessage('Checking out document, please wait ...', true);
    cmsUI.showAlert('Checking out document, please wait ...');

    var myAjax = new Ajax.Request(
      CoreSiteVars.adminTool,
      {
        parameters:'action=activate&path='+editPath,
        onFailure:  function(req) {},
        onComplete: function(req) {
          //cmsHideContextMessage();
          cmsUI.hideAlert();
          cmsMenusUI.destroyMenu(mcmid);
          cmsMenusUI.iconUpdate(mcmid,'cms');
        }
      }

    );

  }

  /* used by ondemand menus */
  function cmsOndemandRevert(editPath,mcmid) {

    //cmsShowContextMessage('Reverting document, please wait ...', true);
    cmsUI.showAlert('Reverting document, please wait ...');

    var myAjax = new Ajax.Request(
      CoreSiteVars.adminTool,
      {
        parameters:'action=revert-to-trunk&path='+editPath,
        onFailure:  function(req) {},
        onComplete: function(req) {
          //cmsHideContextMessage();
          cmsUI.hideAlert();
          cmsMenusUI.destroyMenu(mcmid);
          cmsMenusUI.iconUpdate(mcmid,'cms_inactive');
        }
      }

    );

  }
//}}}

//{{{ ############### MENUS (more..) ###################



// PW: causing error in Mozilla so commenting out, anything break?
// var oPopup = window.createPopup();
var currentMenu = '';
var currentMenuActive = false;
var showingMessage = false;

/* show/hide menus */ /* used for: right click content item menus. (cmsMenuType=context) */
function cmsShowContextMenu(menuId)
{ //alert('cmsShowContextMenu');



  if (!showingMessage && !xMoz) /* NOT Moz compliant right now (for right click menus) */
  {
    cmsHideContextMenu();
    var menuDiv = document.getElementById('cmsContextMenuDiv');
    var menuContent = document.getElementById('item_menu' + menuId);
    // var menuContentDiv = menuContent.childNodes[1];
    var menuContentDiv = $('item_Submenu'+menuId);
    //  alert(menuContentDiv.id);
    menuDiv.innerHTML = '<div class="cmsmenu"><div class="cmsmenutext" style="width:120px;">' +menuContentDiv.innerHTML+'</div></div>';
    //if (document.body.clientWidth < 120 + event.clientX) {
    if (document.body.clientWidth < 120 + xPageX(this)) {
      menuDiv.style.left = document.body.clientWidth - 120;
    } else if (event.clientX < 120) {
      menuDiv.style.left=120;
    } else {
      menuDiv.style.left = event.clientX + document.body.scrollLeft - 5;
    }

    menuDiv.style.top = event.clientY + document.body.scrollTop - 5;
    menuDiv.style.display='block';
    menuDiv.style.visibility = 'visible';
    highlightCI(menuId);
    currentMenu = menuId;
    currentMenuActive = true;
    event.cancelBubble = true;
    return false;
  }
}



/* show/hide menus */ /* used for: right click content item menus. (cmsMenuType=context) */
function cmsShowContextMenuWORKINGORIG(menuId)
{ //alert('cmsShowContextMenu');


  if (!showingMessage && !xMoz) /* NOT Moz compliant right now (for right click menus) */
  {
    cmsHideContextMenu();
    var menuDiv = document.getElementById('cmsContextMenuDiv');
    var menuContent = document.getElementById('item_menu' + menuId);
    // var menuContentDiv = menuContent.childNodes[1];
    var menuContentDiv = $('item_Submenu'+menuId);
    //  alert(menuContentDiv.id);
    menuDiv.innerHTML = '<div class="cmsmenutext" style="width:120px;">' +menuContentDiv.innerHTML+'</div>';
    //if (document.body.clientWidth < 120 + event.clientX) {
    if (document.body.clientWidth < 120 + xPageX(this)) {
      menuDiv.style.left = document.body.clientWidth - 120;
    } else if (event.clientX < 120) {
      menuDiv.style.left=120;
    } else {
      menuDiv.style.left = event.clientX + document.body.scrollLeft - 5;
    }

    menuDiv.style.top = event.clientY + document.body.scrollTop - 5;
    menuDiv.style.display='block';
    menuDiv.style.visibility = 'visible';
    highlightCI(menuId);
    currentMenu = menuId;
    currentMenuActive = true;
    event.cancelBubble = true;
  }
}

function cmsHideContextMenu()
{
  if(!($('cmsContextMenuDiv'))) return null;
  if(typeof(Lightbox)!='undefined'){Lightbox.hideAll()}//console.dir(Lightbox) }
  if (!showingMessage) {
    var menuDiv = document.getElementById('cmsContextMenuDiv');
    menuDiv.style.display='none';
    //menuDiv.style.visibility = 'hidden';
    menuDiv.innerHTML = '';
   /*
     PW: removed 12.05.2005 to fix flicker, seems to work!
     if (currentMenu != '') {
      unhighlightCI(currentMenu);
    }

    */
    currentMenu = '';
    currentMenuActive = false;
    currentContentItem = new Array();
    //window.status='cmsHideContextMenu()';
  }
}


/* show/hide messages */
function cmsShowContextMessage(html,centre)
{
  //cmsShowCustomContextMenu('<div class="cmsDropShadow"><div class="cmsContextMessage">' + html + '</div></div>',true);
  //cmsShowCustomContextMenu('<div class="cmsDropShadow"><div class="cmsContextMessage"><img src="system_images/cms50_ani.gif" align="absmiddle" style="margin-right:4px;" />' + html + '</div></div>',true);
  //showingMessage = true;
  cmsUI.showAlert(html);
}

function cmsHideContextMessage() {
  //showingMessage = false;
  //cmsHideContextMenu();
  cmsUI.hideAlert();
}


//function cmsShowCustomContextMenu(html,centre,triggerId) removed trigger
function cmsShowCustomContextMenu(html,centre)
{
  var menuDiv = document.getElementById('cmsContextMenuDiv');
  if (!(menuDiv=$(menuDiv))) return null;

  if (Prototype.Browser.IE)
  {
    // do original code
    cmsHideContextMenu();
    menuDiv.innerHTML = html;
    if (centre) {
      menuDiv.style.left = (document.body.clientWidth - 100) / 2 + document.body.scrollLeft;
      menuDiv.style.top = (document.body.clientHeight - 50) / 2 + document.body.scrollTop;
    }
    else {
      if (document.body.clientWidth < 120 + event.clientX) {
        menuDiv.style.left = document.body.clientWidth - 120;
      } else if (event.clientX < 120) {
        menuDiv.style.left=120;
      } else {
        menuDiv.style.left = event.clientX + document.body.scrollLeft - 5;
      }
    }
    menuDiv.style.top = event.clientY + document.body.scrollTop - 5;
    menuDiv.style.display='block';
    menuDiv.style.visibility = 'visible';
    event.cancelBubble = true;
    //window.status='cmsShowCustomContextMenu()';
  }
    else {
      var offsetx = -100;
      var offsety =  50;
      cmsHideContextMenu();
      menuDiv.innerHTML = html;
      centerx = document.body.clientWidth / 2;
      centery = document.body.clientHeight / 2;

      menuDiv.style.left = (centerx+offsetx + xScrollLeft()) + 'px';
      menuDiv.style.top = (centery+offsety + xScrollTop()) + 'px';

      menuDiv.style.display='block';
      menuDiv.style.visibility = 'visible';
      //event.cancelBubble = true;
    }
}





function cmsAbsPosMenu(menu)/* This is not tested yet because I don't know where it's being used. */
{
  //menu.style.top = event.y + document.body.scrollTop;
  //menu.style.left = event.x + document.body.scrollLeft;

  x = xPageX(this) + document.body.scrollLeft;
  y = xPageY(this) + document.body.scrollTop;
  xMoveTo(menu, x, y);
  //window.status='cmsAbsPosMenu()';

}


/* ??? */
var currentContentItem = new Array();

/* IE only? */
function cmsContentItemEnter(elem) {
  if (!currentMenuActive && cmsMenuType == 'context') {
    if (currentContentItem.length > 0) {
      myparent = currentContentItem[currentContentItem.length - 1];
      //myparent.className='cmscontentitem-'+cmsMenuType ;
      Element.removeClassName(myparent,'cmscontentitem-'+cmsMenuType+'-over');
    }
    //elem.className='cmscontentitem-'+cmsMenuType + '-over';
    Element.addClassName(elem,'cmscontentitem-'+cmsMenuType+'-over');
    currentContentItem.push(elem);
  }
}
/* IE only? */
function cmsContentItemLeave(elem) {
  if (!currentMenuActive && cmsMenuType == 'context') {
    //elem.className='cmscontentitem-'+cmsMenuType ;
    Element.removeClassName(elem,'cmscontentitem-'+cmsMenuType+'-over');
    currentContentItem.pop();
    if (currentContentItem.length > 0) {
      current = currentContentItem[currentContentItem.length - 1];
      //current.className='cmscontentitem-'+cmsMenuType + '-over';
      Element.addClassName(current,'cmscontentitem-'+cmsMenuType+'-over');
    }
  }
}





/* ------------- class swap with fix for menu lameness ------------- */

var mnuDivs;

function cmsSwapClass(e,newClass,rClass) {

  // clear mnus Fix for Mozilla.
  if(rClass && Prototype.Browser.Gecko) {

    // cache all menu divs (menu divs are divs with 'efly' in their id)
    if (!mnuDivs) {
      var mnuDivsDOM = document.getElementsByTagName("div");
      mnuDivs = [];
      for (var y = mnuDivsDOM.length - 1; y >= 0; y--)
      {
        if (mnuDivsDOM[y].id.indexOf('efly') > -1)
        {
          mnuDivs.push(mnuDivsDOM[y]);
        }
      }
    }

    // apply rClass classname to all menu divs except the current one
  /* PW jun 2008: screw this stuff man
    for (var y = mnuDivs.length - 1; y >= 0; y--)
    {
      if (mnuDivs[y].id != e.id)
      {
        mnuDivs[y].className=rClass;
      }
    } */

    //e.className=newClass;
  }

  //if (!xGetElementById) return '';
  if(!(e=$(e))) return '';
  if(e.className) {
    if(newClass) {
      e.className=newClass;
    }
  }

}



var jsfilenameList = new Array();
function addToFilenameList(name)
{
  jsfilenameList[name] = 'y';
}
function filenameAvailable(name)
{
  return (jsfilenameList[name] == null || jsfilenameList[name] == '');
}
function showElement(elmnt)
{
  document.getElementById(elmnt).style.visibility="visible";
  document.getElementById(elmnt).style.display="";
}
function hideElement(elmnt)
{
  document.getElementById(elmnt).style.visibility="hidden";
  document.getElementById(elmnt).style.display="none";
}


// Doc Listing

var draggedDocumentPath = '';
var draggedDocumentName = '';
var draggedDocumentType = '';

function docListingDumpOrder(nla)
{
  var result = "";
  for (i=1; i<nla.length; i++) {
    result += i + ":" + nla[i] + "|";
  }
  return result;
} 
//}}}

//{{{ moved from listing.xsl
function createTemplate(form)
{
  if (form.template_name.selectedIndex == 0) {
    alert("Please choose a template.");
    return;
  }
  xShowDialog('/admin?action=popup&popupType=selectFile&popupTitle=Enter new filename',
  	new Array(handleCreateTemplate),
  	'status:no;dialogWidth:400px;dialogHeight:125px;help:no;scrollbar:no;center:yes;resizable:yes;');
}

var handleCreateTemplate = function(filename) {
  var form = $('cmsChooseTemplateSelectorForm');
  if (!filename) {
    form.template_name.value='*';
    return;
  }
  
  if (filename.indexOf(".") != -1) {
    form.filename.value = filename;
  }
  else {
    form.filename.value = filename + ".xml";
  }
  
  if (!validFilename(form.filename.value)) {
    form.template_name.value='*';
    return;
  }
  if (!filenameAvailable(form.filename.value)) {
    if (!confirm('Content item already exists named "' + form.filename.value + '", overwrite?')) {
      form.template_name.value='*';
      return;
    }
  }
  form.submit();
}

//used for inline file renaming (IE only)
function moveDoc(thespan, name, src, dst)
{
  if (name != dst ) {
    if (validFilename(dst) && confirm('Move ' + name + ' to ' + dst + '?')) {
      document.location='/admin?action=rename&src=' + src + '&dst=' + dst;
    }
    else {
      thespan.innerHTML = name;
    }
  }
}

function trapRET(thespan, name, src, dst){
  if (event.keyCode == 13) {
    event.returnValue=false;
    //moveDoc(thespan, name, src, dst);
  }
}


function tableruler()
  {
   if (document.getElementById && document.createTextNode)
    {
     var tables=document.getElementsByTagName('table');
     for (var i=0;i<tables.length;i++)
     {
      if(tables[i].className=='ruler')
      {
       var trs=tables[i].getElementsByTagName('tr');
       for(var j=0;j<trs.length;j++)
       {
        if(trs[j].parentNode.nodeName=='TBODY' && trs[j].parentNode.nodeName!='TFOOT' && trs[j].parentNode.parentNode.className=='ruler')
         {
         trs[j].onmouseover=function(){this.className='ruled';return false}
         trs[j].onmouseout=function(){this.className='';return false}
       }
      }
     }
    }
   }
  }
//}}}


 function makeXMLFilename(filename)
 {
    if (filename == null || filename == "") {
      filename = "untitled.xml";
    }
    else if (filename.indexOf(".xml") == -1 && filename.indexOf(".xsl") == -1) {
      filename += '.xml';
    }
    return filename;
  }




 //{{{ Branch Review Page


lastHighlighted = null;
/* ??? still used? - yes on review mode page */
function highlightCI(menuId)
{//alert('highlightCI');
  var highlighted = 'item_menu' + menuId + 'high';
   if (document.getElementById(highlighted)) {
    //Element.addClassName(highlighted, 'cmscontentitem-'+cmsMenuType+'-up')
    document.getElementById(highlighted).className='cmscontentitem-'+cmsMenuType+'-up';
    if (lastHighlighted != null) {
      unhighlightCI(lastHighlighted);
    }
    lastHighlighted = menuId;
  }

}


/* ??? still used? - yes on review mode page  */
function unhighlightCI(menuId)
{//alert('unhighlightCI');
  lastHighlighted = null;
  var highlighted = 'item_menu' + menuId + 'high';
  if (document.getElementById(highlighted)) {
    //Element.removeClassName(highlighted, 'cmscontentitem-'+cmsMenuType+'-up');
    document.getElementById(highlighted).className='cmscontentitem-'+cmsMenuType;
    //new Effect.Highlight(highlighted,{duration:1.5,startcolor: '#b3dcea'}); return false;
  }
}


/* ??? still used? - yes on review mode page*/
function highlightMultiCI(menuId)
{//alert('highlightMultiCI');
  var highlighted = 'item_menu' + menuId + 'high';
  if (document.getElementById(highlighted)) {
    document.getElementById(highlighted).className='cmscontentitem-'+cmsMenuType+'-up';
  }
}


/* ??? still used? - yes on review mode page*/
function unhighlightMultiCI(menuId)
{//alert('unhighlightMultiCI');
  var highlighted = 'item_menu' + menuId + 'high';
  if (document.getElementById(highlighted)) {
    document.getElementById(highlighted).className='cmscontentitem-'+cmsMenuType;
  }
}






/* ??? still used? - dont know */
/* temp script to be replaced by nice version */
function highlightCI2(menuId)
{//alert('highlightCI2');
  var highlighted = 'item_menu' + menuId + 'high';
  if (document.getElementById(highlighted)) {
    document.getElementById(highlighted).className='cmscontentitem-'+cmsMenuType+'-up';
    if (lastHighlighted != null && lastHighlighted != menuId) {
      unhighlightCI(lastHighlighted);
    }
    lastHighlighted = menuId;
  }
}


//}}}








/* XP Style Menu Box */
/* PW: 09112007: dont think this is used anymore, commenting out. */
/* function toggleMenuBox(elem) {
  var chevron = elem.parentNode.childNodes[0].childNodes[2];
  var content = elem.parentNode.childNodes[1];
  if (chevron.className == 'menuBoxRight') {
    chevron.className='menuBoxRightHidden';
    content.style.display='none';
    content.style.visibility='hidden';
  }
  else {
    chevron.className='menuBoxRight';
    content.style.display='';
    content.style.visibility='visible';
  }
}
 */

function cmsPerformAction(msg, loc) {
  /* cmsShowContextMessage(msg, true); */
  cmsUI.showAlert(msg);
  window.location = loc;
}


function toggleDisplay(elem, class1, class2) {
  if (elem.className == class1) {
    elem.className=class2;
  }
  else {
    elem.className=class1;
  }
}






/*

  Notes:

    1. edge & help attributes do not work.
    2. "height" & "width" must be entered before "center"
    3. if you should choose to set "center=yes" do not put in "left" and "top"
    4. Minimize button not hidden, but when clicked the window will not disappear
    5. Aside from the aforementioned, all features should react the same *fingers crossed*
    6. Still in the works, so don't expect miracles. Any problems/queries/complaints please don't hesitate.
  Email:

    [email]x_goose_x@hotmail.com[/email]

*/

dFeatures = 'dialogHeight: 450px; dialogWidth: 1049px; dialogTop: 646px; dialogLeft: 4px; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: Yes;';//default features

modalWin = "";
function xShowDialog( sURL, vArguments, sFeatures, wName)
    {
    if (wName==null)
    {
        var wName = 'defaultwin';
    }
    if (sURL==null||sURL=='')
    {
        alert ("Invalid URL input.");
        return false;
    }
    if (vArguments==null||vArguments=='')
    {
        vArguments='';
    }
    if (sFeatures==null||sFeatures=='')
    {
        sFeatures=dFeatures;
    }
//    if (window.navigator.appVersion.indexOf("MSIE")!=-1)
//    {
//        window.showModalDialog ( sURL, vArguments, sFeatures );
//        return false;
//    }

    sFeatures = sFeatures.replace(/ /gi,'');
    aFeatures = sFeatures.split(";");
    sWinFeat = "directories=0,menubar=0,titlebar=0,toolbar=0,";

    for (var x = 0; x < aFeatures.length; x++)
    {
        aTmp = aFeatures[x].split(":");
        sKey = aTmp[0].toLowerCase();
        sVal = aTmp[1];
        switch (sKey)
        {
            case "dialogheight":
                sWinFeat += "height="+sVal+",";
                pHeight = sVal;
                break;
            case "dialogwidth":
                sWinFeat += "width="+sVal+",";
                pWidth = sVal;
                break;
            case "dialogtop":
                sWinFeat += "screenY="+sVal+",";
                break;
            case "dialogleft":
                sWinFeat += "screenX="+sVal+",";
                break;
            case "resizable":
                sWinFeat += "resizable="+sVal+",";
                break;
            case "status":
                sWinFeat += "status="+sVal+",";
                break;
            case "scrollbar":
                sWinFeat += "scrollbars="+sVal+",";
                break;
            case "center":
                if ( sVal.toLowerCase() == "yes" )
                {
                    sWinFeat += "screenY="+((screen.availHeight-pHeight)/2)+",";
                    sWinFeat += "screenX="+((screen.availWidth-pWidth)/2)+",";
                }
                break;
        }
    }
    if (window.navigator.appVersion.indexOf("MSIE")!=-1) {
      sURL+='&http.referer='+escape(window.location);
    }
    modalWin=window.open(sURL,wName,sWinFeat);
    if (vArguments!=null&&vArguments!='')
    {
      modalWin.dialogArguments = vArguments;
    }
    modalWin.focus();
}

function checkFocus()
    {
    if (window.navigator.appVersion.indexOf("MSIE")==-1)
        {
        if (modalWin!=null && !modalWin.closed)
        {
            self.blur();
            modalWin.focus();
        }
    }
}







function updateIFrame(id,href) {
  o = document.getElementById(id);
  if (o.src) {
    o.src = href;
  }
  else
    o.location = href;
}





/* ------------- single level menus (top bar dropdowns use this) ------------- */

/* xMenu1A Object Prototype

  Parameters:
    triggerId   - id string of trigger element.
    menuId      - id string of menu.
    mouseMargin - integer margin around menu;
                  when mouse is outside this margin the menu is hid.
    slideTime   - integer time for menu slide (in milliseconds).
    openEvent   - string name of event on which to open menu ('click', 'mouseover', etc).
*/


/* PW: This is a copy of function in x_menus.js
(might not need copy if other version made core,
 but also might want to customize this one for tool) */
function cmsxMenu1A(triggerId, menuId, mouseMargin, slideTime, openEvent) {

  var isOpen = false;
  var trg = xGetElementById(triggerId);
  var mnu = xGetElementById(menuId);
  if (trg && mnu) {
    xHide(mnu);
    xAddEventListener(trg, openEvent, onOpen, false);
  }
  function onOpen()
  {
    if (!isOpen) {
      xMoveTo(mnu, xPageX(trg), xPageY(trg));
      xShow(mnu);
      xSlideTo(mnu, xPageX(trg), xPageY(trg) + xHeight(trg), slideTime);
      xAddEventListener(document, 'mousemove', onMousemove, false);
      isOpen = true;
    }
  }
  function onMousemove(ev)
  {
    var e = new xEvent(ev);
    if (!xHasPoint(mnu, e.pageX, e.pageY, -mouseMargin) &&
        !xHasPoint(trg, e.pageX, e.pageY, -mouseMargin))
    {
      xRemoveEventListener(document, 'mousemove', onMousemove, false);
      xSlideTo(mnu, xPageX(trg), xPageY(trg), slideTime);
      setTimeout("xHide('" + menuId + "')", slideTime);
      isOpen = false;
    }
  }
} // end xMenu1A






/* ------------- Locale Manager Scripts ------------- */

  var green1 = '#2eab2e';
  var blue1 = '#5882d5';

  function hlC(t)
  {
    var c = document.getElementsByTagName("a");
    for (var i = 0; i < c.length; i++)
    {
      if (c[i].id.indexOf('aCb') != -1)
      {
        c[i].style.background = '';
        c[i].style.color = blue1;
      }
    }
    //clear P's
    var p = document.getElementsByTagName("a");
    for (var i = 0; i < p.length; i++)
    {
      if (p[i].id.indexOf('aPb') != -1)
      {
        p[i].style.background = '';
        p[i].style.color = '#000000';
      }
    }
    t.style.background = blue1;
    t.style.color = '#FFFFFF';
  }

  function hlV(t)
  {
    var v = document.getElementsByTagName("a");
    for (var i = 0; i < v.length; i++)
    {
      if (v[i].id.indexOf('aVb') != -1)
      {
        v[i].style.background = '';
        v[i].style.color = green1;
      }
    }
    
    //clear C's
    var c = document.getElementsByTagName("a");
    for (var i = 0; i < c.length; i++)
    {
      if (c[i].id.indexOf('aCb') != -1)
      {
        c[i].style.background = '';
        c[i].style.color = blue1;
      }
    }
    
    //clear P's
    var p = document.getElementsByTagName("a");
    for (var i = 0; i < p.length; i++)
    {
      if (p[i].id.indexOf('aPb') != -1)
      {
        p[i].style.background = '';
        p[i].style.color = '#000000';
      }
    }
    t.style.background = green1;
    t.style.color = '#FFFFFF';
  }
   function hlP(t)
  {

    //clear C's
    var c = document.getElementsByTagName("a");
    for (var i = 0; i < c.length; i++)
    {
      if (c[i].id.indexOf('aCb') != -1)
      {
        c[i].style.background = '';
        c[i].style.color = blue1;
      }
    }

    //clear V's
    var v = document.getElementsByTagName("a");
    for (var i = 0; i < v.length; i++)
    {
      if (v[i].id.indexOf('aVb') != -1)
      {
        v[i].style.background = '';
        v[i].style.color = green1;
      }
    }
    //clear P's
    var p = document.getElementsByTagName("a");
    for (var i = 0; i < p.length; i++)
    {
      if (p[i].id.indexOf('aPb') != -1)
      {
        p[i].style.background = '';
        p[i].style.color = '#000000';
      }
    }
    //set current P
    t.style.background = '#000000';
    t.style.color = '#FFFFFF';
  }

  function hlA(t)
  {
    
  }


/* ------------- Locale Selector Scripts ------------- */


// show/hide translations and implications from custom page
function toogle(fieldName)
{
  var trans = document.getElementById("fTree").getElementsByTagName("div");
  for (i = 0; i < trans.length; i++)
  {
    if (trans[i].getAttribute('name') == fieldName)
    {
      if (document.getElementById('ShowTranslations').checked) // TODO: unhardcode this
      {
        trans[i].style.visibility="visible";
        trans[i].style.display="block";
      }
      else
      {
        trans[i].style.visibility="hidden";
        trans[i].style.display="none";
      }
    }
  }
}

/**
 * 2006/04/26 - new prototype for localization checkbox toggling - SK
 * param: state
 * param: l
 * returns: none
 */
function cbUpdtr(state,l) {
	var cbxs = document.getElementsByTagName("input");
	var locals = l.split(",");

  //console.log(state);
  //console.log(l);
  //console.log(cbxs);
  //console.log(locals);
  
	var a = 0;
	var s = locals.length;

	for (a = 0; a < s; a++) {
		var i = 0;
		for (i = 0; i < cbxs.length; i++) {
			if (cbxs[i].getAttribute('locale') == locals[a]) {
				if (!cbxs[i].disabled) {cbxs[i].checked = state;}
			}
		}
	}
	cbSetParents();
}



/**
 * 2006/04/26 - Depricated - SK
 */
function __cbUpdtr(state,l)
{
  var cbxs = document.getElementsByTagName("input");
  //alert("cbxs length = "+cbxs.length+" and state:"+state);

  //checks all arguments passed in
  for (var a = 1; a < arguments.length; a++)
  {
    for (var i = 0; i < cbxs.length; i++)
    {
      if (cbxs[i].getAttribute('locale') == arguments[a])
      {
        //alert("found another:"+cbxs[i].getAttribute('locale'));
        //cbxs[i].checked = state;
        //
        if (!cbxs[i].disabled) {cbxs[i].checked = state;}
      }
    }
  }
  // go and update parents now
  cbSetParents();
}


function cbSetParents()
{
  var groupImgs = document.getElementsByTagName("img");

  for (var x = 0; x < groupImgs.length; x++)
  {
    if (groupImgs[x].getAttribute('gId'))
    {
      var allSelected = 0;
      var atLeastOneSelected = 0;
      var childs = groupImgs[x].getAttribute('gId') + 'Children';
      var cbxs = document.getElementById(childs).getElementsByTagName("input");
      for (var y = 0; y < cbxs.length; y++)
      {
        if (cbxs[y].checked){atLeastOneSelected++;}
        if (cbxs[y].checked){allSelected++;}
      }
      //alert(childs+"atLeastOneSelected:"+atLeastOneSelected+" and allSelected:"+allSelected);

      // set the image
      if (allSelected == cbxs.length)
      {
        groupImgs[x].src =  'system_images/cb1.gif';
      } else
        {
          if (atLeastOneSelected >= 1)
          {
            groupImgs[x].src =  'system_images/cbp.gif';
          } else
            {
              groupImgs[x].src =  'system_images/cb0.gif';
            }
        }

    }
  }

}


// toggles group img
function cbToogler(img,showWaiting)
{

if (showWaiting)
  {
    //cmsShowContextMessage('please wait...', true);
    cmsUI.showAlert('please wait...');
  }

  if (img.src.indexOf('cb0.gif') != -1)
  {
    img.src =  'system_images/cb1.gif';
  }
  else if (img.src.indexOf('cbp.gif') != -1)
    {
      img.src =  'system_images/cb1.gif';
    }
    else if (img.src.indexOf('cb1.gif') != -1)
      {
        img.src =  'system_images/cb0.gif';
      }


}

function cbSetChildren(group,img)
{
  var selected = img.src.indexOf('cb1.gif') != -1;

  var cbxs = document.getElementById(group).getElementsByTagName("input");
  for (var i = 0; i < cbxs.length; i++)
  {
    //if (!cbxs[i].disabled) {cbxs[i].checked = selected;}
    cbxs[i].checked = selected;
  }
}


var cbxDefaults = new Array();
var cbxDefaultValues = new Array();

function cbSaveDefaults()
{
  cbxDefaults = document.getElementById("allLocalesDiv").getElementsByTagName("input");
  for (var i = 0; i < cbxDefaults.length; i++)
  {
     cbxDefaultValues[i] = cbxDefaults[i].checked;
     //alert("set item "+i+" checked = "+cbxDefaults[i].value+" to "+cbxDefaultValues[i]);
  }
}

function cbRestoreDefaults()
{
  cbClearAll();
  var setCbxs = document.getElementsByTagName("input");

  for (var d = 0; d < cbxDefaults.length; d++)
  {
    //alert("setting:"+cbxDefaults[d].getAttribute('locale'));
    cbUpdtr(cbxDefaultValues[d],cbxDefaults[d].getAttribute('locale'));
  }
  cbSetParents();
}


function cbClearAll()
{
  var cbxs = document.getElementsByTagName("input");

  for (var i = 0; i < cbxs.length; i++)
  {
    /* if(window.console){console.log(cbxs[i].id);} */
    if (cbxs[i].id!='ShowTranslations' && cbxs[i].id!='ShowImplications' && cbxs[i].id!='F12n' && cbxs[i].id!='T11n')// TODO: unhardcode this
    {
      cbxs[i].checked = false;
    }
  }
  cbSetParents();
}

function cbSelectAll()
{
  var cbxs = document.getElementsByTagName("input");
  for (var i = 0; i < cbxs.length; i++)
  {
    if (cbxs[i].id!='ShowTranslations' && cbxs[i].id!='ShowImplications')// TODO: unhardcode this
    {
      if (!cbxs[i].disabled) {cbxs[i].checked = true;}
    }
  }
  cbSetParents();
}





/* ------------- info popups ------------- */

var offsetx = -25;
var offsety =  20;

function newelement(newid) {  if(document.createElement) {  var el = document.createElement('div');  el.id = newid;      with(el.style) {  display = 'none'; position = 'absolute'; }  el.innerHTML = '&nbsp;';  document.body.appendChild(el);  }  }  var ie5 = (document.getElementById && document.all);  var ns6 = (document.getElementById && !document.all);

function getmouseposition(e){
  if(document.getElementById){
    if(window.event) {
      /* var msg = '';
      for(n in event){
        msg += n + '\n'
      }
      alert(msg); */
      mousex = Event.pointerX(event)
      mousey = Event.pointerY(event)
      
    }
    else if(e) {
      mousex = Event.pointerX(e)
      mousey = Event.pointerY(e)
    }
    //window.status='offsety= ' +offsety+ ', mousey='+mousey+ ', xScrollTop='+xScrollTop();
    var lixlpixel_tooltip = document.getElementById('tooltip');
    lixlpixel_tooltip.style.left = (mousex+offsetx) + 'px';
    lixlpixel_tooltip.style.top = (mousey+offsety) + 'px';
  }
}

function tooltip(target,twhere) {
  var tippedElem = $(target);
  var tip = $(twhere).innerHTML;
  if(!document.getElementById('tooltip'))
    newelement('tooltip');
  var lixlpixel_tooltip = $('tooltip');
  lixlpixel_tooltip.innerHTML = tip;
  lixlpixel_tooltip.style.display = 'block';
  Event.observe(tippedElem, 'mousemove', function(e){
    getmouseposition(e)
  });//
  //document.onmousemove = getmouseposition;
}

function exit() { document.getElementById('tooltip').style.display = 'none'; }


/* ------------- cmstoolbar and menu show/hide ------------- */
function toggleCMSToolbar (name,value) {
  Element.toggle('cmstoobarcollapsed','cmstoobarexpanded','cmstoolbarcollapsedspacer','cmstoolbarexpandedspacer');
}

function toggleMyMenus (collDiv) {
  var parentDiv = collDiv+'high';
  var allDivs = xGetElementsByClassName('cmsmenu',$(parentDiv));/* TODO: dont use xscripts! */
  for (var x = 0; x < allDivs.length; x++)
  {
    if (allDivs[x].id.indexOf(collDiv) == -1)
    {
      Element.toggle(allDivs[x])
    }
  }
}

function toggleAllMenus () {
  var allDivs = document.getElementsByTagName("div");
  for (var x = 0; x < allDivs.length; x++)
  {
    if (allDivs[x].id.indexOf('item_menu') != -1 && allDivs[x].id.indexOf('high') == -1)
    {
      Element.toggle(allDivs[x])
    }
  }
}


/* ML : 2006-03-31 */

function checkAll(name) {
  return checkOrUncheckAll(name, true);
}
function uncheckAll(name) {
  return checkOrUncheckAll(name, false);
}
function checkOrUncheckAll(name, flag) {
  var elements = document.getElementsByName(name);
  for (i = 0; i < elements.length; i++) {
    elements[i].checked = flag;
  }
  return false;
}


/* POW: 2006-09-15 TABS */
//{{{ Tab Scripts
function cmsCreateTabPanelGroup(id, w, h, th, clsTP, clsTG, clsTD, clsTS,initialTab)
{
  //alert("1:new cmsCreateTabPanelGroup in action! "+xClientHeight());
  var oldColor = '';
  var panelGrp = $(id);
  if (!panelGrp) { return null; }
  var panels = xGetElementsByClassName(clsTP, panelGrp);
  var tabGrp = xGetElementsByClassName(clsTG, panelGrp);
  var tabs = xGetElementsByClassName(clsTD, panelGrp);

/*   if (window.console){console.log(panels);}
  if (window.console){console.log(tabGrp);}
  if (window.console){console.log(tabGrp.length);}   
  if (window.console){console.log(tabs);}
  if (window.console){console.log(tabs.length);}  */

  if (!panels || !tabs || !tabGrp || panels.length != tabs.length || tabGrp.length != 1) { return null; }

   var selectedIndex = 0, highZ, x = 0, i;

   xHeight(tabGrp[0],th);
   xMoveTo(tabGrp[0], 0, 0);  // bug fix, top/height

  w -= 2; // remove border widths
  //var tw = w / tabs.length;
  //var tw = 100;  //PW: new
  var tw = 100;

  for (i = 0; i < tabs.length; ++i) {
    if (tabs[i].style.width != '') {
      tw = xWidth(tabs[i]); // support inline style override
    }
    if (tabs[i].style.display == 'none') {
      tw = 0; // exclude hidden tab widths
    }
    xHeight(tabs[i],th);
    xMoveTo(tabs[i], x, 0);
    x += tw;
    tabs[i].xTabIndex = i;
    tabs[i].onclick = tabOnClick;
    tabs[i].onmouseover = tabOnMouseOver;
    tabs[i].onmouseout = tabOnMouseOut;
    if (i!=0 || !xMoz) {/* ? this is for what? */
      xDisplay(panels[i], 'none');
    }
    xMoveTo(panels[i], 0, th );
  }

  highZ = i;
  tabs[initialTab-1].onclick();

  function tabOnMouseOver() {
   // this.className = clsTS;
   this.style.textDecoration = 'underline';
  }
  function tabOnMouseOut() {
   // if (selectedIndex!=this.xTabIndex) {
   //   this.className = clsTD;
   // }
   this.style.textDecoration = 'none';
  }

  function tabOnClick()
  {
    if (selectedIndex!=0 || !xMoz) {
      xDisplay(panels[selectedIndex], 'none');
    }
    tabs[selectedIndex].className = clsTD;
    this.className = clsTS;
    //cmsResizeTabPanel(panels[this.xTabIndex]);
    xZIndex(this, highZ++);
    xDisplay(panels[this.xTabIndex], 'block');
    selectedIndex = this.xTabIndex;
  }

  this.onUnload = function()
  {
    if (Prototype.Browser.IE) for (var i = 0; i < tabs.length; ++i) {tabs[i].onclick = null;}
  }
}


function cmsResizeTabPanelGroup(id, w, h, th, clsTP, clsTG, clsTD, clsTS, offsetY)
{//alert("2:cmsResizeTabPanelGroup in action! " +xClientHeight());
  var panelGrp = $(id);
  if (!panelGrp) { alert('2:null panelGrp'); return null;}
  var panels = xGetElementsByClassName(clsTP, panelGrp);
  //var tabGrp = xGetElementsByClassName(clsTG, panelGrp);
  //var tabs = xGetElementsByClassName(clsTD, panelGrp);/* NOTE: selected tab not included! */
  //if (!panels || !tabs || !tabGrp || panels.length != tabs.length || tabGrp.length != 1) {alert('bad tab markup');return null; }

  //alert(panelGrp);
  
  // if you got that right iframe then use its height instead ... TODO: need to make better (get hieght of iframe instead).... temp for trakken
  var availSpaceH = (parent.document.getElementById('viewPanel'))? Element.getHeight(parent.document.getElementById('viewPanel')) : xClientHeight();
  var offsetH = (parent.document.getElementById('viewPanel'))? 45 : 95;

  offsetH = (arguments.length>8)?arguments[8]:offsetH;//override offset with param
  //alert(offsetH);

  var pgh = availSpaceH - offsetH;
  xHeight(panelGrp,pgh);
  
  for (i = 0; i <= panels.length; ++i) {
    xHeight(panels[i],pgh - th - 2);
  } 

}

//}}}




  function cleanXML(s) {
    return s.replace(/&#34;/g,'"').replace(/&amp;/g,'&').replace(/&lt;/g,'<')
    .replace(/&gt;/g,'>').replace(/&#39;/g,"'");
  }


  function setCMSSiteVar (name,value) {
     var myAjax = new Ajax.Request(
       CoreSiteVars.adminTool,
       {
         parameters:'action=template-cache-errors&CMSSiteVars='+name+':'+value
       }
     );
  }






































    /* used by editors and workflow tab... and? */

  function findSiblingByName(current, name) {
    var parentNode = current.parentNode;
    for (i = 0; i < parentNode.childNodes.length; i++) {
      if (parentNode.childNodes[i].getAttribute &&
          parentNode.childNodes[i].getAttribute('name') == name) {
        return parentNode.childNodes[i];
      }
    }
    return null;
  }
  function getNextSibling(current) {
    if (current == null) return null;
    var sibling = current.nextSibling;
    if (sibling && !sibling.getAttribute) { // this will skip the text node if any
      return sibling.nextSibling;
    }
    return sibling;
  }
  function getPreviousSibling(current) {
    if (current == null) return null;
    var sibling = current.previousSibling;
    if (sibling && !sibling.getAttribute) { // this will skip the text node if any
      return sibling.previousSibling;
    }
    return sibling;
  }
  function getFirstChild(current) {
    if (current == null) return null;
    var child = current.firstChild;
    if (child && !child.getAttribute) { // this will skip the text node if any
      return child.nextSibling;
    }
    return child;
  }
  function getLastChild(current) {
    if (current == null) return null;
    var child = current.lastChild;
    if (child && !child.getAttribute) { // this will skip the text node if any
      return child.previousSibling;
    }
    return child;
  }
  function findDescendentByName(current, name) {
    if (current.getAttribute) {
      if (current.getAttribute('name') == name) {
        return current;
      }
    }

    var children = current.childNodes;
    var i;
    for (i = 0; i < children.length; i++) {
      var result = findDescendentByName(children[i], name);
      if (result != null) return result;
    }
    return null;
  }
  function getNamedParent(node, name)
  {
    if (node == null) {
      return null;
    }
    if (node.tagName == name) {
      return node;
    }
    return getNamedParent(node.parentNode, name);
  }

  function moveUp(node)
  {
    swap(node, getPreviousSibling(node));
  }
  function moveDown(node)
  {
    swap(node, getNextSibling(node));
  }

  function swap(node1, node2)
  {
    if (node1 == null || node2 == null) return;
    var tempNode1 = node1.cloneNode(true);
    var tempNode2 = node2.cloneNode(true);
    var child2 = getFirstChild(tempNode2);
    var child1 = getFirstChild(node1);
    if (child2 == null || child1 == null) return;
    node1.replaceChild(child2, child1);
    child1 = getFirstChild(tempNode1);
    child2 = getFirstChild(node2);
    if (child2 == null || child1 == null) return;
    node2.replaceChild(child1, child2);
  }


    function cancelEventBubbling(e) {
      if (!e) var e = window.event;
      e.cancelBubble = true;
      if (e.stopPropagation) e.stopPropagation();
    }

    function ajaxCall(textbox) {
      /* JJ-2007.12.19: added Loading message here and displayed autocomplete div here (RT-23506, RT-23678) */
      $('userlist').innerHTML="<li>Loading...</li>";
      $('autocomplete').style.visibility = 'visible';
      Element.setStyle($('autocomplete'), {'display':'block'});// bind it to the textbox
      
      var url = '/ajax/selectUser/' + $(textbox).value + '?wfUserSearchfield=' + textbox;
      var a = new Ajax.Updater('userlist', url, {

      });

      var attachable = $('div' + textbox);
      attachable.appendChild($('autocomplete'));
      Element.setStyle(attachable, {'display':'block'});
      
/*       if($(textbox).style.display != 'none'){
        var attachable = $('div' + textbox);
        attachable.appendChild($('autocomplete'));
        Element.setStyle(attachable, {'display':'block'});
      } 
      else{
         $('userlist').style.display = "none"; 
      } */
     
     /*  $('autocomplete').style.visibility = 'visible'; */
      /* Element.setStyle($('autocomplete'), {'display':'block'}); */ // bind it to the textbox
    }

    function setFocus(element) {
      setTimeout("document.getElementById('" + element + "').focus()", 0);
    }

  //{{{ Workflow tab

      function clearClick(input, span) {
        input.value='';
        span.innerHTML='- unspecified -';
      }

      function newField(form, prefix,value,params) {
        var formJSON = eval(form+'Counters');
        //if(window.console) console.dir(formJSON);
        var change = "return false;";
        var clear = "return false;";
        var count = 0;

        if (prefix == 'secAuth') {
          formJSON.numSecAuths++;
          $('num_secAuth_'+form).value = formJSON.numSecAuths;
          count = formJSON.numSecAuths;
        }
        else if (prefix == 'secPub') {
          formJSON.numSecPubs++;
          $('num_secPub_'+form).value = formJSON.numSecPubs;
          count = formJSON.numSecPubs;
        }
        else if (prefix == 'reviewer') {
          formJSON.numReviewers++;
          $('num_reviewers_'+form).value = formJSON.numReviewers;
          count = formJSON.numReviewers;
        }
        else if (prefix == 'rolePrimeAuthor') {
          formJSON.numRolePrimeAuths++;
          $('num_role_primeAuthors_'+form).value = formJSON.numRolePrimeAuths;
          count = formJSON.numRolePrimeAuths;
        }
        else if (prefix == 'roleSecAuthor') {
          formJSON.numRoleSecAuths++;
          $('num_role_secAuthors_'+form).value = formJSON.numRoleSecAuths;
          count = formJSON.numRoleSecAuths;
        }
        else if (prefix == 'roleReviewer') {
          formJSON.numRoleReviewers++;
          $('num_role_reviewers_'+form).value = formJSON.numRoleReviewers;
          count = formJSON.numRoleReviewers;
        }

        // markup dependant code  :[
        /* change = "return changeClick(getFirstChild(getPreviousSibling(this.parentNode.parentNode)),getLastChild(getPreviousSibling(this.parentNode.parentNode)));"; */
        remove = "return deleteWFField(getFirstChild(getPreviousSibling(this.parentNode.parentNode)).id,this,'"+form+"');"; // Update!!!

        var newname = String(prefix+count);
        var newid = String(prefix+count+'_'+form);
        var newspanid = String('span' + prefix + count + '_' + form);
        //var newvalue = (value)? value : '- unspecified -';
        var newvalue = (value)? value : '';

        // changed this to accept autocomplete field  - autocomplete
        var html =
        '<table width="100%" class="cmscontent" cellpadding="0" cellspacing="0" style="border-bottom:1px solid #E8E8E8;font-size:11px;">' +
        '  <tr>' +
        '    <td class="cmscontent" width="100%">' +
        /* '      <input id="' + newid + '" name="' + newname + '" type="hidden" value="' + newvalue + '" />' + */
        '      <input autocomplete="off" id="' + newid + '" name="' + newname + '" type="text" value="' + newvalue + '" class="autocomplete"/>' +
        '      <div class="automenu" id="div' + newid + '" style="position:absolute;background-color:#fff; border: 1px solid #888; display: none;"></div>' +
        /* '      <span id="' + newspanid + '">' + newvalue + '</span>' + */
        '      <span style="display:none;cursor:pointer;" id="' + newspanid + '"></span>' +
        '   </td>' +
        '   <td class="cmscontent" style="white-space:nowrap;">' +
        '     <nobr>' +
        /* '       <input value="Change..." onclick="' + change + '" class="cms" type="button" style="margin-right:5px" />' + */
        '       <input value="Remove" onclick="' + remove + '" class="cms" type="button" />' +
        '     </nobr>' +
        '   </td>' +
        ' </tr>' +
        '</table>';

        //if( window.console ) window.console.log (html);

        new Insertion.Bottom('new' + prefix + '_' + form,html);//Update!!!



        //popup the user select window
     //   if( window.console ) window.console.log('arguments2 is:'+arguments[2]);
        var launchUserSelect = (arguments.length>3)? arguments[3]:1;
       // if( window.console ) window.console.log('launchUserSelect is:'+launchUserSelect);

       /* commented out for auto-select */
       /*
        if(launchUserSelect) changeClick($(newid),$(newspanid));
        */

        // set up span tag
        /* JJ-2007.12.19: no need to have this onclick event for Role Reviewer RT-23506, RT-23678*/
        if((prefix != 'roleReviewer')&&(prefix != 'rolePrimeAuthor')&&(prefix != 'roleSecAuthor')){
          $(newspanid).onclick = function() {
            setFocus(newid);
            Element.show($(newid));
            Element.hide($(newspanid));
          }
        }
        /* if((prefix == 'roleReviewer')||(prefix == 'rolePrimeAuthor')||(prefix == 'roleSecAuthor')){
          $(newspanid).onclick = function() {
            //setFocus(newid);
            //deletes firsrt parent table
            //deleteWFField(fieldName,obj,form)
            deleteWFField(newid,$(newspanid),form);
            var selector = ($(prefix+'_'+form));
            selector.style.display='block';
          }
        } */

        $(newid).onblur = function() {
         if ($(newid).value != '') {
             $(newspanid).innerHTML = $(newid).value;
             Element.hide($(newid));
             Element.hide($('div' + newid));
             Element.show($(newspanid));

         }
        }

        if ((prefix == 'roleReviewer')||(prefix == 'rolePrimeAuthor')||(prefix == 'roleSecAuthor')) {
          $(newid).onblur();
        }



        if ((prefix != 'roleReviewer')&&(prefix != 'rolePrimeAuthor')&&(prefix != 'roleSecAuthor')) {

          var t = new TimedSearch($(newid));
          t.setTree($('userlist'));



          // event polling stuff
          t.pollCallback = function() {
            // make an AJAX call here.
            ajaxCall(newid);

          }

          t.keypressedEnter = function(response) {
            var val = response.substring(0, response.indexOf(' '));
            $(newid).value = val;
            $(newspanid).innerHTML = val;

            Element.setStyle($('autocomplete').parentNode, {'display':'none'});
            $('userlist').innerHTML = '';


            /* hide element */
            Element.hide($(newid));
            Element.show($(newspanid));

          }

          t.keypressedEscape = function() {
             $('userlist').innerHTML = '';
             Element.setStyle($('autocomplete'), {'display':'none'});

             if ($('autocomplete').parentNode.getAttribute('class') == 'automenu') {
               Element.setStyle($('autocomplete').parentNode, {'display':'none'});
             }

             if ($(newid).value != '') {
                 $(newspanid).innerHTML = $(newid).value;
                 Element.hide($(newid));
                 Element.show($(newspanid));
             }

          }
        }


      }

      // this moves the menu -- the deleteWFField tends to remove everything
      // in the tree
      function reattachMenu() {
        var temp_menu = $('temp_menu');

        if (temp_menu) {

           temp_menu.appendChild($('autocomplete'));
        }
      }

      function deleteWFField(fieldName,obj,form) {
        //if( window.console ) window.console.log (fieldName);

        var formJSON = eval(form+'Counters');


        reattachMenu();

        if (fieldName.search('secAuth')!= -1) {
          formJSON.numSecAuths--;
          $('num_secAuth_'+form).value = formJSON.numSecAuths;
        }
        else if (fieldName.search('secPub')!= -1) {
          formJSON.numSecPubs--;
          $('num_secPub_'+form).value = formJSON.numSecPubs;
        }
        else if (fieldName.search('rolePrimeAuthor')!= -1) {
          formJSON.numRolePrimeAuths--;
          $('num_role_primeAuthors_'+form).value = formJSON.numRolePrimeAuths;
        }
        else if (fieldName.search('roleSecAuthor')!= -1) {
          formJSON.numRoleSecAuths--;
          $('num_role_secAuthors_'+form).value = formJSON.numRoleSecAuths;
        }
        else if (fieldName.search('reviewer')!= -1) {
          formJSON.numReviewers--;
          $('num_reviewers_'+form).value = formJSON.numReviewers;
        }
        else if (fieldName.search('roleReviewer')!= -1) {
          formJSON.numRoleReviewers--;
          $('num_role_reviewers_'+form).value = formJSON.numRoleReviewers;
        }

        table = getNamedParent(obj,'TABLE');
        table.parentNode.removeChild(table);

      }


  function attachTimedElementsEvents(newid, newspanid) {
        $(newspanid).onclick = function() {
          setFocus(newid);
          Element.show($(newid));
          Element.hide($(newspanid));
        }


        $(newid).onblur = function() {
          if ($(newid).value != '') {
            $(newspanid).innerHTML = $(newid).value;
            Element.hide($(newid));
            Element.hide($('div' + newid));
            Element.show($(newspanid));
          }
        }



        var t = new TimedSearch($(newid));
        t.setTree($('userlist'));

        t.pollCallback = function() {
          ajaxCall(newid);
        }

        t.keypressedEnter = function(response) {
          var val = response.substring(0, response.indexOf(' '));
          event_keypressedEnter(response, newid);

          $(newspanid).innerHTML = val;
          Element.hide($(newid));
          Element.show($(newspanid));
        }

        t.keypressedEscape = function() {
           event_keypressedEscape();

           if ($(newid).value != '') {
               $(newspanid).innerHTML = $(newid).value;
               Element.hide($(newid));
               Element.show($(newspanid));
           }

        }



      }

  //}}}



//{{{ Workflow templates

    function setWFValues(options) {
      
      var form = options.form;
      var pa = options.pa;
      var rpa = options.rpa;
      var saList = options.saList;
      var rsaList = options.rsaList;
      var rList = options.rList;
      var rrList = options.rrList;
      var pp = options.pp;
      var spList = options.spList;
      //if( window.console ) window.console.log ('setting setWFValues');

      // clear the form
      clearForm(form);

      // set Primary Author
      $('primary_author_'+form).value = pa;
      //$('primary_author_'+form+'Dpy').innerHTML = pa;
      $('spanprimary_author_'+form).innerHTML = pa;
      setUserList(rpa,'rolePrimeAuthor', form)

      // set Secondary Author(s)
      setUserList(saList,'secAuth', form);
      setUserList(rsaList,'roleSecAuthor', form)

      // set Reviewer(s)
      setUserList(rList,'reviewer', form)
      setUserList(rrList,'roleReviewer', form)

      // set Primary Publisher
      if(pp){
        $('primary_publisher_'+form).value = pp;
        $('spanprimary_publisher_' + form).innerHTML = pp;
      }
      //$('primary_publisher_'+form+'Dpy').innerHTML = pp;

      // set Secondary Publisher(s)
      if(spList){
        setUserList(spList,'secPub', form)
      }
      var formJSON = eval(form+'Counters');
      formJSON.modifyFlag = true;
      if(window.console) console.dir(formJSON);
    }



    function clearForm(form) {
      var WorkFlowForm = Form.getElements(form);
      //if( window.console ) window.console.log ('WorkFlowForm = '+WorkFlowForm.inspect());

      var inputs = $A($(form).getElementsByTagName('input'));
      //if( window.console ) window.console.log ('inputs = '+inputs.inspect());

      for(a=0; a<inputs.length; a++){
        //if( window.console ) window.console.log ('should I delete: '+inputs[a].id);
        // add rolePrimeAuthor, roleSecAuthor
        if (  (inputs[a].id.search('secAuth')!= -1  || inputs[a].id.search('rolePrimeAuthor')!= -1  || inputs[a].id.search('roleSecAuthor')!= -1  || inputs[a].id.search('reviewer')!= -1 || inputs[a].id.search('roleReviewer')!= -1 || inputs[a].id.search('secPub')!= -1) && inputs[a].id.search('num')== -1  ) {
          //if( window.console ) window.console.log ('deleting '+inputs[a].id);
          deleteWFField(inputs[a].id,inputs[a], form);
          var formJSON = eval(form+'Counters');
          formJSON.modifyFlag = false;
        }
      }
    }


    function setUserList(userArray,prefix, form)
    {

      //if( window.console ) window.console.log ('setting '+userArray.length+' '+prefix+'\'s');

      for(a=0; a<userArray.length; a++){
        //if( window.console ) window.console.log (userArray[a]);
        var fieldId = prefix + (a+1) + '_' + form;
        //var spanId = prefix + (a+1) + '_'+form+'Dpy';
        var spanId = prefix + (a+1) + '_'+form;
        //if( window.console ) window.console.log('creating newField for '+userArray[a]);

        newField(form, prefix,userArray[a],0);
        
        $('span' + spanId).innerHTML = $(fieldId).value;


        //window.console.log('SPAN: ' + 'span' + spanId + ' = ' + $(fieldId).value);

        Element.show($('span' + spanId));
        Element.hide($(fieldId));

      }
    }




   //}}}


function updateWebFolderLink(folderlink) {
newFolderLink = window.location.protocol+"//"+window.location.host+folderlink.href;
folderlink.href = newFolderLink;
folderlink.folder = newFolderLink;
}

function formatSearchInput(elem) {
   $(elem).value = $(elem).value.replace(/(\r\n|[\r\n])/g, ' ');
}

function cmsCheckForPostRequired(f) {

  if (Form && Form.serialize) {
    formParams = Form.serialize(f);
    if (formParams.length > 2178) {
      f.method='POST';
    }
  }
}




//{{{ Branch Details (temp)


  function cmsViewPage (path,apu)
  {
    window.location = '/staging'+path+'?pageInfoMode=view&branchInfoUrls='+apu;
  }

  function cmsReviewPage (path,apu)
  {
    window.open('/staging'+path+'?pageInfoMode=review&branchInfoUrls='+apu,'_blank','menubar=yes,toolbar=yes,resizable=yes,width=820,height=600,scrollbars=yes');
  }

  function cmsRevertItem (path)
  {
    if (confirm('Revert to the current Trunk version of this content item?')) cmsPerformAction('Reverting, please wait ...',CoreSiteVars.adminTool+'?action=revert-to-trunk&path='+path);
  }

  function cmsLoadL10nManager (path)
  {
    window.open(CoreSiteVars.adminTool+'?action=localisation-manager&path='+path,'_blank','menubar=no,toolbar=no,resizable=yes,width=820,height=600,scrollbars=yes');
  }

  function cmsCheckout (path)
  {
    cmsPerformAction('Activating, please wait ...',CoreSiteVars.adminTool+'?action=activate&path='+path+'&refreshURL='+CoreSiteVars.adminTool+'!action~branch-info');
  }

  function cmsViewDiffs (path)
  {
    window.open(CoreSiteVars.adminTool+'?action=diff2&path1='+path+'&path2='+path+'&tag1=HEAD&tag2=TRUNK','','menubar=no,toolbar=no,resizable=yes,width=650,height=400,scrollbars=yes');
  }

  function cmsSplitFileByChanges (path,jsCurrentBranch)
  {
    var targetBranchName = prompt('File Split: Enter target Branch name');
    if (targetBranchName != null && targetBranchName != '') cmsPerformAction('Splitting Branch, please wait ...',CoreSiteVars.adminTool+'?action=split-branch&sourceBranch='+jsCurrentBranch+'&targetBranch='+targetBranchName+'&path='+path+'&splitMode=allChanges');
  }

  function cmsSplitFileByLocale (path,jsCurrentBranch)
  {
    var targetBranchName = prompt('File Split: Enter target Branch name');
    if (targetBranchName != null && targetBranchName != '') clwin = window.open(CoreSiteVars.adminTool+'?action=locale-selector&tab=1&localiseAction=split-branch&sourceBranch='+jsCurrentBranch+'&targetBranch='+targetBranchName+'&path='+path+'&splitMode=locale&refreshURL='+CoreSiteVars.adminTool+'!action~branch-info|refreshOpenerandCloseOnSubmit~yes','splitbranch','status=no,location=no,menubar=no.menubar=no,width=640,height=480,scrollbars=no,resizable=yes');
  }


//}}}







// {{{ SCOPE OBJECT
// This was in js/Scope.js but auto-search requires this now
//
var Scoper = {
  scope:function(method,args) {
    var scope = this;

    var argString = '';
    if(args) {
      for(i = 0; i < args.length; i ++) {
        argString += "'"+args[i]+"',";
      }

      argString = argString.substring(0,argString.length - 1);
    }

    eval("var ghostFunc = function() {" +
      "var fakeArgs = ["+argString+"];" +

      "if(fakeArgs.length > 0) {" +
      "  fakeArgs = fakeArgs.reverse();" +
      "  for(i = arguments.length - 1; i >= 0; i--){" +
      "    fakeArgs.push(arguments[i]);" +
      "  }" +
      "  fakeArgs = fakeArgs.reverse();" +
      "} else {" +
      "  fakeArgs = arguments;" +
      "}" +

      "scope[method].apply(scope, fakeArgs);" +
    "}");

    return ghostFunc;
  }
}


// }}}

// {{{ WORKFLOW OBJECT




/**
 * The purpose of this class is to provide auto-completion features
 * to a textbox element.  Most auto-completers are inefficient because
 * they make an AJAX call on every keypress event, or all results
 * needs to be pre-loaded. This class works on time intervals and
 * only makes AJAX requests when needed.  Of course, you dont' have
 * to use AJAX with this class.
 *
 *
 */
function TimedSearch(textbox) {
  this.textbox = textbox;
  this.timer   = 0;  // timer
  this.ms      = 10; // threshhold in milliseconds
  this.current = 0;  // counter
  this.timeout = 50; // how many ticks before calling callback

  this.event_fired = false;

  this.attachSearch();
}


TimedSearch.prototype = {

  // this method is automatically initialized and
  // attaches events to the texbox
  attachSearch:function() {
    Event.observe(this.textbox, 'keyup', this.scope('handleKeyUp'));
    Event.observe(this.textbox, 'blur',  this.scope('handleBlur'));
  },


  // private: this is called recursively. once timeout has been
  // reached, then it will execute pollCallback() which is a public
  // overridable method.
  _pollSearch:function() {
    var _self = this;
    //$('tcount').innerHTML = this.current;

    if (this.current >= this.timeout) {

      this.current = 0;
      this.timer = 0;
      clearTimeout(this.timer);
      this.pollCallback();
    } else {
      this.current++;


      this.timer =  setTimeout(function(ms){
            _self._pollSearch();
          }, this.ms);
    }
  },


  // This is executed every time a key is pressed.
  // It will reset the timer to 0
  handleKeyUp:function(event) {
    var _self = this;
    var keycode = event.keyCode;
    this.current = 0; // always reset



    if (this.event_fired == false) {
      if (window.console) {
        console.log('KEYCODE : ' + keycode);
      }

      switch(keycode) {

        case 16: /* ignore */
        case 36:
        case 35:
        case 91:
        case 17:
        case 18:
        case 27:
        case 38:
        case 40: /* end of ignore list */

        case 13:
          if (keycode == 13) {
            this.event_fired = true;
          }
          this.keyupCallback(keycode);
          return;

      }
    }



    if (this.timer > 0) {
      clearTimeout(this.timer);
    }

    if ($(this.textbox).value != '' && this.event_fired == false) {
        this.timer = setTimeout(function(ms){
          _self._pollSearch();
        }, this.ms);

    }
    this.event_fired = false;

  },

  handleBlur:function() {
    this.current = 0;
    this.timer   = 0;

    this.blurCallback();
    clearTimeout(this.timer);
  },

  // this is meant to be overridden. and is only called
  // after the number of seconds.
  pollCallback:function() {

  },
  // this is meant to be overridden
  blurCallback:function() {

  }


}




ListNavigator = {
  // this is meant to be called when up,down,enter is
  // pressed
  selected:0,
  tree:null,

  // meant to be overidden
  // this is the method that is executed when enter key is pressed
  keypressedEnter:function(response) {

  },

  keypressedEscape:function() {

  },

  // meant to be overidden
  // this is the method that is executed when mouse is pressed
  clickCallback:function() {

  },

  // generic keyup callback which is executed
  // when KEYUP,KEYDOWN,ENTER is selected.  This is used mainly
  // in the TimedSearch class, but you can use it for other things
  // too.
  keyupCallback:function(keycode) {
    var KEYUP   = 38;
    var KEYDOWN = 40;
    var ENTER   = 13;
    var ESCAPE  = 27;

    var tree = this.tree.getElementsByTagName('li');



    if (tree) {
      // remove selected item
      var selected_items = Element.select(this.tree,'.selected');


      // only if we neeed to do anything
      if ((keycode == KEYUP || keycode == KEYDOWN) && (this.selected - 1 >= 0 && this.selected + 2 <= tree.length)) {
        selected_items.each(function(item) {
           Element.removeClassName(item, 'selected');
        });
      }

      switch(keycode) {
        case ESCAPE:
          this.keypressedEscape();
          break;
        case KEYUP:

          if (this.selected - 1 >= 0) {
            Element.removeClassName(tree[this.selected], 'selected');
            Element.addClassName(tree[this.selected - 1], 'selected');
            this.selected--;
          }
          break;

        case KEYDOWN:

          if (this.selected + 2<= tree.length) {
            Element.removeClassName(tree[this.selected], 'selected');
            Element.addClassName(tree[this.selected + 1], 'selected');
            this.selected++;
          }
          break;
        case ENTER:
          //alert('You have selected ' + tree[this.selected].innerHTML );



          if(tree[this.selected] && tree[this.selected].innerHTML.indexOf('Loading...') < 0) {

            this.keypressedEnter(tree[this.selected].innerHTML);

          }

          //$('current_time').setStyle({'display':'none'});
          break;
      }
    }
  },

  setTree:function(tree) {
    this.tree = tree;
  }
}

/* we need to move prototype.js first. */







// }}}


/* AT:commenting out, wondering if any of the form scripts are in fact in use at all */

/* Form.tests.PatternCheckout = {
        name:'pattern-checkout',
        classAddition: '',
        test: "field.checked && !field.hasClassName('branch-builtin')",
        type:"checkbox"
      }

Form.tests.PatternSplitLocale = {
        name:'pattern-checkout',
        classAddition: '',
        test: "field.checked && !field.hasClassName('unlocalized')",
        type:"checkbox"
      } */


