//----------------------------------------------------------------
//  Group DCA Common Javascript functions
//  Copyright © 2003 Group DCA
//
//  Last Update:
//		-> JH, 7/25/2003, Added validation functions for registration forms.
//						  Added swap image functions that are common to each site.
//		-> JH, 6/27/2003, Added goURL param to logOffSite() function
//		-> JH, 6/26/2003, Initial release
//      -> GB, 11/13/03 Added two new functions for customizing the internal home pages
//      -> AA, 01/26/06 Made changes in CheckLogin for update form btn and change to DeleteCookie..included path parameter
//                      which was missing..this fixes the issue signing out
//----------------------------------------------------------------

//----------------------------------------------------------------
// Notes:
//	1. Optional parameters are enclosed in brackets->[optional_param]
//----------------------------------------------------------------

//----------------------------------------------------------------
// Registration Validation
//----------------------------------------------------------------
var iValidatingElement = -1;

function iValidation(sType, fMinimum, fMaximum, iLength, iForm, iElement, sElementName)
{
	var NumericValue;
	var AtSignIndex;
	var PeriodIndex;

	if (
		iValidatingElement != iElement
        && iValidatingElement != -1
       )
		return false;

	iValidatingElement = iElement;

	if (sType.indexOf('Required') >= 0)
	{
		if (
	        document.forms[iForm].elements[iElement].value == null
            ||
	        document.forms[iForm].elements[iElement].value == ""
	        ||
	        document.forms[iForm].elements[iElement].value == " "
	       )

		{
			alert("Required Field");
			document.forms[iForm].elements[iElement].focus();
			return false;
		}
	}

	if (
        sType.indexOf('E-Mail') >= 0
        && document.forms[iForm].elements[iElement].value != ""
       )
	{
		AtSignIndex = document.forms[iForm].elements[iElement].value.indexOf('@');
		if (
	        AtSignIndex <= 0
	        ||
	        AtSignIndex == document.forms[iForm].elements[iElement].value.length - 1
	       )
		{
			alert("Invalid E-Mail Address");
			document.forms[iForm].elements[iElement].focus();
			return false;
		}
	}

	if (
        sType.indexOf('Number') >= 0
        && document.forms[iForm].elements[iElement].value != ""
       )
	{
		if (isNaN(document.forms[iForm].elements[iElement].value))
		{
			alert("Invalid Number");
			document.forms[iForm].elements[iElement].focus();
			return false;
		}
	}

	if (
        sType.indexOf('Integer') >= 0
        && document.forms[iForm].elements[iElement].value != ""
       )
	{
		PeriodIndex = document.forms[iForm].elements[iElement].value.indexOf('.');
		if (PeriodIndex >= 0)
		{
			alert("Field Cannot Contain a Decimal Point");
			document.forms[iForm].elements[iElement].focus();
			return false;
		}
	}

	if (
        sType.indexOf('Minimum') >= 0
        && document.forms[iForm].elements[iElement].value != ""
       )
	{
		NumericValue = parseFloat(document.forms[iForm].elements[iElement].value);
		if (NumericValue < fMinimum)
		{
			alert("Number Must be Greater Than or Equal to " + fMinimum);
			document.forms[iForm].elements[iElement].focus();
			return false;
		}
	}

	if (
        sType.indexOf('Maximum') >= 0
        && document.forms[iForm].elements[iElement].value != ""
       )
	{
		NumericValue = parseFloat(document.forms[iForm].elements[iElement].value);
		if (NumericValue > fMaximum)
		{
			alert("Number Must be a Number Less Than or Equal to " + fMaximum);
			document.forms[iForm].elements[iElement].focus();
			return false;
		}
	}

	if (
        sType.indexOf('Length') >= 0
        && document.forms[iForm].elements[iElement].value != ""
       )
	{
		if (document.forms[iForm].elements[iElement].value.length < iLength)
		{
			alert("Field Must have a Length Greater Than or Equal to " + iLength);
			document.forms[iForm].elements[iElement].focus();
			return false;
		}
	}

	iValidatingElement = -1;
}

