// settable parameters, global state flags
var activePopup = null;  // null | locations | themes | types
var maxListDisplay = 5; // max no. of list items to display before scrolling;
var anyMsg = "(none selected)";
var mouseDown = false;
var selectStatus = false;
var sitesSelected = true;
var metadataSelected = true;
var resultsRequested = false;  // true if "show results" has been clicked
var sortorder = "location";  // location | datatype


function getListContainer( typename ) {
		return document.getElementById( typename + "List" );
}

function getPopupContainer( typename ) {
		return document.getElementById( typename );
}


function showActive( me ) {
	me.parentNode.style.color="green";
}


// Open a popup menu (after closing any previously open menu); show "none selected" message if necessary
function doPopup( me ) {
	
	if (activePopup == me) {
		hidePopup( activePopup );
	}
	else {
		if (activePopup != null) {
			hidePopup( activePopup );
		}
		showPopup( me );
		var listContainer = document.getElementById( me + "List" );
		if (listContainer) {
			if (listContainer.firstChild == null) {
				showAnyMsg( listContainer );
			} 
		}
	}
}

// Hide whichever popup menu is open, if any
function hidePopups() {
	if (activePopup != null) {
		hidePopup( activePopup );
	}
}

// Show a popup menu and hide the search results panel
function showPopup( me ) {
	activePopup = me;
	var thisContainer = document.getElementById(me);

	thisContainer.style.display='block'; 

	var resultsContainer = document.getElementById( "results_container" );
	resultsContainer.style.visibility='hidden';
}


// Hide a popup menu and reveal the search results panel 
function hidePopup(me ) {
	activePopup = null; 
	document.getElementById(me).style.display='none'; 
	var resultsContainer = document.getElementById( "results_container" );
	resultsContainer.style.visibility='visible';
}

// Hide a DOM node (typically, the containing div of a popup menu)
function hideMe() {
	//this.style.visibility = 'hidden';
	this.style.display = 'none';
}

// Select all the checkboxes in a popup menu
function selectPopup(me) {
	var containerDiv = document.getElementById( me );
	var boxes = containerDiv.getElementsByTagName( 'input' );
	var listContainer = getListFromPopup( containerDiv );
	for( var i=0; i<boxes.length; i++ ) {
		var thisbox = boxes[i];
		if ( thisbox.checked == false ) {
			thisbox.checked = true;
			listCheckedItem( listContainer, thisbox.name, thisbox.value );
		}
	}
}

// receive: id of a div containing a popup checkbox menu
// return: reference to the container div of the corresponding list of selected items
function getListFromPopup( popup ) {
	if (popup.id == "placemenu" || popup.id == "placefinder") {
		return document.getElementById( 'locationsList' );
	}
	else if (popup.id == "themes") {
		return document.getElementById( 'themesList' );
	}
}


// clear all the checkboxes in a popup menu
function clearPopup(me) {
	var containerDiv = document.getElementById( me );
	var listContainer = getListFromPopup( containerDiv );
	var boxes = containerDiv.getElementsByTagName( 'input' );
	for( var i=0; i<boxes.length; i++ ) {
		if ( boxes[i].checked == true ) {
			boxes[i].checked = false;
			removeListItem( listContainer, boxes[i].value );
		}
	}
}

// Add an element to a list of selected items; handle long lists by scrolling the contaning div
function insertListItem( container, pNode, tNode ) {
		var item = container.firstChild;
		while (item != null)
		{
			if ( item.title == pNode.value ) {	
				return;
			}
			item = item.nextSibling;
		}

		var firstItem = container.firstChild;
		container.insertBefore( pNode, firstItem );

		
		pNode.appendChild( tNode );
		
		if (container.childNodes.length > maxListDisplay  ) {
			if (container.style.overflow != "auto" ) {
				container.style.height = String( container.offsetHeight - 10 ) + "px";
				container.style.overflow = "auto";
			}
		}
		if (pNode.title != "") {
			pNode.ondblclick = delistMe;
		}
}

