
// Numeric validation
var OrigNumberClassName;

function OnlyDigits(myfield,e,extraChars)
{ // Only numbers and one dot is allowed:
  var keycode;
  var extraCh = new String(extraChars);
  if (window.event) {keycode = window.event.keyCode;}
  else if (e) {keycode = e.which;}
  else {return true;}
  if (((keycode>47) && (keycode<58))  || (keycode==8)) { return true; }
  else 
  { //see, if stroked key is in extra characters... 
    if ((extraCh.indexOf(String.fromCharCode(keycode))>-1) && (myfield.value.indexOf(String.fromCharCode(keycode))<0))
	{ return true; } 
	else
    {  // change color into error color
	if (!(myfield.className=="inpnumbererror")) { OrigNumberClassName=myfield.className; }
	   changeStyle(myfield, "inpnumbererror");
	   // and a little later change it back...
	   setTimeout("changeStyle(document."+myfield.form.name+"."+myfield.name+", '"+OrigNumberClassName+"')",500);
	   window.event.returnValue=false; 
	   return false; 
	}
  }
  return false;
}

function changeStyle(myfield, mystyle)
{
//alert(myfield.name+'->'+mystyle);
  myfield.className=mystyle;
  return true;
}

// Stuff to date validate
// ===============
var dateformat=new String;
var datesepar="?";
var valuebefore=new String;
// to store the year, month, day
var datey=new String;
var datem=new String;
var dated=new String;
// date element positions in format mask
var yp=0;
var mp=0;
var dp=0;
// date element lengths in format mask
var yl=0;
var ml=0;
var dl=0;
// make a valid date from the invalid one just for the possibility of later use
var makeitvaliddate=new String;
// should we make a date validation on the fly ?
var dodatevalidation=false;

var selectRange;

function DateInputOnSelect()
{
if (dodatevalidation) 
   document.selection.createRange().execCommand('Unselect')
}

function CrtKeyUpEvent(myfield,key) {
    var eventObj = document.createEventObject();
    eventObj.keyCode = key;
    eventObj.cancelBubble = true;
    myfield.fireEvent("onkeyup",eventObj);
//    event.cancelBubble = false;
}

function beforeenter(myfield,e)
{ // check (and reject invalid) character inputs into date type items
var keycode;
selectRange=document.selection.createRange().duplicate();
var selectRange2=document.selection.createRange().duplicate();
if (window.event) {keycode = window.event.keyCode;}
else if (e) {keycode = e.which;}
else {return true;}
//window.status="["+keycode+"]";
if (((keycode>47) && (keycode<58)) || (String.fromCharCode(keycode)==datesepar) || (keycode==8)) 
{ // here we insert the new character, but not in the average way...
  if (dodatevalidation) // date validation on the fly ?
  {
  var valuebeforeupdate=new String(myfield.value);
  selectRange2.expand('character'); //select the next character at the cursor
  if (keycode==8)
     { keycode=48; //on deletion just make it zero
     } 
     else
     { selectRange2.expand('character'); //select the next character at the cursor
     }
  if (selectRange2.text==datesepar)
     { // no number allowed at the position of date separator character
       selectRange2.text=datesepar; // replace it with the new one
     }
     else
    { if ((!(selectRange2.text==datesepar)) && (!(String.fromCharCode(keycode)==datesepar))) // no date separator allowed at number pos
      { selectRange2.text=String.fromCharCode(keycode); } // replace it with the new one
    }
  //.selectRange2.empty; // ok, we have the new string, let us see, if it is valid date...
  if (!validDate(myfield.value)) 
  { // if not, reject the update
    // if it is better to write back the preveous value, uncomment this line and comment the next one
    //myfield.value=valuebeforeupdate; 
    //myfield.value=makeitvaliddate;
  
    selectRange2.expand('textedit');
    selectRange2.text=makeitvaliddate;
    // selectRange.expand('character');
    // selectRange.text=String.fromCharCode(keycode);
  }
  return false; 
  //.if (keycode==8) // deletion can go on the old way
  //.{ //return true;  // I wish this would has any effect... but it has not 
  //.  if (window.event) {window.event.returnValue=false;}
  //.  else if (e) {keycode = e.returnValue=false;}
  //.}
  //.else 
  return false; // no other characters allowed
  } // (dodatevalidation)
  else // no date validation
  { return true
  } // (dodatevalidation) else
} // (((keycode>47) && (keycode<58)) || (String.fromCharCode(keycode)==datesepar) || (keycode==8))
}

