var IE = (navigator.appName == 'Microsoft Internet Explorer') ? true : false;
var xmlData;
var xmlRoot;
var curField;
var obsId;
var lanId;


function checkKeyup(e) {
	// checks for press on enter key to submit login form
	IE = (navigator.appName == "Microsoft Internet Explorer") ? true : false;
	if (IE) var toetscode = event.keyCode;
  else var toetscode = e.which;

  if (toetscode == 13) {         // enter
  	// submit form
  	submitLoginform();
  }
}

function ensureScriptIsLoaded(name,src) {
	// test if script is loaded (by name). if not load script (src) in head section
  if (document.getElementById('script_'+name))  {    // Already exists
    return true;
  }
  var head = document.getElementsByTagName("head")[0];
  var script = document.createElement('script');
  script.id = 'script_'+name;
  script.type = 'text/javascript';
  if (src.indexOf('http')== 0){
    script.src = src;
  } else {  
    script.src = '/portal/js/' + src;
  }  
  head.appendChild(script);
  return false;
}

function getPhrase(key) {
	////////////////  translation phrases ////////////////////////////
  return phrar[key] ? phrar[key] : key;
}

function getRadiovalue(el) {  // call with el = document.formname.radioname
	for (i = 0; i < el.length; i++) {
		if (el[i].checked == true)
			return el[i].value;
	}
}

function isNumeric(p_strValue) {
	var strValidchars = '0123456789.,';
 
  for (i = 0; i < p_strValue.length; i++) {
    if (strValidchars.indexOf(p_strValue.charAt(i)) == -1) {
      return false;
    }
	}
	return true;
}

function is_integer(p_strValue) {
	var strValidchars = '0123456789';
 
  for (i = 0; i < p_strValue.length; i++) {
    if (strValidchars.indexOf(p_strValue.charAt(i)) == -1) {
      return false;
    }
	}
	return true;
}

function setScripturl(str) {
	// get script load commands from html.  [[script|script_taxon|form_taxon_js.php]]
  
  var pStart = str.indexOf('[[script|');     // find start script load command 
  while (pStart>-1) {
    pName = pStart + 9;                       // start script name
    pSrc =  str.indexOf('|', pName) + 1;      // start script src 
    pEnd =  str.indexOf(']]', pStart);        // end script command 
    
    sName = str.substr(pName, pSrc - pName - 1);      // script name
    sSrc  = str.substr(pSrc, pEnd - pSrc);           // script src

    ensureScriptIsLoaded(sName, sSrc);        // load script
   
    pStart = str.indexOf('[[script|',pEnd);   // find next start script load command 
  }
}

function showPicture(dir, m, y, name) {
	// shows full picture in largeimagespan
  filename = dir + y + '/' + m + '/' + name;
  document.getElementById('largeimagespan').innerHTML = '<img src="' + filename + '" />';
}

