var _region;
var _curLatLonShape=0;//salva el poligono actual dibujado
var curBoton="OFF";
var warning;
var mini_map=true;
var search_map=true;
var res_original=screen.width;
var resolucion_w=978;
var resolucion_w_search=300;
var _curTool='_pan';

if(res_original>=1280 && res_original<1440){
	resolucion_w=1224;
	resolucion_w_search=400;
	if(document.getElementById('layout_estilo_resolucion'))
		document.getElementById('layout_estilo_resolucion').href='includes/css/resolucion/1280x720/layout.css';
}else{
	if(res_original>=1440 && res_original<1680){
		resolucion_w=1300;
		resolucion_w_search=450;
		if(document.getElementById('layout_estilo_resolucion'))
			document.getElementById('layout_estilo_resolucion').href='includes/css/resolucion/1440x900/layout.css';
	}else{
		if(res_original>=1680 && res_original<1920){
			resolucion_w=1440;
			resolucion_w_search=500;
			if(document.getElementById('layout_estilo_resolucion'))
				document.getElementById('layout_estilo_resolucion').href='includes/css/resolucion/1680x1050/layout.css';
		}else{
			if(res_original>=1920){
				resolucion_w=1680;
				resolucion_w_search=550;
				if(document.getElementById('layout_estilo_resolucion'))
					document.getElementById('layout_estilo_resolucion').href='includes/css/resolucion/1920x1080/layout.css';
			}
		}
	}
}

var w_map_container=resolucion_w-20;


var _dist=document.createElement("DIV");
	_dist.style.display="none";
	_dist.id="divDistance";
	_dist.style.position = 'absolute';
	_dist.style.backgroundColor="#FFFFE1";
	_dist.style.border="thin solid black";




function points2shape(vector)
{

	var newPoints=vector;
	//alert(vector);
	var lat=0,long=0;
	
	if (vector.length==2)//si es de 2 dimensiones hablamos de un rectangulo, hay q buscarlos los 4 puntos
	{
		
		newPoints=[new VELatLong(vector[0].Latitude,vector[0].Longitude),
													new VELatLong(vector[1].Latitude,vector[0].Longitude),
													new VELatLong(vector[1].Latitude,vector[1].Longitude),        
													new VELatLong(vector[0].Latitude,vector[1].Longitude)]

	}
		
		//alert(newPoints);
		//newPoints=newPoints.replace(' ','');
		try{slDrawing.DeleteShape(tempShape);slDrawing.DeleteShape(myCurrentShape);}catch(err){}
		myCurrentShape = new VEShape(VEShapeType.Polygon, newPoints);
		myCurrentShape.Id="theShape";
		//alert('1 '+myCurrentShape.Latitude+' , '+myCurrentShape.Longitude);
		if(myCurrentShape.Latitude==0 && myCurrentShape.Longitude==0){
			for(var i=0; i<vector.length; i++){
					//alert(vector[i].Latitude+' , '+vector[i].Longitude)
					lat+=parseFloat(vector[i].Latitude);
					long+=parseFloat(vector[i].Longitude);
					//alert(lat+' , '+long);
			}
			myCurrentShape.Latitude=lat/vector.length;
			myCurrentShape.Longitude=long/vector.length;
		}
		//alert('2 '+myCurrentShape.Latitude+' , '+myCurrentShape.Longitude);
		try{slDrawing.AddShape(myCurrentShape);}catch(err){}
		//alert('paso');
		myCurrentShape.HideIcon();
	
}

function points2shape2(vector,color,lcolor)
{
	var newPoints=vector;
	var lat=0,long=0;
	
	if (vector.length==2)//si es de 2 dimensiones hablamos de un rectangulo, hay q buscarlos los 4 puntos
	{
		
		newPoints=[new VELatLong(vector[0].Latitude,vector[0].Longitude),
													new VELatLong(vector[1].Latitude,vector[0].Longitude),
													new VELatLong(vector[1].Latitude,vector[1].Longitude),        
													new VELatLong(vector[0].Latitude,vector[1].Longitude)]

	}
		
		//alert(newPoints);
		var myCurrentShape2 = new VEShape(VEShapeType.Polygon, newPoints);
		myCurrentShape2.Id="theShape2";
		//alert('1 '+myCurrentShape.Latitude+' , '+myCurrentShape.Longitude);
		if(myCurrentShape2.Latitude==0 && myCurrentShape2.Longitude==0){
			
			for(var i=0; i<vector.length; i++){
					//alert(vector[i].Latitude+' , '+vector[i].Longitude)
					lat+=parseFloat(vector[i].Latitude);
					long+=parseFloat(vector[i].Longitude);
					//alert(lat+' , '+long);
			}
			myCurrentShape2.Latitude=lat/vector.length;
			myCurrentShape2.Longitude=long/vector.length;
		}
		myCurrentShape2.SetFillColor(new VEColor(255,255,255,0.0));
		myCurrentShape2.SetLineColor(new VEColor(255,255,255,1.0));
		myCurrentShape2.SetLineWidth(1);
		myCurrentShape2.SetLineToGround(true);
		myCurrentShape2.SetMinZoomLevel(1);
		//myCurrentShape2.SetMaxZoomLevel(10);

		//alert('2 '+myCurrentShape.Latitude+' , '+myCurrentShape.Longitude);
		try{slDrawing.AddShape(myCurrentShape2);}catch(err){}
		//alert('paso');
		myCurrentShape2.HideIcon();
		
	
}


