/*
 * Created by Roeland
 * Liesbeth 2010-11 : added extra update-functions
 * Tjess 2011-01-10 : edited updateKeywordsList (not more than 1 search per second)
 * Liesbeth 2011-01-11 : expanded the limited search with a timeout-check
 * Liesbeth 2011-02-17 : during search just show '...' instead of itmValue+'...'
 * Liesbeth 2011-02-18 : added extra check in updateListWithCheck: check whether de active element is actually the searchfield (Could be a different element by the time the function is called)
 * Liesbeth 2011-02-22 : Two new functions to check for doubbles when trying to save.
 * Liesbeth 2011-03-15 : added encodeURI in updateListWithCheck to avoid encodingproblems in IE.
 * Liesbeth 2011-03-21 : substring on tmpspan is no longer necessary. The type is a separate var now.
 * Liesbeth 2011-05-03 : Show the RefIDs of double publications in an alert (checkTitleExists(WithAuthor))
 * Liesbeth 2011-05-06 : added encodeURI in checkTitleExists(WithAuthor) to avoid encodingproblems in IE.
 * Liesbeth 2011-05-   : Show the RefIDs as URLs, using a div to show them (modalbox.js)
 * Liesbeth 2011-05-30 : Added tmpAutpers, tmpAutIns, tmpAutEdit for webinput interface.
 * Liesbeth 2011-09-01 : execute checkTitleExistsWithAuthor only when it is the first author -> added check.
 * Liesbeth 2011-09-02 : If tmptype is empty and it isn't a biblvlcode, value in textfield must be emtpy too.
 * Liesbeth 2011-12-   : Added lock-code.
 */

  var http=getHTTPObject(); //  the HTTP Object
  var div; var glob; var txt; var tmpspan; var txtid; var tmpid; var txttype; var tmptype;
  var tmpAutPers; var tmpAutIns; var tmpAutEdit;

  if(typeof String.prototype.trim !== 'function') {
  	String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
  }

  //called by the user/page
  function updateListWithId(url,lst,itm,divId,itmId,width){ updateListExtended(url,lst,itm,divId,itmId,null,width);}
  function updateList(url, lst, itm, divId, width){ updateListWithId(url,lst,itm,divId,null,width); }
  var cnt=0;
  function updateListExtended(url,lst,itm,divId,itmId,itmType,width){
  	cnt++;
	setTimeout('updateListWithCheck("'+url+'","'+lst+'","'+itm.id+'","'+encodeURI(itm.value)+'","'+itm.name+'","'+divId+'","'+itmId+'","'+itmType+'",'+cnt+','+width+')',750);
  }
  //var lastsearch;
  function updateListWithCheck(url, lst, itmFieldId, itmValue, itmFieldName, divId, itmId, itmType, cntCheck, width){
	if(itmValue.length < 3 || cntCheck!=cnt) return;
  	if(http){
      div=document.getElementById(divId);
      if(itmValue=='' || document.activeElement.name!=itmFieldName) hideDIV();
	  else{
	      txt=document.getElementById(itmFieldId);
		  if (itmId != null) txtid = document.getElementById(itmId);
		  if (itmType != null) txttype = document.getElementById(itmType);
		  var bentField=document.getElementById("bentIDID");
		  var bentId;
		  if(bentField) bentId=bentField.value;

	      div.style.width=((width && width > txt.clientWidth)?width+'px':(txt.clientWidth-5)+'px');
	      div.style.visibility='visible';
	      div.innerHTML = '...';
		  
	      uri = url + 'page=ajax&lst=' + encodeURI(lst) + '&val=' + itmValue + '&itm=' + encodeURI(itmFieldName) + (bentId?'&bentid='+bentId:'');
	      http.open('POST',uri,true); http.onreadystatechange=handleHttpResponse; http.send(null);
      }
    }
  }

  //called by the user/page
  function updateMap(url,divid){
    if(http){
      div=document.getElementById(divid);

      txt='first text'; // itm;

      div.style.width=(txt.clientWidth-5)+'px';
      div.style.visibility='visible';
      div.innerHTML = 'trial'; // itm.value+'...';

      http.open("POST",url,true); http.onreadystatechange=handleHttpResponse; http.send(null);
    }
  }

  function checkTitleExists(titleFieldID,bentID,titleChangedFieldID){
	var titleChanged=document.getElementById(titleChangedFieldID).value;
  	if (titleFieldID != document.activeElement.id && titleChanged=='true') {
			var titleField = document.getElementById(titleFieldID);
			if (http && titleField.value) {
				url = "imis.php?page=ajax&title=" + encodeURI(titleField.value) + "&bentid=" + bentID;
				http.open("POST", url, true); http.onreadystatechange = handleHttpResponse;
				http.send(null);
			}
		}
  }
  function checkTitleExistsWithAuthor(titleFieldID,bentIDFieldID,authorFieldID,titleChangedFieldID){
	var firstAuthor=checkFirstAuthor(authorFieldID);
	if (firstAuthor) {
		var titleChanged = document.getElementById(titleChangedFieldID).value;
		if (authorFieldID != document.activeElement.id && titleChanged == 'true') {
			var authorField = document.getElementById(authorFieldID);
			var titleField = document.getElementById(titleFieldID);
			var bentIDField = document.getElementById(bentIDFieldID);
			if (http && titleField.value && authorField.value) {
				url = "imis.php?page=ajax&title=" + encodeURI(titleField.value) + (bentIDField?"&bentid=" + bentIDField.value:"") + "&author=" + encodeURI(authorField.value);
				http.open("POST", url, true);
				http.onreadystatechange = handleHttpResponse;
				http.send(null);
			}
		}
	}
  }
  function checkTitleExistsFinalCheck(titleFieldID,bentID,titleChangedFieldID){
		var titleChanged=document.getElementById(titleChangedFieldID).value;
  		var answer=true;
		if (titleChanged == 'true') {
			var titleField=document.getElementById(titleFieldID);
			if (http && titleField.value) {
				url = "imis.php?page=ajax&title=" + encodeURI(titleField.value) + "&bentid=" + bentID;
				http.open("POST", url, false); 
				http.onreadystatechange=function(){if(http.readyState==4){}};
				http.send(null);
				if (http.status == 200 && RegExp("\\s*refid=\\d+(, \\d+)*\\s*").test(http.responseText))
					answer = confirm("This title already exists in IMIS.\nDo you want to continue saving?");
			}
		}	
		return answer;
  }
  function openPersonLink(instance){
		var persID=instance.getAttribute('persID');
		if (http && persID) {
			url = 'imis.php?page=ajax&personcheck=' + persID;
			http.open("POST", url, true);
			http.onreadystatechange = handleHttpResponse;
			http.send(null);
		}
  }
  function openInstituteLink(instance){
	var insID=instance.getAttribute('insID');
	if(insID && insID!=null)
		url = 'imis.php?page=ajax&inscheck=' + insID;
		http.open("POST", url, true);
		http.onreadystatechange = handleHttpResponse;
		http.send(null);
  }
  function checkLockFree(bentID){
  	url='imis.php?page=ajax&lockcheck='+bentID;
	http.open("POST",url,true);
	http.onreadystatechange=handleHttpResponse;
	http.send(null);
  }
  //catches the returned data
  function handleHttpResponse(){
    if (http.readyState == 4){
		var match;
		result = http.responseText;
		if (match = RegExp("\\s*refidWithAuthor=\\d+(, \\d+)*\\s*").exec(result)) {
			var refids = match[0].replace('refidWithAuthor=', '').split(', ');
			var str = '';
			var cnt=1;
			if (refids.length > 10) {
				str = 'There are more than 10 matching titles.';
				cnt++;
			}
			else {
				for (var i = 0; i < refids.length; i++) {
					str += '<a href="imis.php?module=ref&refid=' + refids[i] + '" target="_blank">' + refids[i] + '</a><br>';
					cnt++;
				}
			}
			createModalBox('This title already exists in IMIS with the same author<br>' + str, 350, (cnt*13)+78);
		}
		else if (match = RegExp("\\s*refid=\\d+(, \\d+)*\\s*").exec(result)) {
			var refids = match[0].replace('refid=', '').split(', ');
			var str = '';
			var cnt=1;
			if (refids.length > 10) {
				str = 'There are more than 10 matching titles.';
				cnt++;
			}
			else {
				for (var i = 0; i < refids.length; i++) {
					str += '<a href="imis.php?module=ref&refid=' + refids[i] + '" target="_blank">' + refids[i] + '</a><br>';
					cnt++;
				}
			}
			createModalBox('This title already exists in IMIS.<br>' + str, 300, (cnt*13)+78);
		}
		else if(match = RegExp("\\\s*personurl=.+\\s*").exec(result)){
			var personURL=match[0].replace('personurl=','');
			OpenLinkTab(personURL);
		}
		else if(match = RegExp("\\\s*insurl=.+\\s*").exec(result)){
			var insURL=match[0].replace('insurl=','');
			OpenLinkTab(insURL);
		}
		else if(match = RegExp("\\\s*mylock=.+\\s*").exec(result)){
			var patt=/\d+/g;
			numbers=match[0].match(patt);
			lockBEntID=numbers[0];
			if(lockBEntID!=0) countdown(numbers[1],lockBEntID);
			else createModalBox('Someone else is editing this record. Any changes you make will not be saved.',300,105);
		}
		else if (div) {
			div.innerHTML = result;
			//alert(result);
		}
	}
  }

  // declare http
  function getHTTPObject(){
    if (window.ActiveXObject) var http = new ActiveXObject("Microsoft.XMLHTTP");
    else{ if (window.XMLHttpRequest){ http = new XMLHttpRequest(); }}
    return http;
  }

  function hideDIV(){
  	if (div && div.style.visibility != 'hidden') {
		if (tmpid != '' && tmpid && txtid != null) 
			txtid.value = tmpid;
		if (tmptype != 'S' && tmptype != 'M' && tmptype != 'MS' && txttype != null) {
			if (tmptype != '' && tmptype ) 
				txttype.value = tmptype;
			else 
				txttype.value = '';
		}
		if (tmpspan != '' && tmpspan) {
			txt.value = remHTMLbold(tmpspan); // fill in value in textbox
			if (txt.getAttribute('oldValue') != null) txt.setAttribute('oldValue', txt.value);
		}
		if (txt && txt.getAttribute('oldValue') != null && (txt.value == '' || txt.value == null || txt.getAttribute('oldValue') != txt.value)) {
			txt.value = '';
			if (txt.getAttribute('oldValue')) txt.setAttribute('oldValue', null);
			if (txtid) txtid.value = '';
			if (txttype) txttype.value = '';
		}
		div.style.visibility = 'hidden';
		if(typeof(checkRefType) != 'undefined')
			if ((tmptype == 'S' || tmptype == 'M' || tmptype == 'MS') && window.checkRefType) checkRefType(tmptype);
		if( typeof(checkAutButtons) != 'undefined' && (tmpAutPers || tmpAutIns || tmpAutEdit || tmpAutEdit==0)) {
			var nr = txt.name.substring(txt.name.indexOf('[') + 1, txt.name.indexOf(']'));
			checkAutButtons('person',nr,tmpAutPers,null);
			checkAutButtons('institute',nr,tmpAutIns,null);
			checkAutButtons('edit',nr,tmpAutEdit,null);
			tmpAutPers=null;
			tmpAutIns=null;
			tmpAutEdit=null;
		}
	}
  }

  function remHTMLbold(txt){ txt=txt.replace('&nbsp;',''); return txt; }
