/*
General routines used in various places

*/
function toProperCase(s) {
theName = "";
 nameA = s.replace("  "," ").split(" ");
 for(n=0;n<nameA.length;n++) {
   theword = nameA[n].replace("'","`").toLowerCase();
   if (theword.substr(0,2)=="o`") {
    theWord = "O`"+ theword.substr(2,1).toUpperCase()+theword.substr(3);
   } else    if (theword.substr(0,2)=="m`") {
    theWord = "M`"+ theword.substr(2,1).toUpperCase()+theword.substr(3);
   }else if(theword.substr(0,2)=="mc") {
    theWord = "Mc"+theword.substr(2,1).toUpperCase()+theword.substr(3);
     }else if (theword.substr(0,3)=="mac" && (theword.substr(3,1)=='a' ||theword.substr(3,1)=='c' || theword.substr(3,1)=='g')) {
    theWord = "Mac"+theword.substr(3,1).toUpperCase()+theword.substr(4);
     } else {
    theWord = theword.substr(0,1).toUpperCase()+theword.substr(1);
    }
   theName += " "+theWord;
 }
  if (theName !="") {
   theName = theName.substr(1);
  }
  //now deal with hyphens
  nameA = theName.split("-");
  theName2 = nameA[0];
   for(n=1;n<nameA.length;n++) {
   theword = nameA[n];
     theName2 +="-"+theword.substr(0,1).toUpperCase()+theword.substr(1);
   }
 return theName2;
 }
 
function toProperCaseOLD(s)
{
  return s.toLowerCase().replace(/^(.)|\s(.)/g, 
          function($1) { return $1.toUpperCase(); });
}

String.prototype.toProperCaseOLD = function()
{
  return this.toLowerCase().replace(/^(.)|\s(.)/g, 
      function($1) { return $1.toUpperCase(); });
}

function printWindow(winname,thelink) {
    cout = window.open(thelink,winname,"HEIGHT=600,WIDTH=780,status=0,resizable=1,scrollbars=1,menubar=1");
    if ( window.focus )
      cout.focus();

}

function wop(url,wname,p) {
w = window.open(url,wname,p);
if ( window.focus ) w.focus();

}


function setsort(fname) {
//assumes a form called list and fields sort and order
 cursort = document.list.sort.value;
 if (cursort==fname) {
   document.list.order.value = (document.list.order.value!="ASC")?"ASC":"DESC";
 } else {
    document.list.sort.value =fname;
 }
document.list.submit();
 }
 
function basefile(v) {
//returns the filename form a windows or unix path
   v = v.replace(/\\/g,'/');
   fa = v.split('/');
   bf = fa[fa.length-1];
   return bf;
 }
  
 function checklenmin(fld,l) {
    if (fld.value.length>0 && fld.value.length<l) {
    fld.focus();
    alert('passwords must be at least '+l+' characters in length');
       fld.focus();
       return false;
 }
 return true;
}

function addtotext(fld,targ) {
 txt = fld.form[targ].value;
 v = fld.value;
 if (txt.indexOf(v)<0) {
  if (txt.length > 0) txt +=", ";
  txt += v;
  fld.form[targ].value=txt;
  fld.form[targ].style.backgroundColor='#ff0000';
  fld.form[targ].style.color='#ffffff';
  setupdate(fld);
 }
}

function toggleswitch(divid1,divid2) {

document.getElementById(divid1).style.display = (document.getElementById(divid1).style.display!='none')?'none':'block'; 
if(document.getElementById(divid1).style.display!='none')document.getElementById(divid2).style.display='none';
if(document.getElementById(divid1+'viz')) document.getElementById(divid1+'viz').value =document.getElementById(divid1).style.display;
if(document.getElementById(divid2+'viz'))document.getElementById(divid2+'viz').value = document.getElementById(divid2).style.display;

}

function toggledisplay(divid) {

dividstore='display_'+divid;
if (document.getElementById) { // DOM3 = IE5, NS6 
document.getElementById(divid).style.display = (document.getElementById(divid).style.display!='none')?'none':'block'; 
v = (document.getElementById(divid).style.display=='none')?'none':'block';
} 
else { 
if (document.layers) { // Netscape 4 
document.divid.visibility = (document.divid.visibility=='visible')?'hidden':'visible'; 
v = (document.divid.visibility=='hidden')?'hidden':'visible';

} 
else { // IE 4 
document.all.divid.style.visibility = (document.all.divid.style.visibility=='visible')?'hidden':'visible'; 
v = (document.all.divid.style.visibility=='hidden')?'hidden':'visible';

} 
} 
document.getElementById(dividstore).value=v;

}

