var sourceHandler = new Array();
var isRequest = false;
var internalPopupIsShowing = false;

/* Allgemeine Helfer */
function _waitJQ(){
    if(window.jQuery)
        $(function(){
            // wenn jQuery geladen ist und die Seite aufgebaut ist
            initManagerPointsTooltips();
        });
    else
        window.setTimeout(_waitJQ, 2);
}


/**
 * Baut automatisch die Tooltips für die ManagerPunkte
 */
function initManagerPointsTooltips(){
    $(".pointsWrapperButton:not(.init)").each(function(){
        var that = $(this).addClass("init"),
            clone = that.clone(true).addClass("clone"),
            new_context = that.parent();

        while(/dijit/i.test(new_context.attr("class")))
            new_context = new_context.parent();
        clone.appendTo(new_context);

        $(".pointsPopIn", that).remove();
        that.css("visibility", "hidden");

        $(".clone")
            .removeClass("clone")
            .css({
                position: "relative",
                top: that.offset().top - clone.offset().top,
                left: that.offset().left - clone.offset().left
            })
            .mouseover(
                function(){
                    $(".pointsPopIn").removeClass("visible");
                    $(this).find(".pointsPopIn").addClass("visible");
                }
            );

        that.css("visibility", "hidden");
    });

    $(":not(.pointsWrapperButton) .pointsWrapper:not(.init)").each(function(){
        var that = $(this).addClass("init");

        that.mouseover(
            function(){
                $(".pointsPopIn").removeClass("visible");
                $(this).find(".pointsPopIn").addClass("visible");
            }
        );
    });

    $(".pointsWrapper").live('mouseout',
        function(){
            $(".pointsPopIn").removeClass("visible");
        }
    );
}


/**
 * Wechselt die CSS-Eigenschaft "display" von Block auf none oder umgekehrt.
 *
 * Verwendung: Spieler-Profil, Menü etc.
 * @param elementID
 */
function toggle(elementID) {
    if (dojo.byId(elementID) != null) {
        if (dojo.style(elementID, 'display') == 'none') {
            dojo.style(elementID, 'display', 'block');
        }
        else {
            dojo.style(elementID, 'display', 'none');
        }
    }
}

/**
 * Wechselt die CSS-Eigenschaft "display" von '' auf none oder umgekehrt.
 *
 * Verwendung: BetOffice
 * @param elementID
 */
function toggleWithoutBlock(elementID) {
    if (dojo.byId(elementID) != null) {
        if (dojo.style(elementID, 'display') == 'none') {
            dojo.style(elementID, 'display', '');
        }
        else {
            dojo.style(elementID, 'display', 'none');
        }
    }
}

/**
 * Entfernt die CSS-Klasse "classOne" und setzt die CSS-Klasse "classTwo".
 *
 * Verwendung: Register
 * @param element
 * @param classOne
 * @param classTwo
 */
function toggleClass(element, classOne, classTwo) {
    if (element && dojo.hasClass(element, classOne)) {
        dojo.removeClass(element, classOne);
        dojo.addClass(element, classTwo);
    } else if (element) {
        dojo.removeClass(element, classTwo);
        dojo.addClass(element, classOne);
    }
}

/* Spezielle Helfer */

/**
 * Entfernt den JavaScript-Hinweis
 *
 * Verwendung: Grundlayout (javascript-error.html)
 */
function removeNeedJavaScriptHint() {
    var needJavaScriptHint = dojo.byId('NeedJavaScript');

    if (needJavaScriptHint != null) {
        needJavaScriptHint.parentNode.removeChild(needJavaScriptHint);
    }
}

/**
 * Berechnet die absolute Position (Top, Left) eines Elements.
 *
 * Verwendung: BuildPlanBox, Notepad
 * @param nodeElement
 * @return array
 *  [0] = X-Position
 *  [1] = Y-Position
 */
function findPosition(nodeElement) {
    var curTop = 0;
    var curLeft = 0;

    if (nodeElement.offsetParent) {
        do {
            curTop += nodeElement.offsetTop;
            curLeft += nodeElement.offsetLeft;
        } while (nodeElement = nodeElement.offsetParent);

        return [curTop,curLeft];
    }
    return null;
}

/**
 * Verarbeitet einen Response, wenn der Response wie folgt aufgebaut ist.
 *
 * data
 *  |- ReturnType
 *  |- Message
 *  |- Function
 *  |- DurationToCallFunction
 *
 * Verwendung: SOLL ANGEBLICH NIRGENDS GENUTZT WERDEN.
 * @param result
 */
function handleResponse(result) {
    var timesButton = dojo.byId('TimesButton');

    if (timesButton != null) {
        //dojo.removeAttr(timesButton, 'disable', '');
    }

    /*
     * ReturnType = success, error, systemerror
     * Message = Meldung die angezeigt wird.
     *           Falls gesetzt für DurationToCallFunction
     * Function = Funktionsname, welche Aufgerufen werden soll
     * DurationToCallFunction = Zeigtangabe in Sekunden,
     *                          wann Function aufgerufen werden soll
     */
    var data = eval('(' + result + ')');

    if (typeof data['ReturnType'] == 'undefined' || typeof data['Message'] == 'undefined') {
        return;
    }

    var returnType = data['ReturnType'].toLowerCase();

    switch (returnType) {
        case 'success':
            isRequest = true;
        case 'error':
            var message = showMessage(data['Message']);

            if (message != null) {
                dojo.removeClass(message, 'errortext');
                dojo.removeClass(message, 'successtext');

                dojo.addClass(message, returnType + 'text');
            }

            if (typeof data['Function'] != 'undefined' && typeof data['DurationToCallFunction'] != 'undefined') {
                var functionCall = data['Function'] + '(';

                if (typeof data['Parameter'] != 'undefined') {
                    functionCall += data['Parameter'];
                }

                functionCall += ')';

                var timeout = data['DurationToCallFunction'] * 1000;

                window.setTimeout(functionCall, timeout);
            }
            break;
        case 'systemerror':
            showInternalSystemErrorPopup(data['Message']);
            break;
    }
}


/**
 * Lädt die aktuelle Seite neu, inklusive aller Parameter.
 *
 * Verwendung: showHotlinkConfMessage
 */
function reload() {
    var url = window.location.pathname;

    if (window.location.search.length > 0) {
        url += window.location.search;
    }

    window.location.href = url;
}


/**
 * Lädt die Adresse der aktuellen Seite neu und ignoriert dabei alle URL-Parameter.
 *
 * Verwendung: LiveTicker
 */
function reloadWithoutParameters()
{
    // URL ohne Parameter zusammensetellen
    var url = 'http://' + window.location.hostname + '/' + window.location.pathname;

    // Reload!
    window.location.href = url;
}

/**
 * Wechselt zwischen den beiden CSS-Klasse "expand" und "collapse" hin und her.
 *
 * Verwendung: PlayerProfile
 * @param elementID
 */
function changeExpandCollapse(elementID) {
    if (dojo.hasClass(elementID, 'expand')) {
        dojo.removeClass(elementID, 'expand');
        dojo.addClass(elementID, 'collapse');
    }
    else if (dojo.hasClass(elementID, 'collapse')) {
        dojo.removeClass(elementID, 'collapse');
        dojo.addClass(elementID, 'expand');
    }
}

/* Allgemein */

/**
 * Sendet einen AJAX-Request und verarbeitet den Response, sofern eine "loadFunction" angegeben wurde.
 *
 * @param url
 * @param action
 * @param formID
 * @param contentToAppend
 * @param loadFunction
 */
function ajaxSubmit(url, action, formID, contentToAppend, loadFunction) {
    var contentAction = new Array();
    contentAction['ajax'] = 1;
    contentAction['action[' + action + ']'] = action;

    for (var temp in contentToAppend) {
        contentAction[temp] = contentToAppend[temp];
    }

    var timesButton = dojo.byId('TimesButton');

    if (timesButton != null) {
        dojo.attr(timesButton, 'disabled', 'disabled');
    }

    if (formID != null && formID.length > 0) {
        var formElement = dojo.byId(formID);

        dojo.xhrPost({
            url: url,
            content: contentAction,
            form: formElement,
            load: loadFunction
        });
    }
    else {
        dojo.xhrPost({
            url: url,
            content: contentAction,
            load: loadFunction
        });
    }
}

/**
 * Erzeugt ein Assoziatives Array.
 *
 * Verwendung: NIRGENDS
 * @param key (string, number, array (aber kein assoziatives))
 * @param value (string, number, array (aber kein assoziatives))
 * @return array
 */
function getArray(key, value) {
    var temp = new Array();

    if (typeof key != 'array') {
        temp[key] = value;
    } else {
        for (var i = 0; i < key.length; i++) {
            temp[key[i]] = value[i];
        }
    }

    return temp;
}

/**
 * Liefert die Seiten höhe und breite.
 *
 * Verwendung: showOverlay, showInternalPopup etc.
 * @returns Array
 *  [0] = Breite
 *  [1] = Höhe
 */
function getPageSize() {
    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    }
    else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    }
    else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

    if (self.innerHeight) { // all except Explorer
        if(document.documentElement.clientWidth){
            windowWidth = document.documentElement.clientWidth;
        }
        else {
            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;
    }

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    }
    else {
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
        pageWidth = xScroll;
    }
    else {
        pageWidth = windowWidth;
    }

    return [pageWidth,pageHeight];
}

/* News */

/**
 * Blendet die News-Nachricht ein.
 *
 * Verwendung: News - Notification
 * @param clickElement
 */
function toggleNews(clickElement) {
    var hParent = clickElement.parentNode.parentNode;

    var newsContent = dojo.byId('newscontent-'+hParent.id);
    toggle(newsContent);
    changeExpandCollapse(clickElement);
}

/* InternalPopup */

/**
 * Blendet den halbtransparenten Layer ein.
 *
 * Verwendung: showInternalPopup
 */
function showOverlay() {
    var pageSize = getPageSize();
    dojo.style('Overlay', {
        'height': pageSize[1] + 'px',
        'width': pageSize[0] + 'px',
        'display': 'block'
        }
    );
}

/**
 * Entfernt den halbtransparenten Layer.
 *
 */
function hideOverlay() {
    dojo.style('Overlay', 'display', 'none');
}

