window.oldOnLoad = (window.onload) ? window.onload : new Function;
window.onload = function() {
    var links = document.getElementsByTagName('a');
    for(var i=0;i<links.length;i++) {
        if(links[i].href.substr(location.protocol.length+2, location.hostname.length)!=location.hostname
          || links[i].href.substr(links[i].href.length-4)==".jpg"
          || links[i].href.substr(links[i].href.length-4)==".pdf"
          || links[i].href.substr(links[i].href.length-4)==".gif"
          || links[i].href.substr(links[i].href.length-4)==".png"
          || links[i].href.substr(links[i].href.length-4)==".zip"
          || links[i].href.substr(links[i].href.length-4)==".doc"
          || links[i].href.substr(links[i].href.length-4)==".xls") {
            if(links[i].href.substr(0, 11)=='javascript:') continue;
            links[i].oldOnClick = (links[i].onclick) ? links[i].onclick : new Function;
            links[i].onclick = function() {
                statistikCountExternalLink(this.href);
                if(this.rel == "extern" || this.rel == "download") {
                    window.open(this.href);
                    return false;
                }
                return this.oldOnClick();
            }
        } else if(links[i].rel=="extern" || links[i].rel=="download") {
            links[i].onclick = function() {
                window.open(this.href);
                return false;
            }
        }
    }

    var windowWidth, windowHeight;
    if (self.innerHeight) { // all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    var req = loadXMLHttpRequest();
    if(req) {
        req.open('POST', '/statistik_count_screen', true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        var data = 'windowWidth='+encodeURIComponent(windowWidth);
        data += '&windowHeight='+encodeURIComponent(windowHeight);
        data += '&screenWidth='+encodeURIComponent(screen.width);
        data += '&screenHeight='+encodeURIComponent(screen.height);
        data += '&flashVersion='+encodeURIComponent(getSwfVer());
        req.send(data);
    }
    window.oldOnLoad();
}

function statistikCountExternalLink(href)
{
  var req = loadXMLHttpRequest();
  if(!req) return(false);
  req.open('POST', '/statistik_count', true);
  req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  req.send('href='+encodeURIComponent(href)+'&ref='+encodeURIComponent(location.href));
}

var blockCloseAll = function() {
    var divs = document.getElementsByTagName('div');
    for(i=0;i<divs.length;i++) {
        if(divs[i].className=='blockOpened') {
            blockSwitch(divs[i]);
        }
    }
};

var blockSwitch = function(tag) {
    if(tag.className=='blockOpened') {
        tag.className='blockClosed';
    } else if(tag.className=='blockClosed') {
        tag.className='blockOpened';
    } else if(tag.parentNode) {
        blockSwitch(tag.parentNode);
    }
};


function evalHandler(response) {
    try {
        eval(response);
    } catch(e) {
        alert('Ein Fehler beim Updaten ist aufgetrenten: '+e.toString());
    }
}

function _postback(url, data, handler)
{
  var req = loadXMLHttpRequest();
  if(!req) return(false);

  var content = '';
  for(var i in data)
  {
    content += (content.length ? '&' : '') + i + '=' + encodeURIComponent(data[i]);
  }

  function callBack()
  {
    if(req.readyState == 4)
    {
      if(req.status == 200)
      {
        if(typeof handler == 'function')
        handler(req.responseText, req);
      }
      else
      {
        alert('An error has occurred: ' + req.statusText);
      }
    }
  }

  req.onreadystatechange = callBack;

  req.open('POST', url, true);
  req.setRequestHeader
  (
      'Content-Type',
      'application/x-www-form-urlencoded; charset=UTF-8'
  );
  //alert(content);
  req.send(content);
}


function loadXMLHttpRequest() {
    var pageRequest = false;
    /*@cc_on
    @if (@_jscript_version >= 5)
        try {
            pageRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                pageRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                pageRequest = false;
            }
        }
    @end
    @*/

    if (!pageRequest && typeof XMLHttpRequest != 'undefined') {
        pageRequest = new XMLHttpRequest()
    }
    return pageRequest;
}

// JavaScript helper required to detect Flash Player PlugIn version information
/* some parts by quirksmode.org and www.javascriptkit.com/javatutors/conditionalcompile3.shtml */
function getSwfVer(i){

    /*@cc_on
    @if (@_jscript_version >= 5)
        // IE flash detection.
        for(var i=17; i>0; i--){
                try{
                        var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
                        if(flash) {
                            return i;
                        }
                }
                catch(e){
                }
        }
    @end
    @*/

    // NS/Opera version >= 3 check for Flash plugin in plugin array
    if (navigator.plugins != null && navigator.plugins.length > 0) {
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
            var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
            descArray = flashDescription.split(" ");
            tempArrayMajor = descArray[2].split(".");
            return tempArrayMajor[0];
        } else {
            flashVer = -1;
        }
    }
    // MSN/WebTV 2.6 supports Flash 4
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
    // WebTV 2.5 supports Flash 3
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
    // older WebTV supports Flash 2
    else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    // Can't detect in all other cases
    else {

        flashVer = -1;
    }
    return flashVer;
}





/*
Parts Based on Dynamic Heading Generator By Stewart Rosenberger www.stewartspeak.com

Parts based on code by Dean Edwards/Matthias Miller/John Resig dean.edwards.name

Parts Based on Lightbox by Lokesh Dhakar www.huddletogether.com
Creative Commons Attribution 2.5 License

*/
var imageLoaded = false;
var initDone = false;

document.write('<link id="hide-flicker" rel="stylesheet" media="screen" href="/css/replacement-screen.css" />');
window.flickerCheck = function()
{
    if(!imageLoaded)
        setStyleSheetState('hide-flicker',false);
};
setTimeout('window.flickerCheck();', 1000)

var replaceItems = [];
replaceSelector("h1.grafikheadline","/heading.php", false);
replaceSelector(".bannerrot h1.headline","/heading.php", false);
replaceSelector(".bannerorange h1.headline","/heading.php", false);


var test = new Image();
test.onload = function() {
    imageLoaded = true;
    if(initDone) replacement();
}
test.src = "/files/test.png?date=" + (new Date()).getTime();

function init()
{
    // quit if this function has already been called
    if (initDone) return;

    // flag this function so we don't do the same thing twice
    initDone = true;

    // kill the timer
    if (_timer) clearInterval(_timer);

    if(imageLoaded) {
        replacement();
    }

    //download-links und externe links in neuem fenster öffnen
    //links auf fremde domains per ajax zählen
    var links = document.getElementsByTagName('a');
    for(var i=0;i<links.length;i++) {
        if(links[i].href.substr(location.protocol.length+2, location.hostname.length)!=location.hostname
        && links[i].href.substr(0, 11)!='javascript:') {
            links[i].oldOnClick = (links[i].onclick) ? links[i].onclick : new Function;
            links[i].onclick = function() {
                statistikCountExternalLink(this.href);
                if(this.rel == "extern" || this.rel == "download") {
                    window.open(this.href);
                    return false;
                }
                return this.oldOnClick();
            }
        } else if(links[i].rel=="extern" || links[i].rel=="download") {
            links[i].onclick = function() {
                window.open(this.href);
                return false;
            }
        }
    }
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
        document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
        var script = document.getElementById("__ie_onload");
        script.onreadystatechange = function() {
                if (this.readyState == "complete") {
                        init(); // call the onload handler
                }
        };
/*@end @*/

/* for Safari */
if (/KHTML|WebKit/i.test(navigator.userAgent)) { // sniff
        var _timer = setInterval(function() {
                if (/loaded|complete/.test(document.readyState)) {
                        init(); // call the onload handler
                }
        }, 10);
}

/* for other browsers */
window.onload = init;


function replaceSelector(selector,url,hover)
{
    if(typeof replaceItems == "undefined")
        replaceItems = new Array();

    replaceItems[replaceItems.length] = {selector: selector, url: url, hover: hover};
}


function replacement()
{
    for(var i=0;i<replaceItems.length;i++)
    {
        var elements = getElementsBySelector(replaceItems[i].selector);
        if(elements.length > 0) for(var j=0;j<elements.length;j++)
        {
            if(!elements[j]) continue;

            var element = elements[j];

            var text = extractText(elements[j]);
            text = text.replace(/^\s*|\s*$/g,""); //trim

            while(elements[j].hasChildNodes())
                elements[j].removeChild(elements[j].firstChild);

            var url = replaceItems[i].url + "?text="+escape(text)+"&selector="+escape(replaceItems[i].selector);

            var image = document.createElement("img");
            image.className = "replacement";
            image.alt = text.replace("[v]","").replace("[>]",""); //die pfeile aus dem alttext rausnehmen
            if(elements[j].tagName.toLowerCase()=='button') {
                //wenn parent ein button ist die breite händisch setzen
                //weil der ie macht ihn um ein paar pixel zu breit
                //+1 weil er sonst beim tollen onmousedown-effekt vom ie abgeschnitten wird
                image.onload = function() {
                    if(this.width > 0) {
                        this.parentNode.style.width = (this.width+1)+'px';
                    }
                }
            }
            elements[j].appendChild(image); //bevor src gesetzt wird!
            image.src = url;

            if(replaceItems[i].hover) {
                elements[j].hoverSrc = url+"&hover";
                var preload = new Image();
                preload.src = elements[j].hoverSrc;
                elements[j].originalSrc = url;
                elements[j].onmouseover = function() {
                    if(this.firstChild.src!=this.hoverSrc)
                        this.firstChild.src = this.hoverSrc;
                }
                elements[j].onmouseout = function() {
                    if(this.firstChild.src!=this.originalSrc)
                        this.firstChild.src = this.originalSrc;
                }
            }
        }
    }

    setStyleSheetState('hide-flicker',false);
}

function setStyleSheetState(id,enabled)
{
    var sheet = document.getElementById(id);
    if(sheet)
        sheet.disabled = (!enabled);
}

function extractText(element)
{
    if(typeof element == "string")
        return element;
    else if(typeof element == "undefined")
        return element;
    //else if(element.innerText) doesn't return brs
    //    return element.innerText; 

    var text = "";
    var kids = element.childNodes;
    for(var i=0;i<kids.length;i++)
    {
        if (kids[i].nodeName.toLowerCase()=='br') {
            text += '<br />';
        }
        if(kids[i].nodeType == 1) {
            text += extractText(kids[i]);
        } else if(kids[i].nodeType == 3) {
            text += kids[i].nodeValue;
        }
    }
    return text;
}

/*
    Finds elements on page that match a given CSS selector rule. Some
    complicated rules are not compatible.
    Based on Simon Willison's excellent "getElementsBySelector" function.
    Original code (with comments and description):
        http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
*/
function getElementsBySelector(selector)
{
    var tokens = selector.split(' ');
    var currentContext = new Array(document);
    for(var i=0;i<tokens.length;i++)
    {
        token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
        if(token.indexOf('#') > -1)
        {
            var bits = token.split('#');
            var tagName = bits[0];
            var id = bits[1];
            var element = document.getElementById(id);
            if(!element || (tagName && element.nodeName.toLowerCase() != tagName))
                return new Array();
            currentContext = new Array(element);
            continue;
        }

        if(token.indexOf('.') > -1)
        {
            var bits = token.split('.');
            var tagName = bits[0];
            var className = bits[1];
            if(!tagName)
                tagName = '*';

            var found = new Array;
            var foundCount = 0;
            for(var h=0;h<currentContext.length;h++)
            {
                var elements;
                if(tagName == '*')
                    elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
                else
                    elements = currentContext[h].getElementsByTagName(tagName);

                for(var j=0;j<elements.length;j++)
                    found[foundCount++] = elements[j];
            }

            currentContext = new Array;
            var currentContextIndex = 0;
            for(var k=0;k<found.length;k++)
            {
                if(found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b')))
                    currentContext[currentContextIndex++] = found[k];
            }

            continue;
        }

        if(token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/))
        {
            var tagName = RegExp.$1;
            var attrName = RegExp.$2;
            var attrOperator = RegExp.$3;
            var attrValue = RegExp.$4;
            if(!tagName)
                tagName = '*';

            var found = new Array;
            var foundCount = 0;
            for(var h=0;h<currentContext.length;h++)
            {
                var elements;
                if(tagName == '*')
                    elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
                else
                    elements = currentContext[h].getElementsByTagName(tagName);

                for(var j=0;j<elements.length;j++)
                    found[foundCount++] = elements[j];
            }

            currentContext = new Array;
            var currentContextIndex = 0;
            var checkFunction;
            switch(attrOperator)
            {
                case '=':
                    checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
                    break;
                case '~':
                    checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
                    break;
                case '|':
                    checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
                    break;
                case '^':
                    checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
                    break;
                case '$':
                    checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
                    break;
                case '*':
                    checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
                    break;
                default :
                    checkFunction = function(e) { return e.getAttribute(attrName); };
            }

            currentContext = new Array;
            var currentContextIndex = 0;
            for(var k=0;k<found.length;k++)
            {
                if(checkFunction(found[k]))
                    currentContext[currentContextIndex++] = found[k];
            }

            continue;
        }

        tagName = token;
        var found = new Array;
        var foundCount = 0;
        for(var h=0;h<currentContext.length;h++)
        {
            var elements = currentContext[h].getElementsByTagName(tagName);
            for(var j=0;j<elements.length; j++)
                found[foundCount++] = elements[j];
        }

        currentContext = found;
    }

    return currentContext;
}


