/* Copyright 2005 Camptocamp SA. 
   Licensed under the GPL (www.gnu.org/copyleft/gpl.html) */

/**
 * Double clic parameters
 * (DblClick emulation is required for some browsers)
 */
dbl_click_delay = 200; // ms
dbl_click_tol = 3; // pixels
recentrar = "";
recentrarFlag = false;
/**
 * Min distance betwwen vertex when drawing lines
 * on mouse move event
 */
vertexDistance = 10;

/**
 *
 */
snappingDistance = 10;

/**
 * class names parameters (in concordance with css styles)
 */
// user defined class names for the drawing elements
layerCN = "layer";
vertexCN = "vertex";
linepointCN = "linepoint";
boxCN = "box";
boxfillCN = "boxfill";
polygonfillCN = "polygonfill";

// user defined status for the drawing elements
_OFF = "_off";
_SEL = "_selected";

/**
 * HTML ids in html page
 */
div_geo_id = "floatGeo"; // Geo coordinates
div_distance_id = "floatDistance"; // distance measure
div_surface_id = "floatSurface"; // surface measure
div_features_num_id = "features_num"; // total number of features
div_inserted_num_id = "inserted_features_num"; // number of inserted features
div_updated_num_id = "modified_features_num"; // number of updated features
div_deleted_num_id = "deleted_features_num"; // number of deleted features

/**
 * dhtml main object id
 */
 mainmapid = "map";
 var recenter;
 var mapminx = -89.0693075667;
 var mapminy = 15.38674;
 var mapmaxx = -68.76388564333;
 var mapmaxy = 26.758788;
/**
 * User defined functionnalities
 * Function called on window onload event
 */
createMap = function() {
  myform = document.forms['carto_form'];
  
  // create a new map object with a className as argument
  mainmap = new Map(mainmapid);
  mapconfig = new Config();
  mapconfig.Configurar();
  mainmap.geoTag = xGetElementById(div_geo_id);
  if (mainmap.geoTag != null) {
    mainmap.geoUnits = mainmap.geoTag.innerHTML;
    mainmap.geoTag.innerHTML = sprintf(mainmap.geoUnits, "_", "_");
    xShow(mainmap.geoTag);
  }
  mainmap.distanceTag = xGetElementById(div_distance_id);
  if (mainmap.distanceTag != null) {
    mainmap.distanceUnits = mainmap.distanceTag.innerHTML;
  }
  mainmap.surfaceTag = xGetElementById(div_surface_id);
  if (mainmap.surfaceTag != null) {
    mainmap.surfaceUnits = mainmap.surfaceTag.innerHTML;
  }

  initMap();

  mainmap.displayFeaturesCount();
  mainmap.snap(mainmapid);
  
  // initial selected tool
  if (typeof cw3_initial_selected_tool != "undefined") {
    // prevent interface failure if last selected tool is not available anymore, set tool to zoomin
    try {
      eval(cw3_initial_selected_tool);
    } catch (e) {
      mainmap.zoomin('map');
      if (toolbar_rendering != 'radio' ) {
        setActiveToolButton('zoomin');
      }
    }
  }
  
if(document.getElementById('Map_h').value.split('px')[0] != document.getElementById('s').value ||
	document.getElementById('Map_w').value.split('px')[0] != document.getElementById('p').value){
	Enviar(); 
}
else	
	myMask.hide();
  
};

/**
 * Store the values (coords and type) in the form
 * Used for the navigation tools (zoomin, zoomout, etc ...)
 * @param aFeature
 */
fillForm = function(aFeature) {
  if (typeof(aFeature) == 'undefined') {
      return; // prevents from an error when pressing enter in the label input
  }

  // TODO let the possibility to send more than one feature
  var coords = new String();
  for (var i=0;i<aFeature.vertices.length;i++) {
    coords += aFeature.vertices[i].x + "," + aFeature.vertices[i].y + ";";
  }
  coords = coords.substring(0, coords.length -1);
  switch (aFeature.type) {
    case "point" :
      var shapeType = "point";
      break;
    case "polyline" :
      var shapeType = "polyline";
      break;
    case "polygon" :
      var shapeType = "polygon";
      break;
    case "circle" :
      var shapeType = "circle";
      coords += ";" + aFeature.radius;
      break;
  }
  myform.selection_coords.value = coords;
  myform.selection_type.value = shapeType;
};

/**
 * Empty the inputs (coords and type) in the form
 */
emptyForm = function() {
  myform.selection_coords.value = "";
  myform.selection_type.value = "";
};


/**
 * Fills the feature form input with the edited features of the current layer
 */
