/* Wiki iframe functionality */ 


function loadFrontPage(hash) {
};

function initFrontPage() {
    //xxx This loads what used to be called 'homepage'
    $("#gameinfo, #room_roster").hide();
    $("#room_roster li").hide();
    $("#meta, #top_players").show();
    $.history.init(loadFrontPage);
    $.get('/frontpage', function(data) {
            $('#dynamic_content').replaceWith(data);
            var count_down = gametimer.get_game_countdown();
            gametimer.reset_countdown(count_down);
            $('a#startlink').click( function(ev) {
                    var title = $('a#startlink').attr('href');
                    title = title.replace("#wiki/", "");
                    loadWikiPage(title);
                    return false;
                });
            });
};

function loadWikiPage(title) {
    $("#top_players, #meta").hide();
    $("#gameinfo, #room_roster").show();
    $("div#dynamic_content").replaceWith('<div id="dynamic_content"><iframe id="wiki"></iframe></div>'); 
    $("iframe#wiki").attr("src", "/wiki/"+title);
    wikiFrame(title);
};

function wikiFrame(title){
    var wikiframe = $("iframe#wiki");
    //$.history.init(setWikiPage);
    $(wikiframe[0].contentWindow.document.body).click(function(ev){
        var href = $(ev.target).attr("href");
        if (!href) return;
        var hreflist = href.split("/");
        var target = hreflist[hreflist.length-1];
        $.history.load(target);
        return false;
    });
    /* When the iframe Wiki content is fully loaded, 
    set the users presence, which is click count*/
    wikiframe.load(set_presence);
};



/* Multi User Chat functionality */

function sendChat(ev){
    if (ev.keyCode != 13) return; /* if not 'Enter' pressed */
    var message = $(this).val();
    if (message=="" || message=="\n"){
        $(this).val(""); /* Clear the textarea */
        return;
    }
    $(this).val(""); /* Clear the textarea */
    send_message(message);
    return false; 
};

set_presence = function() {
    var x = Strophe.xmlElement("x", [["xmlns", Strophe.NS.MUC]]);
    var chat_press = $pres({'from':ATTACH_JID,
                            'to':MUC_ROOM}).c('x',{'xmlns':Strophe.NS.MUC});
    var game_status = WINNER+"@@"+CLICKS;
    chat_press.nodeTree.appendChild(Strophe.xmlElement('status', game_status));
    connection.send(chat_press.tree());
};

win_notify = function(winner){
    $("#show_winner").remove();
    $.ajax({
        type:"GET",
        dataType:"html",
        cache:false,
	    url:'/stats/win_notify', 
	    success: function(data) {
            $("#content").append($("<div>").attr("id", "show_winner").addClass("jqmWindow"));
            $("#player_"+winner).html(data);
            $("#show_winner").jqm({ajax:"/stats/winner", trigger:"#show_winner_link"});
	    }
    });
}

send_message = function(text) {
    var msg = $build('message', {to:MUC_ROOM, from:ATTACH_JID, type:'groupchat', 'xmlns':Strophe.NS.CLIENT});
    msg.c('body').t(text);
    connection.send(msg.tree());
    return true;
};

function onConnecter(stat) {
    /*if (stat == Strophe.Status.DISCONNECTED) {log('Disconnected.'); }*/
    return true;
};

onChatMessage = function(msg) {
    $("#chat_stream").css("border", "2px solid #CCC");
    $("#chat_with").hide();
    var from = msg.getAttribute('from');
    var elems = msg.getElementsByTagName('body');
    var user = from.split('/')[1];
    var chat = Strophe.getText(elems[0]);
    var cnt = "<b>"+user+": </b>"+chat;
    var new_line = $("<li>").html(cnt);
    $('div#chat_stream > ul').append(new_line);
    var chat_stream = $("#chat_stream");
    chat_stream.attr({scrollTop: chat_stream.attr("scrollHeight")});
    return true;
};


