
//
// Automatisk markering af ordliste-links
//

// maxterms: maximum number of words in each term
// For example: Set maxterms=4 to support terms 
// such as "Bygning på lejet grund"
var maxterms=4;
var faktaDivId="faktaboks";

// popupPageId: id of the list page that is used for viewing definitions
var popupPageId=10506;

// safeTags is an array of any HTML tags that should not
// to be searched for terms
var safeTags=new Array("A", "STRONG");

// Notice: it is important that the punctuation variable 
// includes space in order to strip trailing spaces
var punctuation=".,:;?! \n\r";


// debug info
var debugdiv;
/*
if (!debugdiv) { debugdiv=document.getElementById("debugdiv") };
if (debugdiv) { debugdiv.value+="Starting...\njavascript:alert(\"\")\n"; }
if (!t0) {
  var t0=new Date().getTime();
}
*/

function GetLinkHTML(linktext, recordid) {
  var linkhref="/showlistrecord.asp?id="+popupPageId+"&recordid"+popupPageId+"="+recordid;
  // set flags (resize window + ignore this keyword)
  linkhref+="&resize=true&ignore="+escape(linktext);
  var html="<a onmouseover=\"window.status='"+linktext+"';return true\" onmouseout=\"window.status='';return true\" class=inlinelink";
  html+=" href='"+linkhref+"' target='"+faktaDivId+"popup' onclick=\"OrdlistePopup('"+linkhref+"');return false\">";
  html+=linktext+"</a>";
  return html;
}

function OrdlistePopup(linkhref) {
  win=window.open(linkhref,faktaDivId+"popup","width=240,height=300,left=500,top=200,resizable=yes,scrollbars=no");
  if (win) {
    if (win.document && win.document.body && win.document.body.innerHTML) {
	// blank window first (to hide any previous contents)
	win.document.body.innerHTML="";
    }
    if (win && win.focus) {
	win.focus();
    }
  }
}

function VisOrdlisteLinks() {
  // don't call script on admin pages
  if (location.href.indexOf("/admin")!=-1) {
    return;
  }
  
var t1=new Date().getTime();
  // read data from iframe 
  if (typeof terms=="undefined") {
    if (frames && frames.glossaryFrame && frames.glossaryFrame.terms) {
	var tt1=new Date().getTime();
	terms=frames.glossaryFrame.terms;
	var tt2=new Date().getTime();
	//alert("Reading data from iframe took " + (tt2-tt1) + "ms\n" + "Time since load of page: " + (tt2-t0) + "ms");
    }
  }
  
  // convert tags to uppercase and store them as properties
  if (typeof safeTags=="undefined") {
    safeTags=new Array();
  } else {
    var tmptag;
    for (var i=0; i<safeTags.length; i++) {
	tmptag=safeTags[i].toUpperCase();
	safeTags[tmptag]=true;
    }
  }
  
  // ignore keyword? (used in popup window to avoid linking to the current keyword)
  var ignore="";
  var re=/ignore=([^&]+)/;
  var m=location.href.match(re);
  if (m && m[1]) {
    ignore=unescape(m[1].toLowerCase());
  }

  // find objects
  var obj=GetElementsByName(faktaDivId);
  if (obj && obj.length && typeof(terms)=="object") {
    // this regular expression extracts 
    // 1) all HTML-tags "<[^>]*>[\s]*" (including any trailing white space)
    //    The string "[^>]" makes the expression non-greedy
    // 2) words (including any punctuation and "[\s]*" gets any trailing white space)
    //    The string "[^<>\s]" is used instead of "\S" to prevent
    //    HTML-tags from being included in the words
    var reg=/<[^>]*>[\s]*|[^<>\s]+[\s]*/g;
    var regTag=/<([^ >]*)/;
    var s, m, tmp, linktext, mtag;
    var key=new Array();
    var i, t, found;
    // prevHTML is set to true to avoid a leading space
    var isHTML, prevHTML=true;
    var safeHTML=false, tagName, tmptag;
    for (i=0; i<obj.length; i++) {
	s=FixInnerHTML(obj[i].innerHTML);
	m=s.match(reg);
	tmp="";
	for (var k=0;m && k<m.length;k++) {
	  found=false;

	  // is the first word a HTML-tag?
	  isHTML=(m[k].indexOf("<")==0);
	  if (isHTML) {
	    // check for safe tags
	    var mtag=m[k].match(regTag);
	    if (mtag && mtag[1]) {
		tmptag=mtag[1].toUpperCase();
		if (safeHTML) {
		  // reached end tag?
		  if (tmptag=="/"+tagName) {
		    safeHTML=false;
		    tagName="";
		  }
		} else {
		  if (safeTags[tmptag]) {
		    // ignore the contents of this HTML tag
		    safeHTML=true;
		    tagName=tmptag;
		  }
		}
	    }
	  }
	  
	  if (!isHTML && !safeHTML) {
	    // combine words to array keys of varyings size (since some  
	    // of the terms consist of multiple words)
	    key[0]=PrepareKeyword(m[k]);
	    for (t=1; t<maxterms && t+k<m.length; t++) {
		key[t]=key[t-1]+" "+PrepareKeyword(m[k+t]);
	    }
	    // search array with terms in reverse order (longest term first)
	    for (t=maxterms-1; t>=0 && !found; t--) {
		if (terms[key[t]] && key[t]!=ignore) {
		  // Found! 
		  if (debugdiv) {
		    debugdiv.value+="-> Found '" + key[t] + "' (recordid: " + terms[key[t]]+")\n";
		  }
  
		  //
		  // add word(s) to output string as a hyperlink 
		  //
		  linktext="";
		  for (var tt=0; tt<t; tt++) {
		    // add keywords including spaces
		    linktext+=m[k+tt];
		  }
		  // strip punctuation from last keyword in this sentence
		  linktext+=StripPunctuationAndSpaces(m[k+t]);
		  
		  //linktext=key[t];
		  tmp+=GetLinkHTML(linktext, terms[key[t]]);
		  tmp+=GetPunctuationAndSpaces(m[k+t]);
  
		  // skip words by incrementing k (relevant when the term 
		  // consists of multiple words)
		  k=k+t;
		  found=true;
		} 
	    } 
	  }
	  if (!found) {
	    // add word to output string

	    //tmp+=((prevHTML || isHTML)?"":" ")+m[k];
	    tmp+=m[k];
	  }
	  prevHTML=isHTML;
	  
	//  if (debugdiv) { debugdiv.value+=m[k]+"\n"; }
	}
	// TO-DO: remove P-tag

	obj[i].innerHTML=tmp;
    }
  }
var t2=new Date().getTime();
if (debugdiv) { debugdiv.value+="Konvertering til links tog: " + (t2-t1) + "ms\n"; }
}

