// LabAPI
var currPage;
var currPageContainer;
var previousPage;
var vispage;
var globalPage;
var appFileRoot = "Hemsida_2";
var appId = "Startsida";
var appName = "Startsida";
var ext = ".htm";
var ie = document.all ? true : false;
var nav = false;
function versionChecker() {
if (window.opera) {
ie = false;
} else {
  var agt = navigator.userAgent.toLowerCase();
  var appVer = navigator.appVersion.toLowerCase();
  var app = navigator.appName;
  if ((agt.indexOf("mozilla") != -1) || (agt.indexOf("netscape")))
    nav = true;
  if (navigator.platform.indexOf("Mac") != -1)
    ie = false;
  if (!ie)
    setGeckoSpecific();
}
}
 //A swapNode function for mozilla/w3c browsers
 if (window.Node && Node.prototype) {
 Node.prototype.swapNode = function (node) {
 var nextSibling = this.nextSibling;
 var parentNode = this.parentNode;
 node.parentNode.replaceChild(this, node);
 parentNode.insertBefore(node, nextSibling);
 }
 }
function setGeckoSpecific() {
  eval("HTMLElement.prototype.innerText setter = geckoSetInnerText;");
  eval("HTMLElement.prototype.innerText getter = geckoGetInnerText;");
}
function initPage() {
  versionChecker();
  // if (ie) { document.body.scroll = "%SCROLLBARS%"; }
  currPage = document.getElementById("page");
  globalPage = document.getElementById("page");
  vispage = document.getElementById("page");
  if (currPage.childNodes.length > 0) {
    if ((ie) && (currPage.filters.length > 0)) {
      for (var i=0; i < currPage.filters.length; i++) {
        currPage.filters[i].apply();
        currPage.style.visibility = "visible";
        currPage.filters[i].play();
      }
    }
    else
      currPage.style.visibility = "visible";
  }
  if (!ie) {
    document.all = new Array();
    collectAllNodes(document.body);
  }
  var child = document.all;
  //var child = ie ? document.all : document.body.childNodes;
  for (var i = 0; i < child.length; i++) {
    var candidate = child[i];
    setObjectMethods(candidate);
    if (isMediaObject(candidate))
      candidate.copyTo(null);
  }
  for (var i=0; i < vispage.childNodes.length; i++) {
    var child = vispage.childNodes[i];
    if (child.id) {
      if (ie) {
        if (objClassMember(child,"group")) {
          for (var j=0; j < child.childNodes.length; j++) {
            var grandChild = child.childNodes[j];
            setObjectMethods(grandChild);
            if (isMediaObject(grandChild))
              grandChild.copyTo(null);
            playTransition(grandChild);
          }
        }
        else
          playTransition(child);
      }
      else {
        setObjectMethods(child);
        child.oldStyle = new oldStyle(child);
        child.resetStyle = getOldStyle;
        if(child.hasChildren) {
          for (var j=0; j < child.childNodes.length; j++) {
            var grandChild = child.childNodes[j];
            setObjectMethods(grandChild);
            grandChild.oldStyle = new oldStyle(grandChild);
            grandChild.resetStyle = getOldStyle;
            if (objClassMember(child,"group"))
              grandChild.style.visibility = "visible";
          }
        }
        child.style.visibility = "visible";
      }
    }
  }
  setPageHeight();
  currPage.autoStart.run();
}
function setPageHeight() {
  var height = parseInt(ie ? vispage.currentStyle.height : document.defaultView.getComputedStyle(vispage,null).height);
  if ((!height) || (height <= 0)) {
    var totHeight = window.screen.height;
    var child = ie ? vispage.all : vispage.childNodes;
    for (var i=0; i < child.length; i++) {
      var candidate = child[i];
      if (candidate.id) {
        var candHeight = parseInt(ie ? candidate.currentStyle.height : document.defaultView.getComputedStyle(candidate,null).height);
        var candTop = parseInt(ie ? candidate.currentStyle.height : document.defaultView.getComputedStyle(candidate,null).height);
        var tmpHeight = candHeight + candTop;
        if (tmpHeight > totHeight)
          totHeight = tmpHeight;
      }
    }
    vispage.style.height = totHeight + "px";
  }
}
function getObject(id) {
  var ref = document.getElementById(id);
  if (ref)
    return ref
  else
    return document;
}
function visObj(id) {
  var ref;
  var ret = false;
  try {
    return document.getElementById(id) ? true : false;
  }
  catch (e) {
    return false;
  }
}
function deleteObject(id) {
  var obj = getObject(id);
  obj.parentNode.removeChild(obj);
}
function isSoundObject(obj) {
  if (objClassMember(obj,"media")) {
    var mObj = getObject(obj.id + "Object");
    return (mObj.className.match("soundObject"));
  }
  return false;
}
function isMediaObject(obj) {
  return (obj.className ? (obj.className.match("media$") != null) : false);
}
function renderHtmlOnPage(page,src) {
  var re = /id=\"(\w{1,})\"/i;
  var res = re.exec(src);
  var flag = false;
  if ((res != undefined) || (getObject(res[1]) == null)) {
    if (ie)
      vispage.insertAdjacentHTML("beforeEnd",src)
    else
      geckoInsertHTML(vispage,src);
    if (ie)
      playTransition(vispage.lastChild)
    else
      ;//vispage.lastChild.style.visibility = "visible";
    flag = true;
    setObjectMethods(vispage.lastChild);
  }
  return flag;
}
function playTransition(obj) {
  try {
    var vis;
    if ((obj.style.visibility == "visible") && (obj.filters.length > 0))
      vis = "hidden"
    else
      vis = "visible";
    for (var i=0; i < obj.filters.length; i++) {
      if (obj.filters[i] != obj.filters["alpha"]) {
        obj.filters[i].apply();
        obj.style.visibility = vis;
        obj.filters[i].play();
      }
    }
  }
  catch (e) {}
}
function jumpToPage(page) {
  if (page == "TordLarsson")
    document.location.href = appFileRoot + ext
  else
    document.location.href = appFileRoot + page + ext;
}
function historyBack() {
  history.go(-1);
}
function previousPage() {
  jumpToPage(appPreviousPage);
}
function nextPage() {
  jumpToPage(appNextPage);
}
function oldStyle(obj) {
  this.oldClassName = obj.className;
}
function getOldStyle() {
  this.className = "";
  this.style.cssText = "";
  this.className = this.oldStyle.oldClassName;
}
function autoStartObject() {
  this.lines = new Array();
  this.add = autoStartAdd;
  this.run = autoStartRun;
}
function autoStartRun() {
  for (var i=0; i < this.lines.length; i++)
    eval(this.lines[i]);
}
function autoStartAdd(line) {
  this.lines[this.lines.length] = line;
}
function moveMedia(destination) {
  if (!isSoundObject(this))
    this.player.className = "vmediaobject";
  if (this.autostart)
    this.play();
}
function addLoadListener(fn)
{
  if (typeof window.addEventListener != 'undefined')
  {
    window.addEventListener('load', fn, false);
  }
  else if (typeof document.addEventListener != 'undefined')
  {
    document.addEventListener('load', fn, false);
  }
  else if (typeof window.attachEvent != 'undefined')
  {
    window.attachEvent('onload', fn);
  }
  else
  {
    var oldfn = window.onload;
    if (typeof window.onload != 'function')
    {
      window.onload = fn;
    }
    else
    {
      window.onload = function()
      {
        oldfn();
        fn();
      };
    }
  }
}
/*PlayEmbbededSound is used in a temporary solution for cross browser sound for
  TTS converted to wav. It will be removed later.
*/
function PlayEmbeddedSound(soundobj) {
  var thissound=document.getElementById(soundobj);
  if (thissound)
    thissound.Play();
}
/*stopBGSound and playBGSound stops (or restarts) a BackgroundSound added thru
  the BackgroundSound property. Note that a sound cannot be stopped in Opera and
  that it did not work to perform method checks in IE: if (obj.Play) obj.Play() 
*/
function stopBGSound() {
  try {
    if (window.parent.document) {
      obj = window.parent.document.getElementById('LABBGSoundPlayer');
      if (obj)
         obj.Stop(); // does not work in Opera
    }
  }
  finally {
    // silent exception
  }
}
function playBGSound() {
  try {
    if (window.parent.document) {
      obj = window.parent.document.getElementById('LABBGSoundPlayer');
      if (obj)
        if (obj)
          obj.Play();
    }
  }
  finally {
    // silent exception
  }
}
function setObjectMethods(obj) {
  if (obj.id) {
    obj.incWidth = methodIncWidth;
    obj.incHeight = methodIncHeight;
    obj.incLeft = methodIncLeft;
    obj.incTop = methodIncTop;
    obj.rescale = methodRescale;
    obj.getAttr = methodGetAttr;
    obj.setAttr = methodSetAttr;
    obj.oldStyle = new oldStyle(obj);
    obj.resetStyle = getOldStyle;
  }
}
function methodIncWidth(w) {
  var width = ie ? this.currentStyle.width : document.defaultView.getComputedStyle(this, null).width;
  var w2 = parseInt(width) + w;
  if (w2 >= 0)
    this.style.width =  w2 + "px";
}
function methodIncHeight(h) {
  var height = ie ? this.currentStyle.height : document.defaultView.getComputedStyle(this, null).height;
  var h2 = parseInt(height) + h;
  if (h2 >= 0)
    this.style.height = h2 + "px";
}
function methodIncLeft(l) {
  var left = ie ? this.currentStyle.left : document.defaultView.getComputedStyle(this, null).left;
  var l2 = parseInt(left) + l;
  if (l2 >= -32768)
    this.style.left = l2 + "px";
}
function methodIncTop(t) {
  var top = ie ? this.currentStyle.top : document.defaultView.getComputedStyle(this, null).top;
  var t2 = parseInt(top) + t;
  if (t2 >= -32768)
    this.style.top = t2 + "px";
}
function methodRescale(wh) {
  this.incWidth(wh*2);
  this.incHeight(wh*2);
  this.incLeft(-wh);
  this.incTop(-wh);
}
function methodGetAttr(attrName) {
  var attrVal;
  if (visObj(this.id)) {
    try {
      attrVal = eval("this.style." + attrName);
    } catch (e) {}
  }
  return attrVal;
}
function methodSetAttr(attrName, attrVal) {
  if (visObj(this.id)) {
    try {
      eval("this.style."+attrName+" = '"+attrVal+"';");
    } catch (e) {}
  }
}
function getSender() {
  try {
    return (ie ? window.event.srcElement : getObject(event.target));
  } catch (e) {  return null; }
}
function hideObject(object) {
  if ((visObj(object.id)) && (object.style.visibility != "hidden")) {
    if (isMediaObject(object))
      object.stop();
    if (ie) {
      if ((object.filters.length > 0)) {
        object.style.visibility="visible";
        playTransition(object);
      }
      else
        object.style.visibility="hidden";
    }
    else
      object.style.visibility="hidden";
  }
}
function showObject(object) {
  if (visObj(object.id)) {
    if (ie) {
      if ((object.filters.length > 0)) {
        object.style.visibility="hidden";
        object.style.display="block";
        playTransition(object);
      }
      object.style.visibility="visible";
    }
    else {
      object.style.visibility="visible";
      object.style.display="block";
    }
  }
}
function moveToTop(object) {
  if (visObj(object.id)) {
    var z = 0;
    for (var i=0; i < vispage.childNodes.length; i++) {
      try {
        var cZ = vispage.childNodes[i].getAttr("zIndex");
        if (cZ > z)
          z = cZ;
      }
      catch(e) {}
    }
    var zIndex = object.getAttr("zIndex");
    if (zIndex <= z) {
      object.setAttr("oldzIndex", zIndex);
      object.setAttr("zIndex", z + 1);
    }
  }
}
function removeObject(object) {
  try {
    if (visObj(object.id))
      deleteObject(object.id);
  } catch (e) {}
}
function newSize(object, width, height) {
  if (visObj(object.id)) {
    object.style.width = width + "px";
    object.style.height = height + "px";
  }
}
function newPos(object, left, top) {
  if (visObj(object.id)) {
    object.style.left = left + "px";
    object.style.top = top + "px";
  }
}
function redrawPage() {
  if (currPage.id != "page")
    jumpToPage(currPage.id);
  else
    document.location.href = document.location.href;
}
function resetObject(object) {
  if (visObj(object.id))
    object.resetStyle();
}
function changeTextColor(object, color) {
  if (visObj(object.id))
    object.style.color = color;
}
function changeBorderColor(object, color) {
  if (visObj(object.id))
    object.style.borderColor = color;
}
function changeBackgroundColor(object, color) {
  if (visObj(object.id))
    object.style.backgroundColor = color;
}
function changeOpacity(object, msopac, nsopac) {
  if (visObj(object.id)) {
    if (ie)
      object.style.filter += "alpha(opacity=" + msopac + ")";
    else
      object.style.opacity = nsopac / 100;
  }
}
function changeVolume(object, volume) {
  if (isMediaObject(object)) {
    var vol = object.player.settings.volume;
    vol += volume;
    if ((vol >= 0) && (vol <= 100))
      object.player.settings.volume = vol;
  }
}
function changeBalance(object, balance) {
  if (isMediaObject(object)) {
    var bal = object.player.settings.balance;
    bal += balance;
    if ((bal >= -100) && (bal <= 100))
      object.player.settings.balance = bal;
  }
}
function setVolume(object, volume) {
  if (isMediaObject(object))
    object.player.settings.volume = volume;
}
function setBalance(object) {
  if (isMediaObject(object))
    object.player.settings.balance = balance;
}
var pImageList = new Array();
function preloadImage(file) {
  var cnt = pImageList.length;
  pImageList[cnt] = new Image();
  pImageList[cnt].src = file;
}
function geckoSetInnerText(src) {
  var r = this.ownerDocument.createRange();
  r.selectNodeContents(this);
  r.deleteContents();
  var df = r.createContextualFragment(src);
  this.appendChild(df);
  return src;
}
function geckoGetInnerText() {
  var str = "";
  re = /\<.*?\>/g;
  str = this.innerHTML;
  return str.replace(re,'');
}
function collectAllNodes(node) {
  var all = new Array();
  var nodes = node.childNodes;
  for (var i=0; i < nodes.length; i++) {
    if (nodes[i].hasChildNodes())
      collectAllNodes(nodes[i]);
      document.all[document.all.length] = nodes[i];
  }
}
function geckoInsertHTML(node, src) {
  var range = document.createRange();
  range.setStartAfter(node.lastChild);
  var docFrag = range.createContextualFragment(src);
  node.appendChild(docFrag);
}
function objClassMember(obj, cName) {
  return (obj.className ? (obj.className.match(cName) != null) : false);
}
function createMedia(isSound) {
  var str = new String();
  if (ie)
    str = "<object id='" + this.id + "Object' classid='" + this.clsid +
          "' width='" + this.width + "' height='" + this.height + "' class='mtype'>"
  else
    str = "<object id='" + this.id + "Object' type='" + this.type +
          "' data='" + fixURL(this.url) +
          "' width='" + this.width + "' height='" + this.height + "' class='mtype'>";
  for (var i=0; i < this.params.length; i++)
    str += this.params[i];
  str += "</object>";
  if (isSound)
    str = str.replace(/mtype/,"soundObject")
  else
    str = str.replace(/mtype/,"mediaobject");
  if (ie)
    this.insertAdjacentHTML("beforeEnd",str)
  else
    geckoInsertHTML(this,str);
  this.player = document.getElementById(this.id + "Object");
  this.copyTo = moveMedia;
  if (isSound)
    this.player.style.visibility = "hidden";
}
function mediaAddParam(name, value) {
  this.params[this.params.length] =
    "<param name='" + name + "' value='" + value + "'/>";
}
function stopAudioVideo() {
  var pChildren = vispage.childNodes;
  for (var i = (pChildren.length - 1); i >= 0; i--) {
    var child = pChildren[i];
    if (objClassMember(child,"media"))
      child.stop();
  }
}
function fixURL(url) {
  var bref = document.location.href;
  if (bref.match(/^file\:\/\//)) {
    var re = /(\.\.)/g;
    var str = url.match(re);
    if (str) {
      url = url.replace(/\.\.\//g,"");
      var cnt = str.length;
      if (cnt != null) {
        var re = new RegExp("(.*\/)(.*?\/){"+cnt+"}(.*?$)");
        str = re.exec(bref);
        return unescape(str[1] + url);
      }
    }
  }
  return url;
}
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
} else {
elm['on' + evType] = fn;
}
}
var finder;
function NodeListItems(aNode,aStyle) {
  this.node = aNode;
  this.borderWidth = aNode.style.borderWidth;
  this.borderStyle = aNode.style.borderStyle;
  this.borderColor = aNode.style.borderColor;
  this.padding = aNode.style.padding;
  this.HotBorderColor = '#FF0000';
  this.HotBorderWidth = 1;
  this.HotBorderStyle = 'solid';
  this.backgroundColor = aNode.style.backgroundColor;
  this.useBackground = (aNode.nodeName == 'OPTION') || (aNode.nodeName == 'INPUT');
  this.execute = function () {
    if (this.node.nodeName == 'A')
      this.node.click()
    else if (this.node.onclick)
      this.node.onclick()
    else if (this.node.type=='checkbox')
      this.node.checked = (!this.node.checked)
    else if (this.node.nodeName=='OPTION')
      this.node.selected = (!this.node.selected)
    else if (this.node.type=='radio')
      if (!this.node.selected) this.node.click();
  }
  // public methods
  this.HighLights = function() {
    this.node.style.borderWidth = '1px'; //this.HotBorderWidth + 'px';
    this.node.style.borderStyle = 'solid'; //this.HotBorderStyle;
    this.node.style.borderColor = '#FF0000'; //this.HotBorderColor;
    this.node.style.padding = this.node.style.borderWidth;
    this.node.focus();
     if (this.useBackground) {
      this.node.style.backgroundColor = this.HotBorderColor;
      this.node.style.outlineStyle = 'solid';
      this.node.style.outlineWidth = '1px';
      this.node.style.outlineColor = '#FF0000';
    }
  }
  this.resetStyles = function () {
    this.node.style.borderStyle = this.borderStyle;
    this.node.style.borderWidth = this.borderWidth;
    this.node.style.borderColor = this.borderColor;
    this.node.style.padding = this.padding;
    if (this.useBackground) {
      this.node.style.backgroundColor = this.backgroundColor;
      this.node.style.outlineStyle = this.borderStyle;
      this.node.style.outlineWidth = this.borderWidth;
      this.node.style.outlineColor = this.borderColor;
    }
  } // end resetStyles
}
function findNode(node, direction) {
  var ObjectList = new Array();
  var ItemIndex = -1;
  var FHotBorderColor;
  var FHotBorderWidth;
  var FHotBorderStyle;
  // public
  this.CurrentNode = null;
  this.Init = function() {
      // this is needed to access the properties from local function FindSelectableNodes:
      FHotBorderColor = this.HotBorderColor;
      FHotBorderWidth = this.HotBorderWidth;
      FHotBorderStyle = this.HotBorderStyle;
    FindSelectables(node);
    }
  this.next = function next(direction) {
      var l = ObjectList.length;
      if (l > 0) {
      if (direction =='next') {
        if (ItemIndex < l - 1){
          ItemIndex++
        }else{
          ItemIndex = 0;}
          } else if (direction =='execute') {
          ObjectList[ItemIndex].execute();
         } else {
          if (ItemIndex > 0){
          ItemIndex--
          }else{
          ItemIndex = l-1;}
          }
        if (this.CurrentNode)
          this.CurrentNode.resetStyles();
        //alert(ObjectList[ItemIndex].node.id);
        this.CurrentNode = ObjectList[ItemIndex];
        this.CurrentNode.HighLights();
      }
  } // end next
 function FindSelectables(node) {
    var children = node.childNodes;
    for (var i=0; i < children.length; i++)
    {
      var CanSelect = (children[i].onclick) || (children[i].nodeName == 'INPUT') || (children[i].nodeName == 'OPTION') || (children[i].nodeName == 'A');
      if (CanSelect) {
        // add a new item node
        var NewNode = new NodeListItems(children[i], children[i].style);
        NewNode.HotBorderColor = FHotBorderColor;
        NewNode.HotBorderWidth = FHotBorderWidth;
        NewNode.HotBorderStyle  = FHotBorderStyle;
        ObjectList.push(NewNode);
      }
      if ((children[i].className != 'hidden') && (children[i].childNodes.length > 0))
        FindSelectables(children[i]);
    }
  return this;
  }
if (finder == null) {
this.next(direction);
} else {
 finder.next(direction);
 }
}; // end findNode
function findAllNodes(Node,direction) {
  if (finder == null) {
    finder = new findNode(Node,direction);
    if (finder) {
      finder.HotBorderColor = 'red';
      finder.HotBorderWidth = '1px';
      finder.HotBorderStyle = 'solid';
      finder.Init();
    }
  }
};
/**
 * @fileoverview
 * For global vars in multiple pages mode.
 * @author Stefan Cedervall
 */
