var infowindow;
var map;
var bounds;
var image;
var shadow;
var shape;

var mapdisplay = 600;
var circleLatLngs = new Array();
var numPoints = 60;

$(window).resize(mapsize);
$(function () {
    $('.bubbleInfo').each(function () {
        var distance = 10;
        var time = 250;
        var hideDelay = 500;

        var hideDelayTimer = null;

        var beingShown = false;
        var shown = false;
        var trigger = $('.trigger', this);
        var info = $('.popup', this).css('opacity', 0);


        $([trigger.get(0), info.get(0)]).mouseover(function () {
            if (hideDelayTimer) clearTimeout(hideDelayTimer);
            if (beingShown || shown) {
                // don't trigger the animation again
                return;
            } else {
                // reset position of info box
                beingShown = true;

                info.css({
                    top: -90,
                    left: -33,
                    display: 'block'
                }).animate({
                    top: '-=' + distance + 'px',
                    opacity: 1
                }, time, 'swing', function() {
                    beingShown = false;
                    shown = true;
                });
            }

            return false;
        }).mouseout(function () {
            if (hideDelayTimer) clearTimeout(hideDelayTimer);
            hideDelayTimer = setTimeout(function () {
                hideDelayTimer = null;
                info.animate({
                    top: '-=' + distance + 'px',
                    opacity: 0
                }, time, 'swing', function () {
                    shown = false;
                    info.css('display', 'none');
                });

            }, hideDelay);

            return false;
        });
    });
});


function mapsize() {
	//Get the window height and width  
	var winH = $(window).height();
	var winW = $(window).width();
	var position = $('#container').position().top+2;
	$('#container').css({
		'height': (winH-position)+'px'
	});
	position = $('#colgauche').position().top+2;
	//alert(winH+" "+$('#container').height());
	$('#coldroite').css({
		'width': (winW-$('#colgauche').width()-50)+'px',
		'height': (winH-position)+'px'
	});
	if($('#infogeouser').position()) {
		position = position+$('#infogeouser').position().top+20;
	}
	if($('#slider-proxim-mod').position()) {
		position = position+$('#slider-proxim-mod').position().top+32;
	}
	
	$('#map_markers').css({
		'width': (winW-$('#colgauche').width()-80)+'px',
		'height': (winH-position)+'px'
	});
	mapdisplay = $('#map_markers').width();
	if ($('#map_markers').height() < mapdisplay) mapdisplay = $('#map_markers').height();
	//alert($('#container').height());
}

function cremap() {
	animeListAnnonces();
	// Try W3C Geolocation (Preferred)
	/*
	if(navigator.geolocation) {
		browserSupportFlag = true;
		navigator.geolocation.getCurrentPosition(function(position) {
			alert(position.coords.latitude+' '+position.coords.longitude);
			//map.setCenter(initialLocation);
		});
	}
	*/
	var zoom = 5;
	if (rayon != 0) {
		if (rayon>0) drawCircle(rayon,lat,lon,false);
		var minlat = circleLatLngs[0].lat();// [Minimum Latitude];
		var maxlat = circleLatLngs[0].lat();// [Maximum Latitude];
		var minlng = circleLatLngs[0].lng();// [Minimum Longitude];
		var maxlng = circleLatLngs[0].lng();// [Maximum Longitude];
		var ctrlat = lat;// [Center Longitude];
		var ctrlng = lon;// [Center Longitude];
		for (var i = 0; i < circleLatLngs.length; i++) {
			if (circleLatLngs[i].lat() < minlat) minlat = circleLatLngs[i].lat();
			if (circleLatLngs[i].lat() > maxlat) maxlat = circleLatLngs[i].lat();
			if (circleLatLngs[i].lng() < minlng) minlng = circleLatLngs[i].lng();
			if (circleLatLngs[i].lng() > maxlng) maxlng = circleLatLngs[i].lng();
		}
		var interval = 0;

		if ((maxlat - minlat) > (maxlng - minlng)) {
			interval = (maxlat - minlat) / 2;
			minlng = ctrlng - interval;
			maxlng = ctrlng + interval;
		} else {
			interval = (maxlng - minlng) / 2;
			minlat = ctrlat - interval;
			maxlat = ctrlat + interval;
		}

		var dist = (6371 * Math.acos(Math.sin(minlat / 57.2958) * Math.sin(maxlat / 57.2958) + (Math.cos(minlat / 57.2958) * Math.cos(maxlat / 57.2958) * Math.cos((maxlng / 57.2958) - (minlng / 57.2958)))));

		zoom = Math.floor(8 - Math.log(1.6446 * dist / Math.sqrt(2 * (mapdisplay * mapdisplay))) / Math.log (2));
		
	}
	//alert(zoom);
	if (document.getElementById('map_markers') != null) {
		var myOptions = {
				zoom: zoom,
				center: new google.maps.LatLng(lat,lon),
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				mapTypeControl: true,
			    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
				scrollwheel: false
		}
		map = new google.maps.Map(document.getElementById("map_markers"),
				myOptions);
		infoWindow = new google.maps.InfoWindow();
		markerBounds = new google.maps.LatLngBounds();
	    
		setMarkers(rayon);
		if (rayon>0) drawCircle(rayon,lat,lon,true);
	}
}

