/**
 * Created by JetBrains PhpStorm.
 * User: ATA
 * Date: 26/05/11
 * Time: 16:22
 * @exigence	 ADSIA_BLC_LOC1, ADSIA_BLC_LOC2, ADSIA_BLC_ITI1, ADSIA_BLC_ITI2, ADSIA_BLC_LCM
 */

var map = null;
var geocoder = null;
var directionsDisplay;
var marker = null;

function showLatlng(lat, lng, zoom) {
	var latlng = new google.maps.LatLng(lat, lng);
	var myOptions = {
		zoom: zoom,
		center: latlng,
		disableDefaultUI: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	var image = new google.maps.MarkerImage(
		'/images/marker/image.png',
		new google.maps.Size(42,22),
		new google.maps.Point(0,0),
		new google.maps.Point(21,22)
	);

	var shadow = new google.maps.MarkerImage(
		'/images/marker/shadow.png',
		new google.maps.Size(56,22),
		new google.maps.Point(0,0),
		new google.maps.Point(21,22)
	);

	var shape = {
		coord: [41,0,41,1,41,2,41,3,40,4,39,5,38,6,37,7,36,8,35,9,34,10,33,11,32,12,31,13,30,14,29,15,28,16,27,17,26,18,25,19,24,20,24,21,18,21,17,20,16,19,15,18,14,17,13,16,12,15,11,14,10,13,9,12,8,11,7,10,6,9,5,8,4,7,3,6,2,5,1,4,0,3,0,2,0,1,0,0,41,0],
		type: 'poly'
	};

	marker = new google.maps.Marker({
		draggable: false,
		raiseOnDrag: false,
		icon: image,
		shadow: shadow,
		shape: shape,
		map: map,
		position: latlng
	});

	geocoder = new google.maps.Geocoder();
	geocoder.geocode({'latLng': latlng}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			if (results[0]) {
				map.fitBounds(results[0].geometry.viewport);
			}
		}
	});

}

