$(document).ready(function(){
	uid.triggerRichText();
	/* Delay the initialising of collapsible text a little, so that any code that manipulates
	the dom tree on page load has finished before the initing, since the event handlers added
	during the initing otherwise are lost during the dom operations. */
	setTimeout(uid.collapseCollapsibles, 200);
	uid.initPredefChangeListeners();
	uid.initUtilButtons();
	//$('.input_otherval').keyup(); //Force detection of initial state for the "other" input fields
});

uid = {};

uid.editors = {};
uid.curButton = undefined;
uid.stayTimeout = 1500; //Number of milliseconds the popup stays visible after the mouse has left it or the triggering button.
uid.popupShowing = false;
uid.popupTimeout = 0;
uid.cursorResetTimeout = 0;
uid.openEditInNewWin = true; //The js edit links in the export previews either open in new windows/tabs or in same
uid.defaultInteractionLevel = 2; //1 = disallow editing, 2 = allow editing

uid.initUtilButtons = function(){
	$('a.utilBtn, td.d, td.n').each(function(){
		var interactionLevel;
		if($(this).hasClass('noedit')){
			interactionLevel = 1;
		}
		else {
			interactionLevel = uid.getInteractionLevel();
		}
		if($(this).hasClass('existing') || $(this).attr('id').split('_')[0] == 'd'){
			$(this).click(function(e) {
				uid.popupDataMenu(e, this, $(this).attr('id').split('_')[1], null, null, interactionLevel);
			});
		}
		else if(interactionLevel > 1) {
			$(this).click(function(e) {
				uid.popupDataMenu(e, this, null, $(this).attr('id').split('_')[1], $(this).attr('id').split('_')[2]);
			});
		}
	});
};

uid.getInteractionLevel = function(){
	if(!uid.interactionLevel){ //not defined so set to default
		uid.interactionLevel = uid.defaultInteractionLevel;
	}
	return uid.interactionLevel;
}

uid.popupDataMenu = function(event, button, dId, fId, cId, interactionLevel) {
	if(!interactionLevel) {
		interactionLevel = uid.getInteractionLevel();
	}
	if(uid.curButton != button){
		uid.curButton = button;
		$(uid.curButton).add('#bi').mouseenter(function(){
			clearTimeout(uid.popupTimeout);
		})
		.mouseleave(function(){
			clearTimeout(uid.popupTimeout);
			uid.popupTimeout = setTimeout(function(){
				$(uid.curButton, '#bi').unbind('mouseenter').unbind('mouseleave');
				if(uid.popupShowing){
					$('#bi').fadeOut('slow', function(){
						$(this).appendTo($('body')); //Move it back to body in case parent is a temporary element
					});
					uid.curButton = null;
				}
			}, uid.stayTimeout);
		});
		$('#bi').fadeOut('fast', function(){
			uid.popupShowing = false;
			if(button.nodeName.toLowerCase() != 'td' && button.nodeName.toLowerCase() != 'th'){
				$('#bi').appendTo(button.parentNode); //Move the popup to the cell containing the button
			}
			else {
				$('#bi').appendTo(button); //This is a table cell, move to popup here
			}
			uid.popupDataMenuPhase2(dId, fId, cId, interactionLevel);
		});
		event.stopPropagation();
	}
};

uid.popupDataMenuPhase2 = function(dId, fId, cId, interactionLevel){
	if(dId){
		uid.popupFetchHtml('bic', '/uid/customcf/dataMenu.cfm?id=' + dId + '&interactionLevel=' + interactionLevel);
	}
	else {
		uid.popupFetchHtml('bic', '/uid/customcf/dataMenu.cfm?fid=' + fId + '&cid=' + cId + '&interactionLevel=' + interactionLevel);
	}
};

uid.popupFetchHtml = function(id, url) {
	$('body, td.d').css('cursor', 'wait');
	uid.cursorResetTimeout = setTimeout(function(){$('body, td.d').css('cursor', '');}, 10000); //Reset the cursor in 10s in case the ajax call never returns
	requestAJAXWithCallBack(url, 'uid.popupSetInnerHtml', '\'' + id + '\'');
};