storeFeatures = function() {
  /*for (var i=0;i < mainmap.currentLayer.features.length; i++) {
    var aFeature = mainmap.currentLayer.features[i];
    if (typeof(mainmap.editAttributeNames) != 'undefined') {
      for (var j = 0; j < mainmap.editAttributeNames.length; j++) {
        if (mainmap.editAttributeTypes[j] == "")
            continue;
        var input = eval("myform['edit_feature_" + aFeature.id + "[" + mainmap.editAttributeNames[j] + "]']");
        if (!validateFormInput(mainmap.editAttributeTypes[j], input.value)) {
          return false;
        }
      } 
    }
    if (aFeature.operation != 'undefined') {
      // guardar nombe
      createInput(myform, "edit_feature_" + aFeature.id + "[name]", Ext.get("salvarObj").getValue(), 'hidden');
      // store geometry
      createInput(myform, "edit_feature_" + aFeature.id + "[WKTString]", aFeature.getWKT(), 'hidden');
      // store operation
      createInput(myform, "edit_feature_" + aFeature.id + "[operation]", aFeature.operation, 'hidden');
    }
  }
  return true;*/
};

/**
 * Store the feature operation in the form
 */
setFeatureOperation = function(aFeature, operation) {
  aFeature.operation = operation;
  mainmap.displayFeaturesCount();
};

/**
 * Creates an form input
 * @param form form name
 * @param name name of the input
 * @param value value of the input
 */
createInput = function(elt, name, value, type) {

  if (type == 'textarea') {
    var input = createTextarea(name, value);
  } else {
    if (document.all) {
      var str = '<input type="' + type + '" name="' + name + '" value="' + value + '" />';
      var input = xCreateElement(str);
    }
    else {
      var input = xCreateElement("input");
      input.type = type;
      input.name = name;
      input.value = value;
    }
  }
  xAppendChild(elt, input);
  return input;
}

/**
 * Creates an form input
 * @param form form name
 * @param name name of the input
 * @param value value of the input
 */
createTextarea = function(name, value) {
  if (document.all) {
    var str = '<textarea id="' + name + '" name="' + name + '">';
    var input = xCreateElement(str);
  }
  else {
    var input = xCreateElement("textarea");
    input.name = name;
  }
  input.innerHTML = value;
  return input;
}

/**
 * Submits the form
 */
doSubmit = function() {
  Gestionar_CapasSeleccionables(elementos, "dosubmit");
  myform.submit();
};

computeDistance = function(aFeature) {
  var distance = aFeature.getLength();
 //distance = (factor == 1000) ? Math.round(distance /1000 * 100) / 100 : Math.round(distance);
  distance = (factor == 1000) ? (distance /1000 * 100) / 100 : distance;
  return distance;
}

computeSurface = function(aFeature) {
  var surface = aFeature.getArea();
  //surface = (factor == 1000) ? Math.round(surface / 1000000 * 10000) / 10000 : Math.round(surface);
  surface = (factor == 1000) ? (surface / 1000000 * 10000) / 10000 : surface;
  return surface;
}

removeTags = function(text) {
  return text.replace(/<\/?[^>]+(>|$)/g, "");
}

EventManager.Add(window, 'load', createMap, false);

/**
 * enable a tool in dhtml and on toolbar
 * @param string toolid
 * @param bool noToolbarCall, true to avoid activation of tool in toolbar
 */
function enableTool(toolid, noToolbarCall) {
  recenter = noToolbarCall;

  var currentTool = xGetElementById('tool').value;
  
  if(toolid.search("edit") == -1 && toolid != 'distance' && toolid != 'surface' && toolid != 'azimuth' && toolid != 'pdfrotate' && toolid != 'locT' &&
  	(toolid.search("edit") != -1 || currentTool == 'distance' ||currentTool == 'zoomin' || currentTool == 'zoomout' || currentTool == 'surface' || currentTool == 'azimuth' || currentTool == 'pdfrotate'|| currentTool == 'locT'))
	CerrarTab();
  
  recentrar  = currentTool;
  // dhtml activation
  try {

     /*--------------------  Para controlar el recentrado ---------------------------*/
     if(toolid =='recentrar')
     {
       document.getElementById("tool").value = "pan";
       recentrarFlag = true;
     }
     else
       recentrarFlag = false;
     /*------------------------------------------------------------------------------*/
       
     if(toolid =='fullextent')
     { 
	xGetElementById('full').innerHTML="<input id='fullextent.x' type='hidden' name='fullextent.x'/>"
	CartoWeb.trigger('Location.FullExtent', "doSubmit()", {source: 'map'});
     }
     else{
      eval("mainmap."+toolid+"('map');");
     }   
  } catch (e) {
    // the tool not available, using current tool
    toolid = currentTool;
  }
  // toolbar activation
  if(toolid!='fullextent'){
	if(!noToolbarCall){      
		if (toolbar_rendering != 'radio' && xGetElementById(toolid+'_icon').lang.indexOf('cw_stateless') == -1) 
		{ 
		 setActiveToolButton(toolid);
		}
	}
  }
}

