var EasyCMS_jsLibVersion = 199;
// To cover IE 5.0's lack of the push method
if(typeof Array.prototype.push != "function"){
  Array.prototype.push = ArrayPush;
  function ArrayPush(value){
    this[this.length] = value;
  }
}
// ---
/*
	ELO - Encapsulated Load Object, by Robert Nyman, http://www.robertnyman.com
	Inspired and influenced by Dean Edwards, Matthias Miller, and John Resig: http://dean.edwards.name/weblog/2006/06/again/
*/
var ELO = {
	loaded : false,
	timer : null,
	functionsToCallOnload : [], // Type in functions as strings here. e.g. "myFunction()"
	init : function (){
		if(ELO.loaded) return;
		ELO.loaded = true;
		ELO.load();
	},
	
	load : function (){
		if(this.timer){
			clearInterval(this.timer);
		}
		for(var i=0; i<this.functionsToCallOnload.length; i++){
			try{
				eval(this.functionsToCallOnload[i]);
			}
			catch(e){
				// Handle error here
			}
		}
	}
};
// ---
/* Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
	if(document.getElementById){
		document.write("<script id=\"ieScriptLoad\" defer src=\"//:\"><\/script>");
	    document.getElementById("ieScriptLoad").onreadystatechange = function() {
	        if (this.readyState == "complete") {
	            ELO.init();
	        }
	    };
	}
/*@end @*/
// ---
/* Mozilla/Opera 9 */
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", ELO.init, false);
}
// ---
/* Safari */
if(navigator.userAgent.search(/WebKit/i) != -1){
    ELO.timer = setInterval(function (){
		if(document.readyState.search(/loaded|complete/i) != -1) {
			ELO.init();
		}
	}, 10);
}
// ---
/* Other web browsers */
window.onload = ELO.init;
// ---
if(typeof Array.prototype.inArray != "function"){
  Array.prototype.inArray = function (value) {
    var i;
    for (i=0; i < this.length; i++) {
      if (this[i] === value) {
        return true;
      }
    }
    return false;
  }
}

function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}
	
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);function $(o) {
  if (typeof(o) == "string")
    return document.getElementById(o)
    else
    return o;
};
function applyStyleString (obj,str) {
  if(document.all && !window.opera) {
    obj.style.setAttribute("cssText",str);
  } else {
    obj.setAttribute("style",str);
  }
};
/* Function : getElementsByClassName Deluxe Edition
   Author    : http://muffinresearch.co.uk/archives/2006/04/29/getelementsbyclassname-deluxe-edition/ 
   */
function getElementsByClassName(strClass, strTag, objContElm) {
  strTag = strTag || "*";
  objContElm = objContElm || document;
  var objColl = (strTag == '*' && document.all) ? document.all : objContElm.getElementsByTagName(strTag);
  var arr = new Array();
  var delim = strClass.indexOf('|') != -1  ? '|' : ' ';
  var arrClass = strClass.split(delim);
  for (i = 0, j = objColl.length; i < j; i++) {
    var arrObjClass = objColl[i].className.split(' ');
    if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
    var c = 0;
    comparisonLoop:
    for (k = 0, l = arrObjClass.length; k < l; k++) {
      for (m = 0, n = arrClass.length; m < n; m++) {
        if (arrClass[m] == arrObjClass[k]) c++;
        if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
          arr.push(objColl[i]);
          break comparisonLoop;
        }
      }
    }
  }
  return arr;
}


/* Kim Steinhaug JS MM3 library for Easy CMS */
var swlib_doubleclick = { 
  sethighlight: function (){
    els = getElementsByClassName('highlight','table');
    for (var i=0; i<els.length; i++){
      swlib_doubleclick.highlight(els[i]);
    }
  },
  /* Use:
     table has class: highlight
     If TR has edit='url' it will be attached to all TDs without class 'noedit' as onclick
     Remember ELO init.
  */
  highlight: function (table){
    if (! table) { return; }
    var tbodies = table.getElementsByTagName("tbody");
    for (var h = 0; h < tbodies.length; h++) {
      var trs = tbodies[h].getElementsByTagName("tr");

      for (var i = 0; i < trs.length; i++){

        var EditSrc = trs[i].getAttribute('edit');
        if(typeof(EditSrc)=='string' && EditSrc.length){
          var tds = trs[i].getElementsByTagName("td");
          for (var j = 0; j <tds.length; j++){
            var TDClass = tds[j].getAttribute('class');
            if(TDClass != 'noedit'){
              tds[j].onclick = function(e){
                var EditSrc = $(this).up().getAttribute('edit');
                if(EditSrc.length){
                  location.href = EditSrc;
                }
              }
            }
          }

          trs[i].onmouseover= function(e){
            this.setAttribute('stylecache',this.getAttribute('style'));
            applyStyleString(this,'background-color: #eee;');
            this.className = 'highlight';
          };
          trs[i].onmouseout= function(e){
            applyStyleString(this,this.getAttribute('stylecache'));
            this.className = '';
          };
        }
      }
    }
  }
};
ELO.functionsToCallOnload.push("swlib_doubleclick.sethighlight()");



function setActiveStyleSheet(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;
     }
   }
}
function hideLayer(whichLayer) {
  if (document.getElementById) {
    // this is the way the standards work
    document.getElementById(whichLayer).style.display = "none";
  } else if (document.all) {
    // this is the way old msie versions work
    document.all[whichlayer].style.display = "none";
  } else if (document.layers) {
    // this is the way nn4 works
    document.layers[whichLayer].display = "none";
  }
}
function showLayer(whichLayer) {
  if (document.getElementById) {
    // this is the way the standards work
    document.getElementById(whichLayer).style.display = "block";
  } else if (document.all) {
    // this is the way old msie versions work
    document.all[whichlayer].style.display = "block";
  } else if (document.layers) {
    // this is the way nn4 works
    document.layers[whichLayer].display = "block";
  }
}

function sw_add (id) {
  thenumber = document.setting[id].value;
  thenumber = thenumber*(-1);
  thenumber = thenumber-1;
  thenumber = thenumber*(-1);
  document.setting[id].value = thenumber;
}
function sw_sub (id) {
  thenumber = document.setting[id].value;
  if(validateLOW(id,1)){
    thenumber = thenumber-1;
    document.setting[id].value = thenumber;
  }
}

	function chkData() {
		if(document.sw.usr.value <= 0)
			{alert("Skriv inn brukernavn");
			document.sw.usr.value = '';
			document.sw.usr.focus();
			return false;}
		if(document.sw.pas.value <= 0)
			{alert("Skriv inn passord");
			document.sw.pas.value = '';
			document.sw.pas.focus();
			return false;}
	}

function chkNewProduct(theform) {

	if(theform.levelaa.value <= 0){
		alert("Du må velge en kategori som varen skal plasseres i!");
		theform.levelaa.focus();
		return false;
		}

	if(theform.name.value <= 0){
		alert("Du må skrive inn navnet på varen du skal selge!");
		theform.name.focus();
		return false;
		}
	if (validateNRd(theform.price,"Innkjøpsprisen")) return false;
	if (validateNRd(theform.salesprice,"Utsalgsprisen")) return false;

    if(theform.more_info_not_for_sale.value != 1){
      if(theform.salesprice.value <= 0){
        alert("Du må skrive inn utsalgsprisen på varen du skal selge!");
        theform.salesprice.focus();
        return false;
      }
    }

	if(theform.description.value.length < 1){
		if (!confirm("Du har ikke beskrevet varen i kortbeskrivelsen?\n\nVil du lagre allikevel?")) {
		theform.description.focus();
		return false;
		}
	}

    if(typeof(tinyMCE) != 'undefined'){
      try {
        if(tinyMCE.getContent().length < 1){
          if (!confirm("Du har ikke beskrevet varen i hovedbeskrivelsen?\n\nVil du lagre allikevel?")) {
            return false;
          }
        }
      } catch(e) {
        // Multiple WYSIWYGs or disabled
      }
    } else {
      if(theform.descriptionbig.value.length < 1){
        if (!confirm("Du har ikke beskrevet varen i hovedbeskrivelsen?\n\nVil du lagre allikevel?")) {
          //theform.descriptionbig.focus();
          return false;
        }
      }
    }

	if (validateNRd(theform.stock,"Antall varer på lager"))
	return false;
	if (validateNRd(theform.lowstockvalue,"Lavt lagerantall"))
	return false;

	if (theform.usestockcontrol[0].checked == true){
		if(theform.stock.value <= 0){
			alert("Du må skrive inn antall varen du har på lager,\nfordi du har aktivert lagerstyring.");
			theform.stock.focus();
			return false;
			}
		if(theform.lowstockvalue.value <= 0){
			alert("Du må skrive inn lavt lagerantall.\nMed dette så menes hva du mener er\nlite varer igjen på lager.");
			theform.lowstockvalue.focus();
			return false;
			}
	}

// Finally
	if(theform.file1.value <= 0){
			if (confirm("Du har ikke valgt å legge med bilde,\nvil du fortsette uten bilde?")) {
				} else {
				theform.file1.focus();
				return false;
				}
		}

}
function chkNewProduct2(theform) {
	if(document.richedit.levelaa.value <= 0){
		alert("Du må velge en kategori som varen skal plasseres i!");
		document.richedit.levelaa.focus();
		return true;
		}
	if(document.richedit.name.value <= 0){
		alert("Du må skrive inn navnet på varen du skal selge!");
		document.richedit.name.focus();
		return true;
		}

	if (validateNRd(document.richedit.price,"Innkjøpsprisen")) return true;
	if (validateNRd(document.richedit.salesprice,"Utsalgsprisen")) return true;

	if(document.richedit.salesprice.value <= 0){
		alert("Du må skrive inn utsalgsprisen på varen du skal selge!");
		document.richedit.salesprice.focus();
		return true;
		}
	if(document.richedit.description.value.length < 1){
		if (!confirm("Du har ikke beskrevet varen i kortbeskrivelsen?\n\nVil du lagre allikevel?")) {
		document.richedit.description.focus();
		return true;
		}
	}

	if (validateNRd(document.richedit.stock,"Antall varer på lager"))
	return true;
	if (validateNRd(document.richedit.lowstockvalue,"Lavt lagerantall"))
	return true;

	if (document.richedit.usestockcontrol[0].checked == true){
		if(document.richedit.stock.value <= 0){
			alert("Du må skrive inn antall varen du har på lager,\nfordi du har aktivert lagerstyring.");
			document.richedit.stock.focus();
			return true;
			}
		if(document.richedit.lowstockvalue.value <= 0){
			alert("Du må skrive inn lavt lagerantall.\nMed dette så menes hva du mener er\nlite varer igjen på lager.");
			document.richedit.lowstockvalue.focus();
			return true;
			}
	}


// Finally
	if(document.richedit.file1.value <= 0){
			if (confirm("Du har ikke valgt å legge med bilde,\nvil du fortsette uten bilde?")) {
				} else {
				document.richedit.file1.focus();
				return true;
				}
		}

}
function chkNewProductUpdate(theform,catnum) {
  if(catnum<2){
    if(theform.levelaa.value <= 0){
      alert("Du må velge en kategori som varen skal plasseres i!");
      theform.levelaa.focus();
      return false;
    }
  }

  if(theform.name.value <= 0){
    alert("Du må skrive inn navnet på varen du skal selge!");
    theform.name.focus();
    return false;
  }

  if(theform.more_info_not_for_sale.value != 1){
    if (validateNRd(theform.price,"Innkjøpsprisen")) return false;
    if (validateNRd(theform.salesprice,"Utsalgsprisen")) return false;
    if(theform.salesprice.value <= 0){
      alert("Du må skrive inn utsalgsprisen på varen du skal selge!");
      theform.salesprice.focus();
      return false;
    }
  }

  if(theform.description.value.length < 1){
    if (!confirm("Du har ikke beskrevet varen i kortbeskrivelsen?\n\nVil du lagre allikevel?")) {
      theform.description.focus();
      return false;
    }
  }

    if(typeof(tinyMCE) != 'undefined'){
      try {
        if(tinyMCE.getContent().length < 1){
          if (!confirm("Du har ikke beskrevet varen i hovedbeskrivelsen?\n\nVil du lagre allikevel?")) {
            return false;
          }
        }
      } catch(e) {
        // Multiple WYSIWYGs or disabled
      }
    } else {
      if(theform.descriptionbig.value.length < 1){
        if (!confirm("Du har ikke beskrevet varen i hovedbeskrivelsen?\n\nVil du lagre allikevel?")) {
          //theform.descriptionbig.focus();
          return false;
        }
      }
    }

  if (validateNRd(theform.stock,"Antall varer på lager"))
    return false;
  if (validateNRd(theform.lowstockvalue,"Lavt lagerantall"))
    return false;

  if (theform.usestockcontrol[0].checked == true){
    if(theform.stock.value <= 0){
      if (confirm("Du har valgt lagerstyring og samtidig har du 0 varer på lager.\nOm dette er fordi du er utsolgt eller faktisk ikke har varer på\nlager velger du OK.\n\nOm du skal endre antall varer velg AVBRYT.\n\nNB!\nEn vare som står i 0 med lagerstyring vil ikke være synlig fra butikken!")) {
        // OK
      } else {
        theform.stock.focus();
        return false;
      }
    }
    if(theform.lowstockvalue.value <= 0){
      alert("Du må skrive inn lavt lagerantall.\nMed dette så menes hva du mener er\nlite varer igjen på lager.");
      theform.lowstockvalue.focus();
      return false;
    }
  }
  return true;
}

function chkNewProductUpdate2(catnum) {
  if(catnum<2){
    if(document.richedit.levelaa.value <= 0){
      alert("Du må velge en kategori som varen skal plasseres i!");
      document.richedit.levelaa.focus();
      return true;
    }
  }
  if(document.richedit.name.value <= 0){
    alert("Du må skrive inn navnet på varen du skal selge!");
    document.richedit.name.focus();
    return true;
  }
  if (validateNRd(document.richedit.price,"Innkjøpsprisen")) return true;
  if (validateNRd(document.richedit.salesprice,"Utsalgsprisen")) return true;
  if(document.richedit.salesprice.value <= 0){
    alert("Du må skrive inn utsalgsprisen på varen du skal selge!");
    document.richedit.salesprice.focus();
    return true;
  }
  if(document.richedit.description.value.length < 1){
    if (!confirm("Du har ikke beskrevet varen i kortbeskrivelsen?\n\nVil du lagre allikevel?")) {
      document.richedit.description.focus();
      return true;
    }
  }
  if (validateNRd(document.richedit.stock,"Antall varer på lager"))
    return true;
  if (validateNRd(document.richedit.lowstockvalue,"Lavt lagerantall"))
    return true;
  if (document.richedit.usestockcontrol[0].checked == true){
    if(document.richedit.stock.value <= 0){
      if (!confirm("Du har valgt lagerstyring og samtidig har du 0 varer på lager.\nOm dette er fordi du er utsolgt eller faktisk ikke har varer på\nlager velger du OK.\n\nOm du skal endre antall varer velg AVBRYT.\n\nNB!\nEn vare som står i 0 med lagerstyring vil ikke være synlig fra butikken!")) {
        document.richedit.stock.focus();
        return true;
      }
    }
    if(document.richedit.lowstockvalue.value <= 0){
      alert("Du må skrive inn lavt lagerantall.\nMed dette så menes hva du mener er\nlite varer igjen på lager.");
      document.richedit.lowstockvalue.focus();
      return true;
    }
  }
}
function chkUpload() {
	box = document.myXUploadForm.bildegruppe;
	temp = box.options[box.selectedIndex].value;
	if (temp) {

		if(document.myXUploadForm.bildegruppeny.value){
			alert("Du kan ikke både velge bilde kategori å lage ny bilde kategori, velg en av dem.");
			return false;
		}

	} else {
		if(!document.myXUploadForm.bildegruppeny.value)
		document.myXUploadForm.bildegruppeny.value = 'mine bilder'
	}


		if(document.myXUploadForm.file1.value <= 0){
			alert("Du må velge en bildefil før du kan fortsette.");
			document.myXUploadForm.file1.value = '';
			//document.myXUploadForm.file1.value.focus();
			return false;
		}



	}

function chkFileUpload() {
  box = document.myXUploadForm.filgruppe;
  temp = box.options[box.selectedIndex].value;
  if (temp) {
    if(document.myXUploadForm.filgruppeny.value){
      alert("Du kan ikke både velge fil kategori å lage ny fil kategori, velg en av dem.");
      return false;
    }
  } else {
    if(!document.myXUploadForm.filgruppeny.value)
    document.myXUploadForm.filgruppeny.value = 'mine filer'
  }
  if(document.myXUploadForm.file1.value <= 0){
    alert("Du må velge en fil før du kan fortsette.");
    document.myXUploadForm.file1.value = '';
    //document.myXUploadForm.file1.value.focus();
    return false;
  }
}

