/**
 * Copyright 2003, IMTEAM www.imteam.it
 * QUESTO PROGRAMMA E' COPERTO DA COPYRIGHT E NON PUO' ESSERE COPIATO O
 * MODIFICATO (NEMMENO PARZIALMENTE) SENZA ESPLICITO CONSENSO DEL PROPRIETARIO.
 * NON PUO' ESSERE UTILIZZATO AL DI FUORI DEL PRODOTTO CON CUI E' STATO FORNITO.
 */

//  DATA ULTIMA MODIFICA: 2003-10-17;
//  VERSIONE: 0.1-2003;
//  MODIFICATO: C.Lanza clanza@imteam.it;


var deltaX = 0;
var deltaY = 0;
var goniometring = false;

var loading = toolGetActualDate();

var panning = false;
var resizing = false; // se true e' in corso resize senza avere rilasciato il pulsante del
var tempToolMode = 0;
var toolButtaEvento = false;
var toolCurrent = '';
var toolBetweenDownAndUp = false;
var toolLocatorLeft = 0;
var toolLocatorTop = 0;
var toolLocatorRight = 0;
var toolLocatorBottom = 0;
var x1 = 0;
var x2 = 0;
var y1 = 0;
var y2 = 0;
var zooming = false;

var toolImageOn = new Array(); // immagini dei tools quando attivi
var toolImageOff = new Array(); // immagini dei tools quando non attivi
var toolDescrizioni = new Array(); // descrizioni dei tools

// Da una stringa tipo 111px restituisce 111
function toolGetNumberWithoutPx(s) {
  var retval = 1*s;
  if (s.substr(s.length-2, 2)=="px") {
    retval = 1*s.substr(0,s.length-2);
  }
  return retval;
}

// inizializzazione della pagina
function toolStartUpTemplate(needreload) {
  mapDebugMessage("toolStartUpTemplate");
  if (is.ns4 || is.ns6) {
    document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
  }
  document.onmousedown = toolGeneralMouseDown;
  document.onmousemove = toolGeneralMouseMove;
  document.onmouseup   = toolGeneralMouseUp;
  // inizializzo variabili
  mappaLeft = toolGetNumberWithoutPx(layerGetStyle('theMap').left); // horizontal image offset
  mappaTop = toolGetNumberWithoutPx(layerGetStyle('theMap').top); // vertical image offset
  mappaWidth = document.images['laMappa'].width;
  mappaHeight = document.images['laMappa'].height;
  layerGetStyle('loadingDiv').left = mappaLeft;
  layerGetStyle('loadingDiv').top = mappaTop;
  layerGetStyle('miniCartina').left = mappaLeft+2;
  layerGetStyle('miniCartina').top = mappaTop+2;
  toolLocatorLeft = toolGetNumberWithoutPx(layerGetStyle('miniCartina').left);
  toolLocatorTop = toolGetNumberWithoutPx(layerGetStyle('miniCartina').top);
  toolLocatorRight = toolLocatorLeft + toolGetNumberWithoutPx(layerGetStyle('miniCartina').width);
  toolLocatorBottom = toolLocatorTop + toolGetNumberWithoutPx(layerGetStyle('miniCartina').height);
  // adatto la pagina all'area disponibile
  mapResize();
  if (needreload) {
    toolRefreshDoOp();
  }
}

// gestisce evento resize
function winResizeHandler(e) {
  if ( typeof(is)=="undefined" || is == null) {
    return true;
  }
  if (toolIsLoading()) {
    return;
  }
  if (is.ie4 || is.ie5) {
    e = window.event;
  }
  if (e.type == 'resize') {
    mapResize();
  }
  resizing = true;
}

function addhandlers(o) {
  init();
  o.onresize = winResizeHandler;
}


function toolAttivaImmagine(idTool) {
  winChangeImage(idTool+'Img', toolImageOn[idTool]);
}

function toolDisattivaImmagine(idTool) {
  winChangeImage(idTool+'Img', toolImageOff[idTool]);
}


function toolDoPan(direction) {
  oldStatus = form_getStato();
  document.processa.panDirection.value = direction;
  form_setAction("pandir");
  toolLoad();
  form_restoreStato(oldStatus);
  toolButtaEvento = true;
}

function toolDoLocator() {
  mapDebugMessage("toolDoLocator");
  oldStatus = form_getStato();
  //document.processa.panDirection.value = direction;
  form_setAction("locator");
  toolLoad();
  form_restoreStato(oldStatus);
  toolButtaEvento = true;
}


