var isSaved=false;
var pageHitTime = new Date();
function goSaveWorkflow(pageId)
{
   if (!isSaved)
   {  // prevent double click
      isSaved = true;
      goPage(pageId);
   }
}


function hPopup(Site)
{
   var NewWindow1 =window.open(Site, "viewwin","toolbar=0,width=450,height=300,resizable=no");
   NewWindow1.focus();
   return false; 
}



function goState(stateId)
{
  submitGoState( "GO_PAGE_FORM" ,true ,stateId );
}

function submitGoState( formName ,isOkToSubmit ,stateId )
{
  if ( isOkToSubmit )
  {
    formToSubmit = eval( "document." + formName );
    formToSubmit.nextStateId.value=stateId;
    formToSubmit.submit();
  }
}

function goBackState(stateId)
{
  GO_PAGE_FORM.workflowDirection.value='backward';
  goState(stateId);
}

function goPage(pageId)
{
  var currentAction       = document.GO_PAGE_FORM.action;
  var paramStartPosition  = currentAction.indexOf( "?" );
  var bookmarkParam       = "?pageId=" +escape( pageId );
  var bookmarkAction;

  if( paramStartPosition >= 0 )
  {
     //Insert the bookmark param immediately after the base url; this
     //is done for easier debugging.
     bookmarkAction =   currentAction.substring( 0, paramStartPosition )
                      + bookmarkParam
                      + "&"
                      + currentAction.substring( paramStartPosition+1 );
  }
  else
  {
     bookmarkAction = currentAction + bookmarkParam;
  }
  document.GO_PAGE_FORM.action=bookmarkAction;
  document.GO_PAGE_FORM.pageId.value=pageId;
  document.GO_PAGE_FORM.submit();
}


function getPortalHref(pageId)
{
  pageId = pageId.replace( /\?/ ,"&" ); //handles: pageId?var=value, only 1st occurence is replaced!
  return document.GO_PAGE_FORM.portal.value+pageId;
}

function confirmGoPage( msg, pageID )
{
  if ( confirm( msg ) )
  {
    goPage( pageID );
  }
}

function goPagePrintPreview(pageId)
{
  goPageNewWindow(pageId,"printPreview" );
}

/**
 * use this function to redirect the calling window of a opened window, so that
 * the caller/parent will redirect and the child window will close.
 */
function goPageParent(pageId)
{
   opener.goPage(pageId);
   window.close();
}

function goPageHelp(pageId)
{
  goPageNewWindow(pageId,"help","scrollbars=no,height=273,width=391");
}

function goPageHealthwiseNewWindow(srcUniqueId,type)
{
   var features;
   // If different types ("mm-doc" or whatever) needed different features, set if else here.
      features = "height=400,width=500,top=60,left=100,"
                  +"toolbar=no,location=no,menubar=no,statusbar=no,"
                  +"scrollbars=yes,resizable=yes";

   //javascript:goPage('site_content?srcUniqueId=aa150194')
   goPageNewWindow("site_content_popup_more_info?srcUniqueId=" + srcUniqueId,"healthwise",features);
}

function goDocumentNewWindow(docName,windowName,windowStyle)
{
   docName = escape(docName);
   // url-encode plus signs, which escape doesn't do for us
   docName = docName.replace( /\+/g, "%2B" );   //replace all occurrences
   pageId = "stream_document?docName=" + docName;
   goPageNewWindow(pageId,windowName,windowStyle);
}

function goPageNewWindow(pageId,windowName,windowStyle)
{
   currentTime = new Date();
   var totalElapsedTime = (currentTime.getTime() - pageHitTime.getTime()) / 1000;
   if (isValidateLogin)
   {
      if (totalElapsedTime >= timeout)
      {
         goPage("80050");
      }
      else
      {
         pageHitTime = new Date(); // reset pageHitTime
         newWindow( getPortalHref( pageId ),windowName,windowStyle);
      }
   }
   else
   {
      newWindow( getPortalHref( pageId ),windowName,windowStyle);
   }


}

function goPageExternal(url,windowName,windowStyle)
{
  goPageNewWindow("1999?url="+url,windowName,windowStyle);
}

function newWindow(href,windowName,windowStyle)
{
  //  Here is the list of features to choose from:
  // "height=100" (in pixels)
  // "location"   (shows addressbar)
  // "menubar"    (shows file menu)
  // "resizable"  (allow resizing of window)
  // "scrollbars" (show right and bottom scrollbars)
  // "status"     (show status bar)
  // "toolbar"    (show back, forward, stop, etc. buttons)
  // "width=100"  (in pixels)
  // ===================================
  // There should be no spaces:
  // "feature1,feature2,feature3,etc"
  // "height=377,location=no,menubar=no,resizable=yes,scrollbars=no,status=yes,toolbar=no,width=740"

  var undefined;

  if( windowName == undefined )
  {
    windowName = "newWindow";
  }

  if( windowStyle == undefined )
  {
    windowStyle = "status=yes,scrollbars=yes,toolbar=yes,resizable=yes,menubar=yes";
  }

  windowStyle = _verifyWindowSize( windowStyle );

  new_window = window.open(href,windowName,windowStyle);

  //"onerror" is required for external links where the windowName may be changed.
  //Non-matching window names in IE generate a javascript error.
  self.onerror = function() { return true; };
  new_window.focus();
  self.onerror = function() { return false; };
}