function showEntites(entites) {
	var infowindow = null;
	var bounds = new google.maps.LatLngBounds();
	var myOptions = {
		zoom: 11,
		center: new google.maps.LatLng(0, 0),
		disableDefaultUI: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	var image = new google.maps.MarkerImage(
		'/images/marker/image.png',
		new google.maps.Size(42,22),
		new google.maps.Point(0,0),
		new google.maps.Point(21,22)
	);

	var shadow = new google.maps.MarkerImage(
		'/images/marker/shadow.png',
		new google.maps.Size(56,22),
		new google.maps.Point(0,0),
		new google.maps.Point(21,22)
	);

	var shape = {
		coord: [41,0,41,1,41,2,41,3,40,4,39,5,38,6,37,7,36,8,35,9,34,10,33,11,32,12,31,13,30,14,29,15,28,16,27,17,26,18,25,19,24,20,24,21,18,21,17,20,16,19,15,18,14,17,13,16,12,15,11,14,10,13,9,12,8,11,7,10,6,9,5,8,4,7,3,6,2,5,1,4,0,3,0,2,0,1,0,0,41,0],
		type: 'poly'
	};
	infowindow = new google.maps.InfoWindow({
		content: "holding...",
		maxWidth: 300
	});
	for (var i = 0; i < entites.length; i++) {
		var entite = entites[i];
		var latLng = new google.maps.LatLng(entite[1], entite[2]);
		var marker = new google.maps.Marker({
			draggable: false,
			raiseOnDrag: false,
			icon: image,
			shadow: shadow,
			shape: shape,
			map: map,
			position: latLng,
			title: entite[0],
			html: '<div class="coordinated" style="border: none;min-height: 150px;width:300px;padding: 0;"><div>'+
        '<ul>'+
          '<li class="sprite-icon-adress" style="width:280px">'+
            '<dl style="width:250px">'+
              '<dt>'+
                '<strong>'+((entite[6]!='')?'<a href="'+entite[6]+'" target="_blank">'+entite[0]+'</a>':entite[0])+'</strong>'+
              '</dt>'+
              '<dd>'+entite[3]+'</dd>'+
            '</dl>'+
          '</li>'+
          '<li class="sprite-icon-tel" style="width:280px">'+
						'<dl style="width:250px">'+
							'<dt><strong>Téléphone </strong></dt>'+
							'<dd>'+entite[4]+'</dd>'+
						'</dl>'+
          '</li>'+
         '</ul><ul class="right-column">'+
            '<li class="sprite-icon-email" style="width:280px;padding-bottom: 0">'+
                '<dl style="width:250px">'+
                  '<dt><strong>Email</strong></dt>'+
                  '<dd><a href="mailto:'+entite[5]+'">'+entite[5]+'</a></dd>'+
                '</dl>'+
              '</li>'+
        '</ul>'+
                '</div>'+
        '</div>'+
     ' </div>'
		});

		google.maps.event.addListener(marker, 'click', function () {
			infowindow.setContent(this.html);
			infowindow.open(map, this);
		});

		bounds.extend(latLng);
	}

	map.fitBounds(bounds);
}

function showFrance() {
	showAddress('France', function () {
	if (jQuery.trim(jQuery('#lat').val()) != '' && jQuery.trim(jQuery('#long').val()) != '') {
		var bounds = new google.maps.LatLngBounds();
		lat = jQuery.trim(jQuery('#lat').val());
		long = jQuery.trim(jQuery('#long').val());
		bounds.extend(distinationByDistanceAndBearing(lat, long, 450, -45));
		bounds.extend(distinationByDistanceAndBearing(lat, long, 450, 135));
		map.fitBounds(bounds);
	}});
}

function showAddress(address, callback) {
	geocoder = new google.maps.Geocoder();
	geocoder.geocode({ 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {

			var image = new google.maps.MarkerImage(
				'/images/marker/image.png',
				new google.maps.Size(42,22),
				new google.maps.Point(0,0),
				new google.maps.Point(21,22)
			);

			var shadow = new google.maps.MarkerImage(
				'/images/marker/shadow.png',
				new google.maps.Size(56,22),
				new google.maps.Point(0,0),
				new google.maps.Point(21,22)
			);

			var shape = {
				coord: [41,0,41,1,41,2,41,3,40,4,39,5,38,6,37,7,36,8,35,9,34,10,33,11,32,12,31,13,30,14,29,15,28,16,27,17,26,18,25,19,24,20,24,21,18,21,17,20,16,19,15,18,14,17,13,16,12,15,11,14,10,13,9,12,8,11,7,10,6,9,5,8,4,7,3,6,2,5,1,4,0,3,0,2,0,1,0,0,41,0],
				type: 'poly'
			};

			var latlng = results[0].geometry.location;
			var myOptions = {
				zoom: 11,
				center: latlng,
				disableDefaultUI: true,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			}
			map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
			map.fitBounds(results[0].geometry.viewport);
			if (address != 'France') {
				marker = new google.maps.Marker({
					draggable: false,
					raiseOnDrag: false,
					icon: image,
					shadow: shadow,
					shape: shape,
					map: map,
					position: results[0].geometry.location
				});
			}
			else {
				if (typeof(callback) != 'undefined') {
					callback();
				}
			}
		} else {//RG: RG_ADSIA_BLC_LOC1_05
			jQuery(".img_map").hide();
		}
	});
}

function showItineraire(depart, arrivee) {
	var directionsService = new google.maps.DirectionsService();
	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsDisplay.setMap(map);
	directionsDisplay.setPanel(document.getElementById('displayinfo_canvas'));
	directionsService.route({
		origin: depart,
		destination: arrivee,
		unitSystem: google.maps.DirectionsUnitSystem.METRIC,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	}, function(result, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.suppressMarkers = true;
			var image = new google.maps.MarkerImage('/images/greenA.png');
			var markerA = new google.maps.Marker({
				map: map,
				icon: image,
				position: result.routes[0].legs[0].start_location
			});

			marker.setPosition(result.routes[0].legs[0].end_location);

			if ($.browser.msie) {
				google.maps.event.addListener(map, 'idle', function() {
					applyStyle();
				});
			}

			directionsDisplay.setDirections(result);

			jQuery("#displayinfo_title").show();
			jQuery("#displayinfo_canvas").show();
			jQuery(".adress_garage").show();
		} else {
			jQuery("#displayinfo_title").hide();
			jQuery("#displayinfo_canvas").hide();
			jQuery(".adress_garage").hide();

			$("#popup2").slideDown();
			$("#popup_block").css("display", "block");

			$("#popup2 .icon_close").click(function(event) {
				event.preventDefault();
				$("#popup2").css("display", "none");
				$("#popup_block").css("display", "none");
			});
		}
	});
}

