var current = 0;
var MoveResize = false;
var StartXResize;
var Colonne;
var Largeur;
var P;
var Menu;
var tab;

function $(i){return document.getElementById(i)}

function set_select(i) {
    $('tn'+current).className = $('p'+current).className = '';
    $('tn'+i).className = $('p'+i).className = 'select';
    $('menu').scrollTop = ($('tn'+i).offsetTop > ($('menu').offsetHeight/2))?($('tn'+i).offsetTop - ($('menu').offsetHeight/2)):0;  
    current = i;
    SetCookie(i);
}

function redraw() {
    for(var i = 0; i < tab.f.length; i++) {
        $('p'+i).width = (P.offsetWidth - 30)+'px';
        $('p'+i).height = (tab.f[i].h *((P.offsetWidth-30)/tab.f[i].w))+'px'; 
    }
    set_select(current);
    P.scrollTop = $('p'+current).offsetTop - 8;
}

function redraw_thumbs(){
    for(var i = 0; i < tab.f.length;i++) {
        $('tn'+i).style.width = Largeur-50+'px';
    }
}

function preload(i){
    if(!$('p'+i).data) $('p'+i).data=tab.s+'/'+tab.f[i].n+'.svgz';
}

function read(i){
    preload(i);
    set_select(i);
    P.scrollTop = ($('p'+i).offsetTop) - 8;
}

function endPosition() {
    MoveResize = false;
    redraw();
    redraw_thumbs();
}

function setPosition(e) {
    if (!e) e = window.event;
    StartXResize = e.clientX;
    MoveResize = true;
    Largeur = $('menu').style.width;
    //if (!Largeur || Largeur === '') {alert('oh');Largeur = '150px';}
    Largeur = parseInt(Largeur.substring(0,Largeur.length-2), 10);
}

function setNewPosition(e) {
    if (!e) e = window.event;
    var X = e.clientX - StartXResize;
    if (MoveResize === true) {
        //  $('menu').style.width = ((Largeur+X>0)?Largeur+X:0)+'px';
        $('menu').style.width = Largeur+X+'px';
        //$('resize').style.left = ((Largeur+X>0)?Largeur+X+1:0)+'px';
        $('resize').style.left = Largeur+X+1+'px';
        //P.style.left = ((Largeur+X>0)?Largeur+X+2:0)+'px';
        P.style.left = Largeur+X+2+'px';
        // redraw();
    }
}

function reduce() {
    if (Menu) {
        $('reduce').innerHTML = '<img src="a.gif" />';
        $('menu').style.display = 'none';
        $('resize').style.display = 'none';
        P.style.left = '0px';
        Menu = false;
    }
    else {
        $('reduce').innerHTML = '<img src="r.gif" />';
        $('menu').style.display = 'block';
        $('resize').style.display = 'block';
        P.style.left = ($('menu').offsetWidth)+2+'px';
        Menu = true;
    }
    redraw();
}

function scroll() {
    var top = P.offsetHeight/2;
    var next = current + 1;
    var prec = current - 1;
    if(next < tab.f.length) preload(next);
    if(prec >= 0 ) preload(prec);
    if (($('p'+next)) && $('p'+next).offsetTop <= P.scrollTop+top) set_select(next);
    else if ($('p'+current) && $('p'+current).offsetTop >= P.scrollTop + top) set_select(current-1);
}

function checkKey(ev) {
    if (!ev) ev = window.event;
    var c = (ev.which)?ev.which:ev.keyCode;
    if (c == 38 || c == 37 || c == 80) read(current-1);
    else if (c == 40 || c == 39 || c == 32 || c == 78) read(current + 1);
    else if (c >= 96 && c <= 105) {
        if (!$('search')) {
            var x = document.createElement('div');  
            x.id = 'search';
            P.appendChild(x);
            x.innerHTML = '<input id="inputsearch" type="text" name="search" />';
        }
        $('inputsearch').value += ''+(c-96);
    }
    else if (c == 8 && $('search')) {
        var go = $('inputsearch').value;
        $('inputsearch').value = go.substr(0, go.length-1);
        return false;
    }
    else if (c == 13 && $('search')) {
        var go2 = $('inputsearch').value;
        P.removeChild($('search'));
        if (go2 <= tab.f.length) {
            read(go2-1);
        }
    }
    else if (c == 27 && $('search')) P.removeChild($('search'));
    return true;
}

function SetCookie(value) {document.cookie = tab.s+"="+value+"; expires=Fri, 3 Aug 2050 20:47:11 UTC; path=/";}

function GetCookie() {
    var nameEQ = tab.s + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
	var c = ca[i];
	while (c.charAt(0)==' ') c = c.substring(1,c.length);
	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function EraseCookie(name){createCookie(tab.s,"",-1)}

var asyncRequest = function() {
    function handleReadyState(o, callback) {
        if (o && o.readyState == 4) {
            if (o.status==200){callback(o);}
        //     if (o.status==200) {
        //                 if (callback) callback(o);
        //                 if (requestTimer) clearTimeout(requestTimer);
        //             }
        //             else affError();
        }
    }
    var getXHR = function() {
        return (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Msxml2.XMLHTTP");
    };
    return function(uri, callback, postData) {
        var xhr = getXHR();
        xhr.open('POST', uri, true);
        xhr.onreadystatechange = function() {
            handleReadyState(xhr, callback);
        };
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        xhr.send('http=1&'+postData);
        //  requestTimer = setTimeout(function(){xhr.abort();},10);// MAXIMUM_WAITING_TIME);
        return xhr;
    };
}();

function responseAll(o) {
    var menu = '';
    tab =  eval('('+o+')');
    for (var j=0; j<tab.f.length; j++) { 
        menu += '<img id="tn'+j+'" src="'+tab.s+'/'+tab.f[j].n+'.jpg" onclick="read('+j+')" alt="page '+(j+1)+'" title="'+(j+1)+'" /><br />'+(j+1)+'<br />';
        var x = document.createElement('object'); 
        //   var x = document.createElement('embed');
        x.type = 'image/svg+xml';
        x.id = 'p'+j;
        x.height =  Math.round(tab.f[j].h *((P.offsetWidth-30)/tab.f[j].w))+'px';
        
        x.width = (P.offsetWidth-30)+'px';
        P.appendChild(x);  
    }
    $('menu').innerHTML = menu;
    var pa = GetCookie(tab.s);
    if(typeof(pa) && pa != null && current === 0) current=pa-0;
    read(current);
}


function i(pdf, nb) {
    if(nb) current=nb-1;
    Menu = true;
    $('menu').style.width = "150px";
    P = $('page');
    document.onkeydown=checkKey;
    $('resize').onmousedown = setPosition;
    document.onmousemove = setNewPosition;
    document.onmouseup = endPosition;
    $('reduce').onclick = reduce;
    asyncRequest('all.php', function(o) {responseAll(o.responseText);}, 'file='+pdf);
    P.onscroll = scroll;
}

window.onresize = redraw;