uid.popupSetInnerHtml = function(ajaxRequest, id) {
  if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
	  clearTimeout(uid.cursorResetTimeout);
	  $('body, td.d').css('cursor', '');  
	  $('#' + id).html(ajaxRequest.responseText);
	  uid.popupShowing = true;
	  $('#bi').fadeIn('normal');
	  ajaxRequest.onreadystatechange = null;
  }
 else if(ajaxRequest.readyState == 4) { //Errors etc
	$('#' + id).html($('#' + id).html() + '<p class="error">An error occurred and the requested operation could not be completed.<br />' +
		'The error code was ' + ajaxRequest.status);
 }
};

uid.scrollLegends = function(){
	div = $('#uidOutput'); 
	div.animate({scrollTop: (div.attr('scrollHeight') - div.height())}, 
		750,
		'swing');
};

uid.initPredefChangeListeners = function(){
	//Only apply this logic if there is an "other" textfield and there are predefined options too
	if($('.input_otherval').length == 1 && $('input[name=data]').length > 0){
		if($.trim($('.input_otherval').val()).length !== 0){
			$('#otherVal').attr('checked', true);
		}
		else {
			$('.input_otherval').attr('disabled', true);
		}
		$('input[name=data][type=radio]').not('#otherVal').click(function(){
			$('.input_otherval').attr('disabled', true);
		});
		$('#otherVal').click(function(){
			if($(this).attr('checked')){
				$('.input_otherval').attr('disabled', false);
			}
			else if($(this).attr('type') == 'checkbox'){
				$('.input_otherval').attr('disabled', true);
			}
		})
		.change();
	}
};
 
/* Populates a field select with the fields belonging to a selected theme.
 * An array named thefields containing objects on the below format is assumed to exist:
 * {
 *  id: id,
 * 	name: name,
 *  code: code,
 *  theme: theme
 * }
 */
uid.populateFieldsFromTheme = function(e, themeSelect, fieldSelect, nodummy){
	if(!themeSelect){
		var themeSelect = $('[name=theme]'); //Assume the theme select is named "theme" ($(this) approach didn't work for some reason
	}
	if(!fieldSelect){
		var fieldSelect = $('[name=field]'); //Assume the field select is named "field"
	}
	if(!nodummy){
		var nodummy = false;
	}
	var selectedTheme = themeSelect.val();
	if(!nodummy){
		var dummy = fieldSelect.children(':first'); //Save the dummy before clearing (let's hope there was a dummy...)
	}
	fieldSelect.empty();
	if(!nodummy){
		fieldSelect.append(dummy[0]); //Add it back in
	}
	for(var i=0; i<thefields.length;i++){
		if(selectedTheme == -1 || thefields[i].theme == selectedTheme){
			fieldSelect.append(new Option(thefields[i].name + ' (' + thefields[i].code + ')', thefields[i].id, false, false));
		}
	}
};

uid.populatePredefValuesFromField = function(e, fieldSelect, valueSelect, values){
	if(!fieldSelect){
		var fieldSelect = $(this); //Assume this function is used as eventhandler on the field select
	}
	if(!valueSelect){
		var valueSelect = $('[name=value]'); //Assume the value select is named "value"
	}
	var selectedField = fieldSelect.val();
	var dummy = valueSelect.children(':first'); //Save the dummy before clearing
	valueSelect.empty();
	valueSelect.append(dummy[0]); //Add it back in
	for(var i=0; i<values.length;i++){
		if(selectedField == -1 || fields[i].theme == selectedField){
			valueSelect.append(new Option(fields[i].name + ' (' + fields[i].code + ')', fields[i].id, false, false));
		}
	}
};

uid.populateCountriesFromRegion = function(e, regionSelect, countrySelect, countries){
	if(!regionSelect){
		var regionSelect = $(this); //Assume this function is used as eventhandler on the region select
	}
	if(!countrySelect){
		var countrySelect = $('[name=country]'); //Assume the country select is named "country"
	}
	var selectedRegion = regionSelect.val();
	var dummy = countrySelect.children(':first'); //Save the dummy before clearing
	countrySelect.empty();
	countrySelect.append(dummy[0]); //Add it back in
	for(var i=0; i<countries.length;i++){
		if(selectedRegion == -1 || countries[i].reg == selectedRegion || countries[i].preg == selectedRegion){
			countrySelect.append(new Option(countries[i].name, countries[i].id, false, false));
		}
	}
};

uid.renderSourceIcon = function(source){
	if($.trim(source) !== ''){
		return '<img src="/style/img/source.png" alt="Source: ' + source + '" title="Source: ' + source + '" />';
	}
	else return '';
};