function validateig(){
	if(validate(document.setting.pimgsize_mainX.value,'Auto resize max dimensjon'))
	return false;
	if(document.setting.pimgsize_mainX.value > 1024){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha Auto resize max dimensjon høyere en 1024px.\n\nFeltet stilles ned til 1024px.");
		document.setting.pimgsize_mainX.focus();
		document.setting.pimgsize_mainX.value = '1024';
		return false;
 	}
	if(validate(document.setting.pimgsize_mainY.value,'Auto resize max dimensjon'))
	return false
	if(document.setting.pimgsize_mainY.value > 1024){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha auto resize max dimensjon bredere en 1024px.\n\nFeltet stilles ned til 1024px.");
		document.setting.pimgsize_mainY.value = '1024';
		document.setting.pimgsize_mainY.focus();
		return false;
 	}
	if(document.setting.pimgsize_mainX.value < 200){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha Auto resize max dimensjon lavere en 200px.\n\nFeltet stilles opp til 200px.");
		document.setting.pimgsize_mainX.focus();
		document.setting.pimgsize_mainX.value = '200';
		return false;
 	}
	if(document.setting.pimgsize_mainY.value < 200){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha auto resize max dimensjon smalere en 200px.\n\nFeltet stilles opp til 200px.");
		document.setting.pimgsize_mainY.value = '200';
		document.setting.pimgsize_mainY.focus();
		return false;
 	}
	if(validate(document.setting.pimgsize_thumbX.value,'Auto resize max thumbnail'))
	return false
	if(document.setting.pimgsize_thumbX.value > 300){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha thumbnail max dimensjon høyere en 300px.\n\nFeltet stilles ned til 300px.");
		document.setting.pimgsize_thumbX.focus();
		document.setting.pimgsize_thumbX.value = '300';
		return false;
 	}
	if(validate(document.setting.pimgsize_thumbY.value,'Auto resize max thumbnail'))
	return false
	if(document.setting.pimgsize_thumbY.value > 300){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha thumbnail max dimensjon bredere en 300px.\n\nFeltet stilles ned til 300px.");
		document.setting.pimgsize_thumbY.value = '300';
		document.setting.pimgsize_thumbY.focus();
		return false;
 	}
	if(document.setting.pimgsize_thumbX.value < 50){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha thumbnail max dimensjon lavere en 50px.\n\nFeltet stilles opp til 50px.");
		document.setting.pimgsize_thumbX.focus();
		document.setting.pimgsize_thumbX.value = '50';
		return false;
 	}
	if(document.setting.pimgsize_thumbY.value < 50){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha thumbnail max dimensjon smalere en 50px.\n\nFeltet stilles opp til 50px.");
		document.setting.pimgsize_thumbY.value = '50';
		document.setting.pimgsize_thumbY.focus();
		return false;
 	}
	if(validate(document.setting.pimgsize_systemX.value,'Auto resize max system'))
	return false
	if(document.setting.pimgsize_systemX.value > 175){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha system bildene høyere en 175px.\n\nFeltet stilles ned til 175px.");
		document.setting.pimgsize_systemX.focus();
		document.setting.pimgsize_systemX.value = '175';
		return false;
 	}
	if(validate(document.setting.pimgsize_systemY.value,'Auto resize max system'))
	return false
	if(document.setting.pimgsize_systemY.value > 175){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha system bildene bredere en 175px.\n\nFeltet stilles ned til 175px.");
		document.setting.pimgsize_systemY.value = '175';
		document.setting.pimgsize_systemY.focus();
		return false;
 	}
	if(document.setting.pimgsize_systemX.value < 64){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha system bildene lavere en 64px.\n\nFeltet stilles opp til 64px.");
		document.setting.pimgsize_systemX.focus();
		document.setting.pimgsize_systemX.value = '64';
		return false;
 	}
	if(document.setting.pimgsize_systemY.value < 64){
		alert("    --- BILDE OPPLASTNING ---\n\nDu får ikke lov å ha system bildene smalere en 64px.\n\nFeltet stilles opp til 64 px.");
		document.setting.pimgsize_systemY.value = '64';
		document.setting.pimgsize_systemY.focus();
		return false;
 	}
	if(validate(document.setting.richsize_defaultX.value,'Standard bredde artikkel full'))
	return false
	if(document.setting.richsize_defaultX.value > 1024){
		alert("    --- ARTIKKEL OG SIDE EDITOR ---\n\nDu får ikke lov å ha arbeidsfeltet bredere en 1024px.\n\nFeltet stilles ned til 1024px.");
		document.setting.richsize_defaultX.value = '1024';
		document.setting.richsize_defaultX.focus();
		return false;
 	}
	if(document.setting.richsize_defaultX.value < 300){
		alert("    --- ARTIKKEL OG SIDE EDITOR ---\n\nDu får ikke lov å ha arbeidsfeltet smalere en 300px.\n\nFeltet stilles ned til 300px.");
		document.setting.richsize_defaultX.value = '300';
		document.setting.richsize_defaultX.focus();
		return false;
 	}
	if(validate(document.setting.richsize_defaultY.value,'Standard høyde artikkel full'))
	return false
	if(document.setting.richsize_defaultY.value > 750){
		alert("    --- ARTIKKEL OG SIDE EDITOR ---\n\nDu får ikke lov å ha artikkel full feltet høyere en 750px.\n\nFeltet stilles ned til 750px.");
		document.setting.richsize_defaultY.value = '750';
		document.setting.richsize_defaultY.focus();
		return false;
 	}
	if(document.setting.richsize_defaultY.value < 100){
		alert("    --- ARTIKKEL OG SIDE EDITOR ---\n\nDu får ikke lov å ha artikkel full feltet lavere en 100px.\n\nFeltet stilles ned til 100px.");
		document.setting.richsize_defaultY.value = '100';
		document.setting.richsize_defaultY.focus();
		return false;
 	}
	if(validate(document.setting.richsize_ingress.value,'Standard høyde ingress'))
	return false
	if(document.setting.richsize_ingress.value > 300){
		alert("    --- ARTIKKEL OG SIDE EDITOR ---\n\nDu får ikke lov å ha ingress feltet høyere en 300px.\n\nFeltet stilles ned til 300px.");
		document.setting.richsize_ingress.value = '300';
		document.setting.richsize_ingress.focus();
		return false;
 	}
	if(document.setting.richsize_ingress.value < 25){
		alert("    --- ARTIKKEL OG SIDE EDITOR ---\n\nDu får ikke lov å ha ingress feltet lavere en 25px.\n\nFeltet stilles ned til 25px.");
		document.setting.richsize_ingress.value = '25';
		document.setting.richsize_ingress.focus();
		return false;
 	}
	if(validate(document.setting.richsize_extraX.value,'Utvidet bredde artikkel full'))
	return false
	if(document.setting.richsize_extraX.value > 1024){
		alert("    --- ARTIKKEL OG SIDE EDITOR ---\n\nDu får ikke lov å ha det ekstra arbeidsfeltet bredere en 1024px.\n\nFeltet stilles ned til 1024px.");
		document.setting.richsize_extraX.value = '1024';
		document.setting.richsize_extraX.focus();
		return false;
 	}
	if(document.setting.richsize_extraX.value < 300){
		alert("    --- ARTIKKEL OG SIDE EDITOR ---\n\nDu får ikke lov å ha det ekstra arbeidsfeltet smalere en 300px.\n\nFeltet stilles ned til 300px.");
		document.setting.richsize_extraX.value = '300';
		document.setting.richsize_extraX.focus();
		return false;
 	}
	if(validate(document.setting.richsize_extraY.value,'Utvidet høyde artikkel full'))
	return false
	if(document.setting.richsize_extraY.value > 750){
		alert("    --- ARTIKKEL OG SIDE EDITOR ---\n\nDu får ikke lov å ha det ekstra artikkel full feltet høyere en 750px.\n\nFeltet stilles ned til 750px.");
		document.setting.richsize_extraY.value = '750';
		document.setting.richsize_extraY.focus();
		return false;
 	}
	if(document.setting.richsize_extraY.value < 100){
		alert("    --- ARTIKKEL OG SIDE EDITOR ---\n\nDu får ikke lov å ha det ekstra artikkel full feltet lavere en 100px.\n\nFeltet stilles ned til 100px.");
		document.setting.richsize_extraY.value = '100';
		document.setting.richsize_extraY.focus();
		return false;
 	}
}

function validate(string,felt) {
  var valid="1234567890";
  for (var i=0; i<string.length; i++) {
    if (valid.indexOf(string.charAt(i)) < 0) {
      alert(felt+' inneholder ugyldige tegn!');
      return true;
    }
  }
  return false;
}
function validateNR(theform,felt) {
  var valid="1234567890.,-";
  string = theform.value;
  for (var i=0; i<string.length; i++) {
    if (valid.indexOf(string.charAt(i)) < 0) {
      alert(felt+' inneholder ugyldige tegn!');
      theform.value='';
      theform.focus();
      return false;
    }
  }
  return false;
}
function validateNRd(theform,felt) {
  var valid="1234567890.,-";
  string = theform.value;
  for (var i=0; i<string.length; i++) {
    if (valid.indexOf(string.charAt(i)) < 0) {
      alert(felt+' inneholder ugyldige tegn!');
      theform.value='';
      theform.focus();
      return false;
    }
  }
  return false;
}
function InstGenArt(mode){
  if(mode){
    document.setting.richsize_defaultX.value = '620';
    document.setting.richsize_ingress.value = '120';
    document.setting.richsize_defaultY.value = '300';
    document.setting.richsize_extraX.value = '750';
    document.setting.richsize_extraY.value = '500';
  } else {
    document.setting.pimgsize_mainX.value = '750';
    document.setting.pimgsize_mainY.value = '750';
    document.setting.pimgsize_thumbX.value = '120';
    document.setting.pimgsize_thumbY.value = '120';
    document.setting.pimgsize_systemX.value = '75';
    document.setting.pimgsize_systemY.value = '75';
  }
}

function validateLOW (id,range){
	if(document.setting[id].value <= range) {
		alert('Du må vise minnst 1 artikkel!');
		return false;
	} else {
		return true;
	}
}
function swPOP(url,Xvalue,Yvalue,scroll) {
	var w = 480, h = 340;if (document.all || document.layers) { w = screen.availWidth;h = screen.availHeight; }
	var popW = Xvalue, popH = Yvalue;var leftPos = (w-popW)/2, topPos = (h-popH)/2;
	if (scroll) { i = open(url, "displayWindow","top="+topPos+",left="+leftPos+",width="+Xvalue+",height="+Yvalue+",status=no,toolbar=1,menubar=no,resize=no,dependent=yes,scrollbars=yes");} else { i = open(url, "displayWindow","top="+topPos+",left="+leftPos+",width="+Xvalue+",height="+Yvalue+",status=1,toolbar=1,menubar=0,resize=no,dependent=yes,scrollbars=no");}
}

function zoom(header,alt,url,Xvalue,Yvalue,scroll) {
	Xvalue = Xvalue + 20;
	Yvalue = Yvalue + 60;
	if (scroll) {
        i = open("", "EUindow","top=50,left=50,width="+Xvalue+",height="+Yvalue+",status=no,toolbar=no,menubar=no,resize=no,dependent=yes,scrollbars=yes");
	}
	else {
        i = open("", "EUindow","top=50,left=50,width="+Xvalue+",height="+Yvalue+",status=no,toolbar=no,menubar=no,resize=no,dependent=yes,scrollbars=no");
	}
	i.focus();
        i.document.open();
        i.document.write('<html>\n')
        i.document.write('<head>\n')
        i.document.write('<title>EasyWebshop bilde forhåndsvisning</title>\n')
        i.document.write('<\head>\n')
        i.document.write('<body bgcolor="#ffffff" text="#000000">\n')
        i.document.write('<center>\n')
        i.document.write('<div style="font-size:14px; font-weight:bold; font-family:verdana,arial,sans-serif,helvetica;">',header,'</div><a href="javascript:window.close();"><img src="',url,'" border="2" style="border:2px solid white;" alt="',alt,'"></a>\n')
        i.document.write('<div style="font-size:10px;font-family:verdana;color:#808080;">&copy; EasyWebshop</div></center>\n')
        i.document.write('</body>\n')
        i.document.write('</html>\n');
        i.document.close();
}

function confirmRest(theform){
  eval("document." + theform + ".complete.value=1");
  //document.order.complete.value=1;
}
function confirmBack(theform){
  if (confirm("Er du sikker du vil tilbakeføre varene, og dermed fjerne dem fra ordren?")) {
    eval("document." + theform + ".complete.value=1");
  }
}
function confirmOrder(theform){
  if (confirm("Når du fullfører en ordre blir hele ordren fullført, uavhengig av hvilke varer som er valgt.\n\nSjekk derfor at du har generert rest ordre eller tilbakeført de ordre du ikke har på lager før\ndu fullfører.\n\nDenne operasjonen kan ikke tilkabeføres.\n\nVil du fullføre ordren?")) {
    eval("document." + theform + ".complete.value=1");
  }
}

function sumbitOrder(theform){
  if(theform.complete.value==1)
    return true;
    else
    return false;
}

function swap(url,name){
  if (document.images){
    eval('document.images.' + name + '.src="' + url + '"')
  }
}

/* BBS Epay funksjonalitet */

function bbsKapitaliserPoster(theform){
  if (confirm("Poster som er merket vil nå kapitaliseres, husk at om lampene på postene blir røde betyr dette at kapitaliseringen ikke var vellykket og du har derfor IKKE fått betalt!")) {
    eval("document." + theform + ".complete.value=1");
  }
}

