/*==============================================================================

	MPK
	phplib
	
    Javascript for navigation on navigable map.

	Browser abilitati:
		- IE 6
		- Mozilla Firefox 2
	
    Copyright (c) Mizar
    $Id: mpkinteractivemap.js 847 2007-07-13 09:54:29Z mmanzato $
	
==============================================================================*/

// Variabili globali "pubbliche" (da cambiare/settare nella pagina principale)
var map_width = 200;    
var map_height = 200;   

// Variabili globali "private"
var map_mode = 'zoomarea';		// Modo di mappa attivo
var map_vspc = 0;
var map_hspc = 0;
var map_zooming = false;
var map_panning = false;
var map_overIcon = false;
var map_mouseX = 0;
var map_mouseY = 0;
var map_xa = 0;					// Coordinate zoom (point o rect)
var map_ya = 0;
var map_xb = 0;
var map_yb = 0;
var map_tlX = 0;                // Coordinate di mappa (angoli)
var map_tlY = 0;
var map_brX = 0;
var map_brY = 0;
var map_xMap = 0;               // Coordinate di mappa (interpolate)
var map_yMap = 0;
var map_formId = 'theForm';
var map_boicursor = '';
var map_flags = 0;
var map_toolbarIconUrl = '/libm/mpk/img';

var map_pick = false;			// Flag: se true è un "pick" su mappa
var map_pickCallback = null;	// Callback per il pick

/*------------------------------------------------------------------------------
    Ritorna un riferimento ad un elemento, in base al suo id.
    Ritorna null se l'elemento di id 'id' non viene trovato.
    Fonte: www.quirksmode.org
------------------------------------------------------------------------------*/
function mapGetElem(id)
{
    if (document.getElementById)
        return document.getElementById(id);
    else if (document.all)
        return document.all[id];
    else if (document.layers)
        return document.layers[id];
    else
        return null;
}

/*------------------------------------------------------------------------------
    Prepara il form per la sottomissione.
------------------------------------------------------------------------------*/
function mapPrepareSubmitForm(act, param)
{
    var elem = mapGetElem('map_coords');
    if (elem) 
        elem.innerHTML = '';
        
	var elem = mapGetElem("map_loading");
	if (elem != null)
		elem.style.visibility = 'visible';
        
	var form = mapGetElem(map_formId);
	if (!form) return;
    
    form.map_action.value = act;
	form.map_param.value = param;
	form.map_xa.value = map_xa;
	form.map_ya.value = map_ya;
	form.map_xb.value = map_xb;
	form.map_yb.value = map_yb;
	form.map_xMap.value = map_xMap;
	form.map_yMap.value = map_yMap;
	form.map_mode.value = map_mode;
}

/*------------------------------------------------------------------------------
    Sottomette il form inviando una azione di mappa
------------------------------------------------------------------------------*/
function mapSubmit(act, param)
{
    mapPrepareSubmitForm(act, param);

	var form = mapGetElem(map_formId);
	if (!form) {
	    alert('Error: MpkInteractiveMap: (application error) No such form ID: ' + map_formId)
		return;
	}
	form.submit();
}

/*------------------------------------------------------------------------------
    Chiamata quando l'utente esegue un click su un'icona.
------------------------------------------------------------------------------*/
function mapClickOnIcon(url)
{
    if (!map_zooming)
        document.location = url;
}

/*------------------------------------------------------------------------------
    Imposta il modo di interazione con la mappa.
    I valori possibili sono:
        'zoomin'
        'zoomarea'
        'zoomout'
        'centre'
        'pan'
        'pick'
------------------------------------------------------------------------------*/
function mapSetMode(mode)
{
    map_mode = mode;

    // Imposta lo stile del cursore della mappa
    map_img = mapGetElem('map_img');
    if (map_img != null) {
        switch (mode) {
            case 'zoomarea':
                map_img.style.cursor = 'crosshair';
                break;
            case 'centre':
                map_img.style.cursor = 'pointer';
                break;
            case 'pan':
                map_img.style.cursor = 'move';
                break;
            default:
            case 'pick':
            case 'zoomin':
            case 'zoomout':
                map_img.style.cursor = 'default';
                break;
        }
    }

    // Imposta gli strumenti
    var modes = new Array('zoomin', 'zoomout', 'zoomarea', 'centre', 'pan', 'pick');
    var i;
    for (i = 0; i < modes.length; i++) {
        var id = 'map_tool_' + modes[i];
        var elem = mapGetElem(id);
        if (elem == null)
            continue;
		var src = map_toolbarIconUrl + "/" + modes[i];
		if (mode == false)
		    src += "Disabled.gif";
        else if (mode == modes[i])
		    src += "Selected.gif";
        else
		    src += ".gif";
		elem.src = src;
    }
}