uid.renderHelpIcon = function(info){
	if($.trim(info) !== ''){
		return '<img src="/vt/images/question_mark_small_2.gif" alt="' + info + '" title="' + info + '" />';
	}
	else return '';
};

uid.renderLastChangedIcon = function(time, relative){
	if($.trim(time) !== ''){
		if(relative){
			// Add code converting the time to a XX days ago or similar value
		}
		else {
			return '<img src="/style/img/time.png" alt="Last changed ' + time + '" title="Last changed ' + time + '" />';	
		}
	}
	else return '';
};	

uid.renderEditDataIcon = function(id, fromUrl){
	if(!fromUrl){
		var fromUrl = '';
	}
	if(fromUrl !== ''){
		fromUrl = '&amp;fromUrl=' + fromUrl;
	}
	return '<a href="editData.cfm?id=' + id + fromUrl + '"><img src="/style/img/edit.png" alt="Edit entry" title="Edit entry" /></a>';
};

uid.handleOtherChange = function(obj) {};
	/*if($.trim($(obj).val()) === ''){
		$('#otherVal').attr('checked', false);
	}
	else {
		$('#otherVal').attr('checked', true);
	}
};*/

/*
uid.editPredef = function(valId, fieldId, tableId) {
	//console.log('editPredef... valId=' + valId + ', fieldId=' +  fieldId + ', tableId=' + tableId);
	var textInputSize = 25;
	var textareaRows = 3;
	var textareaCols = 25;
	var table = $('#' + tableId);
	if(valId != -1) { //Edit existing one
		var row = table.find('#row_' + valId);
		row.children('td.edit').each(function(){
			field = $(this);
			if (field.attr('id').indexOf('description') > -1) { //Needs textarea
				// field.html('<textarea id="' + field.attr('id') + '" rows="' + textareaRows + '" cols="' + textareaCols + '">' + field.html() + '</textarea>');
				field.html(field.html());
			}
			else { //Needs textfield
				// field.html('<input id="' + field.attr('id') + '" value="' + field.html() + '" size="' + textInputSize + '" />');
				field.html(field.html());
			}
		});
		row.find('a.editPredef').html('<a href="#" onclick="uid.savePredef(' + valId + ', ' + fieldId +', \'' + tableId + '\');return false;">Save</a>');
	}
	else { //Add new one
		row = table.find('#row_add');
		row.empty();
		var td = document.createElement('td');
		$(td).html('<input id="add_val" size="' + textInputSize + ' />"');
		row.append(td);
		td = document.createElement('td');
		$(td).html('<textarea id="add_description" rows="' + textareaRows + '" cols="' + textareaCols + '"></textarea>');
		row.append(td);
		td = document.createElement('td');
		$(td).html('<input id="add_color" size="' + textInputSize + '"');
		row.append(td);
		td = document.createElement('td');
		$(td).html('<input id="add_weight" size="' + textInputSize + '"');
		row.append(td);
		td = document.createElement('td');
		$(td).html('<a href="#" onclick="uid.savePredef(-1, ' + fieldId + ', \'' + tableId + '\');return false;">Save</a>');
		row.append(td);
	}
};

uid.savePredef = function(valId, fieldId, tableId) {
	//console.log('savePredef... valId=' + valId + ', fieldId=' +  fieldId + ', tableId=' + tableId);
	var table = $('#' + tableId);
	var row = table.find('#row_add');
	var queryString = '?field=' + fieldId;
	row.find('input, textarea').each(function() {
		queryString += '&' + $(this).attr('id').split('_')[1] + '=' + $(this).val();
	});
	//console.log('/uid/customcf/savePredef.cfm' + queryString);
	requestAJAXWithCallBack('/uid/customcf/savePredef.cfm' + queryString, 'uid.indicatePredefResult', '\'predefResult\'');		
};

uid.indicatePredefResult = function(req, outputId) {
	if(req.responseText == 'saved'){
		$('#' + outputId).html('New predefined value saved successfully');
	}
	else if(req.responseText == 'updated'){
		$('#' + outputId).html('The predefined value was successfully updated');
	}
	else {
		$('#' + outputId).html('There seems to have been an error and the predefined value may not have been saved/updated.');
	}
	setTimeout('$(\'#' + outputId + '\').html(\'\');', 4000);
};
*/

