/**
 * 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;

/* Versione: $Revision: 1.11 $ */

// distanze immagine mappa dai bordi della cella
var hspcCella= 2;
var vspcCella= 2;

var ovBoxSize = 3;            // Zoombox line width;

/** sostituiscono hspc, vspc, iWidth e iHeight */
var mappaLeft=0;
var mappaTop=0;
var mappaWidth=0;
var mappaHeight=0;

/**
 * Gestione del resize per IE4 o IE5
 * questa funzione calcola la nuova larghezza della mappa e la applica alla
 * mappa, alle division della legenda e layers ed alla cella della table.
 */
function mapResize() {
  mappaLeft = toolGetNumberWithoutPx(layerGetStyle('theMap').left);
  mappaTop = toolGetNumberWithoutPx(layerGetStyle('theMap').top);
  var distLeft = toolGetNumberWithoutPx(layerGetStyle('layer_tab_struttura').left);
  var distRight = distLeft; // la distanza dal bordo dx è uguale al bordo sx
  var distBottom = 2; // la distanza dal fondo è uguale al bordo sup

  // la larghezza finale della pagina deve essere MINIMO 800px
  larghWin = (winGetWidth()>800) ? winGetWidth() : 800;
  // questa è la larghezza della division e dell'immamgine
  mappaWidth = larghWin - mappaLeft - distRight - 2*hspcCella;

    // l' altezza finale della pagina deve essere MINIMO 500px (c'e' anche il menu di explorer)
  altWin = (winGetHeight() > 500) ? winGetHeight() : 500;
  var legTop = toolGetNumberWithoutPx(layerGetStyle('tablegenda').top);
  mappaHeight  = altWin - mappaTop - distBottom - 2*vspcCella;

  var legendHeigth = altWin - legTop -distBottom;


  //alert(mappaWidth+" "+ mappaHeight);
  if (document.getElementById("ECWView")!=null)
  {
    document.getElementById("ECWView").width = mappaWidth;
    document.getElementById("ECWView").height = mappaHeight;
  }
  document.images['laMappa'].width = mappaWidth;
  document.images['loadingImg'].width = mappaWidth + 2*hspcCella;
  document.images['laMappa'].height = mappaHeight;
  document.images['loadingImg'].height = mappaHeight;
  layerGetStyle('tablegenda').height = legendHeigth;
  layerGetStyle('tablayers') .height = legendHeigth;
  //layerClip2("theMap",0,0,mappaWidth,mappaHeight);
  //layerClip2("loadingDiv",0,0,document.images['loadingImg'].width,document.images['loadingImg'].height);
  layerGetStyle('cellamappa').width = mappaWidth + 2*hspcCella;
  layerGetStyle('cellamappa').height = mappaHeight + 2*vspcCella + distBottom;
  /* larghezza della division */
  //iWidth   = mappaWidth;
  //iHeight  = mappaHeight;
  // aggiorno le dimensioni dell'oggetto flash
  if (typeof(wantFlash)!="undefined" && wantFlash)
  {
    flashResize('flash_edit','objEdit','theMap');
  }

  if (document.getElementById("ECWView") != null)
  {
    document.getElementById("ECWView").width = mappaWidth;
    document.getElementById("ECWView").height = mappaHeight;
  }
  document.processa.MapImageX.value = mappaWidth;
  document.processa.MapImageY.value = mappaHeight;
}

function mapDrawZoomBox(theLeft,theTop,theRight,theBottom) {
  layerClip("zoomBoxTop",theLeft,theTop,theRight,theTop + ovBoxSize);
  layerClip("zoomBoxLeft",theLeft,theTop,theLeft+ovBoxSize,theBottom);
  layerClip("zoomBoxRight",theRight-ovBoxSize,theTop,theRight,theBottom);
  layerClip("zoomBoxBottom",theLeft,theBottom-ovBoxSize,theRight,theBottom);
  layerShow("zoomBoxTop");
  layerShow("zoomBoxLeft");
  layerShow("zoomBoxRight");
  layerShow("zoomBoxBottom");
}

