var widthMapClienteWikiMapps;
var heightMapClienteWikiMapps;
var urlWikiCrimes = 'http://www.wikicrimes.org/';
var photoWikiCrimes = null;

function getTamMapClienteWikiMapps(){
	var b = map.getBounds();
	
	/*var north = b.getNorthEast().lat();
	var south = b.getSouthWest().lat();
	var east = b.getNorthEast().lng();
	var west = b.getSouthWest().lng();   */
	
	var northPixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(b.getNorthEast(), map.getZoom()).y;
	var southPixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(b.getSouthWest(), map.getZoom()).y;
	var eastPixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(b.getNorthEast(), map.getZoom()).x;
	var westPixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(b.getSouthWest(), map.getZoom()).x;
	
	widthMapClienteWikiMapps = (eastPixel - westPixel);
	heightMapClienteWikiMapps = (southPixel - northPixel);
	
	//considera a possibilidade de o west > east (ou north > south), qd a emenda do mapa ta no meio do bounds
	var centro = b.getCenter();
	var centroPixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(centro, map.getZoom());
	if(widthMapClienteWikiMapps < 0){
		if(centroPixel.x < westPixel)
			widthMapClienteWikiMapps = 2*westPixel-centroPixel.x;
		else
			widthMapClienteWikiMapps = 2*centroPixel.x-eastPixel;
	}
	if(heightMapClienteWikiMapps < 0){
		if(centroPixel.y < southPixel)
			heightMapClienteWikiMapps = 2*southPixel-centroPixel.y;
		else
			heightMapClienteWikiMapps = 2*centroPixel.y-northPixel;
	}
}

function mapaDeKernelWikiMapps() {
	console.log("mapaDeKernelWikiMapps");
//    var b = map.getBounds();
//    var north = b.getNorthEast().lat();
//    var south = b.getSouthWest().lat();
//    var east = b.getNorthEast().lng();
//    var west = b.getSouthWest().lng();
//   
//    getTamMapClienteWikiMapps();
//   
//    //	Passa os limites para pixel
//    var northPixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(b.getNorthEast(), map.getZoom()).y;
//    var southPixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(b.getSouthWest(), map.getZoom()).y;
//    var eastPixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(b.getNorthEast(), map.getZoom()).x;
//    var westPixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(b.getSouthWest(), map.getZoom()).x;
//    var url = urlWikiCrimes+'ServletWikiCrimesApi?acao=kernelMap&northPixel=' + northPixel + '&southPixel=' + southPixel + '&eastPixel=' + eastPixel + '&westPixel=' + westPixel + '&width='+ widthMapClienteWikiMapps + '&height='+ heightMapClienteWikiMapps +'&pontoXY=';
	var url = urlWikiCrimes + 'ServletWikiCrimesApi?acao=geraKernel' + boundsUrlParam(map) +'&pontoXY=';
    var qtdCrimes = 0;
    
    
    /*
     *	Implementação para o wikimapps [INICIO]
     */
    marcadoresKernel = {};
    
    for (i in markersArray) {
    	if (!markersArray[i].obj.isHidden()) {
    		marcadoresKernel[i] = markersArray[i];
    	}
    }
    /*
     *	Implementação para o wikimapps [FIM]
     */
    
    
    for (k in marcadoresKernel){
        qtdCrimes++;
    } 
    
    var qtdCriEnv = 200;
    var cont = 0;
    //alert('1');
    for (k in marcadoresKernel){
    	if(marcadoresKernel[k].obj instanceof GMarker){
	        cont++;
	        var point = marcadoresKernel[k].obj.getPoint();
	        var pixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(point, map.getZoom());
	        url+= pixel.y + "," + pixel.x + "a";
	        if(cont % qtdCriEnv == 0 && qtdCrimes>qtdCriEnv){
	        	//alert('3');
	            if(cont == qtdCriEnv){
	                url+='&statusReq=Pri';
	            }else{
	                url+='&statusReq=SegOuMais';
	            }
	            url+='&jsoncallback=?';
	
	            executaRequisicaoKernelmap(url);
//	            url = urlWikiCrimes + 'ServletWikiCrimesApi?acao=kernelMap&pontoXY=';
	            url = urlWikiCrimes + 'ServletWikiCrimesApi?acao=geraKernel&pontoXY=';
	        }
    	}else{
    		//e polygono;
    		cont--;
    	}	
    }
   
    url = url.substring(0,url.length-1)
    
    if(qtdCrimes<=qtdCriEnv)
        url+='&statusReq=PriUlt';
    else
        url+='&statusReq=Ult';
    
    url+='&jsoncallback=?';
    console.log("url: " + url);
    executaRequisicaoKernelmap(url);
}