function toolGetActualDate() {
  return (new Date()).getTime();
}

function toolIsLoading() {
  /*if (loading != 0 && (loading-toolGetActualDate()) > 15000) {
    toolLoaded();
    return false;
  }*/
  return (loading != 0);
}

var loadingTimeoutId = 0;

function toolLoad() {
  var _status = form_getStato();
  mapDebugMessage("toolLoad:"+_status);
  if (toolIsLoading()) {
    alert("L'operazione precedente non e' stata ancora completata.");
    return;
  }
  loading = toolGetActualDate();
  layerShow("loadingDiv"); // l'ho messa anche sulla onSubmit() della form
  // sospende utilizzo editor flash
  if ((typeof(fFeatureEditorObj) != "undefined") && fFeatureEditorObj.initialized) 
  	fFeatureEditorObj.suspend(true);    
  document.processa.submit();
  loadingTimeoutId = setTimeout("toolLoadingTimeout()", 20000);
}

function toolLoaded() {
  clearTimeout(loadingTimeoutId);
  loading = 0;
  layerHide("loadingDiv");
  // riattiva utilizzo editor flash
  if ((typeof(fFeatureEditorObj) != "undefined") && fFeatureEditorObj.initialized) 
  	fFeatureEditorObj.suspend(false);     
}

function toolLoadingTimeout() {
  window.status="L'operazione precedente non si e' completata nel tempo massimo. E' possibile attendere ancora o proseguire con altre operazioni.";
  toolLoaded();
}


/****************************************************************
 * CONFIGURAZIONE DEGLI HANDLERS
 * Ci sono azioni immediate (tipo zoomfx) che definiscono il solo handler doop,
 * ed azioni che necessitano di azioni utente (tipo zoomin) che definiscono cinque
 * metodi: start, stop, mousedown, mousemove, mouseup
 */
var toolHandlers = new Object();

toolHandlers.bussola = new Object();
toolHandlers.bussola.start = toolLongActionStart; //toolBussolaStart;
toolHandlers.bussola.stop  = toolLongActionStop;
toolHandlers.bussola.down  = toolBussolaDown;
toolHandlers.bussola.move  = toolBussolaMove;
toolHandlers.bussola.up    = toolBussolaUp;

toolHandlers.scala = new Object();
toolHandlers.scala.doop    = toolScalaDoOp;

toolHandlers.refresh = new Object();
toolHandlers.refresh.doop    = toolRefreshDoOp;




/**
 * Se chiamo direttamente la funzione sull'array,
 * quando l'elemento non c'e' si genera l'errore FASTIDIOSISSIMO "toolHandlers[...] e' nullo o non e' un oggetto"
 *  quindi chiamo questa funzione cha fa tutti i controlli
 */
function toolDoOp(_op)
{
  var currHand = toolHandlers[_op];
  if ("undefined" != typeof(currHand) && "undefined" != typeof(currHand["doop"])) {
    currHand.doop(_op);
  } else {
    // debug
    window.status=("toolDoOp("+_op+") non definito. Azione di default.");
    toolImmediateActionDoOp_NoWait(_op);
  }
}

/**
 * Se chiamo direttamente la funzione sull'array,
 * quando l'elemento non c'e' si genera l'errore FASTIDIOSISSIMO "toolHandlers[...] e' nullo o non e' un oggetto"
 *  quindi chiamo questa funzione cha fa tutti i controlli
 */
function toolStartOp(_op)
{
  mapDebugMessage("toolStartOp("+_op+")");
  var currHand = toolHandlers[_op];
  if ("undefined" != typeof(currHand) && "undefined" != typeof(currHand["start"])) {
    currHand.start(_op);
    var myCursor = actionCursor[_op];
    if (!myCursor || myCursor=="null") {
    	myCursor = "pointer";
    }
  	setLayerCursor("theMap", myCursor);
   	setLayerCursor("theMapBlend", myCursor);
  } else {
    // debug
    alert("toolStartOp("+_op+") non definito");
  }
}

/**
 * Questa funzione chiama lo stop tramite toolHandlers, verificandone l'esistenza.
 * In genere la funzione e' chiamata da tutti gli start dei tool che prendono controllo della
 * form per gestire azioni utente (vedi zoom, pan, etc...), MA NON dai tool che agiscono immediatamente
 * e poi lasciano la form cosi' come l'hanno trovata (e.g. zoomfx, refresh, etc...).
 */

