﻿//Global Parameter of the Map and cusror
//Map
var map = null;
var normalProj = null;
var mapLat = null;
var mapLng = null;
var mapViewType = null;
var delay = null;
var timer = null;
var cursor = null;
var xmlCriteria = null;
var mapDivsText = new Array();
var wcfState = false;

//Map Layout
var selectCursor = null;
var selectCircle = null;
var selectImage = null;
var selectRadius = null;
var selectPoints = null;

//Area Layout
var typeAreas = new Array();
var radiusAreas = new Array();
var colorAreas = new Array();
var imageAreas = new Array();
var zoomAreas = new Array();
var countAreas = new Array();

//Zoom Lvl
var mapZoomMin = null;
var mapZoomMax = null;
var mapCurrentZoom = null;

//WCF
var gisService = null;
var coordJson = null;


function InitializeMap() {
	if (GBrowserIsCompatible()) {
  	$get("searchResultMap").style.marginLeft = "0px";
  	$get("searchResultMap").style.width = "auto";
		selectPoints = $get("HiddenSelectPoints").value == "" ? null : JSON.parse($get("HiddenSelectPoints").value);

  	//Create map object and init Default view    
    map = new GMap2($get("searchResultMap"));
    map.setCenter(new GLatLng(mapLat, mapLng), mapCurrentZoom);
    normalProj = G_NORMAL_MAP.getProjection();

    //InitCursor
    InitCursor(new GLatLng(mapLat,mapLng));

    //Set map Control
    InitMapControl();

    //Set map zoom level
    InitMapZoom();

    //Gis Service Init
    //gisService = new Portia.IGisService();
    gisService = new Portia.Frontend.ProxyLayer.GisProxy();

    //Init Data
    RefreshMap();

    //**************** Events     
		GEvent.addListener(map, "click", function(overlay, center) {
        //Clear the old circle
        if(selectCircle != null) map.removeOverlay(selectCircle);
                    
        //Draw the new circle
			if (center != null) {
           //Draw select image and get points
				DrawSelector(center.lat(), center.lng(), true);
           
           //Post select circle value
				ClickPostBack(center.lat(), center.lng(), selectPoints[0].y, selectPoints[0].x);
        }
     });
            
		GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
        //Reset timer     
        clearTimeout(timer);
        
        //Update hidden zoom
        var CurrentZoom = $get("HiddenCurrentZoom");    
        CurrentZoom.value = map.getZoom();
          
        //Clear the old circle
//			if (selectCircle != null)
//				map.removeOverlay(selectCircle);
                  
        //Zoom Out              
			if (newLevel < oldLevel) {
            //Full refresh
            ClearText();
            map.clearOverlays();
            timer = setTimeout("RefreshMap();", delay);
        }
        
        //Zoom In              
			if (newLevel > oldLevel) {
            //Refresh if area lvl change
            ClearText();
            map.clearOverlays();
            timer = setTimeout("RefreshMap();", delay);
        }          
			DrawSelector(mapLat, mapLng, false);
     });
     
		GEvent.addListener(map, "dragstart", function() {
        //Reset timer                           
        clearTimeout(timer);
     });
     
		GEvent.addListener(map, "dragend", function() {
        //Refresh overlays                    
        timer = setTimeout("RefreshMap();", delay); 
     });
     
		GEvent.addListener(map, "mousemove", function(latlng) {
        MoveCursor(latlng);
    });

    document.cookie = "googleScriptLoaded=1; path=/";
  } else alert('This webbrowser is incompatible');
}

//**************** Drawing Utilities
function ComputeCircle(center, radius, step, zoom) {
    //Var   
    var points = [];
    var centerPt = normalProj.fromLatLngToPixel(center, zoom);        
            
    //Compute circle point
	for (var a = 0; a < 361; a += step) {
        var aRad = a*(Math.PI/180);
        y = centerPt.y + radius * Math.sin(aRad);
        x = centerPt.x + radius * Math.cos(aRad);
        var p = new GPoint(x,y);
        points.push(normalProj.fromPixelToLatLng(p, zoom));
    }
    
    return points;
}

function DrawSelector(p_mapLat, p_mapLng, p_reDraw) {
     //Draw select image
	if (selectPoints == null || p_reDraw) {
		selectPoints = ComputeCircle(new GLatLng(p_mapLat, p_mapLng), selectRadius, 90, map.getZoom());
	}
	var circleCompute = new GPolyline(selectPoints, '#000000', 0, 0);
     selectCircle = new GGroundOverlay(selectImage, circleCompute.getBounds());
     map.addOverlay(selectCircle);
}

