﻿// JScript File
function isblank(s)
{
	if ((s==null) || (s==' '))
	{
		return false;
	}
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c!= ' ') && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}

String.prototype.trim = function () 
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}


function validateSplChars(str,dispName,charBag)
{
	var j;
	var charBag = '<>/?,;:"~`!#$%^&*()-=+\|[]{}' + "'";
	if (str.length>0 || charBag.length>0)
	{
		//loop for not allowed special chars
		for (j=0;j<charBag.length; j++)
		{
			if (str.indexOf(charBag.charAt(j))>=0)
			{
				if (dispName != '');
				return false;
			}
		}
	}
	return true;
}

function validateEmail(email,dispName)
{
    var i=email.length;
    var len= i-email.lastIndexOf('.')-1
    if(len <=6)
    {
         var reg = new RegExp("^((?:(?:(?:[a-zA-Z0-9][\\.\\-\\+_]?)*)[a-zA-Z0-9])+)\\@((?:(?:(?:[a-zA-Z0-9][\\.\\-_]?){0,62})[a-zA-Z0-9])+)\\.([a-zA-Z0-9]{2,6})$");
         if(email.match(reg))
         {
             return true;
         }
         return false;
    }
    return false
}

function isCreditCard(st) {
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) == 0)
    return (true);
  else
    return (false);

} // END FUNCTION isCreditCard()

//function	to convert the dateformats to the standard format (mm/dd/yyy)
function convertToStdFormat(dtValue, dtFormat)
{
	var mm,dd;
	
	var parts = dtValue.split("/");
	

	if(dtFormat == "mm/dd/yyyy")
	{
		var mm=parts[0];
		var dd=parts[1];
		var yyyy=parts[2];
	}
	else if(dtFormat == "dd/mm/yyyy")
	{
		var mm=parts[1];
		var dd=parts[0];
		var yyyy=parts[2];
	}
	var sFinal = mm + "/" + dd + "/" + yyyy;

	return sFinal;

}

//check for a valid date
function isValidDate(dt)
{
	var dtValue=dt.value;
	var dtFormat=dt.format;
	var dtSeparator=dt.dateSeparator;

	if(dtValue == "")
		return true;
		
	var parts = dtValue.split(dtSeparator);
	var formatParts = dtFormat.split(dtSeparator);
	
	if (parts.length != formatParts.length)
		return false;
	
	var mm;
	var dd;
	var year;
	
	for(var i = 0; i < formatParts.length; i++)
	{
		if (formatParts[i].toLowerCase() == "dd" ||
			formatParts[i].toLowerCase() == "d") 
		{
			dd = parts[i];
		}
		else if (formatParts[i].toLowerCase() == "mm" ||
				 formatParts[i].toLowerCase()== "m") 
		{
			mm = parts[i];
		}
		else if (formatParts[i].toLowerCase() == "yyyy" ||
				 formatParts[i].toLowerCase() == "yy" ||
				 formatParts[i].toLowerCase() == "y") 
		{
			year = parts[i];
		}
	}

	var days = new Array(31,28,31,30,31,31,31,31,30,31,30,31);

	if(( year%4==0 && year%100!=0) || year%400==0 )
	    days[1]=29;
	if(mm > 12 || isNaN(mm) || mm<=0)
	{
		return false;
	}

	if( days[mm-1]< dd || isNaN(dd) || dd <=0)
	{
		 return false;
	}

	if(year<1753 || isNaN(year))
	{
		 return false;
	}
	return true;
}

function compareDate(startDate,endDate)
{
  var stDate = getDateObject(startDate,"-");
  var enDate = getDateObject(endDate,"-");
  if(stDate > enDate)
    return 1;
  else if(stDate <= enDate)
    return -1;
  else
    return 0;
}
function getDateObject(dateString,dateSeperator)
{
    //This function return a date object after accepting 
    //a date string ans dateseparator as arguments
    var curValue=dateString;
    var sepChar=dateSeperator;
    var curPos=0;
    var cDate,cMonth,cYear;
    
    //extract day portion
    curPos=dateString.indexOf(sepChar);
    cDate=dateString.substring(0,curPos);
	
    //extract month portion				
    endPos=dateString.indexOf(sepChar,curPos+1);			
    cMonth=dateString.substring(curPos+1,endPos);
    cMonth = GetMonthNumByName(cMonth);

    //extract year portion				
    curPos=endPos;
    endPos=curPos+5;			
    cYear=curValue.substring(curPos+1,endPos);
	
    //Create Date Object
    dtObject=new Date(cYear,cMonth,cDate);	
    return dtObject;
  }
  
  function GetMonthNumByName(month)
{
    var nMonth;
    
    switch (month)
    {
        case "Jan": 
            nMonth = 1;  
            break;         
        case "Feb": 
            nMonth = 2;           
            break;
        case "Mar": 
            nMonth = 3;           
            break;
        case "Apr": 
            nMonth = 4;           
            break;
        case "May": 
            nMonth = 5;           
            break;
        case "Jun": 
            nMonth = 6;           
            break;
        case "Jul": 
            nMonth = 7;           
            break;
        case "Aug": 
            nMonth = 8;           
            break;
        case "Sep": 
            nMonth = 9;           
            break;
        case "Oct": 
            nMonth = 10;           
            break;
        case "Nov": 
            nMonth = 11;           
            break;
        case "Dec": 
            nMonth = 12;                      
            break;
    }
    return nMonth;    
}

