/**
 * @author jap
 */


/** 
 * spottingMap
 * 
 * extends overviewMap
 * enables clicking the map and adding spottings * 
 * 
 ******************/

function overviewMap(elementId) {

	var self = this;
	
	this.markers         = new Array;
	this.geocoder 		 = new google.maps.Geocoder();
	this.infowindow      = new google.maps.InfoWindow();
	this.defaultLocation = new google.maps.LatLng(51.55716919145916, 5.086154937744141);
	this.defaultZoom     = 12;	
	this.defaultOptions = {
		zoom: this.defaultZoom,
		center: this.defaultLocation,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		
		mapTypeControl: false,
		scrollwheel: false
	};
	
	this.map = new google.maps.Map(document.getElementById(elementId), this.defaultOptions);
	
	$('#'+elementId).parents('.spotkaart').find('.searchForm').submit(function(){
		self.handleSearchForm(this);
		return false;
	});
	
	/*
	// Create our "tiny" marker icon
	this.baseIcon = new GIcon(G_DEFAULT_ICON);
	this.baseIcon.shadow = "http://www.google.com/mapfiles/ms/micons/msmarker.shadow.png";
	this.baseIcon.iconSize = new GSize(32, 32);
	this.baseIcon.shadowSize = new GSize(59, 32);
	this.baseIcon.iconAnchor = new GPoint(9, 34);
	this.baseIcon.infoWindowAnchor = new GPoint(9, 2);
	*/
	this.prepareDialogs();
	//this.loadSpottings(spottings);
}


overviewMap.prototype.handleGetLocations = function(response, status) {
	if (this.validResponse(response, status)) {
		var latlng = response[0].geometry.location;
		console.log(response[0]);
		this.map.setCenter(latlng);
		this.map.setZoom(17);
		this.openInfoWindow(latlng, '<div class="content" style="text-align: center;"><h3>'+response[0].formatted_address+'</h3></div>');
	}
};

overviewMap.prototype.handleSearchForm = function(form) {
	var address = form.adres.value;	
	if (address.toLowerCase().search('tilburg') == -1)
		address += ', Tilburg';
		
	var self = this;
	this.geocoder.geocode({address: address}, function(response, status){
		self.handleGetLocations(response, status);
	});
}

overviewMap.prototype.validResponse = function(response, status) {
	if (!response || status != google.maps.GeocoderStatus.OK) {
		this.handleResponseError(status);
		return false;
	}	
	if (!this.checkGemeente(response, 'Tilburg')){
		$('#outsidetilburg').dialog('open');
		return false;
	}
	return true;
}

overviewMap.prototype.checkGemeente = function(response, gemeente) {
	var addr = response[0].address_components;
	for (var i in addr)
		if (addr[i].types[0] == 'locality' && addr[i].long_name == gemeente)
			return true;
	
	return false;
}

overviewMap.prototype.loadSpottings = function() {
	spottings = this.spottings;
	if (spottings.length > 0) {
		for (var i in spottings) {
			var spotting = spottings[i];
			var point = new google.maps.LatLng(spottings[i].latitude, spottings[i].longitude);
			var marker = this.addSpottingToMap(point);
			    marker.id = spottings[i].id;
		}
	}
}

overviewMap.prototype.addSpottingToMap = function(point) {
	var self = this;
	var marker = this.createMarker(point);
	google.maps.event.addListener(marker, 'click', function(event) {
		self.openSpottingInfo(marker);
	});
	return marker;
};

overviewMap.prototype.createMarker = function(point) {
	var icon = (this.type == 'Nestkasten') 
				? 'images/homeicon.gif'
				: 'images/gzicon.gif';
	return new google.maps.Marker({
		map: this.map,
		position: point,
		icon: icon
	});
	
}

overviewMap.prototype.openSpottingInfo = function(marker) {
		var $table = (this.type == 'Nestkasten') 
						? $('<table class="tablesorter"><thead><tr><th>Nestkast geplaatst op</th><th>Aantal nestkasten</th></tr></thead><tbody></tbody></table><br/><br/>')
						: $('<table class="tablesorter"><thead><tr><th>datum</th><th>aantal gierzwaluwen</th><th>gedrag</th></tr></thead><tbody></tbody></table><br/><br/>');
		var $tr    = $('#originaltable').find('tbody tr#marker'+marker.id).clone(false);
		// move location from table-cell to header
		var $h3    = $('<h3>'+$tr.find('td').eq(1).remove().text()+'</h3>');
		var $container = $('<div />');
		$table.find('tbody').append($tr);
		$container.append($h3).append($table);

		this.infowindow.close();
		this.infowindow.setOptions({ content: $container[0] });
		this.infowindow.open(this.map, marker);
		
};

overviewMap.prototype.openInfoWindow = function(point, content) {
	//alert('opening with ' + content);
	this.infowindow.open(this.map);
	this.infowindow.setOptions({ position: point, content: content });
};
	
