var browserIsIE = false;

if(document.all) browserIsIE = true;


function trim(str) {
   if(str == null) return '';
   return str.replace(/^\s*/, '').replace(/\s*$/, '');
}

function isPlainNumber(fieldValue)
{

   if(fieldValue == null) return false;

	var i;
	var c;

	for(i = 0; i < fieldValue.length; i++) {
		c = fieldValue.charAt(i);
		if (c < "0" || c > "9")
			return false;
	}

	return true;
}

function isDecimalNumber(fieldValue)
{

   decimalCount = 0;

   if(fieldValue == null) return false;

   //count decimals
   for(i = 0; i < fieldValue.length; i++) {
		c = fieldValue.charAt(i);
		if (c == ".") {
			decimalCount = decimalCount + 1;
        }
   }

   if (decimalCount>1) {
      alert('Invalid number. Too many decimal points');
      return;
   }



   var badCharacters = /\D/;   //any non numeric value

   /* replace all decimals with a number */
   noSpaceString = fieldValue.replace(/[.]/, "0");

//   alert(noSpaceString);

   while(noSpaceString.match(/[.]/)) {
      noSpaceString = noSpaceString.replace(/[.]/, "0");
   }

   /* check to see if soemthign other than a letter exists */
   if(noSpaceString.match(badCharacters)) {
      return false;
   }
   else {
      return true;
   }
}

/**
 * This method validates an email address. It will display an
 * appropriate error message in an alert box if the address is invalid.
 * Returns true if valid, false if invalid.
 */
function validateEmail(email, required)
{
   if(email == null || trim(email) == '')
   {
      if(required)
      {
         alert("Please provide an email address.");
         return false;
      }
      else return true;
   }

   email = trim(email);

   // check for the presence of bad characters.
   //var badChars = "~`!# $%^&*()=|\\/?\"'<>:;{}[]";
   var badChars = "~`!# $%^&*()=|\\/?\"<>:;{}[]";

   for(j = 0; j < badChars.length; j++)
   {
      var thisChar = badChars.charAt(j);
      if(email.indexOf(thisChar) > -1)
      {
         var badChar = thisChar;
         if(thisChar == ' ') badChar = 'space';
         alert( "Email addresses may not contain a " + badChar + " character.");
         return false;
      }
   }

   // make sure there's a '@' character, not in the first
   // or last position
   var atIndex = email.indexOf("@");
   if(atIndex < 1 || atIndex == (email.length - 1))
   {
      alert("Email address is improperly formatted.");
      return false;
   }

   //make sure only 1 @ symbol
   var atIndex2 = email.indexOf("@",atIndex+1);
   if(atIndex2 > 1)
   {
      alert("Email address is improperly formatted.");
      return false;
   }

   // make sure there's at least one dot appearing after
   // the @ character
   var dotIndex = email.indexOf(".", atIndex);
   if(dotIndex < 0 || (dotIndex == atIndex+1))
   {
      alert("Email address is improperly formatted.");
      return false;
   }

   // make sure the last character is not a dot.
   if(email.lastIndexOf(".") == email.length - 1)
   {
      alert("Email address is improperly formatted. (Last character may not be '.')");
      return false;
   }
   
   // make sure the sticky dots are not a present.
   if(email.indexOf("..") > 0)
   {
      alert("Email address is improperly formatted. (sticky dots[..] are not allowed)");
      return false;
   }

   // leading and trailing character of domain name should not be '.' or '-'
   // leading and trailing character of local name should not be '.'
	var localName = email.substr(0,atIndex);
	var dns = email.substr(atIndex+1);
	var checkChars = ['-','.'];
	var checkString = localName;
	for (var x= 1 ; x < checkChars.length ; x++)
	{
		if (checkString.substr(0,1) == checkChars[x])
		{
			alert("Email address is improperly formatted. (First character should not be '"+ checkChars[x] + "' in the string '" + checkString + "')");
			return false;
		}
		if (checkString.substr(checkString.length - 1,1) == checkChars[x])
		{
			alert("Email address is improperly formatted. (First character should not be '"+ checkChars[x] + "' in the string '" + checkString + "')");
			return false;
		}
	}
	checkString = dns;
	for (var x= 0 ; x < checkChars.length ; x++)
	{
		if (checkString.substr(0,1) == checkChars[x]){
			alert("Email address is improperly formatted. (First character should not be '"+ checkChars[x] + "' in the string '" + checkString + "')");
			return false;
		}
		if (checkString.substr(checkString.length - 1,1) == checkChars[x]){
			alert("Email address is improperly formatted. (Last character should not be '"+ checkChars[x] + "' in the string '" + checkString + "')");
			return false;
		}
	}
   return true;
}

