//  Commonly used functions for Javascript
var errhnd=false

function IsPhone(eobj){//Phone Validation
   var str = eobj;
   str1=strreplace(str," ","")
   var res = str1.match(/^\([0-9]{1,3}\)[0-9]{3}-[0-9]{4}$/g)
   if (res)
	  return true //Valid Phone
   return false  //Invalid Phone
}
function IsMobile(eobj){//CellPhone Validation
   var str = eobj;
   str1=strreplace(str," ","")
   var res = str1.match(/^\([0-9]{1,4}\)[0-9]{3}-[0-9]{4}$/g)
   if (res)
	  return true //Valid Phone
   return false  //Invalid Phone
}
function IsEmail(ieobj){//Email Validation
   var estr = ieobj          
   var eres = estr.match(/^(\s)*[_a-z0-9A-Z-]+(\.[_a-z0-9A-Z-]+)*@[a-z0-9A-Z-]+(\.[a-z0-9A-Z-]+)+$/g)
   if (eres)
	  return true  //Valid Email
   return false  //Invalid Email
}
function IsNull(obj) //Null Validation
{
   var myString = obj
   var inThere = myString.match(/\S/g)
   if (inThere) 
	  return false //Invalid number
   return true //Valid Number
}
function IsSpaceFound(sobj){ //Space Validation
   if (sobj.indexOf(" ")!=-1)
      return true //String with space
   return false //String without space
}
function InvalidCode(nobj)
{
   var mstr = nobj          
   var res = mstr.match(/[^A-Za-z0-9\-]/g)
   if (res)
	  return true //Invalid Code
   return false //Valid Code
}
function IsNotNumber(iobj){ //Integer Validation
   var myString = iobj
   var inThere = myString.match(/\D/g)
   if (inThere) 
	  return true //Invalid number
   return false //Valid Number
}
function IsColor(iobj){ //Color Validation
   var myString = iobj
   var inThere = myString.match(/\#([0-9a-fA-F]){6}/g)
   if (inThere) 
	  return true //Valid Color
   return false //Invalid Color
}
function IsFloat(iobj){ //Float Validation
   var myString = iobj
   var inThere = myString.match(/^((\d{0,3}(\,\d{3})*)|(\d)+)\.\d{0,2}$/g)
   if (inThere) 
      return true //Invalid number
   return false //Valid Number
}
function IsInt(iobj){ //Float Validation
   var myString = iobj
   var inThere = myString.match(/^((\d{0,3}(\,\d{3})*)|(\d)+)$/g)
   if (inThere) 
      return true //Invalid number
   return false //Valid Number
}

var julianDate;

function Julian(yr, mt, dy){    
  if (mt < 3) {            // January & February to be considered as  
    mt = mt + 12           // 13th & 14th month
    yr = yr - 1            // of previous year
   } 
   
  var years = Math.floor((4712 + yr) * 365.25)              // days of full years since -4712  
  var leaps = Math.floor(yr / 100) - Math.floor(yr / 400)   // calculate invalid leap days
  var mnths = Math.floor(((mt - 1) * 30.6) + 0.2)           // days of full months
  return years - leaps + mnths + dy;                        
}

function IsDate(dateStr) {
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?
    var monthname=""
    if (matchArray == null) {
        alert("Please enter date as either mm/dd/yyyy.");
        return false;
    }

    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[5];
	
	julianDate  = Julian(parseInt(year),parseInt(month),parseInt(day));

    if (month < 1 || month > 12) { // check month range
        alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        alert("Day must be between 1 and 31.");
        return false;
    }
	if (month == 2)monthname="February";
	else if (month == 4)monthname="April";
	else if (month == 6)monthname="June";
	else if (month == 9)monthname="September";
	else if (month == 11)monthname="November";

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        alert(monthname+" doesn't have 31 days!")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            alert(monthname + " " + year + " doesn't have " + day + " days!");
            return false;
        }
    }
    return true; // date is valid
}
function InvTimeDiff(a,b,c,d){
   sdur = (parseInt(a) * 60)+parseInt(b)
   edur = (parseInt(c) * 60)+parseInt(d)
   if (parseInt(edur)>=parseInt(sdur))
      return false
   return true
}
function IsMilTime(timeStr) {
    var tstr = timeStr
	var timePat = /^(\d{1,2}):(\d{2})$/;
	var tres = tstr.match(timePat)
	if (tres) {
   	   var hh = parseInt(tres[1]);
       var mm = parseInt(tres[2]);
	   if ((hh>24) || (mm>59)) {
          return false
	   }
	   else if((hh==24) && (mm!=0)){	
	        return false
	   } 
	}
	else return false
		return true
}