Map.prototype.snap = function(aDisplay) {
  this.getDisplay(aDisplay).useSnapping =
    (typeof myform['snapping'] != "undefined" && myform['snapping'].checked)? true : false;
};

Map.prototype.resetMapEventHandlers = function() {
  if (this.onToolUnset != undefined) {
    this.onToolUnset();
  }
  polilinea=null;

  this.onToolUnset = undefined;
  this.onFeatureInput = undefined;
  this.onClic = undefined;
  this.onSelPoint = undefined;
  this.onFeatureChange = undefined;
  this.onNewFeature = undefined;
  this.onCancel = function() {
    createMap();
  }
  
  this.onMove = function(geoX, geoY) {
    // display geo coordinates
    if (this.geoTag)
      //this.geoTag.innerHTML = sprintf(this.geoUnits, Math.round(geoX), Math.round(geoY));
      /*var puntop = new Point();
      puntop.x=geoX;
      puntop.y=geoY; 
      var punto = window.fromLatLong(18, puntop);*/
	this.geoTag.innerHTML = mapconfig.printCoord(geoX, geoY);
  }
};
  
Map.prototype.displayFeaturesCount = function() {
  var div_features_num = xGetElementById(div_features_num_id);
  var div_inserted_num = xGetElementById(div_inserted_num_id);
  var div_updated_num = xGetElementById(div_updated_num_id);
  var div_deleted_num = xGetElementById(div_deleted_num_id);
  this.updateFeaturesCount();
  if (div_features_num != null)
    div_features_num.innerHTML = this.featuresNum;
  if (div_inserted_num != null)
    div_inserted_num.innerHTML = this.insertedNum;
  if (div_updated_num != null)
    div_updated_num.innerHTML = this.updatedNum;
  if (div_deleted_num != null)
    div_deleted_num.innerHTML = this.deletedNum;
};

/**
 * Tools specific functionnalities
 */
Map.prototype.selectionBox = function(aDisplay, ajaxAction) {
  this.resetMapEventHandlers();

  this.setCurrentLayer('drawing');
  this.getDisplay(aDisplay).setTool('sel.box');
  this.onSelBox = function(x1, y1, x2, y2) {
    myform.selection_coords.value = x1 + "," + y1 + ";" + x2 + "," + y2;
    myform.selection_type.value = "rectangle";
    //storeFeatures();
    CartoWeb.trigger(ajaxAction, "doSubmit()");
  }
};

Map.prototype.selectionPoint = function(aDisplay, ajaxAction) {
  this.resetMapEventHandlers();
  
  this.setCurrentLayer('drawing');
  this.getDisplay(aDisplay).setTool('sel.point');
  this.onSelPoint = function(x, y) {
    myform.selection_coords.value = x + "," + y;
    myform.selection_type.value = "point";
    //storeFeatures();
    CartoWeb.trigger(ajaxAction, "doSubmit()");
  }
}

/***** LOCATION ****/
Map.prototype.zoomout = function(aDisplay) {
  this.selectionPoint(aDisplay, 'Location.Zoom');
};

Map.prototype.zoomin = function(aDisplay) {
  this.selectionBox(aDisplay, 'Location.Zoom');
};

Map.prototype.fullextent = function(aDisplay) {
  doSubmit();
}

Map.prototype.pan = function(aDisplay) {
  this.resetMapEventHandlers();
  this.getDisplay(aDisplay).setTool('pan');
  mainmap.onPan = function(x, y) {
    myform.selection_coords.value = x + "," + y;
    myform.selection_type.value = "point";
    //storeFeatures();
    CartoWeb.trigger('Location.Pan', "doSubmit()", {source: 'map'});
  }
};

Map.prototype.recentrar = function(aDisplay) {
  this.resetMapEventHandlers();
  this.getDisplay(aDisplay).setTool('pan');
  mainmap.onPan = function(x, y) {
    myform.selection_coords.value = x + "," + y;
    myform.selection_type.value = "point";
    //storeFeatures();
    CartoWeb.trigger('Location.Pan', "doSubmit()", {source: 'map'});
  }    
};

Map.prototype.query_by_point = function(aDisplay) {
  this.selectionPoint(aDisplay, 'Query.Perform');
  this.getDisplay(aDisplay).docObj.style.cursor = "help";
};

Map.prototype.query_by_bbox = function(aDisplay) {
  this.selectionBox(aDisplay, 'Query.Perform');
  this.getDisplay(aDisplay).docObj.style.cursor = "help";
};
  