function DrawAreaMarker() {
    //Clear map overlay
    ClearText();
    map.clearOverlays();
    
    //Get appropriate area index
    var index = GetAreaIndex();

    //Browse the node and create markers buffer
	for (var i in coordJson) {
        //Draw marker
        var center = new GLatLng(coordJson[i].Latitude, coordJson[i].Longitude);
        map.addOverlay(new GMarker(center,InitMarkersIcon(radiusAreas[index]*2,imageAreas[index]),true,{clickable:false, draggable:false}));
        
        //Draw text
		if (countAreas[index] == 'true') {
            var sum = coordJson[i].NumberOfAdMaterialAtThisLocation;
            DrawText(sum,center);
        }
    }
	DrawSelector(mapLat, mapLng, false);
}

function DrawAreaPolygon() {
    //Clear map overlay
    ClearText();
    map.clearOverlays();
   
    //Get appropriate area index
    var index = GetAreaIndex();

    //Browse the node and create circles buffer
	for (var i in coordJson) {
        //Draw polygon
        var center = new GLatLng(coordJson[i].Latitude, coordJson[i].Longitude);
        //alert(zoomAreas[index]);
        //poly = new GPolygon(ComputeCircle(center,radiusAreas[index],20,zoomAreas[index]),'#FFFFFF', 1, 1, colorAreas[index], 0.4);
        poly = new GPolygon(ComputeCircle(center,radiusAreas[index],20,map.getZoom()),'#FFFFFF', 1, 1, colorAreas[index], 0.4);
        map.addOverlay(poly);
        GEvent.addListener(poly,"click",function(point){if (point) GEvent.trigger(map,"click",null,point)});
        
        //Draw text
		if (countAreas[index] == 'true') {
			var sum = coordJson[i].NumberOfAdMaterialAtThisLocation;
			DrawText(sum, center);
		}
	}
	if ($get("SearchByMap") != null && $get("SearchByMap").value == "1")
		DrawSelector(mapLat, mapLng, false);
}

function DrawText(text, center) {
    //Create div text 
    var p = map.fromLatLngToDivPixel(center);
    var div = document.createElement("div");   
	div.innerHTML = '<p style="font-size: 12pt; font-style: 900; color: black; text-align:center;" >' + text + '</p>';
	div.style.position = 'absolute';
	div.style.width = 40 + 'px';
	div.style.height = 20 + 'px' ;
	div.style.left = (p.x - 20) + 'px';
	div.style.top = (p.y - 10) + 'px';
	mapDivsText.push(div);
	
	//Add div to map
	map.getPane(G_MAP_MARKER_PANE).appendChild(div);
}

function DrawWait() {
      waitImage = new GScreenOverlay('/Portals/Immostreet15/Resources/images/googlemap/searching_red.gif',
        new GScreenPoint(0.0, 0.0, null, null),  // screenXY
        new GScreenPoint(0, 0),  // overlayXY
        new GScreenSize(0.0, 0.0, null, null)  // size on screen
      );
      map.addOverlay(wait);
}

function ClearText(divs) {
    for(var i in mapDivsText)
        mapDivsText[i].parentNode.removeChild(mapDivsText[i]);
    
    mapDivsText = new Array();
}

function InitCursor(latlng) {
    //Create cursor
    var div = document.createElement("div");
    var divIdName = 'divCursor';
    div.setAttribute('id',divIdName); 
    div.style.position = 'absolute';
    div.style.left = map.fromLatLngToDivPixel(latlng).x-selectRadius+'px';
    div.style.top = map.fromLatLngToDivPixel(latlng).y-selectRadius+'px';
    div.innerHTML = '<img style="position : absolute; border: 0px; width:'+ selectRadius*2 +'px; height:'+ selectRadius*2 +'px; cursor: crosshair;" src="'+selectCursor+'"/>';
    
    //Add div to map
    map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
}
    
function MoveCursor(latlng) {
   //Move cursor to current mouse position
   var point = map.fromLatLngToDivPixel(latlng);
   document.getElementById('divCursor').style.left=point.x-selectRadius+'px';
   document.getElementById('divCursor').style.top=point.y-selectRadius+'px';
}

