
//Globals
var gpath = 'graphics/'; //Graphics path
var response;	//xmlhttp response
var xmlHttp;	//xmlhttp object
var sessionTimeout; //Session's setTimeout holder
var csvWindow;

//Disable "enter" key.
function killEnter(ev)
{
	if (ev == null)
		ev = window.event;
	
	var which = -1;
	if (ev.which)
		which = ev.which;
	else if (ev.keyCode)
		which = ev.keyCode;
		
	if (which == 13)
		return false;
}
//Mouseover effect for button background
function domouseover(btnId) 
{
	document.getElementById(btnId).style.backgroundImage = 'url(' + gpath + 'button_hover.gif' + ')';
}

function domouseout(btnId) 
{
	document.getElementById(btnId).style.backgroundImage = 'url(' + gpath + 'button.gif' + ')';
}

//Start session timeout countdown
function startSession(interval)
{
	clearTimeout (sessionTimeout); //stop any previous timeouts that may be running.
	sessionTimeout = setTimeout('timeoutAlert()', interval);
}

//Session timeout alert
function timeoutAlert()
{
	alert ('Your session has timed out. Please login\n' +
	'again to resume working with this site.');
	window.open('Logout.aspx' + window.location.search + "&timeout=yes", '_self');
}

//Logout
function logout()
{
	if ((window.location.pathname).indexOf('protected') == -1)
		window.open('protected/Logout.aspx' + window.location.search, '_self');
	else
		window.open('Logout.aspx' + window.location.search, '_self');
}

//Show the rest of the tutorial in a new window.
function showTutorial()
{
	window.open('Tutorial_contd.htm', 'tutorialContinued',
		'width=688px, height=600px, resizable=0, scrollbars=1');
}

//Show the concept processing page.
function showConceptProcessing(dSName, dSPath, dSType, dSNName)
{
	var qString = cleanQstring(window.location.search);
	var url = 'ConceptProcessing.aspx' + qString + '&dSName=' + dSName + '&dSPath=' + dSPath +
		'&dSType=' + dSType + '&dSNName=' + dSNName + "&operation=build";
	window.open(url, 'conceptProcessing',
		'width=688px, height=600px, resizable=0, scrollbars=1');
	return false;
}

//Show the csv processing page.
var closedFromDSType = false;
function showCSVProcessing()
{
	//Make sure this ID matches that of the data source type selection
	//box of the aspx community page!
	var elem = document.getElementById('dSType');
	if (elem.options[elem.selectedIndex].value.toLowerCase() == "csv")
	{
		var qString = cleanQstring(window.location.search);
		var url = 'CSVProcessing.aspx' + qString;
		csvWindow = window.open(url, 'csvProcessing',
			'width=688px, height=600px, resizable=0, scrollbars=1, status=0');
	}
	
	else
	{
		if (csvWindow)
		{
			closedFromDSType = true;
			csvWindow.close();
		}
	}
}

//Persist the csvWindow object
function persistCSVWin(elem)
{
	csvWindow = elem;
}

//Perform operations to make sure user decides what to do with the files uploaded in the
//csv window if any.
var accepted = false;
var hasFiles = 'false';
function doCSVWinUnload()
{	
	setTimeout('internalDo()', 50); //Give the window time to close.
}

function internalDo()
{
	if (csvWindow.closed)
	{
		var confirmed = false;
		
		if (accepted)
		{
			confirmed = true;
			accepted = false;
		}
		
		else
		{
			if (hasFiles == 'true')
			{
				var msg = 'The CSV file upload window has been closed without specifying ' +
					'what to do with the uploaded files. Click \'OK\' to keep them and proceed with ' +
					'the data source addition or \'Cancel\' to discard them and abort.'
					
				confirmed = confirm(msg);
			}
		}
		
		var elem = document.getElementById('dSType');
		var selInd = elem.selectedIndex;
		
		//Emulating postback.
		try //Aligns mozilla browsers' behaviour to that of IE when dSType's index changes and the confirm box is displayed.
		{
			if (!closedFromDSType)
			{
				for (var i=0; i<elem.options.length; i++)
				{
					if (elem.selectedIndex != i)
					{
						elem.selectedIndex = i;
						break;
					}
				}
			}
		}
		
		catch(ex)
		{
			for (var i=0; i<elem.options.length; i++)
			{
				if (elem.selectedIndex != i)
				{
					elem.selectedIndex = i;
					break;
				}
			}
		}
		//Make sure this ID matches that of the data source type selection
		//box of the aspx community page!
		if (confirmed)
			alert ('Please click on "ADD DATA SOURCE" on the community page to continue the addition process.');
			
		window.__doPostBack('dSType', 'fromScript|' + confirmed + '|' + selInd);
	}
}