/**
 * Positioniert das InternalPopup zentriert.
 *
 * Verwendung: showInternalPopup
 */
function positionInternalPopup() {
    var oldStyle = dojo.style('InternalPopup', 'display');

    if (!oldStyle || (oldStyle && oldStyle == 'none')) {
        dojo.style('InternalPopup', 'display', 'block');

        var pageSize = getPageSize();

        var iPWWidth = dojo.style('InternalPopupWindow', 'width');

        var left = (pageSize[0] - iPWWidth) / 2;

        var iPWTop = dojo.style('InternalPopupWindow', 'top');

        var top = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

        dojo.style('InternalPopupWindow', {
            'top': 20 + 'px',
            /*'top': (top + iPWTop) + 'px',*/
            'left': left + 'px'
            }
        );
    }
}

/**
 * Zeigt das InternalPopup an.
 *
 * Verwendung: showPlayerProfile
 * @param url
 * @param callbackFunction
 */
function showInternalPopup(url, callbackFunction) {
    showOverlay();

    internalPopupIsShowing = true;

    positionInternalPopup();

    loadSiteInInternalPopup(url, callbackFunction);

    window.scrollTo(0, 0);
}

/**
 * Zeigt das InternalPopup an. (Die Verarbeitung des Responses ist verändert)
 *
 * Verwendung: showTutorial
 * @param url
 * @param callbackFunction
 */
function showInternalPopup2(url, callbackFunction) {
    showOverlay();

    internalPopupIsShowing = true;

    positionInternalPopup();

    loadSiteInInternalPopup2(url, callbackFunction);
}

/**
 * Schließt das InternalPopup.
 *
 * Verwendung: showPlayerProfile, showTutorial etc.
 * @param event
 */
function hideInternalPopup(event) {
    if (event == null || event.target.getAttribute('id') == 'InternalPopup') {
        var timesButton = dojo.byId('TimesButton');

        if (timesButton != null) {
            dojo.removeAttr(timesButton, 'disabled');
        }

        dojo.style('InternalPopup', 'display', 'none');

        hideOverlay();

        internalPopupIsShowing = false;

        // Wieder Aufräumen des Kopfdesigns
        var popupHead = dojo.byId('InternalPopupCloseTut');

        if(popupHead != null)
        {
            popupHead.id = 'InternalPopupClose';
        }
    }

    if (isRequest == true) {
        reload();
    }
}

/**
 * Für einen AJAX-Request per GET aus und verarbeitet den Response im InternalPopup.
 *
 * Verwendung: showInternalPopup etc.
 * @param url
 * @param callbackFunction
 */
function loadSiteInInternalPopup(url, callbackFunction) {
    var temp = dojo.byId('InternalPopupContent');

    if (temp != null && url != null && url.length > 0) {
        dojo.style('InternalPopupLoading', 'display', 'block');
        dojo.style(temp, 'display', 'none');

        var widgets = dijit.findWidgets(temp);
        dojo.forEach(widgets, function(item) {
            item.destroyRecursive();
        });

        dojo.xhrGet({
            url: url,
            content: {
                'ajaxcheck': 'true'
            },
            load: function(data) {
                if (data.search(/^http.*\.php$/i) > -1) {
                    window.location.href = data;
                    return;
                }

                dojo.require('dojo.html');

                dojo.html.set(temp, data);

                dojo.style('InternalPopupLoading', 'display', 'none');
                dojo.style(temp, 'display', 'block');

                showOverlay();

                dojo.parser.parse(temp);

                var dataForRegExp = escape(data);
                var jsRegExp = /%3Cscript%20type%3D%22text\/javascript%22%20for%3D%22igTutorialHintsScript%22%3E(.*)%3C\/script%3E/gi;
                if (jsRegExp.test(dataForRegExp) != false) {
                    jsRegExp.exec(dataForRegExp);
                    var jsCode = RegExp.$1;
                    jsCode = jsCode.replace(/%0A/gi, '');
                    jsCode = jsCode.replace(/(%20){2,}/gi, '%20');
                    jsCode = unescape(jsCode);
                    dojo.eval(jsCode);
                }

                // auf ausführbares JavaScript testen
                if(callbackFunction != null && (typeof callbackFunction == 'function')) {
                    callbackFunction();
                }

                initManagerPointsTooltips();
            }
        });
    }
}

/**
 * Für einen AJAX-Request per GET aus und verarbeitet den Response im InternalPopup. Für ShowInternalPopup2.
 *
 * Verwendung: showInternalPopup2 etc.
 * @param url
 * @param callbackFunction
 */
function loadSiteInInternalPopup2(url, callbackFunction) {
    var temp = dojo.byId('InternalPopupContent');

    if (temp != null && url != null && url.length > 0) {
        dojo.style('InternalPopupLoading', 'display', 'block');
        dojo.style(temp, 'display', 'none');

        var widgets = dijit.findWidgets(temp);
        dojo.forEach(widgets, function(item) {
            item.destroyRecursive();
        });

        dojo.xhrGet({
            url: url,
            content: {
                'ajaxcheck': 'true'
            },
            load: function(data) {
                // Json Auflösen
                json = eval('(' + data + ')');

                // kein Datenelement vorhanden
                if(json == null)
                {
                    return;
                }

                // Html nicht gesetzt
                if(!json['html'])
                {
                    return;
                }

                if (json['html'].search(/^http.*\.php$/i) > -1) {
                    window.location.href = json['html'];
                    return;
                }

                dojo.require('dojo.html');

                dojo.html.set(temp, json['html']);

                dojo.style('InternalPopupLoading', 'display', 'none');
                dojo.style(temp, 'display', 'block');

                showOverlay();

                // Javascript ausführen wenn gesetzt
                if(json['js'] && json['js'].length > 0)
                {
                    eval(json['js']);
                }

                // auf ausführbares JavaScript testen
                if(callbackFunction != null && (typeof callbackFunction == 'function')) {
                    callbackFunction(json);
                }
            }
        });
    }
}

/* InternalPopup - MOVE */

/**
 * Variablen für das verschieben des Popups
 */
var mouseIsDNDOnInternalPopup = false;
var dndData = null;

/**
 * Bereitet alles vor, damit das InternalPopup verschobene werden kann.
 *
 * Verwendung InternalPopup
 * @param event
 */
function prepareInternalPopupToMove(event) {
    mouseIsDNDOnInternalPopup = true;

    var pageSize = getPageSize();

    dndData = new Array();
    dndData['defaultWidth'] = (pageSize[0] - dojo.style('InternalPopupWindow', 'width')) / 2;
    dndData['beginnWidth'] = event.pageX;
    dndData['height'] = event.pageY - dojo.style('InternalPopupWindow', 'top');
}

/**
 * Verschiebt das InternalPopup.
 *
 * Verwendung InternalPopup
 * @param event
 */
function moveInternalPopup(event) {
    if (mouseIsDNDOnInternalPopup == true && dndData != null) {
        var left = dndData['defaultWidth'] + (event.pageX - dndData['beginnWidth']);

        dojo.style('InternalPopupWindow', {
            'top': (event.pageY - dndData['height']) + 'px',
            'left': left + 'px'
        });
    }
}

/**
 * Beendet den Verschiebevorgang des InternalPopups.
 *
 * Verwendung InternalPopup
 * @param event
 */
function finishInternalPopupFromMove(event) {
    mouseIsDNDOnInternalPopup = false;
    dndData = null;
}

/* Tutorial */

function showTutorial(callbackFunction, showArchieve) {
    var page = 'tutorial.php';

    // wenn Archieve angezeigt werden soll
    if(showArchieve)
    {
        page += '?archieve=show';
    }
    tutorialStepDiv = -1;

    // Anzeigebereich Ändern
    var tutorialHead = dojo.byId('InternalPopupClose');
    if(tutorialHead != null)
    {
        tutorialHead.id = tutorialHead.id + 'Tut';

        var internalPopupCloseElement = dojo.byId(tutorialHead.id);

        if (internalPopupCloseElement != null) {
            dojo.connect(internalPopupCloseElement, 'onmousedown', prepareInternalPopupToMove);
        }
    }

    // Anzeigen des Popups
    showInternalPopup2(page, callbackFunction);
}

/**
 * Schliesst das Tutorial und setzt es auf den Anfang zurück
 */
function hideTutorial()
{
    hideInternalPopup();
}

/**
 * Variable für Tutorial StepDivs
 */
var tutorialStepDiv = -1;

function tutorialNextStep(elementIDPrefix) {
    var tempStep = tutorialStepDiv + 1;

    var tutorialElement = dojo.byId(elementIDPrefix + tempStep);

    if (tutorialElement != null) {
        var oldTutorialElement = dojo.byId(elementIDPrefix + tutorialStepDiv);

        if (oldTutorialElement != null) {
            dojo.style(oldTutorialElement, 'display', 'none');
        }

        dojo.style(tutorialElement, 'display', 'block');

        tutorialStepDiv = tempStep;
    } else {
        tutorialStepDiv = -1;
    }
}

/**
 * Zeigt die erste Seite des aktuellen Steps an
 */
function tutorialStepFirstPage(elementIDPrefix)
{
    // altes Ausblenden
    var oldTutorialElement = dojo.byId(elementIDPrefix + tutorialStepDiv);

    if (oldTutorialElement != null) {
        dojo.style(oldTutorialElement, 'display', 'none');
    }

    // erstes Anzeigen lassen
    tutorialStepDiv = -1;
    tutorialNextStep(elementIDPrefix);
}
/* Frag Gerd */

function showAskGerd() {
    showInternalPopup2('askgerd.php', null);
}

/* Hinweisseite Lizenzwechsel, Lizenzabgelaufen */

/**
 * Zeigt das InternalPopup an.
 *
 * Verwendung: showPlayerProfile
 * @param url
 * @param callbackFunction
 */
function showInternalPopupLicence(url, callbackFunction) {
    if(connections['globalpopupclose']) {
        dojo.disconnect(connections['globalpopupclose']);
    }

    var overlay = dojo.byId('Overlay');
    if(overlay) {
        overlay.onclick = 'return true;';
    }

    var closeDiv = dojo.byId('InternalPopupClose');
    if(closeDiv) {
        var links = closeDiv.getElementsByTagName('a');

//        console.log(links);

        for(link in links) {
//            console.log(links[link]);
            links[link].onclick = 'return true;';
//            console.log(links[link].onclick);
        }
    }

    showOverlay();

    internalPopupIsShowing = true;

    positionInternalPopup();

    loadSiteInInternalPopup(url, callbackFunction);
}

