/* 
WordCounter is similar to textCounter, except it counts the number of words in the passed form field and displays the current count, realtime, in the passed fielddisp which is typically an input box next to the textarea. It shows in an alert popup the passed error message if the count exceeds the passed max. The field value is truncated at the maxlimit. Typically used in a textarea input in the onkeyup event.
onkeyup="WordCounter(this.form.FieldName, 120, 'You entered too many words for FieldName. The maximum is 120. The value has been truncated at the 120th word.',this.form.FieldName_disp)
*/
function WordCounter(field, maxlimit,errmsg,fielddisp) 
{
Str=field.value;
// alert('Str = ' + Str);
WordArray=Str.split(" ");
WordCount=WordArray.length;
fielddisp.value=WordCount;
if (WordCount > maxlimit) 
	{
Wval = WordArray[maxlimit];
Wvalslice = WordArray.slice(0,maxlimit);
WvalsliceCount = Wvalslice.length;
WvalsliceJoin = Wvalslice.join(" ");
alert(errmsg);
field.value = WvalsliceJoin;
fielddisp.value= maxlimit;
	}
}
function confirmSubmit()
{
var agree = confirm("Are you sure you wish to delete the role(s)?");
if (agree)
	return true ;
else
	return false ;
}
function AddUserContact(ContactID) {
if (confirm("Are you sure you want to add this contact to your Contacts list?"))
	{
var UrlStr = '';
UrlStr = "/cgiarcontacts/manage_user_contacts.cfm?ContactID=" + ContactID + "&Action=Add&AutoMode=Yes";
NewWindow(UrlStr,'CGPopup','80','80');
	}
	else 
	{
	return false;
	}
}
function RemoveUserContact(ContactID) {
if (confirm("Are you sure you want to remove this contact from your Contacts list?"))
	{
var UrlStr = '';
UrlStr = "/cgiarcontacts/manage_user_contacts.cfm?ContactID=" + ContactID + "&Action=Remove&AutoMode=Yes";
NewWindow(UrlStr,'CGPopup','80','80');
	}
	else 
	{
	return false;
	}
}
function NewWindow(mypage, myname, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+'yes'+',resizable'
//	alert("winprops= " + winprops);
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { 
		win.window.focus(); 
	}
}
function PrintWindow(mypage, myname, w, h) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops =
'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+'yes'+',menubar='+'yes'+',toolbar='+'yes'+',resizable' 
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { 
		win.window.focus(); 
	}
}
function closeAndRefresh() {
    window.opener.location.reload();
    close();
}
/* SetFrmVal will set the value for the FormName.FrmField to FrmFieldVal
*/
function SFrmVal(FormName,FrmField,FrmFieldVal)
{
	FormName.UseList.value = 'No';
}
function SubmitFrm(FormName){
//var ThisFormName = eval("document.forms." + FormName);
	FormName.submit();
}
/* Usage: ShowHideBlock(Blockname to show, state to enable)
ShowHideBlock(TOBlockOn,'none')
*/
function ShowHideBlock(BlockToShow,blockstate){
if (blockstate == "none")
	{
	BlockToShow.style.display = 'none';
	}
else
	{
	BlockToShow.style.display = 'block';
	}
}
/*
checkall will check all checkboxes, or uncheck them, depending on what is passed as thestate
javascript:checkall('Search_Form','SiteAreas',true) will check all
javascript:checkall('Search_Form','SiteAreas',false) will uncheck
*/
function checkall(formname,checkname,thestate){
var el_collection=eval("document.forms."+formname+"."+checkname)
for (c=0;c<el_collection.length;c++)
el_collection[c].checked=thestate
}
/*
uncheckbox will uncheck the specified form.checkbox
javascript:uncheckbox('Search_Form','CheckBoxName')
*/
function uncheckbox(formname,targ){
 var targ_to_uncheck = eval("document.forms."+formname+"."+targ);
  targ_to_uncheck.checked = false;
		return false ;
}
/* 
clearSelect is to deselect all items in a select box 
javascript:clearSelect('Search_Form','SelectBoxName')
*/
function clearSelect(formname,targ) 
{
  var currentForm = eval("document.forms."+formname);
  var targ_selects = eval("document.forms."+formname+"."+targ);
  targ_selects.selectedIndex = -1;
}
/* 
textCounter counts the number of characters in the passed form field, and shows in an alert popup the passed error message if the count exceeds the passed max. The field value is truncated at the maxlimit. Typically used in a textarea or text input in the onchange event.
onchange="textCounter(this.form.FieldName,150,'You entered too many characters for FieldName! The value will be truncated at 150 characters.')
*/
function textCounter(field, maxlimit,errmsg,fielddisp) 
{
if (typeof(fielddisp) != 'undefined')
	{
WordCount=field.value.length;
fielddisp.value=WordCount;
	}
if (field.value.length > maxlimit) {
alert(errmsg);
field.value = field.value.substring(0, maxlimit);
	if (typeof(fielddisp) != 'undefined')
		{
fielddisp.value=maxlimit;
		}
	}
}
/* 
checkEmailAddress will validate the passed form field value against the regular expression below. If it doesn't pass, it alerts with the passed msg if it is defined or the default error, focuses back on the calling document with the form field selected.
*/
function checkEmailAddress(field,msg) 
{
// Note: The next expression must be all on one line...
//       allow no spaces, linefeeds, or carriage returns!
var goodEmail = field.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);

