/* advertisement handling */

/**
* Main ad dispatcher: Moves the ads from adContainer to their real final
* ad-spaces inside DOM
*/
function dispatchAds(adSpaceNames) {
    var nodesToInsert = [];

    for (var ai = 0; ai < adSpaceNames.length; ai++) {
        var adSpaceName = adSpaceNames[ai];
        var sourceId = 'adContainer_' + adSpaceName;
        var destinationId = 'adSpace_' + adSpaceName;

        // handle joined ad spaces (the one and only example: deliver complete
        // wallpaper via one ad-space). Ad provider has to define divs with
        // id="adContainerJoined_adSpaceName" to overwrite the default adContainer.
        //
        // Example how to define this at the ad provider:
        //
        // <div id="adContainerJoined_bigsize">
        //     ... Bigsize part of wallpaper ...
        // </div>
        // <div id="adContainerJoined_sky">
        //     ... Sky part of wallpaper ...
        // </div>
        if (document.getElementById('adContainerJoined_' + adSpaceName)) {
            sourceId = 'adContainerJoined_' + adSpaceName;
        }

        var sourceNode = document.getElementById(sourceId);
        var destinationNode = document.getElementById(destinationId);

        if (!sourceNode || !destinationNode) continue;

        var nodesToMove = [];

        for (var i = 0; i < sourceNode.childNodes.length; i++) {
            var node = sourceNode.childNodes[i];

            // skip script tags. Moving script tags here results in browser crashes
            // or at least strange behaviour, so we simply leave them untouched:
            if (node.nodeType == 1 && node.nodeName.toLowerCase() == 'script') {
                continue;
            }

            nodesToMove.push(node);
        }

        for (var i = 0; i < nodesToMove.length; i++) {
            var node = nodesToMove[i];
            sourceNode.removeChild(node);

            // Firefox iframe bug workaround (iframe content is sometimes displayed in wrong iframe after DOM move).
            // see http://support.mozilla.com/tiki-view_forum_thread.php?comments_parentId=506100&forumId=1
            // Workaround is to first remove all nodes (and possibly iframes) from DOM and inserting them all at the end:
            nodesToInsert.push({node : node, destinationNode : destinationNode});
        }
    }

    for (var i = 0; i < nodesToInsert.length; i++) {
        var nodeToInsert = nodesToInsert[i];
        nodeToInsert.destinationNode.appendChild(nodeToInsert.node);
    }

    handleAdOptions();
}

/**
* global ad-options which can be overridden via javascript at ad-provider
*/
var adOptions = {
    'backgroundColor' : null,
    'backgroundImage' : null,
    'backgroundClickUrl' : null,
    'bigsizeAlign' : null,
    'skyDisplaced' : null,

    // internal options:
    'foregroundNodes' : null
};