Map.prototype.query_by_polygon = function(aDisplay) {
  this.resetMapEventHandlers();
  this.setCurrentLayer('drawing');
  this.getDisplay(aDisplay).setTool('draw.poly');

  this.onNewFeature = function(aFeature) {
      this.onToolUnset();
  };
  this.onFeatureInput = this.onFeatureChange = function(aFeature) {
    fillForm(aFeature);
    CartoWeb.trigger('Query.Perform', "doSubmit()");
  };
  this.onToolUnset = function() {
    //clear the outline_poly's display layer
    this.getDisplay(aDisplay).clearLayer('drawing');
    this.onCancel();
  };
  this.onCancel = function() {
    emptyForm();
  };
};

Map.prototype.query_by_circle = function(aDisplay) {
  this.resetMapEventHandlers();
  this.setCurrentLayer('drawing');
  this.getDisplay(aDisplay).setTool('draw.circle');

  this.onNewFeature = function(aFeature) {
      this.onToolUnset();
  };
  this.onFeatureInput = this.onFeatureChange = function(aFeature) {
    fillForm(aFeature);
    CartoWeb.trigger('Query.Perform', "doSubmit()");
  };
  this.onToolUnset = function() {
    //clear the outline_poly's display layer
    this.getDisplay(aDisplay).clearLayer('drawing');
    this.onCancel();
  };
  this.onCancel = function() {
    emptyForm();
  };
};
/********Calculo de Distancia******/
function CalculoDistancia(aPolilinea)
{
  var dist=0;
  cantidad=aPolilinea.vertices.length;

 
   for(i=0;i<cantidad-1;i++)
          {
             punto = new Point();
             punto2 = new Point();	
	     punto.x=aPolilinea.vertices[i].x;
	     punto.y=aPolilinea.vertices[i].y; 
	     punto2.x=aPolilinea.vertices[i+1].x;
	     punto2.y=aPolilinea.vertices[i+1].y; 
             dist += mapconfig.CalculoDist(punto,punto2);
  	  }		
	
    
   return dist;
}
/*********Calculo de Area******/
function CalculoArea(aPolilinea)
{
  var area = 0;
  var punto;
  var puntop;
  var punto2;
  cantidad=aPolilinea.vertices.length;
  if (cantidad > 1) {
     for (i = 0; i<cantidad - 1;i++)
     {
       puntop = new Point();
       puntop.x=aPolilinea.vertices[i].x;
       puntop.y=aPolilinea.vertices[i].y; 
       punto = GD2UTM(puntop.x, puntop.y);
       puntop.x=aPolilinea.vertices[i+1].x;
       puntop.y=aPolilinea.vertices[i+1].y; 
       punto2 = GD2UTM(puntop.x, puntop.y);
       area += punto.x * punto2.y - punto2.x * punto.y;
     }
     puntop = new Point();
     puntop.x = aPolilinea.vertices[aPolilinea.vertices.length -1].x;
     puntop.y = aPolilinea.vertices[aPolilinea.vertices.length -1].y; 
     punto = GD2UTM(puntop.x, puntop.y);
     puntop.x=aPolilinea.vertices[0].x;
     puntop.y=aPolilinea.vertices[0].y; 
     punto2 = GD2UTM(puntop.x, puntop.y);  
     area += punto.x * punto2.y - punto2.x * punto.y;
    
     area =  ConvUnidAre(Math.abs(area) / 2);
     
     return area;
  } 
  else 
  {
    return 0;
  }
}

/***** STATICTOOLS ****/
Map.prototype.locT = function(aDisplay) {
	this.resetMapEventHandlers();
	fLocalizacionT();
}

Map.prototype.distance = function(aDisplay) {
  this.resetMapEventHandlers();
  this.setCurrentLayer('distance');
  this.getDisplay(aDisplay).setTool('draw.line');
  this.getDisplay(aDisplay).useSnapping = false;
  this.onMove = function(x,y) {
    if(polilinea){
       puntop = new Point();
       punto2 = new Point();
       polin = polilinea.vertices.last();
       puntop.x = polin.x;
       puntop.y = polin.y; 
       //punto = GD2UTM(puntop.x, puntop.y);
       punto2.x = x;
       punto2.y = y; 
      
       var distance = mapconfig.CalculoDist(puntop,punto2);	
       //var distance = mapconfig.CalculoDistEsferica(puntop,punto2);    
       distance = ConvUnidLon(distance); 
       mapconfig.printDistancia(distance);
    }
    if (this.geoTag){
       /*this.geoTag.innerHTML = sprintf(this.geoUnits, x, y);
       var puntop = new Point();
       puntop.x=geoX;
       puntop.y=geoY; 
       var punto = GD2UTM(16, puntop);*/
       this.geoTag.innerHTML = mapconfig.printCoord(geoX, geoY);
       }
  }
  this.onClic = function(aFeature) {
    polilinea=aFeature;
    //distance = computeDistance(aFeature);
    //fCalculoDistancia.findById('distacumulada').setValue(distance);
    distance=CalculoDistancia(aFeature);
    distance = ConvUnidLon(distance);
    mapconfig.printDistanciaA(distance); 
    this.distanceTag.innerHTML = sprintf(this.distanceUnits, distance);
    this.distanceTag.style.display = "block";
    if (this.distanceTag.style.position == "absolute")
      xMoveTo(this.distanceTag, mouse_x, mouse_y);
  }
  this.onNewFeature = function(aFeature) {
    this.onToolUnset();
  };
  this.onFeatureInput = function(aFeature) {
    aFeature.operation = "";
  };
  this.onToolUnset = function() {
    //clear the distance's display layer
    this.getDisplay(aDisplay).clearLayer('distance');
    this.onCancel();
  };
  this.onCancel = function(aFeature) {
    this.distanceTag.style.display = "none";
  };
};
 