if (!goodEmail)
	{
	if (typeof(msg) != 'undefined')
		{
   alert('' + msg);
   		}
	else
		{
   alert('The email address you entered is not valid. Please enter a valid email address.');
		}
	/*self.focus();
	field.select();
	field.focus();
	*/
   }
}
// -------------------------------------------------------------------
// autoComplete (text_input, select_input, ["text"|"value"], [true|false])
//   Use this function when you have a SELECT box of values and a text
//   input box with a fill-in value. Often, onChange of the SELECT box
//   will fill in the selected value into the text input (working like
//   a Windows combo box). Using this function, typing into the text
//   box will auto-select the best match in the SELECT box and do
//   auto-complete in supported browsers.
//   Arguments:
//      field = text input field object
//      select = select list object containing valid values
//      property = either "text" or "value". This chooses which of the
//                 SELECT properties gets filled into the text box -
//                 the 'value' or 'text' of the selected option
//      forcematch = true or false. Set to 'true' to not allow any text
//                 in the text box that does not match an option. Only
//                 supported in IE (possible future Netscape).
// -------------------------------------------------------------------
function autoComplete (field, select, property, forcematch) 
{
	var found = false;
	for (var i = 0; i < select.options.length; i++) 
	{
	if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) 
		{
		found=true; break;
		}
	}
	if (found) 
	{ 
	select.selectedIndex = i; 
	}
	else 
	{ 
	select.selectedIndex = -1; 
	}
	if (field.createTextRange) 
	{
		if (forcematch && !found) 
		{
			field.value=field.value.substring(0,field.value.length-1); 
			return;
		}
		var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
		if (cursorKeys.indexOf(event.keyCode+";") == -1) 
		{
			var r1 = field.createTextRange();
			var oldValue = r1.text;
			var newValue = found ? select.options[i][property] : oldValue;
			if (newValue != field.value) 
			{
				field.value = newValue;
				var rNew = field.createTextRange();
				rNew.moveStart('character', oldValue.length) ;
				rNew.select();
			}
		}
	}
}
/* 
writeSelected will copy the text of the selected option(s) from the passed selectbox obj to the form element passed as targ. If additional 'yes' arg is passed, the script will also write the selectbox value to a form element with the same base name as targ with _val appended.
onchange="writeSelected('MainFrm','Selectbox','inputbox')
onchange="writeSelected('MainFrm','Selectbox','inputbox','yes')
*/
function writeSelected(frm,obj,targ,writeval)
{
	var ChosenText = "";
	var ChosenTextVal = "";
	var selectObj = eval("document.forms."+frm+"."+obj);
	var descObj = eval("document.forms."+frm+"."+targ);
	if (writeval == 'yes')
	{
	var descObjval = eval("document.forms."+frm+"."+targ + "_val");
	}	
	if (selectObj.type == "select-multiple")
	{
	for (var i=0; i < selectObj.options.length; i++ )
		{
		if (selectObj.options[i].selected) 
			{
		ChosenText = ChosenText + selectObj.options[i].text+",";
		ChosenTextVal = ChosenTextVal + selectObj.options[i].value+",";
			}
		}
			descObj.value = ChosenText;
		if (writeval == 'yes')
		{
			descObjval.value = ChosenTextVal;
		}
	}
	else
	{
		if (selectObj.type == "select-one")
		{
	for (var i=0; i < selectObj.options.length; i++ )
			{
		if (selectObj.options[i].selected) 
				{
		ChosenText  = ChosenText + selectObj.options[i].text;
		ChosenTextVal = ChosenTextVal + selectObj.options[i].value;
				}
			}
			descObj.value = ChosenText;
		if (writeval == 'yes')
			{
			descObjval.value = ChosenTextVal;
			}
		}
	}
}
function padzero(frm,obj)
{
//function used for padding zeros to the project id,to make it 7 characters
var usr;
var len;
var zeros = new Array("0","00","000","0000","00000","000000");
var fobj=eval("document.forms."+frm+"."+obj)
alert("fobj = " + fobj);
usr = fobj.value;

len = usr.length;

if(len < 7)

	{

len = 7-len-1;

fobj.value = zeros[len] + fobj.value;

	}
}
function trim(str)
{
  return( (""+str).replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,'$1') );
}
function checkObj(){

	//alert(typeof(obj));

	var obj = eval("document.forms.frm1");
	alert(typeof(obj));

	if(typeof(obj)!='undefined'){
		alert('Dude exists');
	}
	else{
		alert('Dude DOES NOT exist');
	}

}
//function to check if the fields given in an array have some value entered or not
// labels array is used to display the error message
/*
	alert("type = " + type);
	alert("Label is " + labelsArr[i]);

		if (type != 'undefined')
			{
		type=type.toLowerCase();
			}
	for(var i=0; i<NomFrm.elements.length; i++)
	{
	var thisel = NomFrm.elements[i];
		if (thisel.type == 'radio')
		{
	alert("This is a radio element " + thisel.name)
		}
	}
*/