function getLatLongAndSubmit(address) {

	if (jQuery.trim(address) == '') {
		jQuery('#msg_erreur').text('Veuillez saisir une ville ou un code postal');
		$("#popup2").slideDown();
		$("#popup_block").css("display", "block");

		$("#popup2 .icon_close").click(function(event) {
			event.preventDefault();
			$("#popup2").css("display", "none");
			$("#popup_block").css("display", "none");
		});

		return;
	}

	geocoder = new google.maps.Geocoder();

	address = address + ' France';
	geocoder.geocode({ 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var latLong = results[0].geometry.location;
			jQuery('#lat').val(latLong.lat());
			jQuery('#long').val(latLong.lng());
			jQuery('#recherche_garages').submit();

			return;
		} else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
			jQuery('#msg_erreur').text('Ville ou CP erroné');
		} else {
			jQuery('#msg_erreur').text('Erreur non identifié');
		}

		$("#popup2").slideDown();
		$("#popup_block").css("display", "block");

		$("#popup2 .icon_close").click(function(event) {
			event.preventDefault();
			$("#popup2").css("display", "none");
			$("#popup_block").css("display", "none");
		});
	});
}
function gmap_draw(){

		geocoder = new google.maps.Geocoder();

	address = jQuery('#search2').val() + ' France';
	geocoder.geocode({ 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var latLong = results[0].geometry.location;
			jQuery('#lat-search').val(latLong.lat());
			jQuery('#long-search').val(latLong.lng());
		}

		jQuery('#find-garage').submit();

		return;
	});
};
function getLatLongAndSubmit2() {
	 var s = document.createElement("script");
   s.type = "text/javascript";
   s.src  = "http://maps.google.com/maps/api/js?sensor=false&language=fr&.js&callback=gmap_draw";
   $("head").append(s);
}

function applyStyle() {
	jQuery("#content #displayinfo_canvas > div > div:first-child + div + div > *:first-child + div tr:last-child > td:first-child + td > div").addClass('votre_destination');
	jQuery("#content #displayinfo_canvas > div > div:first-child + div + div > div:last-child").addClass('garage');
	jQuery("#content #displayinfo_canvas > div > div:first-child + div + div > *:first-child + div tr td:last-child").addClass('distances');
}

function distinationByDistanceAndBearing(lat, long, distance, bearing) {
	var d = parseInt(distance, 10) / 6371;
	var lat1 = parseFloat(lat) * Math.PI / 180;
	var lon1 = parseFloat(long) * Math.PI / 180;
	var brng = parseInt(bearing, 10) * Math.PI / 180;
	var dLat = d * Math.cos(brng);
	var lat2 = lat1 + dLat;
	var dPhi = Math.log(Math.tan(lat2 / 2 + Math.PI / 4) / Math.tan(lat1 / 2 + Math.PI / 4));
	var q = (!isNaN(dLat / dPhi)) ? dLat / dPhi : Math.cos(lat1);  // E-W line gives dPhi=0
	var dLon = d * Math.sin(brng) / q;
	// check for some daft bugger going past the pole
	if (Math.abs(lat2) > Math.PI / 2) lat2 = lat2 > 0 ? Math.PI - lat2 : -(Math.PI - lat2);
	lon2 = (lon1 + dLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI;


	var latlong = new google.maps.LatLng(lat2 * 180 / Math.PI, lon2 * 180 / Math.PI);
	return latlong;
}

function getLatLong(address) {
	geocoder = new google.maps.Geocoder();
	address = address + ' France';
	geocoder.geocode({ 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var latLong = results[0].geometry.location;
						
			jQuery('#cpLatitude').val(latLong.lat());
			jQuery('#cpLongitude').val(latLong.lng());
			
			jQuery('#latLongSearch').submit();
			
			return;
		} 
	});
}
