//------------------------------------------------------------------
// File: /include/js/general.js
// Desc: Utility functions  
// $Revision: 2$
// $Date: 02/16/2007 4:23:12 PM$
// $Author: Amy Love$
//------------------------------------------------------------------

window.onerror = GEN_ErrorHandler;
function GEN_ErrorHandler(sMsg,sUrl,sLine) {
    var c = GEN_ErrorHandler.caller;
    if (c === null) { c = "[none]" ; }
    GEN_load(1, 'url', sUrl, 'line', sLine, 'msg', sMsg, 'caller', c);
    return true;
}

function GEN_noErrorHandler() {
    return true;
}

function GEN_load(act) {
    if (document.images) {
        var qs = 'act=' + act;
        for (var i = 1; i < arguments.length - 1; i += 2) {
		  qs += '&' + arguments[i] + '=' + escape(arguments[i+1]) ;
        }
        var i1 = new Image();
        i1.src = "/~r.asp?" + qs;
    }
}

function GEN_P_keepalive() {
    GEN_load(0);
    setTimeout("GEN_P_keepalive()", 900000);
}

var GEN_P_oWindowOpenWin;

function GEN_P_windowOpenErrorHandler() {
    GEN_load(3, "b", 1, "url", GEN_P_windowOpenErrorHandler.caller.arguments[0]);
    // location = GEN_P_windowOpenErrorHandler.caller.arguments[0]
    return true;
}

function GEN_windowOpen(url, name, props) {
    var _saverr = window.onerror;
    window.onerror = GEN_P_windowOpenErrorHandler;
    var _win = window.open(url, name, props);
    var _dummy = _win.opener;
    if (typeof(_dummy) != "object") { 
        GEN_load(3, "b", "1", "url", url);
        //location = url;
        return true;
    }
    GEN_P_oWindowOpenWin = _win;
    setTimeout("GEN_P_testPopupOpen('" + url + "')", 1500);
    window.onerror = _saverr;
    return _win;
}

function GEN_P_testPopupOpen(url) {
    var _saverr = window.onerror;
    window.onerror = GEN_P_windowOpenErrorHandler;
    if (typeof(GEN_P_oWindowOpenWin) != "object") { 
        GEN_load(3, "b", "1", "url", url);
        // location = url ;
        return;
    } else {
        if (GEN_P_oWindowOpenWin.closed) {
            GEN_load(3, "b", "1", "url", url); 
            // location = url ;
            return;
        }
    }
    GEN_load(3, "b", "0", "url", url); 
    window.onerror = _saverr;
}     

function GEN_P_GetKeyCode(evt) {
    if (evt.keyCode) {
        return evt.keyCode;
    } else if (evt.which) {
	  return evt.which;
    } else {
       return 0;
    }
}

function GEN_NumericKeyPress(evt) {
	var iKeyCode = GEN_P_GetKeyCode(evt);
    if ((iKeyCode > 31 && iKeyCode < 48) || iKeyCode > 57) {
        return false;
    } 
}

function GEN_AutoTab(evt, iMaxLen, fldCurr, fldNext, iIndex) {
    if (fldCurr.value.length >= iMaxLen) {
        if (GEN_P_GetKeyCode(evt)> 47)  {
            if (!fldNext.focus) { 
			  if (!fldNext[iIndex] || !fldNext[iIndex].focus) { return; }
			  fldNext = fldNext[iIndex] ;
            }
            if (fldNext.focus) { fldNext.focus(); }
            if (fldNext.select) { fldNext.select(); }
        }
    }
}

function GEN_FieldError(fld, msg) {
    alert(msg);
    if (fld.focus) { fld.focus(); }
    if (fld.select) { fld.select(); }
    return false;
}

function GEN_swapImgRestore() {
  var i,x,a=document.GEN_sr; 
  for (i=0; a&&i<a.length && (x=a[i]) && x.oSrc; i++) { x.src=x.oSrc; }
}

function GEN_preloadImages() {
  var d=document; 
  if (d.images){ 
	if (!d.GEN_p) { d.GEN_p=new Array(); }
    var i, j=d.GEN_p.length, a=GEN_preloadImages.arguments; 
	for (i=0; i<a.length; i++) {
	  if (a[i].indexOf("#")!==0) { 
		d.GEN_p[j]=new Image; 
		d.GEN_p[j++].src=a[i];
	  }
	}
  }
}

