
window.pagingOffset = 0;
window.mustShowPageBackButton = false;
window.hsGameType = 0;
window.highscores = new Array("highscore_daily", "highscore_weekly", "highscore_monthly", "highscore_alltime");

$(document).ready(function() {

    $('#logininfopanel a.lif_chpw').click(function (e) {
        e.preventDefault();
        // load the modalwin form using ajax
        $.get("/change_password.php", function(data){
            // create a modal dialog with the data
            $(data).modal({
                closeHTML: "<a href='#' title='Close' class='modalCloseX'><span>x</span></a>", // selber bauen, sonst hat der link keine Hand
                position: ["20%",],
                overlayId: 'modalwin-overlay',
                containerId: 'modalwin-container',
                containerCss: {width: '500px'}, // muss angegeben werden, sonst ist Modalfenster 0px breit
                dataId: 'simplemodal-data',
                onOpen: modalwin.open,
                onShow: modalwin.showChangePasswordDialog,
                onClose: modalwin.close
            });
        });
    });

    $('#logininfopanel .request_pw').click(function (e) {
        e.preventDefault();
        //Inhalt des Modalfensters laden
        $.get("/request_password.php", function(data) {
            //Modalfenster mit den Inhaltsdaten erzeugen
            $(data).modal({
                closeHTML: "<a href='#' title='Close' class='modalCloseX'><span>x</span></a>", // selber bauen, sonst hat der link keine Hand
                position: ["20%",],
                overlayId: 'modalwin-overlay',
                containerId: 'modalwin-container',
                containerCss: {width: '500px'}, // muss angegeben werden, sonst ist Modalfenster 0px breit
                dataId: 'simplemodal-data',
                onOpen: modalwin.open,
                onShow: modalwin.showRequestPasswordDialog,
                onClose: modalwin.close
            });
        });
    });

    function findValueCallback(event, data, formatted) {
        if (data){
            $("#highscoresearch_btn").show();
            alert(formatted);
        } else {
            alert("hide");
            $("#highscoresearch #highscoresearch_btn").hide();
        }
    //alert(data);
    // $("#hs_search").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");
    }

    updateHighscoreClickable();
    updateReplaysClickable();

    $("#partnerbox img").tooltip({
        track: true,
        showURL: false
    } );
    $('#profiletoolbar li').tooltip({
        track: true,
        showURL: false
    } );
    $(".mib_player").tooltip({
        track: true,
        showURL: false
    });
    $("#profiletrophy a").tooltip({
        track: true,
        showURL: false
    } );
    $("#logininfopanel a").tooltip({
        track: true,
        showURL: false
    } );
    $(".withtooltip").tooltip({
        track: true,
        showURL: false
    } );
    $("table.premium_partner td").tooltip({
        track: true,
        showURL: false
    } );

    $("map area")
    .mouseover(function(e){
        var mapobj=$($(this).parent()[0]); $("#img_" + mapobj.attr("id")).css("cursor", "help");
    })
    .mouseout(function(e){
        var mapobj=$($(this).parent()[0]); $("#img_" + mapobj.attr("id")).css("cursor", "default");
    })
    .tooltip({
        track: true,
        showURL: false
    } );

    $("#hrlogo").click( function (e){
        e.preventDefault();
        window.location.href = "/";
    });

    $("div.matchinfobox span.mib_player").click( function(e){
        e.preventDefault();
        window.location.href = "/profile.php?p=" + $(this).attr("playerid");
    });

    $("div.watchonlinebutton").click(function(e){
        e.preventDefault();
        if ($(this).attr("fgid") != "undefined")
            window.location.href = "/video.php?fgid=" + $(this).attr("fgid");
    }).tooltip({ 
        track: true
    });


    $("div.downloadreplaybutton").click(function(e){
        e.preventDefault();
        if (typeof $(this).attr("fgid") != "undefined")
            location.href = "/replays/" + $(this).attr("fgid") + ".hrg";
    }).tooltip({ 
        track: true
    });

    $("div.downloadreplaybuttonmp4").click(function(e){
        e.preventDefault();
        if (typeof $(this).attr("fgid") != "undefined") {
            //location.href = "/flash/" + $(this).attr("fgid") + ".mp4";
            location.href = "/mp4download.php?fgid=" + $(this).attr("fgid");
        }
    }).tooltip({ 
        track: true
    });

    // Hole Daten für den Vergleich von Playerstatistiken
    $("#stats_search_btn").click(function(e){
        e.preventDefault();
        var pname = $("#hs_search_txt").val();
        if (pname){
            $("div.compare div.ajaxloading").show();
            $.getJSON("/webrpc/playerstats.php?n=" + pname + getRandomParam(), function (data, textStatus) {
                if (textStatus == "success" && data){
                    $("#statcmp_ps").html(data.creationdate);
                    $("#statcmp_pt").html(data.playtimehrs);
                    $("#statcmp_mc").html(parseInt(data.won)+parseInt(data.loss) );
                    $("#statcmp_wg").html(data.won);
                    $("#statcmp_lg").html(data.loss);
                    $("#statcmp_ku").html(data.killedunits);
                    $("#statcmp_lu").html(data.lossunits);
                    $("#statcmp_kb").html(data.killedbuildings);
                    $("#statcmp_lb").html(data.lossbuildings);
                    $("#statcmp_ur").html(data.unitRatio);
                    $("#statcmp_br").html(data.buildingRatio);
                    $("#statcmp_wr").html(data.winRatio);
                }
                $("div.compare div.ajaxloading").hide();
            });
        }
    });


    // Hole Daten für die Highscore des gewählten Players
    $("#hs_search_form").submit( function(e){
        updateHighscoreContentFnc(e, $("#hs_search_txt").val(), window.hsGameType );
        return false;
    } );
    // Das hier kann für ajax-loading der highscores (de)aktiviert werden.
    $("#hs_paging_next").click( function(e){ 
        window.pagingOffset++; updateHighscoreContentFnc(e,"", window.hsGameType);
    } );
    $("#hs_paging_prev").click( function(e){ 
        window.pagingOffset--; updateHighscoreContentFnc(e,"", window.hsGameType);
    } );
    $("#hs_paging_start").click( function(e){ 
        window.pagingOffset=0; updateHighscoreContentFnc(e,"", window.hsGameType);
    } );


    // Autocomplete für Spieler
    $("#hs_search_txt").autocomplete("/webrpc/playernames.php", {
        minChars: 1,
        max: 15,
        autoFill: false,
        mustMatch: true,
        matchContains: true,
        scrollHeight: 220,
        width: 260
    });

    // Buddyliste anzeigen
    $("a.btn_buddylist").click(function(e){
        e.preventDefault();
        //var height = $('div.buddylist').height();
        //var width = $('div.buddylist').width();
        var leftVal= (findPosX(this, 150)) + "px";
        var topVal= (findPosY(this)+15) + "px";
        
        $("div.buddylist").css({
            left:leftVal,
            top:topVal
        }).toggle("slow");
    });

    // Buddylist schliessen
    $("a.btn_closebuddylist").click( closeBuddyListFnc );

    // Auf Buddylist Eintrag klicken
    $("td.buddylist_entry").click(function(e){
        e.preventDefault();
        var bname = $(this).text();
        $("input#hs_search_txt").val(bname);
        closeBuddyListFnc(e);
    });


    $('.moveable_trophy').tooltip({
        bodyHandler: function() {
            tt = "<b>" + $(this).attr("trophyname") + "</b><br>";
            tt += $(this).attr("trophydesc");
            return tt;
        },
        showURL: false,
        track: true
    });


    $("#hs_gametype img").click( function(e){
        e.preventDefault();
        window.hsGameType = $(this).attr("gametype");
        updateHighscoreContentFnc(e, $("#hs_search_txt").val(), window.hsGameType);
    });

    //PrettyPhoto Screenshots
    if(typeof $("html").prettyPhoto == 'function') {
        $("a[rel^='prettyPhoto']").prettyPhoto({
            theme: 'hiverise',
            opacity: 0.55
        });
    }

    // Submenu - Download
    var timeout_download = null;

    $("#nav-download").hover( function() {
        if(timeout_download) window.clearTimeout(timeout_download);
        $(".sub_navigation.download").slideDown("fast");
    }, function() {
        timeout_download = window.setTimeout("closeSubnavi('.sub_navigation.download')", 200);
    });

    $(".sub_navigation.download").hover( function() {
        if(timeout_download) window.clearTimeout(timeout_download);
    }, function () {
        timeout_download = window.setTimeout("closeSubnavi('.sub_navigation.download')", 200);
    });

    // Submenu - Game
    var timeout_game = null;

    $("#nav-game").hover( function() {
        if(timeout_game) window.clearTimeout(timeout_game);
        $(".sub_navigation.game").slideDown("fast");
    }, function() {
        timeout_game = window.setTimeout("closeSubnavi('.sub_navigation.game')", 200);
    });

    $(".sub_navigation.game").hover( function() {
        if(timeout_game) window.clearTimeout(timeout_game);
    }, function () {
        timeout_game = window.setTimeout("closeSubnavi('.sub_navigation.game')", 200);
    });

    // Submenu - Help
    var timeout_help = null;

    $("#nav-help").hover( function() {
        if(timeout_help) window.clearTimeout(timeout_help);
        $(".sub_navigation.help").slideDown("fast");
    }, function() {
        timeout_help = window.setTimeout("closeSubnavi('.sub_navigation.help')", 200);
    });

    $(".sub_navigation.help").hover( function() {
        if(timeout_help) window.clearTimeout(timeout_help);
    }, function () {
        timeout_help = window.setTimeout("closeSubnavi('.sub_navigation.help')", 200);
    });

    // Submenu - Game
    var timeout_info = null;

    $("#nav-info").hover( function() {
        if(timeout_info) window.clearTimeout(timeout_info);
        $(".sub_navigation.info").slideDown("fast");
    }, function() {
        timeout_info = window.setTimeout("closeSubnavi('.sub_navigation.info')", 200);
    });

    $(".sub_navigation.info").hover( function() {
        if(timeout_info) window.clearTimeout(timeout_info);
    }, function () {
        timeout_info = window.setTimeout("closeSubnavi('.sub_navigation.info')", 200);
    });

    if(typeof window.initializePage == 'function')
        initializePage();
});