function isValidPhNumber(PhNumber)
{
	var PhNumberFormat = PhNumber.format;
	var PhNumberValue=PhNumber.value;

	if (PhNumberFormat == "xxx-xxx-xxxx")
	{
		if(PhNumberValue.length!=12 || PhNumberValue.charAt(3)!='-' || PhNumberValue.charAt(7)!='-')
		{
			//wrong format
			return false;
		}


		var firstPhNumberValue = new Number(PhNumberValue.substring(0,3),12);
		var secondPhNumberValue = new Number(PhNumberValue.substring(4,7),12);
		var thirdPhNumberValue = new Number(PhNumberValue.substring(8,12),12);


		if(isNaN(firstPhNumberValue) || isNaN(secondPhNumberValue) || isNaN(thirdPhNumberValue))
		{
			//not an integer
			 return false;
		}

	}
	else
		return false;
	return true;
}

function ValidateABA(ABA)
{
var sABA = ABA.value;
var strABAKey = "37137137";
var iResult = 0;
var iPlace = 0;
var iTotal = 0;
var iABADigit = 0;
var iABAKey = 0;
do
{
iABAKey = strABAKey.substr(iPlace,1);
iABADigit = sABA.substr(iPlace,1);
iResult = iResult + (iABAKey * iABADigit);
iPlace ++;
}
while (iPlace <=7)
iPlace = 8;
iABADigit = sABA.substr(iPlace,1);
iTotal = ((iABADigit/1) + (iResult/1)) / 10;

sResult = iTotal + "";
		if ((sABA == "") || (isNaN(sABA)) || (sABA.length !== 9) || (sResult.indexOf(".") != -1))
			return false;
		else
			return true;
}


function isValidSSN(SSN)
{
	var SSNFormat = SSN.format;
	var SSNValue=SSN.value;

	if (SSNFormat == "xxx-xx-xxxx")
	{
		if(SSNValue.length!=11 || SSNValue.charAt(3)!='-' || SSNValue.charAt(6)!='-')
		{
			return false;
		}
	}
	return true;
}
function isValidpub(pubname)
{
	if (pubname == "-- Select Publisher --" ||pubname == "" )
	{
			return true;
	}
	return false;
}