function checkBirthday(fld,agefield) {
		  fmt = 'E, d NNN yyyy';
          dt = parseDate(fld.value,fmt);
            updatefcalv(fld, fmt);
            v = fld.value;
            if (v=='') {
            return '';
            }
            myage = age('',v,'ym');
            if (myage=='') {
             //try 100 years ago in case a two dig year was enterd and assumed this century
             va = v.split(' ');
             vx ='';
             va[va.length-1] = va[va.length-1]*1-100
             for(i=0;i<va.length;i++) {
             if(i>0) { vx += ' '; }
               vx += va[i];
               
             }
             //alert(vx);
             fld.value = vx;
             myage = age('',fld.value,'ym');
            }
            if (myage=='') {
             alert ("Birthdays must be before the current date! " + fld.value + " is not!");
               agefield.value="";
               fld.value="";
              fld.focus;
              return false;
              } else {
               agefield.value=myage;
             return true;
          }
}

function DateAdd(timeU,byMany,dateObj) {
	var millisecond=1;
	var second=millisecond*1000;
	var minute=second*60;
	var hour=minute*60;
	var day=hour*24;
	var year=day*365;

	var newDate;
	var dVal=dateObj.valueOf();
	switch(timeU) {
		case "ms": newDate=new Date(dVal+millisecond*byMany); break;
		case "s": newDate=new Date(dVal+second*byMany); break;
		case "mi": newDate=new Date(dVal+minute*byMany); break;
		case "h": newDate=new Date(dVal+hour*byMany); break;
		case "d": newDate=new Date(dVal+day*byMany); break;
		case "y": newDate=new Date(dVal+year*byMany); break;
	}
	return newDate;
}
function updatefcalv(fld,fmt) {
fld.value=fixDate(fld.value,fmt);
updatev(fld,'text','optional');
}

var currentfcal='';
function fcalOnChange(y,m,d) {
//alert(currentfcal + ' ' + y + ' ' + m + ' ' + d);
//set currentfcal in the onChange event of the fcal
if(currentfcal!='') {
myDate = new Date();
myDate.setFullYear(y,m-1,d);
document.getElementById(currentfcal).value=formatDate(myDate,"dd NNN yyyy");
document.getElementById(currentfcal).onchange();
currentfcal='';
}
}

var updateset =0;
function updatev(fld,ftype,required) {
		err='';
		fname = fld.name;
		theform = fld.form.name;
		r = fname.substring(fname.lastIndexOf('_')+1)*1;
		prefix = (fname.indexOf('add_')==0)?'add_':'';
		if((prefix=='')&&(required=='required')&&((fld.value=='')||(fld.value==null))) {
			err += fld.name+' cannot be blank';
		}
		if((fld.value!='')&&(fld.value!=null)) {
			switch (ftype) {
				case 'integer':
				 if(!isInteger(fld,fld.name+' must be an integer')) err= fld.name+' must be an integer';
				 break
				case 'number':
				 if(!isNumeric(fld,fld.name+' must be a number')) err= fld.name+' must be a number';
				 break
			}
		}
	if (err=='') {
	ufld = prefix+'updated_'+r;
    fld.style.backgroundColor='#ff0000';
    fld.style.color='#ffffff';
    if (fld.form[ufld]) { fld.form[ufld].value=1;}
    if(updateset==0) {
	for(i=0;i<fld.form.elements.length;i++) {
	 if(fld.form.elements[i].id=='update_button') {
	 	fld.form.elements[i].style.backgroundColor='#ff0000';
		fld.form.elements[i].style.color='#ffffff';

	 }
     }
     if(parent && parent.topFrame) {
     if(parent.topFrame.document.getElementById('update_button')) {
       parent.topFrame.document.getElementById('update_button').style.display='inline';
        parent.topFrame.document.getElementById('update_button').style.backgroundColor='#ff0000';
        parent.topFrame.document.getElementById('update_button').style.color='#ffffff';
     }
     }
	 updateset=1;
	 }
	} else {
	 fld.value='';
	 fld.focus();
    }

}

//reset top button whenever loaded
if(parent && parent.topFrame) {
 if(parent.topFrame.document.getElementById('update_button')) {
        parent.topFrame.document.getElementById('update_button').style.backgroundColor='#ffffff';
        parent.topFrame.document.getElementById('update_button').style.color='#000000';
        parent.topFrame.document.getElementById('update_button').style.display='none';
     }
}

function setupdate(fld) {
    if(updateset==0) {
	for(i=0;i<fld.form.elements.length;i++) {
	 if(fld.form.elements[i].id=='update_button') {
	 	fld.form.elements[i].style.backgroundColor='#ff0000';
		fld.form.elements[i].style.color='#ffffff';

	 }
	 }
	 if(parent && parent.topFrame){
	  if(parent.topFrame.document.getElementById('update_button')) {
	    parent.topFrame.document.getElementById('update_button').style.display='inline';
        parent.topFrame.document.getElementById('update_button').style.backgroundColor='#ff0000';
        parent.topFrame.document.getElementById('update_button').style.color='#ffffff';
     }
  }
	 updateset=1;
}
}