function closeSubnavi(jQuerySelector)
{
    $(jQuerySelector).slideUp("fast");
}

var updateHighscoreContentFnc = function(e, pname, gtype){
    e.preventDefault();
    window.mustShowPageBackButton = false;
    
    if (window.pagingOffset < 0)
        window.pagingOffset = 0;

    //alert(window.pagingOffset);
    
    //if (pname || offset >= 0){
    for (var i=1; i<=window.highscores.length; i++){
        $("#" + window.highscores[i] + " div.ajaxloading").show();

        $.getJSON("/webrpc/highscore_rpc.php?d=" + i + "&o=" + window.pagingOffset + "&p=" + pname + "&gt=" + gtype + getRandomParam(), function (data, textStatus) {
            if (textStatus == "success" && data){
                $("#" + data.tname).html(data.html);
            
                $("#" + data.tname + " div.ajaxloading").hide();

                updateHighscoreClickable();

                //alert(data.firstpos);

                if ( data.firstpos > 1)
                    window.mustShowPageBackButton = true;

                if (window.pagingOffset >  0 || window.mustShowPageBackButton){
                    //alert("show " + window.mustShowPageBackButton + " " + data.firstpos);
                    $("#hs_paging_start").show();
                    $("#hs_paging_prev").show();
                }
                else{
                    $("#hs_paging_start").hide();
                    $("#hs_paging_prev").hide();
                }
            }
        });
    }
//}
};


