// JavaScript Document: common.js

<!--

if (self != top) { // we are in a frame!
   if( document.domain.match( /dradibfar/ ) ||
       document.domain.match( /centrepayment.com/ ) ||
       document.domain.match( /centerps.bongo4u.com/ ) ||

       document.domain.match( /help.bongo4u.com/ ) ) {
   // the above sites use frames, so allow frames on those sites
   }
   else {
      var ignore_frame		= false;
      var cookies_string	= document.cookie;
      if (cookies_string.length > 0) {
         var cookies_array	= cookies_string.split("; ");
         for (i in cookies_array) {
            var this_cookie	= cookies_array[i];
            var name_and_value	= this_cookie.split("=");
            var this_name	= name_and_value[0];
            var this_value	= name_and_value[1];
            if (this_name == 'backend_username' && this_value && this_value != 'x') {
               ignore_frame	= true;
            }
         }
      }
      if (!ignore_frame) {
         top.location.href=window.location.href; // kick it out of the frame!
      }
   }
}
  
/* Functions that swap images. */
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];
      }
}

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;
}

/* Functions that handle preload. */
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) { //v4.01
   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);
   if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v3.0
   var i,p,v,obj,args=MM_showHideLayers.arguments;
   for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) {
      v=args[i+2];
      if (obj.style) {
         obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v;
      }
      obj.visibility=v;
   }
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
   window.open(theURL,winName,features);
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
   if (init==true) with (navigator) {
      if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
         document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage;
      }
      }
   else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_changeProp(objName,x,theProp,theValue) { //v6.0
   var obj = MM_findObj(objName);
   if (obj && (theProp.indexOf("style.")==-1 || obj.style)){
      if (theValue == true || theValue == false)
         eval("obj."+theProp+"="+theValue);
      else eval("obj."+theProp+"='"+theValue+"'");
   }
}

var e2_already_clicked = false;
function only_click_once( submit_button ) {
   if( e2_already_clicked == true ) {
      alert( "Your request is in progress..." );
      return false;
   }
   else{
      e2_already_clicked = true;
      return true;
   }
}

function e2_maxlength_alert( given_textarea, given_maxlength ) {
   if( given_textarea.value.length > given_maxlength ) {
      alert( 'This field has a maximum length of ' + given_maxlength + '.' );
      given_textarea.value = given_textarea.value.substring( 0, given_maxlength );
   }
}

function MM_reloadPage(init) {  //reloads the window if IE resized
   if (init==true) with (navigator) {
      if ((appName=="MSIE")) {
         document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage;
      }
      }
   else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);


function MM_jumpMenu(targ,selObj,restore){ //v3.0
   eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
   if (restore) selObj.selectedIndex=0;
}


function b4u_open_activitylog_window( req_page ){
   var tmpwidth = (screen.availWidth - 20);
   var tmpheight = parseInt(screen.availHeight * .9);
   if ( tmpwidth < 100 ) {
      tmpwidth = (screen.width - 20);
   }
   if ( tmpheight < 100 ) {
      tmpheight = parseInt(screen.height * .9);
   }
   if ( tmpwidth < 100 ) {
      tmpwidth = 760;
   }
   if ( tmpheight < 100 ) {
      tmpheight = 540;
   }
   if ( tmpwidth > 1000 ) {
      tmpwidth = 1000;
   }
   if ( tmpheight > 1000 ) {
      tmpheight = 1000;
   }
   features = 'width=' + tmpwidth + ',height=' + tmpheight + ',top=1,left=2,' + 'toolbar=no,scrollbars=yes,location=no,status=yes,menubar=no,resizable=yes';
   if( req_page=='' ) {
      url = '/bongo4u/activitylog/';
   } else {
      url = '/bongo4u/activitylog/?PID='+req_page;
   }
   window_name	= 'b4u_activitylog_window';
   result = window.open(url,window_name,features);
   result.focus();
}

function b4u_open_user_activitylog_window(){
   var tmpwidth = (screen.availWidth - 20);
   var tmpheight = parseInt(screen.availHeight * .9);
   if ( tmpwidth < 100 ) {
      tmpwidth = (screen.width - 20);
   }
   if ( tmpheight < 100 ) {
      tmpheight = parseInt(screen.height * .9);
   }
   if ( tmpwidth < 100 ) {
      tmpwidth = 760;
   }
   if ( tmpheight < 100 ) {
      tmpheight = 540;
   }
   if ( tmpwidth > 1000 ) {
      tmpwidth = 1000;
   }
   if ( tmpheight > 1000 ) {
      tmpheight = 1000;
   }
   features = 'width=' + tmpwidth + ',height=' + tmpheight + ',top=1,left=2,' + 'toolbar=no,scrollbars=yes,location=no,status=yes,menubar=no,resizable=yes';
   url = '/bongo4u/activitylog/?log_type=1';
   window_name	= 'b4u_user_activitylog_window';
   result = window.open(url,window_name,features);
   result.focus();
}


