function setLayerVisibility(whichPanel,isVisible)
{
	if (document.getElementById)
	{
		var panel = document.getElementById(whichPanel).style;
		panel.display = isVisible ? "block":"none";
	}
}

//Window open
var cmsadmindefaultpopup='width=666,height=450,scrollbars=yes,location=no,menubar=no,resizable=yes,dependent=yes';

function windowopen(url,winid,params) {
  if (!url) url='about:blank';

  var strMsg="Your browser (or pop-up blocker) appears to have prevented this link from opening a pop-up window. Please add this website to your 'trusted sites' or 'white list' in order to see all features.";
  var oWin=window.open(url,winid,params);
  if (oWin==null || typeof(oWin)=="undefined")  {
    alert(strMsg);
  } else {
    if (oWin.closed)  {
      alert(strMsg);
    } else {
      oWin.focus();
      return(oWin);
    }
  }
}

//toggle layers
//Thanks to http://www.netlobo.com/div_hiding.html for this code!
function toggleLayer(whichLayer)  {
  if (document.getElementById)  {
    // this is the way the standards work
    var style2 = document.getElementById(whichLayer).style;
    style2.display = style2.display? "":"block";
  } else if (document.all)  {
    // this is the way old msie versions work
    var style2 = document.all[whichLayer].style;
    style2.display = style2.display? "":"block";
  } else if (document.layers)  {
    // this is the way nn4 works
    var style2 = document.layers[whichLayer].style;
    style2.display = style2.display? "":"block";
  }
}

//get elem
function getElem(id)  {
	if (document.all) {
		return (document.all(id));
	} else {
		return (document.getElementById(id));
	}
}


//rel="external" instead of target="_blank" for standards fallback of no new windows

function externalLinks() {
  if (!document.getElementsByTagName) { return; }

  var anchors = document.getElementsByTagName("a");
  for (var i=0; i<anchors.length; i++) {
    var anchor = anchors[i];
    if (anchor.getAttribute("href") && anchor.getAttribute("rel")) {
	 	if (anchor.getAttribute("rel").indexOf('popup:') == 0) {
	      anchor.target = anchor.getAttribute("rel").substring(6);
	 	} else if (anchor.getAttribute("rel") == "external") {
	      anchor.target = "_blank";
		}
    }
  }
}

//clear inputs in forms, etc
function clearAndFocus( el,def ) { if (el.value==def) el.value = ''; el.focus() }
function InputLostFocus( el,def ) { if (el.value=='') el.value = def;}
function clearDefault( el,def ) { if (el.value==def) el.value = ''; }


//bookmark site
/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

/* Modified to support Opera */
function bookmarksite(title,url)  {
  if (window.sidebar) { // firefox
    window.sidebar.addPanel(title, url, "");
  } else if(window.opera && window.print) { // opera
    var elem = document.createElement('a');
    elem.setAttribute('href',url);
    elem.setAttribute('title',title);
    elem.setAttribute('rel','sidebar');
    elem.click();
  } else if(document.all) { // ie
    window.external.AddFavorite(url, title);
  }
}

//javascript rollovers (dont use them for menus, learn some CSS!
function MM_preloadImages() {
  var d=document;
  if (d.images)  {
    if(!d.MM_p) d.MM_p=new Array();
    var i;
    var j=d.MM_p.length;
    var a=MM_preloadImages.arguments;
    for(i=0; i<a.length; i++) {
      if (a[i].indexOf("#")!=0) {
        d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];
      }
    }
  }
}

function MM_swapImgRestore() {
  var i,x;
  var a=document.MM_sr;
  for (i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) {
    x.src=x.oSrc;
  }
}

function MM_findObj(n, d) {
  var p,i,x;
  if (!d) {  d=document; }
  if ((p=n.indexOf("?"))>0 && parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document;
    n=n.substring(0,p);
  }
  if (!(x=d[n]) && d.all) { x=d.all[n] };
  for (i=0;!x&&i<d.forms.length;i++) { x=d.forms[i][n]; }
  for (i=0;!x&&d.layers&&i<d.layers.length;i++) { x=MM_findObj(n,d.layers[i].document) };
  if (!x && d.getElementById) { x=d.getElementById(n); }
  return x;
}