function startxmlhttp() {
	var xmlhttp = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	try {
	 	xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
	} catch (e) {
	  try {
	   	xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
	  } catch (E) {
	   	xmlhttp = false;
	  }
	}
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	if (!xmlhttp && window.createRequest) {
		try {
			xmlhttp = window.createRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
  return xmlhttp;
}

function submitLoginform() {
	// check and submit login form
	var userel = document.getElementById('us_login');
	var passwordel = document.getElementById('us_password');
	if ((userel.value == '') && (passwordel.value != '')) {
		alert('geen gebruikersnaam ingevuld'); 
	} else if ((userel.value != '') && (passwordel.value == '')) {
		alert('geen wachtwoord ingevuld');
	} else if ((userel.value != '') && (passwordel.value != '')) {
		if (!isIllegal(userel.value)) {
			document.getElementById('user_login').submit();
		} else {
			alert('ongeldige tekens in het veld loginnaam');
		}
	}
}

function trim(value) {
  value = value.replace(/^\s+/, '');
  value = value.replace(/\s+$/, '');
  return value;
}

function isIllegal(p_username) {
	var ar_illegal = new Array("<", ">", ";");
	for (var i = 0; i < ar_illegal.length; i++) {
		if (p_username.indexOf(ar_illegal[i]) >= 0) {
			return true;
		}
	}
	return false;
}

////////////////  XML functions ////////////////////////////

function getFormXML() {
	// get xml form data:
	xmlvalue = document.getElementById('formxml').value;
	
	if (xmlvalue != '') {   		// convert the string to an XML object
		if (navigator.appName == 'Microsoft Internet Explorer') {
			xmlData = new ActiveXObject('Microsoft.XMLDOM');
			xmlData.async = 'false';
		  xmlData.loadXML(xmlvalue);
		}
		else {
		  xmlData = (new DOMParser()).parseFromString(xmlvalue, 'text/xml');
		}
		xmlRoot = xmlData.documentElement;  // root node...
    obsId = readAtt(xmlRoot, 'id', 0);          // get observation-id...
    lanId = readAtt(xmlRoot, 'lanid', 112345);  // get language-id...
	}
}

function readAtt(node, att, standard) {
	// read attribute from node:
  return (node.getAttribute(att)==null) ? standard : node.getAttribute(att);
}

function convertAtt(node, att, standard, name) {
	// convert attribute to text (name=value):
  return ' ' + name + '="' + readAtt(node, att, standard) + '"';
}

function writeAtt(node, att, value, standard) {
	// write or clear attribute:
  if (value == '') {
  	value = standard;
  }
  if (value != '') {
    if (value == '-') {                   // clear attribute
      node.setAttribute(att, '');
    } else {
      node.setAttribute(att, value);
    }
  } else {                              // delete attribute
    if (node.getAttribute(att) != null) {
    	node.removeAttribute(att);
    }
  }
}

function writeNode(node, tag, value) {
	// add or remove childnode (given tag-name and value):
  var child = node.getElementsByTagName(tag)[0];  // see if node already exists
  if (child != null) {                              // yes:
    if (value == '') {                              // value='': remove childnode 
      node.removeChild(child);
    } else {                                      // else change value
      child.text = value;
    }
  } else {                                        // childnode doesnt exist yet:
    if (value != '') {
      child = dataDoc.createElement(tag);         // add childnode
      node.appendChild(child);
      child.text = value;
    }
  }
}

////////////////////  message functions ///////////////////////////////////

function showMessage(messagetext,cname,wait){
  if (messagetext == '') return;     // don't show empty messages
  if (wait == null) wait=5000;       // default display time
  if (wait < 500) wait = wait * 1000 // convert second to milliseconds
  if (cname == null) cname= '';      // style to use ('message', 'error', 'help', 'confirm?')
  if (wait == -1) {
    wait = 60000;

   messagetext +=  '<a href="hideMessage();">'+'close'+'</a>';
  }
  if (document.getElementById('messagediv')){
    document.getElementById('messagediv').innerHTML = messagetext;
    document.getElementById('messagediv').className = cname;
    if (wait > 0) m_iInterval = setTimeout(hideMessage, wait);
  }
}

function hideMessage() {
  if (document.getElementById('messagediv')){
    document.getElementById('messagediv').innerHTML = '';
    document.getElementById('messagediv').className = 'message';
  }
}

///////////////////////  form-field functions: 

// find certain field (node) by Id in data xml:
function findField(fldid) {
  curField = xmlRoot.getElementsByTagName('f'+fldid)[0];
  if (curField != null) { 
    return 1;
  } else return 0;
}
  
// get value for certain field: (value input is default value)
function getFieldvalue(field, value) {
  return (findField(field)==1) ? readAtt(curField, 'val', value) : 0;
}

// get text for field item, given field-id and item-id, put in span:
function getFielddescription(field,item,span) {
  var pagina = 'lib/forms/fieldinfo.php?fld=' + field + '&itm=' + item;
  var xmlhttp = startxmlhttp();    // Creating the AJAX object
  xmlhttp.open('GET', pagina, true);
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      document.getElementById(span).innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.send(null);
}

//////////////////////////////  hide / show / clear div's and spans: ////////////////////

function toggleDiv(_element, _action) {
	// show or hide div element
	var action;
	var element = document.getElementById(_element);
	if (element) {
		action = ((_action == '') || (_action == '?')) ? ((element.style.display == 'inline') ? 'h' : 's') : _action;
		if (action == 's') {
			element.style.display = 'inline';
		} else {
			element.style.display = 'none';
		}
	}
	if (_action == '?') {
		return action;
	}
}

function toggleBool(_element,show) {
  (show) ? toggleDiv(_element,'s') : toggleDiv(_element,'h');
}

// show or hide div elements: action applies to element1, element2 gets opposite action:
function toggleDiv2(divid, linkid, _action, texton, textoff) {
  fielddiv = document.getElementById(divid);
  if (fielddiv) {
    if (_action=='s') fielddiv.style.display = 'inline';
    if (_action=='h') fielddiv.style.display = 'none';
    if (_action=='') {
      fielddiv.style.display = (fielddiv.style.display == 'inline') ? 'none' : 'inline';
    }
    if (linkid > 0) {
      linediv = document.getElementById('linediv'+linkid);
      if (linediv) {
        linediv.style.display = (fielddiv.style.display == 'inline') ? 'none' : 'inline';
      }
    }
    adiv = document.getElementById('adiv'+linkid);
    if (adiv) {
      adiv.innerHTML = (fielddiv.style.display == 'inline') ? textoff : texton;
    }
  }
}

function visibleDiv(divid) {
  fielddiv = document.getElementById(divid);
  result = 'h';
  if (fielddiv) {
    result = (fielddiv.style.display == 'inline') ? 's' : 'h';
  }
  return result;
}

function clearSpan(_w) {
  element = document.getElementById(_w);
  if (element) {
    element.innerHTML = '';
    return true;
  } else return false;
}

// get a certain page, and paste it in div 'target':
function getPage(pagina,target) {
  var xmlhttp = startxmlhttp();               // Creating the AJAX object
  xmlhttp.open('GET', pagina, true);
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      document.getElementById(target).innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.send(null); 
}

function getWaitimage(size) {
	// available sizes: 16-30, only even numbers
	if (size < 16) {
		size = 16;
	}
	if (size > 30) {
		size = 30;
	}
	if (size % 2 > 0) {
		size -= 1;
	}
	
	var result = '<img src="/layout/gfx/wait' + size + 'trans.gif" title="even geduld a.u.b." alt="even geduld a.u.b." />';
	return result;
}