/**
 * This invokes GenericServlet with the Page business class,
 * and forwards the request the JSP page indicated by the first
 * argument. The first argument should not include the ".jsp"
 * extension. Parameters for the post can be set by subsequent
 * pairs of arguments (for example, args[1] and args[2], args[3]
 * and args[4]), where the first argument in the pair is
 * the parameter name and the next argument is its value.
 */
function goToPage() {

   var args = goToPage.arguments;


   // add hidden inputs to the form for each pair of arguments following the first
   // argument.
   var started = false;
   var url = "/servlets/qml";
   for(var i=1; i<(args.length-1); i+=2){
      if(started == false) {
         url += "?";
         started = true;
      }
      else {
         url += "&";
      }
      url = url + args[i] + "=" + args[i+1];
   }

   document.forms['_subForm_'].action = url;
   document.forms['_subForm_'].elements['NEXT_PAGE'].value = args[0];
   document.forms['_subForm_'].submit();

   return true; // in IE, the onClick event should return true to
                // cancel the href action.


//   var args = goToPage.arguments;
//
//   var subForm =
//      '<form name=_subForm action="/servlets/qml" method="POST"><input type="hidden" name="OBJECT_TYPE" value="Page"><input type="hidden" name="PAGE" value="getPage"><input type="hidden" name="OBJECT_PKG" value="pri.businessClasses"><input type="hidden" name="NEXT_PAGE" value="">';
//
//   // add hidden inputs to the form for each pair of arguments following the first
//   // argument.
//   for(var i=1; i<(args.length-1); i+=2){
//      var newInput = '<input type="hidden" name="' + args[i] + '" value="' + args[i+1] + '">';
//      subForm += newInput;
//   }
//
//   // now add the closing </form> tag.
//   subForm += '</form>';
//
//   // now make the form part of the document
//   document.write(subForm);
//
//
//   // the first argument is the NEXT_PAGE argument.
//   document.forms['_subForm'].elements['NEXT_PAGE'].value = args[0];
//   document.forms['_subForm'].submit();
//
//   return true; // in IE, the onClick event should return true to
//                // cancel the href action.

}

/**
 * This opens a popup window containing the document at the specified URL.
 */
function popup(url) {
   link = window.open(url,"Link","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=400,height=400,left=375,top=164");
}

function statusMsg(msg) {
   window.status= msg;
   return true;
}

function new_window(url) {
   link = window.open(url,"Link","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=260,height=190,left=418,top=364");
}

function getHelp(helpCat, helpNum) {
   new_window('/servlets/registration?OBJECT_PKG=pri.businessClasses&OBJECT_TYPE=ContextualHelp&PAGE=mainPage&PORTAL_CODE=PRI&HELP_NUM=' + helpNum + '&HELP_CAT=' + helpCat)
}

function iaqgHelp(helpCat, helpNum) {
   new_window('/servlets/registration?OBJECT_PKG=iaqg.businessClasses&OBJECT_TYPE=ContextualHelp&PAGE=mainPage&PORTAL_CODE=IAQG&HELP_NUM=' + helpNum + '&HELP_CAT=' + helpCat)
}