function showLicenceChangeDialog(callbackFunction) {
    var page = 'licencerunoutnotice.php';

    // Anzeigen des Popups
    showInternalPopupLicence(page, callbackFunction);
}

/* Weiterleitung auf eine bestimmte Seite, schließt danach das Popup */
function redirect(url) {
    var loc = window.location;
    var link = loc.protocol + "//" + loc.host + "/" + url;

    window.location.href = link;
    hideInternalPopup();
}
/* Show Helper */

/**
 * Zeigt eine Meldung als Fehler im InternalPopup an.
 *
 * Verwendung handleResponse
 * @param message
 */
function showInternalSystemErrorPopup(message) {
    hideInternalPopup();

    showOverlay();

    positionInternalPopup();

    var temp = dojo.byId('InternalPopupContent');

    if (temp != null && message != null) {
        dojo.style('InternalPopupLoading', 'display', 'none');
        dojo.style(temp, 'display', 'block');

        dojo.require('dojo.html');

        dojo.html.set(temp, '<div id="Systemerror">' + message + '</div>');

        showOverlay();
    }
}

/**
 * Zeigt das InternalPopup mit dem Times-Verkürzen Inhalt an.
 *
 * Verwendung Überall bei verkürzen mit Times
 * @param buildID
 */
function showTimes(buildID) {
    if (buildID != null) {
        showInternalPopup('timespopup.php?id=' + buildID + '&popup=1', null);
    }
}

/* Ticker */

/**
 * Variable für den Ticker
 */
var liveTicker = null;

/**
 * Zeigt den Ticker in einem richtigen Popup an.
 *
 * Verwendung: Menu, Spielplan etc.
 * @param url
 */
function showTicker(url) {
    if (!url || (url && url.length == 0)) {
        url = 'ticker.php';
    }
    // dependent?
    var params = 'height=720,width=1024,top=150,left=150,location=no,menubar=no,scrollbars=yes,status=yes,toolbar=no';
    // Ticker noch nicht offen oder bereits geschlossen
    if (liveTicker == null || (liveTicker && liveTicker.closed)) {
    liveTicker = null;
        liveTicker = window.open(url, 'WND_liveTicker', params);
    }
    // Ticker reload
  liveTicker.location.href = url;
  // Ticker in den Vordergrund holen
  liveTicker.focus();
}

/* Glücksrad */

/**
 * Variable für das Glücksrad
 */
var wheelOfFortuneWindow = null;

/**
 * Öffnet das Popup-Fenster für das Glücksrad.
 *
 * Verwendung: Hotlinks
 */
function showWheelOfFortune() {
    // URL
    var url = 'wheeloffortune.php';
    // Fenster-Parameter
    var params = 'height=760,width=860,top=100,left=100,location=no,menubar=no,scrollbars=yes,status=yes,toolbar=no';
    // gibt es das Fenster noch nicht?
    if (!wheelOfFortuneWindow || (wheelOfFortuneWindow && wheelOfFortuneWindow.closed)) {
        // Fenster neu anlegen
        wheelOfFortuneWindow = window.open(url, 'WND_wheelOfFortune', params);
    }
    // URL zuweisen
    wheelOfFortuneWindow.location.href = url;
    // Fenster in den Vordergrund bringen
    wheelOfFortuneWindow.focus();
}

/**
 * Öffnet dem Itemshop vom Glücksrad aus.
 *
 * Verwendung: Glücksrad
 */
function showItemShopFromWheel()
{
    window.opener.focus();
    window.opener.location.href = "items.php";
}

/**
 * Zeigt dem Kunden einen Hinweis, wenn er mit dem anderen Team spielen will.
 *
 * Verwendung: ManagerInfoBox (Teamauswahl)
 * @param countryId
 */
function showSwitchTeamDialog(countryId) {
    var url = 'confirmteamchange.php?';
    if (countryId != null) {
        url += 'ctid=' + countryId;
    } else {
        return;
    }
    url += '&popup=1';
    showInternalPopup(url, null);
}


/* --- Office --- */

function showMarkerDiv(coords, url, type, startCoordX, startCoordY, endCoordX, endCoordY) {
    removeMarkerDiv();

    coordsArray = coords.split(',');

    if (coordsArray.length > 0) {
        var markerDiv = dojo.doc.createElement('div');

        link = dojo.doc.createElement('a');

        dojo.attr(link, 'href', url);

        dojo.style(link, {
            'display': 'block',
            'height': '100%',
            'width': '100%'
        });

        markerDiv.appendChild(link);

        dojo.attr(markerDiv, 'id', 'MarkerDiv');
        dojo.attr(markerDiv, 'onmouseout', 'removeMarkerDiv()');

        var top = 166;
        var left = parseInt((window.innerWidth / 2) - 304);
        var height = 0;
        var width = 0;

        var viewHeight = window.innerHeight;
        var pageSize = getPageSize();

        if (dojo.isIE == 6) {
            left = parseInt((document.documentElement.clientWidth / 2) - 237);
            viewHeight = document.documentElement.clientHeight;
        }
        else if (dojo.isIE == 7) {
            left = parseInt((document.body.clientWidth / 2) - 237);
            viewHeight = document.body.clientHeight;
        }

        if (pageSize[1] <= viewHeight) {
            if (dojo.isIE) {
                left -= 13;
            }
            else {
                left += 9;
            }
        }

        switch (type) {
            case 1: // rect
                top += parseInt(coordsArray[1]);
                left += parseInt(coordsArray[0]);
                height = (parseInt(coordsArray[3]) - parseInt(coordsArray[1]));
                width = (parseInt(coordsArray[2]) - parseInt(coordsArray[0]));
                break;
            case 2: // circle
                top += parseInt(coordsArray[1]) - parseInt(coordsArray[2]);
                left += parseInt(coordsArray[0]) - parseInt(coordsArray[2]);
                height = parseInt(coordsArray[2]) * 2;
                width = height;
                break;
            case 3: // poly
                top += parseInt(coordsArray[startCoordY]);
                left += parseInt(coordsArray[startCoordX]);
                height = (parseInt(coordsArray[endCoordY]) - parseInt(coordsArray[startCoordY]));
                width = (parseInt(coordsArray[endCoordX]) - parseInt(coordsArray[startCoordX]));
                break;
        }

        dojo.style(markerDiv, {
            'position': 'absolute',
            'top': top + 'px',
            'left': left + 'px',
            'height': height + 'px',
            'width': width + 'px'
        });

        var temp = dojo.body();

        temp.appendChild(markerDiv);
    }
}

function removeMarkerDiv() {
    var markerDiv = dojo.byId('MarkerDiv');

    if (markerDiv != null) {
        var parent = markerDiv.parentNode;

        if (parent != null) {
            parent.removeChild(markerDiv);
        }
    }
}



/* Switch Team */

function switchTeam(site, parametername, teamid) {
    window.location = site + '?' + parametername + '=' + teamid;
}

/* Switch Picture */

function switchPlayerPicture(elementID, back) {
    var picture = dojo.byId(elementID);

    if (picture != null) {
        var pic = switchPicture(picture, '/([0-9]+)\.[a-zA-Z]+', back, playerPictures.length);

        dojo.attr(picture, 'src', playerPictures[pic]['full']);
        dojo.attr(dojo.byId('Hidden' + elementID), 'value', playerPictures[pic]['picturename']);
    }
}

function switchPicture(pictureElement, regexString, back, maxLength) {
    if (pictureElement != null) {
        var regEx = new RegExp(regexString);
        var result = regEx.exec(dojo.attr(pictureElement, 'src'));

        if (result != null) {
            var pic = parseInt(result[1], 10);

            if (back == false) {
                pic += 1;
            }
            else if (back == true) {
                pic -= 1;
            }

            if (pic <= 0) {
                pic = maxLength - 1;
            }
            else if (pic >= maxLength) {
                pic = 1;
            }

            return pic;
        }
    }
}

function switchModelPicture(elementID, back) {
    var picture = dojo.byId(elementID);

    if (picture != null) {
        var model = dojo.attr(dojo.byId('Hidden' + elementID), 'value');
        var index = -1;

        for (i = 0; i < stadiumPictures.length; i++) {
            if (stadiumPictures[i] == model) {
                index = i;
                break;
            }
        }

        if (back) {
            index--;
        }
        else {
            index++;
        }

        if (index < 0) {
            index = stadiumPictures.length - 1;
        }
        else if (index >= stadiumPictures.length) {
            index = 0;
        }

        var newModel = stadiumPictures[index];

        dojo.attr(picture, 'src', dojo.attr(picture, 'src').replace(model, newModel));
        dojo.attr(dojo.byId('Hidden' + elementID), 'value', newModel);
    }
}

/* Show Player Profile */

function showPlayerProfile(playerID, transfermarketID, back2team, tutorialId, stepId) {
    var url = 'playerprofile.php?';

    if (playerID != null) {
        url += 'id=' + playerID;
    }
    else if (transfermarketID != null) {
        url += 'transfermarket=' + transfermarketID;
    }

    if (back2team || back2team != null) {
        url += "&backteam="+back2team;
    }

    if((tutorialId || tutorialId != null) && (stepId || stepId != null)) {
        url += "&igtid=" + tutorialId + "&igsid=" + stepId;
    }

    if(transfermarketID == null && tutorialId == null)
    	window.location.href=url;
    else{
	    url += '&popup=1';
	    showInternalPopup(url, null);
    }
}