function toolStopOp(_op)
{
  var currHand = toolHandlers[_op];
  if ("undefined" != typeof(currHand) && "undefined" != typeof(currHand["stop"])) {
    currHand.stop(_op);
    setLayerCursor("theMap", "pointer");

  }
}

/**
 * Adesso definisci alcuni handlers generici
 */

/**
 * start di una azione "lunga"
 * aspetto interazione utente (e.g. un click sulla mappa), quindi stoppo l'op precedente,
*  setto la form per l'op corrente e accendo l'immagine
 */
function toolLongActionStart(idObj) {
  toolAttivaImmagine(idObj);
  if (window.document.processa.op.value!=idObj) {
  	toolStopOp(window.document.processa.op.value);
  }
  // la vecchia potrebbe essere ancora la nuova
  toolAttivaImmagine(idObj);
  form_setAction(idObj);
  return false;
}

/**
 * stop di una azione "lunga"
 * spengo l'immagine.
 */
function toolLongActionStop(idObj) {
  toolDisattivaImmagine(idObj);
  return false;
}

function toolImmediateActionDoOp(idObj) {
  toolAttivaImmagine(idObj);
  mapDebugMessage("toolImmediateActionDoOp:"+idObj);
  oldStatus = form_getStato();
  form_setAction(idObj)
  toolLoad();
  //toolLoaded();
  form_restoreStato(oldStatus);
  setTimeout("toolDisattivaImmagine('"+idObj+"')", 300);
  //return false;
}

function toolImmediateActionDoOp_NoWait(idObj) {
  mapDebugMessage("toolImmediateActionDoOp:"+idObj);
  oldStatus = form_getStato();
  form_setAction(idObj)
  toolLoad();
  toolLoaded();
  form_restoreStato(oldStatus);
  toolAttivaImmagine(idObj);
  setTimeout("toolDisattivaImmagine('"+idObj+"')", 500);
  //return true;
}


function toolBussolaDown(evento) {
  if (toolButtaEvento) {
    return false;
  } else {
    startGoniometro(evento);
    return false;
  }
}

function toolBussolaMove(evento) {
  if (toolButtaEvento) {
    return false;
  } else {
    if (!goniometring) {
      return false;
    }
    var mouseString = "";
    x2=mouseX;
    y2=mouseY;
    goniometro();
    var g_coord = mapPixel2Coord(mouseX, mouseY);
    var g_origcoord = mapPixel2Coord(x1, y1);
    mouseString += "Coordinate : " + g_coord[0] + ", " + g_coord[1];
    mouseString += " - Direzione (Th): " + Math.round(getDirezioneCardinale(x2-x1,y2-y1)*100)/100. + " - Distanza (m): " +
                   Math.round(Math.sqrt((g_coord[0]-g_origcoord[0])*(g_coord[0]-g_origcoord[0])+(g_coord[1]-g_origcoord[1])*(g_coord[1]-g_origcoord[1])));
    window.status = mouseString;
    return false;
  }
}


function toolBussolaUp(evento) {
  if (toolButtaEvento) {
    toolButtaEvento = false;
    return false;
  } else {
    var g_extent = mapGetExtent();
    stopGoniometro(evento); // questa chiama setAction e processa
    return false;
  }
}




function toolExtInfoUp(evento) {
  mapDebugMessage("toolExtInfoUp");
  if (toolButtaEvento) {
    toolButtaEvento = false;
    return false;
  } else {
    /* DC 03-11-2003 */
    infowin = window.open("","infoWindow","width=600,height=450,toolbar=0,location=0,directories=0,status=0,menuBar=0,scrollBars=1,resizable=1");
    document.processa.target="infoWindow";
    document.processa.type_refresh.value="extern";
    mapStopZoomBox(evento);
    return false;
  }
}

function toolPanDown(evento) {
  if (toolButtaEvento) {
//    toolButtaEvento = false;
    return false;
  } else {
    mapStartPan(evento);
    return false;
  }
}

function toolPanMove(evento) {
  if (toolButtaEvento) {
//    toolButtaEvento = false;
    return false;
  } else {
   if (panning) {
      mapMakePan();
    }
    return false;
  }
}


function toolPanUp(evento) {
  if (toolButtaEvento) {
    toolButtaEvento = false;
    return false;
  } else {
    mapStopPan(evento);
    return false;
  }
}

function toolRefreshDoOp(idObj) {
  mapDebugMessage("toolRefreshDoOp");
  if ("undefined"==typeof(idObj)) {
    idObj="refresh";
  }
  oldStatus = form_getStato();
  form_setAction(idObj)
  toolLoad();
  form_restoreStato(oldStatus);
  return false;
}

