

ENCODING = 'iso-8859-1'
base_url = 'http://www.inghist.nl/retroboeken/nnbw';
defaultPane = 'transcriptiePane'; 
default_size = 2;

var valid_sources = {
'1':'',
'2':'',
'3':'',
'4':'',
'5':'',
'6':'',
'7':'',
'8':'',
'9':'',
'10':''
};

function first_source() {
    return '1';
}
function first_page() {
    return 0
}

function the_page() {
    //return the current page index
    return Number(current_state.page);
}

function the_view() {
    //which view (i.e. which tab on the right hand side) is selected?

    return dojo.widget.byId('content_box_main').selectedChild
}
function parse_hash() {
    /* try to get the source and pagenumber from the hashvalue in the url.
    if this fails, return the first_source() and first_page() */
    if (window.location.hash != '') {
        //the hash value is expected to be something of the form #2:345
        //(source:page)
        var arr = window.location.hash.split(':');
        var source_part = arr[0].substr(1); //the source is the 
        var page_part = arr[1];
        return [source_part, page_part]
    } else {
        return [first_source(), first_page()]
    }
}


var last_pages = {

    '1':807,


    '2':781,


    '3':772,


    '4':761,


    '5':601,


    '6':666,


    '7':684,


    '8':666,


    '9':673,


    '10':632

}

function last_page() {
    //return the index of the last page
    return last_pages[the_source()];
}

function prev_page() {
    return Math.max(the_page() - 1, first_page());
}
function next_page() {
    return Math.min(the_page() + 1, last_page());
} 

/* States for adding to the history stack make back and forward buttons owrk */
var State = function(source, page, size, reload){
    this.source = source;
    this.page = page;
    if (size == undefined){
        size =  the_size() /*  */
    }
    if (reload == undefined){
        reload = 1;
    }
    this.size = size; 

    //add a hash value to the url
    if (reload){
        this.changeUrl = source + ':' + page;
    }
    this.go = function(){
        redrawPanes(this.page, this.source);
    }
    this.back =  function() { 
        this.go();
    }
    this.forward =  function() { 
        this.go();
    }
}; 

function the_source() {
    //return the index of the current source 
    return current_state.source;
}

function the_size() {
    return current_state.size
}

function fill_accessors() {
/* set the content of each of the accessors */

    var pane = dojo.widget.byId('accessor_index');
    if (pane) {
        query_string = dojo.io.argsFromMap(
            { 'page' : the_page(),
              'source': the_source(),
              'id': 'accessor_index'
            });
        url = base_url + '/accessor_index?'+ query_string;
        pane.setUrl(url);
    }


    var pane = dojo.widget.byId('index1');
    if (pane) {
        query_string = dojo.io.argsFromMap(
            { 'page' : the_page(),
              'source': the_source(),
              'id': 'index1'
            });
        url = base_url + '/index1?'+ query_string;
        pane.setUrl(url);
    }


    var pane = dojo.widget.byId('toc');
    if (pane) {
        query_string = dojo.io.argsFromMap(
            { 'page' : the_page(),
              'source': the_source(),
              'id': 'toc'
            });
        url = base_url + '/toc?'+ query_string;
        pane.setUrl(url);
    }


    var pane = dojo.widget.byId('thumbnails');
    if (pane) {
        query_string = dojo.io.argsFromMap(
            { 'page' : the_page(),
              'source': the_source(),
              'id': 'thumbnails'
            });
        url = base_url + '/thumbnails?'+ query_string;
        pane.setUrl(url);
    }


    var pane = dojo.widget.byId('searchText');
    if (pane) {
        query_string = dojo.io.argsFromMap(
            { 'page' : the_page(),
              'source': the_source(),
              'id': 'searchText'
            });
        url = base_url + '/searchText?'+ query_string;
        pane.setUrl(url);
    }
 
}

function showPage(page, source, size, highlight) {
    /*
    show the page with index 'page'
    from the source with id 'source'
    the size is given by size
    highlight is a list of strings 
    */
    if (page == undefined) { page = the_page() }
    if (source == undefined) { source = the_source()}
    if (size == undefined) { size = the_size() }

    if (size == 'larger') {
         //6 is the absolute maximum size
         size = Math.min(Number(the_size()) + 1,6);
    }
    if (size == 'smaller') {
        //0 is the absolute minium size
        size = Math.max(the_size() - 1, 0);
    }

    if (highlight == undefined) {
        highlight = '';
    }

    //move to the requested page
    
    if (!request_page) {
        //if the pagenumber where we are comes from the request, setting a new state will already force a reload, and therefore we do not need to redraw the panes (thus preventing some confusing reloading behavior)
        redrawPanes(page, source, size, highlight, force_refresh=0);
    } else {
        redrawPanes(page, source, size, highlight, force_refresh=0);
    }

    /*add a state to the history (only if anything really changed) 
    (this is used for bookmarking and backbuttons)
    */
    if (source != the_source() || page != the_page() || size != the_size()){
        new_state = new State(source=source, page=page, size=size);
        dojo.undo.browser.addToHistory(new_state);
        current_state = new_state;
    } 


    return false;
}


