//
//============================================================================| D A T A   D E F I N I T I O N S |===
//
var global=new Array()      // Global variables
global.uniqueId=1000
global.uniqueId2=5000
var constants=new Array()   // Constants
constants.cssTagsIE=new Array('FONT-SIZE: ','LINE-HEIGHT: ','MARGIN-TOP: ','TEXT-INDENT: ')
constants.cssTagsFF=new Array('font-size: ','line-height: ','margin-top: ','text-indent: ')
var imgObj=new Array()
var T                       // XML template
var X                       // XML data 
var CELL=new Array()        // CELLs in internal formatting
var SLIDER                  // Scrolling animation
var FADER                   // Fading animation (opacity)
var offset=new Array()      // Style sheet elements: calculation base
// Preset containers:
offset['IMAGE']=new Array() // Calculation base - images
var userinfo=new Object()   // User information
var evalrefs=new Array()    // Shortcuts to Template XML components
var colorpalette=new Array()
var sizepalette=new Array('XXS','XS','S','M','L','XL','XXL','XXXL')
var Album=new Array()       // Photo album content
var floatingAlbum=new Array() // Floating album settings
//
//============================================================================| S W E E T   A N D   S H O R T |===
//
function redefine(code,contents) { var divId=document.getElementById(code); if (divId) divId.innerHTML=contents; }
function show(code) { var divId=document.getElementById(code); if (divId) divId.style.visibility='visible'; }
function hide(code) { var divId=document.getElementById(code); if (divId) divId.style.visibility='hidden'; }
function move(code,x,y) { var divId=document.getElementById(code);if (divId) { divId.style.left=x;divId.style.top=y;}}
function inform(msg) { window.status=msg;setTimeout('window.status="";',3000) }
function user_login() { cellScroll(0,0);show("login");document.forms.login.login_user.focus() }
function user_logout() { document.forms.login.login_key.value='';document.forms.login.submit() }
function direct_login(user,key) { document.forms.login.login_user.value=user;document.forms.login.login_key.value=key;document.forms.login.submit();return "" }
function setCookie(name, value, expires, path, domain, secure) { var curCookie=name+"="+escape(value)+((expires)?"; expires="+expires.toGMTString():"")+((path)?";path="+path:"")+((domain)?";domain="+domain:"")+((secure)?";secure":""); document.cookie = curCookie; }
function getCookie(name) { var dc=document.cookie;var prefix=name+"="; var begin=dc.indexOf("; "+prefix); if (begin==-1) { begin=dc.indexOf(prefix); if (begin!=0) return null;} else begin+=2; var end=document.cookie.indexOf(";",begin);if (end==-1) end=dc.length; return unescape(dc.substring(begin+prefix.length,end)); }
function deleteCookie(name, path, domain) { if (getCookie(name)) { document.cookie=name+"="+((path)?";path="+path:"")+((domain)?";domain="+domain:"")+"; expires=Thu, 01-Jan-70 00:00:01 GMT";return true;} else return false; }
function authorisation(request) { return (userinfo.authorisation.search(request)!=-1) }
function random() { return Math.round(Math.random()*1000) }
function IE() { return (navigator.appName.indexOf("Microsoft")!=-1); }
function redefine(code,contents) { var divId=document.getElementById(code); if (divId) divId.innerHTML=contents; }
function slide(code,y) { var divId = document.getElementById(code);if (divId) { divId.style.top=parseInt(divId.style.top)+y;}}
function pos(x,y) { this.x = Math.round(x); this.y = Math.round(y); }
function posKey(x,y) { return 'c'+x+'r'+y; }
function posKey2(xy) { return 'c'+xy.charAt(0)+'r'+xy.charAt(2); }
function Height() { return IE() ? document.body.offsetHeight-20 : window.innerHeight-16; }
function Width() { return IE() ? document.body.offsetWidth-20 : window.innerWidth-16; }
function trueSize(size) { var nSize=parseInt(size*Factor()); if (nSize==0) return 1; return nSize }
function notTransparent(color) { return ((color.toLowerCase())=='transparent')?'white':color; }
function setImageHeight(id,height) { offset['IMAGE'][id]=height; }
function UniqueID() { return ++global.uniqueId; }
function UniqueID2() { return ++global.uniqueId2; }
function floatingAlbumObj() { this.timer=null;this.index=0; }
function editorpanel(par) { if (authorisation('Aanpassen')) paragraafEditor.editpanel(par) }
function goCell(link) { clickLink('CELL',link,'CURRENT') }
function strimplode(str,level2) {
  if (level2) return str.replace(/\r\n/g,'~X')
  return str.replace(/\r\n/g,'~P').replace(/</g,'~Q').replace(/>/g,'~R').replace(/'/g,'~S').replace(/"/g,'~T').replace(/&/g,'~U').replace(/{/g,'~V').replace(/}/g,'~W')
}
function strexplode(str,asHtml,level2) {
  if (str==false) return ''
  if (level2) return str.replace(/~X/g,'\r\n')
  if (asHtml) return str.replace(/~P/g,'<BR>').replace(/~Q/g,'<').replace(/~R/g,'>').replace(/~S/g,"'").replace(/~T/g,'"').replace(/~U/g,'&').replace(/~p/g,'\r\n').replace(/~V/g,'{').replace(/~W/g,'}')
  return str.replace(/~P/g,'\r\n').replace(/~Q/g,'<').replace(/~R/g,'>').replace(/~S/g,"'").replace(/~T/g,'"').replace(/~U/g,'&').replace(/~V/g,'{').replace(/~W/g,'}')
}
function colorPalette(colid) { // colid can also be a form field name
  if (!colid) return colorpalette['A1']
  if (!colorpalette[colid]) {
    var online=new object_online()
    return online.getColor(colid)
  }
  return colorpalette[colid]
}
function eColorPalette(fieldname) { // element color palette
  var online=new object_online()
  return online.getColor(fieldname)
}
function object_online() {
  this.para=global.liveParagraph % 100
  this.area=parseInt((global.liveParagraph/100) % 10)
  this.cell=parseInt((global.liveParagraph/1000) % 100)
  this.values=new Array()
// prepare values:  
  if (!global.eCount) {
    for (var fld in X.N[global.cTag].N[this.cell].N[this.area].N[this.para].N) {
      if (X.N[global.cTag].N[this.cell].N[this.area].N[this.para].N[fld].T=="FIELD") this.values[X.N[global.cTag].N[this.cell].N[this.area].N[this.para].N[fld].A['ID']]=X.N[global.cTag].N[this.cell].N[this.area].N[this.para].N[fld].V
    }
  } else { // Fields for an element
    var elementCounter=0
    for (var ele in X.N[global.cTag].N[this.cell].N[this.area].N[this.para].N) {
      if (X.N[global.cTag].N[this.cell].N[this.area].N[this.para].N[ele].T=="ELEMENT") 
      {
        elementCounter++
        if (elementCounter==global.eCount) { 
          for (var fld in X.N[global.cTag].N[this.cell].N[this.area].N[this.para].N[ele].N) {
		    if (global.goodcause) alert(X.N[global.cTag].N[this.cell].N[this.area].N[this.para].N[ele].N[fld].A['ID'])
            this.values[X.N[global.cTag].N[this.cell].N[this.area].N[this.para].N[ele].N[fld].A['ID']]=X.N[global.cTag].N[this.cell].N[this.area].N[this.para].N[ele].N[fld].V
          }			
        }
      }
    }
  }
  this.get=function (fld) { return (this.values[fld])?this.values[fld]:'' }
  this.getNum=function (fld) { 
    var val
    if (this.values[fld]) {
	  val=parseInt(this.values[fld])
	  if (isNaN(val)) return 0
	  return val
	}
    return 0 
  }
  this.getColor=function (fld) { return colorPalette(this.values[fld]) }
}
function getQueryPos() { 
  if (self.location.search) { 
    var coordinates=self.location.search.substring(1)
    var x=coordinates.split(',')[0]
    var y=coordinates.split(',')[1]
    if (CELL[posKey(x,y)]) return new pos(x,y)
  } return new pos(0,0) 
}
function clickLink(type,link,target) { 
  var tokens=new Array()
  var linkStr
  if ((!link) || (link=='')) return
  switch (type) {
    case 'CELL':
      if ((link.length==3) && (link.charAt(1)==',')) link=link.charAt(0)+link.charAt(2)
      if ((!isNaN(link)) && (link.length==2)) { cellScroll(link.charAt(0),link.charAt(1)); break }
      tokens=link.split(':')
      if ((!isNaN(tokens[0])) && (!isNaN(tokens[1]))) {
	    if (tokens[0]==global.filenumber) { cellScroll(tokens[1].charAt(0),tokens[1].charAt(1)); break }
        linkStr='cellsite.php?index='+tokens[0]+'&cell='+tokens[1]
        if (target=='CURRENT') window.top.location=linkStr
        else open(linkStr)
      } else alert('Fout bij link')
      break
    case 'IMAGE': 
      if (target=='CURRENT') window.top.location=link
      else open(link)
      break
    case 'EXTERNAL': 
      if (target=='CURRENT') window.top.location=link
      else open(link)
      break
    case 'MOVIE': 
      break
  }
}
function Factor() { 
  var factor=(Height()*Width()) / (measurements.windowDimCon.x*measurements.windowDimCon.y)
  factor=((0.555)*(factor*1000)+(176))/1000                    // 260=120A+B, 1490=230A+B factor=(A*(E2*1000)+B)/1000    //0.602
  if (!IE()) factor*=0.8
  return (factor<2)?factor:2
}
function compassToHtml(asCursor) { 
  var mouseHover=''; 
  if (asCursor) {
    return '<table cellpadding=0 cellspacing=0><tr><td colspan=3 onclick=Scroll("N")><img name="c'+UniqueID()+'" src='+imgObj['cmp-n']+'>'+
           '<tr><td onclick=Scroll("W")><img name="c'+UniqueID()+'" src='+imgObj['cmp-w']+'><td onclick=Scroll("S")><img name="c'+UniqueID()+'" src='+imgObj['cmp-s']+'><td onclick=Scroll("E")><img name="c'+UniqueID()+'" src='+imgObj['cmp-e']+'></table>';
  }
  return '<table cellpadding=0 cellspacing=0><tr><td onclick=Scroll("NW")><img name="c'+UniqueID()+'" src='+imgObj['cmp-nw']+'><td style="vertical-align:top;text-align:center;" onclick=Scroll("N")><img name="c'+UniqueID()+'" src='+imgObj['cmp-n']+'><td onclick=Scroll("NE")><img name="c'+UniqueID()+'" src='+imgObj['cmp-ne']+'>'+
         '<tr><td onclick=Scroll("W")><img name="c'+UniqueID()+'" src='+imgObj['cmp-w']+'><td style="vertical-align:center;text-align:center;" '+mouseHover+' onclick=cellScroll(0,0)><img name="c'+UniqueID()+'" src='+imgObj['cmp-c']+'><td onclick=Scroll("E")><img name="c'+UniqueID()+'" src='+imgObj['cmp-e']+'>'+
         '<tr><td onclick=Scroll("SW")><img name="c'+UniqueID()+'" src='+imgObj['cmp-sw']+'><td onclick=Scroll("S")><img name="c'+UniqueID()+'" src='+imgObj['cmp-s']+'><td onclick=Scroll("SE")><img name="c'+UniqueID()+'" src='+imgObj['cmp-se']+'></table>'; 
}
function navPanelFocus(obj,x,y,on) { 
  var peekId='peek'+posKey(measurements.matrixPos.x,measurements.matrixPos.y);
  var peekTitle=''
  if (on) { 
    peekTitle=CELL[posKey(x,y)].title
    redefine(peekId,'<table class=titlepeek height=100% cellspacing=0 cellpadding=4><tr><td><img src=img/blank.gif width=200pt height=1><br>'+peekTitle+'</table>');      
    obj.style.background='yellow';
  } else {
    redefine(peekId,'');
    obj.style.background=notTransparent(CELL[posKey(x,y)].bgColor);
  }
}
function faderFocus(name,x,y,on) { opacityFocus(name+posKey(x,y),'OPA40',on) }
function opacityFocus(id,prefix,on) {
  if (on) { if (!((FADER.active) && (FADER.type==(prefix+'FOCUS')))) {
              FADER.reassign(id,prefix+'FOCUS')
              FADER.animate(40) }
  } else {  if (!((FADER.active) && (FADER.type==(prefix+'FADE')))) {
              FADER.reassign(id,prefix+'FADE')
              FADER.animate(10) } }
}
//
//============================================================================| S C R O L L   A N D   R E S I Z E |===
//
function Scroll(direction,automatic) {
  var x;
  var y;
  var onEdge=false;
  var onTarget=false;

  with (measurements) { 
    x=matrixPos.x;
    y=matrixPos.y;
    for (;(!(onEdge || onTarget));) {
      switch (direction) {
        case 'N' : if (y>0) y--; else onEdge=true; break;
        case 'NE': if (y>0) y--; else onEdge=true;
                   if (x<matrixDim.x) x++; else onEdge=true; break;
        case 'E' : if (x<matrixDim.x) x++; else onEdge=true; break;
        case 'SE': if (y<matrixDim.y) y++; else onEdge=true;
                   if (x<matrixDim.x) x++; else onEdge=true; break;
        case 'S' : if (y<matrixDim.y) y++; else onEdge=true; break;
        case 'SW': if (y<matrixDim.y) y++; else onEdge=true;
                   if (x>0) x--; else onEdge=true; break;
        case 'W' : if (x>0) x--; else onEdge=true; break;
        case 'NW': if (y>0) y--; else onEdge=true;
                   if (x>0) x--; else onEdge=true; break;
        case 'HOME' : x=0;y=0; break;
      }
      if (CELL[posKey(x,y)]) if (!CELL[posKey(x,y)].hidden){
        onTarget=true;
        cellScroll(x,y,false,automatic);
      }
    } 
    if (!onTarget) cellScroll(matrixPos.x,matrixPos.y);
  }
}
function cellScroll(left,top,fastPath,automatic,siteID) {
// Prepare the SLIDER animation to scroll from current position to indicated position:  
  var topStep=measurements.windowDim.y*top; 
  var leftStep=measurements.windowDim.x*left;
  if ((siteID) && (siteID!=global.filenumber)) { window.top.location='cellsite.php?index='+siteID+'&cell='+left+top; return }
  if (!CELL[posKey(left,top)]) { inform('Cel niet gevonden - '+left+top);return}
// Suppress scrolling action in some cases - for automatic movements only
  if ((automatic) && (CELL[posKey(measurements.matrixPos.x,measurements.matrixPos.y)])) 
  if (CELL[posKey(measurements.matrixPos.x,measurements.matrixPos.y)].onExit!='') eval(CELL[posKey(measurements.matrixPos.x,measurements.matrixPos.y)].onExit)
  if (CELL[posKey(left,top)].onEntry!='') eval(CELL[posKey(left,top)].onEntry)

  measurements.matrixPos.x=left
  measurements.matrixPos.y=top 
  measurements.scrollPos.x=leftStep
  measurements.scrollPos.y=topStep
  if (fastPath) window.scrollTo(leftStep,topStep)
  else {
    SLIDER.path=animation.flatCirclePath(window.document.body.scrollLeft,window.document.body.scrollTop,leftStep,topStep,50)
    SLIDER.animate(constants.cellScrollSpeed)
  }
// move the menu
  Menu.move() 
  if (authorisation('Aanpassen')) Menu.systemMenu(CELL[posKey(left,top)].XMLcell,leftStep,topStep)
}
//
//============================================================================| P R I N T   F R I E N D L Y |===
//
function printCell(x,y,XL) {
  var style=measurements.adaptStyleSheet((XL)?1.1:0.6)
  var html=''
  if (!x) x=measurements.matrixPos.x
  if (!y) y=measurements.matrixPos.y
  if (CELL[posKey(x,y)]) html+=CELL[posKey(x,y)].content  
  if (global.printWindow) global.printWindow.close()
  global.printWindow=open("","printerFriendly")
  global.printWindow.document.write('<html><title>Printvriendelijke weergave</title><style>'+style+'</style><body style="background:white">'+html+'</body></html>')
}
//
//============================================================================| C E L L   C O N T E N T S |===
//
function cellObj(x,y,title,content,XMLcell) {
  this.position=new pos(x,y)
  this.title=(title) ? title : ''
  this.content=content
  this.XMLcell=XMLcell

  this.Mc=-1
  this.hidden=false
  this.navPanel=true
  this.compass=true
  this.bgColor='transparent' 
  this.backdropImage=''
  this.cellMargins=new Array(10,10,10,10)
  
  this.onEntry=''
  this.onExit=''

  this.toHtml=function() {
    var yPos=(measurements.windowDim.y*this.position.y);
    var xPos=(measurements.windowDim.x*this.position.x);
    var pxMargin=Math.round(Width()*0.03); //Fixed at 3% of the edge
    var pyMargin=Math.round(Height()*0.03); 
    var pMargin=(pyMargin>pxMargin) ? pyMargin : pxMargin;
    var navPanelWidth=Math.round(22*Factor());
    var cMargin=Math.round(((offset['IMAGE']['COMPASS']+15)*3.2)*Factor()); 
    var dMargin=Math.round(((offset['IMAGE']['DIRECTION']+15)*1.5)*Factor()); 
    var dMargin2=Math.round(dMargin/4);
    var html=this.content;

    if (cMargin>60) {
      if (this.navPanel) html+='<div class=panel id="panel'+posKey(this.position.x,this.position.y)+'" style="position:absolute;top:'+(yPos+pMargin)+';left:'+(xPos+pMargin)+';" onmouseover=faderFocus("panel",'+this.position.x+','+this.position.y+',true) onmouseout=faderFocus("panel",'+this.position.x+','+this.position.y+')>'+this.navPanelToHtml(navPanelWidth)+'</div>';
      if (this.compass) html+='<div class=compass id="compass'+posKey(this.position.x,this.position.y)+'" style="position:absolute;top:'+(yPos+measurements.windowDim.y-cMargin)+';left:'+(xPos+measurements.windowDim.x-cMargin)+';"onmouseover=faderFocus("compass",'+this.position.x+','+this.position.y+',true) onmouseout=faderFocus("compass",'+this.position.x+','+this.position.y+')>'+compassToHtml(constants.simpleCompass)+'</div>';
    } 
    return '<table width='+measurements.windowDim.x+'px \
height='+measurements.windowDim.y+'px cellspacing=0 cellpadding=0>\
<tr><td colspan=3><img src=img/blank.gif height='+this.cellMargins[0]+'px>\
<tr><td><img src=img/blank.gif width='+this.cellMargins[3]+'px>\
<td>'+html+'<td><img src=img/blank.gif width='+this.cellMargins[1]+'px>\
<tr><td colspan=3><img src=img/blank.gif height='+this.cellMargins[2]+'px></table>'
  }
  this.navPanelToHtml=function(x) {
    var html='<table cellspacing=0 cellpadding=0><td><img src='+imgObj['navp-nw']+'><td style="background-image:URL('+imgObj['navp-n']+');background-repeat:repeat-x;"><td><img src='+imgObj['navp-ne']+'><td rowspan=20><br><div id="peek'+posKey(this.position.x,this.position.y)+'"></div><tr><td style="background-image:URL('+imgObj['navp-w']+');background-repeat:repeat-y;"><td><table class=navMatrix cellspacing=1 cellpadding=0>';
    var y=Math.round(x*(Height()/Width()));
    var hideCell
    with (measurements) {
      for (var Y=0;Y<=matrixDim.y;Y++) {
        html+='<tr>';
        for (var X=0;X<=matrixDim.x;X++) {
          if ((Y==this.position.y) && (X==this.position.x)) html+='<td class=cursor><img src=img/blank.gif width='+x+'pt height='+y+'pt>';
          else {
            if (!CELL[posKey(X,Y)]) html+='<td class=empty><img src=img/blank.gif width='+x+'pt height='+y+'pt>';
            else { 
              hideCell=CELL[posKey(X,Y)].hidden
              if (hideCell) { if (authorisation('Aanpassen')) hideCell=false }
              if (hideCell) html+='<td class=empty><img src=img/blank.gif width='+x+'pt height='+y+'pt>';
              else html+='<td style="background:'+notTransparent(CELL[posKey(X,Y)].bgColor)+'" onmouseover=navPanelFocus(this,'+X+','+Y+',true) onmouseout=navPanelFocus(this,'+X+','+Y+') onclick=javascript:cellScroll('+X+','+Y+');><img src=img/blank.gif width='+x+'pt height='+y+'pt>';
            }
          }
        }
      }
    }
    return html+'</table><td style="background-image:URL('+imgObj['navp-e']+');background-repeat:repeat-y;"><tr><td><img src='+imgObj['navp-sw']+'><td style="background-image:URL('+imgObj['navp-s']+');background-repeat:repeat-x;"><td><img src='+imgObj['navp-se']+'><td></table>';
  }
}
function setCell(XY,title,content,XMLcell) { 
  var X=XY.split(',')[0]
  var Y=XY.split(',')[1]
  var id=posKey(X,Y)

  with (measurements.matrixDim) { // Adjust matrix size when required
    if (x<X) x=X;
    if (y<Y) y=Y;
  }
  CELL[id]=new cellObj(X,Y,title,content,XMLcell);
}
function attrExplode(attrStr) {
  var aList=new Array()
  var name
  var val
  while (attrStr.length>0) {
    name=attrStr.substr(0,attrStr.search('="'))
    val=attrStr.substr(attrStr.search('="')+2)
    attrStr=val.substr(val.indexOf('"')+2)
    val=val.substr(0,val.indexOf('"'))
    if (name.length>0) aList[name]=val
  }
  return aList
}
function XMLnode(xmltag,xmlvalue,attrStr) {
  this.T=xmltag
  this.V=(xmlvalue) ? xmlvalue : false
  this.A=new Array()
  if (attrStr.length>1) this.A=attrExplode(attrStr)
  this.N=new Array()
  this.add=function(xmltag,xmlvalue,attrStr) { this.N[this.N.length]=new XMLnode(xmltag,xmlvalue,attrStr) }
  this.copy=function() {
    var root=new XMLnode(this.T,this.V,'')
    for (var at in this.A) root.A[at]=this.A[at]
    for (var node in this.N) root.N[node]=this.N[node].copy()
    return root
  }
}
function JSONadd(node,T,V,attrStr) {
    var obj=new Object()
    obj.T=T
    obj.V=V
    if (!attrStr=="") obj.A=attrExplode(attrStr)
    if (node.N==null) node.N=new Array()
    node.N[node.N.length]=obj
}
function JSONcopy(node) {
    var newRoot=new Object()
    newRoot.T=node.T
    newRoot.V=node.V
    if (node.A==null) newRoot.A=null
    else {
	  newRoot.A=new Array()
	  for (a in node.A) newRoot.A[a]=node.A[a]
	}
    if (node.N==null) newRoot.N=null
    else {
      newRoot.N=new Array()
      for (var n in node.N) newRoot.N[newRoot.N.length]=JSONcopy(node.N[n])
    }
    return newRoot 
}  
//
//============================================================================| O V E R A L L   C O N T R O L |===
//
function setEvalReferences() {  // Set (all) eval references on "evalrefs"
  for (var lvl1 in T.N) switch (T.N[lvl1].T) { // Template matters only !
    case 'HEADER': break;
    case 'TEMPLATE': evalrefs[T.N[lvl1].A["ID"]]="T.N["+lvl1+"]"; 
    for (var lvl2 in T.N[lvl1].N) switch (T.N[lvl1].N[lvl2].T) { 
      case 'HTML': evalrefs[T.N[lvl1].A["ID"]+"HTML"]="T.N["+lvl1+"].N["+lvl2+"]"; break;
    } break;
    case 'PARAGRAPH': evalrefs[T.N[lvl1].A["ID"]]="T.N["+lvl1+"]"; 
    for (var lvl2 in T.N[lvl1].N) switch (T.N[lvl1].N[lvl2].T) { 
      case 'HTML': evalrefs[T.N[lvl1].A["ID"]+"HTML"]="T.N["+lvl1+"].N["+lvl2+"]"; break;
	  case 'EDITORFORM': evalrefs[T.N[lvl1].A["ID"]+"EDITORFORM"]="T.N["+lvl1+"].N["+lvl2+"]"; break;
      case 'FIELD': evalrefs[T.N[lvl1].A["ID"]+T.N[lvl1].N[lvl2].A["ID"]]="T.N["+lvl1+"].N["+lvl2+"]"; break;
    } break;
    case 'ELEMENT': evalrefs[T.N[lvl1].A["ID"]]="T.N["+lvl1+"]"; 
    for (var lvl2 in T.N[lvl1].N) switch (T.N[lvl1].N[lvl2].T) { 
      case 'HTML': evalrefs[T.N[lvl1].A["ID"]+"HTML"]="T.N["+lvl1+"].N["+lvl2+"]"; break;
      case 'EVAL': evalrefs[T.N[lvl1].A["ID"]+"EVAL"]="T.N["+lvl1+"].N["+lvl2+"]"; break;
      case 'EDITORFORM': evalrefs[T.N[lvl1].A["ID"]+"EDITORFORM"]="T.N["+lvl1+"].N["+lvl2+"]"; break;
      case 'FIELD': evalrefs[T.N[lvl1].A["ID"]+T.N[lvl1].N[lvl2].A["ID"]]="T.N["+lvl1+"].N["+lvl2+"]"; break;
    } break;
    case 'DOMAIN': evalrefs[T.N[lvl1].A["ID"]]="T.N["+lvl1+"]"; break;
  }
}
function build_xml(cellId) {
  var chtml='' // Cell
  var ahtml    // Area
  var phtml    // Paragraph
  var pTemp    // Paragraph template
  var ehtmls   // Elements
  var ehtml    // Element (single)
  var eEval    // eval for element
  var tarr     // template areas 
  var fieldname
  var key
  this.systemVars=function(str) { // find the {system:field} tags and replace them by actual values: 
    if (!str) str=""
    for (;str.search("{system:")!=-1;) {
      var anchor=str.search('{system:')
      var fulltag=str.substr(anchor,(str.indexOf('}',anchor)-anchor+1))
      var value
      eval('value='+fulltag.substr(8,(fulltag.length-9)))
      str=str.replace(fulltag,value)
    } return str        
  }
  this.lostFields=function(str) { // find fields that have not been filled in
    if (!str) str=""
    for (;str.search("{")!=-1;) {
      var anchor=str.search('{')
      var fulltag=str.substr(anchor,(str.indexOf('}',anchor)-anchor+1))
      str=str.replace(fulltag,'')
    } return str        
  }
  this.startOff=function(area,cell) {
    return '<table cellspacing=1 cellpadding=2 class=emenu style="background-color:brown" style="background-color:black">\
	<tr><td class=off onMouseOver=javascript:this.className="on" onMouseOut=javascript:this.className="off" style="cursor:pointer;" onclick=javascript:paragraafEditor.create("'+((parseInt(area)*100)+(parseInt(cell)*1000))+'")>Nieuwe paragraaf\
    <td class=off onMouseOver=javascript:this.className="on" onMouseOut=javascript:this.className="off" style="cursor:pointer;" onclick=javascript:paragraafEditor.paste("'+((parseInt(area)*100)+(parseInt(cell)*1000))+'")>Paragraaf plakken\
    </table>'	
  }
  TRACE('build_xml()',cellId)
  if (evalrefs.length==0) setEvalReferences()
  for (var group in X.N) if (X.N[group].T=="CELLS") {
  for (var cell in X.N[group].N) if ((X.N[group].N[cell].T=="CELL") && ((!cellId) || (cellId==cell))) { 
    eval("chtml="+evalrefs[X.N[group].N[cell].A["TEMPLATEID"]+"HTML"]+".V")
    for (var area in X.N[group].N[cell].N) if (X.N[group].N[cell].N[area].T=="AREA") { 
      ahtml='';
      for (var paragraph in X.N[group].N[cell].N[area].N) if (X.N[group].N[cell].N[area].N[paragraph].T=="PARAGRAPH") { 
        if (!evalrefs[X.N[group].N[cell].N[area].N[paragraph].A["ID"]+"HTML"]) alert('Paragraaf '+X.N[group].N[cell].N[area].N[paragraph].A["ID"]+' onbekend')
	  else {
          eval("pTemp="+evalrefs[X.N[group].N[cell].N[area].N[paragraph].A["ID"]])
          eval("phtml="+evalrefs[X.N[group].N[cell].N[area].N[paragraph].A["ID"]+"HTML"]+".V")
          key=parseInt(paragraph)+(parseInt(area)*100)+(parseInt(cell)*1000)
          global.liveParagraph=key
          ehtmls=''
		  global.eCount=0
          for (var fieldOrElement in X.N[group].N[cell].N[area].N[paragraph].N) { 
            switch (X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].T) {
              case 'FIELD':
                global.eCount=0
                fieldname="{"+X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].A["ID"]+"}"
                if (X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].V===false) eval("phtml=phtml.replace(/"+fieldname+"/g,'')")
                else eval("phtml=phtml.replace(/"+fieldname+"/g,X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].V)")
                phtml=systemVars(phtml)
                break
              case 'ELEMENT':
                global.eCount++
                if (!evalrefs[X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].A["ID"]+"HTML"]) { alert('Element '+X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].A["ID"]+' onbekend');break }
                eval("ehtml="+evalrefs[X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].A["ID"]+"HTML"]+".V")
                eEval=""
                if (evalrefs[X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].A["ID"]+"EVAL"]) eval("eEval="+evalrefs[X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].A["ID"]+"EVAL"]+".V")
                for (var field in X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].N) { 
                  fieldname="{"+X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].N[field].A["ID"]+"}"
                  global.elementFieldValue2=global.elementFieldValue
                  global.elementFieldValue=X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].N[field].V
                  if (global.elementFieldValue===false) eval("ehtml=ehtml.replace(/"+fieldname+"/g,'')")
                  else eval("ehtml=ehtml.replace(/"+fieldname+"/g,global.elementFieldValue)")
                  if (eEval!="") eval("eEval=eEval.replace(/"+fieldname+"/g,X.N[group].N[cell].N[area].N[paragraph].N[fieldOrElement].N[field].V)")
                }
                ehtmls+=this.systemVars(ehtml);
                if (eEval!="") eval(this.systemVars(eEval)) 
                break
            }
          }
          if (!pTemp.A['AFLOAT']) phtml="<div id="+key+" style='position:absolute'></div>"+phtml.replace("{panel}","onmouseover=javascript:editorpanel("+key+")")
          phtml=phtml.replace('{elements}',ehtmls)
          ahtml+=lostFields(phtml)
        }
      }
      if ((ahtml=="") && (authorisation('Aanpassen'))) ahtml=startOff(area,cell)
      chtml=chtml.replace("{"+X.N[group].N[cell].N[area].A["ID"]+"}",ahtml)
    }  
