/*
  This file inclues scripts for the following areas
  -- validation   (was pe_validate.js)
  -- focus        (was pe_focus.js)
  -- mouseover    (was pe_mouseover.js)
  -- cookies      (was pe_cookies.js)
*/

/*
   VALIDATION
*/

/**
    * Validates that at least one radio button has been checked
    * @param pForm
      @param pGroupName
    * @param pFieldDescription description of the field
    */
   function validateRadioButtonRequired(pForm, pGroupName, pFieldDescription)
   {

      for (var e = 0; e < pForm.elements.length; e++)
      {

         var formElement = pForm.elements[e];
         if (
            (formElement.type == 'radio')
            && (formElement.type != 'hidden')
            && (formElement.name == pGroupName)
            )
         {
            if (formElement.checked)
            {
               return true;
            }
         }
      }
      alert(pFieldDescription); /* Example of pFieldDescription: Please select an option */
      return false;
   }


   /**
   * Calculates the length of the text encoded in UTF8.
   */
    function calcLengthUTF8(pText)
   {
         var count=0;
         var countChr10=0;

         for(var n=0; n<pText.length; n++)
             {
             var c=pText.charCodeAt(n);
             //  0-127 => 1byte
             if (c<128)
             {
                 count++;
             }
             //  127 through 2047 => 2byte
             else if((c>127) && (c<2048))
             {
                count=count+2
             }
             //  2048 through 66536 => 3byte
             else
             {
                count=count+3;
             }
             // Account for CRLFs added on the server side.
             if (c==10)
             {
               countChr10++;
             }
          }

         return count + countChr10;
     }


   /**
   * Validates text area length
   * @param field field object whose length you need to check
   * @param fieldDescription description of the field
   * @param maxLength maxmium length of the field.
   */
   function validateLength (field,
                        fieldDescription,
                        maxLength)
   {
      // alert("validate length for description=" + fieldDescription);
      var actualLength = calcLengthUTF8(field.value);
      var extraCharLength = actualLength - maxLength;
      var valid=true;
      if (actualLength > maxLength)
      {
        alert ("You have exceeded the maximum "
               + fieldDescription
               + " size of "
               + maxLength
               + " characters.\n Please remove "
               + extraCharLength + " characters from "
               + fieldDescription);
        valid=false;
      }
      return valid;
   }



   /**
   * Validates multiple fields of the same name.  Just make sure they are legit.
   * none is ok
   * @param fieldName
   */
  function isValidEmail(checkValue, isRequired)
  {
     //First check for a blank field or nothing but spaces
      if (checkValue.length == 0)
      {
         if (isRequired == "true")
         {
            return false;
         }
         else
         {
            return true;
         }
      }

      //Split E-Mail addressses at commas, returns an array
      var arrEMailCont = checkValue.split(",");

      if (arrEMailCont.length > 1)
      {
         alert('too manyt');
         return false;
      }

      var strSingleEMail = arrEMailCont[0];
      // alert('will check address=' + strSingleEMail);
      var flagHasDot = "";
      var flagHasAt = "";

      //Test all characters in an individual e-mail addresses for the presence of a "." and an "@"
      for (j = 0; j < strSingleEMail.length; j ++)
      {
         if (strSingleEMail.charAt(j) == ".")
         {
         //  alert('found dot');
            flagHasDot = "yes";
         }
         if (strSingleEMail.charAt(j) == "@")
         {
         //alert('found at');
            flagHasAt = "yes";
         }
      }

      return (flagHasDot == "yes" && flagHasAt == "yes");

   }

   /**
   * Validates an Email address.  Simpler than above
   *
   * Ensures email address is in form of
   *   a.b.c.d.e.@foo.bar.com
   *   a.b.c.d.e@192.168.0.1
   *
   * 'a.b.c.d' means any "OK for email character"
   */
   function isValidEmail(pEmailAddress)
   {
      var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      return re.test(pEmailAddress);
   }


  /**
   * Validates that something has been entered
   * @param field field object whose length you need to check
   * @param fieldDescription description of the field
   */
  function validateRequired (field, fieldDescription)
  {
     var actualLength = 0;
     if (field && field.value)
     {
       actualLength = endtrim(field.value).length;
     }
     var isValid=true;
     if (actualLength == 0)
     {
        alert ("Please enter a value for "
                + fieldDescription + ".");
        isValid=false;
     }
     return isValid;
  }


  /**
  This function only removes the spaces on the ends
  */
  function endtrim (pTrimValue)
  {
     if(pTrimValue.length < 1)
     {
        return "";
     }
     pTrimValue = rtrim(pTrimValue);
     pTrimValue = ltrim(pTrimValue);
     if (pTrimValue == "")
     {
        return "";
     } else {
        return pTrimValue;
     }
  } //End Function

   function rtrim (pValue)
   {
      var w_space = String.fromCharCode(32);
      var v_length = pValue.length;
      var strTemp = "";
      if (v_length < 0) {
        return "";
      }
      var iTemp = v_length -1;

      while(iTemp > -1)
      {
        if(pValue.charAt(iTemp) == w_space)
        {
        } else {
           strTemp = pValue.substring(0,iTemp +1);
           break;
        }
        iTemp = iTemp-1;

      } //End While
      return strTemp;

   } //End Function


   function ltrim (pValue)
   {
      var w_space = String.fromCharCode(32);
      if(v_length < 1){
         return "";
      }
      var v_length = pValue.length;
      var strTemp = "";

      var iTemp = 0;

      while(iTemp < v_length){
         if(pValue.charAt(iTemp) == w_space){
         }
         else{
            strTemp = pValue.substring(iTemp,v_length);
            break;
         }
         iTemp = iTemp + 1;
      } //End While
      return strTemp;
   }
   /**
      This function removes all spaces from a string
      Example Trim(' Me And You ') returns 'MeAndYou'
      @param pUntrimmed
   */
   function trim(pUntrimmed)
   {
      var Trimmed = '';
      for (var i = 0; i < pUntrimmed.length; i++)
      {
         if (pUntrimmed.charCodeAt(i)!=32)
         {
            // @todo verify this works.  untrimmed[i] may be undefined
            Trimmed += pUntrimmed[i];
         }
      }
      return Trimmed;
   }

   function trimString (str)
   {
      str = this != window? this : str;
      return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
   }

   function getRadioValue(radioObjects)
   {
      for (var i=0; i < radioObjects.length; i++)
      {
         if (radioObjects[i].checked)
         {
            return radioObjects[i].value;
         }
      }
      return null;
   }






