
var parseSelector = (function() {
  var SEPERATOR       = /\s*,\s*/
  var WHITESPACE      = /\s*([\s>+~(),]|^|$)\s*/g;
  var IMPLIED_ALL     = /([\s>+~,]|[^(]\+|^)([#.:@])/g;
  var STANDARD_SELECT = /^[^\s>+~]/;
  var STREAM          = /[\s#.:>+~()@]|[^\s#.:>+~()@]+/g;
  
  function parseSelector(selector, node) {
    node = node || document.documentElement;
    var argSelectors = selector.split(SEPERATOR), result = [];
    
    for(var i = 0; i < argSelectors.length; i++) {
      var nodes = [node], stream = toStream(argSelectors[i]);
      for(var j = 0; j < stream.length;) {
        var token = stream[j++], filter = stream[j++], args = '';
        if(stream[j] == '(') {
          while(stream[j++] != ')' && j < stream.length) args += stream[j];
          args = args.slice(0, -1);
        }
        nodes = select(nodes, token, filter, args);
      }
      result = result.concat(nodes);
    }
    
    return result;
  }

  function toStream(selector) {
    var stream = selector.replace(WHITESPACE, '$1').replace(IMPLIED_ALL, '$1*$2');
    if(STANDARD_SELECT.test(stream)) stream = ' ' + stream;
    return stream.match(STREAM) || [];
  }
  
  function select(nodes, token, filter, args) {
    return (parseSelector.selectors[token]) ? parseSelector.selectors[token](nodes, filter, args) : [];
  }
  
  var util = {
    toArray: function(enumerable) {
      var a = [];
      for(var i = 0; i < enumerable.length; i++) a.push(enumerable[i]);
      return a;
    }
  };
  
  var dom = {
    isTag: function(node, tag) {
      return (tag == '*') || (tag.toLowerCase() == node.nodeName.toLowerCase());
    },
  
    previousSiblingElement: function(node) {
      do node = node.previousSibling; while(node && node.nodeType != 1);
      return node;
    },
  
    nextSiblingElement: function(node) {
      do node = node.nextSibling; while(node && node.nodeType != 1);
      return node;
    },
  
    hasClass: function(name, node) {
      return (node.className || '').match('(^|\\s)'+name+'(\\s|$)');
    },
  
    getByTag: function(tag, node) {
      return node.getElementsByTagName(tag);
    }
  };

  var selectors = {
    '#': function(nodes, filter) {
      for(var i = 0; i < nodes.length; i++) {
        if(nodes[i].getAttribute('id') == filter) return [nodes[i]];
      }
      return [];
    },

    ' ': function(nodes, filter) {
      var result = [];
      for(var i = 0; i < nodes.length; i++) {
        result = result.concat(util.toArray(dom.getByTag(filter, nodes[i])));
      }
      return result;
    },
    
    '>': function(nodes, filter) {
      var result = [];
      for(var i = 0, node; i < nodes.length; i++) {
        node = nodes[i];
        for(var j = 0, child; j < node.childNodes.length; j++) {
          child = node.childNodes[j];
          if(child.nodeType == 1 && dom.isTag(child, filter)) result.push(child);
        }
      }
      return result;
    },

    '.': function(nodes, filter) {
      var result = [];
      for(var i = 0, node; i < nodes.length; i++) {
        node = nodes[i];
        if(dom.hasClass([filter], node)) result.push(node);
      }
      return result;
    }, 
        
    ':': function(nodes, filter, args) {
      return (parseSelector.pseudoClasses[filter]) ? parseSelector.pseudoClasses[filter](nodes, args) : [];
    }
    
  };

  parseSelector.selectors     = selectors;
  parseSelector.pseudoClasses = {};
  parseSelector.util          = util;
  parseSelector.dom           = dom;

  return parseSelector;
})();


/*=:project
    scalable Inman Flash Replacement (sIFR) version 3.

  =:file
    Copyright: 2006 Mark Wubben.
    Author: Mark Wubben, <http://novemberborn.net/>

  =:history
    * IFR: Shaun Inman
    * sIFR 1: Mike Davidson, Shaun Inman and Tomas Jogin
    * sIFR 2: Mike Davidson, Shaun Inman, Tomas Jogin and Mark Wubben

  =:documentation
    See <http://wiki.novemberborn.net/sifr3>

  =:license
    This software is licensed and provided under the CC-GNU LGPL.
    See <http://creativecommons.org/licenses/LGPL/2.1/>    
*/

var sIFR = new function() {
  //=:private Constant reference to the Singleton instance
  var SIFR = this;

  var CSS_ACTIVE           = 'sIFR-active';
  var CSS_UNLOADING        = 'sIFR-unloading';
  var CSS_REPLACED         = 'sIFR-replaced';
  var CSS_FLASH            = 'sIFR-flash';
  var CSS_IGNORE           = 'sIFR-ignore';
  var CSS_ALTERNATE        = 'sIFR-alternate';
  var CSS_CLASS            = 'sIFR-class';
  var CSS_LAYOUT           = 'sIFR-layout';
  var CSS_FIX_FOCUS        = 'sIFR-fixfocus'
  var CSS_DUMMY            = 'sIFR-dummy';
  var CSS_ZOOM_DETECT      = 'sIFR-zoomdetect';
  var MIN_FONT_SIZE        = 6;
  var MAX_FONT_SIZE        = 126;
  var MIN_FLASH_VERSION    = 8;
  var PREFETCH_COOKIE      = 'SIFR-PREFETCHED';
  //= Whitespace string each whitespace character is replaced with, as per `preserveSingleWhitespace`.
  var DEFAULT_RATIOS       = [];
  var FLASH_PADDING_BOTTOM = 5;
  var VERSION              = 'beta2';

  this.isActive                 = false;
  this.isEnabled                = true;
  this.preserveSingleWhitespace = false;
  this.fixWrap                  = true;
  this.fixHover                 = true;
  this.autoInitialize           = true;
  this.setPrefetchCookie        = true;
  this.cookiePath               = '/';
  this.domains                  = [];
  this.fromLocal                = false;
  this.forceClear               = false;
  this.forceWidth               = true;
  this.fitExactly               = false;
  this.forceTextTransform       = true;
  this.useDomLoaded             = true;
  this.useStyleCheck            = false;
  this.hasFlashClassSet         = false;
  this.repaintOnResize          = true;
  this.callbacks                = [];
  
  var elementCount = 0; // The number of replaced elements.
  var hasPrefetched = false, isInitialized = false;

  var dom = new function() {
    var XHTML_NS = 'http://www.w3.org/1999/xhtml';
      
    this.getBody = function() {
      var nodes = document.getElementsByTagName('body');
      if(nodes.length == 1) return nodes[0];
      return null;
    };

    this.addClass = function(name, node) {
      if(node) node.className = ((node.className || '') == '' ? '' : node.className + ' ') + name;
    };
    
    this.removeClass = function(name, node) {
      if(node) node.className = node.className.replace(new RegExp('(^|\\s)' + name + '(\\s|$)'), '').replace(/^\s+|(\s)\s+/g, '$1');
    };

    this.hasClass = function(name, node) {
      return new RegExp('(^|\\s)' + name + '(\\s|$)').test(node.className);
    };
    
    this.hasOneOfClassses = function(names, node) {
      for(var i = 0; i < names.length; i++) {
        if(this.hasClass(names[i], node)) return true;
      }
      return false;
    };

    this.create = function(name) {
      if(document.createElementNS) return document.createElementNS(XHTML_NS, name);
      return document.createElement(name);
    };
    
    this.nodeFromHtml = function(html) {
      var temp = this.create('div');
      temp.innerHTML = html;
      return temp.firstChild;
    };
    
    this.getComputedStyle = function(node, property) {
      var result;
      if(document.defaultView && document.defaultView.getComputedStyle) {
        result = document.defaultView.getComputedStyle(node, null)[property];
      } else if(node.currentStyle) result = node.currentStyle[property];
      return result || ''; // Ensuring a string.
    };

    this.getStyleAsInt = function(node, property, requirePx) {
      var value = this.getComputedStyle(node, property);
      if(requirePx && !/px$/.test(value)) return 0;
      
      value = parseInt(value);
      return isNaN(value) ? 0 : value;
    };
    
    this.getWidthFromStyle = function(node) {
      var width = this.getStyleAsInt(node, 'width', ua.ie);
      if(width == 0) {
        var paddingRight  = this.getStyleAsInt(node, 'paddingRight', true);
        var paddingLeft   = this.getStyleAsInt(node, 'paddingLeft', true);
        var borderRight   = this.getStyleAsInt(node, 'borderRightWidth', true);
        var borderLeft    = this.getStyleAsInt(node, 'borderLeftWidth', true);
        width = node.offsetWidth - paddingLeft - paddingRight - borderLeft - borderRight;
      }
      return width;
    };

    this.blurElement = function(element) {
      if (ua.gecko) {
        // This can only be done in Gecko
        element.blur();
        return;
      }
      
      // Move the focus to an input element, and then destroy it.
      var input = dom.create('input');
      input.style.width = '0px';
      input.style.height = '0px';
      element.parentNode.appendChild(input);
      input.focus();
      input.blur();
      input.parentNode.removeChild(input);
    };
    
    this.getDimensions = function(node) {
      var width = node.offsetWidth;
      var height = node.offsetHeight;
      
      if(width == 0 || height == 0) {
        for(var i = 0; i < node.childNodes.length; i++) {
          var child = node.childNodes[i];
          if(child.nodeType != 1) continue;
          width = Math.max(width, child.offsetWidth);
          height = Math.max(height, child.offsetHeight);
        }
      }
      
      return {width: width, height: height};
    };
    
    this.contentIsLink = function(node) {
      var linkFound = false;
      for(var i = 0; i < node.childNodes.length; i++) {
        var child = node.childNodes[i];
        if(child.nodeType == 3 && !child.nodeValue.match(/^\s*$/)) return false;
        else if(child.nodeType != 1) continue;

        var isLink = child.nodeName.toLowerCase() == 'a';
        if(!isLink) return false;
        else linkFound = true;
      }
      return linkFound;
    };
    
    var dom = this;
    this.swf = {
      create: function(builder, fixFocus, id, width, height, src, vars, wmode, backgroundColor) {
        var obj = builder.object(fixFocus, id, src, width, height);
        return builder.params(obj, 'flashvars', vars, 'wmode', wmode, 'bgcolor', backgroundColor, 
                              'allowScriptAccess', 'always', 'quality', 'best');
      },
      
      ie: {
        // fixFocus is not supported for IE.
        object: function(fixFocus, id, src, width, height) {
          return '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="' + id +
           '" width="' + width + '" height="' + height + '" class="' + CSS_FLASH + '">' +
           '<param name="movie" value="' + src + '"></param></object>' +
           // Load in the callback code. Keep the <script> line exactly the same!!! (Yes, IE is that crappy)
           // Thanks to Tom Lee for the tip: <http://tom-lee.blogspot.com/2006/04/dynamically-inserting-fscommand.html>
           '<scr' + 'ipt event=FSCommand(info,args) for=' + id + '>' +
             id + '_DoFSCommand(info, args);' +
           '</' + 'script>' // End like this to prevent syntax error in IE/Mac.
           ;
        },

        params: function(obj) {
          var params = '';
          for(var i = 1; i < arguments.length; i+=2) {
            params += '<param name="' + arguments[i] + '" value="' + arguments[i + 1] + '"></param>';
          }
          return obj.replace(/(<\/object>)/, params + '$1');
        },
        
        insert: function(node, flash) {
          node.innerHTML = flash;
        }
      },

      other: {
        object: function(fixFocus, id, src, width, height) {
          var obj   = dom.create('object');
          var attrs = ['type', 'application/x-shockwave-flash', 'id', id, 'name', id, 'data', src, 
                        'width', width, 'height', height];
          while(attrs.length) obj.setAttribute(attrs.shift(), attrs.shift());
          obj.className = CSS_FLASH;
          
          if(!fixFocus) return obj;
          
          var node = dom.create("div");
          node.className = CSS_FIX_FOCUS;
          node.appendChild(obj);
          return node;
        },

        params: function(obj) {
          for(var i = 1; i < arguments.length; i+=2) {
            if (arguments[i] == 'name') continue;
            var param = dom.create('param');
            param.setAttribute('name', arguments[i]);
            param.setAttribute('value', arguments[i + 1]);
            obj.appendChild(param);
          }
          return obj;
        },
        
        insert: function(node, flash) {
          while (node.firstChild) node.removeChild(node.firstChild);
          node.appendChild(flash);
        }
      }
    };
  };
  this.dom = dom;

  var ua = new function() {
    var ua                = navigator.userAgent.toLowerCase();
    var product           = (navigator.product || '').toLowerCase();

    this.macintosh        = ua.indexOf('mac') > -1;
    this.windows          = ua.indexOf('windows') > -1;
    this.quicktime        = false;

    this.opera            = ua.indexOf('opera') > -1;
    this.konqueror        = product.indexOf('konqueror') > -1;
    this.ie               = false/*@cc_on || true @*/;
    this.ieSupported      = this.ie && !/ppc|smartphone|iemobile|msie\s5\.5/.test(ua)/*@cc_on && @_jscript_version >= 5.5 @*/
    this.ieWin            = this.ie && this.windows/*@cc_on && @_jscript_version >= 5.1 @*/;
    this.windows          = this.windows && (!this.ie || this.ieWin);
    this.ieMac            = this.ie && this.macintosh/*@cc_on && @_jscript_version < 5.1 @*/;
    this.macintosh        = this.macintosh && (!this.ie || this.ieMac);
    this.safari           = ua.indexOf('safari') > -1;
    this.webkit           = ua.indexOf('applewebkit') > -1 && !this.konqueror;
    this.khtml            = this.webkit || this.konqueror;
    this.gecko            = !this.webkit && product == 'gecko';

    this.ieVersion        = this.ie        && /.*msie\s(\d\.\d)/.exec(ua)         ? parseFloat(RegExp.$1) : 0;
    this.operaVersion     = this.opera     && /.*opera(\s|\/)(\d+\.\d+)/.exec(ua) ? parseFloat(RegExp.$2) : 0;
    this.webkitVersion    = this.webkit    && /.*applewebkit\/(\d+).*/.exec(ua)   ? parseFloat(RegExp.$1) : 0;
    this.geckoBuildDate   = this.gecko     && /.*gecko\/(\d{8}).*/.exec(ua)       ? parseFloat(RegExp.$1) : 0;
    this.konquerorMajor   = this.konqueror && /.*konqueror\/(\d).*/.exec(ua)      ? parseFloat(RegExp.$1) : 0;
    this.konquerorMinor   = this.konqueror && /.*khtml\/\d\.(\d).*/.exec(ua)      ? parseFloat(RegExp.$1) : 0;
    this.konquerorSmall   = this.konqueror && /.*khtml\/\d\.\d\.(\d).*/.exec(ua)  ? parseFloat(RegExp.$1) : 0;
    
    this.flashVersion     = 0;
    if(this.ieWin) {
      var axo;
      var stop = false;
      try {
        axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.7');
      } catch(e) {
        // In case the Flash 7 registry key does not exist, we need to test for specific 
        // Flash 6 installs before we can use the general key. 
        // See also <http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/>.
        // Many thanks to Geoff Stearns and Bobby van der Sluis for clarifying the problem and providing
        // examples of non-crashing code.
        try {
          axo                   = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
          this.flashVersion     = 6;
          axo.AllowScriptAccess = 'always';
        } catch(e) { stop = this.flashVersion == 6; }

        if(!stop) try { axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash'); } catch(e) {}
      }

      if(!stop && axo) this.flashVersion = parseFloat(/([\d,?]+)/.exec(axo.GetVariable('$version'))[1].replace(/,/g, '.'));
    } else if(navigator.plugins && navigator.plugins['Shockwave Flash']) {
      var flashPlugin = navigator.plugins['Shockwave Flash'];
      this.flashVersion = parseFloat(/(\d+\.?\d*)/.exec(flashPlugin.description)[1]);

      // Watch out for QuickTime, which could be stealing the Flash handling!
      var i = 0;
      while(this.flashVersion >= MIN_FLASH_VERSION && i < navigator.mimeTypes.length) {
        var mime = navigator.mimeTypes[i];
        if(mime.type == 'application/x-shockwave-flash' && mime.enabledPlugin.description.toLowerCase().indexOf('quicktime') > -1) {
          this.flashVersion = 0;
          this.quicktime = true;
        }
        i++;
      }
    }

    this.flash = this.flashVersion >= MIN_FLASH_VERSION;

    // There are other conditions, but these are ruled out in `computedStyledSupport` or `supported`.
    this.transparencySupport  = this.macintosh || this.windows;

    this.computedStyleSupport = this.ie || document.defaultView && document.defaultView.getComputedStyle 
      && (!this.gecko || this.geckoBuildDate >= 20030624); // Older Geckos have trouble with `getComputedStyle()`
    
    this.requiresPrefetch  = this.ieWin || this.khtml;
    this.fixFocus          = this.gecko && this.windows && this.geckoBuildDate > 20061206;
    this.nativeDomLoaded   = this.gecko || this.webkit && this.webkitVersion >= 525 
                                        || this.konqueror && this.konquerorMajor > 3 || this.opera;
    this.mustCheckStyle    = this.khtml || this.opera;
    this.forcePageLoad     = this.webkit && this.webkit < 523; // Fine in Konqueror 3.5.8, which is required for support.
    this.properDocument    = typeof(document.location) == 'object';

    this.supported         = this.flash && this.properDocument && (!this.ie || this.ieSupported) 
      && (!this.opera/* || this.operaVersion >= 8*/) && (!this.webkit || this.webkitVersion >= 412)
      && (!this.konqueror/* || this.konquerorMajor > 3 || this.konquerorMajor == 3 && (this.konquerorMinor > 5 || this.konquerorMinor == 5 & this.konquerorSmall > 7)*/)
      && this.computedStyleSupport
      && (!this.gecko || this.geckoBuildDate > 20040804); // Had a few reports about Netscape 7.2 crashing, therefore 
                                                          // now requiring a newer Gecko version.

  };
  this.ua = ua;

  var util = new function() {
    var UNIT_REMOVAL_PROPERTIES = {leading: true, 'margin-left': true, 'margin-right': true, 'text-indent': true};
    var SINGLE_WHITESPACE = ' ';
    
    function capitalize($) {
      return $.toUpperCase();
    }
    
    this.normalize = function(str) {
      if(SIFR.preserveSingleWhitespace) return str.replace(/\s/g, SINGLE_WHITESPACE);
      // Replace linebreaks by whitespace, then normalize and make sure no nbsp characters are 
      // preserved as Flash doesn't seem to support them.
      return str.replace(/(\n|\r)+/g, SINGLE_WHITESPACE).replace(/(\s)\s+/g, '$1').replace(/\xA0/, SINGLE_WHITESPACE);
    };
    
    this.textTransform = function(type, str) {
      switch(type) {
        case 'uppercase':
          str = str.toUpperCase();
          break;
        
        case 'lowercase':
          str = str.toLowerCase();
          break;
          
        case 'capitalize':
          var strCopy = str;
          str = str.replace(/^\w|\s\w/g, capitalize);
          if(str.indexOf('function capitalize') != -1) {
            var substrs = strCopy.replace(/(^|\s)(\w)/g, '$1$1$2$2').split(/^\w|\s\w/g);
            str = '';
            for(var i = 0; i < substrs.length; i++) str += substrs[i].charAt(0).toUpperCase() + substrs[i].substring(1);
          }
          break;
      }
      
      return str;
    };
    
    this.toHexString = function(str) {
      if(typeof(str) != 'string' || !str.charAt(0) == '#' || str.length != 4 && str.length != 7) return str;
      
      str = str.replace(/#/, '');
      if(str.length == 3) str = str.replace(/(.)(.)(.)/, '$1$1$2$2$3$3');

      return '0x' + str;
    };

    this.toJson = function(obj) {
      var json = '';

      switch(typeof(obj)) {
        case 'string':
          json = '"' + obj + '"';
          break;
        case 'number':
        case 'boolean':
          json = obj.toString();
          break;
        case 'object':
          json = [];
          for(var prop in obj) {
            if(obj[prop] == Object.prototype[prop]) continue;
            json.push('"' + prop + '":' + util.toJson(obj[prop]));
          }
          json = '{' + json.join(',') + '}';
          break;
      }

      return json;
    };
    
    this.convertCssArg = function(arg) {
      if(!arg) return {};
      if(typeof(arg) == 'object') {
        if(arg.constructor == Array) arg = arg.join('');
        else return arg;
      }

      var obj = {};
      var rules = arg.split('}');

      for(var i = 0; i < rules.length; i++) {
        var $ = rules[i].match(/([^\s{]+)\s*\{(.+)\s*;?\s*/);
        if(!$ || $.length != 3) continue;

        if(!obj[$[1]]) obj[$[1]] = {};

        var properties = $[2].split(';');
        for(var j = 0; j < properties.length; j++) {
          var $2 = properties[j].match(/\s*([^:\s]+)\s*\:\s*([^;]+)/);
          if(!$2 || $2.length != 3) continue;
          obj[$[1]][$2[1]] = $2[2].replace(/\s+$/, '');
        }
      }

      return obj;
    };

    this.extractFromCss = function(css, selector, property, remove) {
      var value = null;

      if(css && css[selector] && css[selector][property]) {
        value = css[selector][property];
        if(remove) delete css[selector][property];
      }

      return value;
    };
    
    this.cssToString = function(arg) {
      var css = [];
      for(var selector in arg) {
        var rule = arg[selector];
        if(rule == Object.prototype[selector]) continue;

        css.push(selector, '{');
        for(var property in rule) {
          if(rule[property] == Object.prototype[property]) continue;
          var value = rule[property];
          if(UNIT_REMOVAL_PROPERTIES[property]) value = parseInt(value, 10);
          css.push(property, ':', value, ';');
        }
        css.push('}');
      }

      return css.join('');
    };

    this.bind = function(scope, method) {
      return function() {
        scope[method].apply(scope, arguments);
      };
    };

    this.escape = function(str) {
      return escape(str).replace(/\+/g, '%2B');
    };
    
    this.copyProperties = function(from, to) {
      for(var property in from) {
        if(to[property] === undefined) to[property] = from[property];
      }
      return to;
    };
    
    this.domain = function() {
      var domain = '';
      try { // When trying to access document.domain on a Google-translated page with Firebug, I got an exception.
        domain = document.domain;
      } catch(e) {};
      return domain;
    };
    
    this.domainMatches = function(domain, match) {
      if(match == '*' || match == domain) return true;

      var wildcard = match.lastIndexOf('*');
      if(wildcard > -1) {
        match = match.substr(wildcard + 1);
        var matchPosition = domain.lastIndexOf(match);
        if(matchPosition > -1 && (matchPosition + match.length) == domain.length) return true;
      }
      
      return false;
    };
    
    this.uriEncode = function(s) {
      return encodeURI(decodeURIComponent(s));  // Decode first, in case the URI was already encoded.
    }
  };
  this.util = util;

  var hacks = {};
  hacks.fragmentIdentifier = new function() {
    this.fix = true;

    var cachedTitle;
    this.cache = function() {
      cachedTitle = document.title;
    };

    function doFix() {
      document.title = cachedTitle;
    }

    this.restore = function() {
      if(this.fix) setTimeout(doFix, 0);
    };
  };
  this.hacks = {fragmentIdentifier: hacks.fragmentIdentifier};

  hacks.pageLoad = new function() {
    var dummy = null;
    
    function pollLoad() {
      try {
        // IE hack courtesy of Diego Perini – <http://javascript.nwbox.com/IEContentLoaded/>.
        // Merged polling taken from jQuery – <http://dev.jquery.com/browser/trunk/jquery/src/event.js>
        if(ua.ie || document.readyState != 'loaded' && document.readyState != 'complete') {
          document.documentElement.doScroll('left');
        }
      } catch(e) {
        return setTimeout(pollLoad, 10);
      }
      afterDomLoad();
    };
    
    function afterDomLoad() {
      if(SIFR.useStyleCheck) checkStyle();
      else if(!ua.mustCheckStyle) fire(null, true);
    };
    
    function checkStyle() {
      dummy           = dom.create("div");
      dummy.className = CSS_DUMMY;
      dom.getBody().appendChild(dummy);
      pollStyle();
    };
    
    function pollStyle() {
      if(dom.getComputedStyle(dummy, 'marginLeft') == '42px') afterStyle();
      else setTimeout(pollStyle, 10);
    };
    
    function afterStyle() {
      if(dummy && dummy.parentNode) dummy.parentNode.removeChild(dummy);
      dummy = null;
      fire(null, true);
    };
    
    function fire(evt, preserveReplacements) {
      SIFR.initialize(preserveReplacements);

      // Remove handlers to prevent memory leak in Firefox 1.5, but only after onload.
      if(evt && evt.type == 'load') {
        if(document.removeEventListener) document.removeEventListener('DOMContentLoaded', fire, false);
        if(window.removeEventListener) window.removeEventListener('load', fire, false);
      }
    };
    
    this.attach = function() {
      if(window.addEventListener) window.addEventListener('load', fire, false);
      else window.attachEvent('onload', fire);

      if(!SIFR.useDomLoaded || ua.forcePageLoad || ua.ie && window.top != window) return;
      
      if(ua.nativeDomLoaded) {
        document.addEventListener('DOMContentLoaded', afterDomLoad, false);
      } else if(ua.ie || ua.khtml) {
        pollLoad();
      } 
    };
  };

  hacks.zoom = new function() {
    var element, lastOffset;
    
    function detect() {
      if(element.offsetLeft != lastOffset) {
        lastOffset = element.offsetLeft;
        resize(null, true);
      }
    }
    
    this.init = function() {
      if(!ua.ie || ua.ieVersion < 7) return;

      element = dom.create('div');
      element.className = CSS_ZOOM_DETECT;
      element.style.cssText = 'display:block;width:auto;position:absolute;left:10%;top:-100px;';
      dom.getBody().appendChild(element);
      lastOffset = element.offsetLeft;
      setInterval(detect, 200);
    };
  };

  this.errors = {
    fire: function(id) {
      if(this[id + 'Alert']) alert(this[id + 'Alert']);
      throw new Error(this[id]);
    },
    isFile:      'sIFR: Did not activate because the page is being loaded from the filesystem.',
    isFileAlert: 'Hi!\n\nThanks for using sIFR on your page. Unfortunately sIFR couldn\'t activate, because it was loaded '
                  + 'directly from your computer.\nDue to Flash security restrictions, you need to load sIFR through a web'
                  + ' server.\n\nWe apologize for the inconvenience.',
    getSource:   'sIFR: Could not determine appropriate source'
  };

  var replaceKwargsStore = {
    kwargs: [],
    replaceAll:  function(preserve) {
      for(var i = 0; i < this.kwargs.length; i++) SIFR.replace(this.kwargs[i]);
      if(!preserve) this.kwargs = [];
    }
  };

  // The goal here is not to prevent usage of the Flash movie, but running sIFR on possibly translated pages
  function isValidDomain() {
    if(SIFR.domains.length == 0) return true;

    var domain = util.domain();

    for(var i = 0; i < SIFR.domains.length; i++) {
      var match = SIFR.domains[i];
      if(util.domainMatches(domain, match)) return true;
    }

    return false;
  }

  function isFile() {
    if(!SIFR.fromLocal && document.location.protocol == 'file:') {
      if(SIFR.debug) SIFR.errors.fire('isFile');
      return true;
    }
    return false;
  }

  function resize(evt, force) {
    var viewport = force ? {} : resize.viewport;
    resize.viewport = {
      width: window.innerWidth || document.documentElement.clientWidth || dom.getBody().clientWidth,
      height: window.innerHeight || document.documentElement.clientHeight || dom.getBody().clientHeight
    };

    if(viewport && resize.viewport.width == viewport.width && resize.viewport.height == viewport.height) {
      return;
    }

    if(resize.timer) clearTimeout(resize.timer);
    resize.timer = setTimeout(function() {
      delete resize.timer;
      for(var i = 0; i < SIFR.callbacks.length; i++) SIFR.callbacks[i].resize();
    }, 200);
  }

  function scale() {
    for(var i = 0; i < SIFR.callbacks.length; i++) SIFR.callbacks[i].call('scale');
  }

  this.activate = function(/* … */) {
    if(!ua.supported || !this.isEnabled || this.isActive || !isValidDomain() || isFile()) return;
    if(arguments.length > 0) this.prefetch.apply(this, arguments);

    this.isActive = true;
    this.setFlashClass();

    hacks.fragmentIdentifier.fix = ua.ieWin && hacks.fragmentIdentifier.fix && window.location.hash != ''
    if(hacks.fragmentIdentifier.fix) hacks.fragmentIdentifier.cache();

    if(!this.autoInitialize) return;
    
    hacks.pageLoad.attach();

    if(ua.ie) {
      window.attachEvent('onunload', function() {
        dom.addClass(CSS_UNLOADING, document.documentElement);
      });
    }
  };

  this.setFlashClass = function() {
    if(this.hasFlashClassSet) return;

    dom.addClass(CSS_ACTIVE, dom.getBody() || document.documentElement);
    this.hasFlashClassSet = true;
  };

  this.removeFlashClass = function() {
    if(!this.hasFlashClassSet) return;

    dom.removeClass(CSS_ACTIVE, dom.getBody());
    dom.removeClass(CSS_ACTIVE, document.documentElement);
    this.hasFlashClassSet = false;
  }

  this.initialize = function(preserveReplacements) {
    if(!this.isActive || !this.isEnabled) return;
    if(isInitialized) {
      if(!preserveReplacements) replaceKwargsStore.replaceAll(false);
      return;
    }

    isInitialized = true;
    replaceKwargsStore.replaceAll(preserveReplacements);
    if(SIFR.repaintOnResize) {
      if(window.addEventListener) {
        window.addEventListener('resize', resize, false);
        window.addEventListener('scroll', scale, false);
      } else {
        window.attachEvent('onresize', resize);
        window.attachEvent('onscroll', scale);
      }
      
      hacks.zoom.init();
    }
    clearPrefetch();
  };

  function getSource(src) {
    if(typeof(src) != 'string') {
      // This is a niciety to allow you to create general configuration objects
      // for the prefetch as well as the replacement. You could create constructs
      // like `{src: {src: { /*....*/ }}}`, but that's not really a problem.
      if(src.src) src = src.src;

      // It might be a string now...
      if(typeof(src) != 'string') {
        var versions = [];
        for(var version in src) if(src[version] != Object.prototype[version]) versions.push(version);
        versions.sort().reverse();

        var result = '';
        var i = -1;
        while(!result && ++i < versions.length) {
          if(parseFloat(versions[i]) <= ua.flashVersion) result = src[versions[i]];
        }
        
        src = result;
      }
    }
    
    if(!src && SIFR.debug) SIFR.errors.fire('getSource');
    
    // Some IE installs refuse to show the Flash unless it gets the really absolute
    // URI of the file. I haven't been able to reproduce this behavior but let's
    // ensure a full URI none the less. This turns `/foo.swf` in `http://example.com/foo.swf`.
    if(ua.ie && src.charAt(0) == '/') {
      src = window.location.toString().replace(/([^:]+)(:\/?\/?)([^\/]+).*/, '$1$2$3') + src;
    }
    
    return src;
  }

  this.prefetch = function(/* … */) {
    if((!ua.requiresPrefetch && !this.isActive) || !ua.supported || !this.isEnabled || !isValidDomain()) return;
    if(this.setPrefetchCookie && new RegExp(';?' + PREFETCH_COOKIE + '=true;?').test(document.cookie)) return;

    try { // We don't know which DOM actions the user agent will allow
      hasPrefetched = true;

      if(ua.ieWin) prefetchIexplore(arguments);
      else prefetchLight(arguments);

      if(this.setPrefetchCookie) document.cookie = PREFETCH_COOKIE + '=true;path=' + this.cookiePath;
    } catch(e) { if(SIFR.debug) throw e; }
  };

  function prefetchIexplore(args) {
    for(var i = 0; i < args.length; i++) {
      document.write('<script defer type="sifr/prefetch" src="' + getSource(args[i]) + '"></script>');
    }
  }

  function prefetchLight(args) {
    for(var i = 0; i < args.length; i++) new Image().src = getSource(args[i]);
  }

  function clearPrefetch() {
    if(!ua.ieWin || !hasPrefetched) return;

    try {
      var nodes = document.getElementsByTagName('script');
      for(var i = nodes.length - 1; i >= 0; i--) {
        var node = nodes[i];
        if(node.type == 'sifr/prefetch') node.parentNode.removeChild(node);
      }
    } catch(e) {}
  }

  // Gives a font-size to required vertical space ratio
  function getRatio(size, ratios) {
    for(var i = 0; i < ratios.length; i += 2) {
      if(size <= ratios[i]) return ratios[i + 1];
    }
    return ratios[ratios.length - 1] || 1;
  }

  function getFilters(obj) {
    var filters = [];
    for(var filter in obj) {
      if(obj[filter] == Object.prototype[filter]) continue;

      var properties = obj[filter];
      filter = [filter.replace(/filter/i, '') + 'Filter'];

      for(var property in properties) {
        if(properties[property] == Object.prototype[property]) continue;
        filter.push(property + ':' + util.escape(util.toJson(util.toHexString(properties[property]))));
      }

      filters.push(filter.join(','));
    }

    return util.escape(filters.join(';'));
  }
  
  function calculate(node) {
    var lineHeight, lines;
    if(!ua.ie) { //:=todo Only do once for each selector?
      lineHeight = dom.getStyleAsInt(node, 'lineHeight');
      lines = Math.floor(dom.getStyleAsInt(node, 'height') / lineHeight);
    } else if(ua.ie) {
      // IE returs computed style in the original units, which is quite useless.
      // Therefore we'll only use the fontSize if it's in pixel units, otherwise we'll approximate.
      var fontSize = dom.getComputedStyle(node, 'fontSize');
      if(fontSize.indexOf('px') > 0) {
        lineHeight = parseInt(fontSize);
      } else {
        var html = node.innerHTML;

        // Without these settings, we won't be able to get the rects properly. getClientRects()
        // won't work on elements having layout or that are hidden.
        node.style.visibility  = 'visible';
        node.style.overflow    = 'visible';
        node.style.position    = 'static';
        node.style.zoom        = 'normal';
        node.style.writingMode = 'lr-tb';
        node.style.width       = node.style.height = 'auto';
        node.style.maxWidth    = node.style.maxHeight = node.style.styleFloat  = 'none';
      
        var rectNode = node;
        var hasLayout = node.currentStyle.hasLayout;
        if(hasLayout) {
          node.innerHTML = '<div class="' + CSS_LAYOUT + '">X<br />X<br />X</div>';
          rectNode = node.firstChild;
        } else node.innerHTML = 'X<br />X<br />X';

        var rects = rectNode.getClientRects();
        lineHeight = rects[1].bottom - rects[1].top;

        // In IE, the lineHeight is about 1.25 times the height in other browsers.
        lineHeight = Math.ceil(lineHeight * 0.8);

        if(hasLayout) {
          node.innerHTML = '<div class="' + CSS_LAYOUT + '">' + html + '</div>';
          rectNode = node.firstChild;
        } else node.innerHTML = html;
        rects = rectNode.getClientRects();
        lines = rects.length;

        if(hasLayout) node.innerHTML = html;

        // By setting an empty string, the values will fall back to those in the (non-inline) CSS.
        // When that CSS changes, the changes are reflected here. Setting explicit values would break
        // that behaviour.
        node.style.visibility = node.style.width = node.style.height = node.style.maxWidth 
                              = node.style.maxHeight = node.style.overflow = node.style.styleFloat
                              = node.style.position = node.style.zoom = node.style.writingMode 
                              = '';
      }
    }
    
    return {lineHeight: lineHeight, lines: lines};
  }
  
  this.replace = function(kwargs, mergeKwargs) {
    if(!ua.supported) return;
    
    // This lets you specify to kwarg objects so you don't have to repeat common settings.
    // The first object will be merged with the second, while properties in the second 
    // object have priority over those in the first. The first object is unmodified
    // for further use, the resulting second object will be used in the replacement.
    if(mergeKwargs) kwargs = util.copyProperties(kwargs, mergeKwargs);

    if(!isInitialized) return replaceKwargsStore.kwargs.push(kwargs);
    
    if(SIFR.onReplacementStart) SIFR.onReplacementStart(kwargs);

    var nodes = kwargs.elements;
    if(!nodes && parseSelector) nodes = parseSelector(kwargs.selector);
    if(nodes.length == 0) return;

    var src = getSource(kwargs.src);
    var css = util.convertCssArg(kwargs.css);
    var filters = getFilters(kwargs.filters);
    
    var forceClear      = (kwargs.forceClear == null) ? SIFR.forceClear : kwargs.forceClear;
    var fitExactly      = (kwargs.fitExactly == null) ? SIFR.fitExactly : kwargs.fitExactly;
    var forceWidth      = fitExactly || (kwargs.forceWidth == null ? SIFR.forceWidth : kwargs.forceWidth);
    var preventWrap     = !!(kwargs.preventWrap && !kwargs.forceSingleLine);

    var leading         = parseInt(util.extractFromCss(css, '.sIFR-root', 'leading')) || 0;
    var fontSize        = util.extractFromCss(css, '.sIFR-root', 'font-size', true) || 0;
    var backgroundColor = util.extractFromCss(css, '.sIFR-root', 'background-color', true) || '#FFFFFF';
    var kerning         = util.extractFromCss(css, '.sIFR-root', 'kerning', true) || '';
    var gridFitType     = kwargs.gridFitType || util.extractFromCss(css, '.sIFR-root', 'text-align') == 'right' ? 'subpixel' : 'pixel';
    var textTransform   = SIFR.forceTextTransform ? util.extractFromCss(css, '.sIFR-root', 'text-transform', true) || 'none' : 'none';
    var opacity         = util.extractFromCss(css, '.sIFR-root', 'opacity', true) || '100';
    var cursor          = util.extractFromCss(css, '.sIFR-root', 'cursor', true) || 'default';
    var pixelFont       = kwargs.pixelFont || false;
    var ratios          = kwargs.ratios || DEFAULT_RATIOS;
    var tuneHeight      = parseInt(kwargs.tuneHeight) || 0;
    var events          = !!kwargs.onRelease || !!kwargs.onRollOver || !!kwargs.onRollOut;

    if(parseInt(fontSize).toString() != fontSize && fontSize.indexOf('px') == -1) fontSize = 0; // We only support pixel sizes
    else fontSize = parseInt(fontSize);
    if(parseFloat(opacity) < 1) opacity = 100 * parseFloat(opacity); // Make sure to support percentages and decimals

    var cssText = '';
    // Alignment is handled by the browser in this case.
    if(fitExactly) util.extractFromCss(css, '.sIFR-root', 'text-align', true);
    if(!kwargs.modifyCss) cssText = util.cssToString(css);

    var wmode = kwargs.wmode || '';
    if(!wmode) {
      if(kwargs.transparent) wmode = 'transparent';
      else if(kwargs.opaque) wmode = 'opaque';
    } 
    if(wmode == 'transparent') {
      if(!ua.transparencySupport) wmode = 'opaque';
      else backgroundColor = 'transparent';
    }

    for(var i = 0; i < nodes.length; i++) {
      var node = nodes[i];

      if(dom.hasOneOfClassses([CSS_REPLACED, CSS_IGNORE, CSS_ALTERNATE], node)) continue;

      // Opera does not allow communication with hidden Flash movies. Visibility is tackled by sIFR itself, but
      // `display:none` isn't. Additionally, WebKit does not return computed style information for elements with
      // `display:none`. We'll prevent elements which have `display:none` or are contained in such an element from
      // being replaced. It's a bit hard to detect this, but we'll check for the dimensions of the element and it's
      // `display` property.

      var dimensions = dom.getDimensions(node);

      var height     = dimensions.height;
      var width      = dimensions.width;
      var display    = dom.getComputedStyle(node, 'display');

      if(!height || !width || display == null || display == 'none') continue;

      if(forceClear && ua.gecko) node.style.clear = 'both';

      // If the text doesn't wrap nicely, the width becomes too large and Flash
      // can't adjust for it. By setting the text to just "X" we can be sure
      // we get the correct width.
      var html = null;
      if(SIFR.fixWrap && ua.ie && display == 'block') {
        html = node.innerHTML;
        node.innerHTML = 'X';
      }

      // Get the width (again to approximate the final size). The computed width
      // may not be a pixel unit in IE, in which case we try to calculate using
      // padding and borders and the offsetWidth.
      width = dom.getWidthFromStyle(node);

      if(html && SIFR.fixWrap && ua.ie) node.innerHTML = html;

      var lineHeight, lines;
      if(!fontSize) {
        var calculation = calculate(node);
        lineHeight      = Math.min(MAX_FONT_SIZE, Math.max(MIN_FONT_SIZE, calculation.lineHeight));
        if(pixelFont) lineHeight = Math.max(8, 8 * Math.round(lineHeight / 8));

        lines = calculation.lines;
        if(isNaN(lines) || !isFinite(lines) || lines == 0) lines = 1;

        if(lines > 1 && leading) height += Math.round((lines - 1) * leading);
      } else {
        lineHeight = fontSize;
        lines      = 1;
      }

      height = Math.round(lines * lineHeight);

      // We have all the info we need, reset the display setting now.
      if(forceClear && ua.gecko) node.style.clear = '';

      // I wanted to use `noembed` here, but unfortunately FlashBlock only works with `span.sIFR-alternate`
      var alternate = dom.create('span');
      alternate.className = CSS_ALTERNATE;

      // Clone the original content to the alternate element.
      var contentNode = node.cloneNode(true);
      // Temporarily append the contentNode to the document, to get around IE problems with resolved hrefs
      node.parentNode.appendChild(contentNode);

      for(var j = 0, l = contentNode.childNodes.length; j < l; j++) {
        alternate.appendChild(contentNode.childNodes[j].cloneNode(true));
      }

      // Allow the sIFR content to be modified
      if(kwargs.modifyContent) kwargs.modifyContent(contentNode, kwargs.selector);
      if(kwargs.modifyCss) cssText = kwargs.modifyCss(css, contentNode, kwargs.selector);

      var fixHover = SIFR.fixHover && dom.contentIsLink(contentNode);
      var content = handleContent(contentNode, textTransform, kwargs.uriEncode);

      // Remove the contentNode again
      contentNode.parentNode.removeChild(contentNode);

      if(kwargs.modifyContentString) content.text = kwargs.modifyContentString(content.text, kwargs.selector);
      if(content.text == '') continue;
      
      // Approximate the final height to avoid annoying movements of the page
      var renderHeight = Math.round(lines * getRatio(lineHeight, ratios) * lineHeight) + FLASH_PADDING_BOTTOM + tuneHeight;
      var forcedWidth = forceWidth ? width : '100%';
      
      var vars = ['content=' + util.escape(content.text), 'antialiastype=' + (kwargs.antiAliasType || ''),
                  'width=' + width, 'height=' + height, 'renderheight=' + renderHeight, 'fitexactly=' + fitExactly,
                  'tunewidth=' + (kwargs.tuneWidth || 0), 'tuneheight=' + tuneHeight,
                  'offsetleft=' + (kwargs.offsetLeft || ''), 'offsettop=' + (kwargs.offsetTop || ''),
                  'thickness=' + (kwargs.thickness || ''), 'sharpness=' + (kwargs.sharpness || ''),
                  'kerning=' + kerning, 'gridfittype=' + gridFitType, 'flashfilters=' + filters,
                  'opacity=' + opacity, 'blendmode=' + (kwargs.blendMode || ''), 'size=' + lineHeight,
                  'css=' + util.escape(cssText), 'selectable=' + (kwargs.selectable == null ? 'true' : kwargs.selectable),
                  'fixhover=' + fixHover, 'preventwrap=' + preventWrap, 'forcesingleline=' + (kwargs.forceSingleLine === true),
                  'link=' + util.escape(content.primaryLink[0] || ''), 'target=' + util.escape(content.primaryLink[1] || ''),
                  'events=' + events, 'cursor=' + cursor, 'version=' + VERSION];
      var encodedVars = encodeVars(vars);

      var callbackName = 'sIFR_callback_' + elementCount++;
      var callbackInfo = new CallbackInfo(callbackName, vars, forceWidth, {
        onReplacement: kwargs.onReplacement,
        onRollOver: kwargs.onRollOver,
        onRollOut: kwargs.onRollOut,
        onRelease: kwargs.onRelease
      });
      window[callbackName + '_DoFSCommand'] = (function(callbackInfo) {
        return function(info, arg) {
          callbackInfo.handle(info, arg);
        }
      })(callbackInfo);
      alternate.setAttribute('id', callbackName + '_alternate');

      var builder = ua.ie ? dom.swf.ie : dom.swf.other;
      var flash = dom.swf.create(builder, ua.fixFocus && kwargs.fixFocus, callbackName, 
                                  forcedWidth, renderHeight, src, encodedVars, wmode, backgroundColor);
      builder.insert(node, flash);

      callbackInfo.html = flash;
      SIFR.callbacks.push(callbackInfo);
      if(kwargs.selector) {
        if(!SIFR.callbacks[kwargs.selector]) SIFR.callbacks[kwargs.selector] = [callbackInfo];
        else SIFR.callbacks[kwargs.selector].push(callbackInfo);
      }
      node.appendChild(alternate);
      dom.addClass(CSS_REPLACED, node);
    }

    hacks.fragmentIdentifier.restore();
  };

  this.getCallbackByFlashElement = function(node) {
    for(var i = 0; i < SIFR.callbacks.length; i++) {
      if(SIFR.callbacks[i].id == node.getAttribute('id')) return SIFR.callbacks[i];
    }
  };
  
  this.redraw = function() {
    for(var i = 0; i < SIFR.callbacks.length; i++) SIFR.callbacks[i].resetMovie();
  };
  
  function encodeVars(vars) {
    return vars.join('&').replace(/%/g, '%25');
  }

  /*=:private
    Walks through the childNodes of `source`. Generates a text representation of these childNodes.

    Returns:
    * string: the text representation.

    Notes:
    * A number of items are still to do. See the individual comments for that.
    * This method does not recursion because it'll be necessary to keep a 
      count of all links and their URIs. This is easier without recursion.
  */
  function handleContent(source, textTransform, uriEncode) {
    uriEncode = uriEncode || util.uriEncode;
    var stack = [], content = [], primaryLink = [];
    var nodes = source.childNodes;

    var i = 0;
    while(i < nodes.length) {
      var node = nodes[i];

      if(node.nodeType == 3) {
        var text = util.normalize(node.nodeValue);
        text = util.textTransform(textTransform, text);
        // Escape < characters because they'll mess with the HTML rendering inside Flash.
        text = text.replace(/</g, '&lt;');
        content.push(text);
      }

      if(node.nodeType == 1) {
        var attributes = [];
        var nodeName = node.nodeName.toLowerCase();

        var className = node.className || '';
        // If there are multiple classes, look for the specified sIFR class
        if(/\s+/.test(className)) {
          if(className.indexOf(CSS_CLASS) > -1) className = className.match('(\\s|^)' + CSS_CLASS + '-([^\\s$]*)(\\s|$)')[2];
          // or use the first class
          else className = className.match(/^([^\s]+)/)[1];
        }
        if(className != '') attributes.push('class="' + className + '"');

        if(nodeName == 'a') {
          var href = uriEncode(node.getAttribute('href') || '');
          var target = node.getAttribute('target') || '';
          attributes.push('href="' + href + '"', 'target="' + target + '"');
          
          if(primaryLink.length == 0) primaryLink = [href, target];
        }

        content.push('<' + nodeName + (attributes.length > 0 ? ' ' : '') + attributes.join(' ') + '>');

        if(node.hasChildNodes()) {
          // Push the current index to the stack and prepare to iterate
          // over the childNodes.
          stack.push(i);
          i = 0;
          nodes = node.childNodes;
          continue;
        } else if(!/^(br|img)$/i.test(node.nodeName)) content.push('</', node.nodeName.toLowerCase(), '>');
      }

      if(stack.length > 0 && !node.nextSibling) {
        // Iterating the childNodes has been completed. Go back to the position
        // before we started the iteration. If that position was the last child,
        // go back even further.
        do {
          i = stack.pop();
          nodes = node.parentNode.parentNode.childNodes;
          node = nodes[i];
          if(node) content.push('</', node.nodeName.toLowerCase(), '>');
        } while(i == nodes.length - 1 && stack.length > 0);
      }

      i++;
    }
  
    return {text: content.join('').replace(/\n|\r/g, ''), primaryLink: primaryLink};
  }

  function CallbackInfo(id, vars, forceWidth, events) {
    this.id                     = id;
    this.vars                   = vars;
    this._events                = events;
    this._forceWidth            = forceWidth;
    this._firedReplacementEvent = !(events.onReplacement != null);
    // Type of value depends on SWF builder. This could use some improvement!
    this.html                   = null;
  }
  
  CallbackInfo.prototype.getFlashElement = function() {
    return document.getElementById(this.id);
  };

  CallbackInfo.prototype.available = function() {
    var flashNode = this.getFlashElement();
    return flashNode && flashNode.parentNode;
  };

  CallbackInfo.prototype.handle = function(info, arg) {
    if(!this.available()) return;
    
    switch(/(FSCommand\:)?(.+)/.exec(info)[2]) {
      case 'resize':
        var flashNode = this.getFlashElement();
        
        var $ = arg.split(/\:|,/);
        flashNode.setAttribute($[0], $[1]);
        if($.length > 2) flashNode.style[$[2]] = $[3] + 'px';
      
        // Here comes another story!
        //
        // Good old Safari (saw this in 2.0.3) does not see the resizing
        // of the Flash movie as requiring a repaint of the document. Because
        // of this, the movie won't be resized unless Safari is forced to.
        // This is done by requesting the `offsetHeight` on the Flash node.
        //
        // Just to be sure this hack is applied to all browsers which
        // implement the KHTML engine.
        if(ua.khtml) var repaint = flashNode.offsetHeight;
      
        if(!this._firedReplacementEvent) {
          this._events.onReplacement(this);
          this._firedReplacementEvent = true;
        }
        break;
      case 'resetmovie':
        this.resetMovie();
        break;
      case 'blur':
        dom.blurElement(this.getFlashElement());
        break;
      case 'event':
        if(this._events[arg]) this._events[arg](this);
        break;
      default:
        if(this.debugHandler && /(FSCommand\:)?debug/.test(info)) this.debugHandler(info, arg);
    }
  };
  
  CallbackInfo.prototype.call = function(type, value) {
    if(!this.available()) return false;

    var flashNode = this.getFlashElement();
    try {
      flashNode.SetVariable('callbackType', type);
      flashNode.SetVariable('callbackValue', value);
      flashNode.SetVariable('callbackTrigger', true);
    } catch(e) {
      return false;
    }
    
    return true;
  };

  // `content` must not be util.escaped when passed in.
  // alternate may be an array of nodes to be appended to the alternate content, use this
  // in XHTML documents.
  CallbackInfo.prototype.replaceText = function(content, alternate) {
    var escapedContent = util.escape(content);
    this.updateVars('content', escapedContent);
    if(this.call('replacetext', escapedContent)) {
      var node = this.getAlternate();
      if(alternate) {
        while(node.firstChild) node.removeChild(node.firstChild);
        for(var i = 0; i < alternate.length; i++) node.appendChild(alternate[i]);
      } else {
        try { node.innerHTML = content; } catch(e) {};
      }
      return true;
    }
    return false;
  };
  
  CallbackInfo.prototype.updateVars = function(name, value) {
    for(var i = 0; i < this.vars.length; i++) {
      if (this.vars[i].split('=')[0] == name)
      {
        this.vars[i] = name + '=' + value;
        break;
      }
    }
  };
  
  CallbackInfo.prototype.resetMovie = function() {
    if(!this.available()) return;

    var flashNode = this.getFlashElement();
    var node = flashNode.parentNode;

    var vars = encodeVars(this.vars);
    if(ua.ie) {
      this.html = this.html.replace(/(flashvars(=|\"\svalue=)\")[^\"]+/, '$1' + vars);
      node.replaceChild(dom.nodeFromHtml(this.html), flashNode);
    } else {
      var params = this.html.getElementsByTagName('param');
      for(var i = 0; i < params.length; i++) {
        if(params[i].getAttribute('name') == 'flashvars') {
          params[i].setAttribute('value', vars);
          break;
        }
      }
      node.replaceChild(this.html.cloneNode(true), flashNode);
    }
  };

  CallbackInfo.prototype.resize = function() {
    if(!this.available()) return;

    var flashNode      = this.getFlashElement();
    var ancestor       = flashNode.parentNode;
    var currentWidth   = flashNode.offsetWidth;
    var originalWidth  = flashNode.getAttribute('width');
    var originalHeight = flashNode.getAttribute('height');
    
    // Remove Flash movie from flow
    flashNode.style.width = '0px';
    flashNode.style.height = '0px';
    
    // Set a minimal height on the flashNode's parent, to stop a reflow
    flashNode.parentNode.style.minHeight = originalHeight;
    
    // Restore original content
    var nodes = this.getAlternate().childNodes;
    var clones = [];
    for(var i = 0; i < nodes.length; i++) {
      var node = nodes[i].cloneNode(true);
      clones.push(node);
      ancestor.appendChild(node);
    }
    
    // Calculate width
    var width = dom.getWidthFromStyle(ancestor);

    // Remove original content again
    for(var i = 0; i < clones.length; i++) ancestor.removeChild(clones[i]);

    // Reset Flash movie flow
    flashNode.style.width = flashNode.style.height = flashNode.parentNode.style.minHeight = '';
    flashNode.setAttribute('width', this._forceWidth ? width : originalWidth);
    flashNode.setAttribute('height', originalHeight);

    // Resize!
    if(width != currentWidth) this.call('resize', width);
    else this.call('scale');
  };
  
  CallbackInfo.prototype.changeCSS = function(css) {
    css = util.escape(util.cssToString(util.convertCssArg(css)));
    this.updateVars('css', css);
    return this.call('changecss', css);
  };
  
  CallbackInfo.prototype.getAlternate = function() {
    return document.getElementById(this.id + '_alternate');
  };
};
if(sIFR.ua.gecko==false||sIFR.ua.windows==true){var atkinsCond={src:"fileadmin/templates/sifr/flash/sifr.swf"};var atkinsUltraCond={src:"fileadmin/templates/sifr/flash/sifr2.swf"};sIFR.useStyleCheck=true;sIFR.activate(atkinsCond,atkinsUltraCond);sIFR.replace(atkinsCond,{selector:"h5",css:[".sIFR-root { text-align:left; background:none; color:#333333; font-size:15px; padding:0; margin:0; }","strong { font-weight: bold; }","a { color: #ffffff; text-decoration:none; }","a:hover { color: #ffffff; text-decoration:underline; }"],transparent:true});sIFR.replace(atkinsCond,{selector:"h1.normal",css:[".sIFR-root { text-align:left; background:none; color:#333333; font-size:18px; padding:0; margin:0; }","strong { font-weight: bold; }","a { color: #ffffff; text-decoration:none; }","a:hover { color: #ffffff; text-decoration:underline; }"],transparent:true});sIFR.replace(atkinsUltraCond,{selector:"h1.mittel",css:[".sIFR-root { text-align:left; background:none; color:#333333; font-size:25px; padding:0; margin:0; }","strong { font-weight: bold; }","a { color: #ffffff; text-decoration:none; }","a:hover { color: #ffffff; text-decoration:underline; }"],transparent:true});sIFR.replace(atkinsCond,{selector:"h2",css:[".sIFR-root { text-align:left; background:none; color:#DD5703; font-size:15px; padding:0; margin:0; }","strong { font-weight: bold; }","a { color: #DD5703; text-decoration:none; }","a:hover { color: #DD5703; text-decoration:underline; }"],transparent:true});sIFR.replace(atkinsUltraCond,{selector:"h6.overview2",css:[".sIFR-root { text-align:left; font-weight:normal; background:none; color:#ffffff; font-size:15px; kerning:true; letter-spacing:0.5; padding:0; margin:0; }","strong { font-weight:normal; }","a { color: #ffffff; text-decoration: none; }","a:hover { color: #ffffff; text-decoration: underline; }"],transparent:true});sIFR.replace(atkinsUltraCond,{selector:"h1.big",css:[".sIFR-root { text-align: left; background: none; color:#333333; font-size: 32px; padding:0; margin:0; }","strong { font-weight: bold; }","a { color: #ffffff; text-decoration: none; }","a:hover { color: #ffffff; text-decoration: underline; }"],transparent:true})};
var browserName=navigator.appName;var browserVer=parseInt(navigator.appVersion);var version="";var msie4=(browserName=="Microsoft Internet Explorer"&&browserVer>=4);if((browserName=="Netscape"&&browserVer>=3)||msie4||browserName=="Konqueror"||browserName=="Opera"){version="n3";}else{version="n2";}
function blurLink(theObject){if(msie4){theObject.blur();}}
function decryptCharcode(n,start,end,offset){n=n+offset;if(offset>0&&n>end){n=start+(n-end-1);}else if(offset<0&&n<start){n=end-(start-n-1);}
return String.fromCharCode(n);}
function decryptString(enc,offset){var dec="";var len=enc.length;for(var i=0;i<len;i++){var n=enc.charCodeAt(i);if(n>=0x2B&&n<=0x3A){dec+=decryptCharcode(n,0x2B,0x3A,offset);}else if(n>=0x40&&n<=0x5A){dec+=decryptCharcode(n,0x40,0x5A,offset);}else if(n>=0x61&&n<=0x7A){dec+=decryptCharcode(n,0x61,0x7A,offset);}else{dec+=enc.charAt(i);}}
return dec;}
function linkTo_UnCryptMailto(s){location.href=decryptString(s,2);}

/**
 * Sucht abbr, acronym und span/p Tags mit titel und ersetzt die Titel mit einem JS basierten 
 * Layer
 */



var Akronyme = {

	items: [],
	layer: null,
	text:  null,
	top: null,
	bottom: null,

	/**
	 * initialize
	 * Collect data and bind events to the tags
	 */
	init: function() {

		// Traverse	tags which could be considered
		$$('abbr', 'acronym', 'span', 'dfn').each(function(item, index) {

				if (!item.getProperty) return;
				if (!item.title) return;
				
				var tagtitle = (item.title + "  ").clean();
				if ($type(tagtitle) != "string" || tagtitle.length < 3) return;


				item.addEvents({
					mouseover: this.show.bind(this, index),
					mouseout: this.hide.bind(this)
				});
				this.items[ index ] = {
					el: item,
					txt: tagtitle
				};
				item.addClass('abbrevation').removeProperty('title'); 

			
		}, this);
		
		if (this.items.length > 0) {
			this.layer = new Element('div', {'class': 'akronym-layer'}).injectAfter('page'); this.hide();
			this.text  = new Element('div', {'class': 'mitte'}).injectInside(this.layer);
			this.top = new Element('div', {'class': 'oben'}).injectBefore(this.text);
			this.bottom = new Element('div', {'class': 'unten'}).injectAfter(this.text);			
		}
		
	},
	
	show: function(i) {
		
		this.text.setHTML('<strong>' + this.items[i].el.getText() + '</strong><br />' + this.items[i].txt);
		var h = this.top.getSize().size.y + this.bottom.getSize().size.y + this.text.getSize().size.y;
		
		var size = this.items[i].el.getSize().size;
		var t = this.items[i].el.getTop() - Math.round(h);
		var l = this.items[i].el.getLeft() + Math.round(size.x / 2 - 123);
		
		this.layer.setStyles({
			visibility: 'visible',
			top: t,
			left: l
		});
	},
	
	hide: function() {
		this.layer.setStyles({
			'visibility': 'hidden',
			top: -10000,
			left: -10000
		});
	}
};


var Autocompleter = {};

Autocompleter.Base = new Class({

	options: {
		minLength: 1,
		useSelection: true,
		markQuery: true,
		inheritWidth: true,
		dropDownWidth: 100,
		maxChoices: 10,
		injectChoice: null,
		onSelect: Class.empty,
		onShow: Class.empty,
		onHide: Class.empty,
		customTarget: null,
		className: 'autocompleter-choices',
		zIndex: 42,
		observerOptions: {},
		fxOptions: {},
		multi: false,
		delimeter: ', ',
		autotrim: true,
		allowDupes: false,
		baseHref: 'http://www.cnet.com/html/rb/assets/global/autocompleter/'
	},

	initialize: function(el, options) {
		this.setOptions(options);
		this.element = $(el);
		this.build();
		this.observer = new Observer(this.element, this.prefetch.bind(this), $merge({
			delay: 400
		}, this.options.observerOptions));
		this.value = this.observer.value;
		this.queryValue = null;
		this.element.addEvent('blur', function(e){
			this.autoTrim.delay(50, this, e);
		}.bind(this));
		this.addEvent('onSelect', function(){
			this.element.focus();
			this.userChose = true;
			(function(){
				this.userChose = false;
			}).delay(100, this);
		}.bind(this));
	},


	build: function() {
		if ($(this.options.customTarget)) this.choices = this.options.customTarget;
		else {
			this.choices = new Element('ul', {
				'class': this.options.className,
				'styles': {zIndex: this.options.zIndex}
				}).injectInside(document.body);
			this.fix = new OverlayFix(this.choices);
		}
		this.fx = this.choices.effect('opacity', $merge({wait: false, duration: 200}, this.options.fxOptions))
			.addEvent('onStart', function() {
				if (this.fx.now) return;
				this.choices.setStyle('display', '');
				this.fix.show();
			}.bind(this))
			.addEvent('onComplete', function() {
				if (this.fx.now) return;
				this.choices.setStyle('display', 'none');
				this.fix.hide();
			}.bind(this)).set(0);
		this.element.setProperty('autocomplete', 'off')
			.addEvent(window.ie ? 'keydown' : 'keypress', this.onCommand.bindWithEvent(this))
			.addEvent('mousedown', this.onCommand.bindWithEvent(this, [true]))
			.addEvent('focus', this.toggleFocus.bind(this, [true]))
			.addEvent('blur', this.toggleFocus.bind(this, [false]))
			.addEvent('trash', this.destroy.bind(this));
	},
	
	autoTrim: function(e){
		if(this.userChose) return this.userChose = false;
		var del = this.options.delimeter;
		var val = this.element.getValue();
		if(this.options.autotrim && val.test(del+"$")){
			e = new Event(e);
			this.observer.value = this.element.value = val.substring(0, val.length-del.length);
		}
		return this.observer.value
	},

	getQueryValue: function(value){
		value = $pick(value, this.observer.value);
		return (this.options.multi)?value.lastElement(this.options.delimeter):value||'';
	},
	
	destroy: function() {
		this.choices.remove();
	},

	toggleFocus: function(state) {
		this.focussed = state;
		if (!state) this.hideChoices();
	},

	onCommand: function(e, mouse) {
		var val = this.getQueryValue();
		if (mouse && this.focussed) this.prefetch();
		if (e.key) switch (e.key) {
			case 'enter':
				if (this.selected && this.visible) {
					this.choiceSelect(this.selected);
					e.stop();
				} return;
			case 'up': case 'down':

				if (this.getQueryValue() != (val || this.queryValue) && !this.options.multi) this.prefetch();
				else if (this.queryValue === null) break;
				else if (!this.visible) this.showChoices();
				else {
					this.choiceOver((e.key == 'up')
						? this.selected.getPrevious() || this.choices.getLast()
						: this.selected.getNext() || this.choices.getFirst() );
					this.setSelection();
				}
				e.stop(); return;
			case 'esc': case 'tab': 
				this.hideChoices(); 
				if (this.options.multi) this.element.value = this.element.getValue().trimLastElement();
				return;
		}
		this.value = false;
	},

	setSelection: function() {
		if (!this.options.useSelection) return;
		var del = this.options.delimeter;
		var qVal = this.getQueryValue(this.queryValue);
		var elVal = this.getQueryValue(this.element.getValue());
		var startLength;
		if(this.options.multi)	{
			var index = this.queryValue.lastIndexOf(del);
			var delLength = (index<0)?0:del.length;
			startLength = qVal.length+(index<0?0:index)+delLength;
		} else startLength = qVal.length;

		if (elVal.indexOf(qVal) != 0) return;
		var insert = this.selected.inputValue.substr(startLength);
		if (window.ie) {
			var sel = document.selection.createRange();
			sel.text = insert;
			sel.move("character", - insert.length);
			sel.findText(insert);
			sel.select();
		} else {
			var offset = (this.options.multi && this.element.value.test(del))?
				this.element.getValue().length-elVal.length+qVal.length
				:this.queryValue.length;
			this.element.value = this.element.value.substring(0, offset) + insert;
			this.element.selectionStart = offset;
			this.element.selectionEnd = this.element.value.length;
		}
		this.value = this.observer.value = this.element.value;
	},
/*	Property: hideChoices
		Hides the choices from the user.
	*/
	hideChoices: function() {
		if (!this.visible) return;
		this.visible = this.value = false;
		this.observer.clear();
		this.fx.start(0);
		this.fireEvent('onHide', [this.element, this.choices]);
	},

	showChoices: function() {
		if (this.visible || !this.choices.getFirst()) return;
		this.visible = true;
		var pos = this.element.getCoordinates(this.options.overflown);
		this.choices.setStyles({'left': pos.left-10, 'top': pos.bottom+2});
		this.choices.setStyle('width', (this.options.inheritWidth)?pos.width+20:this.options.dropDownWidth);
		this.fx.start(1);
		this.choiceOver(this.choices.getFirst());
		this.fireEvent('onShow', [this.element, this.choices]);
	},

	prefetch: function() {
		var val = this.getQueryValue(this.element.getValue());
		if (val.length < this.options.minLength) this.hideChoices();
		else if (val == this.queryValue) this.showChoices();
		else this.query();
	},

	updateChoices: function(choices) {
		this.choices.empty();
		this.selected = null;
		if (!choices || !choices.length) return;
		if (this.options.maxChoices < choices.length) choices.length = this.options.maxChoices;
		choices.each(this.options.injectChoice || function(choice, i){
			var el = new Element('li').setHTML(this.markQueryValue(choice));
			el.inputValue = choice;
			this.addChoiceEvents(el).injectInside(this.choices);
		}, this);
		this.showChoices();
	},

	choiceOver: function(el) {
		if (this.selected) this.selected.removeClass('autocompleter-selected');
		this.selected = el.addClass('autocompleter-selected');
	},

	choiceSelect: function(el) {
		if(this.options.multi) {
			var del = this.options.delimeter;
			var value = (this.element.value.trimLastElement(del) + el.inputValue).split(del);
			var fin = [];
			if (!this.options.allowDupes) {
				value.each(function(item){
					if(fin.contains(item))fin.remove(item); //move it to the end
					fin.include(item);
				})
			} else fin = value;
			this.observer.value = this.element.value = fin.join(del)+del;
		} else this.observer.value = this.element.value = el.inputValue;
		
		
		this.hideChoices();
		this.fireEvent('onSelect', [this.element, el.inputValue], 20);
	},

	markQueryValue: function(txt) {
		var val = (this.options.mult)?this.lastQueryElementValue:this.queryValue;
		//return (this.options.markQuery && val) ? txt.replace(new RegExp('^(' + val.escapeRegExp() + ')', 'i'), '<span class="autocompleter-queried">$1</span>') : txt;
		return (this.options.markQuery && val) ? txt.replace(new RegExp('(' + val.escapeRegExp() + ')', 'i'), '<span class="autocompleter-queried">$1</span>') : txt;
	},

	addChoiceEvents: function(el) {
		return el.addEvents({
			'mouseover': this.choiceOver.bind(this, [el]),
			'mousedown': this.choiceSelect.bind(this, [el])
		});
	},
	query: Class.empty
});

Autocompleter.Base.implement(new Events);
Autocompleter.Base.implement(new Options);

var OverlayFix = new Class({

	initialize: function(el) {
		this.element = $(el);
		if (window.ie){
			this.element.addEvent('trash', this.destroy.bind(this));
			this.fix = new Element('iframe', {
					'properties': {'frameborder': '0', 'scrolling': 'no', 'src': 'javascript:false;'},
					'styles': {'position': 'absolute', 'border': 'none', 'display': 'none', 'filter': 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'}})
				.injectAfter(this.element);
		}
	},

	show: function() {
		if (this.fix) this.fix.setStyles($extend(
			this.element.getCoordinates(), {'display': '', 'zIndex': (this.element.getStyle('zIndex') || 1) - 1}));
		return this;
	},

	hide: function() {
		if (this.fix) this.fix.setStyle('display', 'none');
		return this;
	},

	destroy: function() {
		this.fix.remove();
	}

});

String.extend({
	lastElement: function(separator){
		separator = separator || ' ';
		var txt = this; //(separator.test(' $'))?this:this.trim();
		var index = txt.lastIndexOf(separator);
		var result = (index == -1)? txt: txt.substr(index + separator.length, txt.length);
		return result;
	},
 
 
	trimLastElement: function(separator){
		separator = separator || ' ';
		var txt = this; //(separator.test(' $'))?this:this.trim();
		var index = this.lastIndexOf(separator);
		return (index == -1)? "": txt.substr(0, index + separator.length);
	}
});


Autocompleter.Local = Autocompleter.Base.extend({
	options: {
		minLength: 0,
		filterTokens : null
	},
	initialize: function(el, tokens, options) {
		this.parent(el, options);
		this.tokens = tokens;
		if (this.options.filterTokens) this.filterTokens = this.options.filterTokens.bind(this);
	},
	query: function() {
		this.hideChoices();
		this.queryValue = (this.options.multi)?
				this.element.value.lastElement(this.options.delimeter).trim()
				:this.element.value;
		this.updateChoices(this.filterTokens());
	},
	filterTokens: function(token) {
		var regex = new RegExp('^' + this.queryValue.escapeRegExp(), 'i');
		return this.tokens.filter(function(token) {
			return regex.test(token);
		});
	}
});

Autocompleter.Ajax = {};

Autocompleter.Ajax.Base = Autocompleter.Base.extend({

	options: {
		postVar: 'value',
		postData: {},
		ajaxOptions: {},
		onRequest: Class.empty,
		onComplete: Class.empty
	},

	initialize: function(el, url, options) {
		this.parent(el, options);
		this.ajax = new Ajax(url, $merge({
			autoCancel: true
		}, this.options.ajaxOptions));
		this.ajax.addEvent('onComplete', this.queryResponse.bind(this));
		this.ajax.addEvent('onFailure', this.queryResponse.bind(this, [false]));
	},

	query: function(){
		var multi = this.options.multi;
		var data = $extend({}, this.options.postData);
		if(multi) this.lastQueryElementValue = this.element.value.lastElement(this.options.delimeter);
		data[this.options.postVar] = (multi)?this.lastQueryElementValue:this.element.value;
		this.fireEvent('onRequest', [this.element, this.ajax]);
		this.ajax.request(data);
	},
	
	queryResponse: function(resp) {
		this.value = this.queryValue = this.element.value;
		this.selected = false;
		this.hideChoices();
		this.fireEvent(resp ? 'onComplete' : 'onFailure', [this.element, this.ajax], 20);
	}

});

Autocompleter.Ajax.Json = Autocompleter.Ajax.Base.extend({

	queryResponse: function(resp) {
		this.parent(resp);
		var choices = Json.evaluate(resp || false);
		if (!choices || !choices.length) return;
		this.updateChoices(choices);
	}

});

Autocompleter.Ajax.Xhtml = Autocompleter.Ajax.Base.extend({

	options: {
		parseChoices: null
	},

	queryResponse: function(resp) {
		this.parent(resp);
		if (!resp) return;
		this.choices.setHTML(resp).getChildren().each(this.options.parseChoices || this.parseChoices, this);
		this.showChoices();
	},

	parseChoices: function(el) {
		var value = el.innerHTML;
		el.inputValue = value;
		el.setHTML(this.markQueryValue(value));
	}

});


var Observer = new Class({

	options: {
		periodical: false,
		delay: 1000
	},

	initialize: function(el, onFired, options){
		this.setOptions(options);
		this.addEvent('onFired', onFired);
		this.element = $(el);
		this.listener = this.fired.bind(this);
		this.value = this.element.getValue();
		if (this.options.periodical) this.timer = this.listener.periodical(this.options.periodical);
		else this.element.addEvent('keyup', this.listener);
	},

	fired: function() {
		var value = this.element.getValue();
		if (this.value == value) return;
		this.clear();
		this.value = value;
		this.timeout = this.fireEvent.delay(this.options.delay, this, ['onFired', [value]]);
	},

	clear: function() {
		$clear(this.timeout);
		return this;
	}
});

Observer.implement(new Options);
Observer.implement(new Events);


window.addEvent("domready",function(){var el=$("tx-indexedsearch-searchbox-sword");if(el){var form=el;for(var i=0;i<20;i++){form=form.getParent();if(form.nodeName=="FORM")break;}
var sectionpid=0;var section=$("tx-indexedsearch-selectbox-sections");if(section){sectionpid=section.getValue();}
var languageid=-1;var language=$("tx-indexedsearch-selectbox-lang");if(language){languageid=language.getValue();}
var ajaxurl="index.php?eID=pmkisac";var indicator=new Element("div",{"class":"autocompleter-loading","styles":{"display":"none"}}).setHTML("").injectAfter(el);var completer=new Autocompleter.Ajax.Xhtml(el,ajaxurl,{"postData":{id:104,sp:sectionpid,la:languageid,sw:1,ml:2,mc:10,wc:1},"minLength":2,"maxChoices":10,"useSelection":0,"markQuery":0,"inheritWidth":false,"dropDownWidth":200,"multi":1,"delimeter":" ","onSelect":function(){if(form.nodeName=="FORM")form.submit();},"delay":10,"onRequest":function(el){indicator.setStyle("display","");},"onComplete":function(el){indicator.setStyle("display","none");},"parseChoices":function(el){var value=el.getFirst().innerHTML;el.inputValue=value;this.addChoiceEvents(el).getFirst().setHTML(this.markQueryValue(value));}});if(section){section.addEvent("change",function(){completer.options.postData["sp"]=section.getValue();});}
if(language){language.addEvent("change",function(){completer.options.postData["la"]=language.getValue();});}}});

var accordion,menu;
var ActiveAni = false;
var Clicked = false;

var Mainmenu = new Class({

	items: [],
	active:-1,
	current:null,
	startActive: -1,
	hideIt: false,
	mainMenu: [],
	parents: [],
	imgCache: [],
	
	background: null,
	hT: null,
	
	startId: -1,
	
	/**
	 * Bind events to first menu level
	 */
	initialize: function() {

		this.background = $$('#balken-oben .text-top').getLast();
		if ($type(this.background) != 'element') this.background = false;

		this.mainMenu = $$('ul.main')[0].getChildren();

		this.mainMenu.each(function(item, index) {

			item.getElement('a').addEvents({

				mouseover: function() {
					this.enter( index );
				}.bind(this),

				mouseout: function() {
					if (!Clicked) this.hide( index );
				}.bind(this),

				click: function() {
					Clicked = true;
				}

			});


			
			if (item.getChildren().getLast().getTag() != 'ul') {
				this.items[ index ] = false;
			}
			else {
				
				
				
				kid = item.getChildren().getLast();
				
				this.items[ index ] = new Element('div', {'class': 'menu-container'}).injectAfter('page').addEvents({
					mouseenter: function() {
						this.enter( index );
					}.bind(this),
					mouseleave: function() {
						if (!Clicked) this.hide( index );
					}.bind(this)
				}).setStyles({
					'top': -1000,
					'left': -1000,
					'visibility': 'hidden'
				});
				
				new Element('div', {'class': 'shadow-bottom'}).injectInside(this.items[ index ]);
				
				kid.clone().injectInside(new Element('div', {'class': 'shadow'}).injectInside(this.items[ index ])).setStyle('display', 'block');
				this.parents[ index ] = item;
				kid.remove();
			}

			if (item.hasClass('current')) {
				this.startActive = index;
			}

		}, this);


		// Preload all Menu images
		var pics = [];
		mainmenu_pics.each(function(el) {
			pics.push(el.no); pics.push(el.no_ro); pics.push(el.act_ro); pics.push(el.act);
		});
		pics.each(function(el, i) {
			this.imgCache[i] = new Image();
			this.imgCache[i].src = el;
		}, this);
		//new Asset.images(pics);
		
		
		 // Get Index of the 
		 if ($('current-active-menu')) {
			 
			$('current-active-menu').getParent().setProperty('rel', 'active').getParent().getChildren().each(function(el, ind) {
				if (el.getAttribute('rel') == 'active') {
					this.startId = ind;
					el.removeAttribute('rel');
				}
			}.bind(this));
			
			$('current-active-menu').addEvent('mouseover', function() {
				this.enter( this.startId );
			}.bind(this));
		}
		
		
		
	},


	getTop: function(i) {

		return this.parents[ i ].getTop() + 74;

		if (window.ie) t += 74;
		else if (window.mac) t += 74
		else return t += 63;

		return t;

	},


	getLeft: function(i) {
		return this.parents[ i ].getLeft() - 7;
	},


	/**
	 * Sets the styles and submenu visibility
	 * when a point is entered
	 */
	enter: function(i) {
		this.hideIt = false;
		$clear(this.hT);
	//	soundManager.play('menu');
		if ($('current-active-menu')) $('current-active-menu').setStyle('opacity', 0.2);
		if (this.background) this.background.setStyle('opacity', i > 0 ? 0.2 : 1);
		this.items.each(function(item, index) {

			if (!this.items[ index ]) return;

			style = (index == i) ? 'visible' : 'hidden';

			this.items[ index ].setStyles((index == i) ? {
				'visibility': 'visible',
				top: this.getTop(index),
				left: this.getLeft(index) 
			} : {
				'visibility': 'hidden',
				top: -1000,
				left: -1000
			});

		}, this);

		this.setTop(i);
	},


	hide: function(i) {
		this.hideIt = true;
		this.hT = (function() { this.leave(i); }.bind(this)).delay((ActiveAni == true) ? 2000 : 600);
	},


	/**
	 * Reset the main menu point on leave
	 */
	leave: function(i) {

		$clear(this.hT);
		if (this.hideIt == false) return;
		
		
		this.items.each(function(item) {
			if (item) item.setStyles({
				'visibilty': 'hidden',
				'top': -1000,
				'left': -1000
			});
		});

		this.hideIt = false;
		this.setTop( this.startActive );

		if ($('current-active-menu')) $('current-active-menu').setStyle('opacity', 1);
		if (this.background) this.background.setStyle('opacity', 1);
		
		var obj = {};
		accordion.elements.each(function(item, i) {
			obj[i] = {};
			if (item.getStyle('opacity').toInt() > 0) {
				obj[i]['height'] = 0;
				obj[i]['opacity'] = 0;
				accordion.fireEvent('onBackground', [accordion.togglers[i], item]);
			}
		});
		accordion.start(obj);

	},

	setTop: function(i) {

		this.mainMenu.each(function(item, index) {
		
			el = this.mainMenu[index];
			
			if (index == i) {
				if (i != this.startActive) el.addClass('hover');
				el.setStyle('opacity', 1).getElement('a').setProperty('rel', 'hover:' + mainmenu_pics[index].act_ro).getElement('img').setProperty('src',  mainmenu_pics[index].act);
			}
			else {

				if (index != this.startActive) {
					a = mainmenu_pics[index].no_ro;
					b = mainmenu_pics[index].no;
				} else {
					a = mainmenu_pics[index].act_ro;
					b = mainmenu_pics[index].act;
				}

				if (el.hasClass('current')) el.setStyle('opacity', 0.5);
				el.removeClass('hover').getElement('a').setProperty('rel', 'hover:' + a).getElement('img').setProperty('src',  b);

			}
		}, this);


		Mainmenu_Hover = null; Mainmenu_Hover = new Hover($$("#head ul a"));
	},
	
	
	/**
	 * Traverses the DOM of the menu to find the index of the active item
	 */
	getStartActive: function() {
		$$('li span.toggle3').each(function(item, index){
			if (item.getParent().hasClass('current')) this.active = index;
		}, this);
		return this.active;
	}
});


window.addEvent('domready', function() {
	
	menu = new Mainmenu();
	
	accordion = new Accordion(
		$$('li span.toggle3'), 
		$$('li ul.main-level-3'),
		{
			display: menu.getStartActive(),
			opacity: true,

			onActive: function(toggler, section) {
				toggler.addClass('act');
			},

			onBackground: function(toggler, section) {
				toggler.removeClass('act');
			},

			onStart: function() {
				ActiveAni = true;
			},

			onComplete: function() {
				ActiveAni = false;
			}
		}
	);
	
	
	// Change the style after everything has been set up	
	
	
});
var mainmenu_pics = [{"no":"typo3temp\/GB\/Home_af3b76ce75.gif","no_ro":"typo3temp\/GB\/Home_b98887c577.gif","act":"typo3temp\/GB\/Home_main_act_bg_2ec0dc51bb_cfb7a78a2b.gif","act_ro":"typo3temp\/GB\/Home_main_act_bg_2ec0dc51bb_cfb7a78a2b.gif"},{"no":"typo3temp\/GB\/Agentur_7513b3e8b1.gif","no_ro":"typo3temp\/GB\/Agentur_297a480ccb.gif","act":"typo3temp\/GB\/Agentur_main_act_bg_2ec0dc51bb_1848c6e069.gif","act_ro":"typo3temp\/GB\/Agentur_main_act_bg_2ec0dc51bb_1848c6e069.gif"},{"no":"typo3temp\/GB\/Kompetenz_25409b0fdc.gif","no_ro":"typo3temp\/GB\/Kompetenz_ada7dfc8c8.gif","act":"typo3temp\/GB\/Kompetenz_main_act_bg_2ec0dc51bb_eb7f7f5ef8.gif","act_ro":"typo3temp\/GB\/Kompetenz_main_act_bg_2ec0dc51bb_eb7f7f5ef8.gif"},{"no":"typo3temp\/GB\/Leistungen_90b4afba8c.gif","no_ro":"typo3temp\/GB\/Leistungen_b1a090c3df.gif","act":"typo3temp\/GB\/Leistungen_main_act_bg_2ec0dc51bb_13faaf1dd1.gif","act_ro":"typo3temp\/GB\/Leistungen_main_act_bg_2ec0dc51bb_13faaf1dd1.gif"},{"no":"typo3temp\/GB\/Projekte_414ce3e20c.gif","no_ro":"typo3temp\/GB\/Projekte_aebd301e5b.gif","act":"typo3temp\/GB\/Projekte_main_act_bg_2ec0dc51bb_cb6b03af87.gif","act_ro":"typo3temp\/GB\/Projekte_main_act_bg_2ec0dc51bb_cb6b03af87.gif"},{"no":"typo3temp\/GB\/News_eee7bbdf80.gif","no_ro":"typo3temp\/GB\/News_39bb301ca8.gif","act":"typo3temp\/GB\/News_main_act_bg_2ec0dc51bb_dde765a881.gif","act_ro":"typo3temp\/GB\/News_main_act_bg_2ec0dc51bb_dde765a881.gif"},{"no":"typo3temp\/GB\/Kontakt_bab002d0ae.gif","no_ro":"typo3temp\/GB\/Kontakt_aab71c5c7b.gif","act":"typo3temp\/GB\/Kontakt_main_act_bg_2ec0dc51bb_3a50925d57.gif","act_ro":"typo3temp\/GB\/Kontakt_main_act_bg_2ec0dc51bb_3a50925d57.gif"}]
/** Various Helper functions **/


var Websnapr = null;
var Websnapr_img = null;
window.addEvent('domready',function(){
	
	/*
	soundManager.url = '/fileadmin/templates/soundmanager/'; // directory where SM2 .SWFs live

	// disable debug mode after development/testing..
	soundManager.debugMode = false;
	
	soundManager.onload = function() {
	  // SM2 has loaded - now you can create and play sounds!
	  soundManager.createSound('menu','/fileadmin/templates/soundmanager/click-high.mp3');
	  //soundManager.play('menu');
	}
*/
	
		// Init Websnapper
	Websnapr = new Element('div', {'class': 'websnapr'}).injectBefore($('page'));
	Websnapr_img = new Element('img', {
		width: 105,
		height: 80,
		src: 'clear.gif'
	}).injectInside(Websnapr);
	
	$$('a.external-link', 'a.external-link-new-window').each(function(item) {
		item.addEvents({
			mouseover: function() {

				leftPxls = item.getLeft() + Math.round((item.getSize().size.x / 2) - 67);

				Websnapr.setStyles({
					display: 'block',
					top: item.getTop() -107,
					left: leftPxls
				});

				Websnapr_img.setProperty('src', 'http://images.websnapr.com/?size=S&key=rvf31ZXEEa6T&url=' + item.href);
				
			},
			mouseout: function() {
				Websnapr.setStyle('display', 'none');
			}
		});
	});
	
	
	var search_buttons=$$('div.search-wrapper');
	if(search_buttons.length>0) search_buttons[0].setStyles({ position: 'absolute', left: 0, top: -40 });
	
	if ($('search-wrapper-projekte')) {
		$('search-wrapper-projekte').setStyles({
			position:'absolute',
			left:0,
			top:-155
		})
	}
		
	if ($('tx-indexedsearch-searchbox-sword-big')) {
		$('tx-indexedsearch-searchbox-sword-big').addEvents({
			focus: function() {
				val = $('tx-indexedsearch-searchbox-sword-big').getValue().trim();
				if (val == 'Was suchen Sie?') {
					$('tx-indexedsearch-searchbox-sword-big').addClass('current').value = '';
				}
			},
			blur: function() {
				val = $('tx-indexedsearch-searchbox-sword-big').getValue().trim();
				if (val == 'Was suchen Sie?' || val == '') {
					$('tx-indexedsearch-searchbox-sword-big').removeClass('current').value = 'Was suchen Sie?';
				}
			}
		});
		if ($('tx-indexedsearch-searchbox-sword-big').getValue().trim() == '') $('tx-indexedsearch-searchbox-sword-big').value = 'Was suchen Sie?';
		else $('tx-indexedsearch-searchbox-sword-big').addClass('current');
		
		$('tx-indexedsearch-searchbox-button-submit').value = '';
	}
	
	News_Ticker.init();
	
	
	
	$$('#suche button').each(function(fast_serach_submit) {
		fast_serach_submit.addEvents({
			'mouseenter': function() {
				fast_serach_submit.setStyle('background-image', 'url(fileadmin/templates/images/suche_btn_hover.gif)');
			},
			'mouseleave': function() {
				fast_serach_submit.setStyle('background-image', 'url(fileadmin/templates/images/suche_btn.gif)');
			}
		});
	});
	
	
	// Hover Effects of inquiry submit buttons
	
	new Asset.images([
		'fileadmin/templates/images/btn_ro.gif',
		'fileadmin/templates/images/btn_cl.gif'
	]);
	
	
	$$('button.inquiry_submit', 'button.register').each(function(btn) {
		btn.addEvents({
				
			'mouseover': function() {
				btn.setStyle('background-image', 'url(fileadmin/templates/images/btn_ro.gif)');
			},
				
			'mouseout': function() {
				btn.setStyle('background-image', 'url(fileadmin/templates/images/btn_no.gif)');
			},
				
			'mousedown': function() {
				btn.setStyle('background-image', 'url(fileadmin/templates/images/btn_cl.gif)');
			},
				
			'mouseup': function() {
				btn.setStyle('background-image', 'url(fileadmin/templates/images/btn_ro.gif)');
			}
				
		});
	});
	
	
	// Tabs
	var tab_header = $$("div.tab_header");
	var tab_content = $$('div.tab_content');
	
	
	if ($type($$("div.tab_header")[0]) == 'element' && $type($$("div.tab_content")[0])) {
		
		for (var e=0; e<tab_content.length; e++) {
			if ($type(tab_content[e]) == "element") {
				Tabs.tabs[e] = {
					header: new Element('a').setText(tab_header[e].getText()).setProperty('id', e).injectInside($('tabs')).addEvent('click', function(e) {

						nr = new Event(e).target.id;

						Tabs.tabs[ Tabs.active ].header.removeClass('active');
						Tabs.tabs[ Tabs.active ].content.setStyle('display', 'none');
						Tabs.active = nr;

						Tabs.tabs[ Tabs.active ].header.addClass('active');
						Tabs.tabs[ Tabs.active ].content.setStyle('display', 'block');
						
						
					}.bind(Tabs.tabs[e])),
					
					content: tab_content[e]
				};
				if(e>0) {
						Tabs.tabs[e].content.setStyle('display', 'none');
				}
			}
		}
		
		$('tab_header_container').remove();
		Tabs.tabs[0].header.addClass("active").addClass("first");
	}
	
});
var Darken = {
	
	items: [],
	
	init: function() {
		$$('.middle img').each(function(item, el) {

			if (item.getParent().getTag() != 'a') return false;
			Darken.items[el] = new Fx.Style(item.setProperty('id', 'overviewpic-' + el), 'opacity', {duration:100, transition: Fx.Transitions.Sine.easeIn});
			//item.getParent().setStyle('background-color', '#000000');

			item.addEvents({
				mouseenter: function(e) {
					Darken.items[ $(e.target).getProperty('id').split('-').getLast().toInt() ].stop().start(0.85);
				},
				mouseleave: function(e) {
					Darken.items[ $(e.target).getProperty('id').split('-').getLast().toInt() ].stop().start(1);
				}
			});


		}, this);
	}
};

window.addEvent('domready', Darken.init.bind(Darken));
window.addEvent('domready', Akronyme.init.bind(Akronyme));

var News_Ticker = {
	
	items: [],
	active: 0,
	fx: null,
	
	init: function() {
	
		if ($$('#balken-oben .text-top').length < 1) return;
		
		items = $$('#balken-oben .text-top p');
		if (items.length < 2) return;
		
		//this.fx = new Fx.Elements(this.items, {duration: 300});
		
		items.each(function(item, index) {
			this.items.push (new Fx.Styles(item, {duration: 300}));
			item.setStyle('opacity', 0);
		}.bind(this));
		
		this.items[0].start({top: [30, 20], opacity: [0, 1]});
		
		(function() { this.show(); }.bind(this)).periodical(4000);
	},
	
	show: function() {
	
		var styles = [];
	
		this.items[ this.active ].stop().start({top: [20, 10], opacity: [1, 0]});
		
		if (this.active+1 >= this.items.length) {
			this.active = 0;
		} else {
			this.active++;
		}
		
		this.items[ this.active ].stop().start({top: [30, 20], opacity:[0, 1]});
		
		//this.fx.stop().start(styles);
	}
};


var Validator=new Class({options:{text:{name:"Name fehlt",first_name:"Vorname fehlt",last_name:"Nachname fehlt",firma:"Firma fehlt",adresse:"Adresse fehlt",plz:"PLZ fehlt",ort:"Stadt fehlt",telefon:"Telefon fehlt",fax:"Telefax fehlt",email:"eMail Adresse fehlt"},selector:"error",form:"",event:"submit"},fields:[],backups:[],form:null,error:false,lastValue:"",regexp:{required:/[^.*]/,alpha:/^[a-z ._-]+$/i,alphanum:/^[a-z0-9 ._-]+$/i,digit:/^[-+]?[0-9]+$/,nodigit:/^[^0-9]+$/,number:/^[-+]?\d*\.?\d+$/,email:/^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i,phone:/^[\d\s ().-]+$/},initialize:function(A){this.setOptions(A);this.form=$(this.options.form);this.form.getElements("input").each(function(B){if(B.className.test(/validate\[/i)){this.fields.push({el:B,tests:B.className.match(/validate\[(.*)\]$/i)[1].split(",")})}},this);this.form.addEvent("submit",this.validate.bind(this))},validate:function(A){this.error=false;this.fields.each(function(B){if(!this.form.getElements("input").contains(B.el)){return }B.tests.each(function(C){this.validateSingeItem(C,B)},this)}.bind(this));if(this.error){A=new Event(A).stop();return false}else{return true}},validateSingeItem:function(B,A){B=B.split("-");this.currentElement=A;valid=true;switch(B[0]){case"email":case"mail":valid=this._regexp(this.regexp.email);break;case"number":case"zahl":valid=this._regexp(this.regexp.number);break;case"zip":case"plz":valid=(this._regexp(this.regexp.number)&&this._length(4,6));break;case"length":valid=this._length(B[1],B[2]);break;case"phone":case"tel":case"telefon":valid=this._regexp(this.regexp.phone);break}if(!valid||this.lastValue==this.options.text[this.currentElement.el.id]){this.setError()}},setError:function(){el=this.currentElement.el;if(this.options.text[el.id]!=this.lastValue.clean()){this.backups[el.id]=this.lastValue}el.setProperty("value",this.options.text[el.id]).addClass(this.options.selector).addEvent("focus",this.removeError.bind(this));this.error=true},removeError:function(A){this.currentElement=new Event(A).target;this.fields.each(function(B){if(this.currentElement==B.el&&this.currentElement.hasClass(this.options.selector)){this.currentElement.removeClass(this.options.selector).setProperty("value",this.backups[this.currentElement.id])}}.bind(this))},_regexp:function(A){this.lastValue=this.currentElement.el.getProperty("value");if(this.lastValue.search(A)==-1){return false}else{return true}},_length:function(B,A){B=B.toInt();A=(A=="x")?999999:A.toInt();this.lastValue=this.currentElement.el.getProperty("value");if(this.lastValue.length<B||this.lastValue.length>A){return false}else{return true}}});Validator.implement(new Options);
var Ajax_Login = new Class({
	
	link: null,
	box: null,
	fx: null, fx2: null, fx3: null,
	el: {}, msg: {},
	active: false,
	response: null,
	backupMsgBox: false,
	
	data: {
		userPID: 6,
		buttons: {
			login: {
				normal: "typo3conf/ext/ajax_login/res/pics/login_normal.gif",
				hover:  "typo3conf/ext/ajax_login/res/pics/login_hover.gif",
				click:  "typo3conf/ext/ajax_login/res/pics/login_click.gif"
			},
			logout: {
				normal: "typo3conf/ext/ajax_login/res/pics/logout_normal.gif",
				hover:  "typo3conf/ext/ajax_login/res/pics/logout_hover.gif",
				click:  "typo3conf/ext/ajax_login/res/pics/logout_click.gif"
			}
		},
		pics: {
			form_header: "typo3conf/ext/ajax_login/res/images/header_login.gif",
			logout_header: "typo3conf/ext/ajax_login/res/images/header_logout.gif"	
		},
		status: {
			login:false
		}
	},
	btn: null,
	
	addMsgEvents: function() {
		if ($('forgot_submit')) {
			$('forgot_submit').removeEvents().addEvents({
				mousedown: function() {
					this.setStyle('backgroundImage', 'url(fileadmin/templates/images/forgot_click.gif)');	
				},
				mouseenter: function() {
					this.setStyle('backgroundImage', 'url(fileadmin/templates/images/forgot_hover.gif)');	
				},
				mouseleave: function() {
					this.setStyle('backgroundImage', 'url(fileadmin/templates/images/forgot_normal.gif)');	
				}
			});
		}
	},
	
	initialize: function(raw_data) {
		
		$extend(this.data, raw_data);
		this.link = $$("#meta a")[0];
		
		
		//new Asset.css('typo3conf/ext/ajax_login/res/styles.css');
		//new Asset.css('../../typo3conf/ext/ajax_login/res/styles.css');
		new Asset.images([
			this.data.buttons.login.normal,
			this.data.buttons.login.hover,
			this.data.buttons.login.click,
			this.data.buttons.logout.normal,
			this.data.buttons.logout.hover,
			this.data.buttons.logout.click,
			this.data.pics.form_header,
			this.data.pics.logout_header
		]);
		
		this.constructBox();
		
		this.link.addEvent("click", function(ev) {
			ev = new Event(ev).stop();
			return this.show();
		}.bind(this));
	},
	
	constructBox: function() {
		s = window.getSize().scrollSize;		
		var ww = (window.getWidth() == 0) ? window.getScrollWidth()-22 : window.getWidth();
		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
		this.box = new Element("div", {
			'class' : 'login-wrapper',
			events: {
				click: this.hide.bind(this)
			},
			styles: {
				width: ww,
				height: wh
			}
		}).injectBefore( $('page') );


		this.fx  = new Fx.Style(this.box, "opacity", {duration: 300, transition: Fx.Transitions.Cubic.easeInOut}).set(0);
		
			
			// Make Orange Marker
		this.el.marker = new Element("div").addClass("marker").setText("Login").addEvent("click", function() {
			this.hide();
		}.bind(this)).injectInside(this.box);


			// Make Login Form
		this.el.box  = new Element("div", {
			'class': 'loginbox', 
			styles: {
				opacity: 0
			}
		}).injectAfter( this.box ).setHTML(this.data.box);
		this.fx2  = new Fx.Style(this.el.box, "opacity", {duration:300, transition: Fx.Transitions.Cubic.easeInOut});

			
			// Attach Events to the elements
		this.attachEvents();
			// Infobox
		this.msg.outer = new Element("div", {styles: {display: 'none'}}).addClass("login-msg").injectAfter( this.el.box );
		
		
		this.msg.box = new Element("div",{styles: {width: 0, opacity: 0}, 'class': 'message'}).injectInside( this.msg.outer );
		this.fx3 = new Fx.Styles(this.msg.box, {duration: 300, transition: Fx.Transitions.Cubic.easeInOut});
		//this.fx3 = new Fx.Styles(this.msg.box, {duration: 500});
		/*
		this.fx3.set({
			width: 0,
			opacity: 0
		});
		*/
		
		
	},
	
	attachEvents: function() {
		
		if ($type($('user')) == "element") {
			$('user').removeEvents().addEvents({
																																			   
				'focus': function() {
						
					var i = $('user');
					if (i.getProperty("value") == "Benutzername") i.setProperty("value", "");
						
				}.bind(this),
					
				'blur': function() {
						
					var i = $('user');
					if (i.getProperty("value").trim() == "" || i.getProperty("value").trim() == "Benutzername") i.setProperty("value", "Benutzername");
						
				}.bind(this)
			});
		}
		
		if ($type($('pass')) == "element") {
			$('pass').removeEvents().addEvents({
																																					   
				'focus': function() {
					if ($('pass').getProperty("value").trim() == "Passwort") {
							$('pass').setProperties({
								value: '',
								type: 'password'
							});
					}

				}.bind(this),
					
				'blur': function() {

					if ($('pass').getProperty("value") == "" || $('pass').getProperty("value") == "Passwort") $('pass').setProperties({
						value: 'Passwort',
						type: 'text'
					});

				}.bind(this)
			});
		}
		
		if (!this.data.status.login) this.btn = this.data.buttons.login;
		else this.btn = this.data.buttons.logout;
		
		if ($type($('button')) == "element") {
			this.send = new XHR({
				method: "post",
				onRequest: function() {
					this.hideLayer();
				}.bind(this),
				onSuccess: function() {
					this.react(this.send.response.text);
				}.bind(this),
				onFailure: function() {
					this.react(this.send.response.text);
				}.bind(this)
			});
		
		
			$('button').removeEvents().addEvents({
		
					"click": function() {
						
						if (this.data.status.login) {
							sendData = 'pid='+ this.data.userPID + '&logintype=logout';
						} else {
							sendData = 'user=' + encodeURI($('user').value) + '&pass=' + encodeURI($('pass').value) + '&pid='+this.data.userPID+'&logintype=login';
						}
						
						this.send.send('index.php?eID=ajax_login', sendData);

			        }.bind(this),
	
					"mousedown": function() {
		            	$('button').setProperty("src", this.btn.click);
		        	}.bind(this),
	
					"mouseup": function(e) {
		            	$('button').setProperty("src", this.btn.hover);
		        	}.bind(this),
	
					"mouseover": function() {
			            $('button').setProperty("src", this.btn.hover);
		        	}.bind(this),
	
					"mouseout": function() {
		            	$('button').setProperty("src", this.btn.normal);
		        	}.bind(this)
	
			});
		}
			
			if ($('forgot-password')) {
				$('forgot-password').removeEvents().addEvent('click', this.showForgottenFields.bind(this));
			}
			
			if ($('login-help')) {
				$('login-help').removeEvents().addEvent('click', this.showHelp.bind(this));
			}
	},
	
	showHelp: function(e) {
		e = new Event(e).stop();
		(function() {

			this.msg.box.setHTML(this.data.help);
			this.addMsgEvents();
			this.showLayer();

		}.bind(this)).delay(300);
	},

	showForgottenFields: function(e) {
		e = new Event(e).stop();
		new XHR({
			method: "post",
			onRequest: function() {
				this.hideLayer();
			}.bind(this),
			onSuccess: function(r) {
				this.makeForgot(Json.evaluate(r, true));
				this.showLayer();
			}.bind(this),
			onFailure: function(r) {
				this.makeForgot(Json.evaluate(r, true));
				this.showLayer();
			}.bind(this)
		}).send(
			'index.php?eID=tx_ajaxlogin_forgot',
			'action=getform'
		);
	},
	
	makeForgot: function(r) {
		this.msg.box.setHTML(r.text);
		this.addMsgEvents();
		
		if ($('forgot_mail') && $('forgot_submit')) {
			
			$('forgot_submit').removeEvents().addEvent('click', function(e) {
				e = new Event(e).stop();				
				
				new XHR({
					method: "post",
					onRequest: function() {
						this.hideLayer();
					}.bind(this),
					onSuccess: function(r) {
						this.makeForgot(Json.evaluate(r, true));
		//				this.msg.box.setHTML(.text);
						this.showLayer();
					}.bind(this),
					onFailure: function(r) {
						this.makeForgot(Json.evaluate(r, true));
		//				this.msg.box.setHTML(Json.evaluate(r, true).text);
						this.showLayer();
					}.bind(this)
				}).send(
					'index.php?eID=tx_ajaxlogin_forgot',
					'action=getpassword&email=' + encodeURI($('forgot_mail').value)
				);
				
			}.bind(this));
		}
	},
	
	hideLayer: function() {
		
		if (!this.active) return;
		
		this.active = false;
		return this.fx3.stop().start({
			'width'  : 0,
			'opacity': 0
		});
	},
	
	showLayer: function() {
		if (this.active) return;
		
		this.active = true;
		return this.fx3.stop().start({
			'width': 760,
			'opacity': 1
		});
	},
	
	react: function(r) {
		
		r = Json.evaluate(r, true);
		this.data.status.login = r.login;
		this.msg.box.setHTML(r.message);
		
		
		if (r.show_message) this.showLayer();
		
		if (r.box) {
			this.el.box.setHTML(r.box);
			this.attachEvents();
		}
	},
	
	show: function() {
		this.box.setStyle("display", "block");
		this.el.box.setStyle("display", "block");
		this.msg.outer.setStyle("display", "block");
		
		
		// Position Login Link
		
		this.el.marker.setStyles({
			left: this.link.getLeft(),
			top:  this.link.getTop()
		});
		
		// Position Loginbox
		this.el.box.setStyles({
			left: $('balken-oben').getLeft(),
			top:  $('balken-oben').getTop() - 8
		});
		this.msg.outer.setStyles({
			top: this.el.box.getTop(),
			left: (this.el.box.getLeft() + this.el.box.getSize().size.x)
		});
		
		this.fx.stop().start( 0.75);
		this.fx2.stop().start(1);
		if (this.backupMsgBox) {
			this.msg.box.setStyle('display', 'block');
			this.fx3.stop().start({opacity: 1})
		}
		return false;
	},
	
	hide: function() {
	
		this.fx.stop().start(0);
		this.fx2.stop().start(0);
		
		if (this.msg.box.getStyle("opacity").toInt() > 0) {
			this.fx3.stop().start({opacity: 0})
			this.backupMsgBox = true;
			(function() { 
				this.msg.box.setStyle('display', 'none');
				this.msg.outer.setStyle("display", "none");
				this.box.setStyle("display", "none");
				this.el.box.setStyle("display", "none");  
				this.msg.outer.setStyle("display", "none");
			}.bind(this)).delay(350);
		}
		else {
			this.backupMsgBox = false;
		}
	}
});


		window.addEvent("domready", function() {
			var loginbox = new Ajax_Login({"labels":{"login":"Login","user":"Benutzername","pass":"Passwort","submit":"Anmelden","forgot":"Passwort vergessen","help":"Hilfe"},"box":"  <div class=\"header\"><img src=\"typo3conf\/ext\/ajax_login\/res\/images\/header_login.gif\"><\/div>\n  <form mehod=\"post\" action=\"index.php?eID=ajax_login\" name=\"loginform\" id=\"loginform\">\n    <input name=\"user\" type=\"text\" id=\"user\" value=\"Benutzername\">\n    <input name=\"pass\" type=\"text\" id=\"pass\" value=\"Passwort\">\n    <img class=\"button\" src=\"typo3conf\/ext\/ajax_login\/res\/pics\/login_normal.gif\" id=\"button\">\n  <\/form>\n  <div class=\"links\"><a href=\"#\" id=\"forgot-password\">Passwort vergessen?<\/a><a href=\"#\" id=\"login-help\">Hilfe<\/a><\/div>\n","login":false,"links":{"forgot":"service\/login\/passwort-vergessen.html","help":"service\/login\/hilfe.html","submit":"index.php?eID=ajax_login"},"status":{"login":false,"username":null},"help":"<div class=\"wrapper\">\n\t<div><img src=\"fileadmin\/templates\/images\/help.gif\" alt=\"\" \/><\/div>\n\t<p>F\u00fcr einen Login ben\u00f6tigen Sie einen Benutzernamen und ein Passwort, dass Ihnen von viamedia zur Verf\u00fcgung gestellt wird. Sollten Sie noch keine Zugangsdaten erhalten haben, nehmen Sie bitte Kontakt mit uns auf.<\/p>\n\t<p>Des weiteren ist die \u00dcberpr\u00fcfung der Eingaben case-sensitive, da her ist es wichtig auf eine korrekte Gro\u00df- und Kleinschreibung zu achten.<\/p>\n<\/div>"});
		});
var head_elements=[];
var Lightbox={init:function(A){this.options=Object.extend({resizeDuration:400,resizeTransition:Fx.Transitions.sineInOut,initialWidth:250,initialHeight:250,animateCaption:true,showNumbers:true,defaultIframeWidth:500,defaultIframeHeight:300,opacity:0.8,opacityDuration:500,iframeScrolling:"auto",enablePrintButton:0,enableSaveButton:0,llPage:"Page",llOf:"of",psScriptPath:""},A||{});if(window.ie6&&document.compatMode=="BackCompat"){this.options.animateCaption=false}this.anchors=[];$each(document.links,function(C){if(C.rel&&C.rel.test(/^lightbox/i)){C.onclick=this.click.pass(C,this);this.anchors.push(C)}},this);this.eventKeyDown=this.keyboardListener.bindAsEventListener(this);this.eventPosition=this.position.bind(this);this.overlay=new Element("div").setProperty("id","lbOverlay").injectInside(document.body);this.center=new Element("div").setProperty("id","lbCenter").setStyles({width:this.options.initialWidth+"px",height:this.options.initialHeight+"px",marginLeft:"-"+(this.options.initialWidth/2)+"px",display:"none"}).injectInside(document.body);this.canvas=new Element("div").setProperty("id","lbCanvas").injectInside(this.center);this.prevLink=new Element("a").setProperties({id:"lbPrevLink",href:"#"}).setStyle("display","none").injectInside(this.canvas);this.nextLink=this.prevLink.clone().setProperty("id","lbNextLink").injectInside(this.canvas);this.prevLink.onclick=this.previous.bind(this);this.nextLink.onclick=this.next.bind(this);this.bottomContainer=new Element("div").setProperty("id","lbBottomContainer").setStyle("display","none").injectInside(document.body);this.bottom=new Element("div").setProperty("id","lbBottom").injectInside(this.bottomContainer);new Element("a").setProperties({id:"lbCloseLink",href:"#"}).injectInside(this.bottom).onclick=this.overlay.onclick=this.close.bind(this);if(this.options.enablePrintButton&&this.options.psScriptPath){new Element("a").setProperties({id:"lbPrintLink",href:"#"}).injectInside(this.bottom).onclick=this.printOrSave.bind(this,"print")}if(this.options.enableSaveButton&&this.options.psScriptPath){new Element("a").setProperties({id:"lbSaveLink",href:"#"}).injectInside(this.bottom).onclick=this.printOrSave.bind(this,"save")}this.caption=new Element("div").setProperty("id","lbCaption").injectInside(this.bottom);this.number=new Element("div").setProperty("id","lbNumber").injectInside(this.bottom);new Element("div").setStyle("clear","both").injectInside(this.bottom);var B=this.nextEffect.bind(this);this.fx={overlay:this.overlay.effect("opacity",{duration:this.options.opacityDuration}).hide(),resizeCenter:this.center.effects({duration:this.options.resizeDuration,transition:this.options.resizeTransition,onComplete:B}),image:this.canvas.effect("opacity",{duration:this.options.opacityDuration,onComplete:B}),bottom:this.bottomContainer.effect("height",{duration:400,onComplete:B})};this.preloadPrev=new Image();this.preloadNext=new Image()},click:function(D){if(D.rel.length==8){return this.show(D.href,D.title,D.rev)}var B,C,A=[];this.anchors.each(function(E){if(E.rel==D.rel){for(B=0;B<A.length;B++){if(A[B][0]==E.href&&A[B][2]==E.rev){break}}if(B==A.length){A.push([E.href,E.title,E.rev]);if(E.href==D.href&&E.rev==D.rev){C=B}}}},this);return this.open(A,C)},show:function(B,C,A){return this.open([[B,C,A]],0)},open:function(B,D){this.items=B;this.position();this.setup(true);var A=(window.getHeight()==0)?window.getScrollHeight():window.getHeight();var C=document.body.scrollTop||document.documentElement.scrollTop;this.top=C+(A/15);this.center.setStyles({top:this.top+"px",display:""});this.fx.overlay.start(this.options.opacity);return this.changeItem(D)},position:function(){var C=(window.getWidth()==0)?window.getScrollWidth()-22:window.getWidth();var A=(window.getHeight()==0)?window.getScrollHeight():window.getHeight();var B=document.body.scrollTop||document.documentElement.scrollTop;this.overlay.setStyles({top:B+"px",height:A+"px",width:C+"px"})},setup:function(A){var C=$A(document.getElementsByTagName("object"));C.extend(document.getElementsByTagName(window.ie?"select":"embed"));C.each(function(D){if(A){D.lbBackupStyle=D.style.visibility}D.style.visibility=A?"hidden":D.lbBackupStyle});var B=A?"addEvent":"removeEvent";window[B]("scroll",this.eventPosition)[B]("resize",this.eventPosition);document[B]("keydown",this.eventKeyDown);this.step=0},keyboardListener:function(A){switch(A.keyCode){case 27:case 88:case 67:this.close();break;case 37:case 80:this.previous();break;case 39:case 78:this.next()}},previous:function(){return this.changeItem(this.activeItem-1)},next:function(){return this.changeItem(this.activeItem+1)},changeItem:function(C){if(this.step||(C<0)||(C>=this.items.length)){return false}this.step=1;this.activeItem=C;this.bottomContainer.style.display=this.prevLink.style.display=this.nextLink.style.display="none";this.fx.image.hide();this.center.className="lbLoading";this.removeCurrentItem();var B=this.items[this.activeItem][0];var A=this.items[this.activeItem][2];var D=/\.(jpe?g|png|gif|bmp)/i;if(B.match(D)){this.preload=new Image();this.preload.datatype="image";this.preload.w=this.matchOrDefault(A,new RegExp("width=(\\d+%?)","i"),-1);this.preload.h=this.matchOrDefault(A,new RegExp("height=(\\d+%?)","i"),-1);this.preload.onload=this.nextEffect.bind(this);this.preload.src=B}else{this.preload=new Object();this.preload.datatype="iframe";this.preload.w=this.matchOrDefault(A,new RegExp("width=(\\d+)","i"),this.options.defaultIframeWidth);this.preload.h=this.matchOrDefault(A,new RegExp("height=(\\d+)","i"),this.options.defaultIframeHeight);this.preload.src=B;this.nextEffect()}return false},nextEffect:function(){switch(this.step++){case 1:this.center.className="";if(this.preload.datatype=="image"){var ws=(this.preload.w==-1)?this.preload.width.toString():this.preload.w.toString();var hs=(this.preload.h==-1)?this.preload.height.toString():this.preload.h.toString();this.p_width=(q=ws.match(/(\d+)%/))?q[1]*this.preload.width*0.01:ws;this.p_height=(q=hs.match(/(\d+)%/))?q[1]*this.preload.height*0.01:hs;new Element("img").setProperties({id:"lbImage",src:this.preload.src,width:this.p_width,height:this.p_height}).injectInside(this.canvas);this.nextLink.style.right=""}else{this.p_width=this.preload.w;this.p_height=this.preload.h;this.iframeId="lbFrame_"+new Date().getTime();new Element("iframe").setProperties({id:this.iframeId,width:this.p_width,height:this.p_height,frameBorder:0,scrolling:this.options.iframeScrolling,src:this.preload.src}).injectInside(this.canvas);this.nextLink.style.right="25px"}this.canvas.style.width=this.bottom.style.width=this.p_width+"px";this.canvas.style.height=this.prevLink.style.height=this.nextLink.style.height=this.p_height+"px";this.caption.setHTML(this.items[this.activeItem][1]||"");this.number.setHTML((!this.options.showNumbers||(this.items==1))?"":this.options.llPage+" "+(this.activeItem+1)+" "+this.options.llOf+" "+this.items.length);if(this.activeItem){this.preloadPrev.src=this.items[this.activeItem-1][0]}if(this.activeItem!=(this.items.length-1)){this.preloadNext.src=this.items[this.activeItem+1][0]}if(this.center.clientHeight!=this.canvas.offsetHeight){var oh=(this.p_height==this.canvas.clientHeight)?this.canvas.offsetHeight:eval(this.p_height)+18;this.fx.resizeCenter.start({height:oh});break}this.step++;case 2:if(this.center.clientWidth!=this.canvas.offsetWidth){var ow=(this.p_width==this.canvas.clientWidth)?this.canvas.offsetWidth:eval(this.p_width)+18;this.fx.resizeCenter.start({width:ow,marginLeft:-ow/2});break}this.step++;case 3:this.bottomContainer.setStyles({top:(this.top+this.center.clientHeight)+"px",height:"0px",marginLeft:this.center.style.marginLeft,width:this.center.style.width,display:""});this.fx.image.start(1);break;case 4:if(this.options.animateCaption){this.fx.bottom.start(0,this.bottom.offsetHeight+10);break}this.bottomContainer.style.height=(this.bottom.offsetHeight+10)+"px";case 5:if(this.activeItem){this.prevLink.style.display=""}if(this.activeItem!=(this.items.length-1)){this.nextLink.style.display=""}this.step=0}},close:function(){if(this.step<0){return }this.step=-1;this.removeCurrentItem();for(var A in this.fx){this.fx[A].stop()}this.center.style.display=this.bottomContainer.style.display="none";this.fx.overlay.chain(this.setup.pass(false,this)).start(0);return false},printOrSave:function(B){if(this.options.psScriptPath){var A=window.open(this.options.psScriptPath+"?mode="+B+"&image="+this.items[this.activeItem][0],"printsave","left=0,top=0,width="+(parseInt(this.canvas.style.width))+",height="+(parseInt(this.canvas.style.height))+",toolbar=0,resizable=1");return false}return true},removeCurrentItem:function(){if(this.preload){if(this.preload.datatype=="image"){$("lbImage").remove();this.preload.onload=Class.empty}else{$(this.iframeId).remove()}this.preload=null}},matchOrDefault:function(D,B,C){var A=D.match(B);return A?A[1]:C}};
var Pngfix=new Class({initialize:function(A){if(window.ie&&!window.ie7){this.elements().each(function(D,B){var C=D.getSize();D.setStyle("filter",this.style(D.src)).setProperty("src",A).setStyles({height:C.size.y,width:C.size.x})},this)}},elements:function(){imgs=$$("img");pngs=[];for(var A=0;A<imgs.length;A++){if(this.format(imgs[A])=="png"){pngs.push(imgs[A])}}return pngs},format:function(A){return A.getProperty("src").split(".").getLast()},style:function(A){return"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+A+"', sizingMethod='scale')"}});window.addEvent("domready",function(){var A=new Pngfix("clear.gif")});
var Mainmenu_Hover;var Hover=new Class({elements:new Array(),current:null,cache:new Array(),initialize:function(A){A.each(function(C,B){if($type(C)=="element"&&$type(C.getProperty("rel"))=="string"&&C.getChildren().length>0){this.elements[B]={no:C.getChildren()[0].getProperty("src"),ho:this.getHover(C.getProperty("rel")),el:C.getChildren()[0]};this.preload(this.elements[B].ho,B);C.removeEvents("mouseenter").removeEvents("mouseleave").addEvents({mouseenter:function(){this.setCurrent(B).hover()}.bind(this),mouseleave:function(){this.setCurrent(B).normal()}.bind(this)})}}.bind(this));this.preload()},preload:function(B,A){this.cache[A]=new Image();this.cache[A].src=B},getHover:function(A){return A.split(":").getLast()},setCurrent:function(A){this.current=this.elements[A];return this},hover:function(){this.current.el.setProperty("src",this.current.ho)},normal:function(){this.current.el.setProperty("src",this.current.no)}});window.addEvent("domready",function(){Mainmenu_Hover=new Hover($$("#head ul a"))});
function doSomethingStrange() { document.write('&#64;'); }
  function doSomethingWeired() { document.write('&#46;'); }
window.addEvent('domready', Lightbox.init.bind(Lightbox,{resizeDuration: 400, resizeTransition: Fx.Transitions.sineInOut, opacity: 0.8, opacityDuration: 500, initialWidth: 250, initialHeight: 250, animateCaption: 1, showNumbers: 1, defaultIframeWidth: 500, defaultIframeHeight: 300, iframeScrolling: 'auto', enablePrintButton: 0, enableSaveButton: 0,llPage: 'Bild', llOf: 'von', psScriptPath: 'http://www.viamedia.at/typo3conf/ext/pmkslimbox/savefile.php'}));