function b4u_open_enhancements_window(){
   var tmpwidth = (screen.availWidth - 100);
   var tmpheight = parseInt(screen.availHeight * .8);
   if ( tmpwidth < 100 ) {
      tmpwidth = (screen.width - 100);
   }
   if ( tmpheight < 100 ) {
      tmpheight = parseInt(screen.height * .8);
   }
   if ( tmpwidth < 100 ) {
      tmpwidth = 700;
   }
   if ( tmpheight < 100 ) {
      tmpheight = 500;
   }
   if ( tmpwidth > 1000 ) {
      tmpwidth = 1000;
   }
   if ( tmpheight > 1000 ) {
      tmpheight = 1000;
   }
   features = 'width=' + tmpwidth + ',height=' + tmpheight + ',top=20,left=30,' + 'toolbar=no,scrollbars=yes,location=no,status=yes,menubar=no,resizable=yes';
   url = '/bongo4u/enhancements/';
   window_name	= 'b4u_enhancements_window';
   result = window.open(url,window_name,features);
   result.focus();
}


//  The following functions will hide or show the passed tag's area
//
//  e2_tag_hide			Hide the tag
//  e2_tag_show			Show the tag
//  e2_tag_hide_and_show	Hide the first tag, Show the second tag
//  e2_tag_hide_show_toggle	Toggle the tag to the other Hide/Show setting
//
//  See each function below for its required arguments.
//
//  To show or toggle a tag, pass the tag's ID and CLASS names (tag needs to have both).
//  To hide a tag, pass the tag's ID name.

function e2_tag_hide(elm){
   var item = document.getElementById(elm);
   var hide = 'noDisplay';
   if(item){
      item.className = hide;
   }
}

function e2_tag_show(elm, elmClass){
   var item = document.getElementById(elm);
   var unhide = elmClass;
   if(item){
      item.className = unhide;
   }
}

function e2_tag_hide_and_show(elmHide, elmShow, elmClassShow){
   var itemHide = document.getElementById(elmHide);
   var itemShow = document.getElementById(elmShow);
   var hide = 'noDisplay';
   var unhide = elmClassShow;
   if(itemHide){
      itemHide.className = hide;
   }
   if(itemShow){
      itemShow.className = unhide;
   }
}

function e2_tag_hide_show_toggle(elm, elmClass){
   var item = document.getElementById(elm);
   var hide = 'noDisplay';
   var unhide = elmClass;
   if(item){
      item.className = (item.className==hide)?unhide:hide;
   }
}

function e2_check_email_validity(str){
   var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
   if (filter.test(str))
      return true;
   else{
      return false;
   }
}

function e2_check_username_validity(str){
   var len = str.length;
   if (len >= 3)
      return true;
   else{
      return false;
   }
}

/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
** Code licensed under Creative Commons Attribution-ShareAlike License      **
** http://creativecommons.org/licenses/by-sa/2.0/                           **/


function XHConn()
{
   var xmlhttp, bComplete = false;
   try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   }
   catch (e) {
      try {
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {
         try {
            xmlhttp = new XMLHttpRequest();
         }
         catch (e) {
            xmlhttp = false;
         }
      }
   }
   if (!xmlhttp) return null;
   this.connect = function(sURL, sMethod, sVars, fnDone)
   {
      if (!xmlhttp) return false;
      bComplete = false;
      sMethod = sMethod.toUpperCase();
      try {
         if (sMethod == "GET")
         {
            xmlhttp.open(sMethod, sURL+"?"+sVars, true);
            sVars = "";
         }
         else
         {
            xmlhttp.open(sMethod, sURL, true);
            xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
            xmlhttp.setRequestHeader("Content-Type",
               "application/x-www-form-urlencoded");
         }
         xmlhttp.onreadystatechange = function(){
            if (xmlhttp.readyState == 4 && !bComplete)
            {
               bComplete = true;
               fnDone(xmlhttp);
            }
         };
         xmlhttp.send(sVars);
      }
      catch(z) {
         return false;
      }
      return true;
   };
   return this;
}


/**
* Ajax implementation related functions
*/


// Global AdminUser JS Variables
var previousAdminuserEmailValue = '';		// email address string which was last sent to ajax for a lookup
var previousAdminuserEmailExists = '';		// true or false based upon what was returned from the ajax lookup
var previousAdminuserUsernameValue = '';	// Username string which was last sent to ajax for a lookup
var previousAdminuserUsernameExists = '';	// true or false based upon what was returned from the ajax lookup
var previousAdminuserUsernameSyntaxCheck = '';	// Username string which was last checked for syntax errors
var adminuserErrorHeading = "ERRORS ENCOUNTERED\n\n";
var adminuserWhichForm = 'form1';		// Which set for sub-form fields are currently displayed
var adminuserFormSwitchInProgress = false;	// A lock to inhibit multiple concurrent activities during async activities