/********************************************************************************
   FOCUS
*/
/**
 * Brings focus to window, then to the searchString input field
 */
function peFocus()
{
   // get the focus on this page
   self.focus();

   // If there is an input field with id="searchString", put the focus on it
   if (document.getElementById('searchString'))
   {
      document.getElementById('searchString').focus();
   }
}


/***********************************************************
   MOUSEOVER
*/
   function mouseOverEvent(imgArrNo)
   {
     document.images[arrImageNames[imgArrNo]].src = arrOnImages[imgArrNo].src
   }

   function mouseOutEvent(imgArrNo)
   {
     document.images[arrImageNames[imgArrNo]].src = arrOffImages[imgArrNo].src
   }


/*********************************************************
   COOKIES
*/
   /* Get Cookie Function
   @param cookieName = name of the cookie whose value we are attempting to access
   */
   function getCookie(cookieName)
   {
      //Determine starting position of cookie value
      var cookieStart = document.cookie.indexOf(cookieName + "=");

      //Determine length of cookie
      var cookieLength = cookieStart + cookieName.length + 1;

      /*Determine if cookie value exists, return null if not found*/
      if ((!cookieStart) && (cookieName != document.cookie.substring(0,cookieName.length)))
       return null;
      if (cookieStart == -1) return null;

      /*Cookie exists, get value*/
      //Find end position of cookie value
      var cookieEnd = document.cookie.indexOf(";",cookieLength);

      if (cookieEnd == -1)
       cookieEnd = document.cookie.length;

      //Return cookie value
      return unescape(document.cookie.substring(cookieLength,cookieEnd));
   }

   /*
   SetCookie

   @param cookieName  = name of the cookie whose value we are attempting to set
   @param cookieValue = value of the cookie to set
   OPTIONAL PARAMS
   @param cookieExpires = number of hours before cookie expires
   @param cookiePath    = sets the path to the directory (and subdirectories that are allowed to read the cookie; default is current
   @param cookieDomain  = sets the valid domain(s) that are allowed to use the cookie; default is current
   @param cookieSecure  = Boolean indicator requiring SSL for transmission of the cookie; default is not required
   */
   function setCookie(cookieName,cookieValue,cookieExpiresHours,cookiePath,cookieDomain,cookieSecure)
   {
      var expDateGMT;

      /* Convert the number of days after which a cookie will expire to milliseconds for conversion to Greenwich Mean Time */
      if (cookieExpiresHours)
      {
       var currentDate;

       currentDate = new Date();
       //24 hours in a day, 60 minutes in an hour, 60 seconds in a minute, 1000 milliseconds in a second
       currentDate.setTime(currentDate.getTime() + (cookieExpiresHours * 60 * 60 * 1000));
       expDateGMT = currentDate.toGMTString();
      }
      else
       expDateGMT = ""

      /* Set the cookie */
      //Set the cookie name and value
      document.cookie = cookieName + "=" + escape(cookieValue) +
      //Set the cookie expiration date
      ( (expDateGMT) ? ";expires=" + expDateGMT : "") +
      //Set the cookie valid path
      ( (cookiePath) ? ";path=" + cookiePath : "") +
      //Set the valid cookie domain
      ( (cookieDomain) ? ";domain=" + cookieDomain : "") +
      //Set Boolean
      ( (cookieSecure) ? ";secure" : "");
   }


   /*
   deleteCookie
   @param cookieName name of the cookie to delete */
   function deleteCookie (pCookieName)
   {
      setCookie (pCookieName,"",-1)
   }

   /*
   deleteCookieWithPath
   */
   function deleteCookieWithPath (pCookieName, pPath)
   {
      setCookie (pCookieName,"", -1, pPath);
   }