// add a selected item from a to select list
// receive 3 args: reference to list div; label to display; value of a checkbox (to be stashed in the unused title attribute)
function listCheckedItem( container, text, value ) {
		
		// check for already listed items (prevent duplicates)
		
		// create new paragraph
		var newP  = document.createElement("p");
		newP.name = text;
		newP.title = value;
		//newP.style.marginTop = "0px";
		//newP.style.marginBottom="0px";
		if (value == "") {
			//newP.style.color="red";
			newP.className="red_list_item";
		}
		else {
			//newP.style.color="#2F568A";
			//newP.style.cursor = "pointer";
			newP.className = "blue_list_item";
		}
		var newText = document.createTextNode( text );
		hideAnyMsg( container );

		// put new paragraph at the beginning of the list
		// note: if firstItem is null, insertBefore acts like appendChild()
		insertListItem( container, newP, newText );
		
}  

function delistMe() {
	//this.parentNode.removeChild( this );
	//var value = this.title;
	//if (text != anyMsg) {
		removeListItem( this.parentNode, this.title  );
		uncheckMenuItem( this.firstChild.nodeValue );
	//}
}

function uncheckMenuItem( text ) {
	var boxes = document.getElementsByTagName( 'input' );
	for( var i=0; i<boxes.length; i++ ) {
		if (boxes[i].name == text )
		{
			boxes[i].checked = false;
		}
	}
}

//remove an selected item from a dynamic select list
function removeListItem( container, value ) {
	var children = container.childNodes;
//	if (container.childNodes.length == 1 && text != anyMsg ) {
	if (container.childNodes.length == 1 && value != "" ) {
		//listCheckedItem( container, anyMsg, "" );
		showAnyMsg( container );
	} 	
	for(var i=0; i < children.length; i++) {    // Loop through the children
        if ( children[i].title == value) {
			container.removeChild( children[i] );
			break;
		}
    }

	if (container.childNodes.length <= maxListDisplay) {
		if (container.style.overflow != "") {
			container.style.height = "";
			container.style.overflow = "";
		}
	}
}


function getAnyMsg( container ) {
	var msg = "none";
	if ( container.id == "themesList") {
		msg = "any";
	}
	else if (container.id == "locationsList") {
		msg = "none";
	}
	return msg;
}

// show the "none selected" message from the dynamic select list
function showAnyMsg( container ) {
	var newP  = document.createElement("p");
	newP.title = "";
	newP.style.marginTop = "0px";
	newP.style.marginBottom="0px";
	var newText;
	if (container.id=="locationsList") {
		newP.style.color = "red";
		newText = document.createTextNode( "none" );
	}
	else if (container.id=="themesList") {
		newP.style.color = "#2F568A";
		newText = document.createTextNode( "all" );
	}
	else {
		newText = document.createTextNode( "all" );
	}
	
	insertListItem( container, newP, newText );
}

// remove the "none selected" message from the dynamic select list
function hideAnyMsg( container ) {
	removeListItem( container, "" );
	//alert( "removing any msg " + anyMsg );
}

// 
function killSelect() {
	return false;
}


// Attach mouse event handlers to each checkbox in a popup menu
// receive: id of a popup menu's containing div
function initPopup( label ) {
	var popupContainer = getPopupContainer( label );
	var boxes = popupContainer.getElementsByTagName( 'input' );
	for( var i=0; i<boxes.length; i++ ) {
		var thisbox = boxes[i];
		var thisspan = thisbox.parentNode;
		thisbox.checked = false;
		thisbox.onclick =  killSelect;

		if (label == "themes" && thisspan.className == "themeitem") {
			thisspan.onmouseover = dragSelectThemeItem;		
			thisspan.onmousedown = selectThemeItem;
		}
		else if (label == "placemenu" && thisspan.className == "locationitem") {
			thisspan.onmouseover = dragSelectLocationItem;
			thisspan.onmousedown = selectLocationItem;
		}
		else if (label == "placefinder" && thisspan.className == "locationitem" ) {
			thisspan.onmouseover = dragSelectLocationItem;
			thisspan.onmousedown = selectLocationItem;
			// when placefinder pops up, some places may already be listed; these should appear checked
			var list = getListFromPopup( popupContainer )
			
			var item = list.firstChild;
			while (item != null) {
				if ( item.title == thisbox.value ) {	
					thisbox.checked = true;
					break;
				}
				item = item.nextSibling;
			}
		}
		
	}
}


// Attach a mouse event handler for drag-selecting
function dragSelectLocationItem() {
	dragSelectItem( this, "locations" );
}

// Attach a mouse event handler for drag-selecting
function dragSelectThemeItem() {
	dragSelectItem( this, "themes" );
}

