/*
    REQUIRES: dhtmlHistory.js - Historie-Modul
    REQUIRES: pngfix.js - PNG-Korrektur-Modul
*/


// initialize ourselves when the page is
// finished loading
window.onload = initialize;

disableURLCheck = false;

// Bereiche bei denen das Neuladen der Seite verhindert werden soll
// - bei einem Wechsel zwischen diesen Bereichen
// var faqhashs = new Array();
// faqhashs[0] = "SiteTop";
// faqhashs[X] = "...";
// Liste ---> Wird im Servlet erstellt !!!!!!!!!!!!

// verschiedene Status-Variablen
var disableScrollToTop = false;
var initialized = false;
var pageName;
var pageLocation;
var subSiteId;

// 0=normal, 1=with-id-parameter, 2=with-static-parameter, 3=php-call, 4=method post
var callingType = 0;
var callingIdParameter = "";
var callingStaticParameter = "&static";
var callingPostParameter = "";

/** Our function that initializes when the page
    is finished loading. */
function initialize() {

    // Verhindet das Flackern der Seite im FF
    disableURLCheck = true;
    window.setTimeout(enableURLCheck, 100);

    // Platz für Skyscraper?
    checkIfSkyscraper();

    // hashListener.init();

/*
   // initialize the DHTML History framework
   dhtmlHistory.initialize();

   // add ourselves as a DHTML History listener
   dhtmlHistory.addListener(handleHistoryChange);
*/

   initialized = true;

   // PNG-Fix für IE durchführen
   correctPNG();
}

function getStaticSiteContent(page){
    callingType = 2;

    // aktuelle Seite abspeichern
    pageName = page;
    //netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
    tmpLocation = "XMLForwarder?file="+CONTENT_PATH+GLOBAL_LANGUAGE+"/portal/"+pageName+"/"+pageName+".de.xml";
    saveHistoryAndInitGetContent(tmpLocation);
}

function getSiteContent(page)
{
    callingType = 0;

    // aktuelle Seite abspeichern
    pageName = page;
    tmpLocation = "?inhalt="+pageName+"&ajax=true";
    saveHistoryAndInitGetContent(tmpLocation);
}

function sendAndGetSiteContent(page, formular){
    callingType = 4;
    callingPostParameter = "aktion="+page+gettingPostParameterFromFormular(formular);

    //alert(callingPostParameter);

    pageName = page;
    tmpLocation = "Aktion";

    saveHistoryAndInitGetContent(tmpLocation);
}

function gettingPostParameterFromFormular(formularName){
    tForm = eval("document."+formularName);

    targetData = "";
    for (i=0; i<tForm.elements.length; i++){
        if (tForm.elements[i].type.toLowerCase() == "radio" || tForm.elements[i].type.toLowerCase() == "checkbox"){
            if (tForm.elements[i].checked){
                targetData += "&"+tForm.elements[i].name+"="+tForm.elements[i].value;
            }
        }else{
            targetData += "&"+tForm.elements[i].name+"="+tForm.elements[i].value;
        }
    }

    return targetData;
}

function getSubSiteContent(page, id)
{
    callingType = 1;
    callingIdParameter = id;

    // aktuelle Seite abspeichern
    pageName = page;
    subSiteId = id;
    tmpLocation = "?inhalt="+pageName+"&ajax=true&id="+subSiteId;
    saveHistoryAndInitGetContent(tmpLocation);
}

function getSiteContentPHP(targetSite, parameter, page)
{
    callingType = 3;

    // aktuelle Seite abspeichern
    pageName = page;
    tmpLocation = targetSite+"?"+parameter;
    saveHistoryAndInitGetContent(tmpLocation);
}

function saveHistoryAndInitGetContent(tmpLocation){
    //if (tmpLocation != "Aktion"){
        // Historie-Eintrag anlegen
        hashListener.setHash("#"+escape(tmpLocation));
    //}

    // Daten holen
    initGetContent(tmpLocation);
}

var CHECK_FOR_DUPLICATE_REQUEST = false;
var LAST_REQUEST_PARAMETER = null;

function disableDuplicateRequestCheck(){
    CHECK_FOR_DUPLICATE_REQUEST = false;
    LAST_REQUEST_PARAMETER = null;
}