redrawPanes = function(page, source, size,highlight, force_refresh) {
    if (!(source in valid_sources)) {
        source = first_source();
    }

    //show the right values in the navigation pane
    if (the_source() != source ||  force_refresh) {
        //this is a new source, we need to load the corresponding page numbers in the navigation Pane
        query_string = dojo.io.argsFromMap(
            { 'page' : page,
            'source': source
        })
        url =  'page_view_navigation?' + query_string;
        var navigationPane = dojo.widget.byId('navigationPane');
        navigationPane.setUrl(url);
    } else {
        var selectPage = self.document.getElementById('selectPage');
        selectPage.value = page;
        var selectSource = self.document.getElementById('selectSource');
        if (selectSource) {
            selectSource.value = source;
        }
    } 

    if (size == undefined) { size = the_size()};

    query_string = dojo.io.argsFromMap(
        { 'page' : page,
          'source': source,
          'size': size,
          'highlight': highlight
        })

    //the views get assigned new urls, so they will show the right page
    
        var pane = dojo.widget.byId('homePane');

        if (pane) {
            if (pane.widgetId != 'homePane') {
                pane.setUrl(base_url + '/page_view_home?'+ query_string);
            } else { //the homePane of course does not change (but needs to be set at init)
                var new_url = base_url + '/page_view_home';
                pane.setUrl(new_url);
            }
        }
    
    
        var pane = dojo.widget.byId('transcriptiePane');

        if (pane) {
            if (pane.widgetId != 'homePane') {
                pane.setUrl(base_url + '/page_view_nnbw_xml?'+ query_string);
            } else { //the homePane of course does not change (but needs to be set at init)
                var new_url = base_url + '/page_view_nnbw_xml';
                pane.setUrl(new_url);
            }
        }
    
    
        var pane = dojo.widget.byId('image');

        if (pane) {
            if (pane.widgetId != 'homePane') {
                pane.setUrl(base_url + '/page_view_img?'+ query_string);
            } else { //the homePane of course does not change (but needs to be set at init)
                var new_url = base_url + '/page_view_img';
                pane.setUrl(new_url);
            }
        }
     
   //if the home-page pane is selected, we move the focus to the image pane
    //(otherwise leave the focus where it was (say, on the ocr view or the pdf view)
    var homePane = dojo.widget.byId('homePane')
    if (homePane.selected) {
        dojo.widget.byId('content_box_main').selectChild(defaultPane);
    }

    /* We use the dojo "publish/subscribe" model to make page, source and size known to any subscribers
    publishing a dictionary with page, source and size
    to a channel named 'showPage' 
    */
    var message = {
        source_id : source,
        page_index : page,
        size : size,
        highlight : highlight
    };
    
    /*the channel name is case sensitive! */
    dojo.event.topic.publish('/showPage', message);
}


var initialize_browser = function() { 
    /* show an image if we asked for a specific page - otherwise, show the homepage */
    if (window.location.hash != '' ||  window.location.search != '' || request_page) {
        open_on_image = 1;
    } else {
        open_on_image = 0;
    }
    //find out which page to show
    //a page is defined by a page_index and a source
    //we look first in the request (the variables "request_source" and "request_page" are defined in page_view.pt)
    // and if those do not provide data, we look the hash value in the url "#15:4"
    source_page = parse_hash()
    source = request_source || source_page[0] || first_source();
    page =   request_page   || source_page[1] || first_page();

    //initialize the history (for bookmarking and back buttons)
    current_state = new State(source=source, page=page,size=default_size,reload=0)
    dojo.undo.browser.setInitialState(current_state);

   // set the urls for the accessors
    fill_accessors();
    //set the urls for the views 
    redrawPanes(page, source,size=the_size(), highlight='', force_refresh=true);

    //move to the right view (if necessary)
    if (open_on_image) {
        try {
             dojo.widget.byId('content_box_main').selectChild('imagePane');
        } catch(err) {
            dojo.widget.byId('content_box_main').selectChild('transcriptiePane')
        }
    } else {
        //show the homePane
        dojo.widget.byId('content_box_main').selectChild('homePane');
    } 
   
};