// Usage showInfo(object.name);
function showInfo(_obj)
{
  var _HTML_START="<html><head><style>.s1{color:blue;}.s2{color:red;}.s3{color=green;}</style></head><body onunload='opener._win=null;' onload='self.focus()'><a href='javascript:self.close()'>close window</a><br><br>";
  var _HTML_END="</body></html>";
  var OBJ=eval(_obj);
  var I_set="Items Set:<br><pre>";
  var I_notSet="Items Not Set:<br><pre>";
  for(var item in OBJ)
  {
    var _value=eval("OBJ."+item);
	if(_value || parseInt(_value)==_value)
	{
	  var _regExp=/HTML/;
	  if(!_regExp.test(item))
        I_set+="<span class=s1>"+item+"</span><span class=s2>=</span><span class=s3>"+_value+"</span><br>";
	  else
	    I_set+="<span class=s1>"+item+"</span><span class=s2>=</span><span class=s3><b><i>-Set But Code Not Shown-</i></b></span><br>";
	}
	else
      I_notSet+="<span class=s1>"+item+"</span><br>";
  }
  I_set+="</pre>";
  I_notSet+="</pre>";

Stamp = new Date();
var Secs;
Secs = Stamp.getSeconds();

  //if(!_win)
  _win=window.open('',Secs);
  _win.document.open();
  _win.document.write(_HTML_START+"OBJECT <span class=s1>"+_obj+"</span><br><br>"+I_set+"<br><br><hr><br><br>"+I_notSet+_HTML_END);
  _win.document.close();
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *  XMLHttpRequestHeartBeat v1.0                                     *
 *  Simple system for giving a steady heartbeat to the webserver     *
 *  to avoid session timeout and loosing work on pages a user might  *
 *  spend a long time working on                                     *
 *                                                                   *
 *  Revised : 19 August 2005                                         *
 *  Author  : kim@steinhaug.com                                      *
 *                                                                   *
 *  Start :                                                          *
 *  XMLHttpRequestHeartBeatInit([int seconds]);                      *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function XMLHttpRequestHeartBeat(replacement,heartbeatUrl) {
  var currentTime = new Date();
  var req = new XMLHttpRequest();
  if (req) {
    req.onreadystatechange = function() {
      if (req.readyState == 4 && req.status == 200) {
         // To debug remove and add <div id="heartbeat"></div> somewhere on the page
         // document.getElementById(replacement).innerHTML = req.responseText;
      };
    };
    req.open('GET', heartbeatUrl + '?' + currentTime.getDay() + currentTime.getHours() + currentTime.getMinutes() + currentTime.getSeconds());
    req.send(null);
  }
}

function XMLHttpRequestHeartBeatInit(seconds){
  var heartbeatUrl = 'heartbeat.php';
  seconds = seconds * 1000;
  sw_heartbeat_alert = setTimeout('alert("SERVERPULS BLE IKKE AKTIVERT\\n\\nDet har nå gått 15 minutter og du vil snart (typisk om ca. 5-10 minutter) automatisk bli logget ut av serveren,\\nvi anbefaler deg lagre arbeidet ditt så langt å så velge å redigere siden på nytt.\\nDa har du en ny periode innen du automatisk blir logget ut.\\n\\nVi gjør også oppmerksom på at denne feilmeldingen dukker opp ettersom serverPuls ikke ble aktivert,\\nnoe som tyder på en feil med din installasjon av Easy CMS.\\n\\nTa kontakt med support for å løse dette problemet, så slipper du også denne meldingen.")',900000);
  var currentTime = new Date();
  var req = new XMLHttpRequest();
  if (req) {
    req.onreadystatechange = function() {
      if (req.readyState == 4 && req.status == 200) {
        if(req.responseText=='ready'){
          clearTimeout(sw_heartbeat_alert);
          sw_heartbeat = setInterval('XMLHttpRequestHeartBeat("heartbeat","' + heartbeatUrl + '")',seconds);
        };
      };
    };
    req.open('GET', heartbeatUrl + '?status=initialize&' + currentTime.getDay() + currentTime.getHours() + currentTime.getMinutes() + currentTime.getSeconds());
    req.send(null);
  }
}





var swlib = { 
  fixhref: function() {
    var elements = document.getElementsByTagName('a');
    var i;
    for ( i=0;i<elements.length;i++ ) {
      var re = new RegExp("#$");
      if (elements[i].getAttribute('href').match(re)) {
        elements[i].setAttribute('href','javascript:;');
      }
    }
  },
  setstripe: function (){
    els = getElementsByClassName('stripe','table');
    for (var i=0; i<els.length; i++){
      swlib.stripe(els[i]);
    }
  },
  hasClass: function (obj) {
     var result = false;
     if (obj.getAttributeNode("class") != null) {
         result = obj.getAttributeNode("class").value;
     }
     return result;
  },
  stripe: function (table) {
    // [1] - hex color or class name
    // [2] - hex color or class name
    var even = false;
    // if arguments are provided to specify the colours
    // of the even & odd rows, then use the them;
    // otherwise use the following defaults:
    var evenColor = arguments[1] ? arguments[1] : "#eff5fd";
    var oddColor = arguments[2] ? arguments[2] : "#dfecfd";

    if (! table) { return; }
    
    // by definition, tables can have more than one tbody
    // element, so we'll have to get the list of child
    // &lt;tbody&gt;s 
    var tbodies = table.getElementsByTagName("tbody");

    // and iterate through them...
    for (var h = 0; h < tbodies.length; h++) {
     // find all the &lt;tr&gt; elements... 
      var trs = tbodies[h].getElementsByTagName("tr");

      // ... and iterate through them
      for (var i = 0; i < trs.length; i++) {

        // avoid rows that have a class attribute
        // or backgroundColor style
//        if (! swlib.hasClass(trs[i]) &&
//            ! trs[i].style.backgroundColor) {
         if(! trs[i].style.backgroundColor) {

          // get all the cells in this row...
          var tds = trs[i].getElementsByTagName("td");
        
          // and iterate through them...
          for (var j = 0; j < tds.length; j++) {

            var mytd = tds[j];
            // avoid cells that have a class attribute
            // or backgroundColor style
//            if (! swlib.hasClass(mytd) &&
//                ! mytd.style.backgroundColor) {
            if (! mytd.style.backgroundColor) {

              var re = new RegExp("^\#"); if (evenColor.match(re)){
                mytd.style.backgroundColor =
                  even ? evenColor : oddColor;
              } else {
                swlib.addclass(mytd,even ? evenColor : oddColor);
              }

            }
          }
        }
        // flip from odd to even, or vice-versa
        even =  ! even;
      }
    }
  },
  addclass : function(el,cls) {
    swlib.removeclass(el,cls);
    var _classes = swlib.explode(' ', el.className);
    _classes[_classes.length] = cls;
    el.className = _classes.join(' ');
  },
  removeclass : function(el,cls) {
    var _classes = swlib.explode(' ', el.className);
    for (var i=0; i<_classes.length; i++) {
      if (_classes[i] == cls)
      _classes[i] = '';
    }
    el.className = _classes.join(' ');
  },
  explode : function(seperator, str) {
    var temp1 = str.split(seperator);
    var temp2 = new Array();
    for (var i = 0; i<temp1.length; i++) {
      if (temp1[i] != '')
      temp2[temp2.length] = temp1[i];
    }
    return temp2;
  }
};

function confirmDelete(title,uri){
  if (confirm('Er du sikker på at du vil slette ' + title + '?')){
    location.href=uri;
  }
}

function _wet(id){
  $(id).checked = true;
}
  var cookieNames = new Array();
  function Get_Cookie(name) { 
    var start = document.cookie.indexOf(name+"="); 
    var len = start+name.length+1; 
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
    if (start == -1) return null; 
    var end = document.cookie.indexOf(";",len); 
    if (end == -1) end = document.cookie.length; 
    return unescape(document.cookie.substring(len,end)); 
  } 
  function Set_Cookie(name,value,expires,path,domain,secure) { 
    expires = expires * 60*60*24*1000;
    var today = new Date();
    var expires_date = new Date( today.getTime() + (expires) );
    var cookieString = name + "=" +escape(value) + 
      ( (expires) ? ";expires=" + expires_date.toGMTString() : "") + 
      ( (path) ? ";path=" + path : "") + 
      ( (domain) ? ";domain=" + domain : "") + 
      ( (secure) ? ";secure" : ""); 
    document.cookie = cookieString; 
  }

/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Utf8 = {
 
	// public method for url encoding
	encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// public method for url decoding
	decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
         alert(utftext);

		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}


/**************************************************
 * dom-drag.js
 * 09.25.2001
 * www.youngpup.net
 **************************************************
 * 10.28.2001 - fixed minor bug where events
 * sometimes fired off the handle, not the root.
 **************************************************
 * 05.30.2005 - added a workaround for firefox
 * activating links when finished dragging.
 * mmosier@astrolabe.com
 **************************************************/

var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.startX		= x;
		o.startY		= y;
		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		if (o.linkDisabled) {
			var hrefs = o.root.getElementsByTagName("a");
			for (var i = 0; i < hrefs.length; i++) {
				hrefs[i].onclick = hrefs[i].prevOnclick;
				hrefs[i].prevOnclick = null;
			}
			o.linkDisabled = false;
		}

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		var threshold = 4;
		if (!o.linkDisabled) {
			if (Math.abs(nx - o.startX) > threshold || Math.abs(ny - o.startY) > threshold) {
				var hrefs = o.root.getElementsByTagName("a");
				for (var i = 0; i < hrefs.length; i++) {
					hrefs[i].prevOnclick = hrefs[i].onclick;
					hrefs[i].onclick = function() { return false; };
				}
				o.linkDisabled = true;
			}
		}

		Drag.obj.root.onDrag(nx, ny, Drag.obj.root);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
									parseInt(Drag.obj.root.style[Drag.obj.vmode
                                    ? "top" : "bottom"]), Drag.obj.root);
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};
// ----------------------------------------------------------------------------
// (c) Copyright, DTLink, LLC 1997-2005
//     http://www.dtlink.com
//
// DragList - Drag and Drop Ordered Lists
//
// Javascript Support file for formVista <draglist> fvml tag.
//
// For more information please see:
//
//    http://www.formvista.com/otherprojects/draglist.html
//
// For questions or comments please contact us at:
//
//     http://www.formvista.com/contact.html
//
// LICENSE: This file is governed by the new BSD license. For more information
// please see the LICENSE.txt file accompanying this package. 
//
// REVISION HISTORY:
//
// 2004-11-12 YmL:
//	.	initial revision.
//
// 2005-05-28 YmL:
//	.	pulled out of formVista, relicensed and packaged as a standalone implementation.
//
// 2005-06-02 mtmosier:
//	.	added horizontal dragging support.
//
// ------------------------

/**
* constructor for dragList class
*/

function fv_dragList( name )
	{

	// name of this dragList. Must match the id of the root DIV tag.

	this.dragListRootId = name;

	// array of item offsets

	this.offsetsX = new Array();
	this.offsetsY = new Array();

	}

// ----------------------------------------------

/**
* setup the draglist prior to use
*
* @param string orientation defaults to vert. if set to "horz" renders horizontally.
* @param string itemTagName. if null defaults to "div". Can be "span".
*/

fv_dragList.prototype.setup = function( orientation, itemTagName )
	{

	var horizontal;

	if ( orientation == "horz" )
		horizontal = true;
	else
		horizontal = false;

	this.listRoot = document.getElementById( this.dragListRootId );
	this.listItems = this.getListItems( itemTagName );

	for (var i = 0; i < this.listItems.length; i++) 
		{

		if ( this.listItems[i] == undefined )
			continue;

		if ( horizontal )
			{
			Drag.init(this.listItems[i], null, null, null, 0, 0);
			}
		else
			{
			Drag.init(this.listItems[i], null, 0, 0, null, null);
			}

		// ---------------------------------------------------
		// on drag method

		this.listItems[i].onDrag = function( x, y, thisElem ) 
			{

			x = thisElem.offsetLeft;
			y = thisElem.offsetTop;

			// this is a callback from the dom-drag code. From within this
			// function "this" does not refer to the fv_draglist function.

			draglist = getDragList( thisElem );

			draglist.recalcOffsets( itemTagName );

			var pos = draglist.getCurrentOffset( thisElem, itemTagName );

			//var listItems = this.getListItems( itemTagName );

			// if bottom edge is below top of lower item.

			var testMoveUp;
			var testMoveDown;
			if ( horizontal )
				{
				testMoveUp = (x + draglist.getDivWidth(thisElem) > draglist.offsetsX[pos + 1] + draglist.getDivWidth( draglist.listItems[pos + 1] ));
				testMoveDown = x < draglist.offsetsX[pos - 1];
				}
			else
				{
				testMoveUp = (y + draglist.getDivHeight(thisElem) > draglist.offsetsY[pos + 1] + draglist.getDivHeight( draglist.listItems[pos + 1] ));
				testMoveDown = y < draglist.offsetsY[pos - 1];
				}

			if (( pos != draglist.listItems.length - 1) && testMoveUp )
				{ 
				draglist.listRoot.removeChild(thisElem);

				if ( pos + 1 == draglist.listItems.length )
					{
					draglist.listRoot.appendChild( thisElem );
					}
				else
					{
					draglist.listRoot.insertBefore(thisElem, draglist.listItems[pos+1]);
					}

				thisElem.style["top"] = "0px";
				thisElem.style["left"] = "0px";
				}
			else if ( pos != 0 && testMoveDown ) 
				{ 
				draglist.listRoot.removeChild(thisElem);
				draglist.listRoot.insertBefore(thisElem, draglist.listItems[pos-1]);
				thisElem.style["top"] = "0px";
				thisElem.style["left"] = "0px";
				}

			};

		this.listItems[i].onDragEnd = function(x,y,thisElem) 
			{
			thisElem.style["top"] = "0px";
			thisElem.style["left"] = "0px";
			}

		}	// end of for loop.

	this.recalcOffsets( itemTagName );

	}	// end of setup.

// ----------------------------------------------


/**
* update the order value fields and submit the form.
*/

fv_dragList.prototype.do_submit = function( formName, dragListRootId )
	{

	var listOrderItems = this.listRoot.getElementsByTagName("input");

    var count = 0;
	for (var i = 0; i < listOrderItems.length; i++) 
		{

      if (!listOrderItems[i].name.match(/^items/)) { 
        listOrderItems[i].value = count;
        count++;
      }


		}

	expr = "document." + formName + ".submit()";

	eval( expr );
	}

// ----------------------------------------------
// "Private" methods.
// ----------------------------------------------

fv_dragList.prototype.recalcOffsets = function( itemTagName ) 
	{
	var listItems = this.getListItems( itemTagName );

	for (var i = 0; i < listItems.length; i++) 
		{
		this.offsetsX[i] = listItems[i].offsetLeft;
		this.offsetsY[i] = listItems[i].offsetTop;
		}
	}

fv_dragList.prototype.getCurrentOffset = function(elem, itemTagName) 
	{ 
	var listItems = this.getListItems( itemTagName );

	for (var i = 0; i < listItems.length; i++) 
		{
		if (listItems[i] == elem) 
			{ 
			return i;
			}
		}
	}

fv_dragList.prototype.getDivWidth = function(elem) 								  
	{

	if (( elem == undefined) || ( elem.offsetWidth == undefined ))
		return( 0 );

	value = elem.offsetWidth;
	if (isNaN(value))
		{
		value = 0;
		}

	return( value );
	}

fv_dragList.prototype.getDivHeight = function(elem) 
	{

	if (( elem == undefined) || ( elem.offsetHeight == undefined ))
		return( 0 );

	value = elem.offsetHeight;
	if (isNaN(value))
		{
		value = 25;
		}

	return( value );
	}

/**
* return list of draggable items
*/

fv_dragList.prototype.getListItems = function( itemTagName )
	{
	if ( itemTagName == undefined )
		{
		itemTagName = "div";
		}

	var listItems = this.listRoot.getElementsByTagName( itemTagName );

	return( listItems );
	}

// end of draglist class definition.

// -------------------------------------

/**
* add a new dragList to the list of draglists on this page
*
* This implementatoin supports multiple managed draglists on
* a single page. The index is contained in a global dragListIndex
* array that must be declared in the page.
*/

function addDragList( draglist )
	{
	dragListIndex[ draglist.dragListRootId ] = draglist;
	}

// -------------------------------------------------------

/**
* given a draggable div element, return the draglist it belongs to
*
* @see fv_draglist.prototype.setup
* @todo this should probably be a method inside the draglist class.
*/

function getDragList( elem )
	{

	// given a list item return the drag list it belongs to.

	var draglistContainer = elem.parentNode;

	var draglist = dragListIndex[ draglistContainer.id ];

	return( draglist );
	}

// END
// Constructor
function MCContextMenu() {
	this.isMSIE = navigator.appName == "Microsoft Internet Explorer";
	this.isGecko = navigator.userAgent.indexOf('Gecko') != -1;
	this.isSafari = navigator.userAgent.indexOf('Safari') != -1;
	this.isOpera = navigator.userAgent.indexOf("Opera") != -1;
	this.doc = document;
	this.win = window;
	this.items = new Array();
	this.settings = new Array();
	this.menuDiv = null;
	this.menuGenerated = false;
	this.counter = 0;
	this.oldItems = null;

    this.temp_x  = 0;
    this.temp_y  = 0;
    this.temp_dx = 0;
    this.temp_dy = 0;
}

