/* 	House Research Department 
 *	hrdlibrary.js - Library of Website javascript functions
 *
 * Author    	Matt Burress, House Research Department
 * Copyright 	(c) 2010, Minnesota House of Representatives
 */


function ToggleByTab(sNewTab, aryTab) {
/* Purpose: Handles switching between showing or hiding a specialized set of corresponding folder tab & content elements
 * Parameters:
 *		sNewTab		- stub ID of new tab element to display
 *		aryTab		- array of stub IDs of tab elements to hide (except for the sNewTab entry)
 * Requirements:
 *		- each stub ID in aryTab must have element IDs to append the stub ID to
 *		- stub ID is added to the literal strings:
 *			"_Tab"			- main tab element
 *			"_TabTextFront"		- text within the tab element when this tab is at the forefront
 *			"_TabTextBack"		- text within the tab element when this tab is inactive/in the background
 *			"_TabContent"		- element for corresponding content
 *			(e.g., with aryTab[0] = "stuff" --> html element IDs must exist for "stuff_Tab", "stuff_TabTextFront", "stuff_TabTextBack", and "stuff_TabContent")
 */	
 	var iIdx;

		//toggle display or hiding for each of the elements
	for (iIdx=0; iIdx < aryTab.length; iIdx++) {
		if (aryTab[iIdx] == sNewTab) {
			document.getElementById(aryTab[iIdx] + "_Tab").className = "HRDTabFront";
			document.getElementById(aryTab[iIdx] + "_TabTextBack").style.display = "none";
			document.getElementById(aryTab[iIdx] + "_TabTextFront").style.display = "block";
			document.getElementById(aryTab[iIdx] + "_TabContent").style.display = "block";
		}
		else {
			document.getElementById(aryTab[iIdx] + "_Tab").className = "HRDTabBack";
			document.getElementById(aryTab[iIdx] + "_TabTextBack").style.display = "block";
			document.getElementById(aryTab[iIdx] + "_TabTextFront").style.display = "none";
			document.getElementById(aryTab[iIdx] + "_TabContent").style.display = "none";
			
		}
	}
}


function ToggleByStub(sStub, iMax) {
/* Purpose: Handle switching between showing or hiding a specialized numeric list of elements
 * Parameters:
 *		sStub		- base portion of each element's ID
 *		iMax		- highest numeric of the IDs
 * Requirements:
 *		- each element ID must equal the stub id with a numeric appended, starting with 1
 *		  (e.g., with sStub = "XX" and iMax = 3 --> html elements must exist for the IDs "XX1", "XX2", "XX3")
 */
	var iIdx;
	
	for (iIdx = 1; iIdx <= iMax; iIdx++) {
		var oElement = document.getElementById(sStub + iIdx);
		if (oElement.style.display == "none") {
			oElement.style.display = "block";
		}
		else {
			oElement.style.display = "none";
		}
	}
}


function ToggleByID(sNewID, aryToggle, sTextID) {
/* Purpose: Handles switching between display/hide of elements based on element IDs
 *	- also handles associated descriptive text and data in hidden input elements
 * Parameters:
 *		sNewID		- ID of element to display
 *		aryToggle	- array of elements that are subject to the toggle; 2nd dimension indexes:
 *					    0 - main element ID to show/hide
 *					    1 - associated input object ID to clear, if main/parent element is being hidden
 *						    - this can itself be an array of object IDs
 *					    2 - associated descriptive text
 *		sTextID		- ID of element for which to modify descriptive text
 */	
	var iIdx;
	var iIdx2;


		//review elements and (1) toggle display or hiding for each, (2) clear out old data,
		//	and (3) change descriptive text
	for (iIdx=0; iIdx < aryToggle.length; iIdx++) {
		if (aryToggle[iIdx][0] == sNewID) {
			document.getElementById(aryToggle[iIdx][0]).style.display = "block";
			if (aryToggle[iIdx][2] != '') {
				document.getElementById(sTextID).innerHTML = aryToggle[iIdx][2];
			}
		}
		else {	
			document.getElementById(aryToggle[iIdx][0]).style.display = "none";

				//do clearing of associated input objects; can be an array of elements
			if (aryToggle[iIdx][1] instanceof Array) {
				for (iIdx2=0; iIdx2 < aryToggle[iIdx][1].length; iIdx2++) {
					ClearOptions(aryToggle[iIdx][1][iIdx2], '');
				}
			}
			else {
				ClearOptions(aryToggle[iIdx][1], '');
			}
		}
	}

}


function ToggleInfo(sIDStub) {
    /* Purpose: generic handler for display/hiding descriptive info
    * Parameters:
    *		sIDStub		- common base portion of ID for HTML elements used in show/hide
    * Requirements: 
    *		- must have two elements with same base:
    *			sIDStub + "Anchor"	= element providing user control of the toggle feature
    *			sIDStub + "Info"	= element containing the substantive info that is displayed or hidden
    */
    var curStatus

    curStatus = document.getElementById(sIDStub + "Info").style.display;

    if (curStatus == "none") {				//display
        document.getElementById(sIDStub + "Info").style.display = "block";
        document.getElementById(sIDStub + "Anchor").innerHTML = "Hide";
    }
    else {									//hide
        document.getElementById(sIDStub + "Info").style.display = "none";
        document.getElementById(sIDStub + "Anchor").innerHTML = "Show";
    }
}