Map.prototype.surface = function(aDisplay) {
  this.resetMapEventHandlers();
  this.setCurrentLayer('surface');  
  this.getDisplay(aDisplay).setTool('draw.poly');
  this.getDisplay(aDisplay).useSnapping = false;
  this.onClic = function(aFeature) {
    if (typeof aFeature == 'undefined') {
        return;
    }
    var surface = mapconfig.CalcularArea(aFeature);
    var perimetro = CalculoDistancia(aFeature);
    if ((aFeature.vertices.length > 2 ) && (surface > 0) ){
       perimetro += mapconfig.CalculoDist(aFeature.vertices.last(),aFeature.vertices.first());       
    }
    perimetro = ConvUnidLon(perimetro);
    surface = ConvUnidAre(surface);
    mapconfig.printPerimetro(perimetro);
    mapconfig.printArea(surface);
    //document.getElementById('superficie').innerHTML='<span>Superficie: '+ surface +'</span>';
    //document.getElementById('perimetro').innerHTML='<span>Per&iacute;metro: '+ perimetro +'</span>';
   // fcalculoArea.findById('superficie').setValue(surface);
   // fcalculoArea.findById('perimetro').setValue(perimetro);
    this.surfaceTag.innerHTML = sprintf(this.surfaceUnits, surface);
    this.surfaceTag.style.display = "block";
    if (this.surfaceTag.style.position == "absolute")
      xMoveTo(this.surfaceTag, mouse_x, mouse_y);
  }
  this.onNewFeature = function(aFeature) {
    this.onToolUnset();
  };
  this.onFeatureInput = function(aFeature) {
    aFeature.operation = "";
  };
  this.onToolUnset = function() {
    //clear the surface's display layer
    this.getDisplay(aDisplay).clearLayer('surface');
    this.onCancel();
  };
  this.onCancel = function(aFeature) {
    this.surfaceTag.style.display = "none";
  };
};

/*******************Azimuth**************************/
Map.prototype.azimuth = function(aDisplay){
  this.resetMapEventHandlers();
  this.setCurrentLayer('azimuth');
  this.getDisplay(aDisplay).setTool('draw.azimuth');
  this.getDisplay(aDisplay).useSnapping = false;
  this.onMove = function(x,y) {
    if(polilinea){
      ptoR = new Point();  
      ptoO = polilinea.vertices.last();
      ptoR.x = x;
      ptoR.y = y;
    
    if(polilinea.vertices.length < 2)	
      	mapconfig.CalculoAzimuth(ptoO, ptoR);
      	
    }  
	 
    if (this.geoTag){
            this.geoTag.innerHTML = mapconfig.printCoord(geoX, geoY);
       }
    }
  
  this.onClic = function(aFeature) {
    if(typeof(dblclick) == "undefined"){
    	polilinea=aFeature;
    	count = polilinea.vertices.length;
    }
    
    //**********************************************dibujar solo 2 puntos
    if(count == 2){
	this.getDisplay(aDisplay).mouseAction.onDblClick(this.getDisplay(aDisplay));
    }

    if(polilinea.vertices.length >= 2){
      ptoO = polilinea.vertices[count - 2];
      ptoR = polilinea.vertices[count - 1];
    }
    else{
      ptoO = polilinea.vertices[0];
      ptoR = polilinea.vertices[0];
    }
    mapconfig.CalculoAzimuth(ptoO, ptoR);
    
    this.distanceTag.style.display = "block";
    if (this.distanceTag.style.position == "absolute")
      xMoveTo(this.distanceTag, mouse_x, mouse_y);
  }
  this.onNewFeature = function(aFeature) {
    this.onToolUnset();
  };
  this.onFeatureInput = function(aFeature) {
    //aFeature.operation = "";
  };
  this.onToolUnset = function() {
    //clear the distance's display layer
    this.getDisplay(aDisplay).clearLayer('azimuth');
    this.onCancel();
  };
  this.onCancel = function(aFeature) {
    this.distanceTag.style.display = "none";
  };
};