// Methods
MCContextMenu.prototype = {
	init : function(settings) {
		this.settings = typeof(settings) == "undefined" ? new Array() : settings;

		this.defParam("contain_within_body", true);
		this.defParam("handle_iframe_events", true);
		this.defParam("add_before_attrib", "contextmenuaddbefore");
		this.defParam("add_after_attrib", "contextmenuaddafter");
		this.defParam("contextmenu_attrib", "contextmenu");
		this.defParam("ajax_attrib", "acm");
		this.defParam("replace_browser_menu", true);

//		this.addEvent(window, "load", MCContextMenu.prototype.onLoad);
        ELO.functionsToCallOnload.push("MCContextMenu.prototype.onLoad()");
	},

	onLoad : function() {
		mcContextMenu.registerEventListeners(document);

		if (mcContextMenu.getParam('handle_iframe_events')) {
			for (var i=0; i<window.frames.length; i++) {
				try {
					var doc = window.frames[i].document;
					doc.body.mcContextMenuBodyID = "mc" + mcContextMenu.counter++;
					mcContextMenu.registerEventListeners(doc);
				} catch (ex) {
					// May throw security exception
				}
			}
		}
	},

	registerEventListeners : function(doc) {
		this.addEvent(doc, "contextmenu", mcContextMenu.showEvent);
		this.addEvent(doc, "click", mcContextMenu.hideEvent);
		this.addEvent(doc, "keypress", mcContextMenu.hideEvent);
	},

	showEvent : function(e) {
		e = typeof(e) == "undefined" ? window.event : e;
		var elm = e.srcElement ? e.srcElement : e.target;
		var body = mcContextMenu.getBody(elm);
		var lnk = mcContextMenu.getParentElement(elm, 'A');
        if(!lnk){
          var lnk = mcContextMenu.getParentElement(elm, 'IMG');
        }
		var x, y, dx = 0, dy = 0;
		var modified = false;

		// Restore default menu
		if (mcContextMenu.oldItems) {
			mcContextMenu.menuGenerated = false;
			mcContextMenu.items = mcContextMenu.cloneArray(mcContextMenu.oldItems);
			mcContextMenu.oldItems = null;
		}

		if (lnk) {
			var before = lnk.getAttribute(mcContextMenu.getParam('add_before_attrib'));
			var after = lnk.getAttribute(mcContextMenu.getParam('add_after_attrib'));
			var replace = lnk.getAttribute(mcContextMenu.getParam('contextmenu_attrib'));

            var acm = lnk.getAttribute(mcContextMenu.getParam('ajax_attrib'));  // Pick the new system
            if (acm && acm != "") {                                             // If we infact have any data
              mcContextMenu.showEventAjaxMode(e);                               // we cancel this and execute the
              return true;                                                      // new Ajax-system.
            }

			mcContextMenu.oldItems = mcContextMenu.cloneArray(mcContextMenu.items);

			if (after && after != "") {
				var ar = mcContextMenu.explode(';', mcContextMenu.escapeCM(after));

				for (var i=0; i<ar.length; i++)
					mcContextMenu.addItem(ar[i]);

				modified = true;
			}

			if (before && before != "") {
				var ar = mcContextMenu.explode(';', mcContextMenu.escapeCM(before));

				for (var i=ar.length-1; i>=0; i--)
					mcContextMenu.addItemAtBeginning(ar[i]);

				modified = true;
			}

			if (replace && replace != "") {
				mcContextMenu.clear();

				var ar = mcContextMenu.explode(';', mcContextMenu.escapeCM(replace));

				for (var i=0; i<ar.length; i++)
					mcContextMenu.addItem(ar[i]);

				modified = true;
			}
		}

		if (!mcContextMenu.getParam("replace_browser_menu") && !modified) {
			mcContextMenu.hide();
			return true;
		}

		if (mcContextMenu.isMSIE) {
			dx = body.scrollLeft;
			dy = body.scrollTop;
		}

		if (body.mcContextMenuBodyID) {
			var iframe = mcContextMenu.getIFrameElement(body.mcContextMenuBodyID);
			var pos = mcContextMenu.getAbsPosition(iframe);
			dx = pos.absLeft;
			dy = pos.absTop;

			if (!mcContextMenu.isMSIE) {
				dx -= body.scrollLeft;
				dy -= body.scrollTop;
			}
		}

		if (mcContextMenu.isMSIE) {
			x = e.clientX;
			y = e.clientY;
		} else {
			x = e.pageX;
			y = e.pageY;
		}

		x += dx;
		y += dy;

		// Range check
		x = x < 0 ? 0 : x;
		y = y < 0 ? 0 : y;

		// Show menu
		if (mcContextMenu.getParam("replace_browser_menu") || mcContextMenu.items.length > 0) {
			mcContextMenu.show(x, y);
			mcContextMenu.cancelEvent(e);
			return false;
		} else
			mcContextMenu.hide();

		return true;
	},

	showEventAjaxMode : function(e) {
		e = typeof(e) == "undefined" ? window.event : e;
		var elm = e.srcElement ? e.srcElement : e.target;
		var body = mcContextMenu.getBody(elm);
		var lnk = mcContextMenu.getParentElement(elm, 'A');
        if(!lnk){
          var lnk = mcContextMenu.getParentElement(elm, 'IMG');
        }
		var x, y, dx = 0, dy = 0;
		var modified = false;

		// Restore default menu
		if (mcContextMenu.oldItems) {
			mcContextMenu.menuGenerated = false;
			mcContextMenu.items = mcContextMenu.cloneArray(mcContextMenu.oldItems);
			mcContextMenu.oldItems = null;
		}
		if (lnk) {
            var acm = lnk.getAttribute(mcContextMenu.getParam('ajax_attrib'));              // Pick the new system
            mcContextMenu.oldItems = mcContextMenu.cloneArray(mcContextMenu.items);
			if (acm && acm != "") {
				mcContextMenu.clear();
                var ar = mcContextMenu.escapeCM(acm);
                var req = new XMLHttpRequest(); 
                if (req) { 
                  req.onreadystatechange = function() {
                    if (req.readyState == 4 && req.status == 200) { 
                      if (req.status && req.status != "" && req.status != 'no data!') {
                        mcContextMenu.showEventAjaxModeShow(e,req.responseText);
                      }
                    } 
                  }
                  var currentTime = new Date();
                  if (ar && ar != "") {
                    var modified = true;
                    mcContextMenu.cancelEvent(e);  // Cancel the real context menu
                  }
                  if (!mcContextMenu.getParam("replace_browser_menu") && !modified) {
                    mcContextMenu.hide();
                    return true;
                  }
                  if (mcContextMenu.isMSIE) {
                    dx = body.scrollLeft;
                    dy = body.scrollTop;
                  }
                  if (body.mcContextMenuBodyID) {
                    var iframe = mcContextMenu.getIFrameElement(body.mcContextMenuBodyID);
                    var pos = mcContextMenu.getAbsPosition(iframe);
                    dx = pos.absLeft;
                    dy = pos.absTop;
                    if (!mcContextMenu.isMSIE) {
                      dx -= body.scrollLeft;
                      dy -= body.scrollTop;
                    }
                  }
                  if (mcContextMenu.isMSIE) {
                    x = e.clientX;
                    y = e.clientY;
                  } else {
                    x = e.pageX;
                    y = e.pageY;
                  }
                  x += dx;
                  y += dy;
                  // Range check
                  x = x < 0 ? 0 : x;
                  y = y < 0 ? 0 : y;
                  mcContextMenu.ajax_x  = x;  // Store data
                  mcContextMenu.ajax_y  = y;  // Store data
                  mcContextMenu.ajax_dx = dx; // Store data
                  mcContextMenu.ajax_dy = dy; // Store data
                  req.open('GET', 'func.context-menu.php?data=' + ar + '&' + currentTime.getDay() + currentTime.getHours() + currentTime.getMinutes() + currentTime.getSeconds()); 
                  req.send(null);
                } else {
                  // Error, output dummy menu
                  // Trigger contextmenu without nothing
                }
			}
		} // if lnk end
	},
	showEventAjaxModeShow : function(e,val) {
// Debug 
//document.forms.test.trigger.value = val;

		e = typeof(e) == "undefined" ? window.event : e;
		var elm = e.srcElement ? e.srcElement : e.target;
		var body = mcContextMenu.getBody(elm);

        var x = mcContextMenu.ajax_x;
        var y = mcContextMenu.ajax_y;
        var dx = mcContextMenu.ajax_dx;
        var dy = mcContextMenu.ajax_dy;

        var modified = true;
		var ar = mcContextMenu.explode(';', mcContextMenu.escapeCM(val));
		for (var i=0; i<ar.length; i++)
    		mcContextMenu.addItem(ar[i]);

		// Show menu
		if (mcContextMenu.getParam("replace_browser_menu") || mcContextMenu.items.length > 0) {
			mcContextMenu.show(x, y);
			return false;
		} else
			mcContextMenu.hide();

		return true;
	},

	hideEvent : function(e) {
		mcContextMenu.hide();
		return true;
	},

	show : function(x, y) {
        // Latest Dustin Diaz Sweet Tiles
    	var sweetTitles = document.getElementById('toolTip');
		if ( sweetTitles ) {
          sweetTitles.style.visibility = 'hidden';
        }
		// Create menu div
		if (this.menuDiv == null) {
			// Add iframe
			if (this.isMSIE) {
				this.iframe = this.doc.createElement("iframe");
				this.iframe.src = "javascript:void(0);";
				this.iframe.className = "mcContextMenuIFrame";
				this.iframe.frameBorder = "0";
				this.iframe.style.display = "none";
				this.doc.body.appendChild(this.iframe);
			}

			this.menuDiv = this.doc.createElement("div");
			this.menuDiv.className = "mcContextMenuContainer";
			this.doc.body.appendChild(this.menuDiv);
		}

		// Fill menu with items
		if (!this.menuGenerated) {
			var html = "";
			var anyIcons = false;

            // Sprite is counted as Icon aswell
			for (var i=0; i<this.items.length; i++) {
				if (this.items[i].icon)
					anyIcons = true;
				if (this.items[i].sprite)
					anyIcons = true;
			}

            html += '<div class="mcContextMenuInnerContainer">';
			html += '<table border="0" cellpadding="0" cellspacing="0" class="mcContextMenu ' + (anyIcons ? '' : 'NoImagePadding') + '">';

			for (var i=0; i<this.items.length; i++) {
				var item = this.items[i];
				var cls = "";

				cls += " " + (item.class_name ? item.class_name : "");
				cls += " " + (item.disabled ? "mcContextMenuItemDisabled" : "");

				html += '<tr';

				if (item.title == '--') {
					html += '><td class="mcContextMenuSeparator" nowrap="nowrap"' + (anyIcons ? 'colspan="2"' : '') + ' align="center"><div></div></td>';

                    if(item.header){
                      html += '</tr>';
                      html += '<tr><td colspan="2" class="mcContextMenu-header">' + item.header + '</td>';
                    }

				} else {
					html += ' onmouseover="mcContextMenu.addCSSClass(this,\'mcContextMenuItemOver\');"';
					html += ' onmouseout="mcContextMenu.removeCSSClass(this,\'mcContextMenuItemOver\');">';

					if (anyIcons) {
						html += '<td class="mcContextMenuItem' + cls + '" nowrap="nowrap"';
/* Added Kim */
					if (item.url && !item.disabled)
						html += ' onmouseup="document.location=\'' + this.jsEncode(item.url) + '\';"';

						html += '>';

						if (item.sprite)
							html += '<div class="cmCSS cm' + item.sprite + '"></div>';
						else if (item.icon)
							html += '<img src="' + item.icon + '" width="16" height="16" class="mcContextMenuImage" />';
						else
							html += '&nbsp;';

						html += '</td>';
					}

					if (item.disabled){
						html += '<td class="mcContextMenuItem' + cls + '" nowrap="nowrap"';
						html += ' onmouseover="mcContextMenu.addCSSClass(this,\'mcContextMenuItemOverDisabled\');"';
						html += ' onmouseout="mcContextMenu.removeCSSClass(this,\'mcContextMenuItemOverDisabled\');"';
					} else {
/*
						html += '<td class="mcContextMenuItem' + cls + '" nowrap="nowrap"';
						html += ' onmouseover="mcContextMenu.addCSSClass(this,\'mcContextMenuItemOver\');"';
						html += ' onmouseout="mcContextMenu.removeCSSClass(this,\'mcContextMenuItemOver\');"';
*/
						html += '<td ';
					}

// Fires extra event in IE and indeed launches the URL twice which is bad 
					if (item.url && !item.disabled)
						html += ' onmouseup="document.location=\'' + this.jsEncode(item.url) + '\';"';
					if (item.js && !item.disabled)
						html += ' onmouseup="' + item.js + '"';




					html += '>';

					if (item.disabled)
						html += '<span class="mcContextMenuItemText">' + this.xmlEncode(item.title) + '<span>' + this.xmlEncode(item.title) + '</span></span>';
					else
						html += '<span class="mcContextMenuItemText">' + this.xmlEncode(item.title) + '</span>';

//						html += '<a class="mcContextMenuItemText" href="' + this.xmlEncode(item.url) + '" onclick="return false;" onmousedown="return false;">' + this.xmlEncode(item.title) + '</a>';

					html += '</td>';
				}

				html += '</tr>';
            }

            html += "</table>";
            html += "</div>";
            
			this.menuDiv.innerHTML = html;
// Debug 
// document.forms.test.html.value = html;

			this.menuGenerated = true;
        }

        // Measure it
        this.menuDiv.style.left = "-1000px";
        this.menuDiv.style.top = "-1000px";
        this.menuDiv.style.display = 'block';
        width = this.menuDiv.offsetWidth;
        height = this.menuDiv.offsetHeight;

        // Get max x, y
        if (this.getParam("contain_within_body")) {
            var x2 = this.doc.body.scrollLeft + this.doc.body.clientWidth;
            var y2 = this.doc.body.scrollTop + this.doc.body.clientHeight;

            // Move it inside view port
            x = x + width > x2 ? x2 - width : x;
            y = y + height > y2 ? y2 - height : y;

          // Kim HACK to fix IE when window is scrolled
          if (this.isMSIE){
            var y2 = this.doc.body.clientHeight;
            if (document.documentElement && !document.documentElement.scrollTop)
              topoffset = document.documentElement.scrollTop;
              else if (document.documentElement && document.documentElement.scrollTop)
              topoffset = document.documentElement.scrollTop;
              else if (document.body && document.body.scrollTop)
              topoffset = document.body.scrollTop
            var y2 = this.doc.body.clientHeight;
			y = y + height > y2 ? y2 - height : y;
            y = y + topoffset;
          }

        }

        // Range check
        x = x < 0 ? 0 : x;
        y = y < 0 ? 0 : y;

        // Make it visible
        this.menuDiv.style.left = x + "px";
        this.menuDiv.style.top = y + "px";

        if (this.isMSIE) {
            this.iframe.style.left = x + "px";
            this.iframe.style.top = y + "px";
            this.iframe.style.width = width + "px";
            this.iframe.style.height = height + "px";
            this.iframe.style.display = "block";
        }
	},

	hide : function() {
		if (this.menuDiv != null)
			this.menuDiv.style.display = 'none';

		if (this.iframe != null)
			this.iframe.style.display = 'none';
	},

	clear : function() {
		this.items = new Array();
		this.menuGenerated = false;
	},

	addItemAtBeginning : function(s) {
		this.addItem(s, true);
	},

	addItem : function(s, infront) {
		if (infront)
			this.items.unshift(this.parseItem(s));
		else
			this.items[this.items.length] = this.parseItem(s);

		this.menuGenerated = false;
	},

	addSeparator : function() {
		this.addItem('--:--');
		this.menuGenerated = false;
	},

	getParam : function(name, default_value, type) {
		var value = typeof(this.settings[name]) == "undefined" ? default_value : this.settings[name];
		var type = typeof(type) == "undefined" ? "string" : type;

		if (value == "true" || value == "false")
			return value == "true";

		return value;
	},

	defParam : function(k, v) {
		this.settings[k] = this.getParam(k, v);
	},

	addEvent : function(obj, name, handler) {
		if (typeof(obj.attachEvent) != "undefined")
			obj.attachEvent("on" + name, handler);
		else
			obj.addEventListener(name, handler, false);
	},

	cancelEvent : function(e) {
		if (typeof(e.preventDefault) != "undefined") {
			e.preventDefault();
			return;
		}

		e.returnValue = false;
		e.cancelBubble = true;
	},

	getAbsPosition : function(node) {
		var p = {absLeft : 0, absTop : 0};
		var pn = node;

		while (pn) {
			p.absLeft += pn.offsetLeft;
			p.absTop += pn.offsetTop;
			pn = pn.offsetParent;
		}

		return p;
	},

	trim : function(s) {
		return s.replace(/^\s*|\s*$/g, "");
	},

	xmlEncode : function(s) {
		s = s.replace(/&/g, '&amp;');
		s = s.replace(/\"/g, '&quot;');
		s = s.replace(/</g, '&lt;');
		s = s.replace(/>/g, '&gr;');
		return s;
	},

	jsEncode : function(s) {
		s = s.replace(new RegExp('"', 'g'), '\\"');
		s = s.replace(new RegExp("'", 'g'), "\\'");
		return s;
	},

	getBody : function(e) {
		if (e == null)
			return null;

		if (e.nodeName == "HTML")
			return e.getElementsByTagName("BODY")[0];

		return this.getParentElement(e, "BODY");
	},

	getParentElement : function(e, name) {
		var p = e;
		do {
			if (p.nodeName == name)
				return p;
		} while (p = p.parentNode);

		return null;
	},

	getIFrameElement : function(id) {
		var n = document.getElementsByTagName("iframe");
		for (var i=0; i<n.length; i++) {
			if (n[i].contentWindow.document.body.mcContextMenuBodyID == id)
				return n[i];
		}

		return null;
	},

	addCSSClass : function(elm, cls) {
		this.removeCSSClass(elm, cls);
		var ar = this.explode(' ', elm.className);
		ar[ar.length] = cls;
		elm.className = ar.join(' ');
	},

	removeCSSClass : function(elm, cls) {
		var ar = this.explode(' ', elm.className);

		for (var i=0; i<ar.length; i++) {
			if (ar[i] == cls)
				ar[i] = '';
		}

		elm.className = ar.join(' ');
	},

    validateSpacer : function(s) {
      /* Added by Kim Steinhaug
         Extends the devider    */
      if(s.search(new RegExp("^--:","gi"))>=0)
        return true;
      else if(s == '--'){
        return true;
      } else {
        return false;
      }
    },

	parseItem : function(s) {
		s = this.escapeCM(s);
        if (!this.validateSpacer(this.trim(s))) {
            var ar = new RegExp('^\\s*?(.*?)\\s*?:', 'gi').exec(s);  // Corrected after email from Johan 
			// var ar = new RegExp('^\s*?(.*?)\s*?:', 'gi').exec(s); // Gives error 
			var title = ar != null && ar.length == 2 ? ar[1] : "";
		} else {
			title = '--';
        }

		var otitle = this.parseOption(s, 'title');

		return {
			title : otitle == "" ? title : otitle,
			url : this.parseOption(s, 'url'),
			js : this.parseOption(s, 'js'),
			header : this.parseOption(s, 'header'), // New one!
			icon : this.parseOption(s, 'icon'),
            sprite : this.parseOption(s, 'sprite'),
			class_name : this.parseOption(s, 'class'),
			disabled : s.indexOf('disabled') != -1
		};
	},

	parseOption : function(s, n) {
		var ar = new RegExp(n + '\\(\'(.*?)\'\\)', 'gi').exec(s);
		return ar != null && ar.length == 2 ? this.unescapeCM(ar[1]) : '';
	},

	escapeCM : function(s) {
		s = s.replace(new RegExp("''", 'gi'), '<<dquot>>');
		s = s.replace(new RegExp(";;", 'gi'), '<<scolon>>');

		return s;
	},

	unescapeCM : function(s) {
		s = s.replace(/<<dquot>>/gi, "'");
		s = s.replace(/<<scolon>>/gi, ";");

		return s;
	},

	explode : function(d, s) {
		var ar = s.split(d);
		var oar = new Array();

		for (var i = 0; i<ar.length; i++) {
			if (ar[i] != "")
				oar[oar.length] = ar[i];
		}

		return oar;
	},

	cleanArray : function(ar) {
		for (var k in ar)
			ar[k] = null;
	},

	cloneArray : function(ar) {
		var oar = new Array();

		this.cleanArray(oar);

		for (var k in ar)
			oar[k] = ar[k];

		for (var i=0; i<ar.length; i++)
			oar[i] = ar[i];

		return oar;
	}
};
// Setup context menu
mcContextMenu = new MCContextMenu();
mcContextMenu.init({
	replace_browser_menu : false
});

// Setup default menu
mcContextMenu.addItem("Switch menu:url('http://www.somesite.com');");
mcContextMenu.addSeparator();
mcContextMenu.addItem("Cut:url('javascript:alert(''Cut'');') icon('images/cut.gif')");
mcContextMenu.addItem("Copy:url('http://www.somesite.com') icon('images/copy.gif");
mcContextMenu.addItem("Paste:url('http://www.somesite.com') icon('images/paste.gif') disabled");
/*
Sweet Titles (c) Creative Commons 2005
http://creativecommons.org/licenses/by-sa/2.5/
Author: Dustin Diaz | http://www.dustindiaz.com
*/
var sweetTitles = { 
	xCord : 0,								// @Number: x pixel value of current cursor position
	yCord : 0,								// @Number: y pixel value of current cursor position
	tipElements : ['a','img'],                    // @Array: Allowable elements that can have the toolTip, default : 'a','abbr','acronym'
	obj : Object,							// @Element: That of which you're hovering over
	tip : Object,							// @Element: The actual toolTip itself
	active : 0,								// @Number: 0: Not Active || 1: Active
    fadespeed : 40,                         // default : 10, amount of opacity increase
	init : function() {
		if ( !document.getElementById ||
			!document.createElement ||
			!document.getElementsByTagName ) {
			return;
		}
		var i,j;
		this.tip = document.createElement('div');
		this.tip.id = 'toolTip';
		document.getElementsByTagName('body')[0].appendChild(this.tip);
		this.tip.style.top = '0';
		this.tip.style.visibility = 'hidden';
		var tipLen = this.tipElements.length;
		for ( i=0; i<tipLen; i++ ) {
			var current = document.getElementsByTagName(this.tipElements[i]);
			var curLen = current.length;
			for ( j=0; j<curLen; j++ ) {

              // Only attach tooltips on A with IMG inside
              if(current[j].firstChild != null){
                var img = current[j].firstChild;
                if(img.nodeName=='IMG'){
                  if(img.alt){
                    addEvent(current[j],'mouseover',this.tipOver);
                    addEvent(current[j],'mouseout',this.tipOut);
//                    current[j].setAttribute('tip',current[j].title);
//                    current[j].removeAttribute('title');
                    current[j].setAttribute('tip',img.alt);
                    img.removeAttribute('alt');
                    current[j].removeAttribute('title');
                  }
                }
              // Add support for single images if enabled!
              } else if( (current[j].nodeName=='IMG') && this.tipElements.inArray('img') ){
                  if(current[j].alt){
                    addEvent(current[j],'mouseover',this.tipOver);
                    addEvent(current[j],'mouseout',this.tipOut);
                    current[j].setAttribute('tip',current[j].alt);
                    current[j].removeAttribute('alt');
                    current[j].removeAttribute('title');
                  }
              }

			}
		}
	},
	updateXY : function(e) {
		if ( document.captureEvents ) {
			sweetTitles.xCord = e.pageX;
			sweetTitles.yCord = e.pageY;
		} else if ( window.event.clientX ) {
            xoffset = -20;
            yoffset = 0;
			sweetTitles.xCord = window.event.clientX+document.documentElement.scrollLeft + xoffset;
			sweetTitles.yCord = window.event.clientY+document.documentElement.scrollTop + yoffset;
		}
	},
	tipOut: function() {
		if ( window.tID ) {
			clearTimeout(tID);
		}
		if ( window.opacityID ) {
			clearTimeout(opacityID);
		}
		sweetTitles.tip.style.visibility = 'hidden';
	},
	checkNode : function() {
		var trueObj = this.obj;
		if ( this.tipElements.inArray(trueObj.nodeName.toLowerCase()) ) {
			return trueObj;
		} else {
			return trueObj.parentNode;
		}
	},
	tipOver : function(e) {
		sweetTitles.obj = this;
		tID = window.setTimeout("sweetTitles.tipShow()",500);
		sweetTitles.updateXY(e);
	},
	tipShow : function() {		
		var scrX = Number(this.xCord);
		var scrY = Number(this.yCord);
		var tp = parseInt(scrY+15);
		var lt = parseInt(scrX+10);
		var anch = this.checkNode();
//		var addy = '';
//		var access = '';
//		if ( anch.nodeName.toLowerCase() == 'a' ) {
//			addy = (anch.href.length > 25 ? anch.href.toString().substring(0,25)+"..." : anch.href);
//			var access = ( anch.accessKey ? ' <span>['+anch.accessKey+']</span> ' : '' );
//		} else {
//			addy = anch.firstChild.nodeValue;
//		}
//		this.tip.innerHTML = "<p>"+anch.getAttribute('tip')+"<em>"+access+addy+"</em></p>";

// Trimm down http://mysite.no/this to /this
//if ( anch.nodeName.toLowerCase() == 'a' ) {
//	var host = location.hostname.toString();
//	var pattern = new RegExp("(http://?)"+host,"gi");
//	var fullPath = anch.href.toString();
//	var path = fullPath.replace(pattern,'');
//	addy = (path.length > 25 ? path.toString().substring(0,25)+"..." : path);
//	var access = ( anch.accessKey ? " ["+anch.accessKey+"]" : "" );
//}

		this.tip.innerHTML = "<p>"+anch.getAttribute('tip')+"</p>";
		if ( parseInt(document.documentElement.clientWidth+document.documentElement.scrollLeft) < parseInt(this.tip.offsetWidth+lt) ) {
			this.tip.style.left = parseInt(lt-(this.tip.offsetWidth+10))+'px';
		} else {
			this.tip.style.left = lt+'px';
		}
		if ( parseInt(document.documentElement.clientHeight+document.documentElement.scrollTop) < parseInt(this.tip.offsetHeight+tp) ) {
			this.tip.style.top = parseInt(tp-(this.tip.offsetHeight+10))+'px';
		} else {
			this.tip.style.top = tp+'px';
		}
		this.tip.style.visibility = 'visible';
		this.tip.style.opacity = '.1';
		this.tipFade(10);
	},
	tipFade: function(opac) {
		var passed = parseInt(opac);
		var newOpac = parseInt(passed+this.fadespeed);
		if ( newOpac < 80 ) {
			this.tip.style.opacity = '.'+newOpac;
			this.tip.style.filter = "alpha(opacity:"+newOpac+")";
			opacityID = window.setTimeout("sweetTitles.tipFade('"+newOpac+"')",20);
		}
		else { 
			this.tip.style.opacity = '.80';
			this.tip.style.filter = "alpha(opacity:80)";
		}
	}
};
ELO.functionsToCallOnload.push("sweetTitles.init()");

    // 
    // This High Precision Calculator is (c) 2003 by Edward Martin III
    // All rights reserved.  Please contact me for permission to use any or
    // all of this source in a commercial product.
    // Eventually, it'll have all sorts of neat functions, but for now, its 
    // primary function is to not crash a browser.  And whatever's below:
    // 
    // MODIFICATION HISTORY
    //
    // wishlist:   
    //             How can I get some kind of real progress indicator?!
    //             Euler's Totient function
    //             export to an HTML file
    //             fix browser-related routine in Multiply
    //
    // 03-28-2003: Fixed a damn bug in the Multiplication function.  
    //             Eduard Martos Parejo found it for me (thank you, Eduard!) 
    //             and not only did I blast it away, but I was able to 
    //             finally clean up a bit of code that came close to being 
    //             a browser-sniffer.  I'm much happier with what it is 
    //             this time!
    // 01-28-2003: Fixed a damn bug in the DIV_MOD function
    // 01-27-2003: Added Floor(Sqrt(x)) function.  Also added an
    //             IsThisAPerfectSquare function, because the coding is 
    //             pretty trivial, once I have some form of sqrt function.  
    //             It's still a memory-gobbler, though.  I'm open to 
    //             algorithms to reduce this time/computation chunking...
    // 01-14-2003: Added IsPrime function.
    // 01-10-2003: Added Floor and Ceiling, as well as a couple of supporting
    //             rounding functions.  Added GCD and LCM and cleaned up a bit
    //             of code in various places.  Time for a deployment!
    // 01-09-2003: Finished Division.  Yay!  It seems to work pretty
    //             well, including using signs and decimals, but I expect I'll 
    //             have more than a few people point out errors to me.  I hope 
    //             not -- it seems pretty tough.
    //             Also fixed BuildString so that it can handle strings of 
    //             characters of pretty much any length (previously, it had 
    //             been limited to a count no higher than the limit of integers, 
    //             but now it uses the Calculator's own tools for manipulating 
    //             large numbers.)
    // 01-08-2003: Modified the Addition routine to behave better independent of 
    //             browser.  There's still a chunk of code in Multiply that has 
    //             to do result-checks because of browser incompatibilities, but 
    //             eventually, I might nail it, too.  Just not fond of even 
    //             coming CLOSE to results that vary browser-to-browser...
    // 12-19-2002: Added a Help button and associated window.  Much better!
    // 12-03-2002: Added a Status window.  This allows people to know something's 
    //             "going on" during long calculations.  I can't decide if I want 
    //             to disable buttons during long calculations, but this is a 
    //             good interim solution.  It's certainly better than an alert 
    //             window!
    // 11-21-2002: Completed Factorials and Powers.  My sympathies to anyone 
    //             feeding a big number into it -- it takes a bit of time.
    // 11-20-2002: Completed all the trivial cases for DIV and MOD, meaning cases
    //             where one of the numbers = 0, where the Divisor = 1, where 
    //             the Divisor is greater than the Dividend, and where the Divisor 
    //             equals the Dividend.
    // 11-14-2002: Wrangled the last bits of the page to XHTML standards.  Yay!
    //             Also added a ^2 function.  I added a memory bank, such that 
    //             you can "store" results into ten "accumulators".  I'm 
    //             picking ten for the heck of it.  If you really think you need
    //             more, I guess you could just ask.
    // 09-11-2002: Fixed a bug in the IsEqual routine.  Perhaps I should hire
    //             Matthew to find bugs -- he's nailed me twice so far!  Updated
    //             the IsLessThan and IsGreaterThan functions to account for sign
    //             and reinstated those on the client page.  I've changed the 
    //             graphic image of buttons to real buttons, which I HOPE will be 
    //             XHTML transitional acceptable.  For a while, it looked like 
    //             I'd have crazy-shaped buttons, but then I found I can specify 
    //             button width in the stylesheet.  So I did and it works quite 
    //             attractively.  At this moment, I haven't tested the changes 
    //             under Netscape, but I will before deployment.
    // 09-10-2002: Fixed a bug in the Subtraction routine.  Now, the Minuend and
    //             Subtrahend are padded with decimals before any comparisons are
    //             made.  Much smarter that way.  Thanks to Matthew Mastracci for
    //             pointing it out!  I also converted the page to my best attempt
    //             at XHTML and to use a stylesheet.  Always on the bleeding edge, 
    //             we are.  Alas, I miss the transitional mark because href can't 
    //             take an onClick event, but that's the only way to make it work 
    //             (as far as I can tell at the moment) in Netscape.  Grumble...  
    //             I'll bang on it more later.
    // 07-09-2002: Added Multiplication.  I also fixed a bug in the ZeroTrim function.   
    //             It wasn't producing incorrect answers until I implemented the  
    //             Multiplication function, so any valuable scientific research based  
    //             on my JavaScript calculator hasn't been subjected to trouble.
    // 10-04-2001: Added Sign switching functions to buttons and updated addition to 
    //             include negatives.  Added a "No Function Yet" reporter to functions 
    //             that, well, don't work yet.
    // 10-03-2001: Added subtraction.
    // 09-27-2001: Added graphic buttons for interface and changed code to be more 
    //             universal for browsers.  Only trouble with graphical buttons is 
    //             that they're not obviously "disabled" like they were in Explorer.  
    //             I guess I could do "disabled" looking buttons, but later...
    // 09-19-2001: Finished coding the basic addition block.  Looking in dread at 
    //             the future.
    // 

    function BuildString (Symbol, Multiple)
      // returns a string that consists of the a Multiple number of Symbols.
      // for example, BuildString(x,5) returns "xxxxx"
    {
    var CompoundString="";
      while (IsEqualTo(Multiple,"0") == "FALSE")
        {
          CompoundString = CompoundString + Symbol;
          Multiple = Subtraction(Multiple,"1");
        }
      return CompoundString;
    }

    function RoundBigNumberUp (BigPositiveNumber)
      // Rounds a 'big' number up.  The assumption is that the number is Positive
      {
        var Answer = "";
        BigPositiveNumber = ZeroTrim(BigPositiveNumber); // in case it has lotsa zeroes at the end
        if (BigPositiveNumber.search(/\./) != (-1)) // if the number contains a decimal...
          {
            Answer = CalculatorAdd(RegExp.leftContext,"1");
          }
        else // there is no decimal in the number, therefore, it is already rounded
          {
            Answer = BigPositiveNumber;
          }
        return Answer;
      }

    function RoundBigNumberDown (BigPositiveNumber)
      // Rounds a 'big' number down.  The assumption is that the number is Positive
      {
        var Answer = "";
        BigPositiveNumber = ZeroTrim(BigPositiveNumber); // in case it has lotsa zeroes at the end
        if (BigPositiveNumber.search(/\./) != (-1)) // if the number contains a decimal...
          {
            Answer = RegExp.leftContext;
          }
        else // there is no decimal in the number, therefore, it is already rounded
          {
            Answer = BigPositiveNumber;
          }
        return Answer;
      }

    function BigNumberCeiling (BigRealNumber)
      // Finds the ceiling of BigRealNumber.
      {
        var Answer = "";
        if (BigRealNumber.charAt(0) == "-") // then it is a negative number
          {Answer = "-" + RoundBigNumberDown(BigRealNumber.substring(1,BigRealNumber.length));}
        else
          {Answer = RoundBigNumberUp(BigRealNumber);}
        return Answer;
      }

    function BigNumberFloor (BigRealNumber)
      // Finds the floor of BigRealNumber.
      {
        var Answer = "";
        if (BigRealNumber.charAt(0) == "-") // then it is a negative number
          {Answer = "-" + RoundBigNumberUp(BigRealNumber.substring(1,BigRealNumber.length));}
        else
          {Answer = RoundBigNumberDown(BigRealNumber);}
        return Answer;
      }

    function SubProduct (Multiplicand, SingleDigitMultiplier)
      // Multiplies Multiplicand (any number of digits) by a single digit Multiplier
      {
        var Carry = "0";
        var SubProduct = "";
        var TempProd = "0";
        for (var counter = Multiplicand.length-1; counter > (-1); counter--)
        {
          var TempProd = (Multiplicand.charAt(counter) * SingleDigitMultiplier) + parseInt(Carry);
          if (TempProd < 10) {TempProd = "0" + TempProd} // Now all small products are 2-digit numbers
          Carry = (TempProd + "").charAt(0);
          SubProduct = (TempProd + "").charAt(1) + SubProduct;
        }
        if (Carry != "0") {SubProduct = (Carry + SubProduct)}
        return SubProduct;
      }

    function ZeroTrim(BloatyAnswer) // trim trailing zeroes after the decimal and leading zeroes before
    {
      if (BloatyAnswer.search(/\./i) == -1)
        {
        BloatyAnswer = BloatyAnswer + ".0";
        }
      if (BloatyAnswer.charAt(0) == ".")
        {
        BloatyAnswer = "0" + BloatyAnswer;
        }
      while (BloatyAnswer.charAt(BloatyAnswer.length - 1) == "0")
        {
          BloatyAnswer = BloatyAnswer.substring(0,BloatyAnswer.length - 1);
          // trim that last character off if it's a zero
        }
        if (BloatyAnswer.charAt(BloatyAnswer.length - 1) == ".")
          // trim off that last decimal point, if it's there
          {
            BloatyAnswer = BloatyAnswer.substring(0,BloatyAnswer.length - 1);
          }
      // trim leading zeroes, but if the answer is simply "0", then stop.
         while ((BloatyAnswer.length>1) && (BloatyAnswer.charAt(0)=="0") && (BloatyAnswer.charAt(1)!="."))
           {
             BloatyAnswer = BloatyAnswer.substring(1,BloatyAnswer.length);
           }
      return BloatyAnswer;
    }

    function SwitchSign(Arg)
    {
      if (Arg.charAt(0)=="-")
        Arg = Arg.substring(1,Arg.length);
      else
        {
          Arg="-"+Arg;
        }
      return Arg;
    }

    function IsLessThan(Arg1,Arg2) // Is Arg1 less than Arg2?
    {
      var Result = "";
      // If Arg1 is negative and Arg2 is positive, then the answer is automatically true
        if (Arg1.charAt(0) == "-" && Arg2.charAt(0) !="-") {Result = "TRUE"}
      // If Arg1 is positive and Arg2 is negative, then the answer is automatically false
        if (Arg1.charAt(0) != "-" && Arg2.charAt(0) =="-") {Result = "FALSE"}
      // If Arg1 = Arg2, then the answer is automatically false
        if (IsEqualTo(Arg1,Arg2) == "TRUE") {Result = "FALSE"}
      // If Arg1 and Arg2 are both negative, then we swap them, switch signs, and try again.
        if (Arg1.charAt(0) == "-" && Arg2.charAt(0) =="-") {Result = IsLessThan(SwitchSign(Arg2),SwitchSign(Arg1))}
      // If Arg1 and Arg2 are both positive
        if (Result == "")
          {
            // Pad them with zeroes to line up the decimal (if it exists)
               var type = "";
               var AnswerArray1 = Arg1.split("."); // Split into an array
               var AnswerArray2 = Arg2.split("."); // Split into an array
               // make sure arrays have '0' instead of 'undefined' or '' as elements
               // split produces a mixed response, an empty string on the left of the split
               // and undefined on the right of the split.  This is further complicated by
               // the fact that Navigator understands "undefined" in comparisions, but
               // IE doesn't, so I have to create a variable and assign it to a typeof.
                  if (AnswerArray1[0] == "") {AnswerArray1[0] = "0"}
                  type = typeof AnswerArray1[1];
                  if (type == "undefined") {AnswerArray1[1] = "0"}
                  if (AnswerArray2[0] == "") {AnswerArray2[0] = "0"}
                  type = typeof AnswerArray2[1];
                  if (type == "undefined") {AnswerArray2[1] = "0"}

               // Rebuild operands as strings with decimals.
                  Arg1 = AnswerArray1[0] + "." + AnswerArray1[1];
                  Arg2 = AnswerArray2[0] + "." + AnswerArray2[1];
               // if decimal split !=, then equalize by adding trailing zeroes to the short decimal
                  if (AnswerArray1[1].length > AnswerArray2[1].length)
                    {
                      Arg2 += BuildString("0",AnswerArray1[1].length-AnswerArray2[1].length+"");
                    }
                  if (AnswerArray2[1].length > AnswerArray1[1].length)
                    {
                      Arg1 += BuildString("0",AnswerArray2[1].length-AnswerArray1[1].length+"");
                    }

               // if integer split != then equalize by adding leading zeroes to the short integer
                  if (AnswerArray1[0].length > AnswerArray2[0].length)
                    {
                      Arg2 = BuildString("0",AnswerArray1[0].length-AnswerArray2[0].length+"") + Arg2;
                    }
                  if (AnswerArray2[0].length > AnswerArray1[0].length)
                    {
                      Arg1 = BuildString("0",AnswerArray2[0].length-AnswerArray1[0].length+"") + Arg1;
                    }
            var counter = 0;
            while ((Result=="") && (counter < Arg1.length))
            {
              if (Arg2.charAt(counter) < Arg1.charAt(counter)) {Result = "FALSE"}
              if (Arg2.charAt(counter) > Arg1.charAt(counter)) {Result = "TRUE"}
              counter++;
            }
          }
      // Return Result
        return Result;
    }

    function IsGreaterThan(Arg1,Arg2) // Is Arg1 greater than Arg2?
    {
      var Result = "";
      // If Arg1 is negative and Arg2 is positive, then the answer is automatically false
        if (Arg1.charAt(0) == "-" && Arg2.charAt(0) !="-") {Result = "FALSE"}
      // If Arg1 is positive and Arg2 is negative, then the answer is automatically true
        if (Arg1.charAt(0) != "-" && Arg2.charAt(0) =="-") {Result = "TRUE"}
      // If Arg1 = Arg2, then the answer is automatically false
        if (IsEqualTo(Arg1,Arg2) == "TRUE") {Result = "FALSE"}
      // If Arg1 and Arg2 are both negative, then we swap them, switch signs, and try again.
        if (Arg1.charAt(0) == "-" && Arg2.charAt(0) =="-") {Result = IsGreaterThan(SwitchSign(Arg2),SwitchSign(Arg1))}
      // If Arg1 and Arg2 are both positive
        if (Result == "")
          {
            // Pad them with zeroes to line up the decimal (if it exists)
               var type = "";
               var AnswerArray1 = Arg1.split("."); // Split into an array
               var AnswerArray2 = Arg2.split("."); // Split into an array
               // make sure arrays have '0' instead of 'undefined' or '' as elements
               // split produces a mixed response, an empty string on the left of the split
               // and undefined on the right of the split.  This is further complicated by
               // the fact that Navigator understands "undefined" in comparisions, but
               // IE doesn't, so I have to create a variable and assign it to a typeof.
                  if (AnswerArray1[0] == "") {AnswerArray1[0] = "0"}
                  type = typeof AnswerArray1[1];
                  if (type == "undefined") {AnswerArray1[1] = "0"}
                  if (AnswerArray2[0] == "") {AnswerArray2[0] = "0"}
                  type = typeof AnswerArray2[1];
                  if (type == "undefined") {AnswerArray2[1] = "0"}

               // Rebuild operands as strings with decimals.
                  Arg1 = AnswerArray1[0] + "." + AnswerArray1[1];
                  Arg2 = AnswerArray2[0] + "." + AnswerArray2[1];
               // if decimal split !=, then equalize by adding trailing zeroes to the short decimal
                  if (AnswerArray1[1].length > AnswerArray2[1].length)
                    {
                      Arg2 += BuildString("0",AnswerArray1[1].length-AnswerArray2[1].length+"");
                    }
                  if (AnswerArray2[1].length > AnswerArray1[1].length)
                    {
                      Arg1 += BuildString("0",AnswerArray2[1].length-AnswerArray1[1].length+"");
                    }

               // if integer split != then equalize by adding leading zeroes to the short integer
                  if (AnswerArray1[0].length > AnswerArray2[0].length)
                    {
                      Arg2 = BuildString("0",AnswerArray1[0].length-AnswerArray2[0].length+"") + Arg2;
                    }
                  if (AnswerArray2[0].length > AnswerArray1[0].length)
                    {
                      Arg1 = BuildString("0",AnswerArray2[0].length-AnswerArray1[0].length+"") + Arg1;
                    }
            var counter = 0;
            while ((Result=="") && (counter < Arg1.length))
            {
              if (Arg2.charAt(counter) < Arg1.charAt(counter)) {Result = "TRUE"}
              if (Arg2.charAt(counter) > Arg1.charAt(counter)) {Result = "FALSE"}
              counter++;
            }
          }
      // Return Result
        return Result;
    }

    function IsEqualTo(Arg1,Arg2)
    {
      var Result = "FALSE";
      if (Arg1.length == Arg2.length)
        {
          Result = "TRUE";
          for (counter = 0; counter < Arg1.length; counter++)
            {
              if (Arg1.charAt(counter) != Arg2.charAt(counter)) {Result = "FALSE"}
            }
        }

      // Return Result
        return Result;
    }

    function Subtraction(Minuend,Subtrahend) // Minuend - Subtrahend = Difference
    {
      var Difference = "";
      // Pad them with zeroes to line up the decimal (if it exists)
         var type="";
         var AnswerArray1 = Minuend.split("."); // Split into an array
         var AnswerArray2 = Subtrahend.split("."); // Split into an array
         // make sure arrays have '0' instead of 'undefined' or '' as elements
         // split produces a mixed response, an empty string on the left of the split
         // and undefined on the right of the split.  This is further complicated by
         // the fact that Navigator understands "undefined" in comparisions, but
         // IE doesn't, so I have to create a variable and assign it to a typeof.
            if (AnswerArray1[0] == "") {AnswerArray1[0] = "0"}
            type = typeof AnswerArray1[1];
            if (type == "undefined") {AnswerArray1[1] = "0"}
            if (AnswerArray2[0] == "") {AnswerArray2[0] = "0"}
            type = typeof AnswerArray2[1];
            if (type == "undefined") {AnswerArray2[1] = "0"}

         // Rebuild operands as strings with decimals.
            Minuend = AnswerArray1[0] + "." + AnswerArray1[1];
            Subtrahend = AnswerArray2[0] + "." + AnswerArray2[1];
         // if decimal split !=, then equalize by adding trailing zeroes to the short decimal
            if (AnswerArray1[1].length > AnswerArray2[1].length)
              {
                Subtrahend += BuildString("0",AnswerArray1[1].length-AnswerArray2[1].length+"");
              }
            if (AnswerArray2[1].length > AnswerArray1[1].length)
              {
                Minuend += BuildString("0",AnswerArray2[1].length-AnswerArray1[1].length+"");
              }
         // if integer split != then equalize by adding leading zeroes to the short integer
            if (AnswerArray1[0].length > AnswerArray2[0].length)
              {
                Subtrahend = BuildString("0",AnswerArray1[0].length-AnswerArray2[0].length+"") + Subtrahend;
              }
            if (AnswerArray2[0].length > AnswerArray1[0].length)
              {
                Minuend = BuildString("0",AnswerArray2[0].length-AnswerArray1[0].length+"") + Minuend;
              }
      // If Minuend == Subtrahend, then the answer is simply 0
         if (!Difference && (IsEqualTo(Minuend,Subtrahend)=="TRUE")) {Difference= "0"}
      // If Minuend is positive and Subtrahend is negative,
      // then this is an addition problem
         if (!Difference && Minuend.charAt(0)!="-" && Subtrahend.charAt(0)=="-")
           {
             Subtrahend=Subtrahend.substring(1,Subtrahend.length);
             Difference = CalculatorAdd(Minuend,Subtrahend);
           }
      // If Minuend and Subtrahend are negative, invert both
      //  signs and reverse operands -- continue
         if (!Difference && Minuend.charAt(0)=="-" && Subtrahend.charAt(0)=="-")
           {
             Subtrahend=Subtrahend.substring(1,Subtrahend.length);
             Minuend=Minuend.substring(1,Minuend.length);
             var TemporaryVariable = Subtrahend;
             Subtrahend = Minuend;
             Minuend = TemporaryVariable;
           }
      // If Minuend is negative and Subtrahend is positive, then
      // remove Minuend sign, process as an addition, and then
      // append negative sign.
         if (!Difference && Minuend.charAt(0) == "-" && Subtrahend.charAt(0) !="-")
           {
             Minuend=Minuend.substring(1,Minuend.length);
             Difference = "-" + CalculatorAdd(Minuend,Subtrahend);
           }
      // Minuend and Subtrahend are both positive numbers,
      // either because they started out that way, or they started
      // out as both negative numbers and were converted by an
      // earlier process.  For all other cases, Difference has
      // already been assigned a value
         if (!Difference)
           {
             // If the Minuend is smaller than the Subtrahend, then the
             // result will be a negative number, so set a "negative"
             // tag (NegativeTag = "-" instead of ""), reverse the
             // operands, and continue.
                var NegativeTag = "";
                if (IsLessThan(Minuend,Subtrahend)=="TRUE")
                {
                  var TempVariable = Minuend;
                  Minuend = Subtrahend;
                  Subtrahend = TempVariable;
                  NegativeTag="-";
                }
             // Perform the digit-by-digit subtraction
                var BorrowFlag="0";
                for (counter = Minuend.length-1; counter > -1; counter--)
                {
                  if (Minuend.charAt(counter) ==".") // then it's a decimal point
                    Difference = "." + Difference
                  else // it's a genuine number
                    {
                      // because it's a number, perform the subtraction and append it to Difference
                      var MinuendPiece = parseInt(Minuend.charAt(counter));
                      var SubtrahendPiece = parseInt(Subtrahend.charAt(counter));
                      if (BorrowFlag == 1) {BorrowFlag = 0; MinuendPiece = MinuendPiece -1}
                      if (MinuendPiece < 0) {MinuendPiece = 9; BorrowFlag = 1}
                      if (MinuendPiece < SubtrahendPiece)
                        {
                          MinuendPiece = MinuendPiece + 10;
                          BorrowFlag = 1;
                        }
                      Difference = (MinuendPiece - SubtrahendPiece) + Difference;
                    }
                }
             // Remove trailing and leading zeroes
                Difference = ZeroTrim(Difference);
             // Append to the NegativeTag
                Difference = NegativeTag + Difference;
           }
        // Return Difference
      return Difference;
    }

    function CalculatorAdd(operand1,operand2)
    {
      var answer = "";

      if (operand1.charAt(0)!="-" && operand2.charAt(0)=="-") {answer = Subtraction(operand1,SwitchSign(operand2))}
      if (operand1.charAt(0)=="-" && operand2.charAt(0)!="-") {answer = Subtraction(operand2,SwitchSign(operand1))}
      if (operand1.charAt(0)=="-" && operand2.charAt(0)=="-") {answer = Subtraction(operand1,SwitchSign(operand2))}
      if (answer=="")
      {
        // Equalize both sides of the decimals
           var Operand1LeftPad = "";
           var Operand2LeftPad = "";
           var Operand1RightPad = "";
           var Operand2RightPad = "";
           var Operand1RightSide = "";
           var Operand2RightSide = "";
           var Operand1LeftSide = "";
           var Operand2LeftSide = "";

           if (operand1.search(/\./) == -1) // then there is no decimal in operand1
             {
               Operand1RightSide = "0";
               Operand1LeftSide = operand1;
             }
             else // there is a decimal and we must determine the values of the sides
               {
                 Operand1RightSide=RegExp.rightContext;
                 Operand1LeftSide=RegExp.leftContext;
               }
           if (operand2.search(/\./) == -1) // then there is no decimal in operand2
             {
               Operand2RightSide = "0";
               Operand2LeftSide = operand2;
             }
             else // there is a decimal and we must determine the values of the sides
               {
                 Operand2RightSide=RegExp.rightContext;
                 Operand2LeftSide=RegExp.leftContext;
               }
           if (Operand1LeftSide.length > Operand2LeftSide.length)
             { Operand2LeftPad = BuildString("0",(Operand1LeftSide.length - Operand2LeftSide.length+"")+""); }
           if (Operand1LeftSide.length < Operand2LeftSide.length)
             { Operand1LeftPad = BuildString("0",(Operand2LeftSide.length - Operand1LeftSide.length)+""); }

           if (Operand1RightSide.length > Operand2RightSide.length)
             { Operand2RightPad = BuildString("0",(Operand1RightSide.length - Operand2RightSide.length)+""); }
           if (Operand1RightSide.length < Operand2RightSide.length)
             { Operand1RightPad = BuildString("0",(Operand2RightSide.length - Operand1RightSide.length)+""); }

           operand1 = Operand1LeftPad + Operand1LeftSide + "." + Operand1RightSide + Operand1RightPad;
           operand2 = Operand2LeftPad + Operand2LeftSide + "." + Operand2RightSide + Operand2RightPad;

      // perform digit-by-digit addition
         var CarryFlag = 0;
             answer = "";
         for (counter=operand1.length-1; counter > (-1); counter--)
           {
             var temp = parseInt(operand1.charAt(counter)) + parseInt(operand2.charAt(counter)) + parseInt(CarryFlag);
             if ((temp > (-1)) && (temp < 20))
               {
               if (temp > 9)
                 {
                   CarryFlag = 1;
                   answer = temp-10 + answer;
                 }
               else
                 {
                   CarryFlag = 0;
                   answer = temp + answer;
                 }
               }
             else
               {
                 answer = "." + answer;
                 // unless the answer is an actual number, it's going 
                 // to be NaN or undefined, or perhaps something else.  
                 // I just force the conversion to a decimal, but I 
                 // should consider adding some kind of error catching 
                 // routine here.
               }
           }
         // and just in case the CarryFlag is carrying something after all the digits are done...
         if (CarryFlag == 1) {answer = "1" + answer}

      //  In order to make things smoother earlier, I just converted both numbers to
      //  decimals, even if they weren't.  So now that the addition's over, there are
      //  two possibilities that would leave a number unattractive.  One, if I added
      //  two whole numbers such as 5 & 7, the result looks like 12.0, in which case
      //  I want to trim off the trailing zero AND the decimal point.  Another
      //  possibility is if trailing digits totaled out to 0, in which case they would
      //  still be there.  For example, 1.05 and 1.05 should be 2.1, but reports as
      //  2.10 so time to clean that up.
          answer = ZeroTrim(answer);
      }
      return answer;
    }
//
// JavaScript Browser Sniffer
// Eric Krok, Andy King, Michel Plungjan Jan. 31, 2002
// see http://www.webreference.com/ for more information
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
// please send any improvements to aking@internet.com and we'll
// roll the best ones in
//
// adapted from Netscape's Ultimate client-side JavaScript client sniffer
// and andy king's sniffer
// Revised May 7 99 to add is.nav5up and is.ie5up (see below). (see below).
// Revised June 11 99 to add additional props, checks
// Revised June 23 99 added screen props - gecko m6 doesn't support yet - abk
//                    converted to var is_ from is object to work everywhere
// 990624 - added cookie forms links frames checks - abk
// 001031 - ie4 mod 5.0 -> 5. (ie5.5 mididentified - abk)
//          is_ie4 mod tp work with ie6+ - abk
// 001120 - ns6 released, document.layers false, put back in
//        - is_nav6 test added - abk
// 001121 - ns6+ added, used document.getElementById, better test, dom-compl
// 010117 - actual version for ie3-5.5 by Michel Plungjan
// 010118 - actual version for ns6 by Michel Plungjan
// 010217 - netscape 6/mz 6 ie5.5 onload defer bug docs - abk
// 011107 - added is_ie6 and is_ie6up variables - dmr
// 020128 - added link to netscape's sniffer, on which this is based - abk
//          updated sniffer for aol4-6, ie5mac = js1.4, TVNavigator, AOLTV,
//          hotjava
// 020131 - cleaned up links, added more links to example object detection
// 020131 - a couple small problems with Opera detection. First, when Opera
//          is set to be compatible with other browsers it will contain their
//          information in the userAgent strings. Thus, to be sure we have 
//          Opera we should check for it before checking for the other bigs.
//          (And make sure the others are !opera.) Also corrected a minor
//          bug in the is_opera6up assignment.
// 020214 - Added link for Opera/JS compatibility; added improvements for 
//          windows xp/2000 id in opera and aol 7 id (thanks to Les
//          Hill, Les.Hill@getronics.com, for the suggestion).
// 020531 - Added N6/7 and moz identifiers. 
// 020605 - Added mozilla guessing, Netscape 7 identification, and cleaner
//          identification for Netscape 6. (this comment added after code 
//          changes)
// 020725 - Added is_gecko. -- dmr
// 021205 - Added is_Flash and is_FlashVersion, based on Doc JavaScript code. 
//          Added Opera 7 variables. -- dmr
// 021209 - Added aol8. -- dmr
// 030110 - Added is_safari, added 1.5 js designation for Opera 7. --dmr
// 030128 - Added is_konq, per user suggestion (thanks to Sam Vilain).
//          Removed duplicate Opera checks left over after last revision. - dmr
// 031124 - Added is_fb and version. We report this right after the is_moz
//          report. - dmr
// 040325 - Added is_fx and version. We report this right after the is_moz
//          report. - dmr
// 040421 - Added Debian check to is_moz. Thanks to Patrice Bridoux for
//          reporting this.
// 040517 - Added is_fb/is_fx to plugins based flash detection. Thanks to 
//          Martin Bischoff for pointing out this omission.
// 040617 - On Mac IE, appVersion differs from the version in the ua, 
//          with the UA appearing to be more accurate. As an experiment, 
//          for Mac we'll pull is_minor from the ua instead.
// 040831 - Fixed Opera bug in flash detection logic; when Opera has
//          "enable plugins" unchecked in preferences, the "plugin" 
//          variable is still true, but the "description" property 
//          belonging to it is undefined.
//
// Everything you always wanted to know about your JavaScript client
// but were afraid to ask. Creates "is_" variables indicating:
// (1) browser vendor:
//     is_nav, is_ie, is_opera
// (2) browser version number:
//     is_major (integer indicating major version number: 2, 3, 4 ...)
//     is_minor (float   indicating full  version number: 2.02, 3.01, 4.04 ...)
// (3) browser vendor AND major version number
//     is_nav2, is_nav3, is_nav4, is_nav4up, is_nav5, is_nav5up, 
//     is_nav6, is_nav6up, is_ie3, is_ie4, is_ie4up, is_ie5up, is_ie6...
// (4) JavaScript version number:
//     is_js (float indicating full JavaScript version number: 1, 1.1, 1.2 ...)
// (5) OS platform and version:
//     is_win, is_win16, is_win32, is_win31, is_win95, is_winnt, is_win98
//     is_os2
//     is_mac, is_mac68k, is_macppc
//     is_unix
//        is_sun, is_sun4, is_sun5, is_suni86
//        is_irix, is_irix5, is_irix6
//        is_hpux, is_hpux9, is_hpux10
//        is_aix, is_aix1, is_aix2, is_aix3, is_aix4
//        is_linux, is_sco, is_unixware, is_mpras, is_reliant
//        is_dec, is_sinix, is_freebsd, is_bsd
//     is_vms
//
// based in part on 
// http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
// The Ultimate JavaScript Client Sniffer
// and Andy King's object detection sniffer
//
// Note: you don't want your Nav4 or IE4 code to "turn off" or
// stop working when Nav5 and IE5 (or later) are released, so
// in conditional code forks, use is_nav4up ("Nav4 or greater")
// and is_ie4up ("IE4 or greater") instead of is_nav4 or is_ie4
// to check version in code which you want to work on future
// versions. For DOM tests scripters commonly used the 
// is_getElementById test, but make sure you test your code as
// filter non-compliant browsers (Opera 5-6 for example) as some 
// browsers return true for this test, and don't fully support
// the W3C's DOM1.
//

    // convert all characters to lowercase to simplify testing
    var agt=navigator.userAgent.toLowerCase();
    var appVer = navigator.appVersion.toLowerCase();

    // *** BROWSER VERSION ***

    var is_minor = parseFloat(appVer);
    var is_major = parseInt(is_minor);

    var is_opera = (agt.indexOf("opera") != -1);
    var is_opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
    var is_opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
    var is_opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
    var is_opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
    var is_opera6 = (agt.indexOf("opera 6") != -1 || agt.indexOf("opera/6") != -1); // new 020128- abk
    var is_opera7 = (agt.indexOf("opera 7") != -1 || agt.indexOf("opera/7") != -1); // new 021205- dmr
    var is_opera5up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4);
    var is_opera6up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5); // new020128
    var is_opera7up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5 && !is_opera6); // new021205 -- dmr

    // Note: On IE, start of appVersion return 3 or 4
    // which supposedly is the version of Netscape it is compatible with.
    // So we look for the real version further on in the string
    // And on Mac IE5+, we look for is_minor in the ua; since 
    // it appears to be more accurate than appVersion - 06/17/2004

    var is_mac = (agt.indexOf("mac")!=-1);
    var iePos  = appVer.indexOf('msie');
    if (iePos !=-1) {
       if(is_mac) {
           var iePos = agt.indexOf('msie');
           is_minor = parseFloat(agt.substring(iePos+5,agt.indexOf(';',iePos)));
       }
       else is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)));
       is_major = parseInt(is_minor);
    }

    // ditto Konqueror
                                      
    var is_konq = false;
    var kqPos   = agt.indexOf('konqueror');
    if (kqPos !=-1) {                 
       is_konq  = true;
       is_minor = parseFloat(agt.substring(kqPos+10,agt.indexOf(';',kqPos)));
       is_major = parseInt(is_minor);
    }                                 

    var is_getElementById   = (document.getElementById) ? "true" : "false"; // 001121-abk
    var is_getElementsByTagName = (document.getElementsByTagName) ? "true" : "false"; // 001127-abk
    var is_documentElement = (document.documentElement) ? "true" : "false"; // 001121-abk

    var is_safari = ((agt.indexOf('safari')!=-1)&&(agt.indexOf('mac')!=-1))?true:false;
    var is_khtml  = (is_safari || is_konq);

    var is_gecko = ((!is_khtml)&&(navigator.product)&&(navigator.product.toLowerCase()=="gecko"))?true:false;
    var is_gver  = 0;
    if (is_gecko) is_gver=navigator.productSub;

    var is_moz   = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) &&
                    (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1)  &&
                    (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)     &&
                    (is_gecko) && 
                    ((navigator.vendor=="")||(navigator.vendor=="Mozilla")||(navigator.vendor=="Debian")));
    var is_fb = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) &&
                 (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1)  &&
                 (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)     &&
                 (is_gecko) && (navigator.vendor=="Firebird"));
    var is_fx = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) &&
                 (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1)  &&
                 (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)     &&
                 (is_gecko) && (navigator.vendor=="Firefox"));
    if ((is_moz)||(is_fb)||(is_fx)) {  // 032504 - dmr
       var is_moz_ver = (navigator.vendorSub)?navigator.vendorSub:0;
       if(!(is_moz_ver)) {
           is_moz_ver = agt.indexOf('rv:');
           is_moz_ver = agt.substring(is_moz_ver+3);
           is_paren   = is_moz_ver.indexOf(')');
           is_moz_ver = is_moz_ver.substring(0,is_paren);
       }
       is_minor = is_moz_ver;
       is_major = parseInt(is_moz_ver);
    }
   var is_fb_ver = is_moz_ver;
   var is_fx_ver = is_moz_ver;

    var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)
                && (!is_khtml) && (!(is_moz)) && (!is_fb) && (!is_fx));

    // Netscape6 is mozilla/5 + Netscape6/6.0!!!
    // Mozilla/5.0 (Windows; U; Win98; en-US; m18) Gecko/20001108 Netscape6/6.0
    // Changed this to use navigator.vendor/vendorSub - dmr 060502   
    // var nav6Pos = agt.indexOf('netscape6');
    // if (nav6Pos !=-1) {
    if ((navigator.vendor)&&
        ((navigator.vendor=="Netscape6")||(navigator.vendor=="Netscape"))&&
        (is_nav)) {
       is_major = parseInt(navigator.vendorSub);
       // here we need is_minor as a valid float for testing. We'll
       // revert to the actual content before printing the result. 
       is_minor = parseFloat(navigator.vendorSub);
    }

    var is_nav2 = (is_nav && (is_major == 2));
    var is_nav3 = (is_nav && (is_major == 3));
    var is_nav4 = (is_nav && (is_major == 4));
    var is_nav4up = (is_nav && is_minor >= 4);  // changed to is_minor for
                                                // consistency - dmr, 011001
    var is_navonly      = (is_nav && ((agt.indexOf(";nav") != -1) ||
                          (agt.indexOf("; nav") != -1)) );

    var is_nav6   = (is_nav && is_major==6);    // new 010118 mhp
    var is_nav6up = (is_nav && is_minor >= 6); // new 010118 mhp

    var is_nav5   = (is_nav && is_major == 5 && !is_nav6); // checked for ns6
    var is_nav5up = (is_nav && is_minor >= 5);

    var is_nav7   = (is_nav && is_major == 7);
    var is_nav7up = (is_nav && is_minor >= 7);

    var is_ie   = ((iePos!=-1) && (!is_opera) && (!is_khtml));
    var is_ie3  = (is_ie && (is_major < 4));

    var is_ie4   = (is_ie && is_major == 4);
    var is_ie4up = (is_ie && is_minor >= 4);
    var is_ie5   = (is_ie && is_major == 5);
    var is_ie5up = (is_ie && is_minor >= 5);
    
    var is_ie5_5  = (is_ie && (agt.indexOf("msie 5.5") !=-1)); // 020128 new - abk
    var is_ie5_5up =(is_ie && is_minor >= 5.5);                // 020128 new - abk
	
    var is_ie6   = (is_ie && is_major == 6);
    var is_ie6up = (is_ie && is_minor >= 6);