//esta funcion se encarga de agregar el toolbar de dibujo al mapa
function ins_toolbar(adjust,tipo)
{
	var botaux='';
	
		//insertar toolbar al mapa || _mapTool y map son globales				
		_mapTool = document.createElement("div"); 
		_mapTool.id = "control_mapa_div";
		_mapTool.style.position = "absolute";
		_mapTool.style.margin =adjust+" 0px 0px 10px"; 
		//_mapTool.style.visibility='hidden';
		if(tipo=='search'){
			if(mini_map==true)
				botaux="<TD id=\"_maxmin\" class=\"d_maxmin\" onClick=\"_curTool='_maxmin';on_off()\" align=middle ></TD>";
			
			_mapTool.innerHTML = "<div id=\"pan_shape\">"+
			"<TABLE bgcolor=\"orange\" >  "+
			"<TR>"+
			"<TD id=\"_pan\" class=\"a_pan\" onClick=\"this.className ='a_pan';_curTool='_pan';on_off()\" align=middle width=80> </TD>"+
			"<TD  align=middle>&nbsp;</TD>"+
			"<TD id=\"_draw\" class=\"d_draw\" onClick=\"this.className ='a_draw';_curTool='_draw';on_off()\" align=middle width=80></TD>"+
			"<TD  align=middle>&nbsp;</TD>"+
			"<TD id=\"_poly\" class=\"d_poly\" onClick=\"this.className ='a_poly'; _curTool='_poly';on_off()\" align=middle ></TD>"+
			"<TD  align=middle>&nbsp;</TD>"+
			"<TD id=\"_clear\" style='width:80px;height:18px;cursor:pointer;cursor:hand;' onClick=\"_curTool='_clear';on_off()\" align=middle ><img src='img/reset_map.jpg' ></TD>"+
			botaux+
			"</TR>"+
			"</TABLE>"+
			"</div>";
		}else{
//alert(adjust+" | "+tipo);
			search_map=false;_curTool='_maxmin';
			_mapTool.innerHTML = "<div id=\"pan_shape\">"+
			"<TABLE bgcolor=\"orange\" >  "+
			"<TR>"+
			"<TD id=\"_maxmin\" class=\"d_maxmin\" onClick=\"on_off()\" align=middle ></TD>"+
			"</TR>"+
			"</TABLE>"+
			"</div>";
		}
	map.AddControl(_mapTool);	
	
}

//==============================================================
//FUNCIONES PARA DIBUJAR POLIGONO
//==============================================================

var slDrawing = new VEShapeLayer();
var slDrawingBorder = new VEShapeLayer();
var myGeomType = "polygon";
var myCurrentShape = null;
var myPoints = new Array();
var myDistance = 0;
var tempShape = null;
var tempPoints = null;
var tempDistance = 0;
var myCirclePoints = null;
var tempCircle = null;


function DrawPolyMouseClick(e)
{
    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(x, y);
    var LL = map.PixelToLatLong(pixel);    
	
	if (myPoints.length == 0 && myGeomType != "point") 
    {
        map.DetachEvent("onmousemove", MouseMove);
        map.AttachEvent("onmousemove", DrawPolyMouseMove);
		map.AttachEvent("onkeypress", KeyPressedMap);
        if(document.getElementById("divDistance"))
			document.getElementById("divDistance").style.visibility = "visible";
		_dist.style.display="block";
    }    

        myPoints.push(LL);
        myDistance = myDistance + tempDistance;    

        document.getElementById("mymapcontroldiv").style.cursor='crosshair';
		try{slDrawing.DeleteShape(myCurrentShape);}catch(err){}
   
}

//==============================================================