// Check Email field in Admin User Add/Edit Form
// Check syntax (if invalid, js alert).
// Check existance on server (in adminuserEmailCheckDone, display one of two forms depending upon existance).
// mode=0 when invoked at the field level (e.g. onchange), or mode=1 when invoked from the overall form validation function. (not used yet)
function adminuserEmailCheck(mode){
   if(adminuserFormSwitchInProgress) {
      return true;
   }
   adminuserFormSwitchInProgress = true;
   var error_message = '';
   var emailValue = document.b4u_useradmin_form.email.value;
   if(emailValue) {
      emailValue = emailValue.toLowerCase();
   }
   //alert('adminuserEmailCheck: previousAdminuserEmailValue='+previousAdminuserEmailValue+', previousAdminuserEmailExists='+previousAdminuserEmailExists+', emailValue='+emailValue+', adminuserWhichForm='+adminuserWhichForm+', mode='+mode);
   if(!e2_check_email_validity(emailValue)){
      document.b4u_useradmin_form.email.focus();
      error_message = "Please enter a valid email address";
      alert(adminuserErrorHeading + error_message);
      adminuserFormSwitchInProgress = false;
      return false;
   }
   if(emailValue != '' && (previousAdminuserEmailValue == '' || emailValue != previousAdminuserEmailValue)) {
      str = 'PAGE_COMMAND=ajax&CONTENT_TYPE=useradmin&' + ajax_type_parameter + '=' + ajax_type_email_lookup;
      str = str + '&email=' + emailValue + '&uid=' + useradmin_uid;
      //initialize XHConn (if XHConn isn't created successfully,
      //the client doesnt' support Ajax)
      var ajaxConn = new XHConn();
      //post to server
      ajaxConn.connect(useradmin_path, "POST", str, adminuserEmailCheckDone);
      previousAdminuserEmailValue = emailValue;
   } else {
      adminuserFormSwitchInProgress = false;
   }
   return true;
}

function adminuserEmailCheckDone(XML)
{
   if(XML.responseText){
      var res = XML.responseText;
      // alert('adminuserEmailCheckDone: XML.responseText="'+res+'"');
      var newString = res.split('|');
      // Fields: email_address|count|list_of_usernames(uid1=username1~uid2=username2~...)
      var result_email		= newString[0];
      var result_username_count	= newString[1];
      var result_username_list	= newString[2];
      //alert('adminuserEmailCheckDone: result_email='+result_email+', result_username_count='+result_username_count+', result_username_list="'+result_username_list+'", previousAdminuserEmailValue='+previousAdminuserEmailValue);
      if(result_username_count > 0){
         previousAdminuserEmailExists = true;
         if(adminuserWhichForm != 'form2'){
            adminuser_set_form2();
         //alert('adminuserEmailCheckDone: count>0, setting form2, adminuserWhichForm now='+adminuserWhichForm);
         }
         var msg1 = '';
         msg1 += "* NOTE *<br />\n";
         msg1 += 'Email address "<strong>' + previousAdminuserEmailValue + '</strong>" already exists in the Bongo4U system.<br />' + "\n";
         if(result_username_count > 1){
            msg1 += "There are <strong>" + result_username_count + "</strong> user accounts that use this email address.<br />\n";
            msg1 += "To grant one of these user accounts access to this site,";
            msg1 += " please select the desired account from the 'Existing Username' list and press the [Save Changes] button.<br />\n";
         } else {
            msg1 += "To grant this user access to this site,";
            msg1 += " select their account from the 'Existing Username' list and press the [Save Changes] button.<br />\n";
         }
         document.getElementById('useradmin_form2_display_area_1').innerHTML = msg1;
         if(useradmin_uid == 0){
            var msg2 = '';
            msg2 += "Or if you wish to create a new username, then either change the email address or<br />\n";
            msg2 += "click the following radio button to use the same email address for the new username:\n";
            msg2 += '<nobr><input type="radio" name="other_uid" value="1" onclick="adminuser_set_form1();" />';
            msg2 += "Create New User Account</nobr><br />\n";
            document.getElementById('useradmin_form2_display_area_2').innerHTML = msg2;
         }
         // Populate the username options in the select list
         document.b4u_useradmin_form.useradmin_form2_username_select[0] = new Option('- Select -','');
         if(result_username_list.length > 0) {
            var entries			= result_username_list.split('~');
            var no_of_entries		= entries.length;
            document.b4u_useradmin_form.useradmin_form2_username_select.length = no_of_entries + 1; // in case previous list was longer
            for(i=1; i<=no_of_entries; i++){
               var entry		= entries[i-1].split('=');
               var entry_uid		= entry[0];
               var entry_username	= entry[1];
               document.b4u_useradmin_form.useradmin_form2_username_select[i] = new Option(entry_username,entry_uid);
            } // end of for loop
         }
      } else {
         previousAdminuserEmailExists = false;
         if(adminuserWhichForm != 'form1'){
            adminuser_set_form1();
         //alert('adminuserEmailCheckDone: count=0, setting form1, adminuserWhichForm now='+adminuserWhichForm);
         }
      }
      //alert('adminuserEmailCheckDone: previousAdminuserEmailValue='+previousAdminuserEmailValue+', previousAdminuserEmailExists='+previousAdminuserEmailExists+', adminuserWhichForm='+adminuserWhichForm);
      if(!previousAdminuserEmailExists){
         try{
            document.b4u_useradmin_form.first_name.focus();
         } catch (e) {}
      } else {
         document.b4u_useradmin_form.link_to_uid.focus();
      }
   }
   adminuserFormSwitchInProgress = false;
}


