/**
 * 
 * @package
 * @subpackage
 * @author De Bollivier Sébastien <sebastien.debollivier@webarome.net>
 * @licence see LICENCE
 **/

function getCoordonnes(latlng) {
	var lonlat = new String(latlng);
	var coordonnes = lonlat.split(',');
	coordonnes[0] = parseFloat(coordonnes[0].replace('(', ''));
	coordonnes[1] = parseFloat(coordonnes[1].replace(')', ''));
	return coordonnes;
}

var center_point = new GPoint(40, 40);
var size = new GSize(32, 32);

var public_camera = new GIcon(G_DEFAULT_ICON, "./images/point/bleu.png");
public_camera.iconSize = size;
// public_camera.infoWindowAnchor = center_point;

var private_camera = new GIcon(G_DEFAULT_ICON, "./images/point/rouge.png");
private_camera.iconSize = size;
// private_camera.infoWindowAnchor = center_point;

var fake_camera = new GIcon(G_DEFAULT_ICON, "./images/point/gris.png");
fake_camera.iconSize = size;
// fake_camera.infoWindowAnchor = center_point;

var infrared_camera = new GIcon(G_DEFAULT_ICON, "./images/point/rose.png");
infrared_camera.iconSize = size;
// infrared_camera.infoWindowAnchor = center_point;

var omni_camera = new GIcon(G_DEFAULT_ICON, "./images/point/vert.png");
omni_camera.iconSize = size;
// omni_camera.infoWindowAnchor = center_point;

var long_camera = new GIcon(G_DEFAULT_ICON, "./images/point/orange.png");
long_camera.iconSize = size;
// long_camera.infoWindowAnchor = center_point;


// Infowin class for displaying a miniature info window. Does not
// respond to any events - so you should show and remove the
// overlay yourself as necessary.
function Infowin(latlng, html) {

        this.latlng_ = latlng;

        this.html_ = html;

        this.prototype = new GOverlay();

 

        // Creates the DIV representing the infowindow

        this.initialize = function(map) {

                var div = $('<div />');

                div.css({

                        position : 'absolute',

                        width : 234

                }).appendTo(map.getPane(G_MAP_FLOAT_PANE))

 

                this.map_ = map;

                this.div_ = div;

 

                this.update(html);

        }

 

        this.update = function(html){

                this.html_ = html;

 

                this.div_.empty();
				this.div_.click(function() {
					$(this).remove();
				});
				
				this.div_.mouseout(function() {
					$(this).remove();
					events.infowin = null;
				});
				
				this.div_.css({
				'background' : 'transparent url(/images/maps/info.png) no-repeat',
				
				'margin-left'  : '5px',
				'width' : '277px',
				'height': '168px',
				'color':'#fff',
				'z-index':1000
				});
 

                $('<div />').css({
					'background' : 'transparent',
                     height : 14,
                     padding: '0 0 0 0'
                }).appendTo(this.div_);

 

                var content = $('<div />').addClass('infowin-content').css({
						'position' : 'relative', 'top' : -5
                }).html(html);

 

                $('<div />').css({'background' : 'transparent',

                        'background-position' : 'bottom left',

                        'padding' : '0 10px 30px 10px'

                }).append(content).appendTo(this.div_);

 

                this.redraw(true);

        }

 

        // Remove the main DIV from the map pane

        this.remove = function() {

          this.div_.remove();

        }

 

        // Copy our data to a new instance

        this.copy = function() {

          return new Infowin(this.latlng_, this.html_);

        }

 

        // Redraw based on the current projection and zoom level

        this.redraw = function(force) {

                if (!force) return;

 

                var point = this.map_.fromLatLngToDivPixel(this.latlng_);

 

                // Now position our DIV based on the DIV coordinates of our bounds

                this.div_.css({

                        left : point.x - 108,

                        top : point.y - this.div_.height() - 22

                });

        }

}