function DateInputOnBlur(myfield)
{ oldvalue=myfield.value;
  if (!validDate(myfield.value))
  { //if ()
    myfield.className="inpdateerror";
    myfield.value=makeitvaliddate;
    alert(oldvalue+" is an invalid date\n replaced with "+makeitvaliddate);
    myfield.focus();
    return false;
  } else
  {myfield.className="inpdate";
  }
  window.status='';
  return true;
}

function onmovein(val,format)
{ // we are moving into the date field, so we have to prepare the page to stop
  // the useriod enter stupidity
 // dateitemname=name;
  window.status='Date format : '+format;
  for (var i=0; i<val.length; i++)
  { 
    if (!((format.substr(i,1)=='Y') || (format.substr(i,1)=='M') || (format.substr(i,1)=='D') || (format.substr(i,1)==" ")))
    { datesepar=format.substr(i,1); }
  }
  // set the initial values in case of there were another date field before this...
  yp=0;
  mp=0;
  dp=0;
  yl=0;
  ml=0;
  dl=0;
  nextfree=1;
  for (var i=0; i<format.length; i++)
  { // positions of year/month/day character groups in the format mask:
    if (format.charAt(i)=='Y' && yp==0)
    { yp=nextfree;
      nextfree++;
    }
    if (format.charAt(i)=='M' && mp==0)
    { mp=nextfree;
      nextfree++;
    }
    if (format.charAt(i)=='D' && dp==0)
    { dp=nextfree;
      nextfree++;
    }
    if (format.charAt(i)=='Y')
    { yl++; }
    if (format.charAt(i)=='M')
    { ml++; }
    if (format.charAt(i)=='D')
    { dl++; }
  }
  dateformat=format;
// for debug
window.status='dateformat='+dateformat+' datesepar='+datesepar;
// for debug
}

function getEl(val,pos)
{ // get the year, month or day from the text item
  var retval=new String;
  if (pos==1)
  { retval=val.substr(0,val.indexOf(datesepar)); }
  if (pos==2)
  { retval=val.substr(val.indexOf(datesepar)+1,20);
    retval=retval.substr(0,retval.indexOf(datesepar));
  }
  if (pos==3)
  { retval=val.substr((val.lastIndexOf(datesepar)+1),(val.length-val.lastIndexOf(datesepar)+1));
  }
  return retval;
}

function validDate(val)
{ // if beforeenter was accepted the inserted character, we
  // should check if it is fitting into the format mask ...
  var daysinmonths=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  datey=getEl(val,yp);
  datem=getEl(val,mp);  
  dated=getEl(val,dp);
//alert(val+"  :"+datey+"."+datem+"."+dated+"  "+datesepar);
  newVal=new Array(new String,new String,new String);
  newVal[yp-1]=datey.substr(0,yl);
  newVal[mp-1]=datem.substr(0,ml);
  newVal[dp-1]=dated.substr(0,dl);
  if (isNaN(parseInt(newVal[mp-1],10)) || (parseInt(newVal[mp-1],10)<=0)) { newVal[mp-1]="01"; }
  if (isNaN(parseInt(newVal[dp-1],10)) || (parseInt(newVal[dp-1],10)<=0)) { newVal[dp-1]="01"; }
  if (isNaN(parseInt(newVal[yp-1],10)) || (parseInt(newVal[yp-1],10)<=0)) { newVal[yp-1]="2003"; }
  if (newVal[yp-1].length<yl) // if shorter than 4 chars (yl-year length), make it yl chars length with leading zeros
     {newVal[yp-1]=String('2000').substr(0,yl-newVal[yp-1].length)+newVal[yp-1];}
  if (newVal[mp-1].length<ml) // if shorter than 2 chars (ml-month length), make it ml chars length with leading zeros
     {newVal[mp-1]=String('00').substr(0,ml-newVal[mp-1].length)+newVal[mp-1];}
  if (newVal[dp-1].length<dl) // if shorter than 2 chars (dl-day length), make it dl chars length with leading zeros
     {newVal[dp-1]=String('00').substr(0,dl-newVal[dp-1].length)+newVal[dp-1];}
  if (String(parseInt(newVal[yp-1],10)/4).indexOf('.')>=0) // if it is not an integer, than it is a non-leap year
  { daysinmonths[1]=28; }
  else
  { daysinmonths[1]=29; }
  if (parseInt(newVal[mp-1],10)>12) { newVal[mp-1]="12"; }
  if (parseInt(newVal[dp-1],10)>parseInt(daysinmonths[parseInt(newVal[mp-1]-1)])) 
  { newVal[dp-1]=parseInt(daysinmonths[parseInt(newVal[mp-1],10)-1],10); }
  makeitvaliddate=newVal[0]+datesepar+newVal[1]+datesepar+newVal[2];
  return (val==newVal[0]+datesepar+newVal[1]+datesepar+newVal[2]);
}