overviewMap.prototype.handleResponseError = function(response) {
	$('#googleerror').dialog('open');
	//alert("Status Code:" + response.Status.code);
}

overviewMap.prototype.prepareDialogs = function() {
	$(".dialog").dialog({
		autoOpen: false,
		bgiframe: true,
		resizable: false,
		height:240,
		width:300,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		}
	});
	$('#successdialog').dialog('option','buttons', {
			'Schrijf ervaring': function() {
				window.location = '/ervaringen#schrijf-ervaring';
			},
			'Terug naar de kaart': function() {
				$(this).dialog('close');
			}
	});
	$('#outsidetilburg').dialog('option','buttons', {
			'Ok': function() {
				$(this).dialog('close');
			}
	});
	$('#outsidetilburg').dialog('option','height', 290);
	$('#googleerror').dialog('option','buttons', {
			'Ok': function() {
				$(this).dialog('close');
			}
	});
	$('#googleerror').dialog('option','height', 320);
}


/** 
 * spottingMap
 * 
 * extends overviewMap
 * enables clicking the map and adding spottings * 
 * 
 ******************/

var extend = function(SubClass, SuperClass){
	var innerSuperClass = function(){};
	innerSuperClass.prototype = SuperClass.prototype;
	SubClass.prototype = new innerSuperClass();
	SubClass.prototype.constructor = SubClass;
};

extend(spottingMap, overviewMap);
function spottingMap(elementId) {

	overviewMap.call(this, elementId);
	
	var self = this;
	
	google.maps.event.addListener(this.map, 'click', function(event) {
		self.handleMapClick(event.latLng);
	});

	
	$('.spottingform').bind('submit',function() {	
		point = new google.maps.LatLng(this.latitude.value, this.longitude.value);
		self.addSpotting(point,this);
		return false;	
	});	
	

}

	
spottingMap.prototype.handleMapClick = function(latlng) {
	var self = this;
	this.geocoder.geocode({'latLng': latlng }, function(result, status) { 
		self.handleGetLocations(result, status); 
	});
};

spottingMap.prototype.handleGetLocations = function(response, status){
	if (this.validResponse(response, status)) {
	
		response = response[0];
	
		var latlng = response.geometry.location;
		
		var adres = null;
		var parts = response.address_components;
		for (var i=0; i<parts.length; i++) {
			if (parts[i].types[0]=='route') {
				adres = response.formatted_address.split(',')[0];
				break;
			}
		}
		
		this.openSpottingForm(latlng,adres);
	}
};

spottingMap.prototype.openSpottingForm = function(point, adres) {
	if (point) { 
		// copy the original form, without handlers/widgets
		$form = $('#spottingform-original')
			.clone(true);

		// enrich the form	
		$form
			.attr('id','')
			.css('display','block') // reset the id of the original form
			.find('.datum input:text').datepicker().end() // reset old datepicker id and make a new one
			.find('.lat input').val(point.lat()).end()
			.find('.lng input').val(point.lng()).end()
			.find('.slider').slider(sliderOptions).end();
		if (adres) {
			$form.find('.locatie input')
				.val(adres)
				.attr('readonly','readonly')
				.addClass('readonly');
		} else {
			$form.find('.locatie input')
				.val('Vul de naam van de locatie in')
		}
			
		// and show it
		this.infowindow.close();
		this.infowindow.setOptions({ content: $form[0], position: point }); // = new google.maps.InfoWindow({ content: $form[0], position: point });
		this.infowindow.open(this.map);
		//win.open(this.map);					
	}	
};

spottingMap.prototype.addSpotting = function(point, form) {
	if (this.checkForm(form)) {
		
		// add to session
		var self = this;
		
		$.post('./ajax/addspotting', $(form).serialize(), function(data) { 
		
			// add to map
			var marker    = self.addSpottingToMap(point);	
			    marker.id = data;
			//google.event.addListener(marker,'click',self.openSpottingInfo);
			
			// add to table
			var activity = $(form).find('#activity').val();
			activity = (activity=='- Gedrag toen je hem/haar zag') ? 'Onbekend' : activity;
			$row = $(
					'<tr id="marker'+data+'">'
						+'<td>' + $(form).find('#datum').val() + '</td>'
						+'<td>' + form.locatie.value + '</td>'
						+ ((form.aantal) ? '<td>' + form.aantal.value + '</td>' : '')
						+'<td>' + activity + '</td></tr>');
			$('#originaltable tbody').append($row);
			$('#originaltable').trigger("update").trigger("sorton", [[[0, 0]]]); 
		
			$('#successdialog').dialog('open');
		
		});			
	} else {
		alert('De gegevens die in het formulier staan zijn niet correct');
	}
};

spottingMap.prototype.checkForm = function(form) {
	var valid = true;
	valid = valid && (!form.aantal || form.aantal.value.match(/^\d+$/)); // regexp for checking digits only	
	return valid;
};



//extend(spottingMap, overviewMap);