function GEN_findObj(n, d) {
  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=GEN_findObj(n,d.layers[i].document); }
  if (!x && document.getElementById) { x=document.getElementById(n); }
  return x;
}

function GEN_swapImage() {
  var i,j=0,x,a=GEN_swapImage.arguments; 
  document.GEN_sr=new Array; 
  for (i=0; i<(a.length-2); i+=3) {
	if ((x=GEN_findObj(a[i]))!==null) { 
	  document.GEN_sr[j++]=x; 
	  if (!x.oSrc) { x.oSrc=x.src; }
	  x.src=a[i+2];
	}
  }
}

function GEN_ValidateAC34(frm) {
    if (frm.areacode.length) {
	  for (var i = 0; i < frm.areacode.length; i++) {
		if ( i === 0 || 
			 frm.areacode[i].value.length > 0 || 
			 frm.three[i].value.length > 0 || 
			 frm.four[i].value.length > 0) {
		  if (!GEN_ValidateSingleTN(frm.areacode[i], frm.three[i], frm.four[i])) {
			return false;
		  }
		}
	  }

	  if (arguments.length > 1 && 
		  arguments[1] && 
		  (frm.areacode[0].value != frm.areacode[1].value ||
		   frm.three[0].value != frm.three[1].value ||
		   frm.four[0].value != frm.four[1].value
		   )
		  ) {
		return GEN_FieldError( frm.areacode[0], "Both phone numbers must match." );
	  } 
	  return true;
    } 
	else {
	  return GEN_ValidateSingleTN(frm.areacode, frm.three, frm.four);
    }
}

function GEN_ValidateSingleTN(fAC, fThree, fFour) {
  if (!(parseInt("1" + fAC.value) > 999)) {
	return GEN_FieldError( fAC, "Please enter your 3-digit area code." );
  }
  if (!(parseInt("1" + fThree.value) > 999)) {
	return GEN_FieldError( fThree, "Please enter the first 3 digits of your phone number." );
  }
  if (!(parseInt("1" + fFour.value) > 9999)) {
	return GEN_FieldError( fFour, "Please enter the last 4 digits of your phone number." );
  }
  return true;
}

function GEN_ValidateP(frm) {
  if (!(parseInt("1" + frm.p.value.substring(0,5)) > 99999 && parseInt("1" + frm.p.value.substring(5,10)) > 99999)) {
	return GEN_FieldError( frm.p, "Please enter your 10-digit phone number." );
  }
  return true;
}

function GEN_ValidatePassword(frm) {
  if (frm.password.value.length === 0) {
	return GEN_FieldError( frm.password, "Please enter your password." );
  }
  return true;
}

function GEN_WizButton(sName) {
  document.write('<a href="javascript:');
  if (sName == "Next" || sName == "Finish") {
	document.write('if (!window.APP_WizValidate || APP_WizValidate(document.APP_fWiz))');
	document.APP_fWiz.APP_sWizNav.value = sName;
  }
  document.write('{document.APP_fWiz.APP_sWizNav.value = \'' + sName + 
				 '\'; document.APP_fWiz.submit()}" ' +
				 'onmousedown="document.images[\'APP_Wiz' + sName + '\'].src = \'/images/' + sName + 'Down.gif\'" ' +
				 'onmouseup="document.images[\'APP_Wiz' + sName + '\'].src = \'/images/' + sName + 'Up.gif\'" ' +
				 'onmouseout="onmouseup()"><img name="APP_Wiz' + sName + '" src="/images/' + sName + 'Up.gif" ' +
				 'height="22" width="72" border="0" alt="' + sName + '" /></a>');
  if (navigator.appName == "Netscape" && navigator.appVersion.charAt(0) < "5") {
	document.write("<span>");
  }
}

