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 showpageinwawindow(url)
{
	window.open(url,"wa");
}

//
function ValidatorTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
}

//
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){
	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 : mm/dd/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
}

function checkEmail(strng)
{
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(strng) == false) {
      return false;
   }else return true;
	   
}

function checkPassword (strng) 
{
	var error = "";
	var illegalChars = /[\W_]/; 
	if (strng == "") 
	{
		error = "You didn't enter password.\n";
	}
	
	if ((strng.length < 4) || (strng.length > 15)) 
	{
  		error = "The password is of wrong length(valid length 4-15 chars).\n";
	}
	else if (illegalChars.test(strng)) 
	{
		error = "The password contains illegal characters.\n";
	}
	return error;
}

function chkselectedids(formname,objname)
{
	var chkflg,strmessageid,url,returl;
	strmessageid="";
	chkflg=false;
	for(j=0; j<document.forms.length;j++)
	{
		if(document.forms[j].name==formname)
		{
			for (i=0;i<document.forms[j].elements.length;i++)
			{
				if (document.forms[j].elements[i].name==objname) 
				{
					if (document.forms[j].elements[i].checked)
					{							
						chkflg=true;
						break;
					}
				}
			}			
		}	
	}
	return chkflg;	
}

function isAlphabetic(val) {
	
	if (val.match(/^[a-zA-Z]+$/)) {
		return true;
	}
	else {
		return false;
	}	
}


// check to see if input is alphanumeric with space
function alphaNumericValidator(str) {
// if empty fields are invalid,
// replace the * by a +
// * = if any or more
// + = 1 or more
// \w = a letter (= [a-zA-Z])
// \d = a number (= [0-9])
// \s = white space (= [ \n\r\t])
// \n = new line
// \r = carriage return
// \t = tabs
// ^ = the beginning of the string
// $ = the end of the string
//
// [\w\d\s] = [a-zA-Z0-9 \n\r\t]
return /^[\w\d\s]*$/.test(str);
}

// check to see if input is alphanumeric with space ,Appostrophy and Hyphen
function alphaNumericAppostrophyHyphen(str) 
{
	return /^[a-zA-Z\.-]$/.test(str);
	
}
function removeSpaces(string) {
   var newString = '';
   for (var i = 0; i < string.length; i++) {
      if (string.charAt(i) != ' ') newString += string.charAt(i);
   }
   return newString;
}

//function to open in custom window
function openWindow(url,window_name,winWidth,winHeight,fscroll,resize) {
	sWidth = screen.availWidth;
	sHeight = screen.availHeight;
	
	sLeft = (sWidth - winWidth) / 2;
	sTop = (sHeight - winHeight) / 2;
	if(fscroll == '') {fscroll = 0}
	if(resize == '') {resize = 'no'}
	
	window.open(url,window_name,"width=" + winWidth + ",height=" + winHeight + ",top=" + sTop + ",left=" + sLeft + ",toolbar=0,menubar=0,status=0,scrollbars=" + fscroll + ",resizable="+resize);
}

//function to open image in custom window
function openImage(url,window_name,winWidth,winHeight,fscroll,resize) {
	sWidth = screen.availWidth;
	sHeight = screen.availHeight;
	
	sLeft = (sWidth - winWidth) / 2;
	sTop = (sHeight - winHeight) / 2;
	if(fscroll == '') {fscroll = 0}
	if(resize == '') {resize = 'no'}
	
	winId = window.open('',window_name,"width=" + winWidth + ",height=" + winHeight + ",top=" + sTop + ",left=" + sLeft + ",toolbar=0,menubar=0,status=0,scrollbars=" + fscroll + ",resizable="+resize);
	
	with (winId.document) {
		write('<html><title>'+url+'</title><head><style>body {margin-left:0px;margin-top: 0px;margin-right: 0px;margin-bottom: 0px;}</style></head>');
		write('<body onLoad="window.focus();" >');
		write('<div align="center"><img src="'+url+'"></div>');
		write('</body></html>');
		close();
	}
	
}

// Checks the first occurance of spaces and removes them
function trimSpaces(stringValue) {
	for(i = 0; i < stringValue.length; i++) {
		if(stringValue.charAt(i) != " ") {
			break;
		}
	}
	if(i > 0) {
		stringValue = stringValue.substring(i);
	}
	
	// Checks the last occurance of spaces and removes them
	strLength = stringValue.length - 1;
	for(i = strLength; i >= 0; i--) {
		if(stringValue.charAt(i) != " ") {
			break;
		}
	}
	if(i < strLength) {
		stringValue = stringValue.substring(0, i + 1);
	}
	
	// Returns the string after removing leading and trailing spaces.
	return stringValue;
}
function Trim(TXT)
{
	return TXT.replace(/(^\s+)|(\s+$)/g,"");
}

//Convert the date in "DD/MM/YYYY" to "YYYY-MM-DD"
function changeDateformat(datestr) {
	var retarray = datestr.split("/");
	return(retarray[2] + "-" +  retarray[1] + "-" + retarray[0]);
}