//Show the data requirements page
function showDataReq()
{
	var qString = cleanQstring(window.location.search);
	var url = 'DataRequirements.htm' + qString;
	window.open(url, 'dataRequirements',
		'width=688px, height=600px, resizable=0, scrollbars=1');
}

//Check if the provider path field is empty when it's used to rename data source.
function checkProvPathField(id)
{
	var obj = document.getElementById(id);
	if ((obj.value.length == 0) || !whiteSpaceCheck(obj.value))
	{
		obj = document.getElementById(id + 'ErrorMsg');
		obj.innerHTML = 'Error: Please provide a code name for your data source.';
		obj.style.display = 'block';
		return false;
	}
	
	return true;
	
}

//Check for empty required fields in application forms
function checkForm(formId)
{
	var obj, str;
	var rtnValue = true;
	
	if (formId == 'userInfo')
	{
		str = document.forms['userInfo'].fName.value;
		if ((str.length == 0) || !whiteSpaceCheck(str))
		{
			obj = document.getElementById('fNameErrorMsg');
			obj.innerHTML = 'Please provide your first name!';
			obj.style.display = 'block';
			rtnValue = false;
		}
	
		else
		{
			obj = document.getElementById('fNameErrorMsg');
			obj.innerHTML = '';
			obj.style.display = 'none';
		}
	
		str = document.forms['userInfo'].lName.value;
		if ((str.length == 0) || !whiteSpaceCheck(str))
		{
			obj = document.getElementById('lNameErrorMsg');
			obj.innerHTML = 'Please provide your last name!';
			obj.style.display = 'block';
			rtnValue = false;
		}
	
		else
		{
			obj = document.getElementById('lNameErrorMsg');
			obj.innerHTML = '';
			obj.style.display = 'none';
		}
	
		str = document.forms['userInfo'].newUName.value;
		if ((str.length == 0) || !whiteSpaceCheck(str))
		{
			obj = document.getElementById('newUNameErrorMsg');
			obj.innerHTML = 'Please provide your preferred username!';
			obj.style.display = 'block';
			rtnValue = false;
		}
	
		else
		{
			obj = document.getElementById('newUNameErrorMsg');
			obj.innerHTML = '';
			obj.style.display = 'none';
		}
	
		str = document.forms['userInfo'].newPwd.value;
		if ((str.length == 0) || !whiteSpaceCheck(str))
		{
			obj = document.getElementById('newPwdErrorMsg');
			obj.innerHTML = 'Please provide your preferred password!';
			obj.style.display = 'block';
			document.forms['userInfo'].pwdRepeat.value = '';
			rtnValue = false;
		}
	
		else
		{
			if (str != document.forms['userInfo'].pwdRepeat.value)
			{
				obj = document.getElementById('newPwdErrorMsg');
				obj.innerHTML = 'Password mismatch!' +
				'<p>You must enter the same password twice.</p>';
				obj.style.display = 'block';
				document.forms['userInfo'].newPwd.value = '';
				document.forms['userInfo'].pwdRepeat.value = '';
				rtnValue = false;
			}
	
			else
			{
				obj = document.getElementById('newPwdErrorMsg');
				obj.innerHTML = '';
				obj.style.display = 'none';
			}
		}
	
		str = document.forms['userInfo'].email.value;
		if ((str.length == 0) || !whiteSpaceCheck(str))
		{
			obj = document.getElementById('emailErrorMsg');
			obj.innerHTML = 'Please provide email!';
			obj.style.display = 'block';
			rtnValue = false;
		}
	
		else
		{
			obj = document.getElementById('emailErrorMsg');
			obj.innerHTML = '';
			obj.style.display = 'none';
		}
	}
	
	if (formId == 'comInfo')
	{
		str = document.getElementById('cName').value;
		if ((str.length == 0) || !whiteSpaceCheck(str))
		{
			obj = document.getElementById('cNameErrorMsg');
			obj.innerHTML = 'Please provide a name for your community!';
			obj.style.display = 'block';
			rtnValue = false;
		}
	
		else
		{
			obj = document.getElementById('cNameErrorMsg');
			obj.innerHTML = '';
			obj.style.display = 'none';
		}
	}
	
	if (formId == 'dSInfo')
	{
		str = document.getElementById('providerPath').value;
		if ((str.length == 0) || !whiteSpaceCheck(str))
		{
			obj = document.getElementById('providerPathErrorMsg');
			obj.innerHTML = 'Please provide the path to your data source!';
			obj.style.display = 'block';
			rtnValue = false;
			
			obj = document.getElementById('miniContentDiv');
			obj.innerHTML = '';
			obj.style.display = 'none';
		}
	
		else
		{
			obj = document.getElementById('providerPathErrorMsg');
			obj.innerHTML = '';
			obj.style.display = 'none';
		}
	}
	
	if (formId == 'comAdminEmailSend')
	{
		str = document.getElementById('subject').value;
		if ((str.length == 0) || !whiteSpaceCheck(str))
		{
			obj = document.getElementById('subjectErrorMsg');
			obj.innerHTML = 'Please specify a subject for you email!';
			obj.style.display = 'block';
			rtnValue = false;
		}
		
		else
		{
			obj = document.getElementById('subjectErrorMsg');
			obj.innerHTML = '';
			obj.style.display = 'none';
		}
		
		str = document.getElementById('body').value;
		if ((str.length == 0) || !whiteSpaceCheck(str))
		{
			obj = document.getElementById('bodyErrorMsg');
			obj.innerHTML = 'Please enter your message here!';
			obj.style.display = 'block';
			rtnValue = false;
		}
		
		else
		{
			obj = document.getElementById('bodyErrorMsg');
			obj.innerHTML = '';
			obj.style.display = 'none';
		}
	}
	
	return rtnValue;
}