function verify(f)
{
//alert("verify function");

var msg;
var empty_fields = '';
var errors = '';
var password = '';
var confirm = '';
var passwordField ;

	for (var i = 0; i < f.length; i++) {
		var e = f.elements[i];
		var display = e.display;
		var errfield;
		var isEmpty;
		
		if (!display) {
			display = e.name;
		}
		
		if (((e.type == 'text') ||
			 (e.type == 'textarea') ||
			 (e.type == 'password') ||
			 (e.type == 'file') ||
			 (e.type == 'select-one')))
		{

			isEmpty = (e.value == '') || isblank(e.value)
			
			if (e.type == 'select-one')
			{
			    if (isValidpub(e.options[e.selectedIndex].text))
			    {			        
			        isEmpty = true;   
                }
			}

			if (!e.optional && isEmpty)
			{
				empty_fields += '\n     ' + display;
				if (! errfield){
					errfield = e;
				}
				continue;
			}

			if (!isEmpty)
			{
				if (e.numeric || (e.min != null) || (e.max != null)) {
                    
					var v;
					var grpSep;
					var decSep;
					var commaSep = ',';
										
                    if(e.numeric)
                    {
						grpSep = e.groupSeparator ? e.groupSeparator : ',';
						v = replaceAll(e.value, grpSep, '');
						
						decSep = e.decimalSeparator ? e.decimalSeparator : '.';
						v = replaceAll(v, decSep, '.');
                    }
					v = new Number(v);

					if (isNaN(v) || ((e.min != null) && (v < e.min)) ||
									((e.max != null) && (v > e.max)))
					{
						errors += '- The field ' + display + ' must be a number';

						if (e.min != null)
							errors += ' that is greater than or equal to ' + 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';
						if (! errfield){
							errfield = e;
						}

					}

					else
					{
						if (e.avoidDecimal != null)
						{
							if(e.value.indexOf(decSep) > -1)
								errors += '- The field ' + display + ' must not contain decimal separator. \n';
								if (! errfield){
									errfield = e;
							}
						}
						if (e.avoidComma != null)
						{	
						    if(e.value.indexOf(commaSep) > -1)
							    errors += '- The field ' + display + ' must not contain comma separator. \n';
							    if (! errfield){
								    errfield = e;
						    }							
						}
					}
				}
				if ((e.nosplchar != null) && ( validateSplChars(e.value) == false)){
						errors += '- The field ' + display + ' must not have special characters. \n'
						if (! errfield){
							errfield = e;
						}
				}
				if ((e.nosplcharexcept != null) && ( validateSplChars(e.value) == false)){
						errors += '- The field ' + display + ' does not allow special characters except _ and @.\n'
						if (! errfield){
							errfield = e;
						}
				}
				if(e.password != null) {
					password = e.value;
					passwordField = e;
				}

				if(e.confirm != null) {
					confirm = e.value;
				}

				if (e.validateEmail != null) {
					if ( validateEmail(e.value) == false){
						errors += '- The field ' + display + ' must be a valid email id. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

				if (e.creditCard != null) {
					if ( isCreditCard(e.value) == false){
						errors += '- The field ' + display + ' must be a valid credit card. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

				if (e.validateDate !=null){ 
					if ( isValidDate(e) == false){
						errors += '- The field ' + display + ' must be a valid date. \n'
						if (! errfield){
							errfield = e
						}
					}
				}
				if (e.validatePhNumber !=null){
					if ( isValidPhNumber(e) == false){
						errors += '- The field ' + display + ' must be a valid Phone Number. \n'
						if (! errfield){
							errfield = e
						}
					}
				}

                if (e.lengthMin) {
                    if (e.value.length < e.lengthMin) {
                        errors += '- The field ' + display + ' must have at least ' + e.lengthMin + ' characters. \n'
						if (! errfield){
							errfield = e
						}
					}
				}  

                if (e.lengthMax) {
                    if (e.value.length > e.lengthMax) {
                        errors += '- The field ' + display + ' must have only ' + e.lengthMax + ' characters. \n'
						if (! errfield){
							errfield = e
						}
					}
				}  
                
				if (e.validateSSN !=null){
					if ( isValidSSN(e) == false){
						errors += '- The field ' + display + ' must be a valid SS Number. \n'
						if (! errfield){
							errfield = e
						}
					}
				}


				if (e.validateABA !=null){
					if ( ValidateABA(e) == false){
						errors += '- The field ' + display + ' must be a valid ABA Number. \n'
						if (! errfield){
							errfield = e
						}
					}
				}
			}
		}
	}

	if (password != confirm){
		errors += '- The password fields do not match \n'
		if (! errfield)
		{
			errfield = passwordField;
		}
	}


	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 += '- Please fill in all required fields:\n'
		msg += '- The following field(s) are empty:\n'
				+ empty_fields + '\n';
		if (errors) msg += '\n';
	}

	msg += errors;
	alert(msg);
 	errfield.focus()
	if (errfield.type != "select-one")
	{
		errfield.select()
	}
	return false;
}

function replaceAll(oldString, findString, replaceString)
{
    if (findString != replaceString) 
    {
	    var i = oldString.indexOf(findString);
        while (i > -1)
        {
            oldString = oldString.replace(findString, replaceString);
            i = oldString.indexOf(findString);
        }
    }
    return oldString;
}

function IsStrongPassword(strPassword)
{     
      var minlength = 8;
      if (strPassword.length < minlength)
      {
        return false;
      }
      re = /[0-9]/;
      if(!re.test(strPassword)) 
      {        
        return false;
      }
      re = /[a-z]/;
      if(!re.test(strPassword)) 
      {       
        return false;
      }
      re = /[A-Z]/;
      if(!re.test(strPassword)) 
      {       
        return false;
      }      
    return true;
}