// Check Username field in Admin User Add/Edit Form
// Check syntax (if invalid, js alert).
// Check existance on server (in adminuserUsernameCheckDone, display an error message if it already exists, otherwise nothing).
// mode=0 when invoked at the field level (e.g. onchange), or mode=1 when invoked from the overall form validation function. (not used yet)
function adminuserUsernameCheck(mode){
   if(adminuserFormSwitchInProgress) {
      return true;
   }
   if(useradmin_uid > 0) {
      return true;
   }	// this routine is only for NEW user account (not existing accounts)
   adminuserFormSwitchInProgress = true;
   if(adminuserWhichForm != 'form1') {
      adminuserFormSwitchInProgress = false;
      return true;			// we are on the wrong form, there is no username field to check.
   }
   var error_message = '';
   var usernameValue = document.b4u_useradmin_form.username.value;
   if(usernameValue) {
      usernameValue = usernameValue.toLowerCase();
   }
   //alert('adminuserUsernameCheck: previousAdminuserUsernameValue='+previousAdminuserUsernameValue+', previousAdminuserUsernameExists='+previousAdminuserUsernameExists+', usernameValue='+usernameValue+', previousAdminuserUsernameSyntaxCheck='+previousAdminuserUsernameSyntaxCheck+', adminuserWhichForm='+adminuserWhichForm+', mode='+mode);
   if(!e2_check_username_validity(usernameValue)){
      if(usernameValue != previousAdminuserUsernameSyntaxCheck){
         previousAdminuserUsernameSyntaxCheck = usernameValue;
         error_message = "Please enter a valid username using letters and numbers (must be between 3 and 30 characters long). You will use the username to login to your Bongo4U Admin Area.";
         alert(adminuserErrorHeading + error_message);
      }
      if(adminuserWhichForm == 'form1') {
      //document.b4u_useradmin_form.username.focus();
      }
      adminuserFormSwitchInProgress = false;
      return false;
   }
   if(usernameValue != '' && (previousAdminuserUsernameValue == '' || usernameValue != previousAdminuserUsernameValue)) {
      str = 'PAGE_COMMAND=ajax&CONTENT_TYPE=useradmin&' + ajax_type_parameter + '=' + ajax_type_username_lookup;
      str = str + '&username=' + usernameValue;
      //initialize XHConn (if XHConn isn't created successfully,
      //the client doesnt' support Ajax)
      var ajaxConn = new XHConn();
      //post to server
      ajaxConn.connect(useradmin_path, "POST", str, adminuserUsernameCheckDone);
      previousAdminuserUsernameValue = usernameValue;
   } else {
      adminuserFormSwitchInProgress = false;
   }
   return true;
}

function adminuserUsernameCheckDone(XML)
{
   // alert('adminuserUsernameCheckDone: previousAdminuserUsernameValue='+previousAdminuserUsernameValue+', XML.responseText='+XML.responseText);
   if(XML.responseText){
      var res = XML.responseText;
      // Field layout: username|0(new) or 1(in use)
      var newString = res.split('|');
      if(newString[1] == 1){
         previousAdminuserUsernameExists = true;
         alert(adminuserErrorHeading + getUsernameFoundErrorMsg(previousAdminuserUsernameValue));
         document.b4u_useradmin_form.username.focus();
      } else {
         previousAdminuserUsernameExists = false;
      // document.b4u_useradmin_form.password.focus();
      }
   //alert('adminuserUsernameCheckDone: previousAdminuserUsernameValue='+previousAdminuserUsernameValue+', previousAdminuserUsernameExists='+previousAdminuserUsernameExists);
   }
   adminuserFormSwitchInProgress = false;
}


function getUsernameFoundErrorMsg(username){
   var error = '';
   error += 'Username "'+username+'" already exists in the Bongo4U system.';
   error += "  Please enter a different username for this new user account.\n\n";
   error += "Or, if you are trying to grant the existing "+username+" username access to this site (instead of creating a new user account),";
   error += " then just change the email address to match "+username+"'s email address.\n";
   return error;
}

function OLD_addOtherUsername(elmValue, elmId){
   document.getElementById(elmId).value = elmValue;
   str = 'PAGE_COMMAND=ajax&CONTENT_TYPE=useradmin&ajax_type=other_username';
   var ajaxConn = new XHConn();
   //post to server
   ajaxConn.connect(useradmin_path, "POST", str, addOtherUsernameDone);
}

function OLD_addOtherUsernameDone(XML)
{
   if(XML.responseText){
      document.getElementById('emailLookupDone').innerHTML = XML.responseText;
   }
   document.b4u_useradmin_form.first_name.focus();
}

function populateUsername(firstId, lastId, userId){
   var first_name	= document.getElementById(firstId).value;
   var last_name = document.getElementById(lastId).value;
   var username = document.getElementById(userId).value;
   if( first_name.length > 0 && last_name.length > 0 ){
      if(username == ''){
         document.getElementById(userId).value =  strtolower(first_name + last_name);
      }
   }
}

function strtolower( str ) { 
   return (str+'').toLowerCase();
}