function MM_swapImage() {
  var i,x;
  var j=0;
  var a=MM_swapImage.arguments;
  
  document.MM_sr=new Array;
  for(i=0;i<(a.length-2);i+=3) {
    if ((x=MM_findObj(a[i]))!=null) {
      document.MM_sr[j++]=x;
      if(!x.oSrc) { x.oSrc=x.src; }
      x.src=a[i+2];
    }
  }
}



//dynamic text size
var txtnormalsize=Number(0.76);
var txtmidsize=Number(1.0);
var txtbigsize=Number(1.2);

function setinitialtextsize() {
	var textsize=getCookie('cmstextsize');
	if (textsize!=null) {
		textsize=Number(textsize);
		document.body.style.fontSize=textsize+'em';
	}
}

function changetxtsize(i) 
{
	document.body.style.fontSize=i+'em';
	setCookie("cmstextsize", i, null);
}

// Sets cookie values. Expiration date is optional//
function setCookie(name, value, expire) {
   document.cookie = name + "=" + escape(value)   + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
}

function getCookie(Name) {
   var search = Name + "=";  
   if (document.cookie.length > 0) { // if there are any cookies
        offset = document.cookie.indexOf(search)
        if (offset != -1) { // if cookie exists
			offset += search.length          // set index of beginning of value
			end = document.cookie.indexOf(";", offset)          // set index of end of cookie value
			if (end == -1)
					end = document.cookie.length;
			return unescape(document.cookie.substring(offset, end));
		}    
	}
}

//XML Group of functions - all functions related to XML

function xml_selectSingleNode(contextNode, elementPath) {
  if(window.ActiveXObject) {
    return contextNode.selectSingleNode(elementPath);
  } else {
    var xpe = new XPathEvaluator();
    var nsResolver = xpe.createNSResolver( contextNode.ownerDocument == null ? contextNode : contextNode.ownerDocument.documentElement);
    var results = xpe.evaluate(elementPath,contextNode,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    return results.singleNodeValue; 
  }
}

function xml_selectNodes(contextNode, elementPath) {
  if(window.ActiveXObject) {
    return contextNode.selectNodes(elementPath);
  } else {
    var xpe = new XPathEvaluator();
    var nsResolver = xpe.createNSResolver( contextNode.ownerDocument == null ? contextNode.documentElement : contextNode.ownerDocument.documentElement);
    var results = xpe.evaluate(elementPath,contextNode,nsResolver,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var a=new Array();
    for (var i=0; i<results.snapshotLength; i++ ) {
      a[i]=results.snapshotItem(i);
    }
    return a; 
  }
}

function xml_setText(contextNode, elementPath, v) {
  var n=xml_selectSingleNode(contextNode, elementPath);
  var t;
  
  if (!n) { return ""; }

  if (n.nodeType==2) {
    n.nodeValue=v;
  } else {
    t=xml_selectSingleNode(n, "text()");
  
    if (t==null) {
      if (contextNode.ownerDocument == null) return;
      n.appendChild(contextNode.ownerDocument.createTextNode(v));
    } else {
      t.nodeValue=v;
    }
  }
}

function xml_getText(contextNode, elementPath) {
  var n=xml_selectSingleNode(contextNode, elementPath);
  var t;
  
  if (!n) { return ""; }
  if (n.nodeType==2) {
    t=n;
  } else {
    t=xml_selectSingleNode(n, "text()");
  }
  
  if (t==null) {
    return "";
  } else {
    return t.nodeValue;
  }
}

function xml_getXml(contextNode)
{
  if (contextNode.xml) {
    return contextNode.xml;
  } else {
    var xmlser=new XMLSerializer();
    return xmlser.serializeToString(contextNode);
  }
}

function xml_getXmlDom() {
	var xmldom;
	try {
		xmldom = new ActiveXObject("Microsoft.XMLDOM");
  	xmldom.setProperty("SelectionLanguage","XPath");
	} catch (e) {
		try {
			xmldom = document.implementation.createDocument("","",null);
		} catch (e) {
			xmldom=null;
		}
	}
	return xmldom;
}

function xml_getXmlHttp() {
	var xmlhttp;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new XMLHttpRequest();
			} catch (e) {
				xmlhttp=null;
			}
		}
	}
	return xmlhttp;
}