// zoom su bookmark scelto
function mapGoToBookmark(minX,maxX,minY,maxY) {

  oldState = form_getStato();
  form_setAction("bookmark");
  document.processa.x1.value = minX;
  document.processa.x2.value = maxX;
  document.processa.y1.value = maxY;
  document.processa.y2.value = minY;
  toolLoad();
  form_restoreStato(oldState);
}

// start zoom in.... box displayed
function mapStartZoomBox(e) {
  mapDebugMessage("mapStartZoomBox");
  winCursorPosition(e);
  // keep it within the MapImage
  if (zooming) {
    mapStopZoomBox(e);
  } else {
    x1 = mouseX;
    y1 = mouseY;
    x2 = x1;
    y2 = y1;
    zooming = true;
  }
  return false;
}

// stop zoom box display...
function mapStopZoomBox(e) {

  var tempx,tempy;
  zooming = false;
  layerHide("zoomBoxTop");
  layerHide("zoomBoxLeft");
  layerHide("zoomBoxRight");
  layerHide("zoomBoxBottom");
  if (x2 < x1) {
    tempx = x1;
    x1 = x2;
    x2 = tempx;
  }
  if (y1 > y2) {
    tempy = y1;
    y1 = y2;
    y2 = tempy;
  }

  var g_coord1 = mapPixel2Coord(x1, y1);
  document.processa.x1.value = g_coord1[0];
  document.processa.y1.value = g_coord1[1];

  var g_coord2 = mapPixel2Coord(x2, y2);
  document.processa.x2.value = g_coord2[0];
  document.processa.y2.value = g_coord2[1];
  oldOp = document.processa.op.value;
  if ((document.processa.op.value == 'info') || (document.processa.op.value == 'areainfo')) {
    if ((x1 != x2) || (y1 != y2)) {
      document.processa.op.value = 'areainfo';
    } else {
      document.processa.op.value = 'info';
    }
  }
  if ((document.processa.op.value == 'zoomin') || (document.processa.op.value == 'areazoomin')) {
    if ((x1 != x2) || (y1 != y2)) {
      document.processa.op.value = 'areazoomin';
    } else {
      document.processa.op.value = 'zoomin';
    }
  }
  toolLoad();
  document.processa.op.value = oldOp;
  return true;
}

// stop zoom box display...
function mapStopZoomBoxNoLoad(e) {

  var tempx,tempy;
  zooming = false;
  layerHide("zoomBoxTop");
  layerHide("zoomBoxLeft");
  layerHide("zoomBoxRight");
  layerHide("zoomBoxBottom");
  if (x2 < x1) {
    tempx = x1;
    x1 = x2;
    x2 = tempx;
  }
  if (y1 > y2) {
    tempy = y1;
    y1 = y2;
    y2 = tempy;
  }
  var g_coord1 = mapPixel2Coord(x1, y1);
  document.processa.x1.value = g_coord1[0];
  document.processa.y1.value = g_coord1[1];

  var g_coord2 = mapPixel2Coord(x2, y2);
  document.processa.x2.value = g_coord2[0];
  document.processa.y2.value = g_coord2[1];
  return true;
}

// costruisce un piccolo envelope di attorno al punto
function map_BuildPointSmallEnvelope(e) {

  winCursorPosition(e); // setta mouseX/Y
  var g_coord1 = mapPixel2Coord(mouseX - 5, mouseY - 5);
  document.processa.x1.value = g_coord1[0];
  document.processa.y1.value = g_coord1[1];

  var g_coord2 = mapPixel2Coord(mouseX + 5, mouseY + 5);
  document.processa.x2.value = g_coord2[0];
  document.processa.y2.value = g_coord2[1];
  mapDebugMessage("tolleranza:"+(g_coord2[0]-g_coord1[0]));
}

