var bkColor = "yellow";

function Trim(str)
{
  return str.replace(/^\s*|\s*$/g,"");
}

function changePage(newLoc)
 {
   nextPage = newLoc.options[newLoc.selectedIndex].value
   if (nextPage != "")
   {
      document.location.href = nextPage
   }
 }

function setBKColor(objControl)
{
  objControl.style.bkColor = objControl.style.backgroundColor;
  objControl.style.backgroundColor = bkColor;
  if (!(objControl.type == 'select-one'))
    objControl.select();
}
function reSetBKColor(objControl)
{
  objControl.style.backgroundColor = objControl.style.bkColor;
}

function CheckDataForm(frm)
{
  if (verify(frm))
    { return CheckIfGameBetweenSameTeam(frm); }
  else
    { return false; }
}

function checkRegistrationForm(frm)
{
  if (verify(frm))
    {
      if (!validateEmail(frm.EmailAddress.value,1,1))
      {
        frm.EmailAddress.focus(); 
        return false;
      }
    }
  else
    { return false; }
}

function CheckIfGameBetweenSameTeam(frm)
{
  if (frm.HostTeam.options[frm.HostTeam.options.selectedIndex].value == frm.VisitorTeam.options[frm.VisitorTeam.options.selectedIndex].value)
  {
    alert('Game can not be scheduled between same team!  Select different teams');
    return false;
  }
}

function checkPasswords(frm)
{
  if (verify(frm))
    { 
      if (frm.NewPassword.value != frm.PasswordConfirmation.value)
      {
        alert('You have typed two different passwords.  Passwords must match!');
        return false;
      }
    }
  else
    { return false; }
}

