/************************************************************************
 *File: 		 /includes/helperfunctions.js
 *Description: 	 Global Javascript Functions used on all we pages 
 *Date Created:  7/19/2007
 *Author: 		 Rod Miller, MOPS International
 
 *Revisions: (By Sajjad Mahmood, Unitedsol)	
 18/07/08		- New functions are added named "wopen" and "CallPrint"		 
 * 2010-03-18	jpatsey		Mantis #4151 - Added validRouting function
 ************************************************************************/


/**********************************************************************************************************
 * Name:    String.prototype.trim = function ()
 * Purpose: perfom full trim on all javascript strings
 * Input:   Returns trimmed string
 * author:  dbustin 
 **********************************************************************************************************/

	String.prototype.trim = function () 
	{
		return this.replace(/^\s*/, "").replace(/\s*$/, "");
	}

 
/**********************************************************************************************************
 * Name:    isEmail()
 * Purpose: Validate email address before submission of form
 * Input:   Returns true if valid email is confirmed, else returns false. 
 **********************************************************************************************************/
	function isEmail(strEmail){
		/*var bConfirm = false; */
		/*bConfirm = confirm("testing..") */
		return bConfirm;
}



/**********************************************************************************************************
 * Name:    confirmDeletion()
 * Purpose: if any records were checked to be deleted, then confirm deletion
 * Input:   Returns true if deletion is confirmed, else returns false. 
 **********************************************************************************************************/
	function confirmDeletion(){
		var sToBeDeleted = '';
		var bDelete = false;
		bDelete = confirm("Are you sure you wish to delete the selected record?\n\n\nClick 'Ok' to continue.")
		return bDelete;
}

/**********************************************************************************************************
 * Name:    IsNumeric()
 * Purpose: Validate string before submission of form
 * Input:   Returns true if valid number is confirmed, else returns false. 
 **********************************************************************************************************/
	function IsNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }
 
 function validRouting(strRouting)
 {
	 if(!IsNumeric(strRouting))
	 {
		alert("Routing number must be numeric");
		return false;		 
	 }
	 
	 if(strRouting.length != 9)
	 {
		alert("Routing number must be 9 digits");
		return false;
	 }
	 
	 if(strRouting.charAt(0) > 3)
	 {
		alert("Routing number must start with 0,1,2 or 3")
		return false
	 }
	 return true;
	 
	 
	 
 }
/**********************************************************************************************************
 * Name:    validateDate()
 * Purpose: Validate Date before submission of form
 * Input:   Returns true if Date  is Valid , else returns false. 
 **********************************************************************************************************/
function validateDate(fld) {
    var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    var errorMessage = 'Please enter valid date as month, day, and four digit year.\nYou may use a slash, hyphen or period to separate the values.\nThe date must be a real date. 2-30-2000 would not be accepted.\nFormay m/d/yyyy.';
    if ((fld.value.match(RegExPattern)) && (fld.value!='')) {
        return true; 
    } else {
        alert(errorMessage);
        fld.focus();
    } 
}

function IsValidTime(timeStr) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
	alert("Time is not in a valid format.");
return false;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];

if (second=="") { second = null; }
if (ampm=="") { ampm = null }

if (hour < 0  || hour > 23) {
alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
return false;
}
if (hour <= 12 && ampm == null) {
if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
alert("You must specify AM or PM.");
return false;
   }
}
if  (hour > 12 && ampm != null) {
alert("You can't specify AM or PM for military time.");
return false;
}
if (minute<0 || minute > 59) {
alert ("Minute must be between 0 and 59.");
return false;
}
if (second != null && (second < 0 || second > 59)) {
alert ("Second must be between 0 and 59.");
return false;
}
return true;
}


/**********************************************************************************************************
 * Name:    ValidatePhoneNumber()
 * Purpose: Validate Phone before submission of form
 * Input:   Returns true if Phone  is Valid , else returns false. 
 **********************************************************************************************************/
 
 // Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;
var n;
var p;
var p1;

function ValidatePhoneNumber(m){

n=m.name;
//p1=document.forms[0].elements[n]
p1=m
ValidatePhone()
}
function testphone(obj1){
p=obj1.value
//alert(p)
p=p.replace("(","")
p=p.replace(")","")
p=p.replace("-","")
p=p.replace("-","")
//alert(isNaN(p))
if (isNaN(p)==true){
alert("Check phone");
return false;
}
}
//Helper Function For ValidatePhoneNumber
function ValidatePhone(){
p=p1.value
if(p.length==3){
	//d10=p.indexOf('(')
	pp=p;
	d4=p.indexOf('(')
	d5=p.indexOf(')')
	if(d4==-1){
		pp="("+pp;
	}
	if(d5==-1){
		pp=pp+")";
	}
	//pp="("+pp+")";
	document.getElementById(n).value="";
	document.getElementById(n).value=pp;
}
if(p.length>3){
	d1=p.indexOf('(')
	d2=p.indexOf(')')
	if (d2==-1){
		l30=p.length;
		p30=p.substring(0,4);
		//alert(p30);
		p30=p30+")"
		p31=p.substring(4,l30);
		pp=p30+p31;
		//alert(p31);
		document.getElementById(n).value="";
		document.getElementById(n).value=pp;
	}
	}
if(p.length>5){
	p11=p.substring(d1+1,d2);
	if(p11.length>3){
	p12=p11;
	l12=p12.length;
	l15=p.length
	//l12=l12-3
	p13=p11.substring(0,3);
	p14=p11.substring(3,l12);
	p15=p.substring(d2+1,l15);
	document.getElementById(n).value="";
	pp="("+p13+")"+p14+p15;
	document.getElementById(n).value=pp;
	//obj1.value="";
	//obj1.value=pp;
	}
	l16=p.length;
	p16=p.substring(d2+1,l16);
	l17=p16.length;
	if(l17>3&&p16.indexOf('-')==-1){
		p17=p.substring(d2+1,d2+4);
		p18=p.substring(d2+4,l16);
		p19=p.substring(0,d2+1);
		//alert(p19);
	pp=p19+p17+"-"+p18;
	document.getElementById(n).value="";
	document.getElementById(n).value=pp;
	//obj1.value="";
	//obj1.value=pp;
	}
}
//}
setTimeout(ValidatePhone,100)
}