function getRandomParam(){
    return "&__s=" + String((new Date()).getTime()).replace(/\D/gi,'');
}


function updateReplaysClickable(){
    $("#bestmatches tr, #replays tr").click( function (e){ 
        e.preventDefault(); setMatchInfo($(this));
        $("#bestmatches tr, #replays tr").removeClass("selectedRow");
        $(this).addClass("selectedRow");
    } ).tooltip();
    $("#bestmatches tr, #replays tr").hover(/*over*/function (){ 
        $(this).addClass("highlightRow")
    },
    /*out*/function (){
        $(this).removeClass("highlightRow")
    });
}


function updateHighscoreClickable(){
    $("tr.highscoreentry").click( function (e){
        e.preventDefault();
        window.location.href = "/profile.php?p=" + $(this).attr("playerid");
    });
    
    $("tr.highscoreentry").hover(/*over*/function (){ 
        $(this).addClass("highlightRow")
    },
    /*out*/function (){
        $(this).removeClass("highlightRow")
    });
}


var closeBuddyListFnc = function(e){
    e.preventDefault();
    $("div.buddylist").hide(); //.fadeOut(500);
}


function setMatchInfo(row){

    // var parentid = row.parent().parent().attr("id");
    //$("#matchinfobox div.ajaxloading").css("display", "block");
    $("#matchinfobox div.ajaxloading").show();
    $.getJSON("/webrpc/matchinfo.php?fgid=" + row.attr("fgid") + getRandomParam(), function (data, textStatus) {
        // data will be a jsonObj
        // textStatus will be one of the following values:
        //   "timeout","error","notmodified","success","parsererror"
        // this; // the options for this ajax request

        if (textStatus == "success" && data){
            $("#mib_positionmark").css({
                background: "url('" + data.gtImg + "') 0 0 no-repeat"
            });
            
            $("#mib_player").text(data.name);
            $("#mib_player").attr("playerid", row.attr("playerid"));
            $("#mib_time").text(data.date);
            $("#mib_stats #mib_stats_ku").text(data.killedunits);
            $("#mib_stats #mib_stats_kb").text(data.killedbuildings);
            $("#mib_stats #mib_stats_lu").text(data.lossunits);
            $("#mib_stats #mib_stats_lb").text(data.lossbuildings);
            $("#mib_stats #mib_stats_ms").text(data.minutessurvived);

            $("#mib_stats #mib_stats_tr").html(data.imgHtml);
            $("#mib_stats #mib_coins").text(data.receivedCoins);
            $("#mib_stats #mib_points").text(data.points);

            //Checken ob das hrg-Replay existiert, wenn ja, dl-button anzeigen
            $("#matchinfobox div.downloadreplaybutton").hide();
            if (parseInt(data.replaystatus) >= 1 ) {
                $("#matchinfobox div.downloadreplaybutton").show();
            }

            //Checken ob das flv-Replay existiert, wenn ja, dl-button anzeigen
            $("#matchinfobox div.watchonlinebutton").hide();
            $("#matchinfobox div.downloadreplaybuttonmp4").hide();
            if (parseInt(data.replaystatus) >= 3 ) {
                $("#matchinfobox div.watchonlinebutton").show();
                $("#matchinfobox div.downloadreplaybuttonmp4").show();
            }
            $("#matchinfobox div.downloadreplaybutton").attr("fgid", row.attr("fgid"));
            $("#matchinfobox div.downloadreplaybuttonmp4").attr("fgid", row.attr("fgid"));
            $("#matchinfobox div.watchonlinebutton").attr("fgid", row.attr("fgid"));

            $("#matchinfobox div.ajaxloading").hide();
        }
    // else alert(textStatus);
    })
};

    
function wopen(url, wname){
    paywin = window.open(url, wname, "width=700,height=650,left=100,top=100,scrollbars=yes");
    paywin.focus();
    return false;
}

