// Main menu dropdown function
function showMenu(id) {
var d = document.getElementById(id);

  for (var i = 1; i<=1; i++) {
    if (document.getElementById('submenu'+i)) {
      document.getElementById('submenu'+i).style.display='none';
    }
  }
  if (d) {
    d.style.display='block';  
  }
}
showMenu();

var tblRowClass="";
/**
 * designed to be attached to a TR element's onMouseIn method, this method
 * will change the css CLASS of a table TR element to "hover".
 */
function onTableRowIn(tblRow) {
	tblRowClass = tblRow.className;
	tblRow.className="hover";
}

/**
 * designed to be attached to a TR element's onMouseOut method, this method
 * will revert the css CLASS of a table TR element to its original state.
 */
function onTableRowOut(tblRow) {
	tblRow.className = tblRowClass;
}

/**
 * Used by runSearch(listName) and resetFilter(listName) to return to first page of searched list
 * Method Params:
 * listName = the name of dataListName in the tag of frm:dataList.
 */
function returnToFirstPage(listName) {
    document.forms[0][listName + "_DataList_page"].value='0';
}

/**
 * Run by Search Button in the Filter Part
 * Method Params:
 * listName = the name of dataListName in the tag of frm:dataList.
 */
function runSearch(listName) {
    returnToFirstPage(listName);
    document.forms[0].submit();
}

/**
 * Clears Condition Values that have been rendered by a ConditionTag
 * Method Params:
 * listName = the name of dataListName in the tag of frm:dataList.
 */
function resetFilter(listName) {
    returnToFirstPage(listName);
}

/**
 * Replaces Smart quotes with straight quotes in given field.
 * Method Params:
 * fieldName = The name of form field.
 * doReplace = 	True or False. If true replace the smart quotes w/ straight quote, 
 * 				If false replaces w/ accent mark.
 */
function replaceQuotes(fieldName, doReplace) {
	if (document.forms[0][fieldName]) {
		var inputValue = document.forms[0][fieldName].value;
		var tmpValue = "";
		for(i=0; i<inputValue.length; ++i) {
			if((inputValue.charCodeAt(i)=="8216") || (inputValue.charCodeAt(i)=="8217")) {
				tmpValue += (doReplace === true) ?  '\'' : '`';
			} else if((inputValue.charCodeAt(i)=="8220") || (inputValue.charCodeAt(i)=="8221")) {
				tmpValue += (doReplace === true) ?  '\"' : '`';
			} else {
			   tmpValue += inputValue.charAt(i);
			}
		}
		document.forms[0][fieldName].value = tmpValue;
	}
}

function stateCountrySelector(selection, stateOrCountry) {
    if (stateOrCountry == "country") {
        if (selection.value != "US") {
            document.forms[0].frmState.value = "";
        } 
    } else if (stateOrCountry == "state") { 
        if (selection.selectedindex !== 0) {
            document.forms[0].frmCountry.value = "US";
        }
    }
}

/**
 * Sets focus to first form element non-hidden or disabled
 * Method Params:
 * 	
 */
function setFocus() {
    for (f=0; f < document.forms.length; f++)  {
        for(i=0; i < document.forms[f].length; i++)   {
            if ((document.forms[f][i].disabled === false) && (document.forms[f][i].type != "hidden"))   {
                if (!document.forms[f][i].readOnly && document.forms[f][i].style.display != 'none')    {
                    if ((document.forms[f][i].type == "text") || (document.forms[f][i].type == "password"))    {
                        try {
                            document.forms[f][i].focus();
                            break;
                        }
                        catch (err) {
                            //do nothing
                        }
                    }
                }
            }
        }
    }
}

/**
 * Set form field background color on focus
 * 	
 */
var sfFocus = function() {
var sfEls = document.getElementsByTagName("INPUT");
var sfEls2 = document.getElementsByTagName("TEXTAREA");
    for (var i=0; i<sfEls.length; i++) {
        if (!sfEls[i].readOnly) {
            sfEls[i].onfocus=function() {
                this.className+=" sffocus";
            };
            sfEls[i].onblur=function() {
                this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
            };
        }
    }
    for (var k=0; k<sfEls2.length; k++) {
        if (!sfEls2[k].readOnly) {
            sfEls2[k].onfocus=function() {
                this.className+=" sffocus";
            };
            sfEls2[k].onblur=function() {
                this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
            };
        }
    }        
};
if (window.attachEvent) {
	//window.attachEvent("onload", sfFocus);
}
sfFocus();
/**
 * Help Window Popup
 * 
 */
