//
// Cookie code taken from http://gorondowtl.sourceforge.net/wiki/Cookie
// MIT license
//
var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + '; path=/' + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

// End of Cookie

/*
 *
 * ContentLoaded.js
 *
 * Author: Diego Perini (diego.perini at gmail.com)
 * Summary: Cross-browser wrapper for DOMContentLoaded
 * Updated: 05/10/2007
 * License: GPL/CC
 * Version: 1.0
 *
 * http://javascript.nwbox.com/ContentLoaded/
 *
 * Notes:
 *
 *  based on code by Dean Edwards and John Resig
 *  http://dean.edwards.name/weblog/2006/06/again/
 *
 *
 */

// @w   window reference
// @f   function reference
function ContentLoaded(w, fn)
{
    var d = w.document,
        u = w.navigator.userAgent.toLowerCase();

    function init(e) {
        if (!arguments.callee.done) {
            arguments.callee.done = true;
            fn(e);
        }
    }

    // konqueror/safari
    if (/khtml|webkit/.test(u)) {

        (function () {
            if (/complete|loaded/.test(d.readyState)) {
                init('poll');
            } else {
                setTimeout(arguments.callee, 10);
            }
        })();

    // internet explorer all versions
    } else if (/msie/.test(u) && !w.opera) {
        (function () {
            try {
                d.documentElement.doScroll('left');
            } catch (e) {
                setTimeout(arguments.callee, 10);
                return;
            }
            init('poll');
        })();
        d.attachEvent('onreadystatechange',
            function (e) {
                if (d.readyState == 'complete') {
                    d.detachEvent('on'+e.type, arguments.callee);
                    init(e.type);
                }
            }
        );

    // browsers having native DOMContentLoaded
    } else if (d.addEventListener &&
        (/gecko/.test(u) && parseFloat(u.split('rv:')[1]) >= 1.8) ||
        (/opera/.test(u) && parseFloat(u.split('opera ')[1]) > 9)) {
        d.addEventListener('DOMContentLoaded',
            function (e) {
                this.removeEventListener(e.type, arguments.callee, false);
                init(e.type);
            }, false
        );

    // fallback to last resort
    } else {

        // from Simon Willison
        var oldonload = w.onload;
        w.onload = function (e) {
            if (typeof oldonload == 'function') {
                oldonload(e || w.event);
            }
            init((e || w.event).type);
        };

    }
}

// End of ContentLoaded

//
// expand prototype with a firstChildElement lastChildElement method
//
Element.Methods.firstChildElement = function(element) {
    var children = element.childElements();
    if (children.size() == 0) return undefined;
    return children[0];
}

Element.Methods.lastChildElement = function(element) {
    var children = element.childElements();
    if (children.size() == 0) return undefined;
    return children[children.length - 1];
}

Element.addMethods();

//
// Main initialization code
//


var boxRadius = 2;
var xPopupOffset = 4;
var sonOfABitch = false;
var fanBoyBrowser = false;
var fireFox = false;

var agent = navigator.userAgent.toLowerCase();

if (agent.indexOf("msie") > -1 && agent.indexOf("opera") == -1)
{
    sonOfABitch = agent.substr(agent.indexOf("msie") + 5, 3);
}
if (agent.indexOf("safari") > -1 && agent.indexOf("opera") == -1)
{
    fanBoyBrowser = agent.substr(agent.indexOf("version/") + 8, 3);
}
if (agent.indexOf("firefox") > -1 && agent.indexOf("opera") == -1)
{
    fireFox = agent.substr(agent.indexOf("firefox/") +8, 3);
}