Map.prototype.azimuth1 = function(aDisplay){
  this.resetMapEventHandlers();
  this.setCurrentLayer('azimuth');
  this.getDisplay(aDisplay).setTool('draw.line');
  this.getDisplay(aDisplay).useSnapping = false;
    
  this.onClic = function(aFeature) {
       if (typeof aFeature == 'undefined') {
        return;
    }
  }
  this.onNewFeature = function(aFeature) {
    this.onToolUnset();
  };
  this.onFeatureInput = function(aFeature) {
    aFeature.operation = "";
    VCalcularpoligonal(aFeature);	
  };
  this.onToolUnset = function() {
    //clear the distance's display layer
    this.getDisplay(aDisplay).clearLayer('azimuth');
    this.onCancel();
  };
  this.onCancel = function(aFeature) {
    this.distanceTag.style.display = "none";
  };
};
/***** OUTLINE ****/
Map.prototype.outline_circle = function(aDisplay) {
  this.resetMapEventHandlers();
  this.setCurrentLayer('outline_poly');
  this.getDisplay(aDisplay).setTool('draw.circle');

  this.onNewFeature = function(aFeature) {
      this.onToolUnset();
  };
  this.onFeatureInput = this.onFeatureChange = function(aFeature) {
    fillForm(aFeature);
    if (typeof addLabel == 'undefined')
      doSubmit();
    else {
      if (displayMeasures) {
        var surface = sprintf(this.surfaceUnits, computeSurface(aFeature));
        addLabel(removeTags(surface), mouse_x, mouse_y);
      } else {
        addLabel(circleDefaultLabel, mouse_x, mouse_y);
      }
    }
  };
  this.onToolUnset = function() {
    //clear the outline_poly's display layer
    this.getDisplay(aDisplay).clearLayer('outline_poly');
    this.onCancel();
  };
  this.onCancel = function() {
    if (typeof hideLabel != 'undefined')
      hideLabel();
    emptyForm();
  };
};

Map.prototype.outline_poly = function(aDisplay) {
  this.resetMapEventHandlers();
  this.setCurrentLayer('outline_poly');
  this.getDisplay(aDisplay).setTool('draw.poly');

  this.onNewFeature = function(aFeature) {
      this.onToolUnset();
  };
  this.onFeatureInput = this.onFeatureChange = function(aFeature) {
    fillForm(aFeature);
    if (typeof addLabel == 'undefined')
      doSubmit();
    else {
      if (displayMeasures) {
        var surface = sprintf(this.surfaceUnits, computeSurface(aFeature));
        addLabel(removeTags(surface), mouse_x, mouse_y);
      } else {
        addLabel(polyDefaultLabel, mouse_x, mouse_y);
      }
    }
  };
  this.onToolUnset = function() {
    //clear the outline_poly's display layer
    this.getDisplay(aDisplay).clearLayer('outline_poly');
    this.onCancel();
  };
  this.onCancel = function() {
    if (typeof hideLabel != 'undefined')
      hideLabel();
    emptyForm();
  };
};

Map.prototype.outline_line = function(aDisplay) {
  this.resetMapEventHandlers();
  this.setCurrentLayer('outline_line');
  this.getDisplay(aDisplay).setTool('draw.line');

  this.onNewFeature = function(aFeature) {
      this.onToolUnset();
  };
  this.onFeatureInput = this.onFeatureChange = function(aFeature) {
    fillForm(aFeature);
    if (typeof addLabel == 'undefined')
      doSubmit();
    else {
      if (displayMeasures) {
        var distance = sprintf(this.distanceUnits, computeDistance(aFeature));
        addLabel(removeTags(distance), mouse_x, mouse_y);
      } else {
        addLabel(lineDefaultLabel, mouse_x, mouse_y);
      }
    }
  };
  this.onToolUnset = function() {
    //clear the outline_poly's display layer
    this.getDisplay(aDisplay).clearLayer('outline_line');
    this.onCancel();
  };
  this.onCancel = function() {
    if (typeof hideLabel != 'undefined')
      hideLabel();
    emptyForm();
  };
};

/**
  * Construye una feature a partir del box dibujado manualmente
  * @param aDisplay display object
  * @author Armando Batista
  */