function toolScalaDoOp(idObj) {
  mapDebugMessage("toolScalaDoOp:"+idObj);
  oldStatus = form_getStato();
  form_setAction(idObj)
  toolLoad();
  form_restoreStato(oldStatus);
  return false;
}

function toolSelezioneClearDoOp(idObj) {
  document.processa.SelectionLayerIds.value = "";
  document.processa.SelectionWhereClauses.value = "";
  document.processa.HighlightLayerIds.value = "";
  document.processa.HighlightWhereClauses.value = "";
  toolRefreshDoOp("refresh");
  return false;
}



function toolMoveCaptureMousePos(evento) {
  if (toolButtaEvento) {
//    toolButtaEvento = false;
    return false;
  } else {
    if (!zooming) {
      return false;
    }
    var mouseString = "";
    x2 = mouseX;
    y2 = mouseY;
    mapReorderCoords();
    //mouseString += "Estensione : [" + (x1-mappaLeft) + "," + (y1-mappaTop) + " x " + (x2-mappaLeft) + "," + (y2-mappaTop) + "]    ";
    var g_coord = mapPixel2Coord(mouseX,mouseY);
    var g_origcoord = mapPixel2Coord(x1 ,y1);
    mouseString += "Coordinate del mouse: " + g_coord[0] + ", " + g_coord[1];
    window.status = mouseString;
    return false;
  }
}

function toolGeneralMouseDown(e) {
  winCursorPosition(e);
  window.status="toolGeneralMouseDown: overmap: "+toolMouseOverMap()+", overlocator: "+toolMouseOverLocator()+", current op: "+window.document.processa.op.value;
  if (toolMouseOverMap() && !toolMouseOverLocator()) {
    toolBetweenDownAndUp = true;
    if (typeof(toolHandlers[window.document.processa.op.value])!="undefined") {
      if (typeof(toolHandlers[window.document.processa.op.value]["down"])!="undefined") {
        setLayerCursor("theMap", actionCursorDown[window.document.processa.op.value]);
        return (toolHandlers[window.document.processa.op.value].down(e));
      }
    }
  } else {
    return true;
  }
}

function toolGeneralMouseMove(e) {
  winCursorPosition(e);
  if (toolMouseOverMap() && !toolMouseOverLocator()) {
    var g_coord1 = mapPixel2Coord(mouseX, mouseY);
    window.status = "X:"+g_coord1[0]+", Y:"+g_coord1[1];
    if (typeof(toolHandlers[window.document.processa.op.value])!="undefined") {
      if (typeof(toolHandlers[window.document.processa.op.value]["move"])!="undefined") {
        return (toolHandlers[window.document.processa.op.value].move(e));
      }
    }
  } else if (!toolMouseOverMap() && toolMouseOverLocator()) {
      return true;
  } else {
    if (resizing == true) {
      resizing = false;
      toolRefreshDoOp();
    }
    if (toolBetweenDownAndUp) {
      toolBetweenDownAndUp = false;
      if (typeof(toolHandlers[window.document.processa.op.value])!="undefined") {
        if (typeof(toolHandlers[window.document.processa.op.value]["up"])!="undefined") {
          return (toolHandlers[window.document.processa.op.value].up(e));
        }
      }
    }
    return true;
  }
}

function toolGeneralMouseUp(e) {
  toolBetweenDownAndUp = false;
  winCursorPosition(e);
  if (toolMouseOverMap() && !toolMouseOverLocator()) {
    if (typeof(toolHandlers[window.document.processa.op.value])!="undefined") {
      if (typeof(toolHandlers[window.document.processa.op.value]["up"])!="undefined") {
        setLayerCursor("theMap", actionCursor[window.document.processa.op.value]);
        return (toolHandlers[window.document.processa.op.value].up(e));
      }
    }
  } else {
    return true;
  }
}

function toolMouseOverMap() {
  return (!winMouseOnScrollbars(mouseX,mouseY) && (mouseX > mappaLeft) && (mouseX < (mappaWidth+mappaLeft)) && (mouseY > mappaTop) && (mouseY < (mappaHeight+mappaTop)));
}

function toolMouseOverLocator() {
  if (layerIsVisibile("miniCartina")) {
    return ((mouseX >= toolLocatorLeft) && (mouseX <= toolLocatorRight) && (mouseY >= toolLocatorTop) && (mouseY <= toolLocatorBottom));
  } else {
    return false;
  }
}