/*------------------------------------------------------------------------------
    Visualizza la zoom box.
------------------------------------------------------------------------------*/
function mapShowZoomBox()
{
    var obj = mapGetElem('map_zoombox');
    if (obj == null)
        return false;
    x = y = w = h = 0;
    
    if (map_xa > map_xb) {
        x = map_xb;
        w = map_xa - map_xb + 1;
    }
    else {
        x = map_xa;
        w = map_xb - map_xa + 1;
    }
    if (map_ya > map_yb) {
        y = map_yb;
        h = map_ya - map_yb + 1;
    }
    else {
        y = map_ya;
        h = map_yb - map_ya + 1;
    }
    
/*        x--;
        y--;*/
    w -= 2;
    if (w < 0)
        w = 0;
    h -= 2;
    if (h < 0)
        h = 0;

    obj.style.visibility = "visible";
    obj.style.left = (x - 1) + "px";
    obj.style.top = (y - 1) + "px";
    obj.style.width = w + "px";
    obj.style.height = h + "px";
}

/*------------------------------------------------------------------------------
    Nasconde la zoom box.
------------------------------------------------------------------------------*/
function mapHideZoomBox()
{
    var obj = mapGetElem('map_zoombox');
    if (obj == null)
        return false;
    obj.style.visibility.value = 'hidden';
}

/*------------------------------------------------------------------------------
    Gestisce il click su mappa.

    Viene configurata da createZoomBox() per essere richiamata automaticamente
    quando viene premuto il pulsante sinistro del mouse.
------------------------------------------------------------------------------*/
function mouseDown(evt)
{
    if (map_overIcon)
        return false;
        
    if (!evt) 
        var evt = window.event;
    
    var button = evt.button;
    if ((button != 0) && (button != 1))
        return false;
    
    document.onmousemove = mapGetMouse;
    document.onmouseup = mapMouseUp;

    // Recupera e salva le coordinate del mousedown relative alla mappa
    map_hspc = map_vspc = 0;
    mapGetImageXY(evt);
    map_hspc = mapFindPosXById('map_img');
    map_vspc = mapFindPosYById('map_img');
    map_mouseX -= map_hspc; // Il mousedown è sull'immagine
    map_mouseY -= map_vspc;
    map_xa = map_xb = map_mouseX;
    map_ya = map_yb = map_mouseY;
//    alert("(" + map_hspc + ", " + map_vspc + "): (" + map_mouseX + ", " + map_mouseY + ")");
//    return false;
    
    if (!map_zooming && (map_mode == "zoomarea" )
        && (map_mouseX >= 0) && (map_mouseX < map_width)
        && (map_mouseY >= 0) && (map_mouseY < map_height)) {
        mapShowZoomBox();
        map_zooming = true;
        return false;
    }
    else if (!map_panning && (map_mode == "pan" )
        && (map_mouseX >= 0) && (map_mouseX < map_width)
        && (map_mouseY >= 0) && (map_mouseY < map_height)) {
        map_panning = true;
        return false;
    }
    else if (map_zooming) {
        mapGetMouse(evt);
        mapHideZoomBox(evt);
        map_zooming = false;
        map_panning = false;
    }

    return true;
}

/*------------------------------------------------------------------------------
    Salva la posizione del mouse nelle variabili globali map_x2 e map_y2.

    Viene configurata da createZoomBox() per essere richiamata automaticamente
    quando viene spostato il mouse.
------------------------------------------------------------------------------*/
function mapGetMouse(evt)
{
    if (map_overIcon)
        return false;
        
    if (!evt) 
        var evt = window.event;
        
    mapGetImageXY(evt);
    if (!map_panning) {
        if (map_mouseX < 0)
            map_mouseX = 0;
        if (map_mouseX > map_width)
            map_mouseX = map_width;
        if (map_mouseY < 0)
            map_mouseY = 0;
        if (map_mouseY > map_height)
            map_mouseY = map_height;
    }            
    map_xb = map_mouseX;
    map_yb = map_mouseY;
    
    var elem = mapGetElem('map_coords');
    if (elem)
        elem.innerHTML = 'X: ' + map_xMap + '<br />Y: ' + map_yMap;
    
    if (map_zooming)
        mapShowZoomBox();
    else if (map_panning) {
        elem = mapGetElem('map_img');
        elem.style.left = (map_xb - map_xa) + "px";
        elem.style.top = (map_yb - map_ya) + "px";
    }
    
    return false;
}

/*------------------------------------------------------------------------------
    Gestisce il rilascio del pulsante del mouse.

    Viene configurata da createZoomBox() per essere richiamata automaticamente
    quando viene rilasciato il pulsante sinistro del mouse.
------------------------------------------------------------------------------*/
function mapMouseUp(evt)
{
    if (map_overIcon)
        return false;
        
    if (!evt) 
        var evt = window.event;
    
    var button = evt.button;
    if ((button != 0) && (button != 1))
        return false;
    
    document.onmousemove = null;
    document.onmouseup = null;

    // Salva le coordinate del mouseup (assoluto!)
	map_xb = map_mouseX;
	map_yb = map_mouseY;

    if (map_zooming) {
        map_zooming = false;
        mapHideZoomBox();
        if ((map_xa == map_xb) || (map_ya == map_yb)) {
			map_xa = (map_xa + map_xb)/2;
			map_ya = (map_ya + map_yb)/2;
            mapSubmit('zoomin', null);
        }
        else
            mapSubmit('zoomarea', null);
    }
    else if (map_mode == 'pick') {
        // Funzione utente 'pick', richiama la callback
        mapGetImageXY(evt);
        mapSetMode('zoomarea');
        mapPrepareSubmitForm(null, null);
        mapStopPick();
    }
    else if (map_panning) {
        // In caso di pan esegue sempre il submit
        mapGetImageXY(evt);
        mapSubmit(map_mode, null);
    }        
    else {
        // Tutti gli altri modi: esegue il submit solo se click è interno
        // alla mappa
        mapGetImageXY(evt);
        if ((map_mouseX >= 0) && (map_mouseX < map_width)
            && (map_mouseY >= 0) && (map_mouseY < map_height)) {
             mapSubmit(map_mode, null);
        }
    }
    return false;
}