// Area's that were not available in X but are available on the template should be processed:
    eval("tarr="+evalrefs[X.N[group].N[cell].A["TEMPLATEID"]])
    for (var area in tarr.N) if ((tarr.N[area].T=="AREA") && (chtml.search("{"+tarr.N[area].A["ID"]+"}")!=-1)) { 
      ahtml=""
      if (authorisation('Aanpassen')) ahtml=startOff(area,cell)
      chtml=chtml.replace("{"+tarr.N[area].A["ID"]+"}",ahtml)
    }
// Set cell parameters: 
    setCell(X.N[group].N[cell].A['COORDINATES'],X.N[group].N[cell].A['TITLE'],strexplode(chtml,1),cell);
    key=posKey2(X.N[group].N[cell].A['COORDINATES'])
    CELL[key].backdropImage=(X.N[group].N[cell].A['BACKDROPIMAGE'])?(X.N[group].N[cell].A['BACKDROPIMAGE']):''
    CELL[key].bgColor=(X.N[group].N[cell].A['BGCOLOR'])?colorPalette(X.N[group].N[cell].A['BGCOLOR']):'transparent'
    CELL[key].navPanel=(X.N[group].N[cell].A['NAVPANEL'])?((X.N[group].N[cell].A['NAVPANEL'])=='Y'):false
    CELL[key].compass=(X.N[group].N[cell].A['COMPASS'])?((X.N[group].N[cell].A['COMPASS'])=='Y'):false
    CELL[key].hidden=(X.N[group].N[cell].A['HIDDEN'])?((X.N[group].N[cell].A['HIDDEN'])=='Y'):false
    eval('CELL["'+key+'"].cellMargins='+evalrefs[X.N[group].N[cell].A['TEMPLATEID']]+'.A["MARGINS"].split(",")')
  }}
}
function build() { // Build is called from measurements.heartbeat();
// Style sheet builder - control the background colors: 
  var html='<style>'
  var htmlBackgrounds=''
  var htmlBackdrop=''
  var backgroundImage=''
  var backdropImage=''
  var hideCell

  TRACE('build()')
  for (cid in CELL) html+='table.'+cid+' tr td { background:'+CELL[cid].bgColor+'; }';
  html+='</style><table cellspacing=0 cellpadding=0>'; 

  for (var rowz=0;rowz<=measurements.matrixDim.y;rowz++) {
    html+='<tr>'
    htmlBackgrounds+='<tr>'
    htmlBackdrop+='<tr>'
    for (var colz=0;colz<=measurements.matrixDim.x;colz++) {
      if (CELL[posKey(colz,rowz)]) {
        hideCell=CELL[posKey(colz,rowz)].hidden
        if (hideCell) { if (authorisation('Aanpassen')) hideCell=false; }
        if (hideCell) html+='<td style="background-color:'+constants.nocellColor+'">'
        else html+='<td>'+CELL[posKey(colz,rowz)].toHtml()
      }
      else {
        if (CELL[posKey(colz,rowz)]) html+='<td>'+CELL[posKey(x,y)].toHtml()
        else html+='<td style="background-color:'+constants.nocellColor+'">'
      }
      if (CELL[posKey(colz,rowz)]) { // Cell exists
	    backgroundImage=constants.backGroundImage
        backdropImage=(CELL[posKey(colz,rowz)].backdropImage!='')?CELL[posKey(colz,rowz)].backdropImage:'img/blank.gif'
      } else {
	    backgroundImage='img/blank.gif'
	    backdropImage='img/blank.gif'
	  }
      htmlBackgrounds+='<td><img src="'+backgroundImage+'" width='+Width()+' height='+Height()+'>'
      htmlBackdrop+='<td><img src="'+backdropImage+'" width='+Width()+' height='+Height()+'>'
    }
    htmlBackgrounds+='<td style="background-color:'+constants.nocellColor+'"><img src=img/blank.gif width=60>'
    htmlBackdrop+='<td style="background-color:'+constants.nocellColor+'"><img src=img/blank.gif width=60>'
  }
  redefine('backdrop','<table cellspacing=0 cellpadding=0>'+htmlBackdrop+'</table>')
  redefine('backgrounds','<table cellspacing=0 cellpadding=0>'+htmlBackgrounds+'</table>')
  redefine('all',html+'<td rowspan='+(measurements.matrixDim.y+1)+'>&nbsp;<tr><td rowspan='+(measurements.matrixDim.y+1)+' style="background-color:'+constants.nocellColor+'"><p class=l>BV TallVision IT - CellSite &copy; - info@cellsite.nl<br><br><br><br><br></table>');
  measurements.adaptImageHeights()
  TRACE('build()::exit')
}