function ToggleYearChk(iYrStart, iYrEnd, iMaxCount) {
/*	Purpose: Enables/disables checkboxes depending on how many are selected
 *	Parameters:
 *		iYrStart	- the first year, in 1-2 digit format (e.g., 2001 --> '1'; 2010 --> '10')
 *		iYrEnd		- the last year, in 1-2 digit format
 *		iMaxCount	- the max number of year check boxes that can be selected
 *	Requirements:
 *		- checkboxes must have standard IDs: "yr" + two-digit numeric for year (e.g., 'yr02'; 'yr09')
 *		- year checkboxes must be continuous
 */
	var iStart
	var iEnd
	var iIdx
	var iCount
	var objChk

		//find out how many checkboxes are currently selected
	iCount = 0;
	for (iIdx = iYrStart; iIdx <= parseInt(iYrEnd); iIdx++) {
		objChk = document.getElementById("yr" + sGetYear(iIdx));
		if (objChk.checked == true) {
			iCount = iCount + 1;
		}
	}

		//do enable/disable depending on how many checkboxes are selected
	if (iCount < iMaxCount) {							//don't have too many, allow any to be selected
		for (iIdx = iYrStart; iIdx <= parseInt(iYrEnd); iIdx++) {
			objChk = document.getElementById("yr" + sGetYear(iIdx));
			objChk.disabled = false;
		}

	}
    	else {										//at limit, don't allow more to be selected
		for (iIdx = iYrStart; iIdx <= parseInt(iYrEnd); iIdx++) {
			objChk = document.getElementById("yr" + sGetYear(iIdx));
			if (objChk.checked == false) {
				objChk.disabled = true;
			}
		}
	}
}


function sClearEntry(sList, sEntry, sDelim) {
/* Purpose: Removes an entry from a delimited list
 * Parameters:
 *		sList		- the full delimited list
 *		sEntry		- the entry to remove
 *		sDelim		- the delimiter
 * Returns: the remaining list or a zero length string
 */
	var sClearList
	var iStart
	
	iStart = sList.indexOf(sEntry);
	if (iStart == 0) {
		if (sList.length > sEntry.length) {	
			sClearList = sList.replace(sEntry + sDelim, "");
		}
		else {
			sClearList = "";
		}
	}
	else if (iStart >= 0) {
		sClearList = sList.replace(sDelim + sEntry, "");
	}
	else {
		sClearList = sList
	}

	return sClearList
}


function sGetYear(iNum) {
/* Purpose: Returns a padded two-digit year (with preceeding zero if needed)
 * Parameters:
 *		iNum		- number for the year
 */
	if (iNum <= 9) {
		return "0" + String(iNum);
	}
	else {
		return String(iNum);
	}
}


function sGetQueryVal(sQuery, sEntry) {
/* Purpose: Obtain the value from a querystring for a given entry name 
 * 	- for "?name1=value1&name2=value2" querystrings
 * Parameters:
 *		sQuery		- the full querystring
 *		sEntry		- the name of the entry
 * Returns: the value text for that querystring entry
 */
 	var aryQuery;
	var aryVal;
	var iIdx;

	aryQuery = sQuery.split("&");

	if ((aryQuery == "") || (aryQuery == null)) {
		return "";
	}
	
	for (iIdx=0; iIdx < aryQuery.length; iIdx++) {
		aryVal = aryQuery[iIdx].split("=");
		if (aryVal[0] == sEntry) {
			return aryVal[1];
		}
	}

	return "";
}


function HandleOpt(sObjID) {
/* Purpose: handle jump to another page via a option box selection
 * Parameters:
 *      sDbjID      - the ID of the select object
 * Requirements
 *      - assumes value of selected option contains a valid URL
 */
    var objSel
    var sURL

    objSel = document.getElementById(sObjID);
    sURL = objSel.options[objSel.selectedIndex].value;

    objSel.options[0].selected = true;                      //reset user selection (in case user backs up to current page)
    window.location = sURL;
}

function formHandler( boxname ) {
	var URL = boxname.options[boxname.selectedIndex].value;
	window.location.href = URL; 
}


function ClearOptions(sID, sSkip) {
/* Purpose: Clears user choices out of an select element (e.g., dropdown list)
 * Parameters:
 *		sID		    - select element's id attribute
 *		sSkip		- value to skip removal of (e.g., retain "all" selection but clear the rest)
 */
	var objSel
	var iIdx
	
	if (sID == '') {
		return true;
	}

    objSel = document.getElementById(sID);
    if (objSel.selectedIndex >= 0) {
        objSel.selectedIndex = -1;
        if (sSkip != '') {
            for (iIdx = 0; iIdx < objSel.options.length; iIdx++) {
                if (objSel.options[iIdx].value == sSkip) {
                    objSel.options[iIdx].selected = true;
                }
            }
        }
    }
}


function DoPopup(objLink, sWindowName) {
/* Purpose: Creates a popup window
 * Parameters:
 *		objLink			- the calling webpage
 *		sWindowName		- a unique name for the window
 */
	var href;
	
	if (! window.focus) return true;
	
	if (typeof(objLink) == 'string')
	   href = objLink;
	else
	   href = objLink.href;
	
	window.open(href, sWindowName, 'width=550,height=350,scrollbars=yes');
	return false;
}


function IsValidNumber(sInput, sField, iMin, iMax) {
/* Purpose: Does form validation to check if a field contains a proper number
 * Parameters:
 *		sInput			- input text from user
 *		sField			- external name of the field being validated
 *		iMin			- minimum amount
 *		iMax			- maximum amount
 * Returns: an error message if an error occured
 */

    var sChar
    var iIdx

    for (iIdx = 0; iIdx < sInput.length; iIdx++) {
        sChar = sInput.substring(iIdx, iIdx + 1)
        if (sChar < "0" || sChar > "9") {
            return "The entry '" + sInput + "' for the '" + sField + "' is not a number.";
        }
    }
    
    if ((parseInt(sInput) < iMin) || (parseInt(sInput) > iMax)) {
        return "The entry '" + sInput + "' for the '" + sField + "' is outside the allowed range (" + iMin + " - " + iMax + ").";
	}

    return ""
}