function GEN_ValidateEmail() {
  var sEmail1 = arguments[0].value;
  if (arguments.length == 2) {
	if (sEmail1 != arguments[1].value) {
	  return GEN_FieldError( arguments[0], "The two email addresses must match." );
	}
  }
  if (sEmail1.length === 0) {
	return GEN_FieldError( arguments[0], "Please enter a valid email address." );
  }
  if (sEmail1.length > 128) {
	return GEN_FieldError( arguments[0], "CallWave only supports email addresses shorter than 129 characters." );
  }
  if (!(/^(([^\x00-\x1F\x7F-\xFF <>()[\]\\.,;:@"]|\\[\x00-\x7F])+(\.([^\x00-\x1F\x7F-\xFF <>()[\]\\.,;:@"]|\\[\x00-\x7F])+)*|"([^\n\r\\"\x80-\xFF]|\\[\x00-\x7F])+")@[0-9A-Za-z][-0-9A-Za-z]*[0-9A-Za-z](\.[0-9A-Za-z][-0-9A-Za-z]*[0-9A-Za-z])+$/.test(sEmail1))) {
    return GEN_FieldError( arguments[0], "Please enter a valid email address." );
  }
  return true;
}

var GEN_sNonMZRollovers = 
        "\"/images/nav/home2Over.gif\", " +
        "\"/images/nav/members2Over.gif\", " +
        "\"/images/nav/help2Over.gif\"";

var GEN_sLegacyNonMZRollovers = 
        "\"/images/nav/homeOver.gif\", " +
        "\"/images/nav/aboutOver.gif\", " +
        "\"/images/nav/productsOver.gif\", " + 
        "\"/images/nav/membersOver.gif\", " +
        "\"/images/nav/sitemapOver.gif\", " +
        "\"/images/nav/helpOver.gif\"";

var GEN_sRolloverList = "";
var GEN_bDontMoveToFirst = false;
var GEN_bSubmitted = false;

function GEN_DocumentOnLoad() {
    var i, j, f, e, sOnsub;
    if (GEN_sRolloverList.length > 0) { 
        eval("GEN_preloadImages(" + GEN_sRolloverList + ")");
    }
    if (window.P_DocumentOnLoad) { 
        P_DocumentOnLoad();
    }
    // double-click avoidance code
    for (i=0; i < document.forms.length; i++) {
        f = document.forms[i];
        if (!f.target) {
            // save existing validation and use it if it exists
            if (typeof(f.onsubmit) != "function") {
                sOnsub = "true";
            } else {
                f.onSub = f.onsubmit;
                sOnsub = "this.onSub()";
            }
            // redefine onsubmit handler
            f.onsubmit = new Function("if (GEN_bSubmitted) {return false} else { GEN_trim(this); if (" + sOnsub + ") {GEN_bSubmitted = true; return true} else {return false}}");
        }
    }
    if (!GEN_bDontMoveToFirst) {
        for (i=0; i < document.forms.length; i++) {
            f = document.forms[i];
            for (j=0; j < f.length; j++) {
                e = f.elements[j];
                if (e.type && !e.disabled) {
                    if (e.type == "text") {
                        e.focus();
                        return;
                    }
                }
            }
        }
    }
}

function GEN_trim(f) {
    var e;
    for (var i=0; i < f.length; i++) {
        e = f.elements[i];
        if (e.type && e.type == "text") {
            e.value = /^\s*(\S*(\s+\S+)*)\s*$/.exec(e.value)[1];
        }
    }
}

/* Validation for /members/settings/terminate/ */

function TERM_checkOtherReason() {
    if (document.cancelform.otherreason.value === "") {
        alert("Please enter a reason before continuing.");
        document.cancelform.otherreason.focus();
        return false;
    }
}

function TERM_checkOtherService() {
    if (document.cancelform.otherservice.value === "") {
        alert("Please enter a reason before continuing.");
        document.cancelform.otherservice.focus();
        return false;
    }
}

function TERM_checkAOL() {
    if (document.cancelform.AOLCallAlert.value === "") {
        alert("Please enter a reason before continuing.");
        document.cancelform.AOLCallAlert.focus();
        return false;
    }
}