// Validate the entire UserAdmin input form
// Returns false (suppress submit) or true (allow submit).
//
function validate_useradmin_form(){
   if(adminuserFormSwitchInProgress) {
      return false;
   }
   //alert('validate_useradmin_form: started for form='+adminuserWhichForm);
   if(adminuserWhichForm != 'form1' && adminuserWhichForm != 'form2') {
      // Unknown form, set to form1 and hope for the best...
      //alert('validate_useradmin_form: unknown form type, must be in the middle of a form switch');
      return false;				// let form switch take place (do not validate form)
   }

   var first_error_field_name = '';
   var presult = '';				// password-related error messages
   var result = '';				// other (non-password) error messages
   var allowed_chars = new Array('-', '_', '.', ',', '!', '@', '%' );

   // Check the two ajax-related fields first, since they give asynchronous results to the user.
   // Their lookup results cannot be merged with the results from the other input fields.

   // Email field is on both forms.
   // If Email is bad, then it will have already triggered an asynchronous alert. Stop checking remainder of form.
   var in_email			= document.b4u_useradmin_form.email.value;
   if(in_email.length < 1) {
      result += "A valid email address is required\n\n";
      if(first_error_field_name == '') {
         first_error_field_name = 'email';
      }
   } else {
      var email_ok = adminuserEmailCheck(1);
      if(!email_ok) {
         return false;
      }
   }

   // If Username is bad, then it will have already triggered an asynchronous alert. Stop checking remainder of form.
   if(adminuserWhichForm == 'form1' && !limited_mode){
      var in_username		= document.b4u_useradmin_form.username.value;
      if(in_username.length > 0) {
         var username_ok = adminuserUsernameCheck(1);
         if(!username_ok) {
            return false;
         }
      }
   }

   // Check First Name and Last Name

   if(adminuserWhichForm == 'form1' && !limited_mode){
      var in_first_name		= document.b4u_useradmin_form.first_name.value;
      var in_last_name		= document.b4u_useradmin_form.last_name.value;

      if(in_first_name.length < 1){
         result += "First Name is required\n\n";
         if(first_error_field_name == '') {
            first_error_field_name = 'first_name';
         }
      }

      if(in_last_name.length < 1){
         result += "Last Name is required\n\n";
         if(first_error_field_name == '') {
            first_error_field_name = 'last_name';
         }
      }

      if(in_username.length < 1){
         result += "A unique Username is required\n\n";
         if(first_error_field_name == '') {
            first_error_field_name = 'username';
         }
      } else {
         if(previousAdminuserUsernameExists){
            result += getUsernameFoundErrorMsg(previousAdminuserUsernameValue) + "\n";
         }
      }
   }

   // Do Password Checks

   if(adminuserWhichForm == 'form1' && !limited_mode && adminuser_editor_type != 'f' && adminuser_editor_type != 'g'){
      var in_password		= document.b4u_useradmin_form.password.value;
      var in_confirmpassword	= document.b4u_useradmin_form.confirmpassword.value;
      var pw			= in_password;
      presult += validate_password_rules(pw, in_confirmpassword, in_username, in_email, allowed_chars);
   }

   // Do User Permissions Check (at least one user permission must be checked/enabled)

   if(adminuserWhichForm == 'form1'){
      var adminuser_user_perm_count	= adminuser_user_perms.length;
      var user_perms_ok		= false;
      for(i=0; i<adminuser_user_perm_count; i++){
         var user_perm		= adminuser_user_perms[i];
         var field_name		= 'permission_'+user_perm;
         var the_object		= document.getElementById(field_name);
         var user_perm_checked	= the_object.checked;
         if(user_perm_checked){
            user_perms_ok	= true;
         }
      }
      if(!user_perms_ok){
         result += "You must enable(check) at least one of the Permissions checkboxes.\n\n";
      }

   }

   if(adminuserWhichForm == 'form2'){
      var in_link_to_uid	= document.b4u_useradmin_form.link_to_uid.value;

      if(!link_to_uid || link_to_uid < 1){
         result += "An existing username needs to be selected, or the radio button clicked to create a new username\n\n";
         if(first_error_field_name == '') {
            first_error_field_name = 'link_to_uid';
         }
      }

   }

   // Determine the result

   if(result || presult){
      if(presult){
         presult = "Password Requirements:\n" + presult;
      }
      var thanks = "\nThank you.\n";
      alert(adminuserErrorHeading + result + presult + thanks);	// display the error messages
      adminuser_form_set_field_focus(first_error_field_name);
      return false;					// and suppress the submit
   }
   return true;						// allow the submit to take place
}

//function used for validation of password.
function validate_password_rules(pw, in_confirmpassword, in_username, in_email, allowed_chars){
   var presult = '';
   // enforce min/max length
   if (!validatePassword(pw, {
      length:[8,20]
   })){
      presult += "- Length must be between 8 and 20 characters\n";
   }

   // enforce alphabetic character
   if(!validatePassword(pw, {
      alpha:1
   })){
      presult += "- Must contain at least one letter (a-z or A-Z)\n";
   }

   // enforce numeric character
   if(!validatePassword(pw, {
      numeric:1
   })){
      presult += "- Must contain at least one number (0-9)\n";
   }

   // allowed characters
   if(!validateSpecialCharacters(pw, allowed_chars)){
      presult += "- Invalid character found. Allowed characters are letters, digits and special characters:";
      max_allowed_chars = allowed_chars.length;
      for(var i=0;i<max_allowed_chars;i++){
         presult += ' '+allowed_chars[i];
      }
      presult += "\n";
   }

   var re = new RegExp(in_username);
   if(pw.match(re)){
      presult += "- Cannot contain your username anywhere within it\n";
   }
   if(in_email){
      re = new RegExp(in_email);
      if(pw.match(re)){
         presult += "- Cannot contain your email address anywhere within it\n";
      } else {
         var pieces = in_email.split('@');
         if(pieces.length >= 1 && pieces[0].length >= 3){
            re = new RegExp(pieces[0]);
            if(pw.match(re)){
               presult += "- Cannot contain the left-side of your email address ("+pieces[0]+") anywhere within it\n";
            }
         }
         if(pieces.length >= 2 && pieces[1].length >= 4){
            re = new RegExp(pieces[1]);
            if(pw.match(re)){
               presult += "- Cannot contain the right-side of your email address ("+pieces[1]+") anywhere within it\n";
            }
         }
      }
   }
   if(in_confirmpassword != pw){
      presult += "- 'Password' and 'Confirm Password' values must be the same\n";
   }
   return presult;
}