//function to compare dates
/*
		0 - date1 less than date2
		1 - date1 greater than date2
		2 - date1 =  date2
		-1 - not valid dates
*/
function compare2Dates(date1,date2)
{
	// assumes that dates are in the format YYYY-MM-DD
	varDate = date1.split("-");
	day = trimSpaces(varDate[2]); 
	month = trimSpaces(varDate[1]); 
	year = trimSpaces(varDate[0]); 
	d1 = new Date(year,month-1,day).getTime();

	varDate = date2.split("-");
	day = trimSpaces(varDate[2]); 
	month = trimSpaces(varDate[1]); 
	year = trimSpaces(varDate[0]);
	d2 = new Date(year,month-1,day).getTime();
	 
	if (d1==0 || d2==0)
	{
		return -1;
	}
	else if (d1 > d2) 
	{
		return 1;
	}
	else if (d1 == d2) 
	{
		return 2;
	}
	return 0;
}

//function limitText used to limit text in a textarea
function limitText(field,maxlimit,remark) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	}
	else {
		if(remark) {
			remark.value = maxlimit - field.value.length;
		}
	}	
}

function isValidIPAddress(ipaddr) {
	   var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
	   if (re.test(ipaddr)) {
		  var parts = ipaddr.split(".");
		  if (parseInt(parseFloat(parts[0])) == 0) { return false; }
		  for (var i=0; i<parts.length; i++) {
			 if (parseInt(parseFloat(parts[i])) > 255) { return false; }
		  }
		  return true;
	   } else {
		  return false;
	   }
	}

function dateTimeDiff( start, end, interval, rounding ) {

    var iOut = 0;

    // Create 2 error messages, 1 for each argument. 
    var startMsg = "Check the Start Date and End Date\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var bufferA = Date.parse(start) ;
    var bufferB = Date.parse(end) ;
    	
    // check that the start parameter is a valid Date. 
    if ( isNaN (bufferA) || isNaN (bufferB) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }
    
    var number = bufferB-bufferA ;

    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            iOut = parseInt(number / 86400000) ;
            if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            break ;
        case 'h': case 'H':
            iOut = parseInt(number / 3600000 ) ;
            if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
            break ;
        case 'm': case 'M':
            iOut = parseInt(number / 60000 ) ;
            if(rounding) iOut += parseInt((number % 60000)/30001) ;
            break ;
        case 's': case 'S':
            iOut = parseInt(number / 1000 ) ;
            if(rounding) iOut += parseInt((number % 1000)/501) ;
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    
    return iOut ;
}



function DtDiff(date1, date2) {
   dte1 = new Date(Date.parse(date1));
   dte2 = new Date(Date.parse(date2));

    if (isNaN (dte1) || isNaN (dte2) ) {
        alert("Invalid date parameters") ;
        return null ;
    }


   diff = Math.abs(dte1.getTime() - dte2.getTime());

	days = 0;
	hours = 0;
	minutes = 0;
	seconds = 0;
  if((diff % 86400000) > 0)
   {
       rest = (diff % 86400000);
       days = (diff - rest) / 86400000;
       
       if((rest % 3600000) > 0 )
       {
           rest1 = (rest % 3600000);
           hours = (rest - rest1) / 3600000;
     

           if((rest1 % 60000) > 0 )
           {
               rest2 = (rest1 % 60000);
               minutes = (rest1 - rest2) / 60000;
               seconds = rest2/1000;
           }else{
               minutes = rest1 / 60000;
		   }
      }else{
           hours = rest / 3600000;
	   }
   }else{
       days = diff / 86400000;
	}

	var retarray = new Array(4);
	retarray[0]= days;
	retarray[1]= hours;
	retarray[2]= minutes;
	retarray[3]= seconds;
	return retarray;
}





//Convert the date in "DD/MM/YYYY" to "MM/DD/YYYY"
function changeDateformatFromCal(datestr) {
	var retarray = datestr.split("/");
	return(retarray[1] + "/" +  retarray[0] + "/" + retarray[2]);
}


//convert ddm-mmm-yyyy To yyyy-mm-dd;
function ddmmmyyyyToDBdate(datestr) {
	var retarray = datestr.split("-");
	var arrMonth = new Object();
	arrMonth["Jan"] = {value:"01",text:"January"};
	arrMonth["Feb"] = {value:"02",text:"February"};
	arrMonth["Mar"] = {value:"03",text:"March"};
	arrMonth["Apr"] = {value:"04",text:"April"};
	arrMonth["May"] = {value:"05",text:"May"};
	arrMonth["Jun"] = {value:"06",text:"June"};
	arrMonth["Jul"] = {value:"07",text:"July"};
	arrMonth["Aug"] = {value:"08",text:"August"};
	arrMonth["Sep"] = {value:"09",text:"September"};
	arrMonth["Oct"] = {value:"10",text:"October"};
	arrMonth["Nov"] = {value:"11",text:"November"};
	arrMonth["Dec"] = {value:"12",text:"December"};
	var month = arrMonth[retarray[1]];
	return(retarray[2] + "-" + month.value + "-" + retarray[0]);
}