function newHelpWindow() {
    helpWindow=window.open("/EIMS/help/eims_help.jsp?sIsPopUp=true", "helpWin", "width=500,height=450,status,scrollbars,resizable,left=20,top=20");
    helpWindow.focus();
}

/**
 * PDF Help Window Popups
 * 
 */
function newPDFHelpWindow(URL) {
  if (window.screen) {
  w = screen.width - 100;
  h = screen.height - 100;
  }
  helpWindow = window.open(URL, "helpWin", "width=" + w + ",height=" + h + ",scrollbars=yes,resizable=yes,left=20,top=20");
}

/**
 * Privacy Window Popup
 * 
 */
function newPrivacyWindow() {
    whatisWindow = window.open("http://inside.usaid.gov/privsec.html", "privacyWin", "width=630,height=450,scrollbars=yes,resizable=yes,left=20,top=20");
    whatisWindow.focus();
}

/**
 * Timeout
 * 1000 = 1 second and 1800000 = 30 minutes
 * Alert message set to one minute prior to actual timeout.
 * 
 */
function timeout() {
	window.setTimeout("newWarningWindow()",1800000);
}

/**
 * Timeout Window Popup
 * 
 */
 function newWarningWindow() {
    var w = 400;
    var h = 180;
    var leftPos = (screen.width - w) / 2;
    var topPos = (screen.height - h) / 2;  
		warningWindow = window.open("/EIMS/share/EIMSTimeOutWarning.jsp", "warningWin", "width=400,height=170,scrollbars=yes,left="+leftPos+",top="+topPos);
		warningWindow.focus();
}

/**
 * Loader Function to display loading message
 * 
 */
function doLoad() {
	if (document.getElementById('loadMsg')!==null) {
		document.getElementById('loadMsg').style.display = "";
	}
}

/**
 * Loading Dots to display during loading message
 * 
 */
var b=0;
var loadDots=" . . . . . . . . . .";

function progressDots() {
	if (document.getElementById("loadDots")!==null) {
		if (document.getElementById("msgLoad")) {
			document.getElementById("msgLoad").style.display = "block";
		}
		if (document.getElementById("loadMsg")) {
			document.getElementById("loadMsg").style.display = "block";
		}
		if(b===0){
			document.getElementById("loadDots").firstChild.data='';
		}
		if(document.getElementById("loadDots").firstChild.data.length < loadDots.length){
			document.getElementById("loadDots").firstChild.data+=loadDots.substr(b,1);
			b++;
		}
		else if(document.getElementById("loadDots").firstChild.data.length >= loadDots.length){
			b=0;
		}
		setTimeout('progressDots()',600);
	}
}

/**
 * Tabbed Interface
 * 
 */
function tabSelector(tabObj) {
	var tabActiveId = "tab" + tabObj;
	var activeContentId = "tabContent" + tabObj;
    if (tabActive !== null)	{
		tabActive.className = "tabStatic";
		tabActive.style.backgroundImage = "";
	}
	tabActive = document.getElementById(tabActiveId);
	tabActive.className = "tabActive";
	tabActive.style.backgroundImage = "url(../images/spacer.gif)";
	document.getElementById(tabActiveId).blur();
	for(i = 0; i < contentIdArray.length; i++)	{
	  document.getElementById(contentIdArray[i]).style.display = (activeContentId == contentIdArray[i]) ? "block":"none";
	}
	return false;
}

function getCookie(cookieName) {
var c=document.cookie.split(";");
	for (var i=0; i <c.length; i++) {
		var co=c[i].split("=");
		if (co[0]==cookieName) {
			if (co.length > 1) {
				return co[1];
			} else {
				return "";
			}
		}
	}
	return "";
}

/**
 * Disable form buttons
 * 
 */
function handleSubmitForm(theform) {
	if (document.all || document.getElementById) {
		for (i = 0; i < theform.length; i++) {
			var tempobj = theform.elements[i];
			if(tempobj != null && tempobj.type != null) {
				if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset" || tempobj.type.toLowerCase() == "button" ) {
					tempobj.disabled = true;
				}
			}
		}   
	}
	return true;
}