function xml_blockingDataGet(url) {
	var xmlhttp = xml_getXmlHttp();
	if (url.indexOf("?")>-1) {
		url+='&unique='+Number(new Date());
	} else {
		url+='?unique='+Number(new Date());
	}
	xmlhttp.open("GET", url, false);
	xmlhttp.send("");
	
  var xmlobj=null;
  
  try {
    xmlobj=xml_getXmlDom();
    xmlobj.loadXML(xmlhttp.responseText);
  } catch (e) {
    try {
      var oParser = new DOMParser();
      xmlobj = oParser.parseFromString(xmlhttp.responseText, "text/xml");
    } catch (e) {
    }
  }
  
  return xmlobj;
}

//HTML Group functions - all functions that manipulate HTML code or the browser DOM

function html_blockingDataGet(url) {
	var xmlhttp = xml_getXmlHttp();
	if (url.indexOf("?")>-1) {
		url+='&unique='+Number(new Date());
	} else {
		url+='?unique='+Number(new Date());
	}
	xmlhttp.open("GET", url, false);
	xmlhttp.send("");
	
  return xmlhttp.responseText;
}

function html_encode(s)
{
  s=s.replace('<','&lt;').replace('>','&gt;').replace('&','&amp;');

  return s;
}

function html_getClientWidth()
{
  return document.documentElement.clientWidth;
}
function html_getClientHeight()
{
  return document.documentElement.clientHeight;
}

//Palettes  -  all functions relating to virtual (DIV based) popups

var palettes=new Array();

function palette(domobj, nstylingdivs, nmode)
{
  //INTERNAL STATE
  this.servercomponent='';      //the program on the server that supplies data for the panel (parameters in querystring)
  this.updatefrequency=0;       //just fetch new data regardless each X seconds (0 is never)
  this.checkfrequency=0;        //run a check command to see if data has changed - if changed, then fetch (0 is never)
  if (domobj==null) {
    this.parentobject=document.getElementsByTagName('BODY')[0];
  } else {
    this.parentobject=domobj;   //the object under which a new child shall be appended
  }
  this.innerdiv=null;           //the top level div that is created when the palette is shown
  this.className='CMSPalette';  //the class name attached to the top level div 
  this.id='';                   //the id attached to the top level div 
  this.caption="Palette";
  this.tickstillcheck=0;
  this.tickstillupdate=0;
  this.stylingdivs=(nstylingdivs ? nstylingdivs : 0);
  this.xmlobj=null;
  this.responsetext='<p>Loading...</p>';
  this.contentdiv=null;
  this.captiondiv=null;
  this.mode=nmode;

  //EVENTS
  this.onredraw=_palettes_defaultredraw;
  this.ontick=null;             //something to do every one second tick e.g. custom positioning 

  //FUNCTIONS  
  this.open=_palettes_open;
  this.close=_palettes_close;

  if (this.mode=='html') {
    this.refreshcontent=_palettes_refreshhtmlcontent;
  } else if (this.mode=='iframe') {
    this.refreshcontent=function () { this.responsetext='<iframe src="'+this.url+'"></iframe>'; this.onredraw(); }
  } else {
    this.refreshcontent=_palettes_refreshcontent;
  }
  this.setcaption=function (cap) { this.caption=html_encode(cap); if (this.captiondiv) { this.captiondiv.innerHTML=this.caption; } }
  
  return this;
}