Map.prototype.temp_rectangle = function(aDisplay) {
  this.resetMapEventHandlers();
  this.setCurrentLayer('drawing');
  if (Ext.getCmp('btnSeleccionarAreaProp').pressed == true)
      this.getDisplay(aDisplay).setTool('draw.proportionalbox');
  else
      this.getDisplay(aDisplay).setTool('draw.box');

  this.onNewFeature = function(aFeature) {
    this.onToolUnset();
  };
  this.onToolUnset = function() {
    //clear the outline_poly's display layer
    this.getDisplay(aDisplay).clearLayer('temp_rectangle');
    emptyForm();
  };
  this.onFeatureInput = this.onFeatureChange = function(aFeature) {
    fillForm(aFeature);
    var coordcad = document.getElementById('selection_coords').value;
    coordObj = coordcad.split(";");
    var feature = this.getPdfFeature(aDisplay);
    this.drawbox2PdfFeature(feature, aDisplay, coordObj);

    var dist_x = feature.vertices[1].x - feature.vertices[2].x;
    var dist_y = feature.vertices[1].y - feature.vertices[2].y;
    var medidaH = Math.sqrt(dist_x * dist_x + dist_y * dist_y);
    medidaH = medidaH*30*3600*1000;
    dist_x = feature.vertices[1].x - feature.vertices[0].x;
    dist_y = feature.vertices[1].y - feature.vertices[0].y;
    var medidaV = Math.sqrt(dist_x * dist_x + dist_y * dist_y);
    medidaV = medidaV*30*3600*1000;

    myform.medidaH_box.value = medidaH;
    myform.medidaV_box.value = medidaV;

    actualizarEscalaPdf();

    // enviar las coordenadas del centro (Feature.getCentroid)
    // y el angulo al formulario
    var center = aFeature.getCentroid();
    myform.pdfMapCenterX.value = center.vertices[0].x;
    myform.pdfMapCenterY.value = center.vertices[0].y;

    // actualizar la interfaz
    myform.pdfMapAngle.value = "0";
    aDisplay.angle = 0;
    updatePdfAngleInterface(0);

    this.getDisplay(aDisplay).clearLayer('drawing');
    this.showPdfFeature("map");
    mainmap.pdfrotate("map");

    var btnToggle = Ext.getCmp('btnSeleccionarArea');
    btnToggle.toggle(false);
    Ext.getCmp('btnSeleccionarAreaProp').toggle(false);
    validaPdfXCoordInterface();
  };
};

Map.prototype.outline_rectangle = function(aDisplay) {
  this.resetMapEventHandlers();
  this.setCurrentLayer('outline_rectangle');
  this.getDisplay(aDisplay).setTool('draw.box');

  this.onNewFeature = function(aFeature) {
      this.onToolUnset();
  };
  this.onFeatureInput = this.onFeatureChange = function(aFeature) {
    fillForm(aFeature);
    if (typeof addLabel == 'undefined')
      doSubmit();
    else {
      if (displayMeasures) {
        var surface = sprintf(this.surfaceUnits, computeSurface(aFeature));
        addLabel(removeTags(surface), mouse_x, mouse_y);
      } else {
        addLabel(rectangleDefaultLabel, mouse_x, mouse_y);
      }
    }
  };
  this.onToolUnset = function() {
    //clear the outline_poly's display layer
    this.getDisplay(aDisplay).clearLayer('outline_rectangle');
    this.onCancel();
  };
  this.onCancel = function() {
    if (typeof hideLabel != 'undefined')
      hideLabel();
    emptyForm();
  };
};
  
Map.prototype.outline_point = function(aDisplay) {
  this.resetMapEventHandlers();
  this.setCurrentLayer('outline_point');
  this.getDisplay(aDisplay).setTool('draw.point');

  this.onNewFeature = function(aFeature) {
      this.onToolUnset();
  };
  this.onFeatureInput = this.onFeatureChange = function(aFeature) {
    fillForm(aFeature);
    if (typeof addLabel == 'undefined')
      doSubmit();
    else {
      if (displayMeasures) {
        addLabel('', mouse_x, mouse_y);
      } else {
        addLabel(pointDefaultLabel, mouse_x, mouse_y);
      }
    }
  };
  this.onToolUnset = function() {
    //clear the outline_poly's display layer
    this.getDisplay(aDisplay).clearLayer('outline_point');
    this.onCancel();
  };
  this.onCancel = function() {
    if (typeof hideLabel != 'undefined')
      hideLabel();
    emptyForm();
  };
};

/**** adjustMapsize ****/

frameWidth = function() {

    if (window.innerWidth)
        return window.innerWidth;
    else if (document.body && document.body.offsetWidth)
        return document.body.offsetWidth;
    else
        return 0;
};

frameHeight = function() {

    if (window.innerHeight) 
        return window.innerHeight;
    else if (document.body && document.body.offsetHeight)
        return document.body.offsetHeight;
    else
        return 0;
};