function afterentered(val)
{ // if beforeenter was accepted the inserted character, we
  // should check if it is fitting into the format mask ...
  var daysinmonths=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  datey=getEl(val.value,yp);
  datem=getEl(val.value,mp);  
  dated=getEl(val.value,dp);
  newVal=new Array(new String,new String,new String);
  newVal[yp-1]=datey.substr(0,yl);
  newVal[mp-1]=datem.substr(0,ml);
  newVal[dp-1]=dated.substr(0,dl);
  if (isNaN(parseInt(newVal[mp-1],10)) || (parseInt(newVal[mp-1],10)<0)) { newVal[mp-1]="01"; }
  if (isNaN(parseInt(newVal[dp-1],10)) || (parseInt(newVal[dp-1],10)<0)) { newVal[dp-1]="01"; }
  if (isNaN(parseInt(newVal[yp-1],10)) || (parseInt(newVal[yp-1],10)<0)) { newVal[yp-1]="2003"; }
  //window.status="["+(parseInt(newVal[yp-1],10)/4)+" / "+(parseFloat(newVal[yp-1])/4)+"]";
  if (String(parseInt(newVal[yp-1],10)/4).indexOf('.')>=0)
  { daysinmonths[1]=28; }
  else
  { daysinmonths[1]=29; }
  if (parseInt(newVal[mp-1],10)>12) { newVal[mp-1]="12"; }
  if (parseInt(newVal[dp-1],10)>parseInt(daysinmonths[parseInt(newVal[mp-1],10)],10)) { parseInt(daysinmonths[parseInt(newVal[mp-1],10)],10); }
  val.value=newVal[0]+datesepar+newVal[1]+datesepar+newVal[2];
  // store the last accepted input text, if the next 
  valuebefore=val.value;
}

function KeyCheck(myfield,e)
{
var keycode;
if (window.event) {keycode = window.event.keyCode;}
else if (e) {keycode = e.which;}
else {return true;}
if (((keycode>47) && (keycode<58))  || (keycode==8) || ((keycode==46) && myfield.value.indexOf('.')<0)) { return true; }
else { return false; }
}

function DateCheck(myfield,e,dateformat)
{
  if (window.event) {keycode = window.event.keyCode;}
  else if (e) {keycode = e.which;}
  else {return true;}
}

function osel(val)
{ //document.ppp.B1.value=document.getSelection();
}

function keyup(val) //Karakterbevitel utan
{ alert("keyup "+val+" "+document.ppp.T1.value);}

var isIE = document.all?true:false;
var isNS = document.layers?true:false;
var eredeti = "";
function NumericEllenor(e)
{ if (isIE) 
  {  alert("IE");
     return NumericEllenorIE(event.keyCode); 
  }
  if (isNS) 
  {  document.ppp.T1.value="NS";
     return NumericEllenorNS(e.keyCode+'/'+e.which);
  }
}

function NumericEllenorIE(w)
{  
   return ((w==8) || ((w>=48) && (w<=57)) || ((w==46) && document.ppp.T1.value.indexOf('.')<0));
}

function NumericEllenorNS(ff)
{   return ((ff=='46/0') || (ff=='8/8') || (ff=='37/0') || (ff=='39/0') || 
          ((ff=='0/46') && (document.ppp.T1.value.indexOf('.')<0)) || ((ff>='0/48') && (ff<='0/57')));
}