function IsTime(tymStr) {
    var tymfrm = /^(\d{1,2})(\:)(\d{1,2})(\ am| AM| pm| PM)$/;
    var matchArray = tymStr.match(tymfrm); // is the format ok?

    if (matchArray == null) {
        alert("Please enter time as either hh:mm am/pm.");
        return false;
    }
      hour = matchArray[1]; 
      minute = matchArray[3];
   	 
    if (hour < 1 || hour > 12 ||  minute > 59) { // check month range
        alert("Invalid time.");
        return false;
     
     }
     return true; //Time is valid
}
function DateDiff(date1,date2){ //from,to
 
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray1 = date1.match(datePat); // is the format ok?
    var matchArray2 = date2.match(datePat); // is the format ok?

    mm1 = matchArray1[1]; // parse date into variables
    dd1 = matchArray1[3];
    yy1 = matchArray1[5];
    mm2 = matchArray2[1]; // parse date into variables
    dd2 = matchArray2[3];
    yy2 = matchArray2[5];
    var dat2 = new Date(mm2 + "/" + dd2 +"/" + yy2)
    var dat1 = new Date(mm1 + "/" + dd1 +"/" + yy1)
	var diff = new Date()
	diff=dat2.getTime() - dat1.getTime();
    days = Math.floor(diff / (1000 * 60 * 60 * 24)); 
	return days
}
function displayAlert() {   
	 errhnd=false
 }   
function displayerror(){
	errhnd=true
}
function testimage(J){
	errhnd=false
	imageA = new Image(100,100)
	imageA.onload=displayAlert
	imageA.onerror=displayerror
	imageA.src=J
}

function chkimg(imgname,nnflag,noneflag){
var imgsrc,imgold,imgpath,nflag

    imgpath = document.form1.imgpath.value
    eval('imgsrc=document.form1.'+imgname+'.value')
	eval('imgold=document.form1.h'+imgname+'.value')
	if (noneflag=="1"){
	   eval('nflag=document.form1.n'+imgname+'.checked')
	   if (nflag==true){
	      imgsrc="none"
	   }
	}
    if (imgsrc=="none") {
	   if (nnflag=='1'){
          alert('Please enter a valid Image File!')
		  errhnd=true
		  return false
	   }
	   eval('document.images["d'+imgname+'"].src="'+imgpath+'nopic.gif"')
	   eval('document.form1.h'+imgname+'file.value=imgsrc')		   
	   eval('document.form1.n'+imgname+'.checked=true')
	  // eval('alert(document.form1.h'+imgname+'file.value)')
	   return false
	}
    if(IsNull(imgsrc)){
	   if (imgold=="nopic.gif")
  		  eval('document.form1.n'+imgname+'.checked=true')
	   eval('document.images["d'+imgname+'"].src="'+imgpath+imgold+'"')
	   eval('document.form1.h'+imgname+'file.value=imgsrc')		   		   
	   return false
	}
    else if (!IsNull(imgsrc)){
	 	if (document.getElementById&&!document.all){
		   imgsrc = "file:///" + strreplace(imgsrc,"\\","/")
		}
		ext= imgsrc.substr(imgsrc.lastIndexOf(".")+1)
		if ((ext.toUpperCase()!="JPG") && (ext.toUpperCase()!="JPE") && (ext.toUpperCase()!="JPEG") && (ext.toUpperCase()!="GIF") && (ext.toUpperCase()!="PNG")){
	       alert('Please enter a valid Image File!')
	       errhnd=true
		   return false
		}
		if ((document.getElementById&&!document.all)||(document.all))
	        testimage(imgsrc)	   
	    if (errhnd) {
	       alert('Please enter a valid Image File!')
	       errhnd=true
		   return false
	    }
		else {
		//  alert('document.images["d'+imgname+'"].src="'+imgsrc+'"')
    	   if ((document.getElementById&&!document.all)||(document.all))
			   eval('document.images["d'+imgname+'"].src=imgsrc')
		   eval('document.form1.h'+imgname+'ext.value=ext')
		   eval('document.form1.h'+imgname+'file.value=imgsrc')
		   eval('document.form1.n'+imgname+'.checked=false')
		   return false
		}
    }   
}
function vldchk(tf){
 if (tf.chkid.checked){
   if (tf.ctr.value==1){
      tf.deid.checked=true
   }
   else if(tf.ctr.value>1) {
    for (i = 0; i < tf.deid.length; i++)
			tf.deid[i].checked = true ;
   }
 }
 else {
   if (tf.ctr.value==1){
      tf.deid.checked=false
   }
   else if(tf.ctr.value>1) {
    for (i = 0; i < tf.deid.length; i++)
			tf.deid[i].checked = false ;
   }
 }
}