uid.fetchHtml = function(id, url) {
  requestAJAXWithCallBack(url, 'uid.setInnerHtml', '\'' + id + '\'');
};

uid.fetchHtmlPost = function(id, url, urlParam) {
  requestAJAXWithCallBackPost(url, urlParam, 'uid.setInnerHtml', '\'' + id + '\'');
};

uid.fetchHtmlToggle = function(id, url) {
  var obj = getObj(id);
  if (obj.innerHTML !== '') {
    obj.innerHTML = '';
    obj.style.display = 'none';
  } else {
    requestAJAXWithCallBack(url, 'uid.setInnerHtml', '\'' + id + '\'');
  }
};

uid.setInnerHtml = function(ajaxRequest, id) {
  if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
    // getObj(id).innerHTML = ajaxRequest.responseText;
  	$('#' + id).html(ajaxRequest.responseText);
    ajaxRequest.onreadystatechange = null;
    //$('.editcolor').ColorPicker({ flat: true });
	$('#add_color').focus(function(){$('#addColorPicker').show();}).blur(function(){$('#addColorPicker').hide();});
	$('#edit_color').focus(function(){$('#editColorPicker').show();}).blur(function(){$('#editColorPicker').hide();});	
	$('#addColorPicker').hide().farbtastic('#add_color');
	if($('#editColorPicker').length === 1){	
		$('#editColorPicker').hide().farbtastic('#edit_color');
	}
  }
 else if(ajaxRequest.readyState == 4) { //Errors etc
	$('#' + id).html($('#' + id).html() + '<p class="error">An error occurred and the predefined value couldn\'t be updated/saved.<br />' +
		'The error code was ' + ajaxRequest.status);
 }  
};

uid.setMessage = function(msgArea, text, cssClass){
	var msgArea = $('#' + msgArea + 'MsgArea');
	msgArea.removeClass().addClass('msgArea'); //Remove any classes that may have been added and re-add the basic one
	if(cssClass) {
		msgArea.addClass(cssClass);
	}
	msgArea.html(text);
};

uid.clearMessage = function(msgArea){
	uid.setMessage(msgArea, '');
};

uid.warnDateChanged = function(original, message){
	if(uid.isDateChanged(original)){
		uid.setMessage('date', message, 'warning');
	}
	else {
		uid.clearMessage('date');
	}
};

uid.isDateChanged = function(original){
	return $('[name=date]').val() != original;
};

uid.triggerRichText = function(){
	var rts = $('textarea.richtext');
	rts.each(function(){
		var id = $(this).attr('id');
		uid.editors[id] = uid.getEditor(id);
		uid.editors[id].render();
	});
};