//**************** WCF Service Layer
//Get Location
function doGetAdMaterialsLocationFromRectangle() {
    //Get location JSON from WCF   
    var l_bounds = map.getBounds();
     
    gisService.GetAdMaterialsLocationFromRectangle(
     l_bounds.getSouthWest().lat()
    ,l_bounds.getSouthWest().lng()
    ,l_bounds.getNorthEast().lat()
    ,l_bounds.getNorthEast().lng()
    ,xmlCriteria
    ,onGetCoordFromRectangleSuccess
    ,onGetCoordFromRectangleFailure, null);
}

//Get Area
function doGetAdMaterialsAreaFromRectangle(p_areaLvl) {
    //Get area JSON from WCF
    var l_bounds = map.getBounds();
        
    gisService.GetAdMaterialsAreaFromRectangle(
     l_bounds.getSouthWest().lat()
    ,l_bounds.getSouthWest().lng()
    ,l_bounds.getNorthEast().lat()
    ,l_bounds.getNorthEast().lng()
    ,p_areaLvl
    ,xmlCriteria
    ,onGetCoordFromRectangleSuccess
    ,onGetCoordFromRectangleFailure, null);   
}

function onGetCoordFromRectangleSuccess(p_result) {
    //Get JSON result object
    coordJson = null;
    coordJson = p_result;
    
    //Init drawing function 
	if (coordJson != null) {
        if((imageAreas[GetAreaIndex()] == '' || imageAreas[GetAreaIndex()] == null)
            && (colorAreas[GetAreaIndex()] != '' || colorAreas[GetAreaIndex()] != null))
           DrawAreaPolygon();
        else  DrawAreaMarker();
    }
    
    wcfState = false;  
}

function onGetCoordFromRectangleFailure(p_result) {
    //alert('Erreur WCF GetAdImmoCoord' + p_result.get_message());
    wcfState = false;
}

//**************** Init after map loading
function InitMarkersIcon(p_size, p_image) {
    //Init marker size, image and size
    var baseIcon = new GIcon();
    baseIcon.iconSize = new GSize(p_size,p_size);
    baseIcon.iconAnchor = new GPoint(p_size/2,p_size/2);
    return new GIcon(baseIcon, p_image, null, null);
}

function InitMapControl() {
    //Set Map Standard Control
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.disableDoubleClickZoom();
    map.enableScrollWheelZoom();
    map.enableContinuousZoom();
    
    //Set map view type
	if (mapViewType == "Map") {
        map.setMapType(G_NORMAL_MAP);
    }
	if (mapViewType == "Satellite") {
        map.setMapType(G_SATELLITE_MAP);
    }
	if (mapViewType == "Hybrid") {
        map.setMapType(G_HYBRID_MAP);
    }
}

function InitMapZoom() {
    G_NORMAL_MAP.getMinimumResolution = function () { return mapZoomMin };
    G_SATELLITE_MAP.getMinimumResolution = function () { return mapZoomMin };
    G_HYBRID_MAP.getMinimumResolution = function () { return mapZoomMin };

    G_NORMAL_MAP.getMaximumResolution = function () { return mapZoomMax };
    G_SATELLITE_MAP.getMaximumResolution = function () { return mapZoomMax };
    G_HYBRID_MAP.getMaximumResolution = function () { return mapZoomMax }; 
}


//**************** Init before load the map
function InitMapValue(p_mapLat, p_mapLng, p_mapCurrentZoom, p_mapViewType, p_xmlCriteria) {
    //Init defaut map position
    mapCurrentZoom = parseInt(p_mapCurrentZoom);
    var reg = new RegExp("(,)", "g");
    mapLat = p_mapLat.replace(reg,".");
    mapLng = p_mapLng.replace(reg,".");
    mapViewType = p_mapViewType;
    xmlCriteria = p_xmlCriteria;
}