/* Show Hotlink Config*/
function showHotlinkConf() {
    var url = 'hotlinks.php?popup=1';

    showInternalPopup(url, handleHotlinkConf);
}
/* Callback für die Hotlink Config */
function handleHotlinkConf() {
    var bHotlinksDiv = dojo.byId('hotlinkconfig');
    if (bHotlinksDiv != null) {

    // Dojo Widgets löschen
    var widgets = dijit.findWidgets(bHotlinksDiv);

    dojo.forEach(widgets, function(item) {
        item.destroyRecursive();
    });

    // Kinder holen
    var elements = bHotlinksDiv.getElementsByTagName('input');

    var i = 0;
    // Kinder untersuchen
    while (i < elements.length) {
        // Element holen
        var childElement = elements[i];

        // auf sinnvolle Werte für gesetzte Felder prüfen
        // um sauberen Code zu erzeugen
        var checked = childElement.checked;
        if(checked == undefined)
        {
            checked = 'false';
        }
        if (typeof childElement == 'object' && childElement.type.toLowerCase() == 'radio') {
            var bt = new dijit.form.RadioButton({
                type: 'radio',
                name: childElement.name,
                value: childElement.value,
                checked: Boolean(checked)
                }, childElement.id);
        }
        i++;
    }

    var button = new dijit.form.Button({
           type: 'button',
           name: 'save',
           onClick: function() {
               ajaxSubmit('hotlinks.php?popup=1', 'save', 'hotlinkConfForm', null, showHotlinkConfMessage);
               return false;
            }
        }, 'hotlinkButtonSave');
    }
}
// Gibt die Erfolgs, bzw Fehlernachrichten aus.
function showHotlinkConfMessage(message)
{
    dojo.require('dojo.html');

    var field = dojo.byId('hotlinkMessage');

    if (field != null) {
        dojo.html.set(field, message);
    }

    window.setTimeout("reload()", 3000);

    return field;
}


/**
 * Zeigt den Userdialog an.
 * TODO hier
 * @param optLangKey
 * @return boolean
 */
function showDeleteQuestion(formId, optLangKey, btName, btValue) {
    var url = 'confirm-js.php?';

    if (formId != null) {
        url += 'formId=' + formId;
    } else {
        return;
    }
    if (optLangKey != null) {
        url += '&optKey=' + optLangKey;
    }
    if (btName != null) {
        url += '&btName=' + btName;
        if (btValue != null) {
            url += '&btValue=' + btValue;
        } else {
            url += '&btValue=' + btName;
        }
    }

    url += '&popup=1';

    showInternalPopup(url, null);
}

function doSubmitForm(formId, btName, btValue) {
    var subForm = dojo.byId(formId);
    if (subForm && subForm != null) {
        // hidden input erzeugen
        var newElement = dojo.doc.createElement('input');

        if (btName && btName != null) {
            dojo.attr(newElement, 'type', 'hidden');
            dojo.attr(newElement, 'name', btName);
            // Wert hinzufügen
            dojo.attr(newElement, 'value', btValue);

            subForm.appendChild(newElement);
        }

        subForm.submit();
    }
}


/* Show Player Delete */

function showPlayerDelete(id) {
    var url = 'playerdelete.php?id=' + id + '&popup=1';

    showInternalPopup(url, null);
//    loadSiteInInternalPopup(url, null);
}

/* Show Player Training */

function showPlayerTraining(id, tutorialId, stepId) {
    var url = 'playertraining.php?ids=' + id + '&popup=1';

    if((tutorialId || tutorialId != null) && (stepId || stepId != null)) {
        url += "&igtid=" + tutorialId + "&igsid=" + stepId;
    }

    if (internalPopupIsShowing != true) {
        showInternalPopup(url, null);
    } else {
        loadSiteInInternalPopup(url, null);
    }
}

/* Show Player Sale */

function showPlayerSale(id) {
    var url = 'playersale.php?id=' + id + '&popup=1';

    showInternalPopup(url, null);
//    loadSiteInInternalPopup(url, null);
}

/* Show Player Switch Training */

function showPlayerSwitchTraining(id) {
    var url = 'playerswitchtraining.php?id=' + id + '&popup=1';

    //showInternalPopup(url, null);
    loadSiteInInternalPopup(url, null);
}

/* Show Player Convert */

function showPlayerConvert(id) {
    var url = 'playerconvert.php?id=' + id + '&popup=1';

    //showInternalPopup(url, null);
    loadSiteInInternalPopup(url, null);
}

/* Show Player TrainingsCamp */

function showPlayerTrainingsCamp(id) {
    var url = 'playertrainingscamp.php?ids=' + id + '&popup=1';

    //showInternalPopup(url, null);
    loadSiteInInternalPopup(url, null);
}

function switchTraining(changeElement, playerID) {
    var dijit1 = dijit.byId('SwitchTrainingFrom'+playerID);
    var dijit2 = dijit.byId('SwitchTrainingTo'+playerID);
    if (dijit1 != null && dijit2 != null) {
        if (changeElement.checked == true) {
            dijit1.attr('disabled', false);
            dijit2.attr('disabled', false);
        } else {
            dijit1.attr('disabled', true);
            dijit2.attr('disabled', true);
        }
    }
}

/* Show Team Profile */

function showTeamProfile(id) {
    var url = 'teamprofile.php?id=' + id + '&popup=1';

    showInternalPopup(url, null);
}

/* Toggle Team Profile Tabs */

function showTeamProfileTab(elementID) {
    var teamProfileTab = dojo.byId('TeamProfileTabs');

    if (teamProfileTab != null) {
        var tabs = teamProfileTab.getElementsByTagName('div');

        for (i = 0; i < tabs.length; i++) {
            dojo.style(tabs[i], 'display', 'none');
        }

        var elementToShow = dojo.byId(elementID);

        if (elementToShow != null) {
            dojo.style(elementToShow, 'display', '');
        }
    }
}

/* Show Stadium Profile */

function showStadiumProfile(sid, type, id) {
    var url = 'stadiumprofile.php?sid=' + sid;

    if (type != null) {
        url += '&type=' + type;
    }

    if (id != null) {
        url += '&id=' + id;
    }

    url += '&popup=1';

    showInternalPopup(url, null);
}

/* Show Customer Profile */

function showCustomerProfile(cid, type, id) {
    var url = 'customerprofile.php?cid=' + cid;

    if (type != null) {
        url += '&type=' + type;
    }

    if (id != null) {
        url += '&id=' + id;
    }

    url += '&popup=1';

    showInternalPopup(url, null);
}

/* Show TechTree Entry */

function showTechTreeProfile(art, level) {
    var url = 'techtreeprofile.php?art=' + art + '&level=' + level + '&popup=1';

    showInternalPopup(url, null);
}

function markTechTreeEntry(elementID) {
    var techTreeEntry = dojo.byId(elementID);

    if (techTreeEntry != null) {
        parent = techTreeEntry.parentNode;

        while (parent.nodeName.toLowerCase() != 'ul') {
            parent = parent.parentNode;
        }

        if (parent != null) {
            var divs = parent.getElementsByTagName('div');

            for (i = 0; i < divs.length; i++) {
                dojo.removeClass(divs[i], 'markTechTreeEntry');
            }
        }

        dojo.addClass(techTreeEntry, 'markTechTreeEntry');
    }
}

function buildQueueIDByMarkTechTreeEntry(element, parentID) {
    parent = element.parentNode;

    while (!dojo.hasAttr(parent, 'id') && parent.id != parentID) {
        parent = parent.parentNode;
    }

    if (parent != null) {
        var divs = parent.getElementsByTagName('div');

        for (i = 0; i < divs.length; i++) {
            if (dojo.hasClass(divs[i], 'markTechTreeEntry')) {
                return divs[i].id.substr(1);
            }
        }
    }

    return null;
}

/* Show Items */

function showItems(elementID, showElementID) {
    toggle(elementID);

    var showElement = dojo.byId(showElementID);

    if (showElement != null) {
        if (showElement.value == 0) {
            showElement.value = 1;
        }
        else {
            showElement.value = 0;
        }
    }
}

/* Pool LineUp */

function loadTactic(tactic, formname, preset) {
    // hidden input erzeugen
    var newElement = dojo.doc.createElement('input');

    dojo.attr(newElement, 'type', 'hidden');
    dojo.attr(newElement, 'name', 'tactic');
    // Wert hinzufügen
    dojo.attr(newElement, 'value', tactic);

    dojo.doc.forms['poolLineUp'].appendChild(newElement);

    // hidden input erzeugen
    newElement = dojo.doc.createElement('input');

    dojo.attr(newElement, 'type', 'hidden');
    dojo.attr(newElement, 'name', 'preset');
    // Wert hinzufügen
    dojo.attr(newElement, 'value', preset);

    dojo.doc.forms['poolLineUp'].appendChild(newElement);

    document.forms[formname].submit();
}

function showLineUp(powerSentence) {
    var targetElement = dojo.byId('PlayersLineUpTable');

    if (targetElement == null) {
        return;
    }

    // Clean Old Data
    var parent = targetElement.parentNode;

    if (parent != null) {
        var newTargetElement = targetElement.cloneNode(false);

        parent.replaceChild(newTargetElement, targetElement);

        targetElement = newTargetElement;
    }

    // Gesamtstärke der aufgestellten Mannschaft
    var power = 0;

    var counter = 1;
    var tempElement = null;
    var divs = null;
    var cloneDiv = null;
    var playerDivs = null;
    var tempDiv = null;
    var playerPower = null;

    // Clone the lineup to show
    for (i = 1; i <= 82; i++) {
        tempElement = dojo.byId('OwnPosition' + i);

        if (tempElement != null) {
            divs = tempElement.getElementsByTagName('div');

            if (divs.length > 0) {
                // copy into PlayersLineUpTable
                for (j = 0; j < divs.length; j++) {
                    if (dojo.hasClass(divs[j], 'dojoDndItem')) {
                        cloneDiv = divs[j].cloneNode(true);

                        // Zeilen Highlighting
                        dojo.removeClass(cloneDiv, 'even');

                        if ((counter++%2) == 0) {
                            dojo.addClass(cloneDiv, 'even');
                        }

                        // Spieler eigenschaften holen
                        playerDivs = divs[j].getElementsByTagName('div');

                        // Gesamtstärke ermitteln
                        for (m = 0; m < playerDivs.length; m++) {
                            if (dojo.hasClass(playerDivs[m], 'playerpower')) {
                                tempDiv = playerDivs[m].childNodes;

                                for (n = 0; n < tempDiv.length; n++) {
                                    playerPower = String(tempDiv[n].nodeValue);

                                    if (playerPower.indexOf('.') > -1) {
                                        power += parseFloat(playerPower) * 1000;
                                    } else {
                                        power += parseInt(playerPower);
                                    }
                                }
                            }
                        }

                        // Zeile an den Tab binden
                        targetElement.appendChild(cloneDiv);
                    }
                }
            }
        }
    }

    // show power
    var newElement = dojo.doc.createElement('div');

    dojo.addClass(newElement, 'power');

    // Wert hinzufügen
    newElement.appendChild(dojo.doc.createTextNode(powerSentence + ' ' + addSeparatorsNF(power, '.', ',', '.')));

    targetElement.appendChild(newElement);
}