var LabCache;  // "session" variable
/**
 * @private
 * @constructor
 */
function CachedVar(name,value) {
  /**
   * @private
   * @type string
   */
  this.name = name;
  /** @type string */
  this.value = value;
}
function LabCacheHandler() {
  var VarList = new Array();
  function getItemIndex(name) {
    var result = -1;
    if (VarList) {
      for (var i=0; i < VarList.length; i++) {
        if (VarList[i].name == name) {
          return i;
        }
      }
    }
    return result;
  }
  this.VarByName = function(name) {
    idx = getItemIndex(name);
    if (idx ==-1) {
      obj = new CachedVar(name, "");
      VarList.push(obj);
      return obj;
    }
    else
      return VarList[idx];
  }
}
/** @private */
function VarByName(name) {
  // create the session var if does not exists
  if (!LabCache)
    LabCache = new LabCacheHandler();
  return LabCache.VarByName(name);
}
/**
  * Adds or returns a variable to/from the cache
  * <p>
  * Usage: GlobalVarByName(name).value = value;
  * <br>       value = GlobalVarByName(name).value;
  * @return {@link CachedVar}
 */
function GlobalVarByName(name) {
  if (window.parent.VarByName)
    return window.parent.VarByName(name)
  else
    return VarByName(name);
}
/**************************  GlobalVarByName END *****************************/
// Spritefunktioner:
function createSprite(loopAnimation) {
  this.currentFrame = 0;
  this.loopAnimation = loopAnimation;
  this.animationRunning = false;
  this.play = startSprite;
  this.pause = pauseSprite;
  this.stop = stopSprite;
  this.animateSprite = animateSprite;
  this.loadSprite = loadSprite;
  this.frameCount = this.fileName.length;
  this.loadSprite();
}
function startSprite() {
  if (visObj(this.id)) {
    if (!this.animationRunning) {
      this.animationRunning = true;
      this.timerID = setTimeout('getObject("'+this.id+'").animateSprite();',this.delay[this.currentFrame]);
    }
  }
  else {
     this.timerID = setTimeout('getObject("'+this.id+'").play()',25);
  }
}
function stopSprite() {
  this.animationRunning = false;
  this.currentFrame = 0;
}
function pauseSprite() {
  this.animationRunning = false;
}
function animateSprite() {
  var delay = 0;
  var cur = this.currentFrame;
  if (this.animationRunning) {
    if (cur < this.frameCount) {
      this.src = this.image[cur].src;
      delay = this.delay[cur];
      this.currentFrame++;
      this.timerID = setTimeout('getObject("'+this.id+'").animateSprite();',delay);
    }
    else if (this.loopAnimation) {
      this.currentFrame = 0;
      this.timerID = setTimeout('getObject("'+this.id+'").animateSprite();',delay);
    }
  }
}
function loadSprite() {
  this.image = new Array();
  for (var i=0; i < this.frameCount; i++) {
    this.image[i] = new Image();
    this.image[i].src = this.fileName[i];
  }
}