var GoogleMaps = function() {
	this.id = null;
	this.geocoder = new GClientGeocoder();
	this.map = null;
	this.adress = null;
	this.point = null;
	this.pointToAdd = null;
	this.icons = {0:fake_camera, 1:omni_camera, 2:infrared_camera, 3:long_camera, 4:private_camera, 5:public_camera};
	
	this.points = {0:new Array(), 1:new Array(), 2:new Array(), 3:new Array(), 4:new Array(), 5:new Array()};
	this.state = {0:'visible',1:'visible',2:'visible',3:'visible',4:'visible',5:'visible'}
	
	
	this.initialize = function(myAdress) {
		if(GBrowserIsCompatible()) {
			this.map = new GMap2(document.getElementById(this.id));
			this.getFromAdress(myAdress);
		}
	}
	
	this.loadKML = function(file) {
		var kml = new GGeoXml(file);
		this.map.addOverlay(kml);
	}
	
	this.loadDefaultKML = function() {
		/*this.factice = new GGeoXml('http://connect.webarome.net/kml/camera_factices.kml');
		this.omni = new GGeoXml('http://connect.webarome.net/kml/camera_omnidirectionnelles.kml');
		this.infrared = new GGeoXml('http://connect.webarome.net/kml/cameras_infrarouges.kml');
		this.longsee = new GGeoXml('http://connect.webarome.net/kml/cameras_longue_portee.kml');
		this.privatec = new GGeoXml('http://connect.webarome.net/kml/Cameras_privees.kml');
		this.publicc = new GGeoXml('http://connect.webarome.net/kml/Cameras_publiques.kml');
		this.byuser = new GGeoXml('/index.php?module=camaps&action=default:buildKML');
		this.map.addOverlay(this.factice);
		this.map.addOverlay(this.omni);
		this.map.addOverlay(this.infrared);
		this.map.addOverlay(this.longsee);
		this.map.addOverlay(this.privatec);
		this.map.addOverlay(this.publicc);
		this.map.addOverlay(this.byuser);*/
		
	}
	
	this.changeMapType = function(type_id) {
		var types = maps.map.getMapTypes(); 
		maps.map.setMapType(types[type_id]);
		if(type_id == 1) {
			$('#satellite').addClass('vue-activ');
			$('#hybride').removeClass('vue-activ');
			$('#carte').removeClass('vue-activ');
		}
		
		if(type_id == 2) {
			$('#hybride').addClass('vue-activ');
			$('#satellite').removeClass('vue-activ');
			$('#carte').removeClass('vue-activ');
		}
		
		if(type_id == 0) {
			$('#carte').addClass('vue-activ');
			$('#hybride').removeClass('vue-activ');
			$('#satellite').removeClass('vue-activ');
		}
	}
		
	this.disableKML = function(id) {
		if(this.state[id] == 'visible') {
			var arr = this.points[id];
			for(var i=0; i < arr.length; i++) {
				arr[i].marker.hide();
			};
			this.state[id] = 'unvisible';
			$('#' + id + '_link').attr('class', 'a' + id + '_inactif');
		} else {
			for(var i=0; i < this.points[id].length; i++) {
				this.points[id][i].marker.show();
			};
			this.state[id] = 'visible';
			$('#' + id + '_link').attr('class', 'a' + id + '_actif');
		}
	}
		
	this.add = function(type) {
		this.pointToAdd = new PointOfInterest(this.icons[type], type);
		$.ajax({type: "get", url: "/index.php?module=camaps&action=default:add",
		   success: function(msg) {
			display("", msg);
			
		   }
		});
	}
	
	this.addNext = function() {
		this.pointToAdd.desc = $('#cam_desc').val();
		Shadowbox.close();
		var lonlat = new String(this.map.getCenter());
		var coordonnes = lonlat.split(',');
		coordonnes[0] = parseFloat(coordonnes[0].replace('(', ''));
		coordonnes[1] = parseFloat(coordonnes[1].replace(')', ''));
		this.pointToAdd.latitude = coordonnes[0];
		this.pointToAdd.longitude = coordonnes[1];
		this.pointToAdd.isNew = true;
		this.pointToAdd.addToMap("", maps);
	}
	
	this.edit = function(lon, lat) {
		this.pointToAdd = new PointOfInterest('', '');
		this.pointToAdd.latitude = lat;
		this.pointToAdd.longitude = lon;
		$.ajax({type: "get", url: "/index.php?module=camaps&action=default:update&lat=" + lat + "&lon=" + lon,
		   success: function(msg) {
			display("", msg);
			
		   }
		});
	}
	
	this.editNext = function() {
		this.pointToAdd.desc = $('#cam_desc').val();
		Shadowbox.close();
		this.pointToAdd.updateToDb();
	}
	
	this.update = function(point) {
		if(point) {
			this.map.clearOverlays()
			this.map.setCenter(point, 14);
		}
	}
	
	this.getFromAdress = function(adress) {
		this.geocoder.getLatLng(adress, function(point) { 
			maps.update(point);
		});
	}
	
	this.LatLngFromAdress = function(adress) {
		this.geocoder.getLatLng(adress, function(point) {
			maps.point = point;
		});
	}
}