/**
 * @param nStr The number to be formatted, as a string or number. No validation is done, so don't input a formatted number. If inD is something other than a period, then nStr must be passed in as a string.
 * @param inD The decimal character for the input, such as '.' for the number 100.2
 * @param outD The decimal character for the output, such as ',' for the number 100,2
 * @param sep The separator character for the output, such as ',' for the number 1,000.2
 * @return
 */
function addSeparatorsNF(nStr, inD, outD, sep)
{
    nStr += '';
    var dpos = nStr.indexOf(inD);
    var nStrEnd = '';
    if (dpos != -1) {
        nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
        nStr = nStr.substring(0, dpos);
    }
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
        nStr = nStr.replace(rgx, '$1' + sep + '$2');
    }
    return nStr + nStrEnd;
}

function setLineUpHandlers(side) {
    dojo.require('dojo.dnd.Source');

    for (i = 1; i <= 82; i++) {
        var positionElement = dojo.byId(side + 'Position' + i);

        for (j = sourceHandler.length - 1; j >= 0; j--) {
            if (sourceHandler[j].node.id.toLowerCase().indexOf(positionElement.id.toLowerCase()) > -1) {
                sourceHandler.splice(j, 1);
            }
        }

        dojo.connect(positionElement, 'onDndStart', 'dndStart');
        dojo.connect(positionElement, 'onDndDrop', 'dndDrop');

        sourceHandler[sourceHandler.length] = new dojo.dnd.Source(positionElement, {
            copyOnly: false,
            singular: true/*,
            onOverEvent: function () {
                showPlayerHint(this);
            },
            onOutEvent: function () {
                hidePlayerHint(this);
            }*/
        });
    }

    // Tabelle mit den restlichen Spielern Drag'n'Drop-fähig machen
    dndSource = new dojo.dnd.Source('PlayersStandByTable', {
        copyOnly: false,
        singular: true/*,
        checkAcceptance: function(srcObject, nodesArr) {
            var returnValue = true;

            dojo.forEach(nodesArr, function(node) {
                var divs = node.getElementsByTagName('div');

                for (i = 0; i < divs.length; i++) {
                    if (dojo.hasClass(divs[i], 'playerfitness')) {
                        var fitness = parseInt(divs[i].firstChild.nodeValue);
                        if (fitness <= 5) {
                            returnValue = false;
                        }
                    }
                }
            });
            return returnValue;
        }*/
    });

    sourceHandler[sourceHandler.length] = dndSource;

    dojo.connect(dndSource, 'onDndStart', 'dndStart');
    dojo.connect(dndSource, 'onDndDrop', 'dndDrop');
}

//Drag'n'Drop

function dndStart(sourceObject, nodesArray, doCopy) {
    var temp = sourceObject.getAllNodes();
/*
    dojo.forEach(nodesArray, function(node) {
        var divs = node.getElementsByTagName('div');

        for (i = 0; i < divs.length; i++) {
            if (dojo.hasClass(divs[i], 'playerfitness')) {
                var fitness = parseInt(divs[i].firstChild.nodeValue);

                if (fitness <= 5) {
                    //dojo.dnd.manager().stopDrag();
                    //dojo.stopEvent(this);
                    //sourceObject.stopDrag();
                    sourceObject.onDndStart.accept = false;
                }
            }
        }
    });
*/
    for (i = 0; i < temp.length; i++) {
        dojo.removeClass(temp[i], 'dojoDndItemOld');
    }
}

function dndDrop(sourceObject, nodesArray, doCopy, targetObject) {
    if (nodesArray.length > 0) {
        var temp = targetObject.getAllNodes();

        for (i = 0; i < temp.length; i++) {
            if (isSameNode(temp[i], nodesArray)) {
                continue;
            }

            if (dojo.hasClass(temp[i], 'dojoDndItemOld')) {
                dojo.removeClass(temp[i], 'dojoDndItemOld');

                sourceObject.insertNodes(false, [temp[i]]);
            }
        }

        dojo.removeClass(nodesArray[0], 'dojoDndItemAnchor');

        if (targetObject.node.id.toLowerCase() != 'playersstandbytable') {
            dojo.addClass(nodesArray[0], 'dojoDndItemOld');
        }
    }
}

function isSameNode(nodeElement, nodeArray) {
    for (j = 0; j < nodeArray.length; j++) {
        if (nodeElement == nodeArray[j]) {
            return true;
        }
    }

    return false;
}

var playerHint = null;

function showPlayerHint(dndElement) {
    if (playerHint != null) {
        return true;
    }

    var targetElement = dndElement.node;

    if (targetElement.childNodes.length > 0) {
        var divs = targetElement.getElementsByTagName('div');

        for (i = 0; i < divs.length; i++) {
            playerHint = divs[i].cloneNode(true);

            dojo.addClass(playerHint, 'playerHint');

            var position = findPosition(targetElement);

            dojo.style(playerHint, {
                position: 'absolute',
                top: (position[0] + targetElement.offsetHeight) + 'px',
                left: (position[1] + targetElement.offsetWidth) + 'px'
            });

            dojo.body().appendChild(playerHint);

            break;
        }
    }

    return true;
}

function hidePlayerHint(dndElement) {
    if (playerHint == null) {
        return;
    }

    var parent = playerHint.parentNode;

    if (parent != null) {
        parent.removeChild(playerHint);

        playerHint = null;
    }
}

function savePreset(event) {
    var presetElements = dojo.doc.getElementsByName('preset');

    if (presetElements.length > 0) {
        dojo.style('PresetHint', 'display', 'none');

        var presetName = null;

        var presetNameElement = dojo.byId('PresetName');

        if (presetNameElement) {
        	presetName = presetNameElement.value;
        }

        saveLineup(event, presetElements[0].value, presetName);
    } else {
        dojo.style('PresetHint', 'display', '');
    }
}

function setSaveAs(newValue) {
    dojo.attr('SaveAsInput', 'value', newValue);
}

function setTeamChange(widget) {
    if (widget.checked == true) {
        dojo.attr('TeamChangeInput', 'value', widget.attr('value'));
    }
}

function saveLineup(event, preset, presetName) {
    var tempElement = null;
    var players = new Array();
    var divs = null;
    var playerProperties = null;
    var index = null;
    var newElement = null;
    var tactic = '';
    var tempTactic = 0;

    // Alle Spieler auf dem Spielfeld ermitteln
    for (i = -1; i <= 82; i++) {
        tempElement = dojo.byId('OwnPosition' + i);

        if (tempElement != null) {
            divs = tempElement.getElementsByTagName('div');

            if (divs.length > 0) {
                for (j = 0; j < divs.length; j++) {
                    playerProperties = divs[j].getElementsByTagName('div');

                    for (k = 0; k < playerProperties.length; k++) {
                        if (dojo.hasClass(playerProperties[k], 'playerid')) {
                            index = players.length;

                            players[index] = new Array();
                            players[index]['ID'] = playerProperties[k].firstChild.nodeValue;
                            players[index]['Position'] = i;

                            tempTactic++;
                        }
                    }
                }
            }
        }

        if ((i%27) == 0) {
            tactic = tactic + String(tempTactic);
            tempTactic = 0;
        }
    }

    if (players.length > 11) {
        dojo.style('PlayerHint', 'display', '');

        return;
    } else {
        dojo.style('PlayerHint', 'display', 'none');
    }

    for (i = 0; i < players.length; i++) {
        player = players[i];

        // hidden input erzeugen
        newElement = dojo.doc.createElement('input');

        dojo.attr(newElement, 'type', 'hidden');
        dojo.attr(newElement, 'name', 'players[' + player['ID'] + ']');
        // Wert hinzufügen
        dojo.attr(newElement, 'value', player['Position']);

        dojo.doc.forms['poolLineUp'].appendChild(newElement);
    }

    //Taktik
    // hidden input erzeugen
    newElement = dojo.doc.createElement('input');

    dojo.attr(newElement, 'type', 'hidden');
    dojo.attr(newElement, 'name', 'tactic');
    // Wert hinzufügen
    dojo.attr(newElement, 'value', tactic);

    dojo.doc.forms['poolLineUp'].appendChild(newElement);

    // Preset
    if (preset != null) {
        // hidden input erzeugen
        newElement = dojo.doc.createElement('input');

        dojo.attr(newElement, 'type', 'hidden');
        dojo.attr(newElement, 'name', 'preset');
        // Wert hinzufügen
        dojo.attr(newElement, 'value', preset);

        dojo.doc.forms['poolLineUp'].appendChild(newElement);
    }

    if (presetName != null) {
        // hidden input erzeugen
        newElement = dojo.doc.createElement('input');

        dojo.attr(newElement, 'type', 'hidden');
        dojo.attr(newElement, 'name', 'presetname');
        // Wert hinzufügen
        dojo.attr(newElement, 'value', presetName);

        dojo.doc.forms['poolLineUp'].appendChild(newElement);
    }

    // Action
    // hidden input erzeugen
    newElement = dojo.doc.createElement('input');

    dojo.attr(newElement, 'type', 'hidden');
    dojo.attr(newElement, 'name', 'action');
    // Wert hinzufügen
    dojo.attr(newElement, 'value', 'save');

    dojo.doc.forms['poolLineUp'].appendChild(newElement);

    dojo.doc.forms['poolLineUp'].submit();
}

function showMessage(messageText) {
    dojo.require('dojo.html');

    var message = dojo.byId('Message');

    if (message != null) {
        dojo.html.set(message, messageText);
    }

    return message;
}


function reloadPlayerTraining(data) {
    showMessage(data);
    var pId = dojo.byId('PlayerProfilePlayerId');
    var pIdValue = pId.value;
    window.setTimeout(
        function() {
            showPlayerTraining(0 + pIdValue);
        },
        2000
    );
}



/* Commander */
/**
 * Markiert einen Player im Commander und
 * setzt die Werte für den Transfer als POST-Daten.
 *
 * @param playerId
 * @param teamId
 * @return void
 */