// Converte coordinate pixel sulla mappa in coordinate geografiche
function mapGetCoordinateGeografiche(pix_x,pix_y,pix_width,pix_weight,g_extent) {
  var g_width,g_height;
  var g_Dx,g_Dy;
  var g_coord = new Number(2);
  g_width  = g_extent[1]-g_extent[0];
  g_height = g_extent[3]-g_extent[2];
  g_Dx = (g_width/pix_width)*pix_x;
  g_Dy = (g_height/pix_weight)*pix_y;
  g_coord[0] = Math.round((g_extent[0]+g_Dx)*100)/100;
  g_coord[1] = Math.round((g_extent[3]-g_Dy)*100)/100;
  return g_coord;
}

//SM
//Converte coordinate geografiche in coordinate pixel sulla mappa
function mapGetCoordinateMonitor (x_reale, y_reale, mapWidth, mapHeight, extent) {
	var retValue = new Number(2);
	var Dx = -extent[0] + eval(x_reale);
	retValue[0] = Math.round((Math.round  ((Dx / ((extent[1] - extent[0]) / mapWidth))*100)) / 100) ;
	var Dy = extent[3] - eval(y_reale);
	retValue[1]  = Math.round(Dy / ((extent[3] - extent[2]) / mapHeight));
	return retValue;
}


// Converte coordinate pixel sulla mappa in coordinate geografiche
function mapPixel2Coord(pix_x, pix_y) {
  var retval = new Number(2);
  var extent = mapGetExtent();
  var g_coord = new Number(2);
  var coord_width  = extent[1]-extent[0];
  var coord_height = extent[3]-extent[2];
  var Dx = (coord_width/mappaWidth)*(pix_x-mappaLeft);
  var Dy = (coord_height/mappaHeight)*(pix_y-mappaTop);
  retval[0] = Math.round((extent[0]+Dx)*100)/100;
  retval[1] = Math.round((extent[3]-Dy)*100)/100;
  return retval;
}

// estrae dal template l'extent corrente della mappa (in coordinate mappa)
function mapGetExtent() {
  var extent = new Number(4);
  extent[0] = 1 * document.processa.minX.value;
  extent[1] = 1 * document.processa.maxX.value;
  extent[2] = 1 * document.processa.minY.value;
  extent[3] = 1 * document.processa.maxY.value;
  return extent;
}

// clip zoom box layer to mouse coords
function mapReorderCoords() {
  var zbottom = 0;
  var zleft = 0;
  var zright = 0;
  var ztop = 0;
  if (x1 > x2) {
    zright = x1;
    zleft = x2;
  } else {
    zleft = x1;
    zright = x2;
  }
  if (y1 > y2) {
    zbottom = y1;
    ztop = y2;
  } else {
    ztop = y1;
    zbottom = y2;
  }
  if ((x1 != x2) && (y1 != y2)) {
    mapDrawZoomBox(zleft,ztop,zright,zbottom);
  }
  return false;
}

/** Queste due variabili mi servono per ricordare dove stava la division prima
 *  di spostarla per simulare il pan. */
var mapLeftPrePan;
var mapTopPrePan;

function mapMakePan() {
  var left = 0;
  var top = 0;
  var right = 0;
  var bottom = 0;
  var mouseString = "";
  x2 = mouseX;
  y2 = mouseY;
  window.status = mouseString;
  // calcolo spostamento relativo
  deltaX = (x2 - x1);
  deltaY = (y2 - y1);
  layerMove("theMap", mapLeftPrePan + deltaX, mapTopPrePan + deltaY);
  // nascondo la parte del layer che esce dall'area
  if (deltaX > 0) {
    left = 0;
    right = mappaWidth - deltaX;
  } else {
    left = -deltaX;
    right = mappaWidth;
  }
  if (deltaY > 0) {
    top=0;
    bottom = mappaHeight - deltaY;
  } else {
    top = -deltaY;
    bottom = mappaHeight;
  }
  layerClip2("theMap", left, top, right, bottom);
}