//Process cache download functions here and call the download.aspx
//page from here so that CommunityPage doesn't hang on the download.
function fix_dCLErr()
{
	var selectList, control;
	 selectList = document.getElementById('dSCopyList');
	 control = document.getElementById('dCLErr');
	if (selectList.selectedIndex != -1)
	{
		control.innerHTML = '';
		control.style.display = 'none';
	}
	
	return true;
}

//Check for fields containing white spaces only.
//Equivalent to empty fields.
function whiteSpaceCheck(str)
{
	for (var i=0; i<str.length; i++)
	{
		if (str.substring(i, i+1) != " ")
			return true;
	}
	
	return false;
}

//Clean the query string to avoid duplicates.
function cleanQstring(queryStr)
{
	var pairs, singles;
	var newQstring = "";
	
	pairs = queryStr.split('&');
	for (var i=0; i<pairs.length; i++)
	{
		singles = pairs[i].split('=');
		if ((singles[0] != 'pBar') && (singles[0] != 'timer') &&
			(singles[0] != 'error') && (singles[0] != 'setAt') &&
			(singles[0] != 'cfm') && (singles[0] != 'pageIndex') &&
			(singles[0] != 'pageIndex2'))
			newQstring += singles[0] + '=' + singles[1] + '&';
	}
	
	newQstring = newQstring.substring(0, newQstring.lastIndexOf('&'));
	return newQstring;
}

//Poll the database for progress on the cache update --AJAX--
function pollProgress(timerID, pBID)
{
	var currentPage, qString;
	
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null)
	{
		alert ('Your browser does not support HTTP Request.\nPlease upgrade to the latest version.');
		return;
	}
	
	xmlHttp.onreadystatechange = updateProgress;
	
	currentPage = window.location.pathname;
	currentPage = currentPage.substring(currentPage.lastIndexOf('/') + 1);
	qString = cleanQstring(window.location.search);
	var url = currentPage + qString + '&sid=' + Math.random() + '&timer=' + timerID +
		'&pBar=' + pBID;
	
	if (currentPage.indexOf('CommunityPage') != -1) //Add the data source id to the url.
	{
		var dSId = document.getElementsByName(
			pBID.substring(0, pBID.lastIndexOf("_")))[0].value;
		url = url + '&dSId=' + dSId;
	}

	xmlHttp.open ('GET', url, true);
	xmlHttp.send(null);
}