function boundsUrlParam(map){
	var bounds = map.getBounds();
	var proj = map.getCurrentMapType().getProjection();
	var zoom = map.getZoom();
	
	//Passa os limites para pixel
	northPixel = proj.fromLatLngToPixel(bounds.getNorthEast(), zoom).y;
	southPixel = proj.fromLatLngToPixel(bounds.getSouthWest(), zoom).y;
	eastPixel = proj.fromLatLngToPixel(bounds.getNorthEast(), zoom).x;
	westPixel = proj.fromLatLngToPixel(bounds.getSouthWest(), zoom).x;
	//alert(northPixel + "," + southPixel + "," + eastPixel + "," + westPixel);

	var str = '&northPixel=' + northPixel + '&southPixel=' + southPixel + '&eastPixel=' + eastPixel + '&westPixel=' + westPixel;
	//url += '&north=' + north + '&south=' + south + '&east=' + east + '&west=' + west;

	
	width = (eastPixel - westPixel);
	height = (southPixel - northPixel);

	//considera a possibilidade de o west > east (ou north > south), qd a emenda do mapa ta no meio do bounds
	var centro = bounds.getCenter();
	var centroPixel = proj.fromLatLngToPixel(centro, zoom);
	if(width < 0){
		if(centroPixel.x < westPixel)
			width = 2*westPixel-centroPixel.x;
		else
			width = 2*centroPixel.x-eastPixel;
	}
	if(height < 0){
		if(centroPixel.y < southPixel)
			height = 2*southPixel-centroPixel.y;
		else
			height = 2*centroPixel.y-northPixel;
	}
		      		
  	str +='&width='+width+'&height='+height;

  	return str;
}