function hasInvalidCharacters(inputString){
   var badCharacters = /\W/;

   /* replace all Spaces with a letter */
   noSpaceString = inputString.replace(/\s/, "X");

   while(noSpaceString.match(/\s/)) {
      noSpaceString = noSpaceString.replace(/\s/, "X");
   }

   /* check to see if soemthign other than a letter exists */
   if(noSpaceString.match(badCharacters)) {
      return true;
   }
   else {
      return false;
   }
}


 function isBlank(name, str)
        {
           // Return true if field is blank or undefined

           if (str == null || str == "" || str == "<N/A>" ) {
              alert(name + ' cannot be blank. Please enter a value for ' + name.toLowerCase() + '.');
              return true;
           }

           noSpaceString = str.replace(/\s/, "");

           while(str.match(/\s/)) {
                 str = str.replace(/\s/, "");
             }

             if (str.length == 0) {
                alert(name + ' cannot be blank. Please enter a value for ' + name.toLowerCase() + '.');
                return true;
             }

             return false;

         }

 function isEmpty(str)
        {

           // Return true if field is blank or undefined
           if (str == null ||  str == "" || str == "<N/A>" ) {
              return true;
           }

           noSpaceString = str.replace(/\s/, "");

         while(str.match(/\s/)) {
               str = str.replace(/\s/, "");
           }

           if (str.length == 0) {
              return true;
           }

          return false;

 }

 //is unchecked
 function isUnChecked(group)
 {
            var groupLength = group.length;
			var checked = false;

			//we want to make sure at least one item in each group is selected.
			if( groupLength == null)	//single button and not a group
			     checked = group.checked;
			else
            {
               //now check all of the groups elements
               for( var i = 0; i < groupLength; i++)
                   if( (checked = group[i].checked)) break;
            }

            return !checked;
 }


 function checkLength(strName,str,minLen,maxLen)
{
    var len = str.length;
    if ( len < minLen || len > maxLen ) {
        alert("The " + strName + " must be at least "+ minLen +" characters in Length and cannot exceed" + maxLen +" characters; can include numbers and letters; can be upper/lower case; can include only special characters dash(-), underScore(_) or period(.)");
        return true;
    }
    else
        return false;
}


 function validUSAZip(zip)
{
        if (zip.length != 5 && zip.length !=10) {
           alert("Invalid postal code for USA. Must be in format 12345 or 12345-1234");
           return false;
        }

        var ch;
        var dchars = "0123456789"

        for (var i=0; i < zip.length; i++) {
           ch = zip.substring(i,i+1);
           if (i!=5) {
              if (dchars.indexOf(ch) == -1) {
                 alert("Postal Code must be Numeric for United States");
                 return false;
              }
           } else { //when i=5
              if (ch != '-') {
                 alert("Postal Code must contain -  after primary postal code");
                 return false;
              }
           }
        }

        return true;
}

 function validCanadaZip(zip)
{
        //alert("into canada");
        if (zip.length != 7 ) {
           alert("Invalid postal code for CANADA - format must be 'X9X 9X9' where X is Alphabetic and 9 is numeric");
           return false;
        }
        var ch;
        var dchars = "0123456789"
        var achars = ""
        for (var i=0; i < zip.length; i++) {
           ch = zip.substring(i,i+1);
           //alert("into loop for char "+i+ " ..cha to be chked is "+ch);
           if (i==1 || i==4 || i==6) {
              if (dchars.indexOf(ch) == -1) {
                 alert("Invalid postal code for CANADA - format must be 'X9X 9X9' where X is Alphabetic and 9 is numeric");
                 return false;
              }
           } else if (i==0 || i==2 || i==5) {
              if (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')))
                 continue;
              else {
                 document.forms.form.elements["_ADDR_PSTL_CD"].focus();
                 alert("Invalid postal code for CANADA - format must be 'X9X 9X9' where X is Alphabetic and 9 is numeric");
                 return false;
              }
           } else if (i==3) {
              if (ch!=" ") {
                 alert("4th char must be a space in postal code for CANADA");
                 return false;
              }
           }
        }

        return true;
}



function checkSpecialCharacter(strName,str)
{
    var ch;
    var dchars = "0123456789"
    var schars = "-_."
    var state = false;

    for (var i=0; i < str.length; i++){
        ch = str.substring(i,i+1);

        //Numerics
        if (dchars.indexOf(ch) > -1)
        {
            state = true;
            continue;
        }

        //Characters
        if(((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z')))
        {
            state = true;
            continue;
        }

        //Special Characters
        if(schars.indexOf(ch) > -1){
            state = true;
            continue;
        }
        state = false;
        break;
    }

    if(!state){
        alert("The " + strName + " can include numbers and letters, and can be upper/lower case; and can only include these special characters dash(-), underScore(_) or period(.)");
        return true;
    }
    else{
        return false;
    }
}


        /**
         * Replaces smart double(8220,8221) and smart single quotes(8216,8217)  to normal double and normal single quotes
         * Replaces em-dashes(8211,8212) to normal hyphens
         * Replaces bullets (dot type 8226) to single space
         */
        function replaceSpecialChars(inputStr){
        if (inputStr=="") return;
        output ="";
         for (i = 0; i < inputStr.length; i++) {
            c = inputStr.charCodeAt(i);
            if (c==8220||c==8221) val = 34;
            else if (c==8211||c==8212) val = 45;
            else if (c==8216||c==8217) val = 39;
            else if (c==8226) val = 32;
            else val=c;

          output += String.fromCharCode(val);
          }
          return output;

        }

        function checkUnacceptableChars(inputStr){
          for (i = 0; i < inputStr.length; i++) {
               charVal = inputStr.charCodeAt(i);
               if (charVal>127){
                alert("You have an unacceptable character "+inputStr.charAt(i)+" , please replace it with a keyboard character. This can happen when copying and pasting from MS Word" );
                return false;
                }
           }
           return true;
        }