function plainWindow(href)
{
  newWindow(href,"plain");
}

function moreInfoWindow(code)
{
   var pageId = 'more_info?code=' + code;
   newWin = "'" + pageId + "','helpWindow','status=yes,scrollbars=yes,top=150,left=150,width=325,height=300'";
   document.write('<a href="javascript:goPageNewWindow(' + newWin + ');"><img src="./healthecare/ui/images/icons/icon_more_info.gif" border="0" alt="click here for more information" align="absmiddle"></a>');
}

function helpWindow(pageId)
{
   newWin = "'" + pageId + "','helpWindow','status=yes,scrollbars=yes,top=150,left=150,width=325,height=300'";
   document.write('<a href="javascript:goPageNewWindow(' + newWin + ');" title="Help for This Page"><img src="./healthecare/ui/images/icons/page_specific_help.gif" border="0" alt="Help for This Page" align="absmiddle">&nbsp;Help&nbsp;</a>');
}

function goPrintWindow(pageId, theForm)  {

     var queryString = "";

     if(theForm != null)
     {
         //prepare query string, do not append "?" if pageId already contains "?"
         var pageIdString = new String(pageId);

         if (pageIdString.indexOf("?") == -1)
         {
            queryString = "?";
         }

        var printableValues = new Array();
        printableValues = eval('document.' + theForm + '.elements');

        if (printableValues != null || printableValues.length != 0)
        {
           for(var i=0; i < printableValues.length; i++)
           {

              var thisField = printableValues[i];

              if(thisField.name != null)
              {
                 var thisFieldName = thisField.name;
                 var thisFieldValue = "";
                 if(thisField.value != null && thisField.selectedIndex != null)
                 {
                     thisFieldValue = getElementValue(thisField);
                 }
                 queryString += thisFieldName + "=" + thisFieldValue;
              }

              if(i < printableValues.length)
              {
                 queryString += "&";
              }
           }
         }
     }

    newWinParams = "'status=yes,scrollbars=yes,top=150,left=150,width=800,height=600'";
    goPageNewWindow(pageId + queryString, 'printWindow', newWinParams);
}

/** Support functions for formMonitor BEGIN */
   function getElementValue(element)
   {
      var eType  = element.type.toLowerCase();
      var eValue = "";

      if( eType == 'text' || eType == 'password' || eType == 'textarea' || eType == 'hidden' )
      {
         eValue = element.value;
      }
      else if( eType == 'radio' )
      {
         //TODO: deal with arrays- TDinkel
         eValue = element.checked ? element.value : "";
      }
      else if( eType == 'checkbox' )
      {
         //TODO: deal with arrays- TDinkel
         eValue = element.checked ? element.value : "";
      }
      else if( eType == 'select-one' || eType == 'select-multiple' )
      {
         eValue = getValuesFromSelect(element.form.name, element.name);
         //eValue = element.options[element.selectedIndex].value;
      }
      else if( eType == 'button' || eType == 'reset' || eType == 'submit' || eType == 'file' )
      {
         // Do nothing but leave an empty slot in the array.
         eValue = '';
      }
      return eValue;
   }

function printWindow(pageId, theForm)
{
   var theFormString = (theForm != null) ? new String(",'" + theForm + "'") : "";
   document.write('<a href="javascript:goPrintWindow(\'' + pageId + '\'' + theFormString + ');" title="Print This Page"><img src="./healthecare/ui/images/icons/page_specific_print.gif" border="0" alt="Print This Page" align="absmiddle">&nbsp;Print&nbsp;</a>');
}

function _verifyWindowSize( windowStyle )
{
   //For now... only mess with size if no size (width) is specified.

   if( windowStyle.toUpperCase().match( "WIDTH" ) )
   {
      return windowStyle;
   }

   var newH;
   var newW;

   if (isNetscape)
   {
      newW = window.innerWidth ;
      newH = window.innerHeight;
   }
   else if (isIE)
   {
      newW = document.body.clientWidth ;
      newH = document.body.clientHeight;
   }
   else
   {
      newW = 800;
      newH = 600;
   }

   newW = Math.round( 0.9 * newW );
   newH = Math.round( 0.9 * newH );

   var windowSize = ",WIDTH=" +newW+ ",HEIGHT=" +newH;

   return windowStyle + windowSize;
}


function ChangeState(ctrl, imagefilename){
  ctrl.src = imagefilename
  return true
}

function urlEncode( str )
{
  // ToDo: urlEncode()
  return trim( str );
}

function trim(strText)
{
  // strip leading spaces
  while (strText.substring(0,1) == ' ')
      strText = strText.substring(1, strText.length);

  // strip trailing spaces
  while (strText.substring(strText.length-1,strText.length) == ' ')
      strText = strText.substring(0, strText.length-1);

 return strText;
}