function mapStopPan(e) {
  panning = false;
  if (deltaX!=0 || deltaY!=0) {
    document.laMappa.src = ""; // il gif da' problemi a Flash
    layerClip2("theMap", 0, 0, mappaWidth, mappaHeight);
    layerMove("theMap",mapLeftPrePan,mapTopPrePan);
    document.processa.deltaX.value = -deltaX;
    document.processa.deltaY.value = -deltaY;
    toolLoad();
  }
}

function mapStartPan(e) {
  mapLeftPrePan = toolGetNumberWithoutPx(layerGetStyle('theMap').left);
  mapTopPrePan = toolGetNumberWithoutPx(layerGetStyle('theMap').top);
  winCursorPosition(e);
  x1 = mouseX;
  y1 = mouseY
  deltaX=0;
  deltaY=0;
  panning = true;
  return false;
}

function mapMakeZoomOut() {
  x1 = mouseX;
  y1 = mouseY;
  var g_coord1 = mapPixel2Coord(x1, y1);
  document.processa.x1.value = g_coord1[0];
  document.processa.y1.value = g_coord1[1];
  document.processa.x2.value = g_coord1[0];
  document.processa.y2.value = g_coord1[1];
  toolLoad();
}

function mapScalaZoom(factor)
{
  var extent = mapGetExtent();//minX,maxX,minY,maxY
  var oldwidth = extent[1]-extent[0]
  var newwidth = oldwidth*factor;
  var deltax = (oldwidth-newwidth)/2.0;
  var nminx = extent[0]+deltax;


  var oldheight = extent[3]-extent[2]
  var newheight = oldheight*factor;
  var deltay = (oldheight-newheight)/2.0;
  var nminy = extent[2]+deltay;

  mapGoToBookmark(nminx, nminx+newwidth, nminy, nminy+newheight); //minX,maxX,minY,maxY
}


/** FUNZIONI SPECIFICHE DI SIPC */

function mapMakeExtInfo1() {
  mapMakeZoomOut();
}
function mapMakeExtInfo2() {
  mapMakeZoomOut();
}

function toolDoRefreshImage() {
  alert("map.js toolDoRefreshImage(): funzione deprecata")
  //toolRefreshStart("refresh");
}

function mapDebugMessage(msg) {
  //UNCOMMENT FOR DEBUG: note that MainPage must have the field
  //document.forms.debugform.debugmsgs.value += (new Date()).getTime()+" "+msg+"\n";
};


/**
 * Chiamata ad infozoom sul template
 * @param _layeridsCSV 		gli ID dei layers (separati da virgole)
 * @param _whereCSV     	l'espressione SQL di selezione (separati da virgole)
 * @return
 */
function mapDoInfoZoom(_layeridsCSV, _whereCSV)
{
  var statoform = form_getStato();
  form_setAction("infozoom");
  document.processa.ZoomLayerId.value   = _layeridsCSV;
  document.processa.ZoomWhereClause.value = _whereCSV;
  toolLoad();
  form_restoreStato(statoform);
  return false;
}

/**
 * Setta il filtro di visualizzazione sui layers
 * @param _layeridsCSV 		gli ID dei layers (separati da virgole)
 * @param _whereCSV     	l'espressione SQL di selezione (separati da virgole)
 * @return
 */
function mapDoFiltraVisualizzazione(_layeridsCSV, _whereCSV)
{
  var statoform = form_getStato();
  form_setAction("refresh");
  document.processa.FiltroLayerIdsCSV.value   = _layeridsCSV;
  document.processa.FiltroWhereClausesCSV.value = _whereCSV;
  toolLoad();
  form_restoreStato(statoform);
  return false;
}