function TERM_checkContactForm() {
    if (document.contactform.problem.value === "") {
        alert("Please enter a problem before continuing.");
        document.contactform.problem.focus();
        return false;
    }
    if (document.contactform.address.value === "") {
        alert("Please enter a valid e-mail address before continuing.");
        document.contactform.address.focus();
        return false;
    }
    
    var symbol = document.contactform.address.value;
	var atpos = symbol.indexOf("@",1);
	var bad = ",;:/ ";

	for (x=0; x<bad.length; x++) {
			if (symbol.indexOf(bad.charAt(x)) != -1) {
				alert ("You have entered an invalid character or a space. Please check your e-mail address.");
				document.contactform.address.focus();
				document.contactform.address.select();
				return false;
			}
		}

		if (symbol.indexOf("@")==-1) {
			alert("Please enter a valid e-mail address. Be sure to include an '@' symbol and a '.'");
			document.contactform.address.focus();
			return false;
		}

		if (symbol.indexOf(".")==-1) {
			alert("Please enter a valid e-mail address. Be sure to include an '@' symbol and a '.'");
			document.contactform.address.focus();
			return false;
		}

		if (symbol.indexOf("@",atpos+1) != -1) {
			alert("Please enter only one e-mail address.");
			document.contactform.address.focus();
			return false;
		}
}


/***************************************************
Validate Get Password Page (/members/password/default.asp)
***************************************************/

function GEN_validPasswordEmail(email){
	var symbol = email.emailEntered.value;
	var atpos = symbol.indexOf("@",1);
	var bad = ",;:/ ";

	if (email.emailEntered.value === "") {
		alert("Please enter your email address.");
		email.emailEntered.focus();
		email.emailEntered.select();
		return false;
	}
	
	for (x=0; x<bad.length; x++) {
		if (symbol.indexOf(bad.charAt(x)) != -1) {
			alert ("You have entered an invalid character or a space. Please check your email address.");
			email.emailEntered.focus();
			email.emailEntered.select();
			return false;
		}
	}
	if (symbol.indexOf("@")==-1) {
		alert("Please enter a valid email address. Be sure to include an '@' symbol and a '.'");
		email.emailEntered.focus();
		return false;
	}
	if (symbol.indexOf(".")==-1) {
		alert("Please enter a valid email address. Be sure to include an '@' symbol and a '.'");
		email.emailEntered.focus();
		return false;
	}

	if (symbol.indexOf("@",atpos+1) != -1) {
		alert("Please enter only one email address.");
		email.emailEntered.focus();
		return false;
	}
	else {
		return true;
	}
}

/***************************************************
Validate Change Password Page (/members/password/changePass.asp)
***************************************************/
function GEN_changePassword(p) {
    var numbersOnly = "0123456789";
    var goodPassword = p.newPassword.value;
    
    if (p.newPassword.value === "") {
		alert("Please enter your desired password.");
		p.newPassword.focus();
		return false;
	}
    if (p.newPassword.value.length < 4) {
        alert("Your new password must be at least 4 digits.");
        p.newPassword.focus();
        return false;
    }
    for (var i=0; i < goodPassword.length; i++) {
	temp = "" + goodPassword.substring(i, i+1);
		if (numbersOnly.indexOf(temp) == -1) {
			alert("Invalid characters in your password. Please enter numbers only.");
			return false;
		}
	}
    if (p.confirmPassword.value === "") {
		alert("Please confirm your password.");
		p.confirmPassword.focus();
		return false;
	}
    if (p.newPassword.value != p.confirmPassword.value){
        alert("Your passwords do not match. Please re-enter your passwords.");
        p.newPassword.focus();
        p.newPassword.select();
        return false;
    }
    if (p.accessArea.value === ""){
        alert("Please enter a reason before continuing.");
        p.accessArea.focus();
        return false;
    }
    return true;
}

/***************************************************
Validate Need Password Page (/members/password/needPassword.asp)
***************************************************/

function GEN_validateNeedPassword(){
    if (document.needform.nameEntered.value === "") {
        alert("Please enter your name.");
        document.needform.nameEntered.focus();
        return false;
    }
    if ( (!(document.needform.elements[1].checked)) && 
         (!(document.needform.elements[2].checked)) &&
         (!(document.needform.elements[3].checked)) ){
            alert("Please indicate why you need your password.");
            return false;
    }
    return true;
}