function adminuser_form_set_field_focus(fieldname){
   if(fieldname == 'email'){
      document.b4u_useradmin_form.email.focus();
   }
   if(fieldname == 'first_name'){
      document.b4u_useradmin_form.first_name.focus();
   }
   if(fieldname == 'last_name'){
      document.b4u_useradmin_form.last_name.focus();
   }
   if(fieldname == 'username'){
      document.b4u_useradmin_form.username.focus();
   }
   if(fieldname == 'password'){
      document.b4u_useradmin_form.password.focus();
   }
   if(fieldname == 'confirmpassword'){
      document.b4u_useradmin_form.confirmpassword.focus();
   }
   if(fieldname == 'link_to_uid'){
      document.b4u_useradmin_form.link_to_uid.focus();
   }
} // end adminuser_form_set_field_focus


function adminuser_set_form1(){
   var fieldname = '';
   // Hide the form2 fields
   for (i=1;i<=adminuser_form2_max;i++){
      fieldname	= 'useradmin_form2_field_' + i;
      e2_tag_hide(fieldname);
   }
   // Display the form1 fields
   for (i=1;i<=adminuser_form1_max;i++){
      fieldname	= 'useradmin_form1_field_' + i;
      e2_tag_show(fieldname, 'Display');
   }
   e2_tag_show('useradmin_form_submit_line', 'Display');
   adminuserWhichForm = 'form1';
   document.b4u_useradmin_form.myaccount_admin_form.value = adminuserWhichForm;
} // end adminuser_set_form1

function adminuser_set_form2(){
   var fieldname = '';
   // Hide the form1 fields
   for (i=1;i<=adminuser_form1_max;i++){
      fieldname	= 'useradmin_form1_field_' + i;
      e2_tag_hide(fieldname);
   }
   // Display the form2 fields
   for (i=1;i<=adminuser_form2_max;i++){
      fieldname	= 'useradmin_form2_field_' + i;
      e2_tag_show(fieldname, 'Display');
   }
   e2_tag_hide('useradmin_form_submit_line');
   adminuserWhichForm = 'form2';
   document.b4u_useradmin_form.myaccount_admin_form.value = adminuserWhichForm;
} // end adminuser_set_form2


function OLD_is_ajax_email_needed(id){
   var emailId = 'email_' + id
   var email = document.getElementById(emailId).value;
   var ajax_email = document.getElementById('ajax_email').value;
   var other_username = document.getElementById('other_username_same_email').value;
   if(ajax_email != email && other_username != '1'){
      return true;
   }
   return false;
}

function OLD_is_ajax_username_needed(id){
   var userId = 'username_' + id
   var username = document.getElementById(userId).value;
   var ajax_username = document.getElementById('ajax_username').value;
   if(ajax_username != username){
      return true;
   }
   return false;
}


function validateSpecialCharacters(pw, allowed_chars){
   var special_chars = pw.match(/\W/g);
   if(special_chars){
      for(var i=0;i<special_chars.length;i++){
         if(!in_array(special_chars[i],allowed_chars)){
            return false;
         }
      }
   }
   return true;
}

/*
	Password Validator 0.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT License
*/

function validatePassword (pw, options) {
   // default options (allows any password)
   var o = {
      lower:    0,
      upper:    0,
      alpha:    0, /* lower + upper */
      numeric:  0,
      special:  0,
      length:   [0, Infinity],
      custom:   [ /* regexes and/or functions */ ],
      badWords: [],
      badSequenceLength: 0,
      noQwertySequences: false,
      noSequential:      false
   };

   for (var property in options)
      o[property] = options[property];

   var	re = {
      lower:   /[a-z]/g,
      upper:   /[A-Z]/g,
      alpha:   /[A-Z]/gi,
      numeric: /[0-9]/g,
      special: /[\W_]/g
   },
   rule, i;

   // enforce min/max length
   if (pw.length < o.length[0] || pw.length > o.length[1])
      return false;

   // enforce lower/upper/alpha/numeric/special rules
   for (rule in re) {
      if ((pw.match(re[rule]) || []).length < o[rule])
         return false;
   }

   // enforce word ban (case insensitive)
   for (i = 0; i < o.badWords.length; i++) {
      if (pw.toLowerCase().indexOf(o.badWords[i].toLowerCase()) > -1)
         return false;
   }

   // enforce the no sequential, identical characters rule
   if (o.noSequential && /([\S\s])\1/.test(pw))
      return false;

   // enforce alphanumeric/qwerty sequence ban rules
   if (o.badSequenceLength) {
      var	lower   = "abcdefghijklmnopqrstuvwxyz",
      upper   = lower.toUpperCase(),
      numbers = "0123456789",
      qwerty  = "qwertyuiopasdfghjklzxcvbnm",
      start   = o.badSequenceLength - 1,
      seq     = "_" + pw.slice(0, start);
      for (i = start; i < pw.length; i++) {
         seq = seq.slice(1) + pw.charAt(i);
         if (
            lower.indexOf(seq)   > -1 ||
            upper.indexOf(seq)   > -1 ||
            numbers.indexOf(seq) > -1 ||
            (o.noQwertySequences && qwerty.indexOf(seq) > -1)
            ) {
            return false;
         }
      }
   }

   // enforce custom regex/function rules
   for (i = 0; i < o.custom.length; i++) {
      rule = o.custom[i];
      if (rule instanceof RegExp) {
         if (!rule.test(pw))
            return false;
      } else if (rule instanceof Function) {
         if (!rule(pw))
            return false;
      }
   }

   // great success!
   return true;
}


