var geocoder, map, directionsDisplay, addressMarker, fromAddress, toAddress, directionsService;


$(function() {
	GMapsInitialize();
});


function GMapsInitialize() {
	if( $('address#toDirections').length == 0 || $('.address-panel').length == 0 || $('#GoogleErrors').length == 0 || $('#GoogleDirections').length == 0 || $('#map_canvas').length == 0 )
		return;

	// settings
	var companyLatLng     = new google.maps.LatLng( $('address#toDirections').data('lat') , $('address#toDirections').data('lon') );
	var defaultZoomLevel  = parseInt( $('address#toDirections').data('zoom') );
	
	var myOptions = {
		zoom: defaultZoomLevel,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		center: companyLatLng,

		disableDefaultUI: true,
		
		zoomControl: true,
		zoomControlOptions: {
			style: google.maps.ZoomControlStyle.SMALL
		},
		
		mapTypeControl: true,
		mapTypeControlOptions: {
			style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
		},
		
		overviewMapControl: false
	};
	// end settings
	
	
	// Initialize the Geocoder
	geocoder = new google.maps.Geocoder();

	// Try to find the user
	$.geolocation.find( function( location ) {
		
		// Location has been found
		var userLocation = new google.maps.LatLng( location.latitude, location.longitude );
					
		var UserLocationCity = '';
		var UserLocationZip = '';
		var UserLocationStreet = '';
		var UserLocationHouseNumber = '';
		var UserLocationCountry = '';
		
		// Try to geocode back into an address
	    geocoder.geocode( { 'latLng': userLocation }, function( results, status ) {

	        if( status == google.maps.GeocoderStatus.OK && results[0].address_components ) {
				$.each( results[0].address_components, function( index, value ) { 
					switch( value.types[0] ) {
						case 'street_number':
							UserLocationHouseNumber = value.long_name;
							break;
						case 'route':
							UserLocationStreet = value.long_name;
							break;
						case 'locality':
							UserLocationCity = value.long_name;
							break;
						case 'postal_code':
							UserLocationZip = value.long_name;
							break;
						case 'country':
							UserLocationCountry = value.long_name;
							break;
					}
				});
				
				$( '.address-panel input#country' ).val( UserLocationCountry );
				$( '.address-panel input#street' ).val( UserLocationStreet + ' ' + UserLocationHouseNumber );
				$( '.address-panel input#city' ).val( UserLocationCity );
				$( '.address-panel input#zip' ).val( UserLocationZip );
	        }
	    });
	}, function() {
		// Geolocation not supported
	});
	
	var rendererOptions = {
		draggable: true
	};
	
	// Setup elements
	map = new google.maps.Map( $("#map_canvas").get( 0 ), myOptions );
	
	directionsService = new google.maps.DirectionsService();
	directionsDisplay = new google.maps.DirectionsRenderer( rendererOptions );
	
	directionsDisplay.setMap( map );
	directionsDisplay.setPanel( $("#GoogleDirections").get( 0 ) );
	
	// Add Layers
	var trafficLayer = new google.maps.TrafficLayer();
	trafficLayer.setMap( map );

	// set company marker
	setTimeout( function() { addHotelMarker( companyLatLng ); }, 2000 );
	
	// Add autocomplete
	$( '.address-panel #street' ).live( 'focus', function() {
		$( this ).autocomplete({
			source: function( request, response ) {
				geocoder.geocode( { 'address': request.term }, function( results, status ) {

					response( $.map( results, function( item ) {

						var UserLocationCity = '';
						var UserLocationZip = '';
						var UserLocationStreet = '';
						var UserLocationHouseNumber = '';
						var UserLocationCountry = '';

						
						if( status == google.maps.GeocoderStatus.OK && item.address_components ) {
							$.each( item.address_components, function( index, value ) { 
								switch( value.types[0] ) {
									case 'street_number':
										UserLocationHouseNumber = value.long_name;
										break;
									case 'route':
										UserLocationStreet = value.long_name;
										break;
									case 'locality':
										UserLocationCity = value.long_name;
										break;
									case 'postal_code':
										UserLocationZip = value.long_name;
										break;
									case 'country':
										UserLocationCountry = value.long_name;
										break;
								}
							});
						}
						
						return {
							label: item.formatted_address,
							value: UserLocationStreet + ' ' + UserLocationHouseNumber,
							location: item.geometry.location,
							addr: item.address_components[0],
							street: UserLocationStreet + ' ' + UserLocationHouseNumber,
							zip: UserLocationZip,
							city: UserLocationCity,
							country: UserLocationCountry
						}
					}));
				})
			},
			
			minLength: 3,
			
			select: function( event, ui ) {
				$( '.address-panel input#country' ).val( ui.item.country );
				$( '.address-panel input#city' ).val( ui.item.city );
				$( '.address-panel input#zip' ).val( ui.item.zip );
			}
		});
	});
}

function addHotelMarker( companyLatLng ) {
	var hotelMarker = createMarker( 
		companyLatLng, // Icon lat/lon
		GMapsIcon, // Image file
		new google.maps.Size( 32, 37 ), // Image size
		new google.maps.Point( 15, 35 ), // Image base point
		GMapsShadow, // Shadow image
		new google.maps.Size( 51, 37 ), // Shadow image size
		GMapsIconTitle, // Icon title
		false // No dragging
	);
	

	/* var infowindow = new google.maps.InfoWindow({
	    content: '<div id="GMapsBalloonContent">' + GMapsBalloonContent + '</div>',
		maxWidth: 200
	});

	google.maps.event.addListener( hotelMarker, 'click', function() {
		infowindow.open( map, hotelMarker );
	});
	
	infowindow.open( map, hotelMarker ); */
}

function overlayDirections() {
    var fromAddress = $('#street').val() + ', ' + $('#zip').val() + ' ' + $('#city').val() + ', ' + $('#country').val();
	var toAddress = $('address#toDirections').data( 'googleAddress' );

	var request = {
		origin: fromAddress,
		destination: toAddress,
		travelMode: google.maps.TravelMode.DRIVING,
		unitSystem: google.maps.UnitSystem.METRIC,
		provideRouteAlternatives: true,
		avoidHighways: false,
		avoidTolls: false,
		region: GMapsRegion
	};
	
	directionsService.route( request, function( result, status ) {
		if( status == google.maps.DirectionsStatus.OK ) {
			directionsDisplay.setDirections( result );
		} else {
			$('#GoogleErrors').html( GMapsErrors_NotFound  );  
		}
	});

	return false;
}

function createMarker( latlng, imageURL, imageSize, anchorPoint, shadowURL, shadowSize, iconTitle, draggable ) {
    return new google.maps.Marker({
        position: latlng,
        map: map,
		draggable: draggable,
		animation: google.maps.Animation.DROP,
        shadow: new google.maps.MarkerImage( shadowURL, shadowSize, new google.maps.Point( 0, 0 ), anchorPoint ),
        icon: new google.maps.MarkerImage( imageURL, imageSize, new google.maps.Point( 0, 0 ), anchorPoint ),
        title: iconTitle,
        zIndex: 1
    });
}