function iDEACheck(iLength, iForm, iElement) { if ( iValidatingElement != iElement
        && iValidatingElement != -1
       )
		return false;

	iValidatingElement = iElement;

	if (!document.forms[iForm].elements[iElement].checked  && 
	document.forms[iForm].elements[iElement-1].value == ""
		)
	{
		alert("DEA Number must be entered or the DEA Number Not Issued checked "  );
		document.forms[iForm].elements[iElement-1].focus();
		iValidatingElement = -1;
		return false;
	}


	iValidatingElement = -1;
}
function checkEmail(iForm, iElement) {
		iValidatingElement = iElement;

        var str=document.forms[iForm].elements[iElement].value;

	    var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid email address. Please"
	                   +" check the location of the '@' sign."  );
		   document.forms[iForm].elements[iElement].focus();
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr-1 || str.substr(lstr-1,1)==dot) {
		   alert("Invalid email address. Please"
	                   +" check the location of the '.' (period character)."  );
		   document.forms[iForm].elements[iElement].focus();
		   return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		   alert("Invalid email address. Please"
	                   +" remove extra '@' signs."  );
		   document.forms[iForm].elements[iElement].focus();
		   return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		   alert("Invalid email address. Please"
	                   +" check location of period character."  );
		   document.forms[iForm].elements[iElement].focus();
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		   alert("Invalid email address. Please"
	                   +" enter period character after '@' sign."  );
		   document.forms[iForm].elements[iElement].focus();
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		   alert("Invalid email address. Please"
	                   +" remove any spaces."  );
		   document.forms[iForm].elements[iElement].focus();
		    return false
		 }

	iValidatingElement = -1;
}

function iPacCodeCheck(iLength, iForm, iElement)
{
	if (
		iValidatingElement != iElement
        && iValidatingElement != -1
       )
		return false;

		PeriodIndex = document.forms[iForm].elements[iElement].value.indexOf("_");
		if (PeriodIndex == 0)
		{
			return true;
		}
	
	iValidatingElement = iElement;

		if (
	        document.forms[iForm].elements[iElement].value == null
            ||
	        document.forms[iForm].elements[iElement].value == ""
	        ||
	        document.forms[iForm].elements[iElement].value == " "
	       )
		{
		return true;
		}
	if (document.forms[iForm].elements[iElement].value.length > iLength)
	{
		alert("Field Must have a Length Less Than or Equal to " + iLength);
		document.forms[iForm].elements[iElement].focus();
		return false;
	}
	iValidatingElement = -1;
}

function iPasswordCheck(iLength, iForm, iElement)
{
	if (
		iValidatingElement != iElement
        && iValidatingElement != -1
       )
		return false;

	iValidatingElement = iElement;

	if (document.forms[iForm].elements[iElement].value.length < iLength)
	{
		alert("Field Must have a Length Greater Than or Equal to " + iLength);
		document.forms[iForm].elements[iElement].focus();
		return false;
	}

	if (document.forms[iForm].elements[iElement].value == document.forms[iForm].elements[iElement - 1].value)
	{
		alert("User Password Must Not Be the Same as User Login");
		document.forms[iForm].elements[iElement].focus();
		return false;
	}

	iValidatingElement = -1;
}

function iPasswordConfirmCheck(iLength, iForm, iElement)
{
	if (
		iValidatingElement != iElement
        && iValidatingElement != -1
       )
		return false;

	iValidatingElement = iElement;

	if (document.forms[iForm].elements[iElement].value.length < iLength)
	{
		alert("Field Must have a Length Greater Than or Equal to " + iLength);
		document.forms[iForm].elements[iElement].focus();
		return false;
	}
/*
	if (document.forms[iForm].elements[iElement].value != document.forms[iForm].elements[iElement - 1].value)
	{
		alert("User Password Must Be the Same as User Password Confirm");
		document.forms[iForm].elements[iElement].focus();
		return false;
	}
*/
	iValidatingElement = -1;
}

//----------------------------------------------------------------
// Submit form
//----------------------------------------------------------------
function iSubmit(iForm)
{
	document.forms[iForm].submit();
	return false;
}