function buddyAction(action,buddyid){
    $("#addbuddybutton div.ajaxloading").show();
    $("#addbuddybutton img#addbuddybutton_btn").hide();

    $.getJSON("/webrpc/buddy.php?a=" + action + "&b=" + buddyid + getRandomParam(), function (data, textStatus){
        if (textStatus == "success" && data){
            if(data.success == "true")
                $("#addbuddybutton").addClass("successtext");
            else
                $("#addbuddybutton").addClass("errortext");
            
            $("#addbuddybutton").text(data.msg);
        }
        $("#addbuddybutton .ajaxloading").hide();

    });
}

var replayPos = 0;
function moveReplays(dir, p)
{
    $("#replays_wrap div.ajaxloading").show();
    if (dir != 0)
        replayPos += dir;
    else
        replayPos = 0;

    if (replayPos == 0){
        $("#pager a#page_prev").hide();
        $("#pager a#page_first").hide();
    }
    else{
        $("#pager a#page_prev").show();
        $("#pager a#page_first").show();
    }
    
    $("#pager #replay_page").text(replayPos+1);
    $.getJSON("/webrpc/replays.php?d=" + replayPos + "&p=" + p + getRandomParam(), function (data, textStatus){
        if (textStatus == "success" && data){
            if (data.count < data.perpage)
                $("#page_next").hide();
            else
                $("#page_next").show();

            $("#replays_wrap").html(data.html);
            // Muss neu zugewiesen werden, sind ja neue daten im dom
            updateReplaysClickable();
        }
        else{
            $("#replay_page").text(replayPos-1);
        }
        
        $("#replays_wrap div.ajaxloading").hide();
    });
}

/**
 * If onclick returns false, the browser never even looks at the href attribute,
 * and so it is not followed.
 * So return true.
 */
function trackDownload()
{
    //alert("track");
    setTimeout('setTrackDownloadPage()', 500)
    return true;
}
function setTrackDownloadPage(){
    // alert(parent.frames['dl_iframe'].src);
    parent.frames['dl_iframe'].location.href =  "/includes/ga_track_download.php";
    // alert(parent.frames['dl_iframe'].src);
}



function findPosX(obj, maxWidth) {
    var curleft = 0;
    if(obj.offsetParent) {
        while(obj.offsetParent) {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if(obj.x)
        curleft = obj.x;

    if (curleft + maxWidth > $(document).width())
        return curleft - maxWidth;

    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if(obj.offsetParent) {
        while(obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if(obj.y)
        curtop = obj.y;
    return curtop;
}


function getAnchorFromURL() {
    var myFile = document.location.toString();
    if (myFile.match('#')) // the URL contains an anchor
        return myAnchor = '#' + myFile.split('#')[1];
    return "";
}

// "leere" Übersetzungsmethode,
// damit die Methode selbst existiert
// und keine Javascript-Fehler auftauchen
function tr(text) {
    return text;
}