uid.getEditor = function(id){
	return new YAHOO.widget.SimpleEditor(id, { 
		height: '150px', 
		width: '622px', 
		collapse: true,
		titlebar: 'Text Editing Tools',
		draggable: false,
		buttons: [
			{ group: 'textstyle', label: 'Font Style',
				buttons: [
					{ type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' },
					{ type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' },
					{ type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' },
					{ type: 'separator' },
					{ type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
					{ type: 'color', label: 'Background Color', value: 'backcolor', disabled: true }
				]
			},
			{ type: 'separator' },
			{ group: 'indentlist', label: 'Lists',
				buttons: [
					{ type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
					{ type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' }
				]
			},
			{ type: 'separator' },
			{ group: 'insertitem', label: 'Insert Item',
				buttons: [
					{ type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true },
				]
			}
		]		
	});
}

uid.saveHTML = function(){
	for(var i=0; i<uid.editors.length; i++){
		uid.editors[i].saveHTML();
	}
};

uid.collapseCollapsibles = function(){
	var intro, introText, rest, tagBalance, text, lastPos, breakPoint, target;
	$('div.collapsible').not('.coupled').each(function(){
		text = $.trim($(this).html());
		if(text.length > 150){
			breakPoint = 149;
			introText = text.substring(0, breakPoint);
			tagBalance = uid.getTagBalance(introText);
			while(tagBalance !== 0 && breakPoint > -1){
				lastPos = breakPoint;
				while(tagBalance > 0 && lastPos != 0){
					lastPos = text.indexOf('>', lastPos) + 1;
					tagBalance--;
				}
				breakPoint = lastPos;
				introText = text.substring(0, breakPoint);
				tagBalance = uid.getTagBalance(introText);
			}
			if(tagBalance === 0 && breakPoint != 0 && breakPoint < text.length){ //Otherwise it contains malformatted html
				//console.log('introText is ' + introText + ', tag balance is ' + tagBalance);
				intro = '<span class="collapsible_intro">' + introText + '</span>';
				//console.log('intro is ' + intro);
				rest = '<span class="collapsible_rest">' + $.trim($(this).html()).substring(breakPoint) + '</span>';
				//console.log('rest is ' + rest);
				$(this).
					html(intro + rest + '<a class="less"> less</a>') //collapseCollapsible expects a link like this to exist...
					.find('.collapsible_rest')
						.hide() //Lets hide the animation now that we're just initialising
						.end()
					.find('.less')
						.click(uid.collapseCollapsible)
						.click();
			}
		}
	});
	$('.collapsible.coupled').each(function(){
		target = $('#' + $(this).attr('id') + '_target'); 
		if(target.css('display') == 'inline'){
			target.addClass('inline');
		}
		target.hide();
		$(this).append(' <a class="more">more&hellip;</a>')
			.find('.more')
				.click(uid.expandCoupled);
	});
};

uid.expandCoupled = function(){
	var parent = $(this).parents('.coupled');
	var replaceHTML; 
	$('#' + parent.attr('id') + '_target')
		.show('normal', function(){
			var id = $(this).attr('id'); 
			if($(this).hasClass('inline')){
				replaceHTML = '<' + $(this)[0].nodeName + ' class="' + $(this)[0].className + '" id="' + id + '" style="display: inline">' +
								$(this).html() +
								'</' + $(this)[0].nodeName + '>'; 
				$(this).replaceWith(replaceHTML);
				$('#' + id).find('.less') //We need to add the click handler back since it's lost when copying the element
					.click(uid.collapseCoupled);
			}
		})
		.append(' <a class="less">less</a>')
			.find('.less')
				.unbind('click', uid.expandCoupled)
				.click(uid.collapseCoupled);
	$(this).remove();
};

uid.collapseCoupled = function(){
	var parent = $(this).parents('.coupled');
	parent.hide('normal')
		.find('.less')
			.remove(); 
	$('#' + parent.attr('id').split('_')[0])
		.append(' <a class="more">more&hellip;</a>')
		.find('.more')
			.unbind('click', uid.collapseCoupled)
			.click(uid.expandCoupled);
	$(this).remove();
};


uid.getTagBalance = function(html){
	html = html.replace(/<br>|<hr>/g, ''); //Remove the implicitly self-closing tags (may be more than those listed in this regexp)
	return (html.split('<').length-1) - ((html.split('</').length-1) * 2) + (html.split('/>').length-1); //Calculate the balance
};

uid.collapseCollapsible = function(){
	var collapsible = $(this).parents('div.collapsible');
	var intro = collapsible.find('.collapsible_intro');
	var rest = collapsible.find('.collapsible_rest');
		rest.hide('normal');
	var link = $(this);
	collapsible
		.empty()
		.append(intro)
		.append(link)
		.append(rest);
	link.removeClass('less')
		.addClass('more')
		.html('more&hellip;')
		.unbind('click', uid.collapseCollapsible)
		.click(uid.expandCollapsible);		
};

uid.expandCollapsible = function(){
	var collapsible = $(this).parents('div.collapsible');
	var intro = collapsible.find('.collapsible_intro');
	var rest = collapsible.find('.collapsible_rest');
		rest.show('normal', function(){$(this).replaceWith('<span class="collapsible_rest">' + $(this).html() + '</span>');});
	var link = $(this);
	collapsible
		.empty()
		.append(intro)
		.append(rest)
		.append(link);
	link.removeClass('more')
		.addClass('less')
		.html('less')
		.unbind('click', uid.expandCollapsible)
		.click(uid.collapseCollapsible);	
};


/* Code below if pretty specific to the "viewData" views.
 * It should possibly be moved into a uid.cfc function
 * or at least be moved into the uid object in use above
 */

/* Don't run this stuff on irrelevant pages */
if(window.location.href.match(/viewdata\.cfm|view_data\.cfm|search-adv\.cfm|uid\/search\.cfm/i)){
	var numRetrievals = 0;
	var naturalHeight = -1; //Used for storing the output popup's natural height before resizing is applied
	var resizeTimeout = 500; //Used for limiting how often the resize will occur
	var lastTimeoutID = 0;
	var pendingResize = false;
	$(document).ready(
		function(){
			/* Move the popup divs to body element. Otherwise IE6 calculates their widths relative to their parent
			even though they're absolutely positioned. */
			var popupDivs = $('#uidOutputWrapper').add('#uidBgMask');
			popupDivs[0].parentNode.removeChild(popupDivs[0]);
			popupDivs[1].parentNode.removeChild(popupDivs[1]);
			$('body').append(popupDivs[0]);
			$('body').append(popupDivs[1]);
			maintainCopyButtons();
			defaultFields();
			initClosebutton();
			if(getHashNoHash().substring(0,2) == 'cq'){
				$('#' + getHashNoHash())
					.addClass('high')
					.find('a:first').click();
			}
			/* Handle prebuilt queries. Remove '&format=HTML' since this will be appended at later stage. */
			if(getHashNoHash().indexOf('prebuilt=yes') > -1){
				retrieveData(uid.url, getHashNoHash() //The page calling this function is responsible for setting the uid.url variable
					.replace('prebuilt=yes&', '')
					.replace(/&d=.*/, '') +
					getLocalTimeString());
			}
		}
	);
}

function initClosebutton(){
	$('#closebutton').unbind('click').click(
		function(){
			$('select').show();
			$('#uidOutputWrapper').add('#uidBgMask').hide();
			$('#uidOutput').html(''); //Maybe good to free some memory...
			window.location.hash = '';
		}
	);
}

function retrieveData(url, queryString, title){
	numRetrievals++;
	/*
	* Remove any highlighting that may remain if this page was visited with a url hash that triggered a 
	* common query or similar. If this is the first invocation of this function though, any highlighting
	* should be kept.
	*/
	if(numRetrievals > 1){
		$('.high').removeClass('high');
	}
	else {
		$(window).resize(function(){resizePopup(false);}); //No need to add this before first launch of popup
	}
	
	if(title){
		$('#tableTitle').html(title);
	}
	
	if(!queryString){
		var queryString = buildQueryString();
		//Build params from options on this page...
	}
	var noFormatQueryString = queryString; //Handy for passing to displayData...
	queryString += '&format=HTML';
	$('#uidOutput').html('<span style="font-weight: bold">Loading data, please wait...</span> '+
			'<br/>(This could take up to a few minutes for large selections)' +
			'<div style="text-align:center;margin:20px;"><img src="http://www.idea.int/images/ajax-loading.gif" /></div>');
	$('select').hide(); //These show through the popup in IE6 otherwise
	$('#uidOutputWrapper').add('#uidBgMask').show();
	$('#uidOutput').css('height', ''); //Remove any set size from previous contents
	naturalHeight = -1;
	resizePopup(true);
	window.location.hash = 'prebuilt=yes&' + noFormatQueryString;
	requestAJAXWithCallBack(url + '?' + queryString, 'displayData', '\'' + url + '\', \'' + noFormatQueryString + '\'');		
	scroll(0, 0);
}

function displayData(req, url, queryString){
	if(req.readyState == 4 && req.status == 200) {
		$('#excelExportDlLink').attr('href', url + '?' + queryString + '&format=Excel');
		$('#csvExportDlLink').attr('href', url + '?' + queryString + '&format=CSV');		
		$('#uidOutput').html(req.responseText);
		var queryString = $('#queryString').html();			
		setTimeout(function(){resizePopup(false)}, resizeTimeout); //It seems the resize has to be delayed so the browser has time to render fully
		initDataCells();
		uid.initUtilButtons();
	}
	else if(req.readyState == 4){
		$('#uidOutput').html('<h2>ERROR</h2><p>We are sorry, but an error has occurred preventing the data from being displayed. This page is still work in progress and we will resolve the issue as soon as possible.</p><p>Status: ' + req.status + '</p>');
	}
}

function initDataCells() {
	$('#uidOutput').mouseleave(function(){
		$('table#viewData td.d').removeClass('overed');//Since table is "invisibly overflowing" the output div, a cell's mouseleave may not trigger even thouh mouse has left the visible part of the cell
	});
	/*$('table#viewData td.d').click(function(){
		if($(this).attr('id').split('_')[0] == 'd'){ //Existing data entry
			var queryString = 'id=' + $(this).attr('id').split('_')[1];
			var title = 'Click to edit this field';
		}
		else {	//Non-existing data entry
			var field = $(this).attr('id').split('_')[1];
			var country = $(this).attr('id').split('_')[2];
			var queryString = 'field=' + field + '&country=' + country;
			var title = 'Click to add missing data';
		}
		if(uid.openEditInNewWin){
			window.open('http://www.idea.int/uid/editData.cfm?' + queryString, '_blank');
		}
		else {
			window.location.href = 'http://www.idea.int/uid/editData.cfm?' + queryString;
		}
	})*/
	$('table#viewData td.d').mouseenter(function(){
		if(uid.getInteractionLevel() > 1 || $(this).attr('id').split('_')[0] == 'd'){
			if(uid.getInteractionLevel() > 1 && !$(this).hasClass('noedit')){
				$(this).addClass('overed');
				$(this).attr('title', 'Click to view details or suggest new or updated data');
			}
			else if($(this).attr('id').split('_')[0] == 'd'){
				$(this).addClass('overed');
				$(this).attr('title', 'Click to view details');
			}
		}
	})
	.mouseleave(function(){
		if(uid.getInteractionLevel() > 1 || $(this).attr('id').split('_')[0] == 'd'){
			$(this).removeClass('overed');
		}
	})
}

function resizePopup(bgOnly){
	if(lastTimeoutID == 0){ //No resize within resizeTimeout millis
		lastTimeoutID = setTimeout(function(){
			lastTimeoutID = 0;
			if(pendingResize){
				resizePopup(bgOnly);
				pendingResize = false;
			}
		}, resizeTimeout);
		if($('#uidOutputWrapper').is(':visible')){ //Dont do unnecessary computing if it's not visible anyway
			if(typeof(window.innerWidth) == 'number') {
				//Non-IE
				browserWidth = window.innerWidth;
				browserHeight = window.innerHeight;
			} 
			else if(document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight)) {
				//IE 6+ in 'standards compliant mode'
				browserWidth = document.documentElement.clientWidth;
				browserHeight = document.documentElement.clientHeight;
			}
			else if(document.body && (document.body.clientWidth || document.body.clientHeight)){
				//IE 4 compatible
				browserWidth = document.body.clientWidth;
				browserHeight = document.body.clientHeight;
			}
			
			/* We don't want to affect the size of #uidOutput until it's populated with all the data. */
			if(!bgOnly){
				if(naturalHeight === -1){
					naturalHeight = $('#uidOutput')[0].offsetHeight;
				}			
				var availableHeight = (browserHeight - ($('#uidOutputWrapper')[0].offsetHeight - $('#uidOutput')[0].offsetHeight)) * .9;
				$('#uidOutput').css('height', Math.min(availableHeight, naturalHeight) + 'px');
				/*Probably means that it was measured before fully rendered. If we change 
				*/
				if(naturalHeight < 160){ 
					setTimeout(function(){resizePopup(false)}, resizeTimeout);
				}					
			}
			
			var bgHeight = Math.max(document.body.offsetHeight, $('#uidOutputWrapper')[0].offsetHeight + $('#uidOutputWrapper')[0].offsetTop);
			bgHeight = Math.max(bgHeight, browserHeight);
			$('#uidBgMask').css('height', bgHeight + 'px');
		}
	}
	else {
		pendingResize = true;
	}
}

function hideRange(){
	$('#yearrange').hide();
}

function hideHighLow(){
	$('#yearfilter').hide();
}

function hideAll(){
	hideRange();
	hideHighLow();
}

function showRange(){
	$('#yearrange').show();
}

function showHighLow(){
	$('#yearfilter').show();
}

function getLocalTimeString(){
	var now = new Date();
	return '&d=' + now.getDay() + '&h=' + now.getHours() + '&m=' + now.getMinutes();
}

function checkAll(name){
	$('input[name=' + name + ']').attr('checked', true);
}

function uncheckAll(name){
	$('input[name=' + name + ']').attr('checked', false);
}

function allFields(){
	checkAll('fields');
}

function submitForm(url, format){
	window.location.href = url + '?' + buildQueryString() + '&format=' + format;
}

function getHashNoHash(){
	var hash = window.location.hash;
		if(hash.indexOf('#') > -1){
		hash = hash.substring(1);
	}
	return hash;
}

/* Dummy function for viewData pages that don't need to have one and thus doesn't implement it at all
 * Other pages need to define the function after this file is included in the page.
 */
function defaultFields(){}