//Tests if string is "" or null.
function isEmpty( str )
{
   return (str == null) || ( trim( str ).length == 0 );
}

function isValidSearchString( searchString )
{
  var useChars = "!@#$%^&()_+=.-";
  if( trim( searchString ) == "" )
  {
    alert( "Please enter search text." );
    return false;
  }else
  {
	  for(var i = 0; i < searchString.length; i++)
	  {
	      temp = searchString.substring(i,i+1);
	      if(useChars.indexOf(temp.toLowerCase()) != -1)
		  {
		  	alert("Please do not use any special characters in your search term (- . ! @ # $ % ^ & ( ) _ + = )");
			return false;
		  }
	  }
  }

  return true;
}

// Validates "site search" text.
function isValidSiteSearch()
{
   var isValid = isValidSearchString( document.siteSearchForm.query.value );
   if( isValid )
   {
      document.siteSearchForm.pageId.value="31001";
   }
   return isValid
}

// Validates and triggers "site search" text.
function siteSearchGo()
{
   if( isValidSiteSearch() )
   {
      document.siteSearchForm.submit();
   }
}

/* Enter key detection.
   Place this anywhere on your page, it may also go inside your existing script tags.
** vvvvv EXAMPLE vvvvv **
   ~script language="javascript1.3" type="text/javascript"~
   thisPageUsesEnterKeyDetect("alert('Your single-quoted js command goes here')");
   ~/script~
** ^^^^^ EXAMPLE ^^^^^ **

   Set "onfocus" and "onblur" on fields that should detect the enter key.
** vvvvv EXAMPLE vvvvv **
	<input type="text" name="sample" value="Some value"
	onFocus="setEnterKeyAction('on')" onBlur="setEnterKeyAction('off')">
** ^^^^^ EXAMPLE ^^^^^ */
var enterKeyJsCommand    = "";
function thisPageUsesEnterKeyDetect( enterKeyAction )
{
	document.onkeydown = forEveryKeyDown;
	if( isNetscape4 )
    { document.captureEvents(Event.KEYDOWN|Event.KEYUP); }
	enterKeyJsCommand = enterKeyAction;
}
var enterDoThis = "";
function setEnterKeyAction(onOff)
{
	enterDoThis = (onOff == 'on') ? 'on' : 'off';
	enterDoThis = (onOff == 'off') ? 'off' : 'on';
}
var isNetscapeKey = (navigator.appName.indexOf('Netscape') != -1) ? true : false;
function forEveryKeyDown(DnEvents)
{
	var key = (isNetscapeKey) ? DnEvents.which : window.event.keyCode;
	if ( (key == 13) && enterDoThis == 'on')
	{
		eval( enterKeyJsCommand );
    }
} // End Enter key detection.

/* Places focus on the first visible form element
	for the form you specify (override doOnLoad() for "onLoad" event,
   or add it to an already existing doOnLoad() ).
** vvvvv EXAMPLE vvvvv **
   function doOnLoad()
   {
      firstFieldFocus( document.myForm );
   }
** ^^^^^ EXAMPLE ^^^^^ */
function firstFieldFocus( documentForm )
{
   if( isIE || isNetscape6 )
   {
      for(var i = 0; i < documentForm.length; i++)
      {
         if( documentForm.elements[i].type.toLowerCase() != "hidden" )
         {
           documentForm.elements[i].focus();
           break;
         }
      }
   }
}


function getScreenInfo()
{
   var ScreenWidth       = 0;
   var ScreenHeight      = 0;
   var ScreenColorDepth  = 0;
   var ColorCount        = 0;
   var ScreenAvailWidth  = 0;
   var ScreenAvailHeight = 0;
   var WindowWidth       = 0;
   var WindowHeight      = 0;
   var ScreenInfo        = "";

   ScreenWidth       = screen.width;
   ScreenHeight      = screen.height;
   ScreenColorDepth  = screen.colorDepth;
   ColorCount        = Math.pow(2, ScreenColorDepth);

   ScreenAvailWidth  = screen.availWidth;
   ScreenAvailHeight = screen.availHeight;

   WindowWidth       = ( isNaN(window.innerWidth) ) ? document.body.clientWidth  : window.innerWidth;
   WindowHeight      = ( isNaN(window.innerWidth) ) ? document.body.clientHeight : window.innerHeight;

   ScreenInfo = 'ScreenWxH: ' + ScreenWidth + 'x' + ScreenHeight     + '(' + ScreenAvailWidth  + 'x' + ScreenAvailHeight + '); WindowWxH: ' + WindowWidth + 'x' + WindowHeight + '; Colors: ' + ColorCount + '(' + ScreenColorDepth + ' bit);'
   document.GO_PAGE_FORM.ScreenDetails.value = ScreenInfo;
}


// Called by every page... onload event handler.
function dhOnLoad()
{
  //Call the statistics javascript function that will set up the screen resolution size to the request
  getScreenInfo();
  doOnLoad()
}

// override this...
function doOnLoad()
{
}