window.addEvent=function(e,ev,f,c){if(e.addEventListener){e.addEventListener(ev,f,c);}else if(e.attachEvent){var r=e.attachEvent('on'+ev,f);return r;}else{e['on'+ev]=f;}};
window.removeEvent=function(e,ev,f){if(e.removeEventListener){e.removeEventListener(ev,f,false);}else if(e.detachEvent){e.detachEvent("on"+ev,e[ev+f]);e[ev+f]=null;e["e"+ev+f]=null;}else{e['on'+ev]=null;}};

/**
 * Set the variables for Google Maps
 */
var myLocation = 'Belgium';
var markerImage = new google.maps.MarkerImage('images/marker.png', new google.maps.Size(30, 50), new google.maps.Point(0,0), new google.maps.Point(15, 50));
var markerShadow = new google.maps.MarkerImage('images/marker-shadow.png', new google.maps.Size(39, 30), new google.maps.Point(0,0), new google.maps.Point(2, 30));
var geocoder;
var map;
var myMarkers = new Array();
var currentInfoWindow;

/**
 * Add dealers to Google Maps
 * @param json
 * @return
 */
function addDealersToMap (json)
{
	// Remove the current dealers shown in the list and from the map
	jQuery('#dealers .dealer').remove();
	for (var markerId in myMarkers) {
		myMarkers[markerId].setMap(null);
	}

	myMarkers = new Array();
	var points = [];

	// Add the new dealers to Google Maps
	for (var i=0; i<json.length; i++) {
		// Create the marker
		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(json[i].latitude, json[i].longitude),
			map: map,
			shadow: markerShadow,
			icon: markerImage,
			title: json[i].name
		});

		// Create the information window
		json[i].address += (json[i].zipcode ? '<br\/>' + json[i].zipcode : '') + (json[i].city ? (json[i].zipcode ? ' ' : '<br\/>') + json[i].city : '');
		json[i].address += (json[i].phone ? '<br\/>Tel: ' + json[i].phone : '');
		json[i].address += (json[i].fax ? '<br\/>Fax: ' + json[i].fax : '');

		marker.infoWindow = new google.maps.InfoWindow({
				content:	'<strong>' +
							json[i].company +
							'<\/strong><br\/>' +
							json[i].address +
							'<br\/><br\/><a href="javascript:;" onclick="return markAsDealer('+json[i].id+');">Mark as my dealer<\/a>'
			});

		// Only show the first 20 dealers in the dealers list
		if (i<50) {
			var dealer = jQuery('<div class="dealer"><\/div>')
				.addClass(json[i].starred ? 'starred' : '')
				.append(
						jQuery('<h4><\/h4>')
							.html(json[i].company)
							.attr('rel', json[i].id)
							.click(function(){
									google.maps.event.trigger(myMarkers[jQuery(this).attr('rel')], 'click');
								})
					)
				.append(jQuery('<p><\/p>').html(json[i].address));
			if (json[i].website) {jQuery('p:last', dealer).append('<br\/>').append(jQuery('<a target="_blank"><\/a>').attr('href', json[i].website).attr('rel', 'external').html(json[i].website));}
			if (json[i].email) {jQuery('p:last', dealer).append('<br\/>').append(jQuery('<a><\/a>').attr('href', 'mailto:'+json[i].email).html(json[i].email));}

			jQuery('#dealers').append(dealer);
		}

		// Set the events for the information window
		google.maps.event.addListener(marker, 'click', function(){
			if (currentInfoWindow) {
				currentInfoWindow.close();
			}
			this.infoWindow.open(map, this);
			currentInfoWindow = this.infoWindow;
		});

		// Add the marker to the list for later reference
		marker.json = json[i];
		myMarkers[json[i].id] = marker;
		if (json[i].starred) {
			markAsDealer(json[i].id);
		}

		points.push( marker.position );
	}

	// Zoom in/out to fit all the dealers on the map
	fitMap(map, myMarkers);
	jQuery('input').removeClass('busy');
}

/**
 * Zoom in or out to fit all shown markers on the map.
 */
function fitMap(map, markers)
{
	var bounds = new google.maps.LatLngBounds();
	for (var i in markers) {
		bounds.extend(markers[i].position);
	}
	map.fitBounds(bounds);
}

/**
 * Mark a dealer as My dealer
 * @param string dealerId
 * @return bool false
 */
function markAsDealer (dealerId)
{
	jQuery.cookie('myDealer', dealerId);
	jQuery('.starred').removeClass('starred');
	jQuery('h4[rel='+dealerId+']').parent().addClass('starred');

	var dealer = jQuery('<div class="dealer"><\/div>')
		.append(
				jQuery('<h4><\/h4>')
					.html(myMarkers[dealerId].json.company)
					.click(function(){
							google.maps.event.trigger(myMarkers[jQuery(this).attr('rel')], 'click');
						})
			)
		.append(jQuery('<p><\/p>').html(myMarkers[dealerId].json.address));
	if (myMarkers[dealerId].json.website) {jQuery('p:last', dealer).append('<br\/>').append(jQuery('<a target="_blank"><\/a>').attr('href', myMarkers[dealerId].json.website).attr('rel', 'external').html(myMarkers[dealerId].json.website));}
	if (myMarkers[dealerId].json.email) {jQuery('p:last', dealer).append('<br\/>').append(jQuery('<a><\/a>').attr('href', 'mailto:'+myMarkers[dealerId].json.email).html(myMarkers[dealerId].json.email));}

	jQuery('#my_dealer').html('<h2>My dealer<\/h2>').append(dealer);

	return false;
}

/**
 * Refresh the dealers list
 */
function invokeDealerRefresh ()
{
	jQuery('input').addClass('busy');
	var killCache = Math.random();
	jQuery.getJSON('/find/dealer/' + jQuery('#location').val(), {'killCache':killCache}, addDealersToMap);
	return false;
}

/**
 * Initiate the map
 */
window.addEvent(window, 'load', function(){
	// Set the map settings
	geocoder = new google.maps.Geocoder();
	var myOptions = {
		zoom: 8,
		mapTypeId: google.maps.MapTypeId.HYBRID
	}
	map = new google.maps.Map(document.getElementById("google_map"), myOptions);

	geocoder.geocode({'address': myLocation}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
		}
	});
	
	jQuery('#location').autocomplete('/locationPredictor.php', {
		max: 20,
		minChars: 3,
		formatItem: function (row, i, max){
			return row[0] + ', ' + row[1];
		},
		formatResult: function (row) {
			return row[0] + ', ' + row[1];
		},
		clickHandler: function (){
			invokeDealerRefresh();
		}
	});
	
	jQuery('form').submit(invokeDealerRefresh);
	jQuery('#submitBtn').click(invokeDealerRefresh);
	invokeDealerRefresh();
});