onPlayerPresence = function(msg) {
    //FIXME Clean up player_listng <li> manipulation.
    var from = msg.getAttribute('from');
    var type = msg.getAttribute('type');
    var player_nick = from.split('/')[1];
    var player_listing = $("#player_"+player_nick);
    if (player_listing.length) { /* if the player exists */
        if (type=='unavailable') {
            player_listing.remove();
        } else {
            var stat = Strophe.getText(msg.getElementsByTagName('status')[0]);
            var userinfo = stat.split("@@") /* form: WINNER@@CLICKS*/
            var windata = userinfo[0];
            if (windata != ""){
		winner = windata.split("::")[0]
            } else {
                winner = ""; 
            }
            var clicks = userinfo[1];
            var win_notify_elem = $("#win_notify"); /* detect if winner is already shown*/
            if (winner != "" && !win_notify_elem.length){
                win_notify(winner);
            } 
            if (winner != player_nick){ /* dont update the winner's stats */
                player_listing.text(player_nick + ' ' + clicks);
                player_listing.show();
            }
        }
    } else { /* player is new, does not exist */
        if (stat == null) {
            stat = '';
            /*return true*/
        }
        var player_id = "player_"+player_nick;
        var player = $("<li>").attr("id", player_id).text(player_nick+" "+stat);
        if (player_nick == NICK) {
            /* Make which player you are clear*/
            player.css("list-style-type", "circle");
            $('div#room_roster > ul').prepend(player);
        } else {
            $('div#room_roster > ul').append(player);
        }
    }
    return true;
};


GameTimer = function() {
    var game_countdown = 0;
    var start_page = '';
    var start_link = '';
    var end_page = '';
    var end_link = '';
    var game_length = 200;
    var game_on = true;
    var timer_running = false;

    function set_countdown(countdown) {
        game_countdown = countdown;
        if (game_countdown < 0) {
            game_countdown = -game_countdown;
            game_on = false;
            $('div#newgamebox').show();
            $('div#currentgamebox').hide();
            $('.timeremaining').hide();
            $('.timetonextgame').show();
        } else {
            $('div#newgamebox').hide();
            $('div#currentgamebox').show();
            $('.timeremaining').show();
            $('.timetonextgame').hide();
            set_game_data();
        }
        timer_running = true;
    };


    function store_game_data(sp, sl, ep, el) {
        start_page = sp;
        start_link = sl;
        end_page = ep;
        end_link = el;
    };

    function get_game_data() {
        $.ajax({
            type:"GET",
            dataType:"json",
            cache:false,
	    url:'get_game_data', 
	    success: function(data) {
		    //alert("get_game_data " + data.game_countdown);
		    if (data.game_countdown > 0) {
			store_game_data(data.start_page, data.start_link, data.end_page, data.end_link);
		    }
		    game_length = data.game_length;
		    set_countdown(data.game_countdown);
	    }
        });
    };


    function set_game_data() {
        $('a#startlink').attr('href', "#wiki/"+start_link);
        $('span#start').text(start_page);
        $('.endpage').text(end_page);
        var endpagelink = "http://en.wikipedia.org/wiki/"+end_link;
        $('p#endpagelink > a').attr('href', endpagelink);
    };

    function start_game() {
        game_on = true;
        initFrontPage();
        //showFrontPage();
        get_game_data();
        set_game_data();
    };

    function end_game() {
        game_on = false;
        initFrontPage();
        //showFrontPage();
        get_game_data();
        set_game_data();
    };

    return {
        start: function() {
            get_game_data();
        },

        tick: function() {
            if (!timer_running) {
                return;
            }
            game_countdown -= 1;
            if (game_countdown <= 0) {
                if (game_on) {
                    end_game();
                } else {
                    start_game();
                }
            } else {
                $('.game_countdown').text(game_countdown);
            }
        },

        play: function() {


        },
        get_game_countdown: function() {
            return game_countdown;
        },
        reset_countdown: function(game_countdown) {
	    //alert("reset_countdown timer_running=>" + timer_running);
            set_countdown(game_countdown);
            return;
        }
    }
};


setMaincontent = function() {

}

$(document).ready(function(){

    initFrontPage();
    //$("#homelink").click(initFrontPage);

    // Connect then do Session Attachment
    connection = new Strophe.Connection(BOSH_SERVICE);
    connection.attach(ATTACH_JID, ATTACH_SID, ATTACH_RID, onConnecter);
    // XMPP event handlers
    connection.addHandler(onChatMessage, null, 'message', 'groupchat', null,  null);
    connection.addHandler(onPlayerPresence, Strophe.NS.MUC+'#user', "presence", null, null,  null);
    
    //Send precense to MUC room, which essentially 'logs' you into the room
    var pres = $pres({from:ATTACH_JID , to:MUC_ROOM+NICK}).c('x',{'xmlns':Strophe.NS.MUC}).tree();
    connection.send(pres);

    //Set MUC room specific handlers
    $("#chat").keydown(sendChat);
    //Modal window that shows winner
    gametimer = GameTimer();
    gametimer.start();
    setInterval(gametimer.tick, 1000);

    $(window).unload(function(){ connection.disconnect(); });
});