var PointOfInterest = function(icon, kind) {
	this.longitude = 0;
	this.latitude = 0;
	this.point = null;
	this.icon = icon;
	this.desc = null;
	this.kind = kind;
	this.marker = null;
	this.picture = null;
	this.isNew = false;
	this.isNewInfo = null;
	
	this.addToMap = function(adress, googlemaps) {
		if(this.longitude == 0 && this.latitude == 0) {
			googlemaps.LatLngFromAdress(adress);
			this.point = maps.point;
		} else {
			this.point = new GPoint(this.longitude, this.latitude);
		}
		if(this.isNew) {
			this.marker = new GMarker(this.point, {draggable: true,icon:this.icon});
		} else {
			this.marker = new GMarker(this.point, {draggable: false,icon:this.icon});
		}
		events.on_marker_click(this.marker);
		events.on_marker_doubleclick(this.marker);
		googlemaps.map.addOverlay(this.marker);
		if(this.isNew) {
			this.isNewInfo = new Infowin(this.marker.getLatLng(), '<img src="/images/ajouter/add_next.png" />');
			maps.map.addOverlay(this.isNewInfo);
			events.on_marker_dragstart(this.marker);
			events.on_marker_dragend(this.marker);
		}
	}
	
	this.saveToDb = function() {
		$.ajax({
			type: "get", 
			url: "/index.php?module=camaps&action=default:addService&lat=" + this.latitude + '&lon=' + this.longitude + '&desc=' + this.desc + '&type=' + this.kind + '&picture=' + this.picture
		});
	}
	
	this.updateToDb = function() {
		$.ajax({
			type: "get", 
			url: "/index.php?module=camaps&action=default:updateService&lat=" + this.latitude + '&lon=' + this.longitude + '&desc=' + this.desc + '&type=' + this.kind + '&picture=' + this.picture
		});
	}
}

function addPoint(adress) {
	var point = new PointOfInterest();
	point.addToMap(adress, maps);
}

var EventManager = function() {
	this.infowin = null;
	
	this.initialize = function() {
		this.on_maps_ready();
		
	}
	
	this.on_maps_ready = function() {
		GEvent.addListener(maps.map, "load", function() {
			maps.loadDefaultKML();
			maps.map.setZoom(15);
			maps.map.enableScrollWheelZoom();
			getRecord();
		});
	}
	
	this.on_marker_click = function(marker) {
		GEvent.addListener(marker, "click", function() {
			var lonlat = new String(marker.getLatLng());
			var coordonnes = lonlat.split(',');
			coordonnes[0] = parseFloat(coordonnes[0].replace('(', ''));
			coordonnes[1] = parseFloat(coordonnes[1].replace(')', ''));
			$.ajax({type: "get", url: "/index.php?module=camaps&action=default:getInfo&lat=" + coordonnes[0] + "&lon=" + coordonnes[1],
			   success: function(msg) {
				if(events.infowin != null) events.infowin.remove();
				var info = new Infowin(marker.getLatLng(), msg);
				maps.map.addOverlay(info);
				events.infowin = info;
			   }
			});
			
		});
	}
	
	this.on_marker_dragstart = function(marker) {
		GEvent.addListener(marker, "dragstart", function() {
			marker.disableDragging();
			maps.pointToAdd.isNewInfo.remove();
		})
	}
	
	this.on_marker_dragend = function(marker) {
		GEvent.addListener(marker, "dragend", function() {
			marker.disableDragging();
			var lonlat = new String(marker.getLatLng());
			var coordonnes = lonlat.split(',');
			coordonnes[0] = parseFloat(coordonnes[0].replace('(', ''));
			coordonnes[1] = parseFloat(coordonnes[1].replace(')', ''));
			maps.pointToAdd.latitude = coordonnes[0];
			maps.pointToAdd.longitude = coordonnes[1];
			maps.pointToAdd.saveToDb();
			events.on_marker_click(maps.pointToAdd.marker);
			// events.on_marker_mousehover(maps.pointToAdd.marker);
			maps.pointToAdd = null;
		})
	}
	
	this.on_marker_doubleclick = function(marker) {
		GEvent.addListener(marker, "dblclick", function() {
			var coordonnes = getCoordonnes(marker.getLatLng());
			maps.edit(coordonnes[1], coordonnes[0]);
		});
	}
	
	this.on_marker_mousehover = function(marker) {
		GEvent.addListener(marker, "mouseover", function(latlng) {
			var coordonnes = getCoordonnes(latlng);
			$.ajax({type: "get", url: "/index.php?module=camaps&action=default:getInfo&lat=" + coordonnes[0] + "&lon=" + coordonnes[1],
			   success: function(msg) {
				var info = new Infowin(latlng, msg);
				maps.map.addOverlay(info);
				events.infowin = info;
			   }
			});
		});
	}
	
	this.on_marker_mouseout = function(marker) {
		GEvent.addListener(marker, "mouseout", function(latlng) {
			events.infowin.remove();
		});
	}
}