// function PrepareKeyword strips punctuation and converts the
// string to lower case
function PrepareKeyword(str) {
  if (!str) return "";
  str=str.toLowerCase();
  return StripPunctuationAndSpaces(str);
}

function StripPunctuationAndSpaces(str) {
  if (!str) return "";
  var len=0, strlen=str.length;
  while (len<strlen && punctuation.indexOf(str.substr(strlen-len-1, 1))>-1) {
    len++;
  }
  return str.substr(0,strlen-len);
}

// function GetPunctuationAndSpaces returns any trailing
// punctuation and spaces
function GetPunctuationAndSpaces(str) {
  if (!str) return "";
  var len=0, strlen=str.length;
  while (len<strlen && punctuation.indexOf(str.substr(strlen-len-1, 1))>-1) {
    len++;
  }
  return str.substr(strlen-len,len);
}

// function FixInnerHTML removes an empty p tag at the end of the 
// objects innerHTML 
function FixInnerHTML(html) {
  var ptag="<P></P>";
  var l=ptag.length;
  if (html && html.length >= l) {
    var tmp=html.substring(html.length-l);
    if (tmp.toUpperCase() == ptag) {
	html=html.substring(0, html.length-l);
    }
  }
  return html;
}


// GetElementsByName is a modified version of document.getElementsByName
// that also works on IE Mac (by iterating through all divs)
function GetElementsByName(elemname) {
  var obj;
  if (document.getElementsByName) {
    obj=document.getElementsByName(elemname);
  }
  if ((!obj || obj.length==0) && document.getElementsByTagName) {
    obj=new Array();
    var divarray=document.getElementsByTagName("DIV");
    if (divarray && divarray.length) {
	for (var i=0; i<divarray.length; i++) {
	  if (divarray[i].id == elemname) {
	    obj[obj.length]=divarray[i];
	  }
	}
    }
  }
  return obj;
}


function GetWindowHeight() {
  var myWidth = 0;
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
	( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}

function AddTerm(elemid) {
  var termelem=GetElem(elemid);
  if (textelem && elemid) {
    // get A-tag (first child)
    var linktag=GetFirstChild(termelem);
    if (linktag) {
	var href=linktag.href;
	var str=linktag.innerHTML;

	// prepare string (lower case, remove trailing spaces)
	str=PrepareKeyword(str);

	// extract recordid from href
	var recordid=GetRecordId(href, popupPageId);	
	if (str && recordid) {
	  //terms[str]=href;
	  jstext+="terms['"+str+"']='"+recordid+"';\n";
	}
    }
  }
}
// Extract recordid from URL
function GetRecordId(href, pageid) {
  if (!href) { return ""; }
  var reg=new RegExp("recordid"+pageid+"=(\\d+)");
  var m=href.match(reg);
  if (m && m[1]) {
    return m[1];
  } 
  return null;
}
function GetElem(elemid) {
  if (document.all) {
    return document.all[elemid];
  } else if (typeof document.getElementById=="function") {
    return document.getElementById(elemid);
  }
  return null;
}
function GetFirstChild(obj) {
  if (obj) {
    if (obj.firstChild) { 
	return obj.firstChild; 
    } else if (obj.children) {
	return obj.children[0];
    }
    return null;
  }
}

function GetBodyTableHeight() {
  var h=null;
/*
  if (document.body && typeof(document.body.offsetHeight)!="undefined") {
    h=document.body.offsetHeight;
    if (!h && document.body.firstChild) {
	// this works in Safari
	h=document.body.firstChild.offsetHeight;
    }
  }
*/
  var obj=GetElem("bodytable");
  if (obj && obj.offsetHeight) {
    h=obj.offsetHeight;
  }
  return h;
}

// resize window
function ResizeWindow() {
  var bodyHeight=GetBodyTableHeight();
  var windowHeight=GetWindowHeight()
  if (bodyHeight && windowHeight && bodyHeight > windowHeight) {
    window.resizeBy(0, bodyHeight-windowHeight+50);
  }
}
if (location.href.indexOf("&resize=true")!=-1) {
  window.onload=ResizeWindow;
}