$(
	function ()
	{
		$('img[rel=hover]').hover (function () { hoverImage (this); }, function () { hoverImage (this); } );

		$('#dealer-details-email').live ('focus',
			function ()
			{
				var email	= $(this);
				if (email.val () == 'email')
				{
					email.val ('');
				}
			}
		);

		$('#dealer-details').live ('click',
			function ()
			{
				var email	= $('#dealer-details-email');
				var result	= $('#dealer-details-result').hide ();
				var form	= $('#dealer-details-form');
				var button	= $(this);
				var dealer	= button.attr ('rel');
				var message	= '';
				
				if (/^[A-Z0-9._+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i.test (email.val ()) != true)
				{
					message	= 'Ongeldig e-mail adres';
					result.text (message).show ();
					email.focus ();
					return false;
				}

				var data	= {"email": email.val (), "d_id": dealer};
				var call	= $.post ('ajax/dealer-details.php', data,
									function (data)
									{
										switch (data)
										{
											case 'DEALER':
												message	= 'Er is een technische fout voorgekomen. Probeert u het nogmaals.';
											break;
											case 'EMAIL':
												message	= 'Ongeldig e-mail adres.';
												email.focus ();
												return;
											break;
											case 'MAIL':
												message	= 'Wegens technische problemen is het niet mogelijk om op dit moment e-mail te versturen. Probeer het nogmaals.';
											break;
											case 'SUCCESS':
												message	= 'De dealer gegevens zijn naar je toegestuurd.'
											break;
										}

										result.text (message).show ();
										
									}
								);
			}
		);

		setTimeout (
			function ()
			{
				Core.init ();
				var controls	= $('#google-map-custom-controls');
				
				var dSelect		= $('.dealer-select', controls);
				var _dSelect	= $('#dealer-select');
				var dDialog		= $('#dealer-dialog');
				
				controls.prependTo ('#google-map');
				
				$('#ajax-loader').prependTo ('#google-map');
				
				if (dSelect.length > 0 && _dSelect.length > 0)
				{
					_dSelect.dialog ({
							title: 'ZOEK EEN ALFA ROMEO DEALER',
							autoOpen: false,closeOnEscape: true,draggable: false,modal: true,bgiframe: true,height: 200,width: 600,resizable: false,
							buttons: {
								Sluiten: function ()
								{
									$('#dealer-select').dialog ('close');
								},
								'Zoek dealer': function ()
								{
									userPosition ($('#dealer-select'));
								}
							}
						}
					);
					
					dSelect.bind ('click',
						function ()
						{
							_dSelect.load ('ajax/dealer-select.php',
								function ()
								{
									_dSelect.find ('.autocomplete').autocomplete ({
										source: dealerNames, minLength: 1
									});
									_dSelect.find ('.autocomplete').change (
										function ()
										{
											if (typeof dealerIds[$(this).val ()] === 'undefined')
												return false;
											
											$('#dealer-select').dialog ('close');
											$('#dealer-dialog').load ('ajax/dealer-dialog.php?d_id=' + dealerIds[$(this).val ()],
												function ()
												{
													dialogButtons ();
												}
											).dialog ('open');
											
										}
									);
									_dSelect.dialog ('open');
									
									_dSelect.find ('input:first').focus ().keydown (
										function (e)
										{
											if (e.keyCode == 13)
											{
												userPosition (_dSelect);
											}
										}
									);
									
								}
							);
						}
					);
				}
				
				if (dDialog.length > 0)
				{
					dDialog.dialog ({
							title: 'ALFA ROMEO DEALER INFORMATIE',
							autoOpen: false,closeOnEscape: true,draggable: false,modal: true,bgiframe: true,height: 330,width: 600,resizable: false,
							buttons: {
								Sluiten: function ()
								{
									$('#dealer-dialog').dialog ('close');
								}
							},
							open: function ()
							{
								$('#dealer-dialog').empty ().text ('Dealerinformatie laden..');
							}
						}
					);
				}
				
				
				setTimeout (
					function ()
					{
						Core.placeMarker ();
					}
				, 100);
			}, 200);
	}
);

function userPosition (dialog)
{
	if (Core.userPositionMarker !== null)
	{
		Core.GMap.removeOverlay (Core.userPositionMarker);
	}
	var address	= dialog.find ('input:first').val ();
	
	if (address.length > 2)
	{
		Core.userPosition (address, dialog);
	}
	else
	{
		$('.error', dialog).show ();
	}
}

function dialogButtons ()
{
	setTimeout (
		function ()
		{
			var	dDialog	= $('#dealer-dialog');
			
			dDialog.find ('.button').button ();
		}
	, 100);
}

function hoverImage (e)
{
	var e	= $(e);
	var src	= e.attr ('src');
	
	if (src.match (/_h\.png/))
	{
		src	= src.replace (/_h\.png/, '.png');
	}
	else
	{
		if (!src.match (/_s\.png/))
		{
			src	= src.replace (/\.png/, '_h.png');
		}
	}
	
	e.attr ('src', src);

}

var Core	= {
		placeMarkers: new Array (),
		placeMarkersCurrent: 0,
		GMap: null,
		GBounds: null,
		userPositionMarker: null,
		icons: {prospect: null, client: null},
		finishLoading: function ()
		{
			$('#ajax-loader').fadeOut (function () { $('#ajax-loader').remove () });
		},
		init: function ()
		{
			
			var map		= $('#google-map');

			if (GBrowserIsCompatible())
			{
				Core.GMap = new GMap2 (map[0]);
				
				var point	= new GLatLng (
											52.132633,
											5.291266
										);
				Core.GMap.setCenter (point, 8);
				Core.GBounds	= new GLatLngBounds ();
				Core.GMap.setMapType (G_PHYSICAL_MAP);
				var GMapUI = Core.GMap.getDefaultUI();

				GMapUI.maptypes.normal				= false;
				GMapUI.maptypes.satellite			= false;
				GMapUI.maptypes.physical			= false;
				GMapUI.controls.scalecontrol		= false;
				GMapUI.controls.largemapcontrol3d	= false;
				GMapUI.controls.smallzoomcontrol3d	= false;
				GMapUI.controls.maptypecontrol		= false;
				GMapUI.controls.menumaptypecontrol	= false;
						
				Core.GMap.setUI (GMapUI);

				initialize ();

				Core.icons.dealer = new GIcon(G_DEFAULT_ICON);
				Core.icons.dealer.image			= 'assets/img/alfa_pointer.png';
				Core.icons.dealer.iconSize.height	= 32;
				Core.icons.dealer.iconSize.width	= 32;




				Core.icons.user = new GIcon(G_DEFAULT_ICON);
				Core.icons.user.image			= 'assets/img/blue-dot.png';
				Core.icons.user.iconSize.height	= 32;
				Core.icons.user.iconSize.width	= 32;
			}
			else
			{
				alert ('Browser incompatibility cannot load map.');
			}
		},
		placeMarker: function ()
		{			
			var p		= Core.placeMarkers[Core.placeMarkersCurrent];
			var lat		= p.lat;
			var lng		= p.lng;
			var h		= p.h;
			var t		= p.t;
			var id		= p.id;
			var marker, icon;
			var point	= new GLatLng (
										lat,
										lng
									);
			
			Core.GBounds.extend (point);
			
			icon	= Core.icons.dealer;

			marker = new GMarker(point, {icon: icon});
			
			GEvent.addListener(marker, 'click',
				function()
				{
					$('#dealer-dialog').load ('ajax/dealer-dialog.php?d_id=' + id,
						function ()
						{
							dialogButtons ();
						}
					).dialog ('open');
					//marker.openInfoWindow (h);
				}
			);

			Core.GMap.addOverlay(marker);
			
			
			if (Core.placeMarkersCurrent == (Core.placeMarkers.length - 1))
			{
				//Core.GMap.setCenter (Core.GBounds.getCenter (), Core.GMap.getBoundsZoomLevel (Core.GBounds));
				$('#ajax-loader').remove ();
			}
			else
			{
				Core.placeMarkersCurrent++;
				Core.placeMarker ();
			}
			return marker;

		},
		userPosition: function (address, dialog)
		{
			var geocoder	= new GClientGeocoder();
			var marker		= geocoder.getLocations (address + ', Nederland',
				function (r) {
					Core.__userPosition (dialog, r);
					}
				);
		},
		__userPosition: function (dialog, r)
		{
			if (typeof r.Placemark === 'undefined')
			{
				$('.error', dialog).show ();
			}
			else
			{
				r	= r.Placemark[0];
				var point	= new GLatLng (r.Point.coordinates[1], r.Point.coordinates[0]);
				
				Core.GBounds.extend (point);
				icon	= Core.icons.user;
	
				Core.userPositionMarker = new GMarker (point, {icon: icon});
				Core.GMap.addOverlay (Core.userPositionMarker);
				Core.userPositionMarker.openInfoWindowHtml ('Klik op het Alfa Romeo logo om de <br>gegevens van deze dealer te bekijken');
				Core.GMap.setCenter (point, 10);
				dialog.dialog ('close');
			}
		}
		
		
	};