/*------------------------------------------------------------------------------
	Return the click coordinates relative to the current frame.
	Works even if the page is scrolled.
------------------------------------------------------------------------------*/
function mapGetClickCoords(evt)
{
	var x = evt.clientX;
	var y = evt.clientY;

    var html = document.getElementsByTagName("html").item(0);
    if (html != null) {
        x += html.scrollLeft;
        y += html.scrollTop;
	}

	return [x, y];
}

/*------------------------------------------------------------------------------
    Recupera le coordinate di un evento del mouse relativamente all'immagine
    visualizzata.

    Salva le coordinate recuperate nelle variabili globali map_mouseX e
    map_mouseY.

    Tiene conto di un eventuale scroll del tag BODY.
------------------------------------------------------------------------------*/
function mapGetImageXY(evt)
{
    if (!evt) 
        var evt = window.event;

	var coords = mapGetClickCoords(evt);
    map_mouseX = coords[0];
    map_mouseY = coords[1];

    // Subtract offsets from image position
    map_mouseX = map_mouseX - map_hspc;
    map_mouseY = map_mouseY - map_vspc;
    
    map_xMap = map_tlX + 1.0*(map_brX - map_tlX)*map_mouseX/map_width;
    map_yMap = map_tlY + 1.0*(map_brY - map_tlY)*map_mouseY/map_height;
    map_xMap = (Math.floor(map_xMap * 100000))/100000.0 
    map_yMap = (Math.floor(map_yMap * 100000))/100000.0 
}


/*------------------------------------------------------------------------------
    Determina la posizione assoluta X dell'elemento obj
    Fonte: www.quirksmode.org
------------------------------------------------------------------------------*/
function mapFindPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

/*------------------------------------------------------------------------------
    Determina la posizione assoluta Y dell'elemento obj
    Fonte: www.quirksmode.org
------------------------------------------------------------------------------*/
function mapFindPosY(obj)
{
    var curtop = obj.scrollTop;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
            curtop += obj.y;
    return curtop;
}

/*------------------------------------------------------------------------------
    Determina la posizione assoluta X dell'elemento con id="<elemId>".
------------------------------------------------------------------------------*/
function mapFindPosXById(elemId)
{
    var elem = mapGetElem(elemId);
    if (elem != null)
        return mapFindPosX(elem);
}

/*------------------------------------------------------------------------------
    Determina la posizione assoluta Y dell'elemento con id="<elemId>".
------------------------------------------------------------------------------*/
function mapFindPosYById(elemId)
{
    var elem = mapGetElem(elemId);
    if (elem != null)
        return mapFindPosY(elem);
}

/*------------------------------------------------------------------------------
    Passaggio sopra una icona
------------------------------------------------------------------------------*/
function mapIconOver()
{
    if (!map_zooming) {
        map_overIcon = true;
	    var elem = mapGetElem("map_img");
		if (elem != null) {
			map_boicursor = elem.style.cursor; 
			elem.style.cursor = "help";
		}
	}		
    return true;
}

/*------------------------------------------------------------------------------
    Uscita da sopra una icona
------------------------------------------------------------------------------*/
function mapIconOut()
{
    if (!map_zooming) {
        map_overIcon = false;
	    var elem = mapGetElem("map_img");
		if (elem != null)
			elem.style.cursor = map_boicursor; 
	}
    return true;
}

/*------------------------------------------------------------------------------
    Mostra un enhanced tooltip
------------------------------------------------------------------------------*/
function mapDisplayEt(evt, id)
{
    if (!evt) 
        var evt = window.event;
    var elem = mapGetElem(id);
    if (!elem) return;
    map_hspc = map_vspc = 0;
    mapGetImageXY(evt);    
    map_hspc = mapFindPosXById('map_img');
    map_vspc = mapFindPosYById('map_img');
    map_mouseX -= map_hspc; // Il mousedown è sull'immagine
    map_mouseY -= map_vspc;
    elem.style.left = (map_mouseX + 16) + "px";
    elem.style.top = (map_mouseY + 16) + "px";
    elem.style.visibility = 'visible';
}

/*------------------------------------------------------------------------------
    Nasconde un enhanced tooltip
------------------------------------------------------------------------------*/
function mapHideEt(id)
{
    var elem = mapGetElem(id);
    if (!elem) return;
    elem.style.visibility = 'hidden';
}

/*==============================================================================
	Fine del file
==============================================================================*/