function centerPopup(url, name, width, height) {
  popup = centerPopupFull(url, name, width, height, '');
  return popup;
}
function centerScrollPopup(url, name, width, height) {
  popup = centerPopupFull(url, name, width, height, 'location=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes');
  return popup;
}
function centerPopupFull(url, name, width, height, features) {
  // get center of browser window
	var w2 = getBrowserWidth() / 2;
	var h2 = getBrowserHeight() / 2;
	var f  = 'width=' + width + ',' +
           'height=' + height + ',' +
           'top=' + (window.screenTop + (h2 - (height/2))) + ',' +
           'left=' + (window.screenLeft + (w2 - (width/2)));

  if (features === '') {
    f = f + ',location=no,menubar=no,status=no,toolbar=no,scrollbars=no,resizable=yes';
  }
  else {
    f = f + "," + features;
  }
  
  popup = window.open(url, name, f);
  popup.focus();
  
  return popup;
}

function getBrowserWidth() {
  if (navigator.userAgent.indexOf("MSIE") > 0) {
    return document.body.clientWidth;
  }
  else {
    return window.outerWidth;
  }
}

function getBrowserHeight() {
  if (navigator.userAgent.indexOf("MSIE") > 0) {
    return document.body.clientHeight;
  } 
  else {
    return window.outerHeight;
  }
}

/**
 * Logout confirmation
 * 
 */
function logOutConfirm() {
  if(confirm("Are you sure you want to Logout?")) {
    parent.location = "";      
  }
  return true;
}

function leftTrim(sString) {
   while (sString.charAt(0) == ' ')   {
    sString = sString.substring(1);
   }
   return sString;
}
function rightTrim(sString) {
    while (sString.charAt(sString.length-1) == ' ')    {
      sString = sString.substring(0,sString.length-1);
    }
    return sString;
}
function trimAll(sString) {
	while (sString.charAt(0) == ' ') {
		sString = sString.substring(1);
	}
	while (sString.charAt(sString.length - 1) == ' ')  {
		sString = sString.substring(0, sString.length - 1);
	}
	return sString;
}

/**
 * Single checkbox to select or deselect checkbox list
 * 
 */
function deselectAllCheckBox(chkName, event) {
	if (event) {event.cancelBubble=true;}
    document.forms[0][chkName].checked=false;
}


function showFrame(frameName) {
    document.getElementById(frameName).style.display='block';
}
function hideFrame(frameName) {
     document.getElementById(frameName).style.display='none';
}

/**
 * Toggles Help Info display on mouseover.
 * 
 */
var helpTimer;

function toggleHelpInfo (helpId, showOrhide) {
    document.getElementById(helpId).style.display=showOrhide;
}
function mouseInHelp(helpId) {
    helpTimer = setTimeout("toggleHelpInfo('" + helpId + "', 'inline')", 600);
}
function mouseOutHelp(helpId) {
    toggleHelpInfo(helpId, "none"); 
    clearTimeout(helpTimer);
}

/**
 * Display warning when character input count exceeds passed parameter.
 * warning display is in include generic message file
 * Sample code:
 * onkeyup="charCounter(this, 4000);" //Place this code on the field to be detemirned.
 */
function charCounter(txtAreaField, txtSize) {
	var txtAreaContent = txtAreaField.value;
	if(document.getElementById("charCountWarning"+txtSize)) {
		if (txtAreaContent.length > txtSize) {
			document.getElementById("charCountWarning"+txtSize).style.display = "block";
			document.getElementById("currCharCount"+txtSize).value = txtAreaContent.length;
		} else {
			document.getElementById("charCountWarning"+txtSize).style.display = "none";
			document.getElementById("currCharCount"+txtSize).value = 0;
		}
	}
}

/**
 * Standard collapsible search bar
 */
function showHideSearch(el) {
    if (el.className == "sectionSearchShow") {
        document.getElementById(el.id+"Links").style.display = "block";
        el.className = "sectionSearchHide";
    } else if (el.className == "sectionSearchHide") {
        document.getElementById(el.id+"Links").style.display = "none";
        el.className = "sectionSearchShow";
    }
}

function countMaxChars(field, size) {
	var curSize = field.value.length;
	if (curSize > size) {
        alert("This text area field cannot be longer than " + size + " chars in length;\nthe current size is " + curSize + ".");
        return;
	}
}