function MouseMove(e)
{
    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(x, y);
    var LL = map.PixelToLatLong(pixel);
	window.status="Latitude->"+LL.Latitude+" | Longitude->"+LL.Longitude;
}

function KeyPressedMap(e){
	var kC  = (window.event) ?    // MSIE or Firefox?
		event.keyCode : e.keyCode;
	var Esc = (window.event) ?   
		27 : e.DOM_VK_ESCAPE // MSIE : Firefox
		
	if(kC==Esc && myPoints.length>2){
        try
        {
            map.DetachEvent("onmousemove", DrawPolyMouseMove);
            document.getElementById("divDistance").style.visibility = "hidden";
			_dist.style.display="none";
            slDrawing.DeleteShape(tempShape);

        }
        catch (err)
        {
        }        

        myDistance = Math.round(myDistance * 1000) / 1000; //in KM

		points2shape(myPoints);

		//buscar en mysql esto
			var s="",_i=0;
			for( var data in myPoints ) 
			{
				if(data!='remove' && data!='indexOf'){
					if(_i>0) s+="/"; //siguiente lote
					s+=myPoints[data].Latitude +",";
					s+=myPoints[data].Longitude;
					_i++;
				}
			}
			_curLatLonShape=s;//document.getElementById("latlong").value=s;
			pre_ajax("_mapa_",document.getElementById("latlong"));		

			//			
			myGeomType = null;
			//myCurrentShape = null;
			myPoints = new Array();
			myDistance = 0;
			tempShape = null;
			tempPoints = null;
			//

        document.getElementById("mymapcontroldiv").style.cursor = 'http://maps.live.com/cursors/grab.cur';
    }

}
//==============================================================

function DrawPolyMouseMove(e)
{
    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(x-2, y+2);
    var LL = map.PixelToLatLong(pixel);


	tempPoints = myPoints.slice(0, myPoints.length);


   	tempPoints.push(LL);
   	tempDistance = getDistanceKM(tempPoints[myPoints.length-1], LL);
	if(_dist){
		_dist.style.left = (e.clientX-50) + "px";
		_dist.style.top = (e.clientY-50) + "px";
		_dist.innerHTML ="<span style='font-weight:bold'>"+ (Math.round((myDistance + tempDistance) * 1000) / 1000)+"</span>";
	}


	try
    {
        slDrawing.DeleteShape(tempShape);
    }
    catch (err)
    {
    }
    
    if (tempPoints.length == 2)
    {
        tempShape = new VEShape(VEShapeType.Polyline, tempPoints);
        tempShape.HideIcon();
        slDrawing.AddShape(tempShape);
    }
    
    if (tempPoints.length > 2)
    {
        tempShape = new VEShape(VEShapeType.Polygon, tempPoints);
        tempShape.HideIcon();
        slDrawing.AddShape(tempShape);
    }
}


//Actualizacion de poligono en el mapa para saved searches
function DrawPolySaved()
{     
	
	var mapa=document.getElementById("mymapcontroldiv");
	var objMiles=document.getElementById("milerg");
	
	warning.style.display="none";

	cntGps=0;
	cntSearch++;
	var county=curCounty;
	_allocateCounty(county);
	map.DeleteAllPushpins();
	
	
	
	if  (mapa.className!="mapon") {
		mapa.className="mapon"
		curBoton="AVG"
		ins_toolbar("320px","search");
	}
	
	//borramos poligonos existentes
	try
    {
        slDrawing.DeleteShape(myCurrentShape);
    }
    catch (err)
    {
		try
		{
			slDrawing.DeleteShape(tempShape);
		}
		catch (err)
		{
		}
    }
	//alert('Si llega aca');
	
	//leemos el poligono guardado previamente, si existe
	document.getElementById("latlong").value=_curLatLonShape;
	//alert(_curLatLonShape);
	if ( (curBoton=='AVG') && (_curLatLonShape!=0) ) 
	{
		//control_map("search",'noclear'); 
		var _xpoints=new Array();
		//alert(_curLatLonShape);
		for(x=0;x<_curLatLonShape.split("/").length;x++)
		{								//latitude	longitude
			//alert(_curLatLonShape.split("/")[x].split(",")[0]+', '+_curLatLonShape.split("/")[x].split(",")[1])
			_xpoints.push(new VELatLong(_curLatLonShape.split("/")[x].split(",")[0],_curLatLonShape.split("/")[x].split(",")[1]));
		}
		//alert(_xpoints);
		points2shape(_xpoints)
	}
	//init();
}