/*

  Javascript library to support pop-up windows

*/

   /**
      Pops up a window, with all functionality (menu, etc)
      @param pNewUrl
      @param pWindowName the name should not have spaces in it.  It is not the display name,
      but rather the internal name.
   */
   function openFullFunctionWindow(pNewUrl, pWindowName)
   {
      var width = screen.width * 3 / 4;
      var height = screen.height * 2 / 3;
      var left = screen.width - width - 20;
      var top = screen.height - height - 80;
      winprops = 'height=' + height + ',width=' + width + ',left=' + left +
                 ',top=' + top +
                 ',resizable=yes,scrollbars=yes,status=yes,toolbar=yes,location=yes,menubar=yes,directories=yes';
      popwin = window.open(pNewUrl, pWindowName, winprops);
      popwin.window.focus();

   }

/**
   Pops up a window, with no menu
   @param pNewUrl
   @param pWindowName the name should not have spaces in it.  It is not the display name,
   but rather the internal name.
*/
function openLimitedWindow(pNewUrl, pWindowName)
{
   var width = screen.width * 1/2;
   var height = screen.height * 3/4;
   var left = screen.width - width - 40;
   var top = 80;
   winprops = 'height=' + height + ',width=' + width + ',left=' + left +
              ',top=' + top +
              ',resizable=yes,scrollbars=yes,status=yes,toolbar=yes,location=no,menubar=no,directories=no';
   popwin = window.open(pNewUrl, pWindowName, winprops);
   popwin.window.focus();

}

/**
   Pops up a help window, with a fixed size window.  Used by HelpFileTag.java (<pe:helpfile>).
   @param pNewUrl
*/
function openHelpWindow(pNewUrl)
{
   var width = 500;
   var height = 500;
   var left = screen.width - width - 30;
   var top = 30;
   winprops = 'height=' + height + ',width=' + width + ',left=' + left +
              ',top=' + top +
              ',resizable=yes,scrollbars=yes,status=no,toolbar=no,location=no,menubar=no,directories=no';
   newWindow = window.open(pNewUrl, 'ParticipateHelp', winprops);
   // Make sure the window comes to the front, in case it was behind something else
   newWindow.focus();

}

function openLMSCourse(pNewUrl, pFrame, pPrincipal)
{
   // open the course
   pFrame.location.href = pNewUrl;
	callJSCreateLink(pFrame.name);

   // log the opening of the course
   // elementType 62 is a scorm element
   // elementId is the Id for LMS Course
   var loggingUri = "/logging/action?elementId=186&elementTypeId=62&logActionEnumId=17&principalId=" + pPrincipal;
   loadBlindUri(loggingUri)
}

/*
   executes the specified URI, with no expectation of doing anything upon sucess or failure
   @param pUri the URI to load
*/
function loadBlindUri(pUri)
{
   var callback = {success: function success() {}, failure: function failure() {}, argument: []};
   if (!isLoggedOutAvoidVisitor())
   {
      //alert("about to call uri=" + pUri);
      var transaction = YAHOO.util.Connect.asyncRequest('GET', pUri, callback, null);
   }
   else
   {
      //alert("NOT about to call uri=" + pUri);
   }
}

function callJSCreateLink(pFrameName)
{
	if(!window.frames[pFrameName].JSCreateLink)
	{
		setTimeout("callJSCreateLink('"+pFrameName+"')", 500);
	}
	else
	{
		window.frames[pFrameName].JSCreateLink();
	}
}