function setAnUpdateBtn(idname) {
	 	document.getElementById(idname).style.backgroundColor='#ff0000';
		document.getElementById(idname).style.color='#ffffff';

}

function unSetAnUpdateBtn(idname) {
	 	document.getElementById(idname).style.backgroundColor='#ffffff';
		document.getElementById(idname).style.color='#000000';

}


function addMe(fthis,src,dest) {
 sbox = fthis.form[src];
 dbox = fthis.form[dest];
 
 cval = sbox.value;
 cindex = sbox.selectedIndex;
 if (cindex >-1) {
 ctxt = sbox.options[cindex].text;

 if(cval!= "") {
 gotit = -1;
 if(dbox.value == "-1") {
  dbox.options[0] = null;
 }
  for(i=0;i<dbox.length;i++) {
    if(dbox.options[i].value == cval) gotit = i;
  }
  if (gotit == -1) {
  var newopt = new Option(ctxt,cval);
  dbox.options[dbox.length] = newopt;
    storeoptions(fthis,dest);

  //history.go(0);
  }
  else {
  //alert(cdetail + " is already listed");
  }
  }
 }
}

function removeMe(fthis,sbox) {
  dbox = fthis.form[sbox];
   cindex = dbox.selectedIndex;
 if (cindex>-1){
  (dbox.length <= 1) ? si = 0 : si = dbox.selectedIndex;
  if (si==-1) si=dbox.length-1;
  dbox.options[si] = null;
  storeoptions(fthis,sbox);
}
}

function removeAll(fthis,sbox) {
  dbox = fthis.form[sbox];
  for(i=dbox.length;i>=0;i--) dbox.options[i] = null;
    storeoptions(fthis,sbox);
}

Skills = new Array();
numskills = 0;

function skilldef (skill_id,skill,skill_group) {
    this.skill_id = skill_id;
    this.skill = skill;
    this.skill_group = skill_group;
}

function addItem(skill_id,skill,skill_group) {
  Skills[numskills] = new skilldef(skill_id,skill,skill_group);
  numskills++;
}

function updateSkillList(fthis,sbox) {
  dbox = fthis.form[sbox];
  for(i=dbox.length;i>=0;i--) dbox.options[i] = null;
  thissg = fthis.value;
  for(i=0;i<numskills;i++) {
   if((thissg=='') || (Skills[i].skill_group == thissg)) {
      var newopt = new Option(Skills[i].skill,Skills[i].skill_id);
      dbox.options[dbox.length] = newopt;
   }
  }
}

function storeoptions(fthis,src) {

  sbox = fthis.form[src];
  v = "";
  vbox = fthis.form[src+'_selection'];
  for(i=0;i<sbox.length;i++) {
   v += ";"+sbox[i].value;
  }
  if (v!="") v=v.substring(1);
  vbox.value = v;

}

function popUpwindow(inFileLink,popUpName) {
  var popupFeat = "height=300px,width=780px,menubar=0,resizable=1,scrollbars=1,toolbar=0,status=0";
  if ( useSinglePopup ) {
    if ( !openPopUp.closed && openPopUp.location ) {
      openPopUp.location.href = inFileLink;
	} else {
      openPopUp = window.open(inFileLink,popUpName,popupFeat);
    }
    openPopUp.focus();
  } else {
    openPopUp = window.open(inFileLink,popUpName,popupFeat);
    openPopUp.focus();
  }
  return false;
}

