
var min_latency = 300;

var show_info = false;

/*
 * This is where everything starts when the page is loaded
 */
$( function() {
    $.historyInit(pageload);

    $.info = null;
    
    if ((typeof init != "undefined") && (!init.all)) {
        init.all = function() {
            var body = $("body");
            if (!body.attr("augmented")) {
                body.append("<div id='info'></div>");
                $(".action").append(" <span>&raquo</span>");
                body.attr("augmented", "true");
            }
    
            if (show_info) {
                var infoDiv = $("#info");
                infoDiv.setTemplate("<div>Latency: {$T.latency}ms</div>"
                                + "<div>Host: {$T.host}</div>"
                                + "<div>ID: {$T.id}</div>"
                                + "{#if $T.email}<div>EMail Claimed: {$T.email}</div>{#/if}"
                                + "{#if $T.openid_claimed}<div>OpenID Claimed: {$T.openid_claimed}</div>{#/if}"
                                + "{#if $T.aim_claimed}<div>AIM ID Claimed: {$T.aim_claimed}</div>{#/if}"
                                + "{#if $T.lj_claimed}<div>LiveJournal ID Claimed: {$T.lj_claimed}</div>{#/if}"
                                + "{#if $T.id_verified}<div>ID Verified: {$T.id_verified}</div>{#/if}"
                                + "{#if $T.active_playground}<div>Active Exhibit: {$T.active_playground}</div>{#/if}");
                infoDiv.processTemplate($.info);
                infoDiv.click( function() {
                    $.info = null;
                    // $.cookie('id',null, { path: '/' });
                    $.cookie('JSESSIONID', null, { path: '/' });
                    $.cookie('JSESSIONID', null, { path: '/citeline' });
                    $.cookie('apg', null, { path: '/' });
                    $.cookie('host', null, { path :'/' });
                    $("#info").fadeOut(800, function() {
                        $("#info").html("");
                    });
                }).fadeIn(80);
            }
        };
    }

    $("a[@rel='history']").click( function() {
        var hash = this.href;
        hash = hash.replace(/^.*#/, '');
        $.historyLoad(hash);
        return false;
    });
});

/*
 * This function is called: 1. after calling $.historyInit(); 2. after calling
 * $.historyLoad(); 3. after clicking the "Back" button of the browser NOTE:
 * hash does NOT contain the first # character!
 */
function pageload(hash) {
    hash = hash.split("?")[0]; // the hash could contain further parameters
    if ($.info == null) {
        timer.start(); // time how long it takes to fetch "info"
        $.ajax( {
            type: "get",
            url: "info",
            error: error,
            success: function(data) {
                $.info = $.secureEvalJSON(data);
                $.info.latency = timer.since();
                $.info.slow = ($.info.latency > min_latency);
                var host = $.cookie('host');
                if (host != $.info.host) {
                    $.cookie('host', $.info.host, { path: '/' });
                }
                load(hash);
            }
        });
    } else {
        load(hash);
    }
}

var current_pane;

function load(pane) {
    if (!pane) {
        if (authenticated()) {
            prepare("authenticated");
        } else {
            prepare("anonymous");
        }
    } else {
        prepare(pane);
    }
}

function prepare(pane, context) {
    if (typeof init != "undefined") { 
        if (init["all"]) {
            init["all"]();
        }
        
        if (init[pane]) {
            init[pane](context);
        } else {
            reveal(pane);
        }
    }
}

function reveal(pane) {
    var callback = function() {
        current_pane = $("." + pane).fadeIn(50);
    }
    if (current_pane) {
        current_pane.fadeOut(20, callback);
    } else {
        callback();
    }
}

function authenticated() {
    return ($.info && (typeof $.info == "object") && $.info.id_verified);
}

function error(XMLHttpRequest, textStatus, errorThrown) {
    var dialog = $("#error");
    var text = XMLHttpRequest.responseText;
    var msg = dialog.find(".error_msg");
    dialog.find("a[@name='toggle']").click( function() {
        msg.show();
        $(this).hide();
    });
    msg.html(text);
    showDialog(dialog);
    reportError("Error", text);
}

function reportError(title, msg) {
    $.post("error", {
        "title": title,
        "msg": msg
    }, function() {
        // nothing to do here
    });
}

function redirect(url) {
    window.location.href = url;
}

function log(msg) {
    if (console && console.log) {
        console.log(msg);
    }
}

var timer = {
    time: 0,
    now: function(){ 
        return (new Date()).getTime(); 
    },
    start: function(){ 
        this.time = this.now(); 
    },
    since: function(){ 
        return this.now() - this.time; 
    }
};

var currentDrawer;

function showDrawer(drawer) {
    if (currentDrawer && currentDrawer != drawer) {
        currentDrawer.slideUp("fast");
    }
    currentDrawer = drawer.slideDown("fast");
    return currentDrawer;
}

var currentDialog;

function showDialog(dialog) {
    var id = dialog[0].id;
    if (init[id]) init[id]();
    revealDialog(dialog);    
}

function revealDialog(dialog) {
    if (currentDialog) {
        currentDialog.jqmHide();
    }
    currentDialog = dialog.jqm().jqmShow();
}

function hideDialog() {
    if (currentDialog) {
        currentDialog.jqmHide();
        currentDialog = null;
    }
}

function waitDialog(msg) {
    var dialog = $("#waiting");
    dialog.find("span[@name='msg']").html(msg);
    showDialog(dialog);
}

function getParameters() {
    var query = document.location.toString().split("?")[1];
    var p = {};
    if (query) {
        var tokens = query.split("&");
        for (var i = 0; i < tokens.length; i++) {
            var t = tokens[i].split("=");
            p[t[0]] = t[1];
        }
    }
    return p;
}

function formatTime(millis) {
    var sec = 1000;
    var min = 60 * sec;
    var hour = 60 * min;
    var day = 24 * hour;
    var week = 7 * day;
    var month = 30 * day;
    var year = 365 * day;

    if (millis > year) {
        var n = millis / year;
        var string = n.toFixed(0) + " years";
    } else if (millis > month) {
        var n = (millis / month);
        var string = n.toFixed(0) + " months";
    } else if (millis > week) {
        var n = (millis / weeks);
        var string = n.toFixed(0) + " weeks";
    } else if (millis > day) {
        var n = (millis / day);
        var string = n.toFixed(0) + " days";
    } else if (millis > hour) {
        var n = (millis / hour);
        var string = n.toFixed(0) + " hours";
    } else if (millis > min) {
        var n = (millis / min);
        var string = n.toFixed(0) + " min";
    } else {
        var n = (millis / sec);
        var string = n.toFixed(0) + " sec";
    }
    
    return string;
}