//Actualizacion de poligono en el mapa para saved searches
function DrawPolyStat(county)
{     
	
	var mapa=document.getElementById("mymapcontroldiv");
	var objMiles=document.getElementById("milerg");
	/*
	//warning.style.display="none";

	//cntGps=0;
	//cntSearch++;
	var county=curCounty;
	_allocateCounty(1);*/
	//slDrawing = new VEShapeLayer();
	
	
	
	if  (mapa.className!="mapon") {
		mapa.className="mapon"
		curBoton="AVG"
		ins_toolbar("320px","search");
	}
	
	//borramos poligonos existentes
	try
    {
        slDrawing.DeleteShape(myCurrentShape);
    }
    catch (err)
    {
		try
		{
			slDrawing.DeleteShape(tempShape);
		}
		catch (err)
		{
		}
    }
	//county=6;
	var ajax=nuevoAjax();
	ajax.open("POST", "mapasolocuadros.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("county="+county);

	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4)
		{
			var results=ajax.responseText;
			var rest = results.split('^');
			_curLatLonShape=new Array();
			
			for(var i=0; i<rest.length; i++){
				_curLatLonShape.push(rest[i]);
			}
			
			/*//Broward
			_curLatLonShape="26.335,-80.879/25.980,-80.875/25.980,-80.683/25.960,-80.683/25.960,-80.298/25.975,-80.298/25.975,-80.127/26.327,-80.085/26.327,-80.197/26.335,-80.222";
			var _xpoints=new Array();
			for(var i=0; i<_curLatLonShape.split('/').length; i++){
					_xpoints.push(new VELatLong(_curLatLonShape.split('/')[i].split(",")[0],_curLatLonShape.split('/')[i].split(",")[1]));
			}
			//alert(_xpoints);
			points2shape(_xpoints);*/
			
			for(var i=0; i<_curLatLonShape.length; i++){
				//leemos el poligono guardado previamente, si existe
				if ( (_curLatLonShape[i]!=0) ) 
				{
					//control_map("search",'noclear'); 
					var _xpoints=new Array();
					//alert(_curLatLonShape);
					for(x=0;x<_curLatLonShape[i].split("/").length;x++)
					{								//latitude	longitude
						//alert(new VELatLong(_curLatLonShape[i].split("/")[x].split(",")[0],_curLatLonShape[i].split("/")[x].split(",")[1]));
						_xpoints.push(new VELatLong(_curLatLonShape[i].split("/")[x].split(",")[0],_curLatLonShape[i].split("/")[x].split(",")[1].replace(' ','')));
					}
					//alert(_xpoints);
					points2shape2(_xpoints)
				}
			}
			
			_allocateCounty(county);
			
		}
	}
	
	
	//init();
}