//Poll the database for progress on the confirmation --AJAX--
function pollConfirm(timerID, cfmID)
{
	var currentPage, qString;
	
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null)
	{
		alert ('Your browser does not support HTTP Request.\nPlease upgrade to the latest version.');
		return;
	}
	
	xmlHttp.onreadystatechange = updateConfirm;
	
	currentPage = window.location.pathname;
	currentPage = currentPage.substring(currentPage.lastIndexOf('/') + 1);
	qString = cleanQstring(window.location.search);
	
	var url = currentPage + qString + '&sid=' + Math.random() + '&timer=' + timerID +
		'&cfm=' + cfmID;
		
	if (currentPage.indexOf('CommunityPage') != -1) //Add the data source id to the url.
	{
		var dSId = document.getElementsByName(
			cfmID.substring(0, cfmID.lastIndexOf("_")))[0].value;
		url = url + '&dSId=' + dSId;
	}

	xmlHttp.open ('GET', url, true);
	xmlHttp.send(null);
}

//Helper function for datagrid paging --AJAX--
function doPage(parent, pageReq)
{
	var currentPage, qString, currentDataGridPage, url, pageIndex;
 
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null)
	{
		alert ('Your browser does not support HTTP Request.\nPlease upgrade to the latest version.');
		return;
	}
	
	xmlHttp.onreadystatechange = dGPageChanged;
	
	currentPage = window.location.pathname;
	currentPage = currentPage.substring(currentPage.lastIndexOf('/') + 1);
	qString = cleanQstring(window.location.search);
	
	currentDataGridPage = document.getElementById(parent).innerHTML;
	currentDataGridPage = currentDataGridPage.substring(
	currentDataGridPage.indexOf('| Page ') + '| Page '.length, 
	currentDataGridPage.indexOf(' |'));
	
	currentDataGridPage = currentDataGridPage - 1;
	
	if ((parent == 'dSPagingLbl') || (parent == 'usrPagingLbl'))
	{
		switch (pageReq)
		{
			case 'next':
				pageIndex = Number(currentDataGridPage) + 1;
			break;
			
			case 'previous':
				pageIndex = Number(currentDataGridPage) - 1;
			break;
			
			case 'last':
				pageIndex = pageReq;
			break;
			
			case 'first':
			default :
				pageIndex = 0;
			break;
		}
		if (parent == 'dSPagingLbl')
			url = currentPage + qString + '&pageIndex=' + pageIndex;
		if (parent == 'usrPagingLbl')
			url = currentPage + qString + '&pageIndex2=' + pageIndex;
		window.open(url, '_self');
	}

	else
	{		
		url = currentPage + qString + '&sid=' + Math.random() + '&page=' + pageReq +
			'&parent=' + parent + '&current=' + currentDataGridPage;

		xmlHttp.open ('GET', url, true);
		xmlHttp.send(null);
	}
}

//Create and xmlhttp object --AJAX--
function GetXmlHttpObject()
{ 
	var XMLHttp = null;

	try
	{
		XMLHttp = new ActiveXObject('Msxml2.XMLHTTP');
	} 
	catch (e) 
	{
		try 
		{
			XMLHttp = new ActiveXObject('Microsoft.XMLHTTP');
		}

		catch (e)
		{
		} 
	}

	if (XMLHttp == null)
	{
		XMLHttp = new XMLHttpRequest();
	}
	return XMLHttp;
}

//Check if the xmlhttp request's response is ready --AJAX--
function checkReadyState(obj)
{
	if (obj.readyState == 4 || obj.readyState=='complete')
	{
		if (obj.status == 200)
		{
			return true;
		}
			else
		{
			alert('Problem retrieving XML data.');
			//document.body.innerHTML = obj.responseText;
		}
	}
}