/**********************************************************************************************************
 * Name:    checkInternationalPhone()
 * Purpose: Validate Phone before submission of form
 * Input:   Returns true if Phone  is Valid , else returns false. 
 **********************************************************************************************************/

function checkInternationalPhone(strPhone){
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

/**********************************************************************************************************
 * Name:    ValidateEmail()
 * Purpose: Validate Email before submission of form
 * Input:   Returns true if Email  is Valid , else returns false. 
 **********************************************************************************************************/

function ValidateEmail(emField){ //reference to email field passed as argument

var fieldValue = emField.value // store field's entire value in variable

//if field is not empty
if(fieldValue != ""){
	var atSymbol = 0
	
	//loop through field value string
	for(var a = 0; a < fieldValue.length; a++){
	
	//look for @ symbol and for each @ found, increment atSymbol variable by 1
	if(fieldValue.charAt(a) == "@"){
	atSymbol++
	}
	}
	// if more than 1 @ symbol exists
	if(atSymbol > 1){
	// then cancel and don't submit form
	alert("Please Enter A Valid Email Address")
	return false
	}
	
	// if 1 @ symbol was found, and it is not the 1st character in string
	if(atSymbol == 1 && fieldValue.charAt(0) != "@"){
		//look for period at 2nd character after @ symbol
		var period = fieldValue.indexOf(".",fieldValue.indexOf("@")+2)
		
		// "." immediately following 1st "." ?
		var twoPeriods = (fieldValue.charAt((period+1)) == ".") ? true : false
		
		//if period was not found OR 2 periods together OR field contains less than 5 characters OR period is in last position
		if(period == -1 || twoPeriods || fieldValue.length < period + 2 || fieldValue.charAt(fieldValue.length-1)=="."){
		// then cancel and don't submit form
		alert("Please Enter A Valid Email Address")
		return false
		}
	} // no @ symbol exists or it is in position 0 (the first character of the field)
	else{
	// then cancel and don't submit form
	alert("Please Enter A Valid Email Address")
	return false
	}
} 
// if field is empty
else{
	// then cancel and don't submit form
	return true
}
return true
}

	
/**********************************************************************************************************
 * Name:    ValidateWebSite()
 * Purpose: Validate Email before submission of form
 * Input:   Returns true if Email  is Valid , else returns false. 
 **********************************************************************************************************/
function ValidateWebSite(Valwebsite){
	if(Valwebsite.value!="")
	{	
		   if (Valwebsite.value.indexOf ('www', 0) == -1 || Valwebsite.value.length < 10)
		   {
				if(Valwebsite.value.indexOf ('.com', 0) == -1 || Valwebsite.value.length < 10)
				{
					 alert ("Please Enter a valid URL and try again")
					 Valwebsite.focus();
					 return false;
				} else {
			   			return true;
		   		}
		   } else {
			   return true;
		   }
	} else {
		return true;	
	}
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	dtStr = dtStr.value;	
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)

	if (pos1==-1 || pos2==-1){
		alert("The date format should be : m/d/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}



var dateFormat = function () {
	var	token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
		timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (value, length) {
			value = String(value);
			length = parseInt(length) || 2;
			while (value.length < length)
				value = "0" + value;
			return value;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask) {
		// Treat the first argument as a mask if it doesn't contain any numbers
		if (
			arguments.length == 1 &&
			(typeof date == "string" || date instanceof String) &&
			!/\d/.test(date)
		) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date();
		if (isNaN(date))
			throw "invalid date";

		var dF = dateFormat;
		mask   = String(dF.masks[mask] || mask || dF.masks["default"]);

		var	d = date.getDate(),
			D = date.getDay(),
			m = date.getMonth(),
			y = date.getFullYear(),
			H = date.getHours(),
			M = date.getMinutes(),
			s = date.getSeconds(),
			L = date.getMilliseconds(),
			o = date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
			};

		return mask.replace(token, function ($0) {
			return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":       "ddd mmm d yyyy HH:MM:ss",
	shortDate:       "m/d/yy",
	mediumDate:      "mmm d, yyyy",
	longDate:        "mmmm d, yyyy",
	fullDate:        "dddd, mmmm d, yyyy",
	shortTime:       "h:MM TT",
	mediumTime:      "h:MM:ss TT",
	longTime:        "h:MM:ss TT Z",
	isoDate:         "yyyy-mm-dd",
	isoTime:         "HH:MM:ss",
	isoDateTime:     "yyyy-mm-dd'T'HH:MM:ss",
	isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask) {
	return dateFormat(this, mask);
}


function ValidateCreditCard(ccNumb) {  // v2.0
var valid = "0123456789"  // Valid digits in a credit card number

ccNumb = ccNumb.replace (/[^0-9]/g,'');  // strip anything that is not a digit

var len = ccNumb.length;  // The length of the submitted cc number
var iCCN = parseInt(ccNumb);  // integer of ccNumb
var sCCN = ccNumb.toString();  // string of ccNumb
//sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // strip spaces
var iTotal = 0;  // integer total set at zero
var bNum = true;  // by default assume it is a number
var bResult = false;  // by default assume it is NOT a valid cc
var temp;  // temp variable for parsing string
var calc;  // used for calculation of each digit

// Determine if the ccNumb is in fact all numbers
//for (var j=0; j<len; j++) {
//  temp = "" + sCCN.substring(j, j+1);
//  if (valid.indexOf(temp) == "-1"){bNum = false;}
//}

// if it is NOT a number, you can either alert to the fact, or just pass a failure
if(!bNum){
  /*alert("Not a Number");*/bResult = false;
}

// Determine if it is the proper length 
if((len == 0)&&(bResult)){  // nothing, field is blank AND passed above # check
  bResult = false;
} else{  // ccNumb is a number and the proper length - let's see if it is a valid card number
  if(len >= 15){  // 15 or 16 for Amex or V/MC
    for(var i=len;i>0;i--){  // LOOP throught the digits of the card
      calc = parseInt(iCCN) % 10;  // right most digit
      calc = parseInt(calc);  // assure it is an integer
      iTotal += calc;  // running total of the card number as we loop - Do Nothing to first digit
      i--;  // decrement the count - move to the next digit in the card
      iCCN = iCCN / 10;                               // subtracts right most digit from ccNumb
      calc = parseInt(iCCN) % 10 ;    // NEXT right most digit
      calc = calc *2;                                 // multiply the digit by two
      // Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7,
      // I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple.
      switch(calc){
        case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
        case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
        case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
        case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
        case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
        default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
      }                                               
    iCCN = iCCN / 10;  // subtracts right most digit from ccNum
    iTotal += calc;  // running total of the card number as we loop
  }  // END OF LOOP
  if ((iTotal%10)==0){  // check to see if the sum Mod 10 is zero
    bResult = true;  // This IS (or could be) a valid credit card number.
  } else {
    bResult = false;  // This could NOT be a valid credit card number
    }
  }
}
// change alert to on-page display or other indication as needed.
if(!bResult){
  alert("This is NOT a valid Credit Card Number");
}
  return bResult; // Return the results
}

/*Use to open the page in new window*/
function wopen(url, name, w, h, s, r) {
	// Fudge factors for window decoration space.
	// In my tests these work well on all platforms & browsers.
	w += 32;
	h += 96;
	var win = window.open(url, name, 'width=' + w + ', height=' + h + ', ' + 'location=no, menubar=no, ' + 'status=no, toolbar=no, scrollbars= '+ s +' , resizable=' + r + '');
	win.resizeTo(w, h);
	win.focus();
}

/*Use to open the page in new window*/
function wopen2(url, name, w, h, s, r, m, t) {
	// Fudge factors for window decoration space.
	// In my tests these work well on all platforms & browsers.
	w += 32;
	h += 96;
	var win = window.open(url, name, 'width=' + w + ', height=' + h + ', ' + 'location=no, menubar=' + m + ', ' + 'status=no, toolbar=' + t + ', scrollbars= '+ s +' , resizable=' + r + '');
	win.resizeTo(w, h);
	win.focus();
}


/*will print the area*/
function CallPrint(strid,CSSLINK) {		
	var prtContent = document.getElementById(strid);		
	var WinPrint = window.open('','','left=20,top=20,width=640,height=480,toolbar=1,scrollbars=1,status=0');
	WinPrint.document.write("<html><head><LINK rel='stylesheet' type='text/css' href='"+CSSLINK+"' media='print'><LINK rel='stylesheet' type='text/css' href='"+CSSLINK+"' media='screen'><meta name='SKYPE_TOOLBAR' content='SKYPE_TOOLBAR_PARSER_COMPATIBLE' /></head><body>");
	WinPrint.document.write("<table width='98%' align='center' cellpadding='0' cellspacing='0'><tr><td align='left'>");
	WinPrint.document.write(prtContent.innerHTML);
	WinPrint.document.write("</td><tr></table>");
	WinPrint.document.write("</body></html>");
	WinPrint.document.close();
	WinPrint.focus();
	WinPrint.print();
	WinPrint.close();
}