// select or deselect a checkbox by dragging over it, depending on context
function dragSelectItem( span, itemType ) {
	for (var item = span.firstChild; item != null; item=item.nextSibling ) {
		if (item.type == 'checkbox') {
			break;
		}
	}
	if ( mouseDown == true) {
		if (item.checked == true && selectStatus == false || item.checked == false && selectStatus == true) {
			var listContainer = getListContainer( itemType );
			if ( item.checked == true ) {
				//item.checked = false;
				setCheckboxes( item.value, false );
				removeListItem( listContainer, item.value );
			}
			else {
				//item.checked = true;
				setCheckboxes( item.value, true );
				listCheckedItem( listContainer, item.name, item.value );
			}
		}
	}
}

// Attach a mouse event handler for selecting checkboxes in the themes menu
function selectThemeItem() {
	selectItem( this, "themes" );
}

// Attach a mouse event handler for selecting checkboxes in the locations menu
function selectLocationItem() {
	selectItem( this, "locations" );
}

// Attach a mouse event handler for selecting checkboxes
// kludge!!!
function selectItem(span, itemType ) {
	for (var item = span.firstChild; item != null; item=item.nextSibling ) {
		if (item.type == 'checkbox') {
			break;
		}
	}
	

	selectUnselect( item.name, item.value, itemType, item.checked );
	/*var listContainer = getListContainer( itemType );
	if ( item.checked == true ) {
		//item.checked = false;
		setCheckboxes( item.value, false );
		selectStatus = false;
		removeListItem( listContainer, item.value );
	}
	else {
		//item.checked = true;
		setCheckboxes( item.value, true );
		selectStatus = true;
		listCheckedItem( listContainer, item.name, item.value );
	}*/
}

// Handle the checking/unchecking of a checkbox 
function selectUnselect( itemName, itemValue,  itemType, isChecked ) {
	var listContainer = getListContainer( itemType );
	if ( isChecked == true ) {
		//item.checked = false;
		setCheckboxes( itemValue, false );
		selectStatus = false;
		removeListItem( listContainer, itemValue );
	}
	else {
		//item.checked = true;
		setCheckboxes( itemValue, true );
		selectStatus = true;
		listCheckedItem( listContainer, itemName, itemValue );
	}
}

// sets all checkboxes that meet the 
function setCheckboxes( value, checked ) {
  //alert("hey" + value);
	var boxes = document.getElementsByTagName( 'input' );
	for (var i=0; i<boxes.length; i++) {
		if ( boxes[i].value == value ) {
			//alert( boxes[i].type );
			boxes[i].checked = checked;
		}
	}
}

function setMouseDown() {
	mouseDown = true;
}

function setMouseUp() {
	mouseDown = false;
}


// return value attribues of all the checkboxes inside a div
// warning: assumes that checkboxes are the only <input> tags in the div
function getCheckboxValues( container, checkedOnly ) {
	var checked = new Array();
	var elements = container.getElementsByTagName( 'input' );
	var j = 0;
	for( var i=0; i<elements.length; i++ ) {
		if ( checkedOnly == true &&  elements[i].checked == false ) {
			continue;
		}
		checked[j] = elements[i].value;
		j++;
	}
	return checked;

}

// return an array with the 'value' attributes of all selected checkboxes in one popup menu
function getChecked( container ) {
	var checked = new Array();
	var elements = container.getElementsByTagName( 'input' );
	var j = 0;
	for( var i=0; i<elements.length; i++ ) {
		if ( elements[i].checked == true ) {
			checked[j] = elements[i].value;
			j++;
		}
	}
	return checked;
}

function getListed( container ) {
	var listed = new Array();
	var elements = container.getElementsByTagName( 'p' );
	var j = 0;
	for( var i=0; i<elements.length; i++ ) {
		if ( elements[i].title != "" ) {
			listed[j] = elements[i].title;
			j++;
		}
	}
	return listed;

}


// convert an array of strings into a single comma-separated list
function arrToStr( arr ) {
	var str = "";
	for( var i=0; i<arr.length; i++ ) {
		if (str != "" ) {
			str += ",";
		}
		str += arr[i];
	}
	return str;
}


// execute a Findgeodata query 
// called by an onclick event in findgeodata.php
// returns: nothing
// side effect: loads the results page into an iframe on findgeodata.php
function doQuery(sortorder) {

	showResultsLoading();	// 
	resultsRequested = true;
	var url = "findgeodata/browse_results.php?";
	window.frames["results_iframe"].location= url + buildQueryString(sortorder);
}