//Apply the changes sent from the server
function dGPageChanged()
{
	if (checkReadyState(xmlHttp))
	{
		var pairs, singles;
		response = xmlHttp.responseText;
		
		if (response.indexOf('Error.aspx') == -1)
			pairs = response.split('|&|');
		else
			window.open(response, '_self');
			
		for (var i=0; i<pairs.length; i++)
		{
			singles = pairs[i].split('|=|');
			
			if (singles[0] != 'interval')
			{
				if (singles[0].indexOf('Current') != -1)
				{
					document.getElementsByName(singles[0])[0].value = singles[1];	
				}
				
				else
				{
					document.getElementById(singles[0]).innerHTML = singles[1];
				}
			}
			
			else
			{
				startSession(singles[1]);
			}
		}
	}
}

//Update the progress bar
function updateProgress()
{
	if (checkReadyState(xmlHttp))
	{
		var pairs, singles, percentage, pBID, timerID, pageIndex;
		var currentPage, qString, url;
		response = xmlHttp.responseText;
		
		if (response.indexOf('Error.aspx') == -1)
			pairs = response.split('|&|');
		else
			window.open(response, '_self');
		//This means the user's browser session has ended
		//and the failed login redirect page is being sent as a response.
		//So we trigger a session timeout.
		if (pairs.length != 4) 	
			window.open('SessionTimeout.aspx?caller=script', '_self');
				   				   
		for (var i=0; i<pairs.length; i++)
		{
			singles = pairs[i].split('|=|');
			
			switch (singles[0])
			{
				case 'pBar':
					pBID = singles[1];
				break;
				
				case 'timer':
					timerID = singles[1];
				break;
				
				case 'percentage':
					percentage = Number(singles[1]);
				break;
				
				case 'interval':
					startSession(singles[1]);
				break;
				
				default:
					//N/A
				break;
			}
		}
		
			currentPage = window.location.pathname;
			currentPage = currentPage.substring(currentPage.lastIndexOf('/') + 1);
			qString = cleanQstring(window.location.search);
		
		
		if (percentage >= 0)
		{
			setAt(pBID, percentage);	
	
			if (percentage >= 100)
			{
				clearInterval(eval(timerID));
				
				url = currentPage + qString + '&error=100&setAt=' +
					getCompletion(pBID) + '&pBar=' + pBID;
				
				if (currentPage.indexOf('CommunityPage') != -1)
				{
					pageIndex = document.getElementsByName('dSDGCurrentPageIndex')[0].value;
					url  += '&pageIndex=' + pageIndex
				}
				
				window.open(url, '_self');
			}
		}
		
		else
		{
			clearInterval(eval(timerID));
			url = currentPage + qString + '&error=' + percentage + '&setAt=' +
				getCompletion(pBID) + '&pBar=' + pBID;
				
			if (currentPage.indexOf('CommunityPage') != -1)
				{
					pageIndex = document.getElementsByName('dSDGCurrentPageIndex')[0].value;
					url  += '&pageIndex=' + pageIndex
				}
			
			window.open(url, '_self');
		}
	}
}

//Update the confirm message
function updateConfirm()
{
	if (checkReadyState(xmlHttp))
	{
		var pairs, singles, status, cfmID, timerID, pageIndex;
		var currentPage, qString, url;
		response = xmlHttp.responseText;
		
		if (response.indexOf('Error.aspx') == -1)
			pairs = response.split('|&|');
		else
			window.open(response, '_self');
		//This means the user's browser session has ended
		//and the failed login redirect page is being sent as a response.
		//So we trigger a session timeout.
		if (pairs.length != 4) 	
			window.open('SessionTimeout.aspx?caller=script', '_self');
			
		for (var i=0; i<pairs.length; i++)
		{
			singles = pairs[i].split('|=|');
			
			switch (singles[0])
			{
				case 'cfm':
					cfmID = singles[1];
				break;
				
				case 'timer':
					timerID = singles[1];
				break;
				
				case 'status':
					status = singles[1];
				break;
				
				case 'interval':
					startSession(singles[1]);
				break;
				
				default:
					//N/A
				break;
			}
		}
		
			currentPage = window.location.pathname;
			currentPage = currentPage.substring(currentPage.lastIndexOf('/') + 1);
			qString = cleanQstring(window.location.search);
			
		if ((status == 'updated') || (status == '-1') || (status == '-2'))
		{
			clearInterval(eval(timerID));
			status = (status == 'updated')? 0 : status;
			url = currentPage + qString + '&error=' + status + '&cfm=' + cfmID;
			
			if (currentPage.indexOf('CommunityPage') != -1)
			{
				pageIndex = document.getElementsByName('dSDGCurrentPageIndex')[0].value;
				url  += '&pageIndex=' + pageIndex
			}
			
			window.open(url, '_self');
		}
	}
}