make_query_map = function(accessor_id, kw) {
    //make a query on the basis of the values in the form
    map = {}
    //get the form on the page (if any)
    form_id = 'form_' + accessor_id
    frm = document.getElementById(form_id)
    if (frm) {
        for (var i=0; i < frm.elements.length; i++) {
            el = frm.elements[i]
            if (el != null && el.name ) {
                if (el.type == 'select-one') {
                    if (el.selectedIndex > -1) {
                        option = el.options[el.selectedIndex];
                        if (option.value == null) {
                            value = option.text 
                        } else {
                            value = option.value
                        }
                    } else {
                        value = '' 
                    }
                    map[el.name] = value;
                } else {
                    map[el.name] = el.value;

                }
            }
        }
    } 
    
    for (var key in kw) {
        map[key] = kw[key];
    }
    return map;
}

make_query_string = function(accessor_id, kw) {
    result = dojo.io.argsFromMap(make_query_map(accessor_id, kw),encoding=ENCODING);
    return result
};

submit_search = function(accessor_id, kw, url) {
	/*
	show the contents of url, with a query made from kw, in the tab of accessor accessor_id
	
	accessor_id:  a string (default = context/id
	kw: a dictionary with keywords (default {})
	url: a string (default ='.')
		
	*/
    if (accessor_id == null) {
        id = 'nnbw';
    } else{
        id = accessor_id;
    }
    var thisPane = dojo.widget.byId(id);
    if (kw == null) {kw = {}}

    if (kw['reset']) {
        clear_form(accessor_id);
    }
   if (thisPane) {
	    if (url == null) {
         url = id
        }
        qs = make_query_string(id, kw)
        if (qs) { url += '?' + qs }
        thisPane.setUrl(url);
        }
    else {
        window.location.assign(url + '?' + make_query_string(id, kw));
    }
};

search_for = function(accessor_id, kw) {
    // fill in the form with values from kw
    // and submit it
    frm = document.getElementById('form_' + accessor_id);
    for (k in kw) {
        frm.elements[k].value = kw[k] 
    }
    submit_search(accessor_id);
};


clear_form = function(accessor_id) {
    // clear the form 'form_' + accessor_id

    //set the dojo widgets seperately
    //XXX this clears all comboxes in the application
    //XXX (should only clear those within the form form_$accessor_id
    
    comboboxes = dojo.widget.byType('ComboBox')
    for (var i in comboboxes) {
       comboboxes[i].setValue('')  
    }
    selectboxes = dojo.widget.byType('Select')
    for (var i in selectboxes) {
       selectboxes[i].setValue('')  
       selectboxes[i].setSelectedValue('')  
    }
    frm = document.getElementById('form_' + accessor_id);
    if (frm) {
        for (var i=0; i < frm.elements.length; i++) {
            el = frm.elements[i] 
            if (el && el.name == 'reset') {
                //dont tocuh the reset field
            }
            else if (el && el.type == 'hidden') {
                el.value = '';
                }
            else if (el && el.type == 'select-one') {
                el.value = '';
            }
            else if (el && el.type == 'text') {
                el.value = '';
                }
        }
    }
} 

toggle_box = function(box_id, toggle){
    show_button = document.getElementById('show_button_' + box_id)
    hide_button = document.getElementById('hide_button_' + box_id)
    box = document.getElementById('box_' + box_id)
    if (toggle == undefined && show_button && (show_button.style.display ==  'None' || show_button.style.display == 'none')) {
        toggle = false //toggle it off
    } 
    if (toggle == undefined) {
        toggle = true
    }

    if (toggle) { //show all
        if (hide_button) {
            hide_button.style.display = 'inline';
        }
        if (show_button) {
            show_button.style.display = 'None';
        }
        if (box_id) {
            box.style.display = 'inline' 
/*     TOO SLOW:       dojo.lfx.wipeIn(box, 300).play(); */
        }
    } else {
        if (hide_button) {
             hide_button.style.display = 'None';
        }
        if (show_button) {
            show_button.style.display = 'inline';
        }
        if (box_id) {
 /*    TOO SLOW:           dojo.lfx.wipeOut(box, 300).play(); */
            box.style.display = 'None' 
        }

    }
}