function DrawPointStat(county)
{     
	
	var mapa=document.getElementById("mymapcontroldiv");
	var objMiles=document.getElementById("milerg");
	
	if  (mapa.className!="mapon") {
		mapa.className="mapon"
		curBoton="AVG"
		ins_toolbar("320px","search");
	}

	var ajax=nuevoAjax();
	//ajax.open("POST", "mapasolocuadros.php", true);
	ajax.open("POST", "mapasolopuntos.php", true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send("county="+county);

	ajax.onreadystatechange=function()
	{
		if (ajax.readyState==4)
		{
			var results=ajax.responseText;
			var rest = results.split('^');
			_curLatLonShape=new Array;
			
			for(var i=0; i<rest.length; i++){
				_curLatLonShape.push(rest[i]);
			}
			
			
			for(var i=0; i<_curLatLonShape.length; i++){
				
				//_curLatLonShape='27.9929820000,-80.8449500000/27.9629820000,-80.8149500000';
				
				//leemos el poligono guardado previamente, si existe
				//document.getElementById("latlong").value=_curLatLonShape;
				//alert(_curLatLonShape);
				if ( (_curLatLonShape[i]!=0) ) 
				{
					//control_map("search",'noclear'); 
					var _xpoints=new Array();
					//alert(_curLatLonShape);
					for(x=0;x<_curLatLonShape[i].split("/").length;x++)
					{								//latitude	longitude
						//alert(_curLatLonShape[i].split("/")[x].split(",")[0]+', '+_curLatLonShape[i].split("/")[x].split(",")[1])
						/*_curLatLonShape[i].split("/")[x].split(",")[0];
						_curLatLonShape[i].split("/")[x].split(",")[1];
						_xpoints.push(new VELatLong(_curLatLonShape[i].split("/")[x].split(",")[0],_curLatLonShape[i].split("/")[x].split(",")[1]));*/
						myCurrentShape = new VEShape(VEShapeType.Pushpin, new VELatLong(_curLatLonShape[i].split("/")[x].split(",")[0],_curLatLonShape[i].split("/")[x].split(",")[1]));
						myCurrentShape.Id="theShape";
            			myCurrentShape.SetDescription(_curLatLonShape[i].split("/")[x].split(",")[0]+', '+_curLatLonShape[i].split("/")[x].split(",")[1]+', parcelid: '+_curLatLonShape[i].split("/")[x].split(",")[2]);
						try{slDrawing.AddShape(myCurrentShape);}catch(err){}
					}
					//alert(_xpoints);
					//points2shape(_xpoints)
				}
			}
			
			/*for(var i=0; i<_curLatLonShape.length; i++){
				//leemos el poligono guardado previamente, si existe
				if ( (_curLatLonShape[i]!=0) ) 
				{
					//control_map("search",'noclear'); 
					var _xpoints=new Array();
					//alert(_curLatLonShape);
					for(x=0;x<_curLatLonShape[i].split("/").length;x++)
					{								//latitude	longitude
						//alert(_curLatLonShape.split("/")[x].split(",")[0]+', '+_curLatLonShape.split("/")[x].split(",")[1])
						_curLatLonShape[i].split("/")[x].split(",")[0];
						_curLatLonShape[i].split("/")[x].split(",")[1];
						_xpoints.push(new VELatLong(_curLatLonShape[i].split("/")[x].split(",")[0],_curLatLonShape[i].split("/")[x].split(",")[1]));
					}
					//alert(_xpoints);
					points2shape(_xpoints)
				}
			}*/
			/*for(var i=0; i<_curLatLonShape.length; i++){

				if ( (_curLatLonShape[i]!=0) ) 
				{
						myCurrentShape = new VEShape(VEShapeType.Pushpin, new VELatLong(_curLatLonShape[i].split(",")[0],_curLatLonShape[i].split(",")[1]));
						myCurrentShape.Id="theShape";
            			myCurrentShape.SetDescription(_curLatLonShape[i].split(",")[0]+', '+_curLatLonShape[i].split(",")[1]);
						try{slDrawing.AddShape(myCurrentShape);}catch(err){}
						//myCurrentShape.HideIcon();
					
				}
			}*/
			_allocateCounty(county);
			
		}
	}
}

function maxminlatlong(_xp){
	var maxLat=0;
	var maxLong=-1000;
	var minLat=1000;
	var minLong=1000;
	
	for(var i in _xp){
		if(_xp[i].Latitude>maxLat) maxLat=_xp[i].Latitude;
		if(_xp[i].Latitude<minLat) minLat=_xp[i].Latitude;
		
		if(_xp[i].Longitude>maxLong) maxLong=_xp[i].Longitude;
		if(_xp[i].Longitude<minLong) minLong=_xp[i].Longitude;
	}
	
	//alert('maxmin: '+maxLat+', '+maxLong+' / '+minLat+', '+minLong);
}

function borrarTodoMap(){
	map.DeleteAllShapes();
}

//calculate distance
function getDistanceKM(p1, p2) 
{
    p1Lat = latLonToRadians(p1.Latitude);
	p1Lon = latLonToRadians(p1.Longitude);
	
	p2Lat = latLonToRadians(p2.Latitude);
	p2Lon = latLonToRadians(p2.Longitude);	
	
	var R = 6371; // earth's mean radius in km
	var dLat  = p2Lat - p1Lat;
	var dLong = p2Lon - p1Lon;
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(p1Lat) * Math.cos(p2Lat) * Math.sin(dLong/2) * Math.sin(dLong/2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	var disKm = R * c;
	//var disMiles = disKm * 0.6214;	
	return (disKm);
}

//==============================================================

//-------------------------------------------------------- capture les coordonnées de la souris
function MouseCatch(e) {

			posx =  e.clientX-2;			
			posy = e.clientY-2;
			window.status='X: '+posx+' Y: '+posy;

}
	
/* ******** PLAN DE PRINCIPE DE TOUT L'BAZARD  *********************

    P.1 ----lineH---- P.2
     |                 |      ---------> X      
     |                 |     |                ligneH : top left width
     |                 |     |                ligneD : top left height
     |                 |     |                ligneB : top left width
   lineG             lineD   |                ligneG : top left height
     |                 |     |                
     |                 |     v                pour finir,
     |                 |     Y                on ne se sert pas des lignes !
     |                 |
    P.3 ----lineB---- P.4  
    
	pos1x = 0, pos1y = 0; ----------- position point 1
	posx=0, posy=0;       ----------- position point obtenu par le MouseCatch
	clic = 0;             ----------- numero du click 

******************************************************************* */

var  pos1x=pos1y=posx=posy=clic=nbre1=nbre2=0;
var map;
var _points=new Array();


function init() {	
	Z = document.getElementById('region').style;
	S = document.getElementById('4points').style;	
	Z.visibility=S.visibility='hidden';
	pos1x=pos1y=posx=posy=clic=nbre1=nbre2=0;
}
onload = init;

function raz() {
 init();
 }
 
var fini = false;
function termine() {
	fini = !fini;
	pos1x=pos1y=posx=posy=clic=nbre1=nbre2=0;
		Z.visibility='hidden';		
}

//-------------------------------------------------------- positionner les points
function posePoint(point,x,y) {      //                  point = 1 2 3 ou 4
	with(document.getElementById('point'+point).style) {
		top  = y+'px';
		left = x+'px';
		visibility='visible';
		}
}

// ----------------------- pour le lasso on doit garder le pointeur en dehors de la zone retenue (Mozilla)
function lasso(nom) {
 if((pos1x>0 && pos1y>0) && fini) {
	larg = ((posx-pos1x)>0)? posx-pos1x : pos1x-posx;
	haut = ((posy-pos1y)>0)? posy-pos1y : pos1y-posy;
	var somm = (posy>pos1y)? pos1y : posy;
	var gche = (posx>pos1x)? pos1x : posx;
	
	if( (haut-4)<0) haut=4;
	if( (larg-4)<0) larg=4;

	document.getElementById(nom).style.height= (haut-4)+'px';
	document.getElementById(nom).style.width = (larg-4)+'px';
	document.getElementById(nom).style.top = (somm+2)+'px'; 
	document.getElementById(nom).style.left= (gche+2)+'px';
	
/*	with(document.getElementById(nom).style) {
		top = somm+2+'px'; left= gche+2+'px';
		height= haut-4+'px'; width = larg-4+'px';
		}
*/	
	
	Z.visibility='visible';
	if(clic>1) S.visibility='visible';
	}
}
// ------------------------------ zone choisie et pose des points
function creeSelection(x,y) {

if((pos1x >= 0 || pos1y >= 0) && fini) {
	lasso('4points');
	}
}

// ---------------------------- points ds le champ coordonnŽe, terminer ou recommencer la selection
function clicage(e) {
	if(clic==0) {

		if (myCurrentShape) map.DeleteShape(myCurrentShape);
		myCurrentShape=null;		
		_points.length=0;
		_points.push(map.PixelToLatLong(new VEPixel(e.mapX, e.mapY)));
		Z.visibility=S.visibility='hidden';
		fini = !fini;
		}
	clic ++ ;
	if(clic==1 && fini) {
			pos1x = posx; 
			pos1y = posy; 
			nbre1 = posx+'-'+posy;
			}
	else {
			_points.push(map.PixelToLatLong(new VEPixel(e.mapX, e.mapY)));
			creeSelection(posx,posy); 
			fini = !fini;clic=0;
			
			var s=_points[0].Latitude +","	
			s+=_points[0].Longitude +"/"	
			s+=_points[1].Latitude +","	
			s+=_points[1].Longitude;
			_curLatLonShape=s;//document.getElementById("latlong").value=s;
			pre_ajax("_mapa_",document.getElementById("latlong"));
			
			_flip2shape();
		}
}


function _IniMAP()
{

	warning=document.getElementById("ErrorMSG")	

	map = new VEMap("mymapcontroldiv");  	
	map.LoadMap();
	map.Resize(w_map_container,350);
	map.AddShapeLayer(slDrawing);
	map.AddShapeLayer(slDrawingBorder);
	
	//DrawPolyStat('lake');
//
	document.body.appendChild(_dist);
	_dist.zIndex=-1;

	document.getElementById("latlong").value=_curLatLonShape;//leemos el poligono dibujado previamente, si existe
	//alert(_curLatLonShape);
	if ( (curBoton=='AVG') && (_curLatLonShape!=0) ) 
	{
		control_map("search",'noclear'); 
		var _xpoints=new Array();
		for(x=0;x<_curLatLonShape.split("/").length;x++)
		{								//latitude									 longitude
			_xpoints.push(new VELatLong(_curLatLonShape.split("/")[x].split(",")[0],_curLatLonShape.split("/")[x].split(",")[1]));
		}
		//alert(_xpoints);
		points2shape(_xpoints)
	}
	


}

//cambia el recuadro dibujado[DIV], por un objeto VeMap.Shape
function _flip2shape()
{

	if(_points.length>0)
	{
	
		var topleft=map.LatLongToPixel(_points[0]);
		var bottomright=map.LatLongToPixel(_points[1])		

			points2shape(_points);
/*         var shape = new VEShape(VEShapeType.Polygon, [new VELatLong(_points[0].Latitude,_points[0].Longitude),
													new VELatLong(_points[1].Latitude,_points[0].Longitude),
													new VELatLong(_points[1].Latitude,_points[1].Longitude),        
													new VELatLong(_points[0].Latitude,_points[1].Longitude)]);        
         
         var _xpoints=new Array();
         var _lastPoint=new VELatLong(_points[0].Latitude,_points[1].Longitude)
         var tempDistance=0;
         
          _xpoints.push(new VELatLong(_points[0].Latitude,_points[0].Longitude));
          _xpoints.push(new VELatLong(_points[1].Latitude,_points[0].Longitude));
          _xpoints.push(new VELatLong(_points[1].Latitude,_points[1].Longitude));
          _xpoints.push(new VELatLong(_points[0].Latitude,_points[1].Longitude));

         tempDistance += _getDistance(_xpoints[0], _xpoints[1]);
         tempDistance += _getDistance(_xpoints[1], _xpoints[2]);
         tempDistance += _getDistance(_xpoints[2], _xpoints[3]);
         tempDistance += _getDistance(_xpoints[3], _xpoints[0]);
         
         tempDistance=Math.round(tempDistance * 1000) / 1000;
                  
		//Set the info box         
		map.ClearInfoBoxStyles();         
		shape.SetTitle(tempDistance+" km.");
		shape.SetDescription("");
         
         //Set the line color
								//	 R G  B alpha        
         var lineColor = new VEColor(0,0,0,1);
         shape.SetLineColor(lineColor);
         
         //Set the line width
         var lineWidth = 1;
         shape.SetLineWidth(lineWidth);
         
         //Set the fill color
								//	 R G  B alpha
         var fillColor = new VEColor(0,0,255,0.2);
         shape.SetFillColor(fillColor);

         map.AddShape(shape);	
         shape.HideIcon();
		
		shape.Id="theShape";
		myCurrentShape=shape;
*/

         
         //resetear DIVS
         init();
        }
		
		return;



}

//  convert lat/long in degrees to radians
function latLonToRadians( point ) {
	return point * Math.PI / 180;	
}


//calculate distance
function _getDistance(p1, p2) 
{
    p1Lat = latLonToRadians(p1.Latitude);
	p1Lon = latLonToRadians(p1.Longitude);
	
	p2Lat = latLonToRadians(p2.Latitude);
	p2Lon = latLonToRadians(p2.Longitude);	
	
	var R = 6371; // earth's mean radius in km
	var dLat  = p2Lat - p1Lat;
	var dLong = p2Lon - p1Lon;
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(p1Lat) * Math.cos(p2Lat) * Math.sin(dLong/2) * Math.sin(dLong/2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	var disKm = R * c;
	//var disMiles = disKm * 0.6214;	
	return (disKm);
}

function Mouse_lasso(e)
{
	MouseCatch(e); lasso('region')
}

function Mouse_lasso2(e)
{
	MouseCatch(e); lasso('region')
}

function doNothing(){}

function DetachALL()
{
		map.DetachEvent("ondoubleclick",termine);	
		map.DetachEvent("onmousemove",Mouse_lasso);
		map.DetachEvent("onclick",clicage);
		if(_region) _region.detachEvent("onmousemove", Mouse_lasso2);
		
	    map.DetachEvent("onclick", DrawPolyMouseClick);
    	map.DetachEvent("onmousemove", MouseMove);	
        map.DetachEvent("onmousemove", DrawPolyMouseMove);
}

function on_off()
{	
	//alert("empieza: "+_curTool);			
	DetachALL();
	var mapa=document.getElementById("mymapcontroldiv");

	if( _curTool=="_draw" )
	{
		_region=document.getElementById("region");
		_region.attachEvent("onmousemove", Mouse_lasso2);		
		if (myCurrentShape) map.DeleteShape(myCurrentShape);
		myCurrentShape=null;

		map.vemapcontrol.EnableGeoCommunity(true);	
		map.AttachEvent("ondoubleclick", termine);	
		map.AttachEvent("onmousemove", Mouse_lasso);
		map.AttachEvent("onclick",clicage);	
		document.getElementById('_pan').className = 'd_pan';
		document.getElementById('_poly').className = 'd_poly';
		if(mini_map==true)
			document.getElementById('_maxmin').className = 'd_maxmin';
		document.getElementById("mymapcontroldiv").childNodes[0].style.cursor='crosshair';
		
	}
	
	if( _curTool=="_poly" )
	{
		alert("Close the polygon by pressing the 'Escape' key.")
		if (myCurrentShape) map.DeleteShape(myCurrentShape);
		myCurrentShape=null;

	    map.AttachEvent("onclick", DrawPolyMouseClick);
    	map.AttachEvent("onmousemove", MouseMove);
		document.getElementById("mymapcontroldiv").childNodes[0].style.cursor='crosshair';
		document.getElementById('_pan').className = 'd_pan';
		document.getElementById('_draw').className = 'd_draw';
		if(mini_map==true)
			document.getElementById('_maxmin').className = 'd_maxmin';
		map.vemapcontrol.EnableGeoCommunity(true);

	}	

	if( _curTool=="_clear" )
	{
		if (myCurrentShape) map.DeleteShape(myCurrentShape);
		myCurrentShape=null;
		_curTool="_pan";
		if(document.getElementById('_pan'))
			document.getElementById('_pan').className = 'a_pan';
		if(document.getElementById('divRows'))
			document.getElementById('divRows').innerHTML=' none yet ';	
		if(mini_map==true){
			if(document.getElementById('control_mapa_div'))
				map.Resize(null,350);
			if(document.getElementById('control_mapa_div'))
				document.getElementById('control_mapa_div').style.margin ="320px 0px 0px 10px";
		}
		
		if(document.getElementById('divRows')){
		}else{
			
				var ajax=nuevoAjax();
				var compar='_COMP';
				var php='pp_filter.php';
				if(typeComp=='_COMPACT') compar='_COMPACT';
				if(typeComp=='distress') php='pp_filter2.php'; 
				if(typeComp=='rental'){ 
					php='rent_filter.php'; 
					compar='_RENTAL';
				}
				ajax.open("POST", php+"?_compar="+compar+"&_action=_delete", true);
				ajax.send(null);

		
				ajax.onreadystatechange=function()
				{
					if (ajax.readyState==4)	
					{
						//alert('entro');
						if(mapa.className=="mapon"){
							//alert('entro2');
							callFilterFFSaf("false^");
						}
					}
				}
		}
	}

	if( _curTool=="_pan" )
	{	
		map.vemapcontrol.EnableGeoCommunity(false);	
		if(document.getElementById("mymapcontroldiv"))
			document.getElementById("mymapcontroldiv").childNodes[0].style.cursor='';
		if(document.getElementById('_draw'))
			document.getElementById('_draw').className = 'd_draw';
		if(document.getElementById('_poly'))
			document.getElementById('_poly').className = 'd_poly';
		if(mini_map==true)
			if(document.getElementById('_maxmin'))
				document.getElementById('_maxmin').className = 'd_maxmin';
		_region=null;
	}
	
	if( _curTool=="_maxmin" )
	{
		if (myCurrentShape) map.DeleteShape(myCurrentShape);
		myCurrentShape=null;
///		_curTool="_pan";
//alert("dentro: "+search_map);			
		
		if(search_map==true){
			document.getElementById('_pan').className = 'a_pan';
			document.getElementById('_draw').className = 'd_draw';
			document.getElementById('_poly').className = 'd_poly';
		}
		
		if(document.getElementById('_maxmin').className == 'd_maxmin'){ 
			document.getElementById('_maxmin').className = 'a_maxmin';
			
			map.Resize(null,600);
			document.getElementById('control_mapa_div').style.margin ="570px 0px 0px 10px";
//alert("entra1");			
		}else{
			document.getElementById('_maxmin').className = 'd_maxmin';
			map.Resize(null,350);
			document.getElementById('control_mapa_div').style.margin ="320px 0px 0px 10px";
//alert("entra2");			
		}
	}
	

	
}

function control_map(boton)
{

	var mapa=document.getElementById("mymapcontroldiv");
	var objMiles=document.getElementById("milerg");

	switch (boton) { 
    case "search":

		document.getElementById("latlong").value=0;

    	if  (mapa.className=="mapon") {
			cntSearch=0		
            _curLatLonShape = 0;	
			mapa.className="mapoff"
			gridAjust(mapa.className);
			curBoton="OFF"
			//quitar control	
			_curTool='_clear';
			map.DeleteControl(_mapTool);
			on_off();
			
			
			}
		else{
				mapa.className="mapon"
				gridAjust(mapa.className);
				curBoton="AVG"
				ins_toolbar("320px","search");
			}
       break     
} 

}