function InitMapConfig(p_jsonConfig) {
    //Init map settings
    var jsonConfig = eval('('+ p_jsonConfig +')');
        
    //Init Map Layout    
    selectCursor = jsonConfig.mapLayoutField.mapSelectorField.cursorField.imageField;
    selectImage = jsonConfig.mapLayoutField.mapSelectorField.selectorField.imageField;
    selectRadius = jsonConfig.mapLayoutField.mapSelectorField.radiusField.sizeField;

    //Init Zoom Level
    mapZoomMin = jsonConfig.mapLayoutField.mapZoomField.zoomMinField.valueField;
    mapZoomMax = jsonConfig.mapLayoutField.mapZoomField.zoomMaxField.valueField;

    //Init Area Level
	for (var i in jsonConfig.mapLayoutField.mapAreasField.mapAreaField) {
        zoomAreas[i] = jsonConfig.mapLayoutField.mapAreasField.mapAreaField[i].zoomField;
        //debug alert(zoomAreas[i]);
        radiusAreas[i] = jsonConfig.mapLayoutField.mapAreasField.mapAreaField[i].radiusField;  
        //debug alert(radiusAreas[i]);
        typeAreas[i] = jsonConfig.mapLayoutField.mapAreasField.mapAreaField[i].areaTypeIdField;
        //debug alert(typeAreas[i]);
        colorAreas[i] = jsonConfig.mapLayoutField.mapAreasField.mapAreaField[i].colorField;
        //debug alert(colorAreas[i]);
        imageAreas[i] = jsonConfig.mapLayoutField.mapAreasField.mapAreaField[i].imageField;
        //debug alert(colorAreas[i]);
        countAreas[i] = jsonConfig.mapLayoutField.mapAreasField.mapAreaField[i].drawCountField;
        //debug alert(countAreas[i]);
    }
    
    //Init Timer delay
    delay = jsonConfig.mapConfigField.mapTimerField.delayField;
}

//**************** Process
function ClickPostBack(p_CenterLocationLatitude, p_CenterLocationLongitude, p_ExtremityLocationLatitude, p_ExtremityLocationLongitude) {
    //Set hiden value 
    var CenterLocationLatitude = $get("HiddenCenterLocationLatitude");    
	CenterLocationLatitude.value = p_CenterLocationLatitude.toString();
	
	var CenterLocationLongitude = $get("HiddenCenterLocationLongitude");	     
	CenterLocationLongitude.value = p_CenterLocationLongitude.toString();
	
	var ExtremityLocationLatitude = $get("HiddenExtremityLocationLatitude");	     
	ExtremityLocationLatitude.value = p_ExtremityLocationLatitude.toString();
	
	var ExtremityLocationLongitude = $get("HiddenExtremityLocationLongitude");	     
	ExtremityLocationLongitude.value = p_ExtremityLocationLongitude.toString();
	
    var CurrentZoom = $get("HiddenCurrentZoom");	     
	CurrentZoom.value = map.getZoom();
	
	var MapViewType = $get("HiddenMapViewType");	     
	MapViewType.value = map.getCurrentMapType().getName();
		
    var IsMapModule = $get("HiddenIsMapModule");	     
	IsMapModule.value = 'submit';
		
	var SelectPoints = $get("HiddenSelectPoints");
	SelectPoints.value = JSON.stringify(selectPoints);


	PO_setFormActionType('mapSearch');
	PO_onFormSubmit(doGetSubmitButton().form, $get("HiddenSearchId").value);
	doGetSubmitButton().form.submit();
}

function RefreshMap() {
    //Test level
	for (var i = 0; i < zoomAreas.length - 1; i++) {
		if (map.getZoom() <= zoomAreas[i] && map.getZoom() > zoomAreas[i + 1]) {
            //Get and draw area
            if(typeAreas[i] == 'LOCA' || typeAreas[i] == '' || typeAreas[i] == null)
                GetLocation();
            else GetArea(typeAreas[i]);
        }
    }
    
    //Test last level
	if (map.getZoom() <= zoomAreas[zoomAreas.length - 1]) {
		//Get and draw area
		GetArea(typeAreas[typeAreas.length - 1]);
	}
	if ($get("SearchByMap") != null && $get("SearchByMap").value == "1")
		DrawSelector(mapLat, mapLng, false);
}

function GetAreaIndex() {
    //Get the appropriate area size 
    var index;
        
     //Test inter level          
	for (var i = 0; i < zoomAreas.length; i++) {
      if(map.getZoom() <= zoomAreas[i] && map.getZoom() > zoomAreas[i+1])
          index = i;
    }

    //Test last level
    if(map.getZoom() <= zoomAreas[zoomAreas.length-1])
        index = zoomAreas.length-1;
        
    return index;
}

function GetLocation() {
    //Init WCF JSON location
	if (wcfState == false) {
        wcfState = true;
        doGetAdMaterialsLocationFromRectangle();
    }
}

function GetArea(p_areaLvl) {
    //Init WCF JSON area
	if (wcfState == false) {
        wcfState = true;
        doGetAdMaterialsAreaFromRectangle(p_areaLvl);
    }
}

