// CONSTANTS
BASE_TNUID = '52';
BASE_URL = 'http://osuc.biosci.ohio-state.edu/hymDB/';
ICON_EXPAND_LOCATION = '/images/icon-expand.png';
ICON_COLLAPSE_LOCATION = '/images/icon-collapse.png';
SECTION_BODY_COLUMNS = 3;
SECTION_IMAGES_COLUMNS = 6;
POPUP_WIDTH = '300px';
MAX_IMAGE_WIDTH = 500;
IMG_TIMER_DEFAULT = 5;
MAX_RESULT_PAGE = 60;

// GLOBAL VARIABLES
currentTNUID = BASE_TNUID;
currentURL = '';
currentPos = {x:0, y:0};
currentTaxon = '';
currentBoxSearchID = 0;
currentGeneralBoxSearchID = 0;
currentSearchID = 0;
currentTaxonSearchID = 0;
currentPersonSearchID = 0;
totalSearchResults = 0;
currentSearchElementID = '';
currentResultElementID = '';
currentSearchResultPos = 0;
overrideResultsHide = false;
popupTemp1 = '';
popupTemp2 = '';
saveExcelCallback = null;
saveExcelCuids = null;
saveExcelFilename = null;

// Google Analytics Tracking Setup
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

// FUNCTIONS
function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split('&');
	
	for (var i=0; i < vars.length; i++) {
		var pair = vars[i].split('=');
		
		if (pair[0] == variable) {
			var szReturn = pair[1];
			
			// Decode some values
			szReturn = szReturn.replace(/\+/g, ' ');
			/*szReturn = szReturn.replace(/%20/g, ' ');
			szReturn = szReturn.replace(/%25/g, '%');
			szReturn = szReturn.replace(/%28/g, '(');
			szReturn = szReturn.replace(/%29/g, ')');
			szReturn = szReturn.replace(/%2C/g, ',');*/
			
			return unescape(szReturn);
		}
	}
	
	return -1;
}

function setCookie(name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	
	var expires_date = new Date(today.getTime() + (expires));
	
	document.cookie = name + '=' + escape(value) + ((expires) ? ';expires=' + expires_date.toGMTString() : '') + ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '') + ((secure) ? ';secure' : '');
}

function getCookie(name) {
	var start = document.cookie.indexOf(name + '=');
	var len = start + name.length + 1;
	
	if ((!start) && (name != document.cookie.substring(0, name.length))) {
		return null;
	}
	
	if (start == -1) {
		return null;
	}
	
	var end = document.cookie.indexOf(';', len);
	
	if (end == -1) {
		end = document.cookie.length;
	}
	
	return unescape(document.cookie.substring(len, end));
}

function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + '=' + ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '') + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	}
}