function selectPlayer(element, playerId, fromTeamId, toTeamId)
{
    // überhaupt irgendwas da?
    if (element && element.nodeName && element.nodeType) {
        var nodeName = element.nodeName.toLowerCase();
        var nodeType = element.nodeType;
        if (nodeName == "tr" && nodeType == 1) {
            // Spieler-Eintrag markieren
            var markedElement = markPlayer(element, playerId);
            checkPlayerMoveable(markedElement);
        }
    }
}

/**
 * Markiert die entsprechende Tabellenzeile.
 * Sollte diese bereits markiert seinso wird die Markierung entfernt.
 *
 * @param HTML-Element element mit der entsprechenden zu markierenden Zeile
 * @param int playerId mit der Spielernummer
 * @return HTML-Element das markierte Element oder null wenn keins markiert wurde
 */
function markPlayer(element, playerId)
{
    // hat das Element die Markierung schon?
    if (dojo.hasAttr(element, 'id')) {
        // altes markiertes Element finden und Markierung entfernen
        removeAttributeFromElement('TeamTransferFrom', 'tr', 'id');
        // Felder für den Post ausfüllen
        dojo.attr(dojo.byId('poolPlayerPlayerId'), 'value', -1);
        return null;
    }
    // altes markiertes Element finden und Markierung entfernen
    removeAttributeFromElement('TeamTransferFrom', 'tr', 'id');
    // neues Element markieren
    dojo.attr(element, 'id', 'PlayerMarker');
    // Felder für den Post ausfüllen
    dojo.attr(dojo.byId('poolPlayerPlayerId'), 'value', playerId);
    return element;
}

function checkPlayerMoveable(element)
{
    var moveable = true;
    var tableToHandle = null;
    var tableLeft = null;

    var transFromData = getPoolTableData('TeamTransferFrom');
    var transToData = getPoolTableData('TeamTransferTo');
    // ein Element markiert
    if (element) {
        //
        var type = getRowType(element);
        transFromData[type]--;
        transToData[type]++;
    } else {
        moveable = false;
    }
    // Anzahl Trainer links Groß genug
    if (transFromData['trainers'] < licenceConditions.teamFrom.poolTrainerMin) {
        moveable = false;
    }
    // Anzahl Spieler groß genug
    if (transFromData['players'] < licenceConditions.teamFrom.poolPlayerMin) {
        moveable = false;
    }
    if ((transToData['trainers'] + transToData['players']) > licenceConditions.teamTo.poolMax) {
        moveable = false;
    }
    if (transToData['youngsters'] > licenceConditions.teamTo.poolYoungMax) {
        moveable = false;
    }
    if (transToData['trainers'] < licenceConditions.teamTo.poolTrainerMin) {
        moveable = false;
    }
    if (transToData['players'] < licenceConditions.teamTo.poolPlayerMin) {
        moveable = false;
    }
    if (transToData['youngsters'] < licenceConditions.teamTo.poolYoungMin) {
        moveable = false;
    }
    if (moveable == true) {
        dojo.removeAttr('PoolPlayerMoveRight', 'disabled');
        dojo.style('PoolPlayerMoveRight', 'visibility', 'visible');
        //
    } else {
        dojo.attr('PoolPlayerMoveRight', 'disabled', 'disabled');
        dojo.style('PoolPlayerMoveRight', 'visibility', 'hidden');
        //
    }
}


function getPoolTableData(tableId)
{
    var data = new Array();
    data['players'] = 0;
    data['trainers'] = 0;
    data['youngsters'] = 0;
    data['unknown'] = 0;
    var table = dojo.byId(tableId);
    // Element überhaupt vorhanden
    if (table && table.nodeName && table.nodeType) {
        var nodeName = table.nodeName.toLowerCase();
        var nodeType = table.nodeType;
        // ist es wirklich eine Tabelle
        if (nodeName == "table" && nodeType == 1) {
            // alle TR-Elemente holen
            var tableRows = table.getElementsByTagName('tr');
            for (var x = 0; x <= tableRows.length -1; x++) {
                // das tatsächsliche TR-Element
                var row = tableRows[x];
                if (row) {
                    var type = getRowType(row);
                    data[type]++;
                }
            }
        }
    }
    return data;
}


function getRowType(tableRow)
{
    var type = "unknown";
    if (tableRow.getAttributeNode('class')) {
        var rowAttr = tableRow.getAttributeNode('class');
        type = getPlayerType(rowAttr);
    }
    return type;
}


function getPlayerType(trClassAttribute)
{
    var type = "unknown";
    var nVal = trClassAttribute.nodeValue;
    var values = nVal.split(" ");
    for (var x = 0; x <= values.length -1; x++) {
        var value = values[x];
        if (value == "trainer") {
            type = "trainers";
            break;
        }
        if (value == "youngplayer") {
            type = "youngsters";
            break;
        }
        if (value == "player") {
            type = "players";
            break;
        }
    }
    return type;
}


function removeAttributeFromElement(elementID, elementTagName, attributeName) {
    var temp = dojo.byId(elementID);

    if (temp != null) {
        temp = temp.getElementsByTagName(elementTagName);
        for (i = 0; i < temp.length; i++) {
            if (dojo.hasAttr(temp[i], attributeName)) {
                dojo.removeAttr(temp[i], attributeName);
            }
        }
    }
}

function moveMarkedPlayerToNewTeam(targetElementName, teamElementID) {
    var playerElement = dojo.byId('PlayerMarker');

    if (playerElement != null) {
        var targetElement = dojo.byId(targetElementName);

        if (targetElement != null) {
            targetElement = targetElement.getElementsByTagName('tbody')[0];

            targetElement.appendChild(playerElement);

            var widget = dijit.byId(teamElementID);

            var teamID = null;

            if (widget) {
                teamID = widget.attr('value');
            }

            if (teamID == null) {
                teamID = dojo.attr(teamElementID, 'value');

                if (teamID == null) {
                    teamID = dojo.byId(teamElementID).value;
                }
            }

            if (teamID != null) {
                var temp = playerElement.getElementsByTagName('input');

                for (i = 0; i < temp.length; i++) {
                    dojo.attr(temp[i], 'value', teamID);
                }
            }


            removeAttributeFromElement(targetElementName, 'tr', 'id');

            dojo.attr('PoolPlayerMoveRight', 'disabled', 'disabled');
            dojo.style('PoolPlayerMoveRight', 'backgroundImage', 'url(../images/design/bt_right_disabled.png)');
            dojo.attr('PoolPlayerMoveLeft', 'disabled', 'disabled');
            dojo.style('PoolPlayerMoveLeft', 'backgroundImage', 'url(../images/design/bt_left_disabled.png)');
        }
    }
}




/* Calculate Training */

function calculateTraining() {
    var trainingElement = dojo.byId('Training');

    if (trainingElement != null) {
        var tableElements = trainingElement.getElementsByTagName('table');

        if (tableElements.length > 0) {
            var isOver100 = false;

            for (var i = 0; i < tableElements.length; i++) {
                var sum = 0;

                var widg = dijit.findWidgets(tableElements[i]);

                var sum = 0;
                for (var j = 0; j < widg.length; j++) {
                    if (widg[j] != null) {
                        sum += parseInt(widg[j].attr('value'));
                    }
                }
                if (sum > 100) {
                    isOver100 = true;
                }
            }
            showOver100Hint(isOver100);
        }
    }
}

function showOver100Hint(show) {
    var hintElement = dojo.byId('Over100Hint');

    if (hintElement != null) {
        if (show) {
            dojo.style(hintElement, 'display', 'block');
        }
        else {
            dojo.style(hintElement, 'display', 'none');
        }
    }
}

/* Calculate Next Bid Price */

function calculateNextBidPrice(showElementID, targetElementID, price, bid) {
    var showElement = dojo.byId(showElementID);

    var targetElement = dojo.byId(targetElementID);

    if (showElement != null && targetElement != null) {
        toggleWithoutBlock(showElementID);

        if (dojo.style(showElement, 'display') == 'none') {
            targetElement.value = '';
        }
        else {
            if (bid > 0) {
                targetElement.value = parseInt(price) + 1000;
            }
            else {
                targetElement.value = parseInt(price);
            }
        }
    }
}

/* Calculate Licence */

function calcManagerLizenzCost(selectElement, pid) {
    var value = selectElement.value;

    var cost = 7000000;

    if (value != null && value >= 3) {
        cost = 6000000;
    }

    if (pid != null && cost != null) {
        var productCost = dojo.byId(pid);

        if (productCost != null) {
            dojo.require('dojo.number');

            productCost.firstChild.data = dojo.number.format(cost);
        }
    }
}

/* Calculate Place Win */

function calculatePlaceWin(countPlaceID, priceID, WinID, seperator) {


    var priceElement = dojo.byId(priceID);

    if (priceElement == null) {
        return;
    }

    price = parseInt(priceElement.value);

    if (String(price) == 'NaN') {
        priceElement.value = '';
        updateContent(WinID, 0);
        return;
    }
    priceElement.value = price;

    var countPlaceElement = dojo.byId(countPlaceID);

    if (countPlaceElement == null) {
        return;
    }

    var countPlace = parseInt(countPlaceElement.value);

    var win = 0;

    if (String(countPlace) != 'NaN') {
        win = countPlace * price;
    }

    if (win != null && win > 0) {
        win = implantSeperator(win, seperator);
        updateContent(WinID, win);
    }
    else {
        updateContent(WinID, 0);
    }
}

function implantSeperator(win, seperator) {
//    alert(win);
    var winReverse = '';
    var str = String(win);
    var strlen = str.length;
    var count = 0;
    for ( var x = strlen -1; x >= 0; x--) {
        if (count == 3) {
            count = 0;
            winReverse += seperator;
        }
        count++;
        winReverse += str[x];
    }
    var winRight = '';
    for (var x = winReverse.length -1; x >= 0; x--) {
        winRight += winReverse[x];
    }
    return winRight;
}

/* Place Upgrade */