// KNOWN BUG: On AOL4, returns false if IE3 is embedded browser
    // or if this is the first browser window opened.  Thus the
    // variables is_aol, is_aol3, and is_aol4 aren't 100% reliable.

    var is_aol   = (agt.indexOf("aol") != -1);
    var is_aol3  = (is_aol && is_ie3);
    var is_aol4  = (is_aol && is_ie4);
    var is_aol5  = (agt.indexOf("aol 5") != -1);
    var is_aol6  = (agt.indexOf("aol 6") != -1);
    var is_aol7  = ((agt.indexOf("aol 7")!=-1) || (agt.indexOf("aol7")!=-1));
    var is_aol8  = ((agt.indexOf("aol 8")!=-1) || (agt.indexOf("aol8")!=-1));

    var is_webtv = (agt.indexOf("webtv") != -1);
    
    // new 020128 - abk
    
    var is_TVNavigator = ((agt.indexOf("navio") != -1) || (agt.indexOf("navio_aoltv") != -1)); 
    var is_AOLTV = is_TVNavigator;

    var is_hotjava = (agt.indexOf("hotjava") != -1);
    var is_hotjava3 = (is_hotjava && (is_major == 3));
    var is_hotjava3up = (is_hotjava && (is_major >= 3));

    // end new
	
    // *** JAVASCRIPT VERSION CHECK ***
    // Useful to workaround Nav3 bug in which Nav3
    // loads <SCRIPT LANGUAGE="JavaScript1.2">.
    // updated 020131 by dragle
    var is_js;
    if (is_nav2 || is_ie3) is_js = 1.0;
    else if (is_nav3) is_js = 1.1;
    else if ((is_opera5)||(is_opera6)) is_js = 1.3; // 020214 - dmr
    else if (is_opera7up) is_js = 1.5; // 031010 - dmr
    else if (is_khtml) is_js = 1.5;   // 030110 - dmr
    else if (is_opera) is_js = 1.1;
    else if ((is_nav4 && (is_minor <= 4.05)) || is_ie4) is_js = 1.2;
    else if ((is_nav4 && (is_minor > 4.05)) || is_ie5) is_js = 1.3;
    else if (is_nav5 && !(is_nav6)) is_js = 1.4;
    else if (is_hotjava3up) is_js = 1.4; // new 020128 - abk
    else if (is_nav6up) is_js = 1.5;

    // NOTE: In the future, update this code when newer versions of JS
    // are released. For now, we try to provide some upward compatibility
    // so that future versions of Nav and IE will show they are at
    // *least* JS 1.x capable. Always check for JS version compatibility
    // with > or >=.

    else if (is_nav && (is_major > 5)) is_js = 1.4;
    else if (is_ie && (is_major > 5)) is_js = 1.3;
    else if (is_moz) is_js = 1.5;
    else if (is_fb||is_fx) is_js = 1.5; // 032504 - dmr
    
    // what about ie6 and ie6up for js version? abk
    
    // HACK: no idea for other browsers; always check for JS version 
    // with > or >=
    else is_js = 0.0;
    // HACK FOR IE5 MAC = js vers = 1.4 (if put inside if/else jumps out at 1.3)
    if ((agt.indexOf("mac")!=-1) && is_ie5up) is_js = 1.4; // 020128 - abk
    
    // Done with is_minor testing; revert to real for N6/7
    if (is_nav6up) {
       is_minor = navigator.vendorSub;
    }

    // *** PLATFORM ***
    var is_win   = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
    // NOTE: On Opera 3.0, the userAgent string includes "Windows 95/NT4" on all
    //        Win32, so you can't distinguish between Win95 and WinNT.
    var is_win95 = ((agt.indexOf("win95")!=-1) || (agt.indexOf("windows 95")!=-1));

    // is this a 16 bit compiled version?
    var is_win16 = ((agt.indexOf("win16")!=-1) ||
               (agt.indexOf("16bit")!=-1) || (agt.indexOf("windows 3.1")!=-1) ||
               (agt.indexOf("windows 16-bit")!=-1) );

    var is_win31 = ((agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("win16")!=-1) ||
                    (agt.indexOf("windows 16-bit")!=-1));
	
	var is_winme = ((agt.indexOf("win 9x 4.90")!=-1));    // new 020128 - abk
    var is_win2k = ((agt.indexOf("windows nt 5.0")!=-1) || (agt.indexOf("windows 2000")!=-1)); // 020214 - dmr
    var is_winxp = ((agt.indexOf("windows nt 5.1")!=-1) || (agt.indexOf("windows xp")!=-1)); // 020214 - dmr

    // NOTE: Reliable detection of Win98 may not be possible. It appears that:
    //       - On Nav 4.x and before you'll get plain "Windows" in userAgent.
    //       - On Mercury client, the 32-bit version will return "Win98", but
    //         the 16-bit version running on Win98 will still return "Win95".
    var is_win98 = ((agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1));
    var is_winnt = ((agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1));
    var is_win32 = (is_win95 || is_winnt || is_win98 ||
                    ((is_major >= 4) && (navigator.platform == "Win32")) ||
                    (agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1));

    var is_os2   = ((agt.indexOf("os/2")!=-1) ||
                    (navigator.appVersion.indexOf("OS/2")!=-1) ||
                    (agt.indexOf("ibm-webexplorer")!=-1));

    var is_mac    = (agt.indexOf("mac")!=-1);
    if (is_mac) { is_win = !is_mac; } // dmr - 06/20/2002
    var is_mac68k = (is_mac && ((agt.indexOf("68k")!=-1) ||
                               (agt.indexOf("68000")!=-1)));
    var is_macppc = (is_mac && ((agt.indexOf("ppc")!=-1) ||
                                (agt.indexOf("powerpc")!=-1)));

    var is_sun   = (agt.indexOf("sunos")!=-1);
    var is_sun4  = (agt.indexOf("sunos 4")!=-1);
    var is_sun5  = (agt.indexOf("sunos 5")!=-1);
    var is_suni86= (is_sun && (agt.indexOf("i86")!=-1));
    var is_irix  = (agt.indexOf("irix") !=-1);    // SGI
    var is_irix5 = (agt.indexOf("irix 5") !=-1);
    var is_irix6 = ((agt.indexOf("irix 6") !=-1) || (agt.indexOf("irix6") !=-1));
    var is_hpux  = (agt.indexOf("hp-ux")!=-1);
    var is_hpux9 = (is_hpux && (agt.indexOf("09.")!=-1));
    var is_hpux10= (is_hpux && (agt.indexOf("10.")!=-1));
    var is_aix   = (agt.indexOf("aix") !=-1);      // IBM
    var is_aix1  = (agt.indexOf("aix 1") !=-1);
    var is_aix2  = (agt.indexOf("aix 2") !=-1);
    var is_aix3  = (agt.indexOf("aix 3") !=-1);
    var is_aix4  = (agt.indexOf("aix 4") !=-1);
    var is_linux = (agt.indexOf("inux")!=-1);
    var is_sco   = (agt.indexOf("sco")!=-1) || (agt.indexOf("unix_sv")!=-1);
    var is_unixware = (agt.indexOf("unix_system_v")!=-1);
    var is_mpras    = (agt.indexOf("ncr")!=-1);
    var is_reliant  = (agt.indexOf("reliantunix")!=-1);
    var is_dec   = ((agt.indexOf("dec")!=-1) || (agt.indexOf("osf1")!=-1) ||
           (agt.indexOf("dec_alpha")!=-1) || (agt.indexOf("alphaserver")!=-1) ||
           (agt.indexOf("ultrix")!=-1) || (agt.indexOf("alphastation")!=-1));
    var is_sinix = (agt.indexOf("sinix")!=-1);
    var is_freebsd = (agt.indexOf("freebsd")!=-1);
    var is_bsd = (agt.indexOf("bsd")!=-1);
    var is_unix  = ((agt.indexOf("x11")!=-1) || is_sun || is_irix || is_hpux ||
                 is_sco ||is_unixware || is_mpras || is_reliant ||
                 is_dec || is_sinix || is_aix || is_linux || is_bsd || is_freebsd);

    var is_vms   = ((agt.indexOf("vax")!=-1) || (agt.indexOf("openvms")!=-1));