function initGetContent(newLocation) {

    /*alert(
        CHECK_FOR_DUPLICATE_REQUEST
        +" "+
        LAST_REQUEST_PARAMETER
        +" "+
        callingPostParameter
        +" "+
        pageLocation
        +" "+
        newLocation
    );*/
    if (CHECK_FOR_DUPLICATE_REQUEST){
        if (pageName != "SiteTop"){
            if (callingType==4){
                if (LAST_REQUEST_PARAMETER == callingPostParameter.substring(callingPostParameter.indexOf("?")+1)){
                    return false;
                }
            }else{
                if (LAST_REQUEST_PARAMETER == pageLocation.substring(pageLocation.indexOf("?")+1)){
                    return false;
                }
            }
        }
    }
    //if(pageLocation != newLocation){
        //if (callingType==4){
        //    pageLocation = newLocation+"?"+callingPostParameter;
        //}else{
            pageLocation = newLocation;
        //}

        if (pageName != "SiteTop"){
            CHECK_FOR_DUPLICATE_REQUEST = true;
            if (callingType==4){
                LAST_REQUEST_PARAMETER = callingPostParameter.substring(callingPostParameter.indexOf("?")+1);
                ajax_newXmlHttpRequest( printOut, 'POST', "Aktion", callingPostParameter.substring(callingPostParameter.indexOf("?")+1), true);
            }else{
                LAST_REQUEST_PARAMETER = pageLocation.substring(pageLocation.indexOf("?")+1);
                ajax_newXmlHttpRequest( printOut, 'POST', "./", pageLocation.substring(pageLocation.indexOf("?")+1), true);
            }
            window.setTimeout("disableDuplicateRequestCheck()", 100);
        }
    //}
}

function disableDuplicateCheck(){
    LASTRESPONSE = "";
}

var LASTRESPONSE = "";

function printOut(pXml, pText)
{
      //alert(pText);
  if (LASTRESPONSE == pText || pText == ""){
    return false;
  }else{
    LASTRESPONSE = pText;
    window.setTimeout("disableDuplicateCheck()", 100);
  }

    // Daten vollständig geladen?
//    if (reqObject.readyState == 4)
//    {//alert(reqObject.status);
        // Zugriff auf Daten freigegeben? // WIRD VON OPERA NICHT AUSGEFÜHRT (BEI ONLOAD KOMMT EIN 304 ERROR)
//        if (reqObject.status == 200)
//        {
            if (!disableScrollToTop)
            {
                // Vor dem Laden der Seite nach oben scrollen
                window.scrollTo(0,0);
            }

            //alert(pageLocation);

            // XML-Antwort abspeichern
            var response = pXml; //reqObject.responseXML;

            // Seiteninhalt und Seitentitel
            var content = undefined;
            var sitetitle = undefined;

            if (response.getElementsByTagName('aktion').length > 0){

                if (response.getElementsByTagName('erfolg').length > 0){
                    content = getInnerText(response.getElementsByTagName('erfolg')[0]);

                }else{

                    content = getInnerText(response.getElementsByTagName('fehler')[0]);
                    alert(content);
                    return false;
                }

            }else{

                // Falls XML-Antwort nicht geparst werden kann... (wurde wegen eines BUGS integriert)
                if (response.getElementsByTagName('inhalt')[0] == undefined)
                {
                    // Start- und End-Tags festlegen
                    var startTagInhalt = "<![CDATA[";
                    var endTagInhalt = "]]>";
                    var startTagTitel = "<titel>";
                    var endTagTitel = "</titel>";

                    // Text-Antwort
                    var textContent = pText; //reqObject.responseText;

                    // Positionen der Daten suchen
                    var posStartInhalt = textContent.indexOf(startTagInhalt);
                    var posEndInhalt = textContent.indexOf(endTagInhalt);
                    var posStartTitel = textContent.indexOf(startTagTitel);
                    var posEndTitel = textContent.indexOf(endTagTitel);

                    // gesuchte Daten abspeichern
                    content = textContent.substring(posStartInhalt+startTagInhalt.length,posEndInhalt);
                    sitetitle = textContent.substring(posStartTitel+startTagTitel.length,posEndTitel);
                }
                else
                {
                    //alert("responseXML kann ausgewertet werden");

                    // Daten abspeichern
                    content = getInnerText(response.getElementsByTagName('inhalt')[0]);
                    sitetitle = getInnerText(response.getElementsByTagName('titel')[0]);
                }
            }

            // 'Zum Seitenanfang'-Link
            var scrollToTop = "<p><a class=\"anker\" href=\"#SiteTop\">"+ANKER_SITETOP+"</a></p>";

            // Für Opera muss das <![CDATA[ und ]]> manuell entfernt werden,
            //  ansonsten entsteht eine fehlerhafte Darstellung
            if (navigator.userAgent.match("Opera") != null)
            {
                // <![CDATA[ und ]]> suchen und ausschliessen
                var tmp = content;
                if (tmp.indexOf("<![CDATA[") != -1){
                    tmp = tmp.substr(9);
                    if (tmp.indexOf("]]>") != -1){
                        tmp = tmp.substring(0,tmp.indexOf("]]>"));
                    }
                }
                document.getElementById('content').innerHTML = tmp+scrollToTop;
            } else {
                document.getElementById('content').innerHTML = content+scrollToTop;
            }

            // Falls die Newsletter-Seite aufgerufen wurd, und ein Container für die eingebene
            // E-Mail-Adresse existiert, E-Mail einfuegen
            if (document.getElementById("email-address") != undefined)
            {
                document.getElementById("email-address").innerHTML = newsletteremail + " ";
            }

            if (sitetitle !== undefined){
                // Seitentitel in Flash anpassen
                if (document.flashnav != undefined)
                {
                    // Flash-Headline-Aenderung
                    waitingFlashTitle = sitetitle;
                    document.flashnav.SetVariable("headlinevar", sitetitle);
                }
                else if (document.getElementById('flashnav') != undefined)
                {
                    // Flash-Headline-Aenderung
                    waitingFlashTitle = sitetitle;
                    document.getElementById('flashnav').SetVariable("headlinevar", sitetitle);
                }

                // Seitentitel in HTML anpassen
                if (document.getElementById('site-title') != undefined)
                {
                    document.getElementById('site-title').innerHTML = sitetitle;
                }
            }

            // für IE den PNG-Fix einrichten
            addOnLoadCorrectPNG();

            // Focus auf die Seite setzen (funktioniert nicht wirklich)
            //  muss wohl anders gelöst werden (Scrollen erst nach Klick möglich)
            window.focus();

            // Seiten-Titel neusetzen
            document.title = "Spacetale - Das Weltraumhändler-Browserspiel";

            // Banner neuladen
            if (document.getElementById("BannerIFrame") != undefined)
            {
                document.getElementById("BannerIFrame").src = "/Werbung?werbetyp=banner&bereich=portal";
                //document.BannerIFrame.location.reload();
            }

            // Skyscraper neuladen
            if (document.getElementById("SkyscraperIFrame") != undefined)
            {
                document.getElementById("SkyscraperIFrame").src = "/Werbung?werbetyp=skyscraper&bereich=portal";
                //document.SkyscraperIFrame.location.reload();
            }

            versionLink = "?inhalt="+pageName+"&ajax=false";
            if (callingType == 1){
                versionLink += "&id="+callingIdParameter;
            }
            if (document.getElementById("linkHtmlVersion") != undefined)
            {
                document.getElementById("linkHtmlVersion").href = versionLink+"&html=true";
            }

            if (document.getElementById("linkFlashVersion") != undefined)
            {
                document.getElementById("linkFlashVersion").href = versionLink;
            }
      //  }
    //}
}