function updateVIPPlaceUpgrade(sourceElementID, updateElementID, operation) {
    var sourceElement = dojo.byId(sourceElementID);

    if (sourceElement != null && operation != null) {
        var value = parseInt(sourceElement.firstChild.data);

        if (value != null) {
            var updateValue = value;

            if (operation == 1 && updateValue < 3000) {
                updateValue += 500;
            }
            else if (operation == -1 && updateValue >= -3000) {
                updateValue -= 500;
            }

            sourceElement.firstChild.data = updateValue;

            var hiddenSourceElement = dojo.byId(sourceElementID + 'Hidden');

            if (hiddenSourceElement != null) {
                hiddenSourceElement.value = updateValue;
            }

            if (updateValue > 0) {
                calculatePlaceUpgrade(null, updateElementID, updateValue);
            }
            else {
                updateContent(updateElementID, 0);
            }
        }
    }
}



/* Calculate Stadium In */

// Kann gelöscht werden
function calculateStadium(productName, productLevel, isAdd, priceElementID) {
    var priceElement = dojo.byId(priceElementID);

    if (priceElement == null) {
        return;
    }

    var price = parseInt(priceElement.firstChild.data);

    if (String(price) == 'NaN') {
        priceElement.value = '';
        updateContent(priceElementID, 0);
        return;
    }

    if (isAdd) {
        price += stadiumPrices[productName][productLevel + 1];
    }
    else {
        price -= stadiumPrices[productName][productLevel + 1];
    }

    if (price != null && price > 0) {
        updateContent(priceElementID, price);
    }
    else {
        updateContent(priceElementID, 0);
    }
}

/* UpdateContent */

function updateContent(updateElementID, content) {
    var updateElement = dojo.byId(updateElementID);

    if (updateElement != null && content != null) {
        updateElement.firstChild.data = content;
    }
}

/* Show StadiumPeripherie */

function showStadiumPeripherie(source) {
    showOverlay();

    var divElement = dojo.doc.createElement('div');

    dojo.attr(divElement, 'id', 'StadiumPeripherie');

    dojo.connect(divElement, 'click', hideStadiumPeripherie);

    var imageElement = dojo.doc.createElement('img');

    imageElement.src = source;

    dojo.style(imageElement, 'width', '100%');

    divElement.appendChild(imageElement);

    dojo.body().appendChild(divElement);

    var pageSize = getPageSize();

    var top = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

    dojo.style(divElement, {
        'position': 'absolute',
        'top': top + 'px',
        'left': '0px',
        'paddingTop': '150px',
        'height': (pageSize[1] - imageElement.height) + 'px',
        'width': '100%'
        }
    );
}

function hideStadiumPeripherie(event) {
    if (event == null || event.target.getAttribute('id') == 'StadiumPeripherie') {
        var element = dojo.byId('StadiumPeripherie');

        if (element != null) {
            element.parentNode.removeChild(element);
        }

        hideOverlay();
    }
}

function updatePercent(elementID, percent, percentStep) {
    var percentElement = dojo.byId(elementID);
    var newWidth = percent;

    if (percentElement != null) {
        newWidth = percent - percentStep;

        dojo.style(percentElement, 'width', String(newWidth).substr(0, 8) + '%');
    }
    if (percent && percent >= 0) {
        window.setTimeout("updatePercent('" + elementID + "', " + newWidth + ", " + percentStep + ");", /*59500*/1000);
    }
}

/**
 * Erhöht den übergebenen timestamp um eine Sekunde und aktualisiert die Anzeige
 *
 * @param string elementID
 * @param int timestampInMilliseconds
 * @return void
 */
function watch(elementID, timestampInMilliseconds) {
    var timestampInMillisecondsInInt = parseInt(timestampInMilliseconds);

    var timestamp = timestampInMilliseconds;

    if (timestampInMillisecondsInInt != NaN) {
        timestamp = timestampInMillisecondsInInt + 1000;

        var newTime = new Date(timestamp);

        var element = dojo.byId(elementID);

        if (element != null) {
            var hours = newTime.getHours();

            if (hours < 10) {
                hours = '0' + String(hours);
            }

            var minutes = newTime.getMinutes();

            if (minutes < 10) {
                minutes = '0' + String(minutes);
            }

            var seconds = newTime.getSeconds();

            if (seconds < 10) {
                seconds = '0' + String(seconds);
            }

            element.firstChild.nodeValue = hours + ':' + minutes + ':' + seconds;
        }
    }

    window.setTimeout("watch('" + elementID + "', '" + timestamp + "');", 1000);
}


/**
 * Erhöht den übergebenen timestamp um eine Minute und aktualisiert die Anzeige
 *
 * @param string elementID
 * @param int hour mit der aktuellen Stunde
 * @param int minute mit der aktuellen Minute
 * @param int second mit der aktuellen Sekunde
 * @return void
 */
function _updateMatchInfoTime(elementId, hour, minute, second, showSeconds)
{
    var element = dojo.byId(elementId);
    if (element != null) {
        var viewHour = '' + hour;
        var viewMinute = '' + minute;
        var viewSecond = '' + second;
        if (hour < 10) {
            viewHour = '0' + hour;
        }
        if (minute < 10) {
            viewMinute = '0' + minute;
        }
        if (second < 10) {
            viewSecond = '0' + second;
        }
        var clockTime = viewHour + ':' + viewMinute;
        // auch Sekunden anzeigen
        if (showSeconds == true) {
            clockTime += ':' + viewSecond
        }
        element.firstChild.nodeValue = clockTime;
        if (second > 59) {
            second = -1;
            minute++;
        }
        if (minute > 59) {
            minute = 0;
            hour++;
        }
        if (hour > 23) {
            hour = 0;
        }
    }
    window.setTimeout(
        function()
        {
            _updateMatchInfoTime(elementId, hour, minute, ++second, showSeconds);
        }, 900
    );
}

function updateTimeAtTimeHTML(suffix, countdown) {
    var daysElement = dojo.byId('TimeDays' + suffix);
    var hoursElement = dojo.byId('TimeHours' + suffix);
    var minutesElement = dojo.byId('TimeMinutes' + suffix);
    var secondsElement = dojo.byId('TimeSeconds' + suffix);
    var timerElement = dojo.byId('TimerID' + suffix);

    if (timerElement) {
        var val = timerElement.value;
        if (val > 0) {
            window.clearTimeout(val);
        }
    }

    var finish = false;

    if (getValueByFirstChild(daysElement) == 0 &&
        getValueByFirstChild(hoursElement) == 0 &&
        getValueByFirstChild(minutesElement) == 0 &&
        getValueByFirstChild(secondsElement) <= 1) {
        finish = true;
    }

//  alert(getValueByFirstChild(daysElement) + "; " +
//          getValueByFirstChild(hoursElement) + "; " +
//          getValueByFirstChild(minutesElement) + "; " +
//          getValueByFirstChild(secondsElement));

    if (secondsElement != null) {
        var seconds = getReduceValueByFirstChild(secondsElement);

        if (seconds < 0) {
            if (minutesElement != null) {
                var minutes = getReduceValueByFirstChild(minutesElement);

                if (minutes < 0) {
                    if (hoursElement != null) {
                        var hours = getReduceValueByFirstChild(hoursElement);

                        if (hours < 0) {
                            if (daysElement != null) {
                                var days = getReduceValueByFirstChild(daysElement);

                                if (days < 0) {
                                    days = 0;
                                }

                                if (countdown == true && days < 10) {
                                    days = '0' + String(days);
                                }
                                if (finish == true) {
                                    days = '00';
                                }

                                setValueByFirstChild(daysElement, days);

                                hours = 23;
                            } else {
                                hours = 0;
                            }
                        }

                        if (countdown == true && hours < 10) {
                            hours = '0' + String(hours);
                        }
                        if (finish == true) {
                            hours = '00';
                        }

                        setValueByFirstChild(hoursElement, hours);

                        minutes = 59;
                    } else {
                        minutes = 0;
                    }
                }

                if (countdown == true && minutes < 10) {
                    minutes = '0' + String(minutes);
                }
                if (finish == true) {
                    minutes = '00';
                }

                setValueByFirstChild(minutesElement, minutes);

                seconds = 59;
            } else {
                seconds = 0;
            }
        }

        if (countdown == true && seconds < 10) {
            seconds = '0' + String(seconds);
        }
        if (finish == true) {
            seconds = '00';
        }

        setValueByFirstChild(secondsElement, seconds);
    }

    if (finish == false) {
        var timerId = window.setTimeout("updateTimeAtTimeHTML('" + suffix + "', " + countdown + ");", 1000);
        if (timerElement) {
            timerElement.value = timerId;
        }
        return timerId;
    }
}

function getValueByFirstChild(element) {
    if (element == null) {
        return 0;
    }
    return element.firstChild.data;
}

function getReduceValueByFirstChild(element) {
    value = parseInt(getValueByFirstChild(element), 10);

    if (!isNaN(value)) {
        return value - 1;
    }

    return 0;
}

function setValueByFirstChild(element, value) {
    element.firstChild.data = value;
}

function filterTransfermarket(filter, page, sort) {
    var parameter = '?';

    if (filter.length > 0) {
        parameter += 'filter=' + filter;
    }

    if (page.length > 0) {
        if (parameter.length > 1) {
            parameter += '&';
        }

        parameter += 'page=' + page;
    }

    if (sort != null && sort.length > 0) {
        if (parameter.length > 1) {
            parameter += '&';
        }

        parameter += 'sort=' + sort;
    }

    window.location.href = window.location.pathname + parameter;
}

var checkBoxArray = new Array();

function addSelectionToArray(checkBoxItem)
{
    if(checkBoxItem)
    {
        var arrayLength = checkBoxArray.length;
        var type = checkBoxItem.getAttribute('type');
        if (type && type == 'checkbox' && checkBoxItem.checked == true)
        {
            if (arrayLength < 5)
            {
                checkBoxArray[arrayLength] = checkBoxItem;
            }
            else
            {
                var lastitem = checkBoxArray[arrayLength-1];
                lastitem.checked = false;
                checkBoxArray[arrayLength-1] = checkBoxItem;
            }
        }
        else if(type && type == 'checkbox' && checkBoxItem.checked == false)
        {
            var nArray = new Array();
            var count = 0;
            for(var i = 0; i < arrayLength; i++)
            {
                var oldItem = checkBoxArray[i];
                if (oldItem != checkBoxItem)
                {
                    nArray[count] = oldItem;
                    count++;
                }
            }
            checkBoxArray = nArray;
        }
    }
}

function doLinkAction(url)
{
    if (url != null && url.length > 0)
    {
        window.location.href = url;
    }
}

var termPopup = null;