function printSetup(pageName) {
	var arrPageName = new Array('im') ;
	var flag = 0;
	
	for(var i=0; i < arrPageName.length; i++) {
		if(arrPageName[i] == pageName) {
			flag = 1;
			break;
		}
	}
	
	if (flag == 0) return false;
	hideMe();
	var a = document.all.item("noPrint");

	if (a!=null) {
		if (a.length!=null) {
			for (i=0; i< a.length; i++) {
				a(i).style.display = window.event.type == "beforeprint" ? "none" :"inline";
			}
		} 
		else { 
			a.style.display = window.event.type == "beforeprint" ? "none" :"inline";
		}
	}

	if( window.event.type == "afterprint") {
		var hidemenu = readCookie("hidemenu");
		if (hidemenu == 1 && document.getElementById("sideMenu"))
		{
			hideMe();
		}
		else {
			showMe();
		}
	}
} 

function roundNumber(val,precision) {
	var newVal = Math.round(val*Math.pow(10,precision))/Math.pow(10,precision);
	return newVal ;
}

//function:minuteToHM - convert minute to hour:minute
function minuteToHM(minute) {
	var sign = "";
	if(minute < 0) {
		sign = "-";
	}	

	var minute = parseInt(Math.abs(minute));

	var hour = parseInt(minute/60);
	var fract = minute % 60;
	var hh = hour;
	var mm = Math.floor(fract);

	if (hh <= 9) hh = "0"+hh ;
	if (mm <= 9) mm = "0"+mm ;
	
	return sign+hh+":"+mm ;	
}

// functions used for auto complete drop down
var keyTime, keyStr = '', lastKey;
var agt=navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));

function setSelection(element)
{
  
  if(is_ie)
  {
    var currentKey = unescape('%' + window.event.keyCode.toString(16)).toLowerCase();
    var idx, currentSIdx = element.selectedIndex;
    var newTime = new Date().getTime();
    if(keyTime != null && newTime - keyTime < 500) // if two keys were pressed between 0.3 seconds (can be customized), do type-ahead
    {
      keyStr += currentKey;
      idx = findIdx(element);
    }
    else // unfortunately we seem to have to handle default browser behavior too
    {
      keyStr = currentKey;
      var selectFirst = true;
      if(keyStr == lastKey)
      {
        idx = currentSIdx + 1;
        if(idx < element.options.length && element.options[idx].text.charAt(0) == lastKey)
          selectFirst = false;
      }
      if(selectFirst) idx = findIdx(element);
      lastKey = currentKey;
    }
    if(idx >= 0)
    {
		element.options[currentSIdx].selected = false;
     	element.options[idx].selected = true;
    }
  }
  
}

function findIdx(element)
{
  var idx = -1, len = keyStr.length;
  for(var i = 1; i < element.options.length; i++)
  {
    var str = element.options[i].text.toLowerCase();
	str = str.substring(0, len); 
	if(keyStr == str) { idx = i; break }
  }
  return idx;
}

function setTime()
{
  keyTime = new Date().getTime();
  return false;
}


//Convert the date in "MM/DD/YYYY HH:MM:SS" to "DD-MMM-YYYY HH:MM:SS"
function jsDateToMydate(datestr) {
	var m_names = new Array("", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov","Dec");
	var retarray = datestr.split("/");
	return(retarray[1] + "-" +  m_names[parseInt(retarray[0])] + "-" + retarray[2]);
}

// allows only numeric
function numericOnly(e) {
	if(window.event) {
		key = e.keyCode; // for IE, e.keyCode or window.event.keyCode can be used
	}
	else if(e.which) {
		key = e.which; // netscape
	}
	else {
		return true;// no event, so pass through
	}
	
	if( ((key>45) && (key<58)) || (key == 8) ) {
		return true; 
	}
	else {
		return false;
	}
	
}

// to set focus on default control
function setFocus() {
	var frm = document.forms[0];
	if(frm) { 
		for(i=0; i < frm.elements.length; i++) {
			if(frm.elements[i].type == "text" || frm.elements[i].type == "password" || frm.elements[i].type == "textarea" || frm.elements[i].type == "button"){
				if(frm.elements[i].disabled == false) {
					frm.elements[i].focus();
					return true;
				}			
			}
		}
	}
											 
}

//  check for valid numeric strings	
function IsNumeric(strString)   
{
	var testExp = /^\d+\.?\d*$/ ;
	
	if(testExp.test(strString)) {
		return true;
	}
	else {
		false;
	}	
	
}
/////////For integer value
 function isNumberKey(evt)
  {
	 var charCode = (evt.which) ? evt.which : event.keyCode
	 if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	 else
		return true;
  }                            
//////////////////////////////
//return the value of the radio button that is checked
//return an empty string if none are checked, or
//there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}