//helper function to create a palette and add it to the list 
function palettes_create(domobj, stylingdivs, nmode)
{
  return (palettes[palettes.length]=new palette(domobj, stylingdivs, nmode));
}

function palettes_close(e)
{
  if (window.event) {
    window.event.srcElement.parentNode.palette.close();
  } else if (e) {
    e.target.parentNode.palette.close();
  }
}

//open will create the divs for the palette if they don't already exist and will fetch the xml document
//from the server. The xml document will be passed to the redraw function.
function _palettes_open()
{
  if (!this.innerdiv) {
    this.innerdiv=document.createElement("DIV");
		this.parentobject.appendChild(this.innerdiv);
		if (this.className!='') { this.innerdiv.className = this.className; }
		if (this.id!='') { this.innerdiv.id = this.id; }
    this.innerdiv.palette=this;

    var stylingdiv;
    
    for (var sd=0; sd<this.stylingdivs; sd++) {
      stylingdiv=document.createElement("DIV");
		  this.innerdiv.appendChild(stylingdiv);
      stylingdiv.className="CMSStyling"+(sd+1);
    }

    this.contentdiv=document.createElement("DIV");
	  this.innerdiv.appendChild(this.contentdiv);
    this.contentdiv.className="CMSContent";

    stylingdiv=document.createElement("DIV");
	  this.innerdiv.appendChild(stylingdiv);
    stylingdiv.className="CMSClose";
    stylingdiv.onclick=palettes_close;

    this.captiondiv=document.createElement("DIV");
	  this.innerdiv.appendChild(this.captiondiv);
    this.captiondiv.className="CMSCaption";
    var text=document.createTextNode(this.caption);
    this.captiondiv.appendChild(text);
  }
  
  this.refreshcontent();
}

//remove the divs from the dom for this palette
function _palettes_close()
{
  this.innerdiv.parentNode.removeChild(this.innerdiv);
  this.innerdiv=null;
  this.contentdiv=null;
  this.captiondiv=null;
}

//fills the window with a serialization of the xml code downloaded
function _palettes_defaultredraw()
{
  if (this.mode == 'html' || this.mode == 'iframe') {
    this.contentdiv.innerHTML=this.responsetext;
  } else {
    if (this.xmlobj) {
      this.contentdiv.innerHTML="The XML is<br><br>"+xml_getXml(this.xmlobj).replace(/</g, '&lt;');
    } else {
      this.contentdiv.innerHTML="The XML Object is empty.";
    }
  }
}

function _palettes_refreshcontent()
{
  if (!this.servercomponent) { return; }
  
  this.xmlobj=xml_blockingDataGet(this.servercomponent);

  if (this.onredraw) { this.onredraw(); }
}

function _palettes_refreshhtmlcontent()
{
  if (!this.url) { return; }
  
  this.responsetext=html_blockingDataGet(this.url);

  if (this.onredraw) { this.onredraw(); }
}

function palettes_initialise()
{
}

//Initialisation
var _CMSOnloadList=new Array();

function CMSAddOnloadFunc(func) {
  _CMSOnloadList[_CMSOnloadList.length]=func;
}
function CMSOnloadHandler() {
  for (var i=0;i<_CMSOnloadList.length;i++) {
    var func=_CMSOnloadList[i];
    func();
  }
}

CMSAddOnloadFunc(externalLinks);
CMSAddOnloadFunc(palettes_initialise);

window.onload = CMSOnloadHandler;


//Code injection
function injectCSS(rules) {
    if (document.createStyleSheet) {
      var newss=document.createStyleSheet(); for (var i in rules) { newss.addRule(rules[i].rule, rules[i].style); };
    } else {
        if (document.styleSheets[0].addRule) {
          for (var i in rules) { document.styleSheets[0].addRule(rules[i].rule, rules[i].style) };
        } else {
          var style=''; for (var i in rules) { style+=rules[i].rule+' {'+rules[i].style+' } '};
          document.getElementsByTagName('head')[0].appendChild(document.createElement('style')).innerHTML=style;
        }
    }
}