function encodeURL(szText) {
	szText = escape(szText);
	szText = szText.replace(/\+/g, '%2B');
	szText = szText.replace(/\//g, '%2F');
	
	return szText;
}

function encodeJavascript(szText) {
	if (szText) {
		szText = szText.replace(/'/g, '\\\'');
	}
	
	return szText;
}

function sendJSONRequest(szURL, szMethod, fCallback, fStart, option) {
	if (typeof(szMethod) == 'undefined' || szMethod.toUpperCase() == 'GET') {
		// Create a new script object (JSON-style query)
		aObj = new JSONscriptRequest(szURL);
		// Build the script tag
		aObj.buildScriptTag();
		// Execute (add) the script tag
		aObj.addScriptTag();
	} else if (szMethod.toUpperCase() == 'POST') {
		// Only works for local servers
		var http;
		
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			http = new XMLHttpRequest();
			
			if (http.overrideMimeType) {
				http.overrideMimeType('text/html');
			}
		} else if (window.ActiveXObject) { // IE
			try {
				http = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					http = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
		
		http.open("POST", szURL, true);
		
		// Send the proper header information along with the request
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", option.length);
		http.setRequestHeader("Connection", "close");
		
		// Call a function when the state changes.
		http.onreadystatechange = function() {
			if (http.readyState == 4) {
				if (http.status == 200) {
					fCallback(eval('(' + http.responseText + ')'));
				} else {
					alert('There was a problem with the request.');
				}
			}
		}
		
		http.send(option);
	} else if (szMethod.toUpperCase() == 'FORM') {
		AIM.submit(option, {'onStart':fStart, 'onComplete':fCallback}, true);
	} else if (szMethod.toUpperCase() == 'UPLOAD') {
		// This is just a preloader which waits to be submitted though form submit
		$(document).ready(function() { 
			var options = {
				beforeSubmit: function () {
					fStart();
				},
				success: function (responseText, statusText) {
					fCallback(responseText);
				},
				dataType: 'json',
				type: 'post',
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					alert('AJAX ERROR: ' + errorThrown)
				}
				
				// $.ajax options can be used here too, for example: 
				//timeout:   3000 
			}; 
		 
			// bind form using 'ajaxForm' 
			$('#' + option.form_id).ajaxForm(options); 
		}); 
	} else {
		var formName = buildPostRequest(szURL, option);
		
		// Use the form submitter to actually send the POST request
		AIM.submit(document[formName], {'onStart':fStart, 'onComplete':fCallback}, true);
	}
}

function showLoadingImage(szElementID, nLoadingPixels) {
	// Make sure element is visible
	document.getElementById(szElementID).style.visibility = 'visible';
	
	// Set the element to contain only the loading image
	if (nLoadingPixels) {
		document.getElementById(szElementID).innerHTML = '<img src="/HymOnline/loading.gif" title="Loading..." align="center" style="width: ' + nLoadingPixels + 'px; height: ' + nLoadingPixels + 'px; border-style: none;">';
	} else {
		document.getElementById(szElementID).innerHTML = '<img src="/HymOnline/loading.gif" title="Loading..." align="center" style="width: 32px; height: 32px; border-style: none;">';
	}
}

function hideLoadingImage(szElementID) {
	// Set the element to contain nothing and hide
	var element = document.getElementById(szElementID);
	
	element.innerHTML = '';
	element.style.visibility = 'hidden';
}

function setCursorPosition(browserEvent) {
	var cursor = {x:0, y:0};
	
	/*browserEvent = browserEvent || window.event;
	
	if (browserEvent.pageX || browserEvent.pageY) {
		cursor.x = browserEvent.pageX;
		cursor.y = browserEvent.pageY;
	} else {
		var docElement = document.documentElement;
		var docBody = document.body;
		
		cursor.x = browserEvent.clientX + (docElement.scrollLeft || docBody.scrollLeft) - (docElement.clientLeft || 0);
		cursor.y = browserEvent.clientY + (docElement.scrollTop || docBody.scrollTop) - (docElement.clientTop || 0);
    }*/
	
	if (browserEvent.pageX) {
		cursor.x = browserEvent.pageX;
		cursor.y = browserEvent.pageY;
	} else if (browserEvent.clientX) {
		cursor.x = browserEvent.clientX + document.body.scrollx - document.body.clientx;
		cursor.y = browserEvent.clientY + document.body.scrollTop - document.body.clientTop;
		
		// include html element space, if applicable
		if (document.body.parentElement && document.body.parentElement.clientx) {
			var bodParent = document.body.parentElement;
			
			cursor.x += bodParent.scrollx - bodParent.clientx;
			cursor.y += bodParent.scrollTop - bodParent.clientTop;
		}
	}
	
	// Set the cursor position to the global variable
	currentPos = cursor;
}

function toggleElement(szSectionID, bUseBlock) {
	var element = document.getElementById(szSectionID);
	
	if (element) {
		if (element.style.visibility != 'visible') {
			if (bUseBlock) {
				element.style.display = 'block';
			} else {
				element.style.display = 'inline';
			}
			element.style.visibility = 'visible';
			
			return true;
		} else {
			element.style.display = 'none';
			element.style.visibility = 'hidden';
			
			return false;
		}
	}
}

function toggleSection(szSectionID, szIconID) {
	var section = document.getElementById(szSectionID);
	var icon = document.getElementById(szIconID);
	
	if (section) {
		if (section.style.visibility != 'visible') {
			section.style.display = 'block';
			section.style.visibility = 'visible';
			icon.src = ICON_COLLAPSE_LOCATION;
			icon.title = 'collapse';
		} else {
			section.style.display = 'none';
			section.style.visibility = 'hidden';
			icon.src = ICON_EXPAND_LOCATION;
			icon.title = 'expand';
		}
	}
}

function togglePopup(szPopupID, show) {
	var popup = document.getElementById(szPopupID);
	var bodyContainer = document.getElementById('hymBodyContainerID');
	
	// Reset default width
	popup.style.width = POPUP_WIDTH;
	
	if (popup) {
		if (popup.style.visibility != 'visible' || show == true) {
			// Set position from global mouse position and make visible
			//popup.style.top = currentPos.y + 'px';
			//popup.style.left = currentPos.x + 'px';
			popup.style.display = 'block';
			popup.style.visibility = 'visible';
			
			// Make background somewhat opaque (check for browser - IE first)
			if (window.ActiveXObject) {
				bodyContainer.style.filter = 'alpha(opacity = 40)';
			} else {
				bodyContainer.style.opacity = .4;
			}
		} else {
			popup.style.display = 'none';
			popup.style.visibility = 'hidden';
			
			// Remove background opacity (check for browser - IE first)
			if (window.ActiveXObject) {
				bodyContainer.style.filter = 'alpha(opacity = 100)';
			} else {
				bodyContainer.style.opacity = 1.0;
			}
		}
	}
}

function toggleImageLink(szImageID, bIsOver) {
	var image = document.getElementById(szImageID);
	
	if (image) {
		// Check for which image to toggle
		switch (szImageID) {
			case 'hymHomeImageID': {
				if (bIsOver) {
					image.src = 'home.gif';
				} else {
					image.src = 'home-gray.gif';
				}
				
				break;
			}
			case 'hymOSUCImageID': {
				if (bIsOver) {
					image.src = 'osuc_logo.gif';
				} else {
					image.src = 'osuc_logo-gray.gif';
				}
				
				break;
			}
			case 'hymMorphBankImageID': {
				if (bIsOver) {
					image.src = 'mbLogo.png';
				} else {
					image.src = 'mbLogo-gray.png';
				}
				
				break;
			}
			case 'hymRSSImageID': {
				if (bIsOver) {
					image.src = 'rss.gif';
				} else {
					image.src = 'rss-gray.gif';
				}
				
				break;
			}
		}
	}
}

function processInfoText() {
	if (getCookie('hymShowInfo') != 'N') {
		showInfoText();
	} else {
		hideInfoText()
	}
}

function showInfoText() {
	deleteCookie('hymShowInfo', '/');
	
	setCookie('hymShowInfo', 'Y', 365, '/');
	
	var elementInfo = document.getElementById('hymBodyInfoID');
	
	if (elementInfo) {
		elementInfo.innerHTML = '<p>The order Hymenoptera contains some 115,000 species and literally millions of specimens in collections around the world. Some parts of this database have extensive information available (e.g., <a href="index.html?id=64" title="Go to the Proctotrupoidea page">Proctotrupoidea</a>, <a href="index.html?id=195000" title="Go to the Platygastroidea page">Platygastroidea</a>, <a href="index.html?id=61" title="Go to the Ceraphronoidea page">Ceraphronoidea</a>, <a href="index.html?id=71" title="Go to the Apoidea page">Apoidea</a>), even to the level of specimens (see <a href="index.html?id=13712" title="Go to the Platygastridae page">Platygastridae</a>, <a href="index.html?id=105" title="Go to the Pelecinidae page">Pelecinidae</a>, <a href="index.html?id=98" title="Go to the Monomachidae page">Monomachidae</a>, <a href="index.html?id=87" title="Go to the Stephanidae page">Stephanidae</a>). These data have been gathered with the collaboration of a number of colleagues. Other taxa still need work. If you would like to contribute to the further development and enhancement of this resource, please contact <a href="mailto:johnson.2@osu.edu">Norman F. Johnson</a> or <a href="mailto:musetti.2@osu.edu">Luciana Musetti</a>. For technical assistance related to Hymenoptera Online services, please contact <a href="mailto:cora.1@osu.edu">Joe Cora</a>.</p><p>Search for taxa, collections, authors, collectors and specimens by typing your simple query in the text box below. Taxon name searches are case-sensitive and a wildcard (%) will automatically be appended to the end of your query (e.g. <a href="search.html?limit=50&name=Telenomus">Telenomus</a>); the same applies to collectors and authors (e.g. <a href="search.html?limit=50&name=Johnson">Johnson</a>), collections (e.g. <a href="search.html?limit=50&name=CNC">CNC</a>), places (e.g. <a href="search.html?limit=50&name=Bahia">Bahia</a>), journals (e.g. <a href="search.html?limit=50&name=Memoirs">Memoirs</a>), and specimen searches by specimen ID (e.g. <a href="search.html?limit=50&name=ANIC%20DB%2032">ANIC DB 32</a>).</p><p>If you would like to see a list of new features, recent changes and recent additions to OSUC online resources, visit the <a href="updates.html" title="Go to the updates pages">updates page</a>. Visit the <a href="inst-full.html?id=1" title="Go to the OSUC collection page">collection page</a> for the C.A. Triplehorn Insect Collection at the Ohio State University for information on its primary and secondary type holdings as well as databased taxa in the collection.</p><a href="javascript:hideInfoText();"><img src="info_hide-icon.gif" id="hymInfoIconID" title="Hide the basic Hymenoptera Online text"></a>';
	}
}

function hideInfoText() {
	deleteCookie('hymShowInfo', '/');
	
	setCookie('hymShowInfo', 'N', 365, '/');
	
	var elementInfo = document.getElementById('hymBodyInfoID');
	
	if (elementInfo) {
		elementInfo.innerHTML = '<a href="javascript:showInfoText();"><img src="info_show-icon.gif" id="hymInfoIconID" title="Show the basic Hymenoptera Online text"></a>';
	}
}

function showHierarchy() {
	var urlStats = BASE_URL + 'OJ_Break.getTaxonHierarchy?tnuid=' + currentTNUID + '&callback=handleHierarchy';
	
	sendJSONRequest(urlStats);
}

function handleHierarchy(jData) {
	if (jData == null) {
		// Parse problem so return
		return;
	}
	
	// Set current taxon
	currentTaxon = jData.taxon;
	
	// Update title with taxon name & author
	document.title += ' > ' + jData.taxon + ' ' + jData.author;
	
	// Handle hierarchy
	var hierarchy = jData.hier;
	var resultHTML = '';
	var currentRank = 'Order'; // Starting rank
	var previousRank;
	var nCount = 0;
	
	// Change starting rank for mites
	if (currentURL.match(/Acarology/)) {
		currentRank = 'Subclass';
	}
	
	// Loop through the hierarchy to display all of the names
	while (currentRank != 'null') {
		// For the first taxon, do not prepend with <
		if (nCount != 0) {
			resultHTML += ' > ';
		} else {
			nCount = 1;
		}
		
		resultHTML += '<a href="index.html?id=' + hierarchy[currentRank].id + '" title="' + currentRank + '">' + hierarchy[currentRank].name + '</a>';
		
		// Get next taxon in hierarchy
		previousRank = currentRank;
		currentRank = hierarchy[currentRank].next;
	}
	
	// Add invalid taxon name to end of hierarchy
	if (hierarchy[previousRank].name != currentTaxon) {
		resultHTML += ' (*' + currentTaxon + ')';
	}
	
	// Set the result HTML for hierarchy
	document.getElementById('hymSubtitleID').innerHTML = resultHTML;
}

function showSearchResults(bSearchOnly) {
	var searchBox = document.getElementById('hymBodyFormInputID');
	var results = document.getElementById('hymBodyInputResultsID');
	
	// Check whether to query the DB for results or set the results position
	if (!bSearchOnly) {
		results.style.left = searchBox.offsetLeft + 'px';
		results.style.top = (searchBox.offsetTop + searchBox.offsetHeight) + 'px';
	}
	
	// Make sure some name is there to search
	if (searchBox.value.length > 1 && searchBox.value.length < 256) {
		// Increment search ID
		currentBoxSearchID++;
		
		// Erase previous search results
		document.getElementById('hymBodyInputResultsID').innerHTML = '';
		
		sendJSONRequest('http://osuc.biosci.ohio-state.edu/hymDB/OJ_Break.getTaxaFromText?name=' + searchBox.value + '%25&limit=10&nameOnly=Y&callback=handleShowTaxonSearchResults');
		sendJSONRequest('http://osuc.biosci.ohio-state.edu/hymDB/OJ_Break.getAgentsFromText?name=' + searchBox.value + '%25&limit=10&callback=handleShowAgentSearchResults');
		
		// Show search results
		results.className = 'hymInputResults';
	}
}

function handleShowTaxonSearchResults(jData) {
	if (jData == null) {
		return;
	}
	
	var szResultHTML = '';
	var taxa = jData.taxa;
	
	// Check if search results are for current search
	if (currentTaxonSearchID == currentBoxSearchID - 1) {
		// If there were no matches, hide results
		if (taxa.length == 0) {
			// Check if other search queries are done
			if (currentPersonSearchID == currentBoxSearchID) {
				// Check if results need hidden
				if (totalSearchResults == 0) {
					hideSearchResults();
				}
			} else {
				totalSearchResults = 0;
			}
		} else {
			// Check if other search queries are not done
			if (currentPersonSearchID != currentBoxSearchID) {
				totalSearchResults = taxa.length;
			}
		}
		
		// Display the results
		for (var taxaCount = 0; taxaCount < taxa.length; taxaCount++) {
			var taxon = taxa[taxaCount];
			
			szResultHTML += '<div class="hymInputResultItem" id="hymInputTaxonResultItem' + taxaCount + 'ID" onMouseOver="javascript:highlightInputResult(\'hymInputTaxonResultItem' + taxaCount + 'ID\');" onMouseOut="javascript:unhighlightInputResult(\'hymInputTaxonResultItem' + taxaCount + 'ID\');"><a href="javascript:copyToInputBox(\'hymBodyFormInputID\',\'hymBodyInputResultsID\',\'' + taxon.name + '\');">' + taxon.name + ' ' + taxon.author + '</a></div>';
		}
		
		document.getElementById('hymBodyInputResultsID').innerHTML += szResultHTML;
	}
	
	// Increment taxon search ID
	currentTaxonSearchID++;
}

function handleShowAgentSearchResults(jData) {
	if (jData == null) {
		return;
	}
	
	var szResultHTML = '';
	var agents = jData.agents;
	
	// Check if search results are for current search
	if (currentPersonSearchID == currentBoxSearchID - 1) {
		// If there were no matches, hide results
		if (agents.length == 0) {
			// Check if other search queries are done
			if (currentTaxonSearchID == currentBoxSearchID) {
				// Check if results need hidden
				if (totalSearchResults == 0) {
					hideSearchResults();
				}
			} else {
				totalSearchResults = 0;
			}
		} else {
			// Check if other search queries are not done
			if (currentTaxonSearchID != currentBoxSearchID) {
				totalSearchResults = agents.length;
			}
		}
		
		// Display the results
		for (var agentCount = 0; agentCount < agents.length; agentCount++) {
			var agent = agents[agentCount];
			
			szResultHTML += '<div class="hymInputResultItem" id="hymInputAgentResultItem' + agentCount + 'ID" onMouseOver="javascript:highlightInputResult(\'hymInputAgentResultItem' + agentCount + 'ID\');" onMouseOut="javascript:unhighlightInputResult(\'hymInputAgentResultItem' + agentCount + 'ID\');"><a href="javascript:copyToInputBox(\'hymBodyFormInputID\',\'hymBodyInputResultsID\',\'' + agent.name + '\');">' + agent.name + '</a></div>';
		}
		
		document.getElementById('hymBodyInputResultsID').innerHTML += szResultHTML;
	}
	
	// Increment person search ID
	currentPersonSearchID++;
}

function hideSearchResults(szResultElementID) {
	if (!overrideResultsHide) {
		var results = document.getElementById(szResultElementID);
		
		currentSearchResultPos = 0;
		
		// Hide search results
		results.className = 'hymInputResultsHidden';
	}
}

function highlightInputResult(szElementID) {
	document.getElementById(szElementID).style.backgroundColor = '#E8E8E8';
	
	overrideResultsHide = true;
}

function unhighlightInputResult(szElementID) {
	document.getElementById(szElementID).style.backgroundColor = '';
	
	overrideResultsHide = false;
}

function copyToInputBox(szSearchElementID, szResultElementID, szValue) {
	document.getElementById(szSearchElementID).value = szValue;
	
	currentSearchResultPos = 0;
	overrideResultsHide = false;
	
	hideSearchResults(szResultElementID);
}

function moveHighlightDown() {
	var baseResultElement = document.getElementById(currentResultElementID);
	
	// Unhighlight current element
	if (currentSearchResultPos > 0) {
		unhighlightInputResult(baseResultElement.childNodes[currentSearchResultPos - 1].id);
	}
	
	// Check if next element exists
	if (baseResultElement.childNodes[currentSearchResultPos]) {
		// Highlight the next item
		highlightInputResult(baseResultElement.childNodes[currentSearchResultPos].id);
		
		currentSearchResultPos++;
	}
}

function moveHighlightUp() {
	var baseResultElement = document.getElementById(currentResultElementID);
	
	// Unhighlight current element
	if (currentSearchResultPos > 0) {
		unhighlightInputResult(baseResultElement.childNodes[currentSearchResultPos - 1].id);
	}
	
	// Check if previous element exists
	if (baseResultElement.childNodes[currentSearchResultPos - 2]) {
		// Highlight the previous item
		highlightInputResult(baseResultElement.childNodes[currentSearchResultPos - 2].id);
		
		currentSearchResultPos--;
	}
}

function selectCurrentHighlight() {
	var baseResultElement = document.getElementById(currentResultElementID);
	
	if (currentSearchResultPos > 0) {
		baseResultElement.childNodes[currentSearchResultPos - 1].getElementsByTagName('a')[0].onclick();
	}
}

function displayPageNavigation(szBaseElementID, szFuncName, nStart, nCount, nLength) {
	var szResult = '';
	
	if (nStart > 0) {
		szResult += '<a href="javascript:' + szFuncName + '(undefined,' + (nStart - MAX_RESULT_PAGE) + ');" title="Get Previous">PREV ' + MAX_RESULT_PAGE + '</a>';
	}
	if (nCount + nStart < nLength) {
		// Check if a separator needs added
		if (nStart > 0) {
			szResult += ' - ';
		}
		
		var nNumResults;
		
		if (nStart + MAX_RESULT_PAGE * 2 < nLength) {
			nNumResults = MAX_RESULT_PAGE;
		} else {
			nNumResults = nLength - (nStart + MAX_RESULT_PAGE);
		}
		
		szResult += '<a href="javascript:' + szFuncName + '(undefined,' + (nStart + MAX_RESULT_PAGE) + ');" title="Get Next">NEXT ' + nNumResults + '</a>';
	}
	
	document.getElementById(szBaseElementID + 'TopID').innerHTML = szResult;
	document.getElementById(szBaseElementID + 'BottomID').innerHTML = szResult;
}

function saveExcel(file_prefix, cuids, callback) {
	// Save the callback function and cuids for later
	saveExcelCallback = callback;
	saveExcelCuids = cuids;
	
	// Open window with processing info
	var currWin = window.open('','_new-Excel',config='height=75,width=400,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no');
	var currWinDoc = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/transitional.dtd"><html><head><link rel="stylesheet" type="text/css" href="http://hol.osu.edu/HymOnline.css"><script type="text/javascript" src="http://hol.osu.edu/HymOnline.js"></script><title>Hymenoptera Online &gt; Specimen Info Download</title></head><body><div class="hymBody"><div class="hymBodySubtitle">Please wait while the Excel file is processed. This operation may take a few minutes...</div></div></body></html>';
	
	currWin.document.write(currWinDoc);
	currWin.moveTo(250, 250);
	
	// Prepare new excel filename
	saveExcelFilename = file_prefix + '_' + (new Date()).getTime() + '.xls';
	var urlExcel = 'http://hymfiles.biosci.ohio-state.edu/scripts/vSysLab.pl?action=createMatEx&file=' + saveExcelFilename + '&callback=saveCuids';
	
	// Send create excel file request
	sendJSONRequest(urlExcel);
}

function saveCuids() {
	// Send request to save the cuids to a file
	sendJSONRequest('/cgi-bin/vSysLab-osuc.pl', 'POST', addExcelRecords, undefined, 'action=saveCuids&filename=' + saveExcelFilename + '&cuids=' + saveExcelCuids);
}

function addExcelRecords(jData) {
	// Open window to create Excel file
	var currWin = window.open('http://hymfiles.biosci.ohio-state.edu/scripts/vSysLab.pl?action=addMatExFile&file=' + saveExcelFilename + '&program=HymOnline&cuid_file=' + jData.filename,'_new-Excel',config='height=75,width=400,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no');
	
	// Set cuids back to null
	saveExcelCuids = null;
}

// Array.unique() - Remove duplicate values
Array.prototype.unique = function(b) {
	var a = [], i, l = this.length;
	
	for(i=0; i<l; i++) {
		if(a.indexOf(this[i], 0, b) < 0) {
			if (this[i].length > 0) {
				a.push(this[i]);
			}
		}
	}
	
	return a;
};

// String.addCommas() - Add commas delimiting thousand blocks
String.prototype.addCommas = function() {
	var nStr = this;
	
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	
	var rgx = /(\d+)(\d{3})/;
	
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	
	return x1 + x2;
}
