// Standard JavaScript Utility Methods
// $Id: ctaUtilities.js,v 1.15 2011-03-29 12:53:00 john Exp $

function CTA_Popup(URL, target, args) {
  // Create/lookup the window by target.
  var newWin = window.open(URL, target, args);
  // Ensure the window is focused.
  newWin.focus();
}

function CTA_updateClock (stime, diffTime, prefix) {
  var currentTime = new Date ();
  var clientTime = new Date ();
  if (stime == 0) {
    currentTime.setTime(currentTime.getTime() + diffTime);
  } else {
    currentTime = new Date(stime);
    diffTime = (currentTime.getTime() - clientTime.getTime())/1000;
    diffTime = Math.floor(diffTime) * 1000;
  }
  // Update the time display
  document.getElementById(prefix + "serverclock").firstChild.nodeValue = currentTime.toUTCString().replace(/,/, "").replace(/:[0-9][0-9] /, " ");
  document.getElementById(prefix + "clientclock").firstChild.nodeValue = clientTime.toLocaleString().replace(/:[0-9][0-9] /, " ").replace(/:[0-9][0-9]$/, "");
  return diffTime;
}

function CTA_togglevisibility(element) {
  e = document.getElementById(element);
  if (e.style.visibility=='visible') {
    e.style.visibility='hidden';
  } else {
    e.style.visibility='visible';
  }
}

/** Simple method for toggling display style between 'none' and 'block'.
 * Used by 'alert' message which can be enabled via the WebSettings interface.
 */
function CTA_toggleDisplay(elementId) {
  var element = document.getElementById(elementId);
  if (element.style.display != 'none') {
    element.style.display = 'none';
  } else {
    // That the client wants block is a hell of an assumption, but this is a simplistic method anyway.
    // You can't use 'inherit' because it isn't supported on IE6.
    element.style.display = 'block';
  }
}

/** This method toggles two fields visibility based on whether a checkbox is
 * checked. If checked, field1 row is visible and field input enabled and field2 row is hidden and field input disabled.
 * If not checked, field1 row is hidden and field input disabled and field2 row is visible and field input enabled.
 * If field1 = 'field.name', then it needs a row id 'field.name.row' and an input field 'field.name'.
 */
function CTA_toggleFieldVisibility(checkbox, field1, field2) {
  var checkbox = document.getElementById(checkbox);
  var field1EncapsulatingTag = document.getElementById(field1 + ".row");
  var field2EncapsulatingTag = document.getElementById(field2 + ".row");
  var field1Input = document.getElementById(field1);
  var field2Input = document.getElementById(field2);
  if (checkbox.checked) {
    field1EncapsulatingTag.style.display = "";
    field1Input.disabled = false;
    field2EncapsulatingTag.style.display= "none";
    field2Input.disabled = true;
  } else {
    field1EncapsulatingTag.style.display= "none";
    field1Input.disabled = true;
    field2EncapsulatingTag.style.display= "";
    field2Input.disabled = false;
  }
 }

/** Helper used initially by DojoDialogFormActionHandler.
 * This does the job of opening a dialog, but also ensuring any script contents
 * are eval'd and the cancel buttons just close the dialog rather than doing a server roundtrip.
 */
function CTA_showDojoDialog(dojoDialogId, evalScriptNodes) {
  var dojoDialog = dijit.byId(dojoDialogId);
  if (!dojoDialog) {
    console.error("Could not locate dialog: " + dojoDialogId);
  } else {
    if (evalScriptNodes) {
      // dijit.Dialog doesn't use dojox ContentPane, and so doesn't have script support.
      dojo.connect(dojoDialog, 'onLoad', this, function() {
        var dojoDialogNode = dojo.byId(dojoDialogId);
        CTA_evalScriptNodes(dojoDialogNode);
      });
    }

    // Hookup any 'cancel' button to the dialog close function.
    dojo.connect(dojoDialog, 'onLoad', this, function() {
      var dojoDialogNode = dojo.byId(dojoDialogId);
      var cancelButtons = dojo.query("div.btn input[name*='cancel']", dojoDialogNode);
      cancelButtons.forEach(function(cancelButton) {
        dojo.connect(cancelButton, 'onclick', this, function(event) {
          // Stop the click from going any further.
          event.stopPropagation();
          event.preventDefault();
          dojo.stopEvent(event);

          // Close the dialog.
          dojoDialog.hide();
        });
      });
    });

    dojoDialog.show();
  }
}

/** Find script blocks in the supplied container eval them.
 * This is useful when asynchronously requesting some HTML and wishing to integrate it in a page.
 * Please note this function REQUIRES DOJO.
 * @param containerNode DOM node containing script tags to execute.
 */
function CTA_evalScriptNodes(containerNode) {
  if (containerNode) {
    var appendNode = dojo.doc.body;
    dojo.query("script", containerNode).forEach(function(scriptNode) {
      // Execute script element, technique from dojox.layout.ContentPane.evalInGlobal function.
      // Do not pull in the src if it is a dojo.js import, we should never call dojo.js twice.
      if (!(scriptNode.src && scriptNode.src.match(/dojo.js/))) {
        var newScriptNode = appendNode.ownerDocument.createElement('script');
        newScriptNode.type = "text/javascript";
        appendNode.appendChild(newScriptNode);
        if (scriptNode.src) {
          newScriptNode.src = scriptNode.src;
        } else {
          newScriptNode.text = scriptNode.innerHTML;
        }
      }
    });
  }
}

/** Used by ComponentExtenderWeb.PerformTask to ensure onclick methods in a wrapped UC are executed
 * if the transition button will call that UC action.
 */
function CTA_performWorkflowTransitionOnClick(ucButtonOnClickId) {
  var ucButtonQuery = dojo.query("input[name='" + ucButtonOnClickId + "']");
  if (ucButtonQuery[0]) {
    // Detect if button has an onclick event.
    var ucButton = ucButtonQuery[0];
    var ucButtonOnClickFunction = ucButton.onclick;
    if (ucButtonOnClickFunction) {
      // Execute the function within the current scope.
      var hitchedFunction = dojo.hitch(this, ucButtonOnClickFunction);
      return hitchedFunction();
    }
  }
  // If we could not locate the onclick then default to allowing the transition to continue.
  console.debug("Could not locate onclick for button: " + ucButtonOnClickId);
  return true;
}