function in_array( what, where ){
   var a=false;
   for(var i=0;i<where.length;i++){
      if(what == where[i]){
         a=true;
         break;
      }
   }
   return a;
}

function getKey(e)
{
   var key;
   if(window.event){
      key = window.event.keyCode;     //IE
      if(key == 13)
         window.event.keyCode=9;//convert to tab
      else
         return true;
   }
   return true;
}

function getKeyPress(e,path,str,elmId)
{
   if(window.event){
      userLookup(path, str, elmId);
   }
   return true;
}


// START of SLIDESHOW Image Filename Validation Functions


// slideshow_form_validation_store_image_filename(filename) invoked in a loop for each image filename.
// slideshow_form_validation() will recursively call itself if the image data isn't available yet, else will verify & invoke submit if ok

// Global Variables:

var global_slideshow_image_filename_list	= '';
var global_slideshow_image_checks_in_progress	= false;
var global_slideshow_image_data_missing		= false;
var global_slideshow_image_data_retry_count	= 0;

// Store an Image Filename for later Validation
//
// Input: image file's filename & image's field label
// Output: (none)
//
function slideshow_form_validation_store_image_filename(filename,fieldlabel){
   if(filename){
      if(global_slideshow_image_filename_list != ''){
         global_slideshow_image_filename_list += '|';
      }
      global_slideshow_image_filename_list += filename + '^' + fieldlabel;	// store as: filename^fieldlabel|...
   }
}

// See if we have the image data available.  If not, then sleep and recursively callback ourselves to check again.
// If data is ok or checking is bypassed, then invoke the submit function, otherwise trigger a pop-up alert box.
//
// Input: (none)
// Output: (none) but might trigger the submit function or an alert box as needed.
//
function slideshow_form_validation(contentId){
   var trigger_submit_action		= false;
   if(contentId == undefined){
      contentId = '';
   }

   // Determine if this is the first invocation
   if(!global_slideshow_image_checks_in_progress){
      global_slideshow_image_checks_in_progress	= true;
      global_slideshow_image_data_retry_count	= 0;
      // Hide submit button, display 'please wait' message
      document.getElementById('b4u_slideshow_submit_'+contentId).style.display="none";
      document.getElementById('b4u_slideshow_wait_'+contentId).style.display="";
   }

   // Were any images specified by the user?
   if(global_slideshow_image_filename_list == ''){
      alert("ERRORS ENCOUNTERED\n\nYou need to upload or select image files to be displayed in your Slideshow.\n\nNo images have been specified yet.\n\nPlease click the Browse Images button to upload new images or to selected previously-updated images.\n");
      slideshow_form_validation_global_resets(contentId);
   }

   // See if the user elected to bypass image size checks
   var user_bypass_checks		= false;
   //   if(document.getElementById('b4u_slideshow_submit_check').checked == true){
   //      user_bypass_checks		= true;
   //      if(global_slideshow_image_filename_list != ''){
   //         trigger_submit_action		= true;
   //      }
   //   }

   // Do the image size checks (unless checks have been bypassed)
   if(global_slideshow_image_filename_list != '' && !user_bypass_checks){
      global_slideshow_image_data_missing	= false;
      var filenames			= global_slideshow_image_filename_list.split('|');
      var max_filenames			= filenames.length;
      for(var i=0;i<max_filenames;i++){
         var pieces			= filenames[i].split('^');	// filename^fieldlabel
         var newImg			= new Image();
         newImg.src			= pieces[0];			// filename
         var width			= newImg.width;
         var height			= newImg.height;
         if(width == 0 && height == 0){
            global_slideshow_image_data_missing	= true;
         }
      } // end of data-available loop
      if(global_slideshow_image_data_missing && global_slideshow_image_data_retry_count < 30){
         global_slideshow_image_data_retry_count++;
         var timeout_id		= setTimeout("slideshow_form_validation(" + contentId + ")",500);
      }else{
         var error_messages		= '';
         var b4u_slideshow_display	= document.getElementById('b4u_slideshow_display_size').value;
         var imageProperties		= b4u_slideshow_display.split('_');
         for(var i=0;i<max_filenames;i++){
            var pieces			= filenames[i].split('^');	// filename^fieldlabel
            var newImg			= new Image();
            newImg.src			= pieces[0];			// filename
            var width			= newImg.width;
            var height			= newImg.height;
            // If we cannot determine width+height (e.g. firefox v3.0.5 bug when on a mac),
            // then ignore the file and don't report it as a possible mismatch (since we don't know its size).
            if((width > 0 && height > 0) && (height != imageProperties[1] || width != imageProperties[0])){
               var splitter		= pieces[0].split('/');		// filename
               var count		= splitter.length - 1;
               var image_name		= splitter[count];
               error_messages		+= "- " + pieces[1] + " (" + image_name + ")";
               if(width > 0 || height > 0){
                  error_messages	+= ": Image Size is " + width + " wide x " + height + " high";
               }
               error_messages		+= "\n";
            }
         } // end of size-check loop
         if(error_messages != ''){
            // Unhide the Bypass Checks button as an option for the user
            document.getElementById('b4u_slideshow_submit_check_button').style.display="";
            // Display error messages
            alert(generate_slideshow_error_message(error_messages));
         }else{
            // Everything is ok
            trigger_submit_action	= true;
         }
         slideshow_form_validation_global_resets(contentId);
      }
   }else{
      slideshow_form_validation_global_resets(contentId);
   }
   if(trigger_submit_action){ 
      document.b4u_slideshow_edit_form.submit();
   }
}