//----------------------------------------------------------------
// Image Swap functions
//----------------------------------------------------------------
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//----------------------------------------------------------------
// General Use Functions
//----------------------------------------------------------------

//----------------------------------------------------------------
//	logOffSite([goURL])
//
//	Deletes the session_id ending the user's current session 
//	(effectively logging them off the website).
//		goURL - optional parameter indicating a URL to open.  This could
//			    be a fully qualified URL or a relative URL (e.g. '/')
//  
//----------------------------------------------------------------
function logOffSite(goURL) {
	DeleteCookie ("session_id")
	if (logOffSite.arguments.length == 1)
		self.location.href =  goURL;
}

//----------------------------------------------------------------
// String Functions
//----------------------------------------------------------------

//----------------------------------------------------------------
//	indexOf(aString, searchString [, startFrom])
//    returns the first index of the searchString or -1 if it doesn't exist
//----------------------------------------------------------------
function indexOf(aString, searchString, startFrom) {
	if (indexOf.arguments.length < 1) return -1
	if (indexOf.arguments.length < 2) return -1
	if (indexOf.arguments.length < 3) startFrom = 0
	if (!((startFrom >= 0) && (startFrom < aString.length)))
      return -1
    return aString.indexOf(searchString, startFrom)
}

//----------------------------------------------------------------
//	lastIndexOf(aString, searchString [, startFrom])
//	  returns the last index of the searchString or -1 if it doesn't exist
//----------------------------------------------------------------
function lastIndexOf(aString, searchString, startFrom) {
	if (lastIndexOf.arguments.length < 1) return -1
	if (lastIndexOf.arguments.length < 2) return -1
    if (lastIndexOf.arguments.length < 3) startFrom = 0
	if (!((startFrom >= 0) && (startFrom < aString.length)))
      return -1
    return aString.lastIndexOf(searchString, startFrom)
}

//----------------------------------------------------------------
// Cookie Functions
//----------------------------------------------------------------

//----------------------------------------------------------------
//  SetCookie (name, value [, expires] [, path] [, domain] [, secure])
//
//  Creates or updates a cookie.
//	  name  - String object containing the cookie name.
//    value - String object containing the cookie value.  May contain
//      any valid string characters.
//    [expires] - Date object containing the expiration data of the cookie.  If
//      omitted or null, the  cookie expires at the end of the current session.
//    [path] - String object indicating the path for which the cookie is valid.
//      If omitted or null, uses the path of the calling document.
//    [domain] - String object indicating the domain for which the cookie is
//      valid.  If omitted or null, uses the domain of the calling document.
//    [secure] - Boolean (true/false) value indicating whether cookie transmission
//      requires a secure channel (HTTPS).  
//
//  The first two parameters are required.  The others, if supplied, must
//  be passed in the order listed above.  To omit an unused optional field,
//  use null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//      SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you would code:
//
//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
//----------------------------------------------------------------
function SetCookie (name, value) {
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
		((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
		((path == null) ? "" : ("; path=" + path)) +
		((domain == null) ? "" : ("; domain=" + domain)) +
		((secure == true) ? "; secure" : "");
}

//----------------------------------------------------------------
// GetCookie (name)
//
// Returns the value of the cookie specified by "name", or null if
// the cookie does not exist.
//	  name - String object containing the cookie name.
//----------------------------------------------------------------
function GetCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break; 
	}
	return null;
}

//----------------------------------------------------------------
// getCookieVal (offset)
//	
// Returns the actual value of the cookie found by GetCookie()
//----------------------------------------------------------------
function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

//----------------------------------------------------------------
// DeleteCookie (name)
//
// Delete a cookie. (Sets expiration date to current date/time)
//    name - String object containing the cookie name
//----------------------------------------------------------------
function DeleteCookie (name) {
	var exp = new Date(1997, 5, 5);
//	exp.setTime (exp.getTime() - 1);
	var cval = GetCookie (name);
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString() + "; path=/";
}