Map.prototype.adjust_mapsize = function(aDisplay) {
    
    /**** header (200) - layertree (300) ****/

    var h = frameHeight() - 200;
    var w = frameWidth() - 330;

    cartoForm = document.forms['carto_form'];

    cartoForm.customMapsize.value = w + "x" + h;

    doSubmit();
}

Map.prototype.linkit = function(aDisplay) {
    var linkbox = xGetElementById('linkItBox');
    if (linkbox.style.display == 'none') {
        // warning: requires prototypejs lib
        new Ajax.Request(linkItRequestUrl, {
          method: 'get',
          onSuccess: function(transport) {
            linkbox.innerHTML = transport.responseText;
            xGetElementById('linkItUrl').select();
          }
        });
        
        linkbox.style.display = 'block';
    } else {
        linkbox.style.display = 'none';
    }
}
//************************ perfil *****************************************************************
//---------------------------------------------- Llamada de la Herramienta ----------------------
Map.prototype.perfil = function(aDisplay) 
{
	//-----------------------------------------------------
	this.resetMapEventHandlers();
	//----- Dibujar Herramienta de Seleccion ------------------------------------------------
	this.getDisplay(aDisplay).setTool('draw.line');
	this.getDisplay(aDisplay).useSnapping = false;
	//----- Control de Eventos sobre el Mapa ------------------------------------------------
	//-------------------------- Enento: onMove (control de movimiento de mouse)-------------
	this.onMove = function(x,y) 
	{
		if(polilinea)
		{
			Actual_x = x; 
			Actual_y = y;
		}
		if (this.geoTag)
		{
			Actual_x = x; 
			Actual_y = y; 
			this.geoTag.innerHTML = mapconfig.printCoord(geoX, geoY);
		}
 	};
	//-------------------------- Enento: onMove -------------------
	this.onClic = function(aFeature) 
	{	//---- Controla la accion del click izquierdo	
		polilinea=aFeature;
 	};
	//-------------------------- Enento: onNewFeature -------------
 	this.onNewFeature = function(aFeature) 
	{	//---- Controla la accion iniciar el uso de la herramienta
 		this.onToolUnset();
 	};
	//-------------------------- Enento: onFeatureInput -----------
 	this.onFeatureInput = function(aFeature) 
	{	//---- Controla la accion del doble click izquierdo
 		aFeature.operation = "";
		CartoWeb.trigger("Perfil.Perform");
	};
	//-------------------------- Enento: onToolUnset --------------
	this.onToolUnset = function() 
	{	//---- Controla la accion de desseleccion de la herramienta
 		this.getDisplay(aDisplay).clearLayer('perfil');
 		this.onCancel();
 	};
	//-------------------------- Enento: onCancel -----------------var Itr = 1;
 	this.onCancel = function(aFeature) 
	{	//---- Controla la accion de cancelar el uso de la herramienta
		this.distanceTag.style.display = "none";
 	};
};

//************************ Rutas **********************************

Map.prototype.routing = function(aDisplay) {
   this.resetMapEventHandlers();
   CartoWeb.trigger("Routing.Perform","doSubmit()");
};
Map.prototype.routing_reset = function(aDisplay) {
   this.resetMapEventHandlers();
   CartoWeb.trigger("Routing.Reset", "doSubmit()");
};
Map.prototype.routing_start = function(aDisplay) {
this.resetMapEventHandlers();
this.setCurrentLayer('routing');
this.getDisplay(aDisplay).setTool('draw.point');
this.getDisplay(aDisplay).useSnapping = false;
this.onClic = function(x,y) {
     xGetElementById('coordxorig').value = geoX;
		 xGetElementById('coordyorig').value = geoY;
		 };
this.onNewFeature = function(aFeature) {
    this.onToolUnset();
  };
this.onFeatureInput = function(aFeature) {
    aFeature.operation = "";
  };
this.onToolUnset = function() {
    this.getDisplay(aDisplay).clearLayer('routing');
    this.onCancel();
  };
this.onCancel = function(aFeature) {
    this.distanceTag.style.display = "none";
  };
};
Map.prototype.routing_end = function(aDisplay) {
this.resetMapEventHandlers();
this.setCurrentLayer('routing');
this.getDisplay(aDisplay).setTool('draw.point');
this.getDisplay(aDisplay).useSnapping = false;
this.onClic = function() {
   	 xGetElementById('coordxdest').value = geoX;
		 xGetElementById('coordydest').value = geoY;
		 }
this.onNewFeature = function(aFeature) {
    this.onToolUnset();
  };
this.onFeatureInput = function(aFeature) {
    aFeature.operation = "";
  };
this.onToolUnset = function() {
    this.getDisplay(aDisplay).clearLayer('routing');
    this.onCancel();
  };
this.onCancel = function(aFeature) {
    this.distanceTag.style.display = "none";
  };
};

//***************************************************************


