// JavaScript Document
function MapController(Map){

	//L'objet MapController
	var _this = this;
	
	//Association de la map au controleur
	_this.Map = Map;
	
	//Le niveau de zoom minimal auquel faire apparaitre les dalles
	_this.min_zoom = 9;
	
	//largeur / hauteur d'une dalle
	_this.tile_size = 0.25;
	_this.tile_size_2 = 0.50;
	
	_this.ajaxCallGetTiles = null;
	
	//Les types de map disponibles, et les ids des boutons correspondants
	_this.map_type = Array(
							Array('G_SATELLITE_MAP','SatView'),
							Array('G_HYBRID_MAP','HybridView'),
							Array('G_NORMAL_MAP','NormalView')
							);


	
	_this.tiles = Array();
	_this.tiles_ids = Array();
	_this.tiles_selection = Array();
	
	//Ajout des écouteurs sur les mouvements de la map
	GEvent.addListener(_this.Map, 'moveend', function(){ _this.stopMove()} );

	//on intialise son Geocoder
	_this.geocoder = new GClientGeocoder(); 
	

	//si une recherche par reférence est lancée, cette variable est renseignée en cas de succès
	_this.ref_search = null;
	
	 
	//récupère les limites de la portion de map actuellement visible
	_this.getBounds = function(){
		
		_this.map_bounds = _this.Map.getBounds();
		_this.sw = _this.map_bounds.getSouthWest();
		_this.ne = _this.map_bounds.getNorthEast();
		_this.n = _this.ne.lat();
		_this.e = _this.ne.lng();
		_this.s = _this.sw.lat();
		_this.w = _this.sw.lng();
		
	};
	
	
	//Retourne le niveau de zoom correct en fonction du rectangle et de son centre
	_this.getCenteredBoundsZoomLevel = function(center, bounds) { 
	
		var mapType = (_this.Map.getCurrentMapType() || G_NORMAL_MAP); 
		var proj = mapType.getProjection();

		var dummyZoom = 0; 
		
		var centerPoint = proj.fromLatLngToPixel(center, dummyZoom); 
		var swPoint = proj.fromLatLngToPixel(bounds.getSouthWest(), dummyZoom); 
		var nePoint = proj.fromLatLngToPixel(bounds.getNorthEast(), dummyZoom);
		
		var dx = Math.max(Math.abs(swPoint.x - centerPoint.x), Math.abs(centerPoint.x - nePoint.x)); 
		var dy = Math.max(Math.abs(swPoint.y - centerPoint.y), Math.abs(centerPoint.y - nePoint.y)); 
		swPoint = new GPoint(centerPoint.x - dx, centerPoint.y - dy); 
		nePoint = new GPoint(centerPoint.x + dx, centerPoint.y + dy); 
		var newBounds = new GLatLngBounds( proj.fromPixelToLatLng(swPoint, dummyZoom), proj.fromPixelToLatLng(nePoint, dummyZoom)); 
		return mapType.getBoundsZoomLevel(newBounds, _this.Map.getSize()); 
		
	}; 
	
	
	_this.stopMove = function(){
		
		_this.removeOverlays();
		
		if(MapCtrl.rectSelection != null){
			
			MapCtrl.Map.removeOverlay(MapCtrl.rectSelection);
		
		}

		if(_this.ajaxCallGetTiles != null){
				
				_this.ajaxCallGetTiles.abort;	
			
		}
		
		_this.mapNewPos = _this.Map.getCenter();
		var zoom_level = _this.Map.getZoom();

		if (zoom_level >= _this.min_zoom){
			
				if(_this.globalView != null){
					
					_this.globalView.hide();
				
				}
				
				if(noTilesMessage != null){
				
					noTilesMessage.style.display = 'none';
				
				}
				
				_this.getTiles();
			
			}	else{
				
				if(_this.globalView != null){
					
					_this.globalView.show();
					
				}
				
				if(noTilesMessage != null){
					
					noTilesMessage.style.display = 'block';
					
				}
			
			}
	}
	
	
	_this.removeOverlays = function(){
		
		var n = _this.tiles.length;
		
		for(i=0;i<n;i++){
			
			_this.tiles[i].hide();
				
		}
		
	 }



	_this.getTiles = function(){
			
				_this.getBounds();
				_this.ajaxCallGetTiles = new AjaxCall('project/map_request',['request=getTiles','n='+parseFloat(parseFloat(_this.n)+_this.tile_size),
																					  's='+parseFloat(parseFloat(_this.s)-_this.tile_size), 
																					  'w='+parseFloat(parseFloat(_this.w)-_this.tile_size), 
																					  'e='+parseFloat(parseFloat(_this.e)+_this.tile_size)],
																					  _this.returnTiles,true,true);

	}
	
	

	_this.returnTiles = function($xml){	
		
		_this.tiles_selection = new Array();
		
		//le document XML à analyser
		var xml_doc 	= $xml.documentElement;
		var rows 		= xml_doc.getElementsByTagName('row');
		var n = rows.length;
		
		_this.num_tiles = n;
		
		for(i=0;i<n;i++){
	
			var t = rows[i];
			var id = t.getAttribute('id');
			var ref = t.getAttribute('ref');
			var lat = t.getAttribute('lat_lower');
			var lng = t.getAttribute('lng_left');
			var in_cart = t.getAttribute('in_cart');
			
			//On vérifie s'il il faut générer un nouveau polygon, ou si celui-ci existe
			var currentPos = _this.inTiles(id);
			
			//Si il n'existe pas, on le créé
			if(currentPos === -1){
				
				var tile = _this.addTile(lat,lng,id,ref,in_cart);
				_this.tiles.push(tile);
				_this.tiles_ids.push(id);
				_this.switchColorTile(tile);
				_this.Map.addOverlay(tile);
				
			}	else{
				
				if(in_cart == 1){
			
					_this.tiles[currentPos].status = 'on';
					_this.tiles_selection.push(_this.tiles[currentPos]);	
			
				
				}	else{
				
					_this.tiles[currentPos].status = 'off';	
			
				}
				
				_this.switchColorTile(_this.tiles[currentPos]);
				_this.tiles[currentPos].show();
				
			}
				
		}
	
		_this.ref_search = null;
		
	}
	
	
	_this.inTiles = function(id){
		
		var pos = -1;

		len = _this.tiles_ids.length;
		
		for ( var x = 0 ; x <= len ; x++ ) {
		
		if ( _this.tiles_ids[x] == id ) {
			
			pos = x;
			break;
		}
		
		}
		
		return pos;
		
	}
	
	
	_this.searchByTileRef = function(ref_search){
		_this.ref_search = ref_search;
		var ajaxcall = new AjaxCall('project/map_request',['request=searchByTileRef','ref_search='+ref_search],_this.returnSearchByTileRef,true,false);

	}
		
	
	_this.searchByAddr = function(value){
		
		_this.geocoder.getLatLng(value, _this.returnSearchByAddr);
	
	}
	
	
	_this.returnSearchByAddr = function(point){
			
		if(point){
				
			_this.Map.setCenter(point,(Math.round(_this.min_zoom)));
			
		}	
			
	}
	
	
	_this.returnSearchByTileRef = function(ajaxResponse){
		
		var latLng = ajaxResponse.split('@');
			
		if(latLng[0] != '' && latLng[1] != ''){
				
			var point = new GLatLng(latLng[0],latLng[1]);
			_this.Map.setCenter(point,(Math.round(_this.min_zoom)));
			
		}	
			
	}		
			
	

	_this.addTile = function(lat,lng,id,ref,in_cart){
		
		var bl = new GLatLng(lat,lng);
		var tl = new GLatLng(parseFloat(lat)+_this.tile_size,lng);
		
		if(parseFloat(lat) < -50 || (parseFloat(lat)+_this.tile_size) > 50){
		
			var tr = new GLatLng(parseFloat(lat)+_this.tile_size,parseFloat(lng)+_this.tile_size_2);
			var br = new GLatLng(lat,parseFloat(lng)+_this.tile_size_2);	
		
		}	else{
			
			var tr = new GLatLng(parseFloat(lat)+_this.tile_size,parseFloat(lng)+_this.tile_size);
			var br = new GLatLng(lat,parseFloat(lng)+_this.tile_size);				
		}
		
		var tile = new GPolygon([tl,tr,br,bl,tl], '#111111', 1, 1, '#111111', 0);	
		tile.id = id;
		tile.ref = ref;
		
		if(in_cart == 1){
			
			tile.status = 'on';
			_this.tiles_selection.push(tile);	
			
				
		}	else{
				
			tile.status = 'off';	
			
		}
				
		_this.switchColorTile(tile);
		

		
		GEvent.addListener(tile, 'click' , function(){ _this.toggleTile(this);} );
		
		return tile;
		  
	}
	
	
	_this.switchColorTile = function(tile){
		
		if(tile.ref == _this.ref_search){
			
			tile.setFillStyle({'color':'#FF8866','opacity':0.3}); 
			tile.setStrokeStyle({'color':'#EEEEEE','opacity':1}); 	
			
		}	else{
		
			if(tile.status == 'on'){
			
				tile.setFillStyle({'color':'#00FF2A','opacity':0.5}); 
				tile.setStrokeStyle({'color':'#EEEEEE','opacity':1}); 
			
			}	else{
				
				tile.setFillStyle({'color':'#007FFF','opacity':0.2}); 
				tile.setStrokeStyle({'color':'#EEEEEE','opacity':1}); 
				
			}
			
		}
			
	}
	
	
	_this.toggleTile = function(tile){

		if(tile.status == 'off'){
			
			//if(document.getElementById('numTiles').value < 4){
				
				tile.status = 'on';
				_this.tiles_selection.push(tile);
				var bottomLeft = tile.getVertex(3);
				var bottom = bottomLeft.lat();
				var left = bottomLeft.lng();
				var topRight = tile.getVertex(1);
				var top = topRight.lat();
				var right = topRight.lng();
				
				var ajaxcall = new AjaxCall('project/map_request',['request=addTile','id_tile='+tile.id,'ref_tile='+tile.ref,'lat_lower='+bottom,'lat_upper='+top,'lng_left='+left,'lng_right='+right], updateCartList,true,true);	
			
			
			//}
			
		}	else{
			
			tile.status = 'off';
			var pos_in_selection = _this.tiles_selection.getPos(tile);	
			_this.tiles_selection.splice(pos_in_selection,1);
			var ajaxcall = new AjaxCall('project/map_request',['request=removeTile','id_tile='+tile.id], updateCartList,true,true);	
		}
		
		_this.switchColorTile(tile);
	}


	_this.toggleViewType = function(type){

		_this.Map.setMapType(eval(type));
		
		for(i=0;i<=2;i++){
		
			if(_this.map_type[i][0] == type){
		
				document.getElementById(_this.map_type[i][1]).className = 'mapOptionsButtonSelected';
				
			} else {
				
				document.getElementById(_this.map_type[i][1]).className = 'mapOptionsButton';
				
			}
		
		}
	
	}
	

			
	
	return true;

}