//----------------------------------------------------------------
// CheckLogin (site, calledfrom)
//
// This determines if a user is logged in by checking for the session cookie.
// If it's set, the doc's last name is then retrieved from the 'ln' cookie.
//If logged in already, the login/password entry fields are replaced with
//custom controls to perform functions against their account/profile    
// The parameters are:
//		site - valid DCA site variable (iex, dca, gtails, psr)
//		calledfrom - either 'cgi' or 'html' depending on whether its
//				called directly from an html page or from a page built via cgi-bin
//----------------------------------------------------------------

function CheckLogin(site,calledfrom) {
    var lname="";
    var sid="";
    var slash="'/'";
    var bslash="'../'";
if (document.URL.indexOf('psrdev') >= 0
                || document.URL.indexOf('gtailsdev') >= 0
                || document.URL.indexOf('iexdev') >= 0)
        {
                var linkToUse = "dcadev";
                var pageid="133,198041";
        }
        else
        {
                var linkToUse = "groupdca";
                var pageid="74,192104";
        }

    lname = GetCookie("ln");
    sid = GetCookie("session_id");
    if (sid == null)
    {
	   if (calledfrom == "html")
       {
          document.write('<img src="images/h_username.gif" alt="Username" width="57" height="15"><br>');
          document.write('<input type="text" name="login" size="12" maxlength="80"><br>');
          document.write('<img src="images/h_password.gif" alt="Password" width="54" height="15"><br>');
          document.write('<input type="password" name="password" size="12" maxlength="12"><br>');
          document.write('<img src="images/h_pac.gif" alt="Survey ID" width="64" height="15"><br>');
          document.write('<input type="promo" name="promo" size="12" maxlength="30">');
          document.write('<br><br>');
          document.write('<input name="submit" type="image" src="images/bn_login.gif" alt="Login" width="65" height="21" border="0">');
	   }
	   else
	   {
	      document.write('<img src="../images/h_username.gif" alt="Username" width="57" height="15"><br>');
          document.write('<input type="text" name="login" size="12" maxlength="80"><br>');
          document.write('<img src="../images/h_password.gif" alt="Password" width="54" height="15"><br>');
          document.write('<input type="password" name="password" size="12" maxlength="12">');
          document.write('<img src="../images/h_pac.gif" alt="Survey ID" width="64" height="15"><br>');
          document.write('<input type="promo" name="promo" size="12" maxlength="30">');
          document.write('<br><br>');
          document.write('<input name="submit" type="image" src="../images/bn_login.gif" alt="Login" width="65" height="21" border="0">');
	   }
    }
    else
    {
	   document.write('<p><font color="#FFFFFF" size="3" face="Verdana, Arial, Helvetica, sans-serif"><strong><br>'); 

	   if (lname == null)
	   {
	      document.write('Welcome Doctor<br><br>');
	   }
	   else
	   {
	      document.write('Welcome <br>');
	      document.write('Dr. ' + lname + '<br>');
	   }
	   if (calledfrom == "html")
	   {
	      document.write('<form name="form1" method="post" action="../cgi-bin/oraactl_psr.wrp"><br>');
		  document.write('<input type="hidden" name="site" value="' + site + '">');
		  document.write('<input type="image" src="images/bn_account.gif" border="0" align="left" ></form>');
		 document.write('<br><form name="form112" method="post" action="http://s8a.' + linkToUse + '.com/portal/page">');
                  document.write('<input type="hidden" name="_pageid" value="' + pageid + '">');
                  document.write('<input type="hidden" name="_dad" value="portal">');
                  document.write('<input type="hidden" name="site" value="' + site + '">');
                  document.write('<input type="hidden" name="_schema" value="PORTAL">');
                  document.write('<input type="hidden" name="session_id" value="' + sid + '">');
     document.write('<a href="javascript:document.form112.submit()"><img src="images/bn_profile.gif" border="0" align="left"></a></form><br>');
 document.write('<a href="javascript:logOffSite(' + slash + ')"><img src="images/bn_signout.gif" border="0" align="left"></a>');

	   }
	   else
	   {
 	      document.write('<table><form name="form1" method="post" action="../cgi-bin/oraactl_psr.wrp"><br>');
		  document.write('<input type="hidden" name="site" value="' + site + '">');
		  document.write('<input type="image" src="../images/bn_account.gif" border="0" align="left"></form>');

		    document.write('<br><form name="form112" method="post" action="http://s8a.' + linkToUse + '.com/portal/page">');
                  document.write('<input type="hidden" name="_pageid" value="'+ pageid +  '">');
                  document.write('<input type="hidden" name="_dad" value="portal">');
                  document.write('<input type="hidden" name="_schema" value="PORTAL">');
                  document.write('<input type="hidden" name="site" value="' + site + '">');
                  document.write('<input type="hidden" name="session_id" value="' + sid + '">');
 document.write('<a href="javascript:document.form112.submit()"><img src="../images/bn_profile.gif" border="0" align="left"></a></form><br>');
          document.write('<a href="javascript:logOffSite(' + bslash + ')"><img src="../images/bn_signout.gif" border="0" align="left"></a></table>');
	   }
    }
}

