function doc_player(doc, subject_o, content_o, base) {
    var orders;
    var self = this;
    var i;
    
    this.sub_ctxs = doc.sub_ctxs;
    this.ajaxmind = doc.ajaxmind;
    this.subject_o = subject_o;
    this.content_o = content_o;
    
    orders = [];
    function walk(sidx) {
	var subject;
	var cidx, i;
	
        orders.push(sidx);
	subject = self.ajaxmind[sidx];
	for(i = 0; i < subject.children.length; i++) {
	    cidx = subject.children[i];
	    child = self.ajaxmind[cidx];
	    child.parent = sidx;
	    walk(cidx);
	}
    }
    for(i = 0; i < this.ajaxmind.length; i++) {
        if(typeof this.ajaxmind[i].parent != "undefined")
	    break;
	walk(i);
    }
    this.orders = orders;
    this.parser = new gindoc_parser(base, base);
}

doc_player.prototype = {
    show_page: function(page) {
        var subject, idx;
	var content;
        if(page >= this.orders.length) {
	    return;
	}
	idx = this.orders[page];
	subject = this.ajaxmind[idx];
	content = this.sub_ctxs[subject.subject];
	content = this.parser.show_msg(content);
	this.content_o.innerHTML = content;
	this.subject_o.innerHTML = subject.subject;
    },
    get_pages: function() {
        return this.orders.length;
    }
};

var current_page = 0;

function keydown_hdlr(evt) {
    switch(evt.keyCode) {
    case 33: // page up
        if(typeof player == "undefined") return;
        current_page = current_page - 1;
	if(current_page < 0)
	    current_page = 0;
	player.show_page(current_page);
	break;
    case 32: // space
    case 34: // page down
        if(typeof player == "undefined") return;
        current_page = current_page + 1;
	if(current_page >= player.get_pages())
	    current_page = player.get_pages() - 1;
	player.show_page(current_page);
	break;
    case 76: // L
        load_doc();
	break;
    };
    //alert(evt.keyCode);
}

function load_doc() {
    var load_doc_dlg;
    
    load_doc_dlg = get_elm("load_doc_dlg");
    dialog(load_doc_dlg);
}

function real_load_doc() {
    var load_doc_dlg;
    var doc_file_name;
    var fn, doc;
    var base;
    
    load_doc_dlg = get_elm("load_doc_dlg");
    doc_file_name = get_elm("doc_file_name");
    fn = doc_file_name.value;
    base = fn.substring(0, fn.lastIndexOf('/'));
    doc = loadFile(fn);
    doc = convertUTF8ToUnicode(doc);
    doc = doc.substring("var _amdoc = ".length, doc.length - 1);
    doc = doc.parseJSON(function(k,v) {return v;});
    set_player(doc, base);
    dialog_close(load_doc_dlg);
    get_elm("view").focus();
}

function set_player(doc, base) {
    var subject_o, content_o;
    
    subject_o = get_elm("subject");
    content_o = get_elm("content");
    player = new doc_player(doc, subject_o, content_o, base);
    current_page = 0;
    player.show_page(current_page);
}

function load() {
    document.addEventListener("keydown", keydown_hdlr, false);
    
    if(_amdoc) {
        set_player(_amdoc, "./");
    }
}