/*
Validates Address capture form for MIC Invoice
*/
function verifyAddressCapture(oForm)
    {
        if (oForm.address1.value === "")
        {
            return GEN_FieldError(oForm.address1, "Please enter a street address.");
        }
        // 4 future -- FYI address2 can be null, no error checking required
        if (oForm.city.value === "")
        {
            return GEN_FieldError(oForm.city, "Please enter a city.");
        }
        if (oForm.state.selectedIndex === 0)
        {
            return GEN_FieldError(oForm.state, "Please select a state.");
        }
        var bResult = /^\d{5}(\-?\d{4})?$/.test(oForm.zip.value);
        if (bResult === false)
        {
            return GEN_FieldError(oForm.zip, "Please enter a valid zip code.");
        }
    }
    
/*
Opens a child window: used principally from Download Abandon Reduction files
*/
var newchildwin;
var childcreatetime = null;
var ssPath;

function GEN_openChildWindow(HTMLPage) {
    var onErrorSave = window.onerror;
    window.onerror = GEN_P_blockerErrorHandler;
    newchildwin = GEN_windowOpen(HTMLPage,'childWin','height=300,width=500,top=0,left=0');
    window.onerror = onErrorSave;
    childcreatetime=new Date();
}

function GEN_P_blockerErrorHandler(sMsg,sUrl,sLine) {
    if (ssPath) {
        location.href = ssPath;
    } else {
        childcreatetime=new Date();
        newchildwin = new Object();
        newchildwin.closed = true;
    }
    return true;
}

/*
This function is used to cope with pop-up stopper programs. If the user chooses to
download our software, a child window appears - first the control check window and then
the download window. But if a pop-up stopper is lurking in the wings, the child window
will appear and disappear quickly. This function will be invoked to check for that condition
by monitoring the condition every quarter-second (250 milliseconds) and redirect the user to 
the standard download page if it occurs.

NOTE that the user can close the child window after the download has been completed. When
that happens, this code must be disabled. I'm using a time interval to determine this. If the
window is destroyed less than (say) 2 seconds after it was created, assume it was destroyed by
a pop-up stopper and perform the location.href statement.

Late update. Certain popup killers appear to disable parts of this java code. The child window
handle remains valid but newchildwin.closed is not true. The error condition is triggered when 
location.length is used and causes a redirect statement to be executed.
*/

function GEN_isTheWindowThere(sPath)
{
   if (newchildwin)
   {
       ssPath = sPath;
       var onErrorSave = window.onerror;
       window.onerror = GEN_P_blockerErrorHandler;
       if (newchildwin.closed)
       {
           window.onerror = onErrorSave;
           var childdestroytime = new Date();
           if (childdestroytime-childcreatetime < 2000)  // difference in milliseconds
           {
               location.href = sPath;
           }
       }
       else
       {
           if (newchildwin.location)
           {
               if (newchildwin.location.length === 0)
               {
                   location.href = sPath;
               }
           }
           else
           {
               location.href = sPath;
           }
       }
       window.onerror = onErrorSave;
   }
   var sParam = "GEN_isTheWindowThere('" + sPath + "')" ;
   setTimeout (sParam, 250);
}


/* NPL Learn More widnows */
function GEN_openLearnMoreWindow(sId, iWindowHeight) {
    var topLocation = 0;
    var leftLocation = 0;
    newWin = GEN_windowOpen('/members/order/learnMoreWindow.asp?id=' + sId + ' ','','height=' + iWindowHeight + ',width=450,scrollbars=0,top=' + topLocation + ',left=' + leftLocation);
}
        
function GEN_openTempWindow(sId, sTN, sFN) {
    var topLocation = 0;
    var leftLocation = 0;
    //alert("sId: " + sId + " sTN: " + sTN + " sFN: " + sFN);
    newWin = GEN_windowOpen('/members/order/learnMoreWindow.asp?id=' + sId + '&tn=' + sTN + '&tfn=' + sFN + '','newWin','height=300,width=300,top=' + topLocation + ',left=' + leftLocation);
}       

/*  requires a bgsound id="music" tag on the page */ 
function GEN_PlayMusic( fileName ) {

    if (document.all) { // IE only...
        document.all.music.src = fileName;
        return false;
    }
    return true;
    
}