// additional checks, abk
	var is_anchors = (document.anchors) ? "true":"false";
	var is_regexp = (window.RegExp) ? "true":"false";
	var is_option = (window.Option) ? "true":"false";
	var is_all = (document.all) ? "true":"false";
// cookies - 990624 - abk
	document.cookie = "cookies=true";
	var is_cookie = (document.cookie) ? "true" : "false";
	var is_images = (document.images) ? "true":"false";
	var is_layers = (document.layers) ? "true":"false"; // gecko m7 bug?
// new doc obj tests 990624-abk
	var is_forms = (document.forms) ? "true" : "false";
	var is_links = (document.links) ? "true" : "false";
	var is_frames = (window.frames) ? "true" : "false";
	var is_screen = (window.screen) ? "true" : "false";

// java
	var is_java = (navigator.javaEnabled());

// Flash checking code adapted from Doc JavaScript information; 
// see http://webref.com/js/column84/2.html

   var is_Flash        = false;
   var is_FlashVersion = 0;

   if ((is_nav||is_opera||is_moz||is_fb||is_fx)||
       (is_mac&&is_ie5up)) {
      var plugin = (navigator.mimeTypes && 
                    navigator.mimeTypes["application/x-shockwave-flash"] &&
                    navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) ?
                    navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
//      if (plugin) {
      if (plugin&&plugin.description) {
         is_Flash = true;
         is_FlashVersion = parseInt(plugin.description.substring(plugin.description.indexOf(".")-1));
      }
   }

   if (is_win&&is_ie4up)
   {
      document.write(
         '<scr' + 'ipt language=VBScript>' + '\n' +
         'Dim hasPlayer, playerversion' + '\n' +
         'hasPlayer = false' + '\n' +
         'playerversion = 10' + '\n' +
         'Do While playerversion > 0' + '\n' +
            'On Error Resume Next' + '\n' +
            'hasPlayer = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & playerversion)))' + '\n' +
            'If hasPlayer = true Then Exit Do' + '\n' +
            'playerversion = playerversion - 1' + '\n' +
         'Loop' + '\n' +
         'is_FlashVersion = playerversion' + '\n' +
         'is_Flash = hasPlayer' + '\n' +
         '<\/sc' + 'ript>'
      );
   }
