/*

	main function

*/
// function "processJSONreply" is called from Ajax, keep the name!
function processJSONreply(myJSONtext,jSONsourceName) {
	//alert(jSONsourceName+':'+myJSONtext);
	// apparently the use of eval here is potentially dangerous...
	if (!myJSONtext) return;
	var myObject = eval('(' + myJSONtext + ')');
	for(var k=0;k<myObject.results.length;k++) {
		var data = myObject.results[k];
		for(var j=0;j<sectionFunctions.length;j++) {
			eval(sectionFunctions[j]);
		}
	}
}

/*

	helper functions

*/
// default texts in the JS files; set with setTextLabel() *before* loading the page specific JS script
var numAltDesc = 0;
var texts = new Array(0);
	//defaults
	texts[0] = 'nothing found';
	texts[1] = 'Date';
	texts[2] = 'Longitude';
	texts[3] = 'Latitude';
	texts[4] = 'Location';
	texts[5] = 'Show all';
	texts[6] = 'total';
	texts[7] = '? (unknown locality)';
	texts[8] = 'more';
	texts[9] = 'and';
	texts[10] = 'External link';
	texts[11] = 'From:';	
	texts[12] = 'Name'; // page 1 (names etc.)
	texts[13] = 'Rank'; // page 1
	texts[14] = 'Status'; // page 1
	texts[15] = 'Synonym'; // page 1
	texts[16] = 'Status'; // page 8 (conservation)
	texts[17] = 'Source'; // page 8

function setText(lbl,txt) {
	if(texts[lbl]) texts[lbl] = txt;
}


// check whether source name and link actually have a value
function checkSourceAndLink(data,jSONsourceName) {
	var ret = new Array();
	ret[0] = (data.source=='' || data.source==undefined ? unescape(jSONsourceName) : unescape(data.source));
	ret[1] = (data.link=='' || data.link==undefined ? '#' : unescape(data.link));
	return ret;
}


// checks if a specific result was identically printed before (to avoid duplicates)
function wasPrintedBefore(haystack,needle) {
	if (!haystack || haystack.length==0 || haystack==undefined) return false;
	for(var i=0;i<haystack.length;i++) if (haystack[i]==needle) return i;
	return false;
}


// unique ID generator for element-ID's of initially hidden tables
var qId = 0;
function uniqId() {
	return 'id'+qId++;
}


/* 

	generic print vars and functions, identical for all sections

*/
var htmlTable = '<table border="0" cellpadding="0" cellspacing="0" class="sectionData" id="%id%" style="display:%display%">%data%</table>';
var htmlSourceCell =
	'<tr><td valign="top" colspan="2" class="sectionSources"><p  style="margin-top: 0px; margin-bottom: 5px;" class="sourceheader"><span id="%id%">%textFrom% %data%</span></p></td></tr>\n';
var htmlEmptyCell =
	'<tr><td valign="top" colspan="2" class="sectionSources"><span>%data%</span></td></tr>\n';
var htmlSource =
	'<span class="nounderline"><a title="%label%" href="%url%" target="_blank">'+
	'<img src="images/link.gif" alt="%textExtLink%" width="15" border="0" height="9"></a>'+
	'</span><span class="stronglink"><a title="%label%" href="%url%" target="_blank">%label%</a></span>';
var htmlSeeMore = '<p style="margin-top: 6px;"> [%link%]</p>';
var htmlHr = '<div style="width:430px;border-bottom:1px dotted #777;height:1px; margin-bottom: 16px;">&nbsp;</div>';

function getHtmlSourceCell() {
	return htmlSourceCell.replace(/%textFrom%/g,texts[11]);
}

function getHtmlSource() {
	return htmlSource.replace(/%textExtLink%/g,texts[10]);
}

function makeTable(data,id,hidden) {
	if (hidden)
		return htmlTable.replace(/%data%/,data).replace(/%display%/,'none').replace(/%id%/,id);
	else
		return htmlTable.replace(/%data%/,data).replace(/%display%/,'').replace(/%id%/,id);
}