/*
function checkMandatoryFields(fieldsArr, labelsArr)
{
	NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;
	IE4plus = (document.all) ? true : false;
	IE5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.")!=-1)) ? true : false;
	
	if(NS6){ var prefix = "document.layers."; }
	else{var prefix = "document.all.";}
	
	var temp = eval(prefix+fieldsArr[1]+".type");
	alert(temp);
// alert("NominatorSalutation.type = " + document.NomFrm.NominatorName.type);
	var ErrorStr="";
	for(var i=0;i<fieldsArr.length;i++)
	{
		var type = eval(prefix+fieldsArr[i]+".type");
// 	alert("type = " + type);
//	alert("Label is " + labelsArr[i]);
	alert(type);
		if(type=="text" ||type=="file" ||type=="textarea")
		{
			var len = eval("trim("+prefix+fieldsArr[i]+".value).length")
			if(!len)
			{
				ErrorStr=ErrorStr+"Please Enter "+labelsArr[i] +"\n";
			}
		}
		else if(type=="select-one")
		{
			var len = eval(prefix+fieldsArr[i]+".value")
			if(len==0)
			{
				ErrorStr=ErrorStr+"Please Select "+labelsArr[i] +"\n";
			}
		}
		else
		{
//				ErrorStr=ErrorStr+"Please choose "+labelsArr[i] +"\n";
		}
	}
	return 	ErrorStr;		
}*/

function checkMandatoryFields(fieldsArr, labelsArr)
{
var ErrorStr="";
var bReturn = true;
for (var i=0; i<fieldsArr.length; i++) 
{
	for (var k=0; k<document.forms[0].length; k++) 
	{
		if (document.forms[0].elements[k].name == fieldsArr[i]) 
		{
			if (document.forms[0].elements[k].value == "") 
			{
				ErrorStr=ErrorStr+"Please Enter "+labelsArr[i] +"\n";
				document.forms[0].elements[k].focus();
			}
		}
	}
}
return(ErrorStr);
}

function AddToFoundList(Frm,Fld,ActType) 
{
var ActionType = ActType;
if (ActionType != 'Add' && ActionType != 'Rem')
	{
alert("Error! ActType is not Add or Rem. Nothing can be done.");
	}
else
	{
var UrlStr = '';
var ThisFoundList = '';
var obj = eval("document.forms." + Frm + "." + Fld);
// alert('ThisFoundList 1 is ' + ThisFoundList);

for (c=0;c<obj.length;c++)
		{
// alert("obj[c].checked =  " + obj[c].checked);
		if (obj[c].checked == true)
			{
ThisFoundList = ThisFoundList + ',' + obj[c].value;
			}
		}
	if (ThisFoundList.length == 0)
		{
alert('In order to add to or remove from your found list, you must check one or more of the checkboxes in the first column before the contact\'s name.');
		}
	else
		{
UrlStr = "/cgiarcontacts/manage_foundlist.cfm?Action=" + ActionType + "&AutoMode=Yes&IDList=" + ThisFoundList;
NewWindow(UrlStr,'CGPopup','80','80');
		}
	}
/*
		if (ActionType == 'Add')
			{
			if (obj[c].checked == true)
				{
ThisFoundList = ThisFoundList + ',' + obj[c].value;
				}
			}
		else
			{
			if (obj[c].checked == false)
				{
ThisFoundList = ThisFoundList + ',' + obj[c].value;
				}
			}
*/
}

