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

// remove leading spaces of a string object
function ltrim (textObj)
{
   var textPos = 0;
   var textLen = textObj.length;

   for (textPos =0; textPos <textObj.length ; ++textPos )
   {
       var ch = textObj.charAt(textPos );
       if (ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r') 
          break;    
   }

   if (textPos < textLen)
       return textObj.substring(textPos,textLen);
   else
       return "";
}

// remove trailling spaces of a string object
function rtrim (textObj)
{
   var textPos=0;

   for (textPos =textObj.length-1; textPos >= 0 ; textPos-=1 )
   {
      var ch = textObj.charAt(textPos);
      if (ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r') 
         break;    
   }
   if (textPos >=0 )
      return textObj.substring(0,textPos+1);
   else
      return "";
}


function validPCode(PCodeObj)
{
    var PcodeValue = PCodeObj.value.toLowerCase();
    var PcodeValue = ltrim(rtrim(PcodeValue)); 
    var charSet =  "abceghjklmnprstvxywz";
    var digitSet = "1234567890";

    var mustBeDigit = true;

    if (PcodeValue.length == 7)
    {
        // Length is 7.  It must have a space in the middle
        if (PcodeValue.charAt(3) != ' ' && PcodeValue.charAt(3) != "-")
          return 1;
        else // remove middle character
          PcodeValue = (PcodeValue.substring(0,3) + PcodeValue.substring(4,7));
    }
    else if (PcodeValue.length != 6)
        return 1;

    // Make sure characters are legal
    // the first alpha char must not contain d,f,i,o,q,u,w,z
    if (charSet.lastIndexOf(PcodeValue.charAt(0),charSet.length-3) ==-1)
      return 1;

    for (var i = 1; i < 6; ++i)
    {
        if (!mustBeDigit)
        {
            if (charSet.lastIndexOf(PcodeValue.charAt(i),charSet.length-1) ==-1)
            return 1;
        }
        else if (digitSet.lastIndexOf(PcodeValue.charAt(i),digitSet.length-1) ==-1)
            return 1;

        // toggle between digit and alpha
        mustBeDigit = !mustBeDigit;
    }

    PcodeValue = PcodeValue.toUpperCase();
    PCodeObj.value = PcodeValue.substring(0,3) + '-' + PcodeValue.substring(3,6);
   
    // everything went ok
    return "";
} 

// This is the function that performs form verification. It will be invoked
// from the onSubmit() event handler. The handler should return whatever
// value this function returns.
function verify(f)
{
    var language = "";

    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        if (e.name == "language")
        {
            language = e.value;
        }


    }


    var msg;
    var empty_fields = "";
    var errors = "";
 
    if ( language == "ENG") {
    var allFields = {
                     lname:"Last Name",
                     fname:"First Name",
                     email:"Email",
                     title:"Title",
                     address:"Street Address",
                     city:"City/Town",
                     bigRegion:"Province",
                     borough:"Borough",
                     district:"District",
                     profession:"Occupation",
                     geogcode:"Postal Code",
                     geogSyntax:"Postal Code (invalid format!! Should be like H2H 2H2)",
                     word:"Word Verification (copy the word in the green box into the field!)"
                    }
    } else if (language == 'FRA')
    {
     var allFields = {lname:"Nom de famille",
                     fname:"Prénom",
                     email:"Courriel",
                     title:"Titre",
                     address:"Adresse",
                     city:"Ville/village",
                     bigRegion:"Province",
                     geogcode:"Code postal",
                     profession:"Métier",
                     geogSyntax:"Code Postal (format inadmissible !! Il doit être comme H2H 2H2)",
                     word:"Verification du mot (copiez le mot qui se trouve dans la boîte verte dans le champ!)"
                    }
    }

    // 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.
    // 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.optional) {
            // first check if the field is empty
            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
                empty_fields += "\n          " + allFields[e.name];
                continue;
            }

            // if the non-null field is the postalcode, validate it
            if ( e.name == "geogcode" )
            {
                if ( validPCode(document.composer.geogcode) != "" ) {
                   empty_fields += "\n          " + allFields["geogSyntax"];
                   continue;
                }

            }

        }

        if ( (e.type == "select-one" ) && ( e.name == "bigRegion" ) ) {
            // ensure that the default is not selected
            if (f.bigRegion.options[0].selected) {
                empty_fields += "\n          " + allFields[e.name];
            }
        }                             
    }

    // 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"

    if (empty_fields) {
        if (language == "ENG") { 
           msg += "- The following required field(s) are empty or incorrect:\n"
                   + empty_fields + "\n";
           msg += "\nPlease fill them in and try again.\n"; 
           if (errors) msg += "\n";
        }
        else if (language == "FRA") { 
           msg += "- Les champs exigés suivants sont vides ou incorrects:\n"
                   + empty_fields + "\n";
           msg += "\nVeuillez les corriger et essayez encore.\n"; 
           if (errors) msg += "\n";
        }
    }
    msg += errors;
    alert(msg);
    return false;
}

function TrackCount2(taObj,countFieldName,maxChars)
{
  RegExp.multiline = true;
  // this function will only put the line count in the count field
  var countField = eval("taObj.form."+countFieldName);

  // get the line count
  
  //taObj.value = taObj.value.replace(/\0D\0A/, "\n");      // DOS aka Windows.
  //taObj.value = taObj.value.replace(/%0A/, "\n");         // Unix.
  //taObj.value = taObj.value.replace(/%0D/, "\n");         // Mac.

  var linesArray = taObj.value.split(/\b/g);

  countField.value = linesArray.length ;
  alert("\"" + linesArray[1] + "\"");
}