function slideshow_form_validation_global_resets(contentId){
   global_slideshow_image_filename_list		= '';
   global_slideshow_image_checks_in_progress	= false;
   // Unhide the normal submit button. Hide the "please wait" message.
   document.getElementById('b4u_slideshow_submit_'+contentId).style.display="";
   document.getElementById('b4u_slideshow_wait_'+contentId).style.display="none";
}

function generate_slideshow_error_message(result){
   var b4u_slideshow_display = document.getElementById('b4u_slideshow_display_size').value;
   var imageProperties = b4u_slideshow_display.split('_');
   var top = "ERRORS ENCOUNTERED\n\n";
   top += "You have selected a Slideshow Display Size of " + imageProperties[0] + " wide x " + imageProperties[1] + " high (pixels).";
   top += "  Unfortunately, the size of the following images do not match your selected Display Size:\n\n";
   var bottom = "\nYOUR CHOICES ARE:\n\n";
   bottom += "(1) Click the 'Bypass Image Size Checks' button to ignore these problems and to use these images anyway (images will be squeezed or stretched without regard to their aspect ratio, which might not look very good)\n\n";
   bottom += "(2) Change your selected Display Size to match the size of your images\n\n";
   bottom += "(3) Replace your images with ones that match your selected Display Size\n";
   return (top + result + bottom);
}


// END of SLIDESHOW Image Filename Validation Functions


// getImgSize no longer used
function getImgSize(imgSrc, fieldlabel, type)
{
   var result = '';
   if(imgSrc){
      var newImg = new Image();
      newImg.src = imgSrc;
      var height = newImg.height;
      var width = newImg.width;
      var splitter = imgSrc.split('/');
      var count = splitter.length - 1;
      var image_name = splitter[count];
      var b4u_slideshow_display = document.getElementById('b4u_slideshow_display_size').value;
      var imageProperties = b4u_slideshow_display.split('_');
      if(height != imageProperties[1] || width != imageProperties[0]){
         if(type == 'single'){
            result += "ERROR ENCOUNTERED for " + fieldlabel  + " (" + image_name + "):\n\n";
            result += "This image's width of " + width +
            " and height of " + height +
            " does NOT match your selected Display Size of " +
            imageProperties[0]+ " wide and " + imageProperties[1] + " high (pixels). \n\n";
         }
         else if(type =='all'){
            result += "- " + fieldlabel + " (" + image_name + "): Image Size is " + width + " wide x " + height + " high.\n";
         }
      }
   }
   return result;
}


// Redirect to the page address that is the value of the passed object, e.g. pass "this" to it from a select statement.
// <select name="..." onChange="b4u_redirect_to(this);"><option value="contact">Contact Us</option>...</select>
//
function b4u_redirect_to(field_object){
   var page_addr = field_object.value;
   var url = base_href + page_addr;
   location.href = url;
}


// Redirect to the page address that is the value of the passed object or redirect to an external URL in a new window.
// You must pass "this" to it from a select statement
// The option value from the passed object must contain a "p" or "e" then a "|" then the page address or external full url.
// Example of an internal page target: value="p|about_us"
// Example of an external URL target: value="e|http://www.other-website.com/"
// <select name="..." onChange="b4u_redirect_to_page_or_external(this);"><option value="p|contact">Contact Us</option>...
//	<option value="e|http://www.otherplace.com/">Other Site</option>...</select>
//
function b4u_redirect_to_page_or_external(field_object){
   var selected_value = field_object.value;
   var url_type = '';
   var url = '';
   if(selected_value){
      var pieces = selected_value.split('|');
      if(pieces && pieces.length>=2){
         url_type = pieces[0].toLowerCase();
         url = pieces[1];
      }
   }
   if(url_type=='p' && url.length>=1){
      var full_url = base_href + url;
      location.href = full_url;
   }
   if(url_type=='e' && url.length>=11 && url.substr(0,4).toLowerCase()=='http'){
      var win_name = 'Link_from_' + window.name;
      var result = window.open(url,win_name);
      if(result){
         result.focus();
      }
   }
}


/** No more used
function ajax_getimgsize(imgSrc){
   imgSrc = slideshow_site_base_href + imgSrc;
   var getimagesize_path = slideshow_site_base_href + '/custom_app/getimagesize.php';
   var str='img_src=' + imgSrc;
   var ajaxConn = new XHConn();
   //post to server
   return ajaxConn.connect(getimagesize_path, "POST", str, getImgSizeDone);
}

function getImgSizeDone(XML){
   document.getElementById('slideshow_image_check').value = XML.responseText;
}
**/

// End of common.js -->