function setMarkers(rayon) {
	image = new google.maps.MarkerImage('/images/adsflag.png',
		// This marker is 20 pixels wide by 32 pixels tall.
		new google.maps.Size(20, 32),
		// The origin for this image is 0,0.
		new google.maps.Point(0,0),
		// The anchor for this image is the base of the flagpole at 0,32.
		new google.maps.Point(0, 32));
	shadow = new google.maps.MarkerImage('/images/adsflag_shadow.png',
		// The shadow image is larger in the horizontal dimension
		// while the position and offset are the same as for the main image.
		new google.maps.Size(37, 32),
		new google.maps.Point(0,0),
		new google.maps.Point(0, 32));
	// Shapes define the clickable region of the icon.
	shape = {
		coord: [1, 1, 1, 20, 18, 20, 18 , 1],
		type: 'poly'
	};
	for (var i = 0; i < adsmarker.length; i++) {
		var latlng = new google.maps.LatLng(adsmarker[i][1], adsmarker[i][2]);
		var marker = createMarker(adsmarker[i], latlng);
		var sidebar = document.getElementById('position'+i);
		var sidebarEntry = createSidebarEntry(marker,adsmarker[i][5],i);
		sidebar.appendChild(sidebarEntry);
	}
	if (rayon == 0 && adsmarker.length>0) 
		rebound(map);
}


function createMarker(adsmarker, latlng) {
	var marker = new google.maps.Marker({
		position: latlng,
		map: map,
		title: adsmarker[0],
		shadow: shadow,
		icon: image,
		shape: shape,
		zIndex: adsmarker[3]
		});
	google.maps.event.addListener(marker, "click", function() {
		if (infowindow) infowindow.close();
		infowindow = new google.maps.InfoWindow({content: adsmarker[4]});
		infowindow.open(map, marker);
	});
	return marker;
}

function rebound(mymap){
	bounds = new google.maps.LatLngBounds();
	for (var i = 0; i < adsmarker.length; i++) {
		bounds.extend(new google.maps.LatLng(adsmarker[i][1], adsmarker[i][2]));
	}
	mymap.fitBounds(bounds);
}

function drawCircle(radius,lat,lon,adonmap) {
		
		var distance_longitude = 111 * Math.cos(Math.PI * (lat) / 180 );
		var circleLat = radius / 111;  // Convert statute km into degrees latitude
		var circleLng = radius / distance_longitude;
		var pasendegre = 360/numPoints;
		
		if (adonmap == true) {
			var polygon = new google.maps.Polygon({
			      paths: circleLatLngs,
			      strokeColor: "#3D7D00",
			      strokeOpacity: 0.6,
			      strokeWeight: 3,
			      fillColor: "#00DD00",
			      fillOpacity: 0.35
			    });
	
			polygon.setMap(map);
		} else {
			// 2PI = 360 degrees, +1 so that the end points meet
			circleLatLngs = new Array();
			for (var i = 0; i < numPoints; i++) { 
				var theta = Math.PI * (i / (numPoints / 2)); 
				var vertexLat = lat + (circleLat * Math.sin(theta)); 
				var vertexLng = lon + (circleLng * Math.cos(theta));
				var vertextLatLng = new google.maps.LatLng(vertexLat, vertexLng);
				//alert('lat:'+lat +' + '+ (circleLat * Math.sin(theta))+' long:'+lon +' + '+ (circleLng * Math.cos(theta))+' avec pas '+'lat:'+lat +' + '+ (circleLat * Math.sin(pasendegre*i))+' long:'+lon +' + '+ (circleLng * Math.cos(pasendegre*i)));
				circleLatLngs.push(vertextLatLng); 
			}
		}
}

function createSidebarEntry(marker,text,id) {
	var div = document.createElement('span');
	//var html = text + ' ' + id;
	var html = text;
	//alert(html);
	div.innerHTML = html;
	div.title = infoboxtxt;
	div.style.cursor = 'pointer';
	div.style.marginBottom = '5px'; 
	google.maps.event.addDomListener(div, 'click', function() {
		google.maps.event.trigger(marker, 'click');
	});
	google.maps.event.addDomListener(div, 'mouseover', function() {
		div.style.backgroundColor = '#eee';
	});
	google.maps.event.addDomListener(div, 'mouseout', function() {
		div.style.backgroundColor = '#fff';
	});
	return div;
}