function executaRequisicaoKernelmap(url){
	console.log("executaRequisicaoKernelmap");
	$j.getJSON(url, false, function(data){
//      if(data.numRandomico!=null && data.numRandomico!= undefined){
//    	if(data.imagePath!=null && data.imagePath!= undefined){
//        	var numRandomico = data.numRandomico;
//          var idImage = data.idImage;
//    		var imagePath = data.imagePath;
		console.log("executaRequisicaoKernelmap, statuRes: " + data.statuRes);
    	if(data.statuRes == "concluido"){
           
            //	Converte pixel para latlng. Lembrete: GPoint(lat, lng)
            var sw1 = map.getCurrentMapType().getProjection().fromPixelToLatLng(new GPoint(data.topLeftX,data.topLeftY), map.getZoom(), true);
            var sw2 = map.getCurrentMapType().getProjection().fromPixelToLatLng(new GPoint(data.bottomRightX,data.bottomRightY), map.getZoom(), true);
           
            //	Recupara os latlong da resposta da requisicao                       
            var lon1 = sw1.lng();
            var lat1 = sw1.lat();
           
            //	Recupera os latlong da resposta da requisicao                       
            var lon2 = sw2.lng();
            var lat2 = sw2.lat();
           
            photoWikiCrimes = new TPhoto();
            photoWikiCrimes.id = 'addphoto';
            //photo.id = id;
           
//          photoWikiCrimes.src = urlWikiCrimes + 'images/KernelMap/'+ numRandomico + '/Img' + idImage + '.png';
//            photoWikiCrimes.src = urlWikiCrimes + imagePath;
            photoWikiCrimes.src = urlWikiCrimes + "ServletWikiCrimesApi?acao=pegaImagem&jsoncallback=?&data=" + new Date();
           
            //photo.src = './images/KernelMap/' + idUsuarioMapaKernel +'@'+ emailUsuarioMapaKernel + '/Img' + idImage + '.png';
            //photo.src = '${contextPath}/Img2.png';           
            //photo.src = '${pageContext.request.contextPath}/Img2.png';
            //photo.src = 'images/TesteM.png';
            photoWikiCrimes.percentOpacity = 50;
            photoWikiCrimes.anchorTopLeft = new GLatLng(lat1,lon1);
            photoWikiCrimes.anchorBottomRight = new GLatLng(lat2,lon2);
   
            map.addTPhoto(photoWikiCrimes);
            //document.getElementById("loadingKernelMap").style.visibility='hidden';
             
            //Manda confirmação para apagar a imagem no servidor.
//          url = urlWikiCrimes + 'ServletWikiCrimesApi?acao=kernelMap&imagem=' + numRandomico;
//            url = urlWikiCrimes + 'ServletWikiCrimesApi?acao=kernelMap&imagem=true';
            console.log("executaRequisicaoKernelmap, photoWikiCrimes.src: " + photoWikiCrimes.src);
//            url+='&jsoncallback=?';
            //executaRequisicaoKernelmap(url);
            
        } else { }
    });
}



function TPhoto(){}

TPhoto.prototype.initialize=function(a){
    this.parentMap=a;
    var b=document.createElement('img');
    b.style.display='none';
    b.setAttribute('id',this.id);
    b.setAttribute('src',this.src);
    b.style.position='absolute';
    b.style.zIndex=1;
    this.mapTray=a.getPane(G_MAP_MAP_PANE);
    this.mapTray.appendChild(b);
    this.setPosition(a);
    b.style.display='block';
    if(this.percentOpacity){this.setOpacity(this.percentOpacity);}
    GEvent.bind(a,"zoomend",this,function(){this.setPosition(a)});
    GEvent.bind(a,"moveend",this,function(){this.setPosition(a)});
}

TPhoto.prototype.setPosition=function(a){
    var d=this.parentMap.fromLatLngToDivPixel(this.anchorTopLeft);
    var e=this.parentMap.fromLatLngToDivPixel(this.anchorBottomRight);
    var x=document.getElementById(this.id);
   
    if(x != null){
        x.style.top=d.y+'px';
        x.style.left=d.x+'px';
        x.style.width=e.x-d.x+'px';
        x.style.height=e.y-d.y+'px';
    }
   
}

TPhoto.prototype.setOpacity=function(b){
    if(b<0){b=0;}  if(b>=100){b=100;}
    var c=b/100;
    var d=document.getElementById(this.id);
    if(typeof(d.style.filter)=='string'){d.style.filter='alpha(opacity:'+b+')';}
    if(typeof(d.style.KHTMLOpacity)=='string'){d.style.KHTMLOpacity=c;}
    if(typeof(d.style.MozOpacity)=='string'){d.style.MozOpacity=c;}
    if(typeof(d.style.opacity)=='string'){d.style.opacity=c;}
}

GMap2.prototype.addTPhoto=function(a){
    a.initialize(this);

    //	Controle de interface.
    clicouBotaoKernel = true;
}

GMap2.prototype.removeTPhoto = function(a) {
    try{
    	var b=document.getElementById(a.id);
        
    	if(b != null){
            this.getPane(G_MAP_MAP_PANE).removeChild(b);
            delete(b);
        }
    } catch(e) { }
    
    //	Controle de interface.
    clicouBotaoKernel = true;
}