//Menu handling routines:
function handlerMenuMouse(e){
x =  event.clientX;
y =  event.clientY;
}


function repaintMenu(obj, el, px, py, enabled)
{
var flatStyle;
var hiliteStyle;
var x,y;
var menuSrc1;
 hiliteStyle = findStyleRule(".menuhilite");
 disableStyle = findStyleRule(".menudisabled");

  // repaint root menu item
  if (enabled)
  {
  obj.style.backgroundColor=hiliteStyle.style.backgroundColor;
  obj.style.color=hiliteStyle.style.color;
  } else
  {
  obj.style.backgroundColor=disableHiliteStyle.style.backgroundColor;
  obj.style.color=disableHiliteStyle.style.color;
  }
  // show submenu, if exists
  if ((px+py)>0) { showSubMenu(el, px, py); }
}

function unpaintMenu(obj, enabled)
{
  // unpaint root menu item
 flatStyle = findStyleRule(".menutext");
 disableHiliteStyle = findStyleRule(".menudisabledhilite");
  if (enabled)
  {
  obj.style.backgroundColor=flatStyle.style.backgroundColor;
  obj.style.color=flatStyle.style.color;
  } else
  {
  obj.style.backgroundColor=disableStyle.style.backgroundColor;
  obj.style.color=disableStyle.style.color;
  }
}

function showSubMenu(el, px, py) {
  whichEl = eval("menuSrcA" + el);
// menu image :??  whichIm = eval(el+"Img");
//  if (whichEl.style.display == "none") {
//    whichEl.style.display = "block";
//    // menu image :??  whichIm.src = "images/minus.gif";
//  }
//  else {
//    whichEl.style.display = "none";
//    // menu image :??  whichIm.src = "images/plus.gif";
//  }
  ChildMenu.innerHTML="";
  for (i=0;i<whichEl.length;i++)
    { 
	  if (SubMenuArr[el-1][i]) 
	     { ClassStr="menutext"; 
		   onClickStr=whichEl[i][4];
		   truefalse="true";
		 } 
		 else 
		 { ClassStr="menudisabled"; 
		   onClickStr="";
		   truefalse="false";
		 }
	  ChildMenu.innerHTML=ChildMenu.innerHTML +  
	  " <p class=\""+ClassStr+"\" style=\" margin-top: 0; margin-bottom: 0\" "+
			" onMouseOver=\"repaintMenu(this, '"+whichEl[i][1]+"', "+whichEl[i][2]+", "+whichEl[i][3]+", "+truefalse+")\" "+
			" onMouseOut=\"unpaintMenu(this, "+truefalse+")\""+
			" onClick=\""+onClickStr+"\">"+
    		" "+whichEl[i][0]+"</p> ";
	}
  ChildMenu.style.pixelLeft=px;
  ChildMenu.style.pixelTop=py;
  ChildMenu.style.display = "block";
}

//This SCRIPT tag is for handling menuitems
function findStyleRule(styleName) {
  for (i = 0; i < document.styleSheets.length; i++) { 
    for (j = 0; j < document.styleSheets(i).rules.length; j++) {
      if (document.styleSheets(i).rules(j).selectorText == styleName) {
        return document.styleSheets(i).rules(j);
      }
    }     
  }
}

function depostrophe(thisvalue)
{ var disvalue=thisvalue;
  while (disvalue.search("'")>-1)
  {
     disvalue=disvalue.replace("'","`");
  } 
  return (disvalue)
}

function SortTheList(frm, column_name)
{ if (frm.listorderby.value==column_name)
  { // if the same column has been clicked again -> change direction of sort
      if (frm.listorder.value=='desc')
      { frm.listorder.value='asc'; }
      else
      { frm.listorder.value='desc'; }
  } else 
  { frm.listorder.value='asc'; }
  frm.listorderby.value=column_name;
  frm.submit();
  return true;
}

function emailCheck(emailStr) {
var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
//	alert("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
    // user is not valid
//    alert("The username doesn't seem to be valid.")
    return false
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
//	        alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
//	alert("The domain name doesn't seem to be valid.")
    return false
}

var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
//   alert("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
//   var errStr="This address is missing a hostname!"
//   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}