//Show the georeferenced records window
function showGeorefed(id, numCor, isByUser)
{
	var url, qString;
	
	qString = cleanQstring(window.location.search);
	url = 'ShowDetails.aspx' + qString + '&totalCor=' + numCor + '&show=' + id +
		'&byUser=' + isByUser;
	
	window.open(url, 'GeorefedRecsDetails',
		'width=800px, height=400px, resizable=0, scrollbars=1');
}

//Expand/collapse the rows in the sample table to show correstions
function expCol(rowNum, TableName)
{
	var table = document.getElementById(TableName);

	if (table.rows[rowNum*2].style.display == 'none')
	{
		table.rows[rowNum*2].style.display = '';
		table.rows[(rowNum*2)-1].cells[0].innerHTML = 
			'<a class=\'ExpColLinks\' href="javascript:expCol(' + rowNum + ', \'' + TableName + '\')">-</a>';
	}
	
	else
	{
		table.rows[rowNum*2].style.display = 'none';
		table.rows[(rowNum*2)-1].cells[0].innerHTML = 
			'<a class=\'ExpColLinks\' href="javascript:expCol(' + rowNum + ', \'' + TableName + '\')">+</a>';
	}
}

//Show upload initialization message
var progressCount = 0;
var navUrl = null;
function showProgInitMsg(lblId, uploadId, dsCodeId, progLinkId)
{
	progressCount++;
	var str = document.getElementById(uploadId).value;
	var dSCodeTxt = document.getElementById(dsCodeId).value;
	var haveFile = document.getElementsByName('haveFile')[0];
	var progressL = document.getElementById(progLinkId);
	navUrl = (navUrl == null)? progressL.onclick.toString() : navUrl;
	
	if (haveFile.value == 'false')
	{
		if ((dSCodeTxt.length == 0) || !whiteSpaceCheck(dSCodeTxt))
		{
			document.getElementById(lblId).innerHTML = '<span style=\'color: red\'>Error: No data source code provided.</span>';
			if (window.event)
				window.event.returnValue = false; //Prevents IE from submitting form even when false is returned.
			return false;
		}
	}
	
	if ((str.length != 0) && whiteSpaceCheck(str))
	{
		if (/.*\.(csv)$/gi.test(str))
		{
			document.getElementById(lblId).innerHTML = '';
			var str1 = navUrl.match(/\(.*\)/gi)[1].replace(/\(|\)/g, '');
			var target = str1.match(/"[^"]*"|\'[^\']*\'/gi)[1].replace(/"|\'/g, '').toString();
		
			var keyList = str1.split('&');
			for (var i=0; i<keyList.length; i++)
			{
				var key = keyList[i].split('=')[0];
				if (key.toLowerCase() == 'postbackid')
				{
					keyList[i] = key + '=' + target + progressCount;
					break;
				}
			}

			str1 = keyList.join('&');
			navUrl = navUrl.replace(/window.open(.*)/, 'window.open(' + str1 + ')');
			progressL.onclick = function () {eval ('window.open(' + str1 + ')')};
			progressL.style['display'] = '';
			if (window.event)
				window.event.returnValue = true;
			return true;
		}
		
		else
		{
			document.getElementById(lblId).innerHTML = '<span style=\'color: red\'>Error: Selected file does not appear to be in CSV format.</span>';
			if (window.event)
				window.event.returnValue = false;
			return false;
		}
	}
	
	else
	{
		document.getElementById(lblId).innerHTML = '<span style=\'color: red\'>Error: No file selected.</span>';
		if (window.event)
			window.event.returnValue = false;
		return false;
	}
}