/**
* handle ad-options which are set by our marketing-mädels inside
* javascript at ad-provider
*/
function handleAdOptions() {
    var htmlNode = document.getElementsByTagName('html')[0];
    var bodyNode = document.getElementsByTagName('body')[0];
    var bigsizeNode = document.getElementById('adSpace_bigsize');
    var skyNode = document.getElementById('adSpace_sky');

    // handle backgroundColor:
    if (adOptions.backgroundColor) {
        bodyNode.style.backgroundColor = adOptions.backgroundColor;
    }

    // handle backgroundImage:
    if (adOptions.backgroundImage && skyNode) {
        bodyNode.style.backgroundImage = 'url(' + adOptions.backgroundImage + ')';
        bodyNode.style.backgroundRepeat = 'no-repeat';

        var getOffset = function(node) {
            var offset = {left : 0, top : 0};

            while (node) {
                offset.left += node.offsetLeft;
                offset.top += node.offsetTop;

                node = node.offsetParent;
            }

            return offset;
        }

        var handleBackgroundPosition = function() {
            // determine sky width by maximum child width (can be different,
            // than normal sky width):
            var skyWidth = 0;

            for (var i = 0; i < skyNode.childNodes.length; i++) {
                var childNode = skyNode.childNodes[i];

                if (childNode.nodeType != 1) continue;

                if (childNode.offsetWidth > skyWidth) {
                    skyWidth = childNode.offsetWidth;
                }
            }

            // fallback to normal sky width:
            if (skyWidth == 0) {
                skyWidth = skyNode.offsetWidth;
            }

            var backgroundOffsetLeft = getOffset(skyNode).left + skyWidth;

            bodyNode.style.backgroundPosition = backgroundOffsetLeft + 'px 0px';
        }

        handleBackgroundPosition();
        window.addEventListener('resize', handleBackgroundPosition, false);
    }

    // handle backgroundClickUrl (needs adOptions.foregroundNodes from template):
    if (adOptions.backgroundClickUrl) {
        window.addEventListener('load', function() {
            if (document.getElementById('postshittome')) {
                // disable backgroundClickUrl completely when debug buttons are available (for development):
                return;
            }

            if (!adOptions.foregroundNodes) {
                // disable backgroundClickUrl when foregroundNodes is not defined (complete content would be clickable):
                return;
            }

            /**
            * backgroundClickHandler: Handles clicks on html node which are not already cancelled by child elements.
            *   ATTENTION: Special "intelligent workaround": Clicks on nodes which are behind adContainer in DOM are ignored,
            *   to not destruct clicks on nodes which are dynamically added to body (popups, ExtJS windows, ...)
            */
            var backgroundClickHandler = function(event) {
                if (!event) var event = window.event;

                // determine really clicked node:
                var targetNode = null;

                if (event.target) {
                    targetNode = event.target;
                } else if (event.srcElement) {
                    targetNode = event.srcElement; // IE
                }

                if (targetNode) {
                    // determine topmost parent node of clicked node inside body:
                    var topmostParentNode = targetNode;

                    while (topmostParentNode.parentNode &&
                        topmostParentNode.parentNode != bodyNode &&
                        topmostParentNode != htmlNode) {

                        topmostParentNode = topmostParentNode.parentNode;
                    }

                    // check if we are inside body or html (Chrome Bug: parentNode = null somewhere)
                    if (topmostParentNode.parentNode == bodyNode || topmostParentNode == htmlNode) {
                        // check if clicked node is behind adContainer in DOM (i.e. dynamically added nodes to body):
                        var clickIsBehindAdContainer = false;
                        var adContainerSibling = document.getElementById('adContainer');

                        while (adContainerSibling.nextSibling) {
                            adContainerSibling = adContainerSibling.nextSibling;

                            if (adContainerSibling == topmostParentNode) {
                                // yes, it's behind - prevent click:
                                clickIsBehindAdContainer = true;
                                break;
                            }
                        }

                        if (!clickIsBehindAdContainer) {
                            window.open(adOptions.backgroundClickUrl);
                        }
                    }
                }
            };

            /**
            * eventBubbleCanceler: Prevents event to be handled by parent elements (in our case: the html node)
            */
            var eventBubbleCanceler = function(event) {
                if (!event) var event = window.event;
                event.cancelBubble = true;
                if (event.stopPropagation) event.stopPropagation();
            };

            // all content clickable by default:
            htmlNode.onclick = backgroundClickHandler;

            // exclude bigsize/sky child nodes from backgroundClickHandler:
            var foregroundNodes = [
                {node : bigsizeNode, childrenOnly : true},
                {node : skyNode, childrenOnly : true}
            ];

            // exclude main content nodes from backgroundClickHandler (defined in layout):
            for (var i = 0; i < adOptions.foregroundNodes.length; i++) {
                foregroundNodes.push({id : adOptions.foregroundNodes[i], childrenOnly : false});
            }

            // apply disabling of event bubbling to all nodes or child nodes:
            for (var i = 0; i < foregroundNodes.length; i++) {
                var foregroundNode = foregroundNodes[i];

                if (typeof foregroundNode.id == 'string') {
                    foregroundNode.node = document.getElementById(foregroundNode.id);
                }

                if (!foregroundNode.node) continue;

                if (!foregroundNode.childrenOnly) {
                    foregroundNode.node.onclick = eventBubbleCanceler;
                } else {
                    for (var j = 0; j < foregroundNode.node.childNodes.length; j++) {
                        var childNode = foregroundNode.node.childNodes[j];

                        if (childNode.nodeType != 1) continue;

                        childNode.onclick = eventBubbleCanceler;
                    }
                }
            }
        }, false);
    }

    // handle bigsizeAlign:
    if (bigsizeNode) {
        bigsizeNode.style.textAlign = adOptions.bigsizeAlign ? adOptions.bigsizeAlign : 'center';
    }

    // handle skyDisplaced:
    if (adOptions.skyDisplaced && skyNode) {
        if (typeof adOptions.skyDisplaced == 'number') {
            skyNode.style.marginTop = adOptions.skyDisplaced + 'px';
        } else {
            skyNode.style.marginTop = '90px';
        }
    }
}

/**
* window.addEventListener for IE
*/
if (!window.addEventListener && window.attachEvent) {
    window.addEventListener = function(eventType, listener, useCapture) {
        window.attachEvent('on' + eventType, listener);
    };
}