function CheckDisplayTabs(site,calledfrom) {
    var lname="";
    var sid="";
    var slash="'/'";
    var bslash="'../'";
	var image41="'Image41','','images/main/menu_b_on.gif'";
	var image41pre="'Image41','','images/main/menu_b_pre_on.gif'";
	var image51="'Image51','','images/main/menu_c_on.gif'";
	var image51bs="'Image51','','../images/main/menu_c_on.gif'";


    sid = GetCookie("session_id");
    if (sid == null)
    {
	   if (calledfrom == "html")
	   {	
          document.write('<td><a href="join.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage(' + image41pre + ',1)">');
          document.write('<img src="images/main/menu_b_pre_off.gif" alt="Join Our g-Team" name="Image41" width="108" height="18" border="0" id="Image41"></a></td>');
          document.write('<td><a href="rewards.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage(' + image51 + ',1)">');
          document.write('<img src="images/main/menu_c_off.gif" alt="g-team Rewards" name="Image51" width="110" height="18" border="0" id="Image51"></a></td>');
	   }
	   else
	   {
          document.write('<td><a href="../join.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage(../' + image41pre + ',1)">');
          document.write('<img src="../images/main/menu_b_pre_off.gif" alt="Join Our g-Team" name="Image41" width="108" height="18" border="0" id="Image41"></a></td>');
          document.write('<td><a href="../rewards.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage(../' + image51 + ',1)">');
          document.write('<img src="../images/main/menu_c_off.gif" alt="g-team Rewards" name="Image51" width="110" height="18" border="0" id="Image51"></a></td>');
	   }	
    }
    else
    {
	   if (calledfrom == "html")
	   {
	      document.write('<td><form name="form5" method="post" action="../cgi-bin/oraactl_psr.wrp">');
		  document.write('<input type="hidden" name="site" value="' + site + '">');
		  document.write('<input type="image" src="images/main/menu_b_off.gif" align="right" border="0"></form></td>');
          document.write('<td><a href="http://s3a.dcadev.com/pls/portal30/studiodev.dyn_newthumb_rpt.show?p_arg_names=practid&p_arg_values=' + sid + '&p_arg_names=pointid&p_arg_values=999&p_arg_names=rewards&p_arg_values=T" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage(' + image51bs + ',1)">');
          document.write('<img src="images/main/menu_c_off.gif" alt="g-team Rewards" name="Image51" width="110" height="18" border="0" id="Image51"></a></td>');
	   }
	   else
	   {
	      document.write('<td><form name="form5" method="post" action="../cgi-bin/oraactl_psr.wrp">');
		  document.write('<input type="hidden" name="site" value="' + site + '">');
		  document.write('<input type="image" src="../images/main/menu_b_off.gif" align="right" border="0"></form></td>');
          document.write('<td><a href="http://s3a.dcadev.com/pls/portal30/studiodev.dyn_newthumb_rpt.show?p_arg_names=practid&p_arg_values=' + sid + '&p_arg_names=pointid&p_arg_values=999&p_arg_names=rewards&p_arg_values=T" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage(' + image51bs + ',1)">');
          document.write('<img src="../images/main/menu_c_off.gif" alt="g-team Rewards" name="Image51" width="110" height="18" border="0" id="Image51"></a></td>');
	   }
    }
}