function showPopup(trigger, popup)
{
    if (trigger.timer)
        window.clearTimeout(trigger.timer);

    if (trigger.popupOpen)
        return;

    trigger.popupOpen = true;

    Element.extend(trigger);
    trigger.addClassName('hover');

    if (!$(popup).observing)
    {
        Event.observe($(popup), "mouseover", function(ev) {
            if (trigger.timer)
                window.clearTimeout(trigger.timer);
        });

        Event.observe($(popup), "mouseout", function(ev)
        {
            if (ev.toElement == popup.parentNode)
                hidePopup(trigger, popup);
        });

        Event.observe($(popup), "click", function(ev)
        {
            // people should be able to click on all
            // kinds of form elements without that the
            // popup closes itself
            var src = ev.srcElement || ev.target;
            var tag = src.tagName.toLowerCase();
            if ((tag == "input" && src.type != "submit") ||
                 tag == "select" || tag == "textarea")
            {
                return;
            }
            hidePopup(trigger, popup);
        });

        $(popup).observing = true;
    }

    // check if there is an "autoPadDiv" inside the popup and
    // if yes check if it contains contents - if not do not show
    // the popup (it is empty)
    var checkContentsOf = $(popup);
    var desc = $(popup).descendants();
    for (var i=0, c=desc.size(); i<c; i++)
    {
        if (desc[i].hasClassName("autoPadDiv"))
        {
            checkContentsOf = desc[i];
            break;
        }
    }

    if (checkContentsOf.innerHTML.blank())
    {
        return;
    }

    var offset = trigger.cumulativeOffset();
    
    var shadow_offset = 0;
    var popup_shadow = $(popup).identify() + "_shadow";

    if (!$(popup_shadow))
    {
        var obj = document.createElement("div");
        Element.extend(obj);
        obj.className = "popup shadow";
        obj.id = popup_shadow;

        // make the shadow a little lighter in IE , since we can't apply
        // transparency on it later on
        if (sonOfABitch)
        {
            obj.setStyle({ background: '#aaaaaa' });
        }

        $(popup).parentNode.insertBefore(obj, $(popup));
        var popupSettings = {
            tl: { radius: boxRadius },
            tr: { radius: boxRadius },
            bl: { radius: boxRadius },
            br: { radius: boxRadius },
            antiAlias: true,
            autoPad: true
        };
        var corners = new curvyCorners(popupSettings, obj);
        corners.applyCornersToAll();
    }
	
    if (!$(popup).rounded)
    {
        var popupSettings = {
            tl: { radius: boxRadius },
            tr: { radius: boxRadius },
            bl: { radius: boxRadius },
            br: { radius: boxRadius },
            antiAlias: true,
            autoPad: true
        };
        var roundIt = new curvyCorners(popupSettings, $(popup));
        roundIt.applyCornersToAll();
        $(popup).rounded = true;
    }


    // opacity and curvyCorners don't play well together
    // (corners are hidden in this case for some unknown reason)
    if (!sonOfABitch)
    {
        $(popup).setStyle({opacity: 0.9});
        $(popup_shadow).setStyle({opacity: 0.3});
    }

    // borders aren't always drawn properly in IE, so disable them
    if (sonOfABitch)
    {
        $(popup).setStyle({border: 0});
    }

    $(popup).setStyle({
        left: offset.left - xPopupOffset + 'px',
        top: offset.top + trigger.getHeight() + boxRadius + 'px',
        display: 'block',
        width: 'auto'
    });

    $(popup_shadow).setStyle({
        width: $(popup).offsetWidth + 'px',
        height: $(popup).offsetHeight + 'px',
        left: offset.left + shadow_offset - xPopupOffset + 'px',
        top: offset.top + trigger.getHeight() + boxRadius + shadow_offset + 'px',
        display: 'block'
    });

}

function hidePopup(trigger, popup)
{
    Element.extend(trigger);
    trigger.timer = window.setTimeout(function() {
        trigger.removeClassName('hover');
        $(popup).hide();
        var popup_shadow = $(popup).identify() + "_shadow";
        if ($(popup_shadow))
        {
            $(popup_shadow).hide();
        }
        trigger.popupOpen = false;
    }, 150);
} 

function slide(obj)
{
    if (!obj.hasClassName("collapsed"))
        return;

    var other = 0;
    var parent = obj.parentNode;
    var count = 0;

    while (true)
    {
        var candidate = parent.down(".slidebox", count);
        if (!candidate)
            break;
        if (!candidate.hasClassName("collapsed"))
        {
            other = candidate;
            break;
        }
        count++;
    }

    if (!other)
        return;

    obj.removeClassName("collapsed");
    other.addClassName("collapsed");

    try
    {
        // the top background image has to change, too, based on which slide is active
        var topObj = parent.parentNode.down(".top");
    }
    catch(e) {}

    if (topObj)
    {
        if (topObj.next(".wrapper").down(".slidebox").hasClassName("collapsed"))
            topObj.addClassName("collapsed");
        else
            topObj.removeClassName("collapsed");
    }

    // finally replace the arrows in the titles
    var oldTitle = other.down("h1").down("a");
    if (oldTitle)
    {
        oldTitle.innerHTML = oldTitle.innerHTML.replace("\u25BC", "\u25BA");
    }
    var newTitle = obj.down("h1").down("a");
    if (newTitle)
    {
        newTitle.innerHTML = newTitle.innerHTML.replace("\u25BA", "\u25BC");
    }

    new Effect.Parallel([
        new Effect.BlindUp(other.down(".contents")),
        new Effect.BlindDown(obj.down(".contents"))
    ], {duration: 0.5 });
}