function isNumeric(elem, helperMsg){
	var numericExpression = /^(-)?(\d*)(\.?)(\d*)$/;
	if(elem.value.match(numericExpression)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function isInteger(elem, helperMsg){
	var numericExpression = /^(\d*)$/;
	if(elem.value.match(numericExpression)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}


function twodecplaces(x) {
 return decplaces(x,2);
}


function decplaces(x,dp) {
ztail='';
for(d=0;d<dp;d++) {
 ztail +='0';
}
  n = parseFloat(x);
  if(isNaN(n)) return '0.00';
  sign = (n<0)?'-':'';
  n = Math.abs(n);
  nwhole = parseInt(n);
  nfrac = (n-nwhole)* Math.pow(10,dp);
  ndec = nfrac.toString()+ztail;
  return sign + nwhole.toString() + '.' + ndec.substring(0,dp);
}

function left_op_change(elem,fname) {
//used in report definition to show or unset right hand options
 switch (elem.value) {
 case "<":
 case "<=":
 case ">":
 case ">=":
 case "IS NULL":
 case "IS NOT NULL":
  document.getElementById('right_table_'+fname).style.display='block';
   switch (elem.value) {
    case "<":
		opsign=">";
		break;
	case "<=":
		opsign=">=";
		break;
	case ">":
		opsign="<";
		break;
	case ">=":
		opsign="<=";
		break;
   }
    document.getElementById('right_op_'+fname).value=opsign;
 break;
 default:
    document.getElementById('right_table_'+fname).style.display='none';
    document.getElementById('right_data_'+fname).value="";
    document.getElementById('right_op_'+fname).selectedIndex=-1;
 }
}

function couldBeEmail(email) {  //no spaces, an @, a dot somewhere after the @  if (email.indexOf(" ") != -1) return false;  if (email.indexOf(",") != -1) return false;  var at = email.indexOf("@");  if (at < 1) return false;  var lastdot = email.lastIndexOf(".");  if (lastdot < at) return false;  return true; } 
 
function checkEmail(fld) {
if (fld.value.length>0){
if(!couldBeEmail(fld.value)) {
  fld.focus;
  alert('Please enter a valid email address');
 }
 }
}

function checkHttp(fld) {
 v = fld.value;
 if (v.length>0 && (v.indexOf('http://')<0 && v.indexOf('https://')<0)) fld.value = 'http://'+v;

}

  function help(ht){
 ht = (arguments.length==0)?'admin':ht;
    var context
    var urln 
    context = "";
    urln = ht + "_help.php";
    if (parent['contents'].document.getElementById('context')) {
    context = parent['contents'].document.getElementById('context').value;
    }
    urln= ht + "_help.php#"+context;
    printWindow('help',urln);
    
}

//routines fot text caharcetr counter
function txtLimit(txtobj,strict) {
	//var taObj=event.srcElement;
	if (txtobj.value.length==txtobj.maxLength*1 && strict==1) return false;
}

function txtCount(txtobj,visCnt,strict) { 
	//var taObj=event.srcElement;
	if (strict==1 && txtobj.value.length>txtobj.maxLength*1) txtobj.value=txtobj.value.substring(0,txtobj.maxLength*1);
	if (document.getElementById(visCnt)) {
	 l = txtobj.maxLength-txtobj.value.length;
	 clr="green";
	 if (l==0) clr = "black";
	 if (l<0) clr = "red";
	 setText(visCnt,l);
	 document.getElementById(visCnt).style.color = clr;
	}
}


function setText(txtobj,txt) {
if(document.all){
     document.getElementById(txtobj).innerText = txt;
} else{
    document.getElementById(txtobj).textContent = txt;
}
}

function resetCtr(visCnt,txt,defaultv,defaultc) {
	 setText(visCnt,defaultv-document.getElementById(txt).value.length);
	 document.getElementById(visCnt).style.color = defaultc;
	 //document.getElementById(txt).value = '';
     document.getElementById(txt).maxLength = defaultv;

}


function setUpTimeStamper(prefix) {

document.write ("hh <select id=\""+prefix+"_hour\"  name=\""+prefix+"_hour\" onChange=\"consoliDate('"+prefix+"');\">");
for(h=0;h<24;h++) {
 h2 =(h<10)?"0"+h:h;
document.write("<option value=\""+h+"\">"+h2+"</option>");
}
document.write ("</select>");
document.write(":mm");

document.write ("<select id=\""+prefix+"_minute\" name=\""+prefix+"_minute\" onChange=\"consoliDate('"+prefix+"');\">");
for(h=0;h<60;h++) {
 h2 =(h<10)?"0"+h:h;
document.write("<option value=\""+h+"\">"+h2+"</option>");
}
document.write ("</select>");
  
document.write ("&nbsp; <INPUT TYPE=text width=10 id=\"date_"+prefix+"\" NAME=\""+prefix+"_date\" VALUE=\"\" SIZE=14 onChange=\"this.value=fixDate(this.value,'E, d NNN yyyy');consoliDate('"+prefix+"');\">");
document.write ("<input type=hidden name=\""+prefix+"\" id=\""+prefix+"\">");
}

function setTimeStamper(prefix,time) {
if(time=='' || time==null) {
 t = new Date();
 } else {
 t = new Date(time);
 }
 h = t.getHours();
 m = t.getMinutes();
 hselect = document.getElementById(prefix+'_hour');
 mselect = document.getElementById(prefix+'_minute');
 hselect.selectedIndex = h;
 mselect.selectedIndex = m;
 
 document.getElementById('date_'+prefix).value=fixDate(t,'E, d NNN yyyy');
 consoliDate(prefix);
}

function consoliDate(prefix) {
 hh = document.getElementById(prefix+'_hour')[document.getElementById(prefix+'_hour').selectedIndex].text;
 mm = document.getElementById(prefix+'_minute')[document.getElementById(prefix+'_minute').selectedIndex].text;
 ddate = document.getElementById('date_'+prefix).value;
 document.getElementById(prefix).value = ddate+ " "+hh+":"+mm+":00";
}
  