function makeSourceHeader(sectName,id,label,url) {
	if ((label=='' && url=='') || (label==undefined && url==undefined)) {
		var dummy = ymmud = '';
	} else {
		var dummy = getHtmlSourceCell();
		var ymmud = getHtmlSource();
	}

	return dummy.replace(/%id%/,sectName+'sources'+id).replace(/%data%/,ymmud.replace(/%label%/g,label).replace(/%url%/g,url));
}

function makeEmptyCell(data) {
	return htmlEmptyCell.replace(/%data%/,data);
}


// adds a source to the header, if there are more than 0 places and 'and', if there's more then two, replaces the ands with commas first
function updateSourceHeader(sectName,id,label,url) {
	var glue = '<span id=glueId> '+texts[9]+' </span>';
	var dummy = document.getElementById(sectName+'sources'+id).innerHTML;
	set = dummy.match(/glueId/g);
	elements = (set ? set.length+1 : 1);

	if(elements>1) dummy = dummy.replace(eval('/ '+texts[9].replace('+','\\+')+' /g'),', ');

	var ymmud = getHtmlSource();
	document.getElementById(sectName+'sources'+id).innerHTML = 
		dummy +
		(elements > 0 ? glue : '') +
		ymmud.replace(/%label%/g,label).replace(/%url%/g,url);
}

function printData(dataId,headId,counter,data,sourceData) {
	document.getElementById(dataId).innerHTML =
		document.getElementById(dataId).innerHTML +
			makeTable(
				makeSourceHeader(headId,counter,sourceData[0],sourceData[1]) +
				data
			);
}


var htmlObservationOrSpecimentData =
	'<tr><td valign="top"><p style="width: 95px; margin-right: 10px; margin-top: 3px;">%date%</p></td>'+
	'<td valign="top"><p style="width: 70px; margin-right: 10px; margin-top: 3px;">%longitutde%</p></td>'+
	'<td valign="top"><p style="width: 70px; margin-right: 10px; margin-top: 3px;">%latitude%</p></td>'+
	'<td valign="top"><p style="width: 150px; margin-right: 10px; margin-top: 3px;">'+
	'<a href="%link%" target="_blank"><img src="images/link.gif" alt="'+texts[10]+'" width="15" align="right" border="0" height="9" hspace="5">'+
	'</a>%label%</p></td></tr>\n';

function makeObservationOrSpecimenHtml(data) {
	return htmlObservationOrSpecimentData.
		replace(/%date%/g,data.date ? unescape(data.date) : '-').
		replace(/%longitutde%/g,data.longitude ? unescape(data.longitude) : '-').
		replace(/%latitude%/g,data.latitude ? unescape(data.latitude) : '-').
		replace(/%link%/g,unescape(data.link)).
		replace(/%label%/g,data.location ? unescape(data.location) : texts[7]);
// longitude_decimal,latitude_decimal,number_counted
}

function scaleImage(data,maxHeight,maxWidth) {
	var w = unescape(data.width);
	var h = unescape(data.height);

	var res = new Array();
	if (w > maxWidth) {
		factor = maxWidth/w;
		res[0] = false;
		res[1] = Math.round(factor * w,0);
	}

	if (maxHeight!==false) {
		if (h > maxHeight) {
			factor2 = maxHeight/h;
			factor = factor < factor2 ? factor : factor2;
		}
		res[0] = Math.round(factor * h,0)
		res[1] = Math.round(factor * w,0)
	}
//alert(maxWidth+':'+w+':'+res[1]+'||'+maxHeight+':'+h+':'+res[0]);
	return res;
}

function stripSlashes(thisString) {
	while (thisString.indexOf("\\") != -1) {
		thisString = thisString.replace("\\","") ;
	}
	return thisString ;
}

function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object
   for (var i in obj) {
      // if a parent (2nd parameter) was passed in, then use that to
      // build the message. Message includes i (the object's property name)
      // then the object's property value on a new line
      if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
      // Display the message. If the user clicks "OK", then continue. If they
      // click "CANCEL" then quit this level of recursion
      if (!confirm(msg)) { return; }
      // If this property (i) is an object, then recursively process the object
      if (typeof obj[i] == "object") {
         if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
      }
   }
}