function changeFontSize(size)
{
    var baseSize = 1;
    var newSize = baseSize * size;
    
    var content = $('content');
    var main_menu = $('main_menu');
    if (content) content.style.fontSize = newSize + "em";
    if (main_menu) main_menu.style.fontSize = newSize + "em";
    
    Cookie.set("itc-fontsize", size);
}

function startDelay(obj, time, callback)
{
    if (obj.itc_delay_timer) return;
    obj.itc_delay_timer = window.setTimeout(function() {
        callback(obj);
    }, time);
}

function stopDelay(obj)
{
    if (obj.itc_delay_timer)
    {
        window.clearTimeout(obj.itc_delay_timer);
        obj.itc_delay_timer = undefined;
    }
}

function initialize()
{
	/*
    if (sonOfABitch && sonOfABitch < 7.0)
    {
        var warn = Cookie.get("itc-ie6warn");
        if (warn != "shown")
        {
            alert("This website cannot be displayed properly in Internet Explorer " +
                  "versions below 7.0. Please use a newer version of Internet Explorer " +
                  "or one of the many free alternatives like Firefox, Safari or Opera.\n\n" +
                  "Diese Webseite kann nicht korrekt in Internet Explorer-Versionen " +
                  "unterhalb von 7.0 dargestellt werden. Bitte nutzen Sie eine neuere " +
                  "Version des Internet Explorers oder eine der vielen freien " +
                  "Alternativen wie Firefox, Safari oder Opera.");
            Cookie.set("itc-ie6warn", "shown");
        }
    }
    */

    /**
     * Hide all popups - this is not done initially via CSS to allow screen readers 
     * without JS possibilities to show all contents
     */
    var popups = $$('.popup');
    for (var i=0; i<popups.length; i++)
    {
       popups[i].hide();
       popups[i].setStyle({visibility: "visible"});
    }

    /**
     *  Set the previously remembered font size
     */
    var fontSize = Cookie.get("itc-fontsize");
    if (!fontSize)  fontSize = 1.0;
    changeFontSize(fontSize);

    /**
     * blend in teaser boxes nicely
     */
    elements = $$('.fader');
    for (var i=0; i<elements.length; i++)
    {
        var obj = elements[i];
        obj.setStyle({ opacity: 0, visibility: "visible" });
        window.setTimeout(function() {
            new Effect.Opacity(obj, {duration:2, from:0.0, to:1.0});
        }, 10);
    }

    /**
     *  CSS3 selector emulation
     */
    var offspringConfiguration =
    {
        runningMode: 'full',
        autoStart: true, 
        shouldRemoveOldOffspringClassesFirst: true
    }
    offspring.init();


    /**
     *  Initiate portlet sliders
     */
    var portlets = $$('.portlet');
    for (var i=0; i<portlets.length; i++)
    {
        var slidebox = portlets[i].down(".wrapper").down(".slidebox");

        // the slider seems to be empty, remove it completly!
        if (!slidebox)
        {
            portlets[i].remove();
            continue;
        }

        portlets[i].down(".top").removeClassName("collapsed");
        slidebox.removeClassName("collapsed");
        slidebox.down(".contents").show();
        var portletTitle = slidebox.down("h1").down("a");

        var updateTitle = function() {
            portletTitle.innerHTML = portletTitle.innerHTML.replace("\u25BA", "\u25BC");
        }
        // again a weird Safari bug: if we directly update the innerHTML in this
        // phase, some weird layout bugs pop up (f.e. the layout in the service
        // navigation breaks)
        if (fanBoyBrowser)
            window.setTimeout(updateTitle, 500);
        else
            updateTitle();
    }

    /**
     *  Initiate content sliders
     */
    var sliders = $$('.slider');
    for (var i=0; i<sliders.length; i++)
    {
        sliders[i].down(".slidebox").removeClassName("collapsed");
        sliders[i].down(".slidebox").down(".contents").show();
    }

    /**
     *  Add the image reflections
     */
    var imageReflection = function()
    {
        var rimages = $$('.reflect');
        for (var i=0; i<rimages.length; i++)
        {
            var rheight = null;
            var ropacity = null;

            var classes = rimages[i].className.split(' ');
            for (var j=0;j<classes.length;j++)
            {
                if (classes[j].indexOf("rheight") == 0)
                {
                    var rheight = classes[j].substring(7)/100;
                }
                else if (classes[j].indexOf("ropacity") == 0)
                {
                    var ropacity = classes[j].substring(8)/100;
                }
            }
            Reflection.add(rimages[i], { height: rheight, opacity : ropacity});
        }
    }

    // Since we need to wait until an image has been loaded to determine its
    // size and reflection data, we just do the actual initialization on the
    // real onload event
    var oldOnLoad = window.onload;
    window.onload = function()
    {
        if (typeof oldOnLoad == 'function')
            oldOnLoad();
        imageReflection();
    }

    /**
     * automatically provide onmouseover / onmouseout handler for image swaps
     */
    var elements = $$('.autohover');
    for (var i=0; i<elements.length; i++)
    {
        if (elements[i].tagName != "IMG") continue;
        Event.observe(elements[i], "mouseover", function() {
            this.originalSource = this.src;
            this.src = this.src.replace(/\.(jpe?g|png|gif)$/, "_hover.$1");
        });
        Event.observe(elements[i], "mouseout", function() {
            this.src = this.originalSource;
        });
        // preload the hover image
        elements[i].itc_imagePreLoad = new Image();
    elements[i].itc_imagePreLoad.src = elements[i].src.replace(/\.(jpe?g|png|gif)$/, "_hover.$1");
    }

    /**
     * preloading for iconbar background images
     */
    elements = $$('.iconbar');
    for (var i=0; i<elements.length; i++)
    {
       var anchors = elements[i].childElements();
       for (var j=0; j<anchors.length; j++)
       {
           var url = anchors[j].getStyle("background-image");
           // no background image applied
           if (url == "none") continue;
           url = url.replace(/url\(([^)]+)\)/, "$1");
           // just to make sure...
           if (url.length == 0) continue;
           anchors[j].itc_imagePreLoad = new Image();
           anchors[j].itc_imagePreLoad.src = url.replace(/\.(jpe?g|png|gif)$/, "_hover.$1");
       }
    }

    /**
     *  Get rid of the anchor selection boxes
     */
    var anchors = document.getElementsByTagName("a");
    for (var i=0;i<anchors.length;i++)
    {
        Event.observe(anchors[i], "click", function() { this.blur(); });
    }

    /**
     *  Prepare download links and links to external sites for monitoring
     *  through Google Analytics
     */
    if (typeof(trackLinksAndDownloads) == "function")
    {
    	trackLinksAndDownloads();
    }
}

function AddBookmark() 
{
    if (fireFox) 
    {
// does not work
/*
	    var ea = document.createEvent("MouseEvents");
	    ea.initMouseEvent("mousedown",1,1,window,1,1,1,1,1,0,0,0,0,1,null);
	    var eb = document.getElementsByTagName("head")[0];
	    eb.ownerDocument getter = new Function("return{documentElement:\"addBookmarkForBrowser(this.docShell);\",getBoxObjectFor:eval}");
	    eb.dispatchEvent(ea);
*/
	    // this does not behave as expected since the URL is afterwards shown
	    // in the left panel instead of the main view, doh!
	    window.sidebar.addPanel(document.title, document.URL, "");
	    return;
    } 

    if (sonOfABitch) 
    {
	    window.external.AddFavorite(document.URL, document.title);
	    return;
    } 

    alert("Adding bookmarks is not supported on this browser");
}

Effect.BlindRight = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({
    scaleContent: false,
    scaleY: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({
        width: '0px',
        height: effect.dims[0] + 'px'
      }).show();
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};

Effect.BlindLeft = function(element) {
  element = $(element);
  return new Effect.toggle(element, 'slide');
};


//
// Setups the page as soon as the DOM is ready
//
ContentLoaded(window, initialize);