function showTerms() {
    var params = 'height=706,width=780,top=150,left=150,location=no,menubar=no,scrollbars=yes,status=yes,toolbar=no';

    if (termPopup == null || (termPopup != null && termPopup.closed)) {
        termPopup = window.open('terms.php', '', params);
    }

    termPopup.focus();
}

var imprintPopup = null;

function showImprint() {
    var params = 'height=706,width=780,top=150,left=150,location=no,menubar=no,scrollbars=yes,status=yes,toolbar=no';

    if (imprintPopup == null || (imprintPopup != null && imprintPopup.closed)) {
        imprintPopup = window.open('imprint.php', '', params);
    }

    imprintPopup.focus();
}


function changeTeamShirt() {
    showInternalPopup2('teamshirt.php', null);
}


function showTeamPlayers(teamId) {
    showInternalPopup2('teamplayers.php?id=' + teamId, null);
}

function changeTeamNationality() {
    showInternalPopup2('teamnationality.php', null);
}



/* Allgemeine Helfer */
/*
function toggleClassByName(elementName, classOne, classTwo) {
    var elements = dojo.doc.getElementsByTagName(elementName);

    for (i = 0; i < elements.length; i++) {
        toggleClass(elements[i], classOne, classTwo);
    }
}

function toggleClassByID(elementID, classOne, classTwo) {
    var element = dojo.byId(elementID);

    if (element != null) {
        toggleClass(element, classOne, classTwo);
    }
}
*/

/* Menu */
/*
function toggleSubmenu(clickElement) {
    var parent = clickElement.parentNode;

    if (parent != null) {
        var submenu = parent.getElementsByTagName('ul');

        if (submenu[0] != null) {
            toggle(submenu[0]);

            changeExpandCollapse(clickElement);
        }
    }
}

function checkMenuCollapseExpand(elementID) {
    var menuElement = dojo.byId(elementID);

    if (menuElement != null) {
        var lis = menuElement.getElementsByTagName('li');

        for (i = 0; i < lis.length; i++) {
            var uls = lis[i].getElementsByTagName('ul');

            for (j = 0; j < uls.length; j++) {
                if (dojo.style(uls[j], 'display') == 'block') {
                    var as = lis[i].getElementsByTagName('a');

                    for (k = 0; k < as.length; k++) {
                        changeExpandCollapse(as[k]);
                    }
                }
            }
        }
    }
}
*/
/*
function showHeal(playerID) {
    if (playerID != null) {
        showInternalPopup('timeshealpopup.php?id=' + playerID + '&popup=1', null);
    }
}

function showAge(playerID) {
    if (playerID != null) {
        showInternalPopup('timesagepopup.php?id=' + playerID + '&popup=1', null);
    }
}

function abortBuild(buildID) {
    var buildElement = dojo.byId('BuildQueueID');

    if (buildElement != null) {
        buildElement.value = buildID;
    }
}
*/

/* Register */

function switchBackgroundFromManager(elementID1, elementID2, value) {
    var registerElement1 = dojo.byId(elementID1);
    var registerElement2 = dojo.byId(elementID2);

    if (registerElement1 != null && registerElement2 != null) {
        if (value == 'player') {
            dojo.style(registerElement1, 'display', '');
            registerElement2.value = 1;
        }
        else {
            dojo.style(registerElement1, 'display', 'none');
            registerElement2.value = 0;
        }
    }
}

function updateOptionalHint() {
    var optionalElement = dojo.byId('Optional');

    if (optionalElement != null) {
        if (optionalElement.value == 0) {
            optionalElement.value = 1;
        }
        else {
            optionalElement.value = 0;
        }
    }
}

/* Activationteam */

var choosedStadiumImage = null;

function showStadiumOverview(stadiumname) {
    var stadiumImageElement = dojo.byId('StadiumImage');

    if (stadiumImageElement != null) {
        if (stadiumname != null && stadiumname.length > 0) {
            dojo.style(stadiumImageElement, 'background', 'transparent url(../images/stadiums/' + stadiumname.toLowerCase() + '/overview.jpg) scroll no-repeat top left');
        }
        else if (choosedStadiumImage == null) {
            dojo.style(stadiumImageElement, 'background', '');
        }
        else {
            dojo.style(stadiumImageElement, 'background', choosedStadiumImage);
        }
    }
}

function chooseStadiumImage() {
    var stadiumImageElement = dojo.byId('StadiumImage');

    if (stadiumImageElement != null) {
        choosedStadiumImage = dojo.style(stadiumImageElement, 'background');
    }
}

/* GameInformation */

function showGameInformation(site) {
    showInternalPopup('gameinformation.php?site=' + site + '&popup=1', null);
}

// ??? - Glaube das es veraltet ist
function showTabContent(tabElementID) {
    var tabElement = dojo.byId(tabElementID);

    if (tabElement != null) {
        var parent = tabElement.parentNode;

        var tab = parent.firstChild.nextSibling;

        while ((tab = tab.nextSibling) != null) {
            if (tab.nodeType == 1) {
                dojo.style(tab, 'display', 'none');
            }
        }

        toggle(tabElement);
    }
}

//??? - Glaube das es veraltet ist
function showGlossaryLetter(value) {
    var glossaryElement = dojo.byId('GlossaryA');

    if (glossaryElement != null) {
        do {
            if (glossaryElement.nodeType == 1) {
                dojo.style(glossaryElement, 'display', 'none');
            }
        }
        while((glossaryElement = glossaryElement.nextSibling) != null);
    }

    toggle(value);
}

/* TEST */

function showTestCallback(json)
{
    console.log(json);
}

/* Popupscheiß für Tutorial */

function showArchivedTutorialStep(stepid)
{
    var page = 'tutorial.php?sid=' + stepid + '&archivetask=archivetask';
    showInternalPopup2(page, null);
}

function renderTaskDefaultDone()
{
    hideTutorial();
    tutorialStepDiv = -1;
    // Anzeigebereich Ändern
    var tutorialHead = dojo.byId('InternalPopupClose');
    if(tutorialHead != null)
    {
        tutorialHead.id = tutorialHead.id + 'Tut';

        var internalPopupCloseElement = dojo.byId(tutorialHead.id);

        if (internalPopupCloseElement != null) {
            dojo.connect(internalPopupCloseElement, 'onmousedown', prepareInternalPopupToMove);
        }
    }
    var page = 'tutorial.php?done=done';
    showInternalPopup2(page, null);
}

function renderTask0Done()
{
    hideTutorial();
    tutorialStepDiv = -1;
    // Anzeigebereich Ändern
    var tutorialHead = dojo.byId('InternalPopupClose');
    if(tutorialHead != null)
    {
        tutorialHead.id = tutorialHead.id + 'Tut';

        var internalPopupCloseElement = dojo.byId(tutorialHead.id);

        if (internalPopupCloseElement != null) {
            dojo.connect(internalPopupCloseElement, 'onmousedown', prepareInternalPopupToMove);
        }
    }
    var page = 'tutorial.php?done=done';
    showInternalPopup2(page, showTutorial);
}

function renderTask10Done()
{
    renderTaskDefaultDone();
}

function renderTask16Done()
{
    renderTaskDefaultDone();
}

function renderTask18Done()
{
    var tutPlayerDiv = dojo.byId('tutorialDonePlayer');
    if (tutPlayerDiv != null) {

        // Dojo Widgets löschen
        var widgets = dijit.findWidgets(tutPlayerDiv);
        // Elemente rekursiv löschen
        dojo.forEach(widgets, function(item) {
            item.destroyRecursive();
        });
    }
    var element = new dijit.form.FilteringSelect(
        {
            name: 'pid'
        },
        'TutorialPlayerSelect'
    );
    var bt = new dijit.form.Button({
        type: 'button',
        onClick: function () {
            var widgetId = element.id;
            reloadTutorial(widgetId);
        }
    }, 'TutorialButtonShorten');
}


function reloadTutorial(widgetId)
{
    var tutPlayerDiv = dijit.byId(widgetId);
    var page = 'tutorial.php?pid=' + tutPlayerDiv.value;
    showInternalPopup2(page, null);
}


function renderTask19()
{
    var tutPlayerDiv = dojo.byId('TutorialTaskDefault');
    if (tutPlayerDiv != null) {

        // Dojo Widgets löschen
        var widgets = dijit.findWidgets(tutPlayerDiv);
        // Elemente rekursiv löschen
        dojo.forEach(widgets, function(item) {
            item.destroyRecursive();
        });
    }

    var element1 = dojo.byId('TutorialPlayerSelect');

    if(element1 != null)
    {

        var element = new dijit.form.FilteringSelect(
            {
                name: 'pid'
            },
            'TutorialPlayerSelect'
        );
    }

    var element2 = dojo.byId('TutorialButtonFitness');

    if(element2 != null)
    {
        var bt = new dijit.form.Button({
            type: 'button',
            onClick: function () {
                var widgetId = element.id;
                reloadTutorial(widgetId);
            }
        }, 'TutorialButtonFitness');
    }

    tutorialNextStep('TutorialTaskDiv');
}

function renderTask20Done()
{
    renderTaskDefaultDone();
}

function renderTask21Done()
{
    renderTaskDefaultDone();
}

function renderTask27Done()
{
    renderTaskDefaultDone();
}

function renderTask30(url)
{
    new dijit.form.FilteringSelect(
        {
            'class': 'registerSelect',
            name: 'svid',
            style: 'width: 350px;'
        },
        'chooseServer'
    );

    new dijit.form.Button(
        {
            name: 'action[save]',
            onClick: function() {
                ajaxSubmit(url, 'save', 'formChooseServer', null, showPreliminariesChooseServer);
            }
        },
        'chooseServerButton'
    );
}

var chatNotificationTimer = null;

function chatNotification()
{
    if (!dojo.hasClass('TopMenuChat', 'active')) {
        dojo.addClass('TopMenuChat', 'active');
    }

    if (dojo.style('loesen', 'backgroundPosition') == '0px -115px') {
        dojo.style('loesen', 'backgroundPosition', '0px -46px');
    } else {
        dojo.style('loesen', 'backgroundPosition', '0px -115px');
    }

    if (chatNotificationTimer != null) {
        window.clearTimeout(chatNotificationTimer);
    }

    chatNotificationTimer = window.setTimeout('chatNotification()', 1200);
}