/*

Cross-Browser XMLHttpRequest v1.2
=================================

Emulate Gecko 'XMLHttpRequest()' functionality in IE and Opera. Opera requires
the Sun Java Runtime Environment <http://www.java.com/>.

by Andrew Gregory
http://www.scss.com.au/family/andrew/webdesign/xmlhttprequest/

This work is licensed under the Creative Commons Attribution License. To view a
copy of this license, visit http://creativecommons.org/licenses/by/1.0/ or send
a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305,
USA.

Not Supported in Opera
----------------------
* user/password authentication
* responseXML data member

Not Fully Supported in Opera
----------------------------
* async requests
* abort()
* getAllResponseHeaders(), getAllResponseHeader(header)

*/
// IE support
if (window.ActiveXObject && !window.XMLHttpRequest) {
  window.XMLHttpRequest = function() {
    var msxmls = new Array(
      'Msxml2.XMLHTTP.5.0',
      'Msxml2.XMLHTTP.4.0',
      'Msxml2.XMLHTTP.3.0',
      'Msxml2.XMLHTTP',
      'Microsoft.XMLHTTP');
    for (var i = 0; i < msxmls.length; i++) {
      try {
        return new ActiveXObject(msxmls[i]);
      } catch (e) {
      }
    }
    return null;
  };
}
// Gecko support
/* ;-) */
// Opera support
if (window.opera && !window.XMLHttpRequest) {
  window.XMLHttpRequest = function() {
    this.readyState = 0; // 0=uninitialized,1=loading,2=loaded,3=interactive,4=complete
    this.status = 0; // HTTP status codes
    this.statusText = '';
    this._headers = [];
    this._aborted = false;
    this._async = true;
    this._defaultCharset = 'ISO-8859-1';
    this._getCharset = function() {
      var charset = _defaultCharset;
      var contentType = this.getResponseHeader('Content-type').toUpperCase();
      val = contentType.indexOf('CHARSET=');
      if (val != -1) {
        charset = contentType.substring(val);
      }
      val = charset.indexOf(';');
      if (val != -1) {
        charset = charset.substring(0, val);
      }
      val = charset.indexOf(',');
      if (val != -1) {
        charset = charset.substring(0, val);
      }
      return charset;
    };
    this.abort = function() {
      this._aborted = true;
    };
    this.getAllResponseHeaders = function() {
      return this.getAllResponseHeader('*');
    };
    this.getAllResponseHeader = function(header) {
      var ret = '';
      for (var i = 0; i < this._headers.length; i++) {
        if (header == '*' || this._headers[i].h == header) {
          ret += this._headers[i].h + ': ' + this._headers[i].v + '\n';
        }
      }
      return ret;
    };
    this.getResponseHeader = function(header) {
      var ret = getAllResponseHeader(header);
      var i = ret.indexOf('\n');
      if (i != -1) {
        ret = ret.substring(0, i);
      }
      return ret;
    };
    this.setRequestHeader = function(header, value) {
      this._headers[this._headers.length] = {h:header, v:value};
    };
    this.open = function(method, url, async, user, password) {
      this.method = method;
      this.url = url;
      this._async = true;
      this._aborted = false;
      this._headers = [];
      if (arguments.length >= 3) {
        this._async = async;
      }
      if (arguments.length > 3) {
        opera.postError('XMLHttpRequest.open() - user/password not supported');
      }
      this.readyState = 1;
      if (this.onreadystatechange) {
        this.onreadystatechange();
      }
    };
    this.send = function(data) {
      if (!navigator.javaEnabled()) {
        alert("XMLHttpRequest.send() - Java must be installed and enabled.");
        return;
      }
      if (this._async) {
        setTimeout(this._sendasync, 0, this, data);
        // this is not really asynchronous and won't execute until the current
        // execution context ends
      } else {
        this._sendsync(data);
      }
    }
    this._sendasync = function(req, data) {
      if (!req._aborted) {
        req._sendsync(data);
      }
    };
    this._sendsync = function(data) {
      this.readyState = 2;
      if (this.onreadystatechange) {
        this.onreadystatechange();
      }
      // open connection
      var url = new java.net.URL(new java.net.URL(window.location.href), this.url);
      var conn = url.openConnection();
      for (var i = 0; i < this._headers.length; i++) {
        conn.setRequestProperty(this._headers[i].h, this._headers[i].v);
      }
      this._headers = [];
      if (this.method == 'POST') {
        // POST data
        conn.setDoOutput(true);
        var wr = new java.io.OutputStreamWriter(conn.getOutputStream(), this._getCharset());
        wr.write(data);
        wr.flush();
        wr.close();
      }
      // read response headers
      // NOTE: the getHeaderField() methods always return nulls for me :(
      var gotContentEncoding = false;
      var gotContentLength = false;
      var gotContentType = false;
      var gotDate = false;
      var gotExpiration = false;
      var gotLastModified = false;
      for (var i = 0; ; i++) {
        var hdrName = conn.getHeaderFieldKey(i);
        var hdrValue = conn.getHeaderField(i);
        if (hdrName == null && hdrValue == null) {
          break;
        }
        if (hdrName != null) {
          this._headers[this._headers.length] = {h:hdrName, v:hdrValue};
          switch (hdrName.toLowerCase()) {
            case 'content-encoding': gotContentEncoding = true; break;
            case 'content-length'  : gotContentLength   = true; break;
            case 'content-type'    : gotContentType     = true; break;
            case 'date'            : gotDate            = true; break;
            case 'expires'         : gotExpiration      = true; break;
            case 'last-modified'   : gotLastModified    = true; break;
          }
        }
      }
      // try to fill in any missing header information
      var val;
      val = conn.getContentEncoding();
      if (val != null && !gotContentEncoding) this._headers[this._headers.length] = {h:'Content-encoding', v:val};
      val = conn.getContentLength();
      if (val != -1 && !gotContentLength) this._headers[this._headers.length] = {h:'Content-length', v:val};
      val = conn.getContentType();
      if (val != null && !gotContentType) this._headers[this._headers.length] = {h:'Content-type', v:val};
      val = conn.getDate();
      if (val != 0 && !gotDate) this._headers[this._headers.length] = {h:'Date', v:(new Date(val)).toUTCString()};
      val = conn.getExpiration();
      if (val != 0 && !gotExpiration) this._headers[this._headers.length] = {h:'Expires', v:(new Date(val)).toUTCString()};
      val = conn.getLastModified();
      if (val != 0 && !gotLastModified) this._headers[this._headers.length] = {h:'Last-modified', v:(new Date(val)).toUTCString()};
      // read response data
      var reqdata = '';
      var stream = conn.getInputStream();
      java.lang.System.err.println(stream);
      if (stream) {
        var reader = new java.io.BufferedReader(new java.io.InputStreamReader(stream, this._getCharset()));
        var line;
        while ((line = reader.readLine()) != null) {
          if (this.readyState == 2) {
            this.readyState = 3;
            if (this.onreadystatechange) {
              this.onreadystatechange();
            }
          }
          reqdata += line + '\n';
        }
        reader.close();
        this.status = 200;
        this.statusText = 'OK';
        this.responseText = reqdata;
        this.readyState = 4;
        if (this.onreadystatechange) {
          this.onreadystatechange();
        }
        if (this.onload) {
          this.onload();
        }
      } else {
        // error
        this.status = 404;
        this.statusText = 'Not Found';
        this.responseText = '';
        this.readyState = 4;
        if (this.onreadystatechange) {
          this.onreadystatechange();
        }
        if (this.onerror) {
          this.onerror();
        }
      }
    };
  };
}
// ActiveXObject emulation
if (!window.ActiveXObject && window.XMLHttpRequest) {
  window.ActiveXObject = function(type) {
    switch (type.toLowerCase()) {
      case 'microsoft.xmlhttp':
      case 'msxml2.xmlhttp':
      case 'msxml2.xmlhttp.3.0':
      case 'msxml2.xmlhttp.4.0':
      case 'msxml2.xmlhttp.5.0':
        return new XMLHttpRequest();
    }
    return null;
  };
}    /* Steinhaug Opener v1.0           */
    /* (c) Easy Webshop/ Easy CMS 2008 */
      var swOpener = {
        init: function(){
          var cont = document.getElementById('swOContainer');
          var swTitles = getElementsByClassName('swOTitle','div',cont);
          for (var i = 0, j = swTitles.length; i < j; i++) {
            $(swTitles[i]).down().href = 'javascript:;';
            if($(swTitles[i]).next().className == 'swOOpen'){
              $(swTitles[i]).down().insert({top: '<span class="switch">- lukk -</span>'});
              $(swTitles[i]).down().onclick = function(){
                swOpener.closeit(this);
              }
            } else {
              $(swTitles[i]).down().insert({top: '<span class="switch">+ åpne +</span>'});
              $(swTitles[i]).down().onclick = function(){
                swOpener.openit(this);
              }
            }
          }
        },
        openit: function(el){
          $(el).up().next().className = 'swOOpen';
          $(el).down().innerHTML = '- lukk -';
          Set_Cookie($(el).up().getAttribute('section'),'open',100000);
          el.onclick = function(){
            swOpener.closeit(this);
            //
          }
        },
        closeit: function(el){
          $(el).up().next().className = 'swOClose';
          $(el).down().innerHTML = '+ åpne +';
          Set_Cookie($(el).up().getAttribute('section'),'close',100000);
          el.onclick = function(){
            swOpener.openit(this);
          }
        }
      };
      ELO.functionsToCallOnload.push("swOpener.init()");
// 2008-05-28
// http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "," : dec_point;
    var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
function trim( str, charlist ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
 
    var whitespace;
    
    if(!charlist){
        whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
    } else{
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    }
  
  for (var i = 0; i < str.length; i++) {
    if (whitespace.indexOf(str.charAt(i)) === -1) {
    str = str.substring(i);
    break;
    }
  }
  for (i = str.length - 1; i >= 0; i--) {
    if (whitespace.indexOf(str.charAt(i)) === -1) {
      str = str.substring(0, i + 1);
      break;
      }
  }
  return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    
    var ret = str;
       
    ret = ret.replace(/\+/g, '%20');
    ret = decodeURIComponent(ret);
    ret = ret.toString();
 
    return ret;
}