function doPrintableQuery() {
	var url = "printable_results.php?printable=1&" + buildQueryString();
	window.open( url );

}


// build a URL to call browse_results.php with a HTTP query string that specifies a Findgeodata query
// returns the URL
function buildQueryString() {
	var typesContainer = document.getElementById('types');
	typesInput =  getChecked( typesContainer );
	var typesStr = arrToStr( typesInput );
	//alert( typesStr );

	var themesContainer = document.getElementById('themesList');
	themesInput = getListed( themesContainer );
	var themesStr = arrToStr( themesInput );
	//alert( themesStr );

	var locationsContainer = document.getElementById('locationsList');
	locationsInput = getListed( locationsContainer );
	var locationsStr = arrToStr( locationsInput );
	//alert( locationsStr );

	// handle sort order. default is by location
	//var sortorder = "location"; // sortorder is not declared globally
	if (arguments.length == 1) {
		sortorder = arguments[0];
	}

	var str = "locations=" + escape(locationsStr)+ "&themes=" + escape(themesStr) + "&types=" + escape(typesStr) + "&sortorder=" + escape(sortorder);

	return str;
}

function procPlaceFinder() {
	var input = document.getElementById( "placenamesInput" );
	var args = "?input=" + escape( input.value );
	window.frames["placefinder_iframe"].location="findgeodata/placefinder.php" + args;
	//alert( str );
}


function showResultsLoading() {
	var msg = "Searching";
	if (resultsRequested)
	{
		msg = "Updating";
	}
	var html = "<div style='margin-left:82px;margin-top:15px;font-weight:bold;font-size:120%;color:#993333'>" + msg + "</div>";
	var resultsContainer = document.getElementById( "results_container" );
	resultsContainer.innerHTML = html;	
}

function updateTallies( me ) {
	alert( me );
}

//***created by Jared, used to load county data in image map****
//based on code from doQuery and buildQueryString functions
//added calls to setcheckboxes, getListFromPopup, and listCheckedItem 
//sortOrder defined in buildQueryString and locationStr from clicked on county
function doMapQuery(county) {

	showResultsLoading();	// 
	resultsRequested = true;
	var url = "findgeodata/browse_results.php?";
	window.frames["results_iframe"].location= url + buildQueryStringMap(county);
}


function buildQueryStringMap(county ) {
	var typesContainer = document.getElementById('types');
	typesInput =  getChecked( typesContainer );
	var typesStr = arrToStr( typesInput );
	//alert( typesStr );

	var themesContainer = document.getElementById('themesList');
	themesInput = getListed( themesContainer );
	var themesStr = arrToStr( themesInput );
	//alert( themesStr );
	
	var locationsStr = county + ":county,Wisconsin:state";
	//alert( locationsStr );
	
	
	setCheckboxes( county+":county", true );
	listCheckedItem( document.getElementById( 'locationsList' ), county, county+ ":county" );
  getListFromPopup( "placemenu" );
	
	sortorder = "location";
	
	var str = "locations=" + escape(locationsStr)+ "&themes=" + escape(themesStr) + "&types=" + escape(typesStr) + "&sortorder=" + escape(sortorder);
	return str;
}

//******end code created by Jared***********


/*
function showResourceHoldings() {

	var siteBox = document.getElementById( 'siteBox' );
	var metaBox = document.getElementById( 'metaBox' );
	var spanArr = document.getElementsByTagName( 'span' );

	var idx = -1;
	if (siteBox.checked == true && metaBox.checked == false ) {
		idx = 1;
		//alert( "sites" );
	}
	else if (siteBox.checked == false && metaBox.checked == true) {
		idx = 2;
		//alert( "meta" );
	}
	else if (siteBox.checked == true && metaBox.checked == true) {
		//alert( "both checked" );
		idx = 0;
	}
	var thisSpan;
	for( var i=0; i<spanArr.length; i++ ) {
		thisSpan = spanArr[i];
	
		if (thisSpan.className == 'spanData') {	
			numRecords = 0;
			if (idx != -1) {
				dataArr = thisSpan.title.split( "," );
				numRecords = dataArr[ idx ];
			}
			thisSpan.innerHTML =  String(numRecords) ;
			if (numRecords == 0) {
				thisSpan.previousSibling.style.color = "#999999";
			}
			else if ( thisSpan.previousSibling.style.color = "#999999" ) {
				thisSpan.previousSibling.style.color = "#000000";
			}
		}
	}
}

	*/