function undoit(taObj)
{
  taObj.cols = taObj.cols - 2;
}

function tallWindow(taObj)
{
  RegExp.multiline = true;
  var flag = false;

  // remember  the selectionEnd and Start
  var Sstart = taObj.selectionStart ;
  var Send   = taObj.selectionEnd ; 
     

  // get the line count
  
  var linesArray = taObj.value.split(/\n/g);

  var totLines = 0;
  var lns = 0;

  for (x = 0 ; x < linesArray.length ; x++)
  {   
     lns = Math.ceil(linesArray[x].length/72);
     if (lns > 1)
        totLines = totLines + lns;
  }
  
  totLines = totLines + linesArray.length;


  if ( totLines < 25 )
  {
      taObj.rows = 25;
  }
  else if ( totLines > taObj.rows) 
  {
    // strange case such as when the usre pastes text from somewhere else.
    // make the number of rows correct

    var pattern1 = RegExp("gecko", "i");
    var pattern2 = RegExp("netscape", "i");


    if ( pattern1.test(navigator.userAgent ) )
    {
       if ( pattern2.test(navigator.userAgent )  )
       {
          //alert('Got here1');
          //taObj.columns =+ 2;
       }
       else
       {
          // recalculate the new number of lines
          //linesArray = taObj.value.split(/\n/g);
          //taObj.columns = taObj.columns + 3;
       }
    }
     
    taObj.rows = totLines + 5;
    taObj.cols = taObj.cols + 2;
    flag = true;
  
    alert('press me');
   // taObj.cols = taObj.cols - 2;

    //alert('sleep');

    //linesArray = taObj.value.split(/\n/g);
    //taObj.rows = linesArray.length + 4;
  }
  else
  {
     taObj.rows = totLines + 5;
  }

  //if ( linesArray.length > 25 )
  //{
 //     taObj.rows = linesArray.length + 2;
 // }

  // if (  linesArray.length < ( taObj.rows + 1  ) ) 
 // {
  //   var slack = taObj.rows - linesArray.length;
  //   var trail = "";

  //   for (x = 1; x < slack + 3; x++)
   //  {
  //      trail += "\n";
  //   }

   //  taObj.value += trail;
  //   taObj.selectionStart =  Sstart ;
  //   taObj.selectionEnd  = Send;

 // }
   if (flag)
     undoit(taObj);
    //taObj.cols = taObj.cols - 2;

}

function TrackCount(taObj,countFieldName,maxChars)
{
  // this function will only put the line count in the count field
  var countField = eval("taObj.form."+countFieldName);

  // get the line count
  
  var textBlock = taObj.value;
  
  // replace all grab previous characters with the letter P
  textBlock = textBlock.replace(/[\:\;\,\.\'\"]/g, "P");
   
  //alert(textBlock);

  var linesArray = textBlock.split("\n");

  // split up really long lines
  var total = 0;

  for (x = 0 ; x < linesArray.length ; x++)
  {   
     if (Math.ceil(linesArray[x].length/66) >= 1)
     {  
       var curLineArray = (linesArray[x]).split(/\b/g);
       
       var tot  = 0;
       for (y=0; y < curLineArray.length ; y++)
       { 
          if ( (curLineArray[y].length + tot ) >= 66)
          {
              //alert("\"" + curLineArray[y] + "\"");
              tot = 0; 
              ++total;
              
              if ( curLineArray[y].match(/^[ ]*$/) )
              {
                  //alert("got here1");
                  y = y -2;
              }
              else 
              {
                if ( curLineArray[y].match(/^P/g ) )
                {
                  //alert("got here2");
                  y = y -3;
                }
                else
                {
                  //alert("y : \"" + curLineArray[y] + "\"\n" + 
                  //      "y - 1 : \"" + curLineArray[y - 1] + "\"\n" +
                  //      "y - 2 : \"" + curLineArray[y - 2] + "\"\n"  +
                  //      "y - 3 : \"" + curLineArray[y - 3] + "\"\n" +
                  //      "Total: " + total);

                  //alert("got here3");
                  y = y -1;
                }
              }
          }
          else
          {
              tot += curLineArray[y].length;
              //if (linesArray.length == 3)
                 //alert(tot);
          }
       }

     }

     //total = total + Math.ceil(linesArray[x].length/66) - 1; 
  }

  // Need to check & enforce limit here also in case user pastes data
  countField.value = linesArray.length + total;
}

function numLines(taObj)
{

  // get the line count
  var textBlock = taObj.value;
  
  // replace all grab previous characters with the letter P
  textBlock = textBlock.replace(/[\:\;\,\.\'\"]/g, "P");
   
  var linesArray = textBlock.split("\n");
 
  // initial line count
  var total = linesArray.length;


  // split up really long lines

  for (x = 0 ; x < linesArray.length ; x++)
  {   
     if (Math.ceil(linesArray[x].length/72) >= 1)
     {  
       var curLineArray = (linesArray[x]).split(/\b/g);
       
       var tot  = 0;
       for (y=0; y < curLineArray.length ; y++)
       { 
          if ( (curLineArray[y].length + tot ) >= 72)
          {
              tot = 0; 
              ++total;
              
              y = y - 1;
          }
          else
          {
              tot += curLineArray[y].length;
          }
       }

     }

  }
 
  return total;

}