function deidchk(tf){
 var tctr, fctr;
 tctr = 0;
 fctr = 0;
    if (tf.ctr.value==1){
		if (tf.deid.checked){
			tf.chkid.checked = true;
		} else { 
			tf.chkid.checked = false;
		}
	} else {
		for (i = 0; i < tf.deid.length; i++){
			if	(tf.deid[i].checked){
				tctr = tctr + 1
			} else { 
				fctr = fctr + 1 
			}
		}
		if (tf.ctr.value==tctr){
			tf.chkid.checked = true;
		} else tf.chkid.checked = false;
	}	
}

function checkbox(){
   var checkb = false
   if (document.form1.ctr.value==1){
      if(document.form1.deid.checked)
	     checkb = true
   }
   else if(document.form1.ctr.value>1) {
    for (i = 0; i < document.form1.deid.length; i++)
			if(document.form1.deid[i].checked)
 	   	      checkb = true
    }
    if (!(checkb)){
	   alert('Please check at least one record.')
	   return false
	}
	
  return true
}

function delcon() {
   condel = false
   if (document.form1.ctr.value==1){
      if(document.form1.deid.checked)
	     condel = true
   }
   else if(document.form1.ctr.value>1) {
    for (i = 0; i < document.form1.deid.length; i++)
			if(document.form1.deid[i].checked)
 	   	      condel = true
    }
    if (condel){
      if (confirm("Do you really want to delete your record(s)?")){
          document.form1.submit()
	  }	  
	}
	else 
	   alert('Please check the record(s) to be deleted!')
} 
function delrec(a){
   if (delrec!=""){
      if(confirm("Do you really want to delete your record?")){
	     document.form1.delid.value=a
		 document.form1.submit()
	  }
   }
}
function opennewwindow(mypage,h,w,n,winname){
  if ((IsNull(h)) || (IsNull(w)) || (IsNull(n)) || (IsNotNumber(h)) || (IsNotNumber(w)) || ((n!="no")&&(n!="yes")))
     prpty=""
  else {
     locx = (screen.width - w)/2; 
     locy = (screen.height - h)/2; 
     prpty="status=no,resizable=no,height="+h+",width="+w+",left="+locx+",top="+locy+",menubar=no,toolbar=no,scrollbars=" + n
  }
  if (IsNull(winname))
     wn = null
  else
     wn = winname
  if (!IsNull(mypage)){	 
	 mywin =  window.open(mypage,wn,prpty)
	 mywin.focus()
  }
}
function strreplace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += strreplace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}

//start popup calendar
function popupcalendar(datefield,nextfield){
		showCalendar(datefield,'mm/dd/yyyy','Choose date',nextfield); 
}

function doNothing(){
	;
}
//end popup calendar

function txtNum_onKeypress(){
	var string="1234567890";
	if (string.indexOf(unescape('%' + window.event.keyCode.toString(16))) != -1) 
		window.event.returnValue = true;
	else
		window.event.returnValue = false;
}

function txtNum_onKeypress(){
	var string="1234567890.";
	if (string.indexOf(unescape('%' + window.event.keyCode.toString(16))) != -1) 
		window.event.returnValue = true;
	else
		window.event.returnValue = false;
}

function txtDate_onKeypress(){
	var string="1234567890/";
	if (string.indexOf(unescape('%' + window.event.keyCode.toString(16))) != -1) 
		window.event.returnValue = true;
	else
		window.event.returnValue = false;
}