// A utility function that returns true if a string contains only 
// whitespace characters.
function isblank(s) {
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

// This is the function that performs form verification. It is invoked
// from the onsubmit event handler. The handler should return whatever
// value this function returns.
function verify(f) {
    var msg;
    var empty_fields = "";
    var errors = "";

    // Loop through the elements of the form, looking for all 
    // text and textarea elements that don't have an "optional" property
    // defined. Then, check for fields that are empty and make a list of them.
    // Also, if any of these elements have a "min" or a "max" property defined,
    // verify that they are numbers and in the right range.
    // If the element has a "numeric" property defined, verify that
    // it is a number, but don't check its range.
    // Put together error messages for fields that are wrong.
    for(var i = 0; i < f.length; i++) 
    {
        var e = f.elements[i];
        if ((e.type == "text") || (e.type == "textarea") || (e.type == "select-one") || (e.type == "password"))
        {
          if (!e.optional)
          {
            if ((e.value == null) || (e.value == "") || isblank(e.value)) 
            {
                empty_fields += "\n          " + e.name;
                continue;
            }

            // Now check for fields that are supposed to be numeric.
            if (e.numeric || (e.min != null) || (e.max != null)) 
            { 
                var v = parseFloat(e.value);
                if (isNaN(v) || 
                    ((e.min != null) && (v < e.min)) || 
                    ((e.max != null) && (v > e.max))) 
                {
                    errors += "- The field " + e.name + " must be a number";
                    if (e.min != null) 
                        errors += " that is greater than " + e.min;
                    if (e.max != null && e.min != null) 
                        errors += " and less than " + e.max;
                    else if (e.max != null)
                        errors += " that is less than " + e.max;
                    errors += ".\n";
                }
            }
          }
          //alert(e.name + " length: " + e.value.length + " and Maxlength: " + e.maxlength );
          //errors += "- The field " + e.name + " can not be more than " + e.maxlength + " characters.";
          if (e.value.length > e.maxlength)
          { 
            errors += "- The field " + e.name + " can not be more than " + e.maxlength + " characters.";
          }
        }
    }

    // Now, if there were any errors, display the messages, and
    // return false to prevent the form from being submitted. 
    // Otherwise return true.
    if (!empty_fields && !errors) return true;

    msg  = "______________________________________________________\n\n"
    msg += "The form was not submitted because of the following error(s).\n";
    msg += "Please correct these error(s) and re-submit.\n";
    msg += "______________________________________________________\n\n"

    if (empty_fields) {
        msg += "- The following required field(s) are empty:" 
                + empty_fields + "\n";
        if (errors) msg += "\n";
    }
    msg += errors;
    alert(msg);
    return false;
}

function validateEmail(addr,man,db) 
{
  /*if (addr == '' && man) {
     if (db) alert('email address is mandatory');
     return false;
  }*/
  var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
  for (i=0; i<invalidChars.length; i++) {
     if (addr.indexOf(invalidChars.charAt(i),0) > -1) {
        if (db) alert('email address contains invalid characters');
        return false;
     }
  }
  for (i=0; i<addr.length; i++) {
     if (addr.charCodeAt(i)>127) {
        if (db) alert("email address contains non ascii characters.");
        return false;
     }
  }
  var atPos = addr.indexOf('@',0);
  if (atPos == -1) {
     if (db) alert('email address must contain an @');
     return false;
  }
  if (atPos == 0) {
     if (db) alert('email address must not start with @');
     return false;
  }
  if (addr.indexOf('@', atPos + 1) > - 1) {
     if (db) alert('email address must contain only one @');
     return false;
  }
  if (addr.indexOf('.', atPos) == -1) {
     if (db) alert('email address must contain a period in the domain name');
     return false;
  }
  if (addr.indexOf('@.',0) != -1) {
     if (db) alert('period must not immediately follow @ in email address');
     return false;
  }
  if (addr.indexOf('.@',0) != -1){
     if (db) alert('period must not immediately precede @ in email address');
     return false;
  }
  if (addr.indexOf('..',0) != -1) {
     if (db) alert('two periods must not be adjacent in email address');
     return false;
  }
  var suffix = addr.substring(addr.lastIndexOf('.')+1);
  if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {
     if (db) alert('invalid primary domain in email address');
     return false;
  }
  return true;
}

// *** To Format Numbers

 function GetDecimalDelimiter(countryCode)
{
 
  switch (countryCode)
  {
    case 3:   
           return '#';
    case 2:   
           return ',';
    default:
           return '.';
  }
}

function GetCommaDelimiter(countryCode)
{
 
  switch (countryCode)
  { 
    case 3:          
           return '*';
    case 2:   
           return ',';
    default:
           return ',';
  }
 
}

function FormatClean(num)
{
     var sVal='';
     var nVal = num.length;
     var sChar='';
     
   try
   {
      for(c=0;c<nVal;c++)
      {
         sChar = num.charAt(c);
         nChar = sChar.charCodeAt(0);
         if ((nChar >=48) && (nChar <=57))  { sVal += num.charAt(c);   }
      }
   }
    catch (exception) { AlertError("Format Clean",exception); }
    return sVal;
}
  

function FormatNumber(num,countryCode,decimalPlaces)
{       

  var minus='';
  var comma='';
  var dec='';
  var preDecimal='';
  var postDecimal='';
  
  try 
  {
   
    decimalPlaces = parseInt(decimalPlaces);
    comma = GetCommaDelimiter(countryCode);
    dec = GetDecimalDelimiter(countryCode);
    
    if (decimalPlaces < 1) { dec = ''; }
    if (num.lastIndexOf("-") == 0) { minus='-'; }
   
    preDecimal = FormatClean(num);
    
    // preDecimal doesn't contain a number at all.
    // Return formatted zero representation.
    
    if (preDecimal.length < 1)
    {
       return minus + FormatEmptyNumber(dec,decimalPlaces);
    }
    
    // preDecimal is 0 or a series of 0's.
    // Return formatted zero representation.
    
    if (parseInt(preDecimal) < 1)
    {
       return minus + FormatEmptyNumber(dec,decimalPlaces);
    }
    
    // predecimal has no numbers to the left.
    // Return formatted zero representation.
    
    if (preDecimal.length == decimalPlaces)
    {
      return minus + '0' + dec + preDecimal;
    }
    
    // predecimal has fewer characters than the
    // specified number of decimal places.
    // Return formatted leading zero representation.
    
    if (preDecimal.length < decimalPlaces)
    {
       if (decimalPlaces == 2)
       {
        return minus + FormatEmptyNumber(dec,decimalPlaces - 1) + preDecimal;
       }
       return minus + FormatEmptyNumber(dec,decimalPlaces - 2) + preDecimal;
    }
    
    // predecimal contains enough characters to
    // qualify to need decimal points rendered.
    // Parse out the pre and post decimal values
    // for future formatting.
    
    if (preDecimal.length > decimalPlaces)
    {
      postDecimal = dec + preDecimal.substring(preDecimal.length - decimalPlaces,
                                               preDecimal.length);
      preDecimal = preDecimal.substring(0,preDecimal.length - decimalPlaces);
    }

    // Place comma oriented delimiter every 3 characters
    // against the numeric represenation of the "left" side
    // of the decimal representation.  When finished, return
    // both the left side comma formatted value together with
    // the right side decimal formatted value.
    
    var regex  = new RegExp('(-?[0-9]+)([0-9]{3})');
 
    while(regex.test(preDecimal))
    {
       preDecimal = preDecimal.replace(regex, '$1' + comma + '$2');
    }
       
  }
  catch (exception) { AlertError("Format Number",exception); }
  return minus + preDecimal + postDecimal;
}

function FormatEmptyNumber(decimalDelimiter,decimalPlaces)
{
    var preDecimal = '0';
    var postDecimal = '';
 
    for(i=0;i<decimalPlaces;i++)
    {
      if (i==0) { postDecimal += decimalDelimiter; }
      postDecimal += '0';
    }
   return preDecimal + postDecimal;
}
  

 function AlertError(methodName,e)
 {
            if (e.description == null) { alert(methodName + " Exception: " + e.message); }
            else {  alert(methodName + " Exception: " + e.description); }
 }

var win = null;
function abrirventana(mypage,myname,w,h,scroll)
{
    LeftPosition = (screen.width) ? (screen.width-w)/2: 0;
    TopPosition = (screen.height) ?(screen.height-h)/2 : 0;
    settings =
'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable,titlebar=no'
    win = window.open(mypage,myname,settings)
    if(win.window.focus){win.window.focus();}
}