function enableURLCheck()
{
    disableURLCheck = false;
}


function correctSinglePNG(img) // correctly handle PNG transparency for ONE FILE in Win IE 5.5 or higher.
{
    var imgName = img.src.toUpperCase()
    if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
    {
        // Attribute, Parameter und Styles sammeln und für neues Tag formatieren
        var imgID = (img.id) ? "id='" + img.id + "' " : ""
        var imgClass = (img.className) ? "class='" + img.className + "' " : ""
        var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
        var imgStyle = "display:inline-block;" + img.style.cssText
        var imgAttribs = img.attributes;

        for (var j=0; j<imgAttribs.length; j++)
        {
            var imgAttrib = imgAttribs[j];
            if (imgAttrib.nodeName == "align")
            {
                if (imgAttrib.nodeValue == "left") imgStyle = "float:left;" + imgStyle
                if (imgAttrib.nodeValue == "right") imgStyle = "float:right;" + imgStyle
                break
            }
        }

        // <span>-Tag für die Darstellung von PNG's mittels
        //  MS-DirectX Funktion
        var strNewHTML = "<span " + imgID + imgClass + imgTitle
        strNewHTML += " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
        strNewHTML += "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
        strNewHTML += "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
        img.outerHTML = strNewHTML
    }
}

function addOnLoadCorrectPNG() // fuegt allen .png Bildern ein onLoad hinzu
{
    if (document.all && navigator.userAgent.match("Opera") == null)
    {
        // Alle Bilder (<img>-Tags) der Seite durchgehen
        for(var i=0; i<document.images.length; i++)
        {
            var img = document.images[i]
            var imgName = img.src.toUpperCase()
            if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
            {
                // onLoad-Funktion für PNG-Fix zuweisen
                img.onload = function() {
                    correctSinglePNG(this);
                }
            }
        }
    }
}

function checkIfSkyscraper() {
    // Auflösung > 1152xYYY ?
    if (screen.width >= 1152)
    {
        // Skyscraper-Container vorhanden?
        if (document.getElementById("skyscraper") != undefined)
        {
            // Skyscraper einfuegen
            document.getElementById("skyscraper").innerHTML = "<iframe id=\"SkyscraperIFrame\" scrolling=\"no\" width=\"120\" height=\"600\" border=\"0\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" leftmargin=\"0\" topmargin=\"0\" src=\""+"/Werbung?werbetyp=skyscraper&bereich=portal\" name=\"SkyscraperIFrame\"></iframe>";
        }
    }
}
