var tx_rtpbirdfinder_map = function(options) {
	this.init(options);
}

$.extend(tx_rtpbirdfinder_map.prototype, {
	mapCenter :  {
		centerLatitude : 47.45673410912714,
		centerLongitude : 8.82420654296875,
		startZoom : 10,
		mapType: 'h' // m=>street map, k=>satelite map, h=>hibryd map, p=>physical map
	},
	
	options : {
		showControls: true,
		pathMarkerIcons: '/fileadmin/templates/img/birdfinder/marker_icons/'
	},
	
	selectedCommunity: {},

	markersOnMap: {},
	
	hiddenBirdTypes: {},

	loading: false,

	init: function(options) {
		$.extend(this.options, this.mapCenter);
		$.extend(this.options, options);
	},
	
	initMap: function() {
		$('#birdfinder_map_loading').hide();
		this.map = new GMap2(document.getElementById('map'));

		if(this.options.showControls) {
			this.map.setUIToDefault();
		}
			
		this.setMapTypeFromUrl(this.options.mapType);
		
		if(this.options.bounds) {
			this.initOptionsFromBounds(this.options.bounds);
		}
		
		this.map.setCenter(new GLatLng(this.options.centerLatitude, this.options.centerLongitude), this.options.startZoom);
		
		this.setupMarkerIcons();
		
		this.geocoder = new GClientGeocoder();

		GEvent.addListener(this.map,'moveend',function() {
			txRtpbirdfinderMap.updateMap();
		});
		
		GEvent.addListener(this.map, 'click', function(overlay, latLng, overlayLatLng) {
			if(overlay == null) {
				//hide all open tooltips
				$('.birdfinder_tooltip').css('visibility', 'hidden');
			}
		});
	},
	
	setupMap: function() {
		this.initMap();
		this.refreshMarkers();
	},
	
	initOptionsFromBounds: function(bounds) {
		this.options.startZoom = this.map.getBoundsZoomLevel(bounds);
		this.options.centerLatitude = bounds.getCenter().lat();
		this.options.centerLongitude = bounds.getCenter().lng();
	},
	
	setMapOptionsBoundsFromNeSw: function(neLat, neLng, swLat, swLng) {
		var southWest = new GLatLng(swLat,swLng);
		var northEast = new GLatLng(neLat,neLng);

		var bounds = new GLatLngBounds(southWest, northEast);
		
		this.options.bounds = bounds;
	},
	
	resetMap: function() {
		txRtpbirdfinderForm.removeAllBirdSpecies();
		$('#birdfinder_search_item_input_location').val('');
		$('#birdfinder_search_item_input_community_input').val('');
		$('#birdfinder_search_item_input_quicksearch').val('');
		
		if(txRtpbirdfinderNavigation) {
			txRtpbirdfinderNavigation.resetNavigation();
		}
		
		this.selectedCommunity = {};
		txRtpbirdfinderForm.speciesSelected = {};
		this.hiddenBirdTypes = {};
		
		$('#birdfinder_search_item_input_community').val('');
		this.map.setMapType(G_HYBRID_MAP);
		
		this.map.setCenter(new GLatLng(this.mapCenter.centerLatitude, this.mapCenter.centerLongitude), this.mapCenter.startZoom);
	},
	
	setupMarkerIcons: function() {
		this.markerIcons = {};

		this.markerIcons.c = new GIcon();
		this.markerIcons.c.image = this.options.pathMarkerIcons+'c/c_all_ja.png';
		this.markerIcons.c.shadow = this.options.pathMarkerIcons+'c/c_shadow.png';
		this.markerIcons.c.iconSize = new GSize(52,52);
		this.markerIcons.c.shadowSize = new GSize(0,0);
		this.markerIcons.c.iconAnchor = new GPoint(27, 27);

		this.markerIcons.cs = this.markerIcons.c;

		this.markerIcons.m = new GIcon();
		this.markerIcons.m.image = this.options.pathMarkerIcons+'m/m_50.png';
		this.markerIcons.m.shadow = this.options.pathMarkerIcons+'m/m_shadow.png';
		this.markerIcons.m.iconSize = new GSize(41, 34);
		this.markerIcons.m.shadowSize = new GSize(41, 34);
		this.markerIcons.m.iconAnchor = new GPoint(18, 33);
	},
	
	updateMap: function() {
		this.clearAllMarkers();
		this.refreshMarkers();
	},
	
	refreshMarkers: function() {
		if(this.loading) {
			return false;
		}

		this.loading = true;

		if(rtpBirdfinderMapType == 'full') {
			txRtpbirdfinderForm.disableForm('map');
		}
		this.toggleLoader();
		
		$.ajax({
			type: 'GET',
			url: 'index.php',
			data: this.getUrlParams(),
			dataType: 'json',
			success: function(response){
				if(response.list.length != undefined && response.list.length == 0) {
					txRtpbirdfinderError(txRtpbirdfinderPi1Locallang['map.error.noresult']);
				} else {
					txRtpbirdfinderMap.drawMarkers(response.list);
				}
				
				txRtpbirdfinderMap.loading = false;
				txRtpbirdfinderMap.toggleLoader();
				
				if(rtpBirdfinderMapType == 'full') {
					txRtpbirdfinderForm.enableForm('map');
				}
			}
		});
	},
	
	getUrlParams: function() {
		var bounds = this.map.getBounds();
		var urlParams =
			'eID=tx_rtpbirdfinder'
			+ '&plugin=pi1'
			+ '&tx_rtpbirdfinder_pi1[ne]=' + bounds.getNorthEast().toUrlValue()
			+ '&tx_rtpbirdfinder_pi1[sw]=' + bounds.getSouthWest().toUrlValue()
			+ '&tx_rtpbirdfinder_pi1[cmd]=getMarkers'
			+ '&tx_rtpbirdfinder_pi1[zoom]='+this.map.getZoom();

		//get values of all form fields
		urlParams = urlParams + '&' + $('#birdfinder_search_form').serialize();
		return urlParams;
	},
	
	toggleLoader: function() {
		if($('#birdfinder_map_loading').is(':hidden')) {
			$('#birdfinder_map_loading').show();
		} else {
			$('#birdfinder_map_loading').hide();
		}
	},
	
	drawMarkers : function(jsonObj) {
		this.markersOnMap = {};

		this.markerCount = 0;
		
		for(i in jsonObj) {
			this.markersOnMap[i] = [];
			for(j in jsonObj[i]) {
				this.markerCount ++;
				this.createMarkerAndDrawOnMap(jsonObj[i][j], i);
			}
		}
	},
	
	createMarkerAndDrawOnMap : function(markerObj, birdType) {
		var marker = this.createMarker(markerObj, birdType);

		this.markersOnMap[birdType].push(marker);

		this.map.addOverlay(marker);
		if(rtpBirdfinderMapType == 'full') {
			this.map.addOverlay(marker.tooltip);
		}
		
		if(this.hiddenBirdTypes[birdType] == true) {
			marker.hide();
		}
	},
	
	createMarker : function(markerObj, birdType) {
		var point = new GLatLng(markerObj.latitude,markerObj.longitude);
		var icon = this.markerIcons[markerObj.type];

		switch(markerObj.type) {
			case 'c':
				icon.image = this.options.pathMarkerIcons+'c/c_all_'+markerObj.red_list+'.png';
			break;
			case 'cs':
				icon.image = this.options.pathMarkerIcons+'c/c_'+markerObj.artnummer+'.png';
			break;
			case 'm':
				icon.image = this.options.pathMarkerIcons+'m/m_'+markerObj.artnummer+'.png';
			break;
		}

		var marker = new GMarker(point,icon);

		return this.toolTip(marker, markerObj);
	},
	
	toolTip: function(marker, markerObj) {
		if(rtpBirdfinderMapType == 'teaser') {
			return marker;
		}
		
		marker.tooltip = new Tooltip(marker, markerObj, this.markerCount);

		switch(markerObj.type) {
			case 'c':
			case 'cs':
				//add double click option for cluster markers
				GEvent.addListener(marker, 'dblclick', function() {
					txRtpbirdfinderMap.map.setCenter(this.getPoint(), txRtpbirdfinderMap.map.getZoom()+2);
				});
			default:
				GEvent.addListener(marker, 'click', function() {
					marker.tooltip.toggle();
				});
			break;
		}
		
		return marker;
	},
	
	clearAllMarkers: function() {
		this.map.clearOverlays();
	},
	
	geocodeLocation: function() {
		var location = txRtpbirdfinderForm.getLocation();

		if(location != '') {
			//only geocode, if a location was submited

			this.geocoder.setViewport(this.map.getBounds());
			this.geocoder.getLocations(location+', zürich, schweiz', function(response) {
				if (!response || response.Status.code != 200) {
					txRtpbirdfinderError(txRtpbirdfinderPi1Locallang['map.error.geocode']);
				} else {
					var latLonBox = response.Placemark[0].ExtendedData.LatLonBox;
					var southWest = new GLatLng(latLonBox.west,latLonBox.south);
					var northEast = new GLatLng(latLonBox.east,latLonBox.north);

					var zoomLevel = txRtpbirdfinderMap.map.getBoundsZoomLevel(new GLatLngBounds(southWest, northEast));

					txRtpbirdfinderMap.map.setCenter(new GLatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]), zoomLevel);
				}
			});
		}
	},
	
	searchForCommunityByName: function(communityName) {
		var communityName = txRtpbirdfinderForm.getCommunity();
		if(communityName != '') {
			
			this.toggleLoader();
			var urlParams =
				'eID=tx_rtpbirdfinder'
				+ '&plugin=pi1'
				+ '&tx_rtpbirdfinder_pi1[cmd]=getCommunityBaNyme'
				+ '&tx_rtpbirdfinder_pi1[communityName]='+communityName;
		
			$.ajax({
				type: 'GET',
				url: 'index.php',
				data: urlParams,
				dataType: 'json',
				success: function(response){
					txRtpbirdfinderMap.toggleLoader();
					if(response.community) {
						txRtpbirdfinderForm.addCommunity(response.community);
						txRtpbirdfinderMap.setMapCenterToCommunityCenter(response.community);
					} else {
						txRtpbirdfinderError(txRtpbirdfinderPi1Locallang['form.error.nocommunity']);
					}
				}
			});
		}
	},
	
	searchCommunityById: function(communityId) {
		this.toggleLoader();
		
		var urlParams =
			'eID=tx_rtpbirdfinder'
			+ '&plugin=pi1'
			+ '&tx_rtpbirdfinder_pi1[cmd]=getCommunityById'
			+ '&tx_rtpbirdfinder_pi1[communityId]='+communityId;
	
		$.ajax({
			type: 'GET',
			url: 'index.php',
			data: urlParams,
			dataType: 'json',
			success: function(response){
				txRtpbirdfinderMap.toggleLoader();
				if(response.community) {
					txRtpbirdfinderMap.setMapCenterToCommunityCenter(response.community);
				}
			}
		});
	},
	
	searchCommunity: function() {
		var community = txRtpbirdfinderForm.selectedCommunity;		
		
		if(community.id) {
			this.setMapCenterToCommunityCenter(community);
		} else {
			this.searchForCommunityByName();
		}
	},
	
	setMapCenterToCommunityCenter: function(community) {
		var southWest = new GLatLng(community.sw_lat,community.sw_lng);
		var northEast = new GLatLng(community.ne_lat,community.ne_lng);

		var zoomLevel = txRtpbirdfinderMap.map.getBoundsZoomLevel(new GLatLngBounds(southWest, northEast));
		txRtpbirdfinderMap.map.setCenter(new GLatLng(community.latitude, community.longitude), zoomLevel);
	},
	
	hideMarkersForBirdType: function(birdType) {
		if(txRtpbirdfinderMap.markersOnMap[birdType] != undefined) {
			this.hiddenBirdTypes[birdType] = true;

			$.each(txRtpbirdfinderMap.markersOnMap[birdType], function(){
				this.hide();
			});
		}
	},

	showMarkersForBirdType: function(birdType) {
		this.hiddenBirdTypes[birdType] = false;
		$.each(txRtpbirdfinderMap.markersOnMap[birdType], function(){
			this.show();
		});
	},
	
	getLinkToActualView: function() {
		var center = this.map.getCenter();
		var urlParams =
			'?tx_rtpbirdfinder_pi1%5Blatitude%5D=' + center.lat()
			+ '&tx_rtpbirdfinder_pi1%5Blongitude%5D=' + center.lng()
			+ '&tx_rtpbirdfinder_pi1%5Bzoom%5D='+this.map.getZoom()
			+ '&tx_rtpbirdfinder_pi1%5BmapType%5D='+this.getMapType();
		//get values of all form fields
		urlParams = urlParams + '&' + $('#birdfinder_search_form').serialize();

		var urlCurrentSite = window.location.href.split('?');
		
		return urlCurrentSite[0]+urlParams;
	},
	
	getSW: function() {
		return this.map.getBounds().getSouthWest().toUrlValue();
	},
	
	getNE: function() {
		return this.map.getBounds().getNorthEast().toUrlValue();
	},
	
	getZoom: function() {
		return this.map.getZoom();
	},
	
	getMapType: function() {
		return this.map.getCurrentMapType().getUrlArg();
	},
	
	setMapTypeFromUrl: function(mapType) {
		switch(mapType) {
			case 'm':
				this.map.setMapType(G_NORMAL_MAP);
			break;
			case 'k':
				this.map.setMapType(G_SATELLITE_MAP);
			break;
			case 'p':
				this.map.setMapType(G_PHYSICAL_MAP);
			break;
			case 'h':
			default:
				this.map.setMapType(G_HYBRID_MAP);
			break;
		}
	}
});

var tx_rtpbirdfinder_form = function() {
	this.init();
}

$.extend(tx_rtpbirdfinder_form.prototype, {
	disabledFrom: [],
	speciesDisplayed: 0,
	speciesSelected: {},
	communityHasChanged: false,
	selectedCommunity: {},
	
	init: function(initSpecies) {
	},
	
	options : {
		pathMarkerIcons: '/fileadmin/templates/img/birdfinder/marker_icons/'
	},
	
	initForm: function(initSpecies) {
		$('#birdfinder_search_button').click(function(event){
			event.preventDefault();
			
			txRtpbirdfinderForm.submitForm();
		});
		
		$('#birdfinder_search_form').submit(function(event){
			event.preventDefault();
			
			txRtpbirdfinderForm.submitForm();
		});
		
		$('#birdfinder_search_item_input_quicksearch').change(function(event){
			txRtpbirdfinderForm.updateAll();
		});
		
		$('#birdfinder_search_title a').click(function(event){
			event.preventDefault();

			txRtpbirdfinderForm.toggleSearch();
		});
		
		$('#birdfinder_refresh_button a').click(function(event){
			event.preventDefault();
			
			txRtpbirdfinderForm.resetForm();
			txRtpbirdfinderMap.resetMap();
		});

		this.setupTab('location', 'community');
		this.setupTab('species', 'quicksearch');
		
		$('#birdfinder_search_item_input_community_input').focus(function(event){
			txRtpbirdfinderForm.communityHasChanged = false;
		}).change(function(event){
			if(txRtpbirdfinderForm.communityHasChanged==false) {
				//if the text field changes, the selected community is removwed.
				txRtpbirdfinderForm.communityHasChanged = true;
				txRtpbirdfinderForm.selectedCommunity = {};
				$('#birdfinder_search_item_input_community').val('');
			}
		}).keypress(function(event){
			if(event.keyCode == 13) {
				event.preventDefault();
				txRtpbirdfinderForm.submitForm();
			}
		});
		
		$('#birdfinder_search_item_input_location').keypress(function(event){
			if(event.keyCode == 13) {
				event.preventDefault();
				txRtpbirdfinderForm.submitForm();
			}
		});
		
		$('#birdfinder_species_list_clear').click(function(event){
			event.preventDefault();
			
			txRtpbirdfinderForm.removeAllBirdSpecies();
			txRtpbirdfinderForm.updateAll();
		});
		
		this.setupAjaxAutosuggestCommunity();		
		this.setupAjaxAutosuggestSpecies();
		
		for(i in initSpecies) {
			this.addBirdSpeciesToTable([initSpecies[i].art_de], initSpecies[i]);	
		}
	},
	
	submitForm: function() {
		if($('#birdfinder_search_item_input_location').val() != '' && !$('#birdfinder_search_item_input_location').attr('disabled')) {
			//first geocode and rezoom, form will be submited throug on zoom end event
			txRtpbirdfinderMap.geocodeLocation();
		} else if($('#birdfinder_search_item_input_community_input').val() && !$('#birdfinder_search_item_input_community').attr('disabled')) {
			//first rezoom to the needed values
			txRtpbirdfinderMap.searchCommunity();
		} else {
			this.updateAll();
		}
	},
	
	resetForm: function() {
		if($('#birdfinder_search_title a').hasClass('disabled')) {
			this.toggleSearch();
		}
	},
	
	disableForm: function(disabledFrom) {
		if(this.disabledFrom.length == 0) {
			$('#spinner').toggle();
		}
		this.disabledFrom.push(disabledFrom);
	},

	enableForm: function(enabledFrom) {
		for(i=0; i<this.disabledFrom.length; i++) {
			if(this.disabledFrom[i] == enabledFrom) {
				this.disabledFrom.splice(i,1);
			}
		}

		if(this.disabledFrom.length == 0) {
			$('#spinner').toggle();
		}
	},
	
	toggleSearch: function() {
		if($('#birdfinder_search_title a').hasClass('disabled')) {
			$('#birdfinder_search_title').animate({ width:'258px' }, 'fast', 'swing', function() {
				$('#birdfinder_search_content').slideToggle('fast');
			});
			
			$('#birdfinder_search_title a span').show();
			$('#birdfinder_search_title a').removeClass('disabled');
			$('#birdfinder_refresh_button a').removeClass('disabled');
		} else {
			$('#birdfinder_search_content').slideToggle('fast', function(){
				$('#birdfinder_search_title a span').hide();
				$('#birdfinder_search_title').animate({ width:'35px' }, 'fast', 'swing', function() {
					$('#birdfinder_search_title a').addClass('disabled');
					$('#birdfinder_refresh_button a').addClass('disabled');
				});
			});
		}
	},
	
	setupTab: function(left, right) {
		var leftItem = $('#birdfinder_search_item_nav_'+left);	
		var rightItem = $('#birdfinder_search_item_nav_'+right);	
	
	
		leftItem.click(function(event){
			txRtpbirdfinderForm.toggleTabs(this);
			
			event.preventDefault();
		}).attr('trigger', left).attr('opposite', right);

		rightItem.click(function(event){
			txRtpbirdfinderForm.toggleTabs(this);
			
			event.preventDefault();
		}).attr('trigger', right).attr('opposite', left);
	
		//if right tab is active set it to active
		if($(rightItem[0]).hasClass('active')) {
			//if right tab is active set it to active
			$('#birdfinder_search_item_input_'+right).removeAttr('disabled');
			$('#birdfinder_search_item_input_'+left).attr('disabled', 'disabled');

			$('#birdfinder_search_item_'+right).removeClass('inactive').addClass('active');
			$('#birdfinder_search_item_'+left).removeClass('active').addClass('inactive');
		}	
	},
	
	toggleTabs: function(trigger, callback) {
		var triggerId = $(trigger).attr('trigger');
		var oppositeId = $(trigger).attr('opposite');
	
		if(!$('#birdfinder_search_item_'+triggerId).hasClass('active')) {
			//only switch tab if the clicked is not already active!
			$('#birdfinder_search_item_'+triggerId).addClass('active');
			$('#birdfinder_search_item_'+oppositeId).removeClass('active');
			
			$('#birdfinder_search_item_input_'+triggerId).removeAttr('disabled');
			$('#birdfinder_search_item_input_'+oppositeId).attr('disabled', 'disabled');

			$('#birdfinder_search_item_nav_'+triggerId).removeClass('inactive').addClass('active');
			$('#birdfinder_search_item_nav_'+oppositeId).removeClass('active').addClass('inactive');
			
			//check if there is a callback for the activated tab
			if(this.tabCallbacks[triggerId] && typeof(callback) == 'undefined') {
				this.tabCallbacks[triggerId]();
			} else if(typeof(callback) == 'function') {
				callback();
			}
		}
	},
	
	tabCallbacks: {
		'quicksearch': function() {
			if(txRtpbirdfinderForm.speciesDisplayed > 0) {
				$('#birdfinder_species_list').slideUp();
				$('input.birdfinder_table_selector_item_hidden').attr('disabled', 'disabled');
			}
			txRtpbirdfinderForm.updateAll();
		},
		'species': function() {
			if(txRtpbirdfinderForm.speciesDisplayed > 0) {
				$('#birdfinder_species_list').slideDown();
				$('input.birdfinder_table_selector_item_hidden').removeAttr('disabled');
			}
			txRtpbirdfinderForm.updateAll();
		},
		'location': function() {
			txRtpbirdfinderForm.updateAll();
		},
		'community': function() {
			txRtpbirdfinderForm.updateAll();
		}
	},

	updateAll: function() {
		txRtpbirdfinderMap.updateMap();
	},
	
	getLocation: function() {
		var location = $('#birdfinder_search_item_input_location').val();
		
		if(location == txRtpbirdfinderPi1Locallang['search.hint.location']) {
			location = '';
		}
		
		return location;
	},
	
	getCommunity: function() {
		var community = $('#birdfinder_search_item_input_community_input').val();
		
		if(community == txRtpbirdfinderPi1Locallang['search.hint.community']) {
			community = '';
		}
		
		return community;
	},
	
	setupAjaxAutosuggestSpecies: function() {
		$('#birdfinder_search_item_input_species').autocomplete({
			serviceUrl : 'index.php',
			minChars  : 2,
			maxHeight : 400,
			width : 194,
			deferRequestBy : 0, //miliseconds
			onSelect: function(birdName, bird) {
				txRtpbirdfinderForm.addBirdSpecies(birdName, bird);
			},
			params: {
				'eID' : 'tx_rtpbirdfinder',
				'plugin': 'pi1',
				'tx_rtpbirdfinder_pi1[cmd]' : 'speciesAutosuggest'
			}
		});
	},
	
	setupAjaxAutosuggestCommunity: function() {
		$('#birdfinder_search_item_input_community_input').autocomplete({
			serviceUrl : 'index.php',
			minChars  : 2,
			maxHeight : 400,
			width : 194,
			deferRequestBy : 0, //miliseconds
			onSelect: function(communityName, community) {
				txRtpbirdfinderForm.communityHasChanged = true;
				txRtpbirdfinderForm.addCommunity(community);
				txRtpbirdfinderForm.submitForm();
			},
			params: {
				'eID' : 'tx_rtpbirdfinder',
				'tx_rtpbirdfinder_pi1[cmd]' : 'communiyAutosugest',
				'plugin' : 'pi1'
			}
		});
	},
	
	addCommunity: function(community) {
		if(community) {
			this.selectedCommunity = community;
			$('#birdfinder_search_item_input_community').val(community.id);
		}
	},
	
	addBirdSpecies: function(birdName, bird) {
		var birdName = birdName.split(' (');

		if(this.speciesDisplayed >= 6) {
			txRtpbirdfinderError(txRtpbirdfinderPi1Locallang['form.error.maxbirds']);
			$('#birdfinder_search_item_input_species').val('');
			return false;
		} else if(bird.rare_bird == 1) {
			txRtpbirdfinderError($.sprintf(txRtpbirdfinderPi1Locallang['form.error.rarebird'], birdName[0]));	
			$('#birdfinder_search_item_input_species').val('');
			return false;
		} else if(bird.shown_on_map != 1) {
			txRtpbirdfinderError($.sprintf(txRtpbirdfinderPi1Locallang['form.error.notshowonmap'], birdName[0]));	
			$('#birdfinder_search_item_input_species').val('');
			return false;
		} else if(this.speciesSelected[bird.artnummer] === true) {
			txRtpbirdfinderError($.sprintf(txRtpbirdfinderPi1Locallang['form.error.birdalreadyselected'], birdName[0]));
			$('#birdfinder_search_item_input_species').val('');
			return false;
		}
		
		//Make sure the species tab is displayed if a new bird is added
		var tabSpecies = $('#birdfinder_search_item_nav_species');
		this.toggleTabs(tabSpecies[0], function() {
			$('input.birdfinder_table_selector_item_hidden').removeAttr('disabled');
			if(txRtpbirdfinderForm.speciesDisplayed > 0) {
				$('#birdfinder_species_list').slideDown();
			}
		});
			
		this.addBirdSpeciesToTable(birdName, bird);
		
		this.updateAll();
	},
	
	addBirdSpeciesToTable: function(birdName, bird) {
		if($('#birdfinder_table_selector').length == 0) {
			$('#birdfinder_table_lead').after('<table id="birdfinder_table_selector" class="birdfinder_table_selector"></table>');
		}	
		var trClass = this.speciesDisplayed == 0 ? 'birdfinder_table_selector_item first_row' : 'birdfinder_table_selector_item';
		
		var tr = $('<tr></tr>').attr({
			'class': trClass,
			id: 'birdfinder_table_selector_'+bird.artnummer
		});

		var col1 = this.createListItemMarker(bird);
		var col2 = this.createListItemCategory(bird, birdName[0]);
		var col3 = this.createListItemRemoveLink(bird.artnummer);

		tr.append(col1);
		tr.append(col2);
		tr.append(col3);

		$('#birdfinder_table_selector').append(tr);

		$('#birdfinder_search_item_input_species').attr('value', '');

		if(this.speciesDisplayed == 0) {
			tr.children('td').children('p').show();
			this.toggleSpeciesList();
		} else {
			tr.children('td').children('p').slideDown();
		}
		
		this.speciesDisplayed ++;
		this.speciesSelected[bird.artnummer] = true;
	},
	
	createListItemMarker: function(bird) {
		var checkbox = $('<input type="checkbox" checked="checked">').attr({
			'class': 'birdfinder_table_selector_item_input',
			'id': 'birdfinder_table_selector_item_input_'+bird.artnummer,
			'value' : bird.artnummer
		});

		var hidden = $('<input>').attr({
			type: 'hidden',
			id: 'birdfinder_table_selector_item_hidden_'+bird.artnummer,
			'class': 'birdfinder_table_selector_item_hidden',
			name: 'tx_rtpbirdfinder_pi1[species][]',
			value: bird.artnummer
		});

		checkbox.click(function(event){
			if ($(this).attr('checked') == true) {
				txRtpbirdfinderMap.showMarkersForBirdType($(this).attr('value'));
			} else {
				txRtpbirdfinderMap.hideMarkersForBirdType($(this).attr('value'));
			}
		});

		var imgPath = bird.shown_on_map == 1 ? this.options.pathMarkerIcons+'m_small/m_'+bird.artnummer+'.png' : this.options.pathMarkerIcons+'m_small/m_keineanzeige.png'

		var td = $('<td></td>').attr('class', 'td_checkbox').css(
			'background-image', 'url('+imgPath+')'
		).append(
			$('<p></p>').css('display', 'none').append(checkbox).append(hidden)
		);
		
		return td;
	},
	
	createListItemCategory: function(bird, birdName) {
		var birdLabel = bird.shown_on_map == 1 ? birdName : birdName + '<span class="meta_info">(Nicht auf Karte)</span>';
	
		var td = $('<td></td>').attr('class', 'td_category').append(
			$('<p></p>').css('display', 'none').html(birdLabel)
		);
		
		return td;
	},

	createListItemRemoveLink: function(birdType) {
		var td = $('<td></td>').addClass('td_selector_switcher').append(
			$('<p></p>').css('display', 'none').append(
				$('<a></a>').attr({
					'href': '#',
					'class' : 'selector_switcher'
				}).click(function(event){
					event.preventDefault();
					
					txRtpbirdfinderForm.removeSingleBirdSpecies(this, false);
				})
			)
		);
		
		return td;
	},
	
	removeSingleBirdSpecies: function(itemClicked, removeMultiple) {
		var item = $(itemClicked).parents().filter('tr.birdfinder_table_selector_item');
	
		var birdType = $(item).find('input.birdfinder_table_selector_item_input').val();

		if(birdType) {
			txRtpbirdfinderMap.hideMarkersForBirdType(birdType);
			this.speciesSelected[birdType] = false;
			txRtpbirdfinderMap.hiddenBirdTypes[birdType] = false;
		}

		if(removeMultiple==false) {
			item.children('td').children('p').slideUp('fast', function(){
				$(this).parents().filter('tr.birdfinder_table_selector_item').remove();
				if($(this).parents().filter('td').hasClass('td_selector_switcher')) {
					txRtpbirdfinderForm.removeSingleBirdSpeciesFinalize(false);
				}
			});
		} else {
			item.remove();
			this.removeSingleBirdSpeciesFinalize(true);
		}
	},
	
	removeSingleBirdSpeciesFinalize: function(removeMultiple) {
		this.speciesDisplayed --;
		
		if(this.speciesDisplayed == 0) {
			this.toggleSpeciesList();
			if(removeMultiple==false) {
				this.updateAll();
			}
		} else {
			$('#birdfinder_table_selector tr').eq(0).addClass('first_row');
		}
	},
	
	removeAllBirdSpecies: function() {
		$.each($('td.td_selector_switcher p a'), function() {
			txRtpbirdfinderForm.removeSingleBirdSpecies(this, true);
		});
	},
	
	toggleSpeciesList: function() {
		$('#birdfinder_species_list').slideToggle();
	}
});


var tx_rtpbirdfinder_navigation = function() {
	this.init();
}

$.extend(tx_rtpbirdfinder_navigation.prototype, {
	activeTab: 'info',

	init: function() {
	
	},
	
	initNavigation: function() {
		$('#birdfinder_link').hide();
		
		$('#birdfinder_meta_navigation_list a').click(function(event) {
			event.preventDefault();
			
			$('#birdfinder_search_item_input_sort').val('art_de');
			$('#birdfinder_search_item_input_sortDir').val('ASC');

			txRtpbirdfinderNavigation.navigateToTab('list', this);
			
			txRtpbirdfinderList.updateList();
		}).tooltip({ 
			tip: '#birdfinder_list_tooltip_navigation_list', 
			position: ['center', 'right'], 
	 		offset: [13, 0], 
	        effect: 'toggle', 
	 		onBeforeShow: function() {
				var retVal = false;
				//only show tooltip, if list is active
				if($('#birdfinder_meta_navigation_list a').hasClass('active')) {
					$('#birdfinder_list_tooltip_navigation_list p').html(txRtpbirdfinderPi1Locallang['meta.list.tooltip']);
					retVal = true;
				}
				
				return retVal;
	 		} 
	 	});
		
		$('#birdfinder_meta_navigation_excel a').click(function(event) {
			event.preventDefault();
			
			txRtpbirdfinderList.downloadList();
		}).tooltip({ 
			tip: '#birdfinder_list_tooltip_navigation_excel', 
			position: ['center', 'right'], 
	 		offset: [13, 0], 
	        effect: 'toggle', 
	 		onBeforeShow: function() {
				$('#birdfinder_list_tooltip_navigation_excel p').html(txRtpbirdfinderPi1Locallang['meta.excel.tooltip']);
	 		} 
	 	});
	 
	 	$('#birdfinder_meta_navigation_print a').click(function(event) {
			event.preventDefault();
			
			window.print();
		});
		$('#birdfinder_meta_navigation_info a').click(function(event) {
			event.preventDefault();
			
			txRtpbirdfinderNavigation.navigateToTab('info', this);
		});
		$('#birdfinder_meta_navigation_link a').click(function(event) {
			event.preventDefault();

			$('#birdfiner_link_output').val(txRtpbirdfinderMap.getLinkToActualView());
			
			txRtpbirdfinderNavigation.navigateToTab('link', this);
		});
	},
	
	navigateToTab: function(targetTab, trigger) {
		if(this.activeTab != 'list' && targetTab == 'list') {
			//list not shown list selected -> resize list button
			this.toggleActiveClass(targetTab, this.activeTab);
			$('#birdfinder_meta_navigation_list a').animate({ width:'275px' }, 'fast');
		} else if(this.activeTab == 'list' &&  targetTab != 'list') {
			//list shown other tab selected -> resize list button
			$('#birdfinder_meta_navigation_list a').animate({ width:'240px' }, 'fast', 'swing', (function(targetTab, activeTab){
				return function() {
					txRtpbirdfinderNavigation.toggleActiveClass(targetTab, activeTab);
				}})(targetTab, this.activeTab)
			);
		} else {
			this.toggleActiveClass(targetTab, this.activeTab);
		}
	
		if(this.activeTab!=targetTab) {
			if(this.activeTab != '') {
				//there is a active tab first fade out, before other is faded in
				$('#birdfinder_'+this.activeTab).slideUp('fast', (function(targetTab){
					return function() {
						$('#birdfinder_'+targetTab).slideDown('fast');
					}})(targetTab) 
				);
			} else {
				$('#birdfinder_'+targetTab).slideDown('fast');	
			}
			
			this.activeTab = targetTab;
			$('#birdfinder_meta_navigation').addClass('active');
		}
	},
	
	toggleActiveClass: function(targetTab, activeTab) {
		if(activeTab!=targetTab) {
			$('#birdfinder_meta_navigation_'+activeTab+' a').removeClass('active');
			$('#birdfinder_meta_navigation_'+targetTab+' a').addClass('active');
		}
	},
	
	resetNavigation: function() {
		this.navigateToTab('info', $('#birdfinder_meta_navigation_'+this.activeTab+' a'));
	}
});


var tx_rtpbirdfinder_list = function() {
	this.init();
}

$.extend(tx_rtpbirdfinder_list.prototype, {
	loading: false,

	actualSortingField: 'art_de',
	actualSortingDir: 'ASC',
	
	init: function() {

	},

	initList: function() {
		$('#birdfinder_list').hide();
		$('#birdfinder_list_loading').hide();
		this.initSorting();
	},

	updateList: function() {
		if(this.loading) {
			return false;
		}

		$('#birdfinder_list_table tbody').children().remove();

		this.toggleLoader();

		this.loading = true;

		$.ajax({
			type: 'GET',
			url: 'index.php',
			data: this.getUrlParams('listJson'),
			dataType: 'json',
			success: function(response){
				txRtpbirdfinderList.toggleLoader();
				txRtpbirdfinderList.drawList(response.list);
				txRtpbirdfinderList.loading = false;
			}
		});
	},

	getUrlParams: function(method) {
		var bounds = txRtpbirdfinderMap.map.getBounds();
		var urlParams =
			'eID=tx_rtpbirdfinder'
			+ '&plugin=pi1'
			+ '&tx_rtpbirdfinder_pi1[ne]=' + bounds.getNorthEast().toUrlValue()
			+ '&tx_rtpbirdfinder_pi1[sw]=' + bounds.getSouthWest().toUrlValue()
			+ '&tx_rtpbirdfinder_pi1[cmd]='+method
			+ '&tx_rtpbirdfinder_pi1[zoom]='+txRtpbirdfinderMap.map.getZoom();

		//get values of all form fields
		urlParams = urlParams + '&' + $('#birdfinder_search_form').serialize();

		return urlParams
	},

	drawList: function(list) {
		this.actualList = list;
		
		for(i in list) {
			this.drawListItem(list[i], i);
		}
	},

	drawListItem: function(item, itemPointer) {
		if(itemPointer == 0) {
			$('#birdfinder_list_table tbody').children().remove();
			//$('#birdfinder_list_table thead').after('<tbody></tbody>');
		}		
		var tr = $('<tr></tr>');
		
		tr.append(this.createTableCellIcon(item, itemPointer));
		
		tr.append(this.createTableCell('population_map', item.population_map_value));
		tr.append(this.createTableCellTitle(item));
		tr.append(this.createTableCellRedList(item.red_list));
		tr.append(this.createTableCell('population_zh', item.population_zh));
		tr.append(this.createTableCellTrend(item.trend));
		tr.append(this.createTableCell('living_room', item.living_room));
		
		if(itemPointer == 0) {
			tr.addClass('first_row');
		}
		
		$('#birdfinder_list_table tbody').append(tr);
	},
	
	createTableCell: function(field, value) {
		var td = $('<td></td>').attr('class', 'birdfinder_list_'+field).append(
			$('<p></p>').html(value)
		);
		
		return td;
	},
	
	createTableCellIcon: function(item, itemPointer) {
		if(item.shown_on_map == 1) {
			var td = $('<td></td>').addClass('birdfinder_list_icon').append(
				$('<p></p>').append(
					$('<a href="#"></a>').attr('itemPointer', itemPointer).click(function(event) {
						event.preventDefault();
						
						var itemPointer = $(this).attr('itemPointer');
						var item = txRtpbirdfinderList.actualList[itemPointer];
						var birdName = item.art_de;
						
						txRtpbirdfinderForm.addBirdSpecies(birdName, item);	
					}).tooltip({ 
 						tip: '#birdfinder_list_tooltip', 
						position: ['center', 'right'], 
				 		offset: [0, 0], 
				        effect: 'toggle' 
				    }).html('&nbsp;')
				)
			);
		} else {
			//bird is not shown on map, no icon is displayed
			var td = $('<td></td>').addClass('birdfinder_list_icon').append($('<p></p>').html('&nbsp;'));
		}
		
		return td;
	},

	createTableCellTitle: function(item) {
		var imgPath = item.shown_on_map == 1 ? txRtpbirdfinderMap.options.pathMarkerIcons+'m_small/m_'+item.artnummer+'.png' : txRtpbirdfinderMap.options.pathMarkerIcons+'m_small/m_keineanzeige.png'

		var td = $('<td></td>').attr('class', 'birdfinder_list_art_de').css('background-image', 'url('+imgPath+')').append (
			$('<p></p>').html(item.art_de)
		);	
	
		return td;
	},

	createTableCellRedList: function(value) {
		var td = $('<td></td>').attr('class', 'birdfinder_list_red_list').append(
			$('<p></p>').html(value)
		);
		
		if(value == 'Ja') {
			td.addClass('birdfinder_list_red_list_true');
		}
		
		return td;
	},

	createTableCellTrend: function(value) {
		var td = $('<td></td>').attr('class', 'birdfinder_list_trend').append(
			$('<p></p>').html(value)
		);
		
		if(value == '-' || value == '--') {
			td.addClass('birdfinder_list_trend_negative');
		} else if(value == '+' || value == '++') {
			td.addClass('birdfinder_list_trend_positive');
		}
		
		return td;
	},

	toggleLoader: function() {
		if($('#birdfinder_list_loading').is(':hidden')) {
			$('#birdfinder_list_loading').show();
		} else {
			$('#birdfinder_list_loading').hide();
		}
	},

	initSorting: function() {
		$('#birdfinder_list_sort_population_map').click(function(event){
			event.preventDefault();
		
			txRtpbirdfinderList.sortList('population_map');
		});
		$('#birdfinder_list_sort_art_de').click(function(event){
			event.preventDefault();
		
			txRtpbirdfinderList.sortList('art_de');
		});
		$('#birdfinder_list_sort_red_list').click(function(event){
			event.preventDefault();
		
			txRtpbirdfinderList.sortList('red_list');
		});
		$('#birdfinder_list_sort_population_zh').click(function(event){
			event.preventDefault();
		
			txRtpbirdfinderList.sortList('population_zh');
		});
		$('#birdfinder_list_sort_trend').click(function(event){
			event.preventDefault();
		
			txRtpbirdfinderList.sortList('trend');
		});
		$('#birdfinder_list_sort_living_room').click(function(event){
			event.preventDefault();
		
			txRtpbirdfinderList.sortList('living_room');
		});
	},
	
	sortList: function(sortingField) {
		if(sortingField != this.actualSortingField || this.actualSortingDir == 'DESC') {
			var sortingDir = 'ASC';
			$('#birdfinder_list_table th.birdfinder_list_'+sortingField+' div.birdfinder_list_item a').removeClass('birdfinder_list_sort_desc');
			$('#birdfinder_list_table th.birdfinder_list_'+this.actualSortingField+' div.birdfinder_list_item a').removeClass('birdfinder_list_sort_desc');
		} else {
			var sortingDir = 'DESC';
			$('#birdfinder_list_table th.birdfinder_list_'+sortingField+' div.birdfinder_list_item a').addClass('birdfinder_list_sort_desc');
		}
		
		$('#birdfinder_list_table th.birdfinder_list_'+this.actualSortingField+' div.birdfinder_list_item').removeClass('active');
		$('#birdfinder_list_table th.birdfinder_list_'+sortingField+' div.birdfinder_list_item').addClass('active');
			
		$('#birdfinder_search_item_input_sort').val(sortingField);
		$('#birdfinder_search_item_input_sortDir').val(sortingDir);
	
		this.actualSortingField = sortingField;
		this.actualSortingDir = sortingDir;
		
		txRtpbirdfinderList.updateList();
	},
	
	/**
	 * @author <http://www.filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/>
	 * Changed by RTPartner
	 **/
	downloadList: function() {
		var data = this.getUrlParams('downloadExcel');
		
		data = unescape(data);
		
		//split params into form inputs
		var inputs = '';
		
		jQuery.each(data.split('&'), function(){ 
			var pair = this.split('=');
			inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; 
		});
		
		//send request
		jQuery('<form action="/index.php" method="POST">'+inputs+'</form>').appendTo('body').submit().remove();
	}
});


/**
 * @author Marco Alionso Ramirez, marco@onemarco.com
 * @author Adapated by RTPartner
 * @url http://onemarco.com
 * @version 1.0
 * This code is public domain
 */

/**
 * The Tooltip class is an addon designed for the Google Maps GMarker class.
 * @constructor
 * @param {GMarker} marker
 * @param {Object} markerObj object with all information for the current marker
 */

function Tooltip(marker, markerObj, markerCount){
	this.markerObj = markerObj;
	this.markerCount = markerCount;
	this.marker = marker;
	
	switch(markerObj.type) {
		case 'm':
			this.leftPadding = 24;
			this.rightPadding = -24;
			this.topPadding = -40;
			this.bottomPadding = 1;
		break;
		default:
			this.leftPadding = 20;
			this.rightPadding = -23;
			this.topPadding = -30;
			this.bottomPadding = 5;
		break;
	}
}

Tooltip.prototype = new GOverlay();

Tooltip.prototype.initialize = function(map){
	switch(this.markerObj.type) {
		case 'm':
			var div = $('#birdfinder_tooltip_single').clone();
			this.div = div[0];
			
			$(this.div).find('.birdfinder_single_title a').bind('click', this, function(event) {
				event.preventDefault();
				
				// Popup to vogelguide in pid 29
				//window.open('index.php?id=29&bird[uid]=' + event.data.markerObj.artnummer,'vogelguide');
				window.open(event.data.markerObj.detailLink,'vogelguide');
			}).html(this.markerObj.art_de);
			
			$(this.div).find('.birdfinder_single_subtitle').html(this.markerObj.trivialNames);
			
			var pathToImage = '/fileadmin/files/vogel_portraits/thumbs/'+this.markerObj.image;

			$(this.div).find('.birdfinder_tooltip_single_img img').attr('src', pathToImage);
			$(this.div).find('.birdfinder_tooltip_single_text_rank').html(this.markerObj.rank);
			
			var populationText = this.markerObj.population+' '+txRtpbirdfinderPi1Locallang['map.tooltip.single.label.inventory'];
			$(this.div).find('.birdfinder_tooltip_single_text_population').html(populationText);
			
			$(this.div).find('.birdfinder_tooltip_single_guide').bind('click', this, function(event) {
				event.preventDefault();

				// Popup to vogelguide in pid 29
				//window.open('index.php?id=29&bird[uid]=' + event.data.markerObj.artnummer,'vogelguide');
				window.open(event.data.markerObj.detailLink,'vogelguide');
			});
			
			$(this.div).find('.birdfinder_single_close').bind('click', this, function(event) {
				event.preventDefault();
				
				//event.data contains the the actual tooltip object
				event.data.hide();
			});
		break;
		case 'cs':
			var div = $('#birdfinder_tooltip_cluster_cs').clone();
			this.div = div[0];
			
			$(this.div).find('.birdfinder_cluster_text_1').html(this.markerObj.art_de);
			$(this.div).find('.birdfinder_cluster_text_2 strong').html(this.markerObj.count);
			$(this.div).find('.birdfinder_tooltip_zoom_in').bind('click', this.marker, this.zoom);
		break;
		case 'c':
			var div = $('#birdfinder_tooltip_cluster_c').clone();
			this.div = div[0];

			$(this.div).find('.birdfinder_cluster_text_1 strong').html(this.markerObj.countSpecies);
			$(this.div).find('.birdfinder_cluster_text_2 strong').html(this.markerObj.count);
			$(this.div).find('.birdfinder_tooltip_zoom_in').bind('click', this.marker, this.zoom);
		break;
	}
	
	$(this.div).attr('id', $(this.div).attr('id')+'_'+this.markerCount);
	
	map.getPane(G_MAP_FLOAT_PANE).appendChild(this.div);
	this.map_ = map;
}

Tooltip.prototype.remove = function(){
	this.div.parentNode.removeChild(this.div);
}

Tooltip.prototype.copy = function(){
	return new Tooltip(this.marker, this.markerObj, this.markerCount+1);
}

Tooltip.prototype.redraw = function(force){
	if (!force) return;
	var markerPos = this.map_.fromLatLngToContainerPixel(this.marker.getLatLng());
	var iconAnchor = this.marker.getIcon().iconAnchor;

	var mapContainer = this.map_.getContainer();
	var mapContainerDivNeXY = this.map_.fromLatLngToDivPixel(this.map_.getBounds().getNorthEast());
	
	var mapMovedX = mapContainer.clientWidth - mapContainerDivNeXY.x;
	var mapMovedY = mapContainerDivNeXY.y;

	var yPos = { 
		'top' : markerPos.y - this.div.clientHeight + this.topPadding + mapMovedY,
		'bottom' : markerPos.y + this.bottomPadding + mapMovedY
	}
	
	var xPos = {
		'left': markerPos.x - this.div.clientWidth + this.leftPadding - mapMovedX,
		'right': markerPos.x + this.rightPadding - mapMovedX
	}

	
	var xAlign = (xPos['left']+mapMovedX > 0 && xPos['right']+this.div.clientWidth+mapMovedX > 435) ? 'left' : 'right';
	
	if(
		yPos['top']-mapMovedY < 10 
		|| (markerPos.x > 435 && yPos['bottom']+this.div.clientHeight-mapMovedY < mapContainer.clientHeight)
		|| (xAlign == 'right' && xPos['right']+this.div.clientWidth+mapMovedX > 435 
			&& yPos['bottom']+this.div.clientHeight-mapMovedY < mapContainer.clientHeight
		)
	) {
		var yAlign = 'bottom';
	} else {
		var yAlign = 'top';
	}
	
	$(this.div).addClass(yAlign).addClass(xAlign);
	
	this.div.style.top = Math.round(yPos[yAlign]) + 'px';
	this.div.style.left = Math.round(xPos[xAlign]) + 'px';
}

Tooltip.prototype.show = function(){
	//first hide all other open tooltips
	$('.birdfinder_tooltip').css('visibility', 'hidden');

	$(this.div).css({
		'visibility': 'visible',
		'z-index': '9998'
	});
}

Tooltip.prototype.hide = function(){
	$(this.div).css({
		'visibility': 'hidden',
		'z-index': '1'
	});
}

Tooltip.prototype.toggle = function() {
	if($(this.div).css('visibility') == 'hidden') {
		this.show();
	} else {
		this.hide();
	}
}

Tooltip.prototype.zoom = function(event) {
	event.preventDefault();
	txRtpbirdfinderMap.map.setCenter(event.data.getPoint(), txRtpbirdfinderMap.map.getZoom()+2);
}

function txRtpbirdfinderError(message) {

    /*if( $('#birdfinder_error_messages').length ){
        $('#birdfinder_error_messages').html(message);
        $('#birdfinder_error_messages').attr('class', 'active_error_message');
        setTimeout(function(){
            $('#birdfinder_error_messages').html('');
            $('#birdfinder_error_messages').attr('class','');
            
        }, 5000);
        
    }else{*/
        alert(message);
    //}
	
}

/**
 * sprintf and vsprintf for jQuery
 * somewhat based on http://jan.moesen.nu/code/javascript/sprintf-and-printf-in-javascript/
 * 
 * Copyright (c) 2008 Sabin Iacob (m0n5t3r) <iacobs@m0n5t3r.info>
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details. 
 *
 * @license http://www.gnu.org/licenses/gpl.html 
 * @project jquery.sprintf
 */
(function($){
	var formats = {
		'%': function(val) {return '%';},
		'b': function(val) {return  parseInt(val, 10).toString(2);},
		'c': function(val) {return  String.fromCharCode(parseInt(val, 10));},
		'd': function(val) {return  parseInt(val, 10) ? parseInt(val, 10) : 0;},
		'u': function(val) {return  Math.abs(val);},
		'f': function(val, p) {return  (p > -1) ? Math.round(parseFloat(val) * Math.pow(10, p)) / Math.pow(10, p): parseFloat(val);},
		'o': function(val) {return  parseInt(val, 10).toString(8);},
		's': function(val) {return  val;},
		'x': function(val) {return  ('' + parseInt(val, 10).toString(16)).toLowerCase();},
		'X': function(val) {return  ('' + parseInt(val, 10).toString(16)).toUpperCase();}
	};

	var re = /%(?:(\d+)?(?:\.(\d+))?|\(([^)]+)\))([%bcdufosxX])/g;

	var dispatch = function(data){
		if(data.length == 1 && typeof data[0] == 'object') { //python-style printf
			data = data[0];
			return function(match, w, p, lbl, fmt, off, str) {
				return formats[fmt](data[lbl]);
			};
		} else { // regular, somewhat incomplete, printf
			var idx = 0; // oh, the beauty of closures :D
			return function(match, w, p, lbl, fmt, off, str) {
				return formats[fmt](data[idx++], p);
			};
		}
	};

	$.extend({
		sprintf: function(format) {
			var argv = Array.apply(null, arguments).slice(1);
			return format.replace(re, dispatch(argv));
		},
		vsprintf: function(format, data) {
			return format.replace(re, dispatch(data));
		}
	});
})(jQuery);


/** Leaflet Generator Map Functions **/
var tx_rtpleafletgenerator_form = function(options) {
	this.init(options);
}

$.extend(tx_rtpleafletgenerator_form.prototype, {
	speciesDisplayed: 0,
	speciesSelected: {},
	loadingSpecies: false,
	
	options : {
		selectedCommunity: '',
		pathMarkerIcons: '/fileadmin/templates/img/birdfinder/marker_icons/'
	},
	
	
	init: function(options) {

		$.extend(this.options, options);
		
		$('#leafletgenerator-form').after('<form id="birdfinder_search_form">');
		
		
		if(this.options.speciesField) {
			this.setupSpeciesSelector();
		}
		
		if(this.options.communityField) {
			this.setupCommunitySelector();
		}
	
		if(this.loadingSpecies == false) {
			this.submitForm()
		}
	},
	
	setupCommunitySelector: function() {
		var communityId = $('#'+this.options.communityField).val();

		$('#birdfinder_search_form').append(
			'<input type="hidden" id="birdfinder-form-community" name="tx_rtpbirdfinder_pi1[community]" value="'+communityId+'" />'
		);
	
		$('#'+this.options.communityField).change(function(event){
			var communityId = $(this).val();
			
			$('#birdfinder-form-community').val(communityId);
				
			txRtpbirdfinderMap.searchCommunityById(communityId);
		});
	},
	
	setupSpeciesSelector: function() {
		$('#'+this.options.speciesField).after('<table id="birdfinder_table_selector"></table>');
		
		$('#'+this.options.speciesField).keypress(function(event){
			if(event.keyCode == 13) {
				event.preventDefault();
			}
		});
		
		this.setupAjaxAutosuggestSpecies();
		
		if(this.options.selectedSpecies.length > 0) {
			this.loadingSpecies = true;
			this.preselectSpeciesIds(this.options.selectedSpecies);
		}
	},
	
	submitForm: function() {
		this.updateAll();
	},
	
	updateAll: function() {
		txRtpbirdfinderMap.updateMap();
	},
	
	setupAjaxAutosuggestSpecies: function() {
		$('#'+this.options.speciesField).autocomplete({
			serviceUrl : 'index.php',
			minChars  : 2,
			maxHeight : 400,
			width : 194,
			deferRequestBy : 0, //miliseconds
			onSelect: function(birdName, bird) {
				txRtpbirdfinderForm.addBirdSpecies(birdName, bird);
			},
			params: {
				'eID' : 'tx_rtpbirdfinder',
				'plugin': 'pi1',
				'tx_rtpbirdfinder_pi1[cmd]' : 'speciesAutosuggest'
			}
		});
	},
	
	preselectSpeciesIds: function(speciesIds) {
		var urlParams =
			'eID=tx_rtpbirdfinder'
			+ '&plugin=pi1'
			+ '&tx_rtpbirdfinder_pi1[cmd]=getSpeciesByIds';
		for(i in speciesIds) {
			urlParams = urlParams+'&tx_rtpbirdfinder_pi1[species][]='+speciesIds[i];	
		}

		$.ajax({
			type: 'GET',
			url: 'index.php',
			data: urlParams,
			dataType: 'json',
			success: function(response){
				for(i in response) {
					txRtpbirdfinderForm.addBirdSpeciesToTable([response[i].art_de], response[i]);	
				}
				
				txRtpbirdfinderForm.submitForm();
			}
		});
	},
	
	addBirdSpecies: function(birdName, bird) {
		var birdName = birdName.split(' (');

		$('#'+this.options.speciesField).val('');
		
		if(this.speciesDisplayed >= 6) {
			txRtpbirdfinderError(txRtpbirdfinderPi1Locallang['form.error.maxbirds']);
			return false;
		} else if(bird.rare_bird == 1) {
			txRtpbirdfinderError($.sprintf(txRtpbirdfinderPi1Locallang['form.error.rarebird'], birdName[0]));	
			return false;
		} else if(bird.shown_on_map != 1) {
			txRtpbirdfinderError($.sprintf(txRtpbirdfinderPi1Locallang['form.error.notshowonmap'], birdName[0]));	
			return false;
		} else if(this.speciesSelected[bird.artnummer] === true) {
			txRtpbirdfinderError($.sprintf(txRtpbirdfinderPi1Locallang['form.error.birdalreadyselected'], birdName[0]));
			return false;
		}
		
		//Make sure the species tab is displayed if a new bird is added
		if(txRtpbirdfinderForm.speciesDisplayed > 0) {
			$('#birdfinder_species_list').slideDown();
		}
		
		this.addBirdSpeciesToTable(birdName, bird);
		
		this.updateAll();
	},
		
	addBirdSpeciesToTable: function(birdName, bird) {
		var trClass = this.speciesDisplayed == 0 ? 'birdfinder_table_selector_item first_row' : 'birdfinder_table_selector_item';
		
		var tr = $('<tr></tr>').attr({
			'class': trClass,
			id: 'birdfinder_table_selector_'+bird.artnummer
		});

		var col1 = this.createListItemMarker(bird);
		var col2 = this.createListItemCategory(bird, birdName[0]);
		var col3 = this.createListItemRemoveLink(bird.artnummer);

		tr.append(col1);
		tr.append(col2);
		tr.append(col3);

		$('#birdfinder_table_selector').append(tr);

		$('#birdfinder_search_item_input_species').attr('value', '');

		if(this.speciesDisplayed == 0) {
			tr.children('td').children('p').show();
			this.toggleSpeciesList();
		} else {
			tr.children('td').children('p').slideDown();
		}
		
		this.speciesDisplayed ++;
		this.speciesSelected[bird.artnummer] = true;
	},
	
	createListItemMarker: function(bird) {
		var checkbox = $('<input type="checkbox" checked="checked">').attr({
			'class': 'birdfinder_table_selector_item_input',
			'id': 'birdfinder_table_selector_item_input_'+bird.artnummer,
			'value' : bird.artnummer
		});

		var hidden = $('<input>').attr({
			type: 'hidden',
			id: 'leafletgenerator_species_'+bird.artnummer,
			'class': 'leafletgenerator_species_hidden',
			name: 'tx_rtpleafletgenerator_pi1[leaflet][species][]',
			value: bird.artnummer
		});
		
		var imgPath = bird.shown_on_map == 1 ? this.options.pathMarkerIcons+'m_small/m_'+bird.artnummer+'.png' : this.options.pathMarkerIcons+'m_small/m_keineanzeige.png'

		var td = $('<td></td>').attr('class', 'td_checkbox').css(
			'background-image', 'url('+imgPath+')'
		).append(
			$('<p></p>').css('display', 'none').append(hidden)
		);
		
		var hiddenForm = $('<input>').attr({
			type: 'hidden',
			id: 'birdfinder_table_selector_item_hidden_'+bird.artnummer,
			'class': 'birdfinder_table_selector_item_hidden',
			name: 'tx_rtpbirdfinder_pi1[species][]',
			value: bird.artnummer
		});
		
		$('#birdfinder_search_form').append(hiddenForm);
		
		return td;
	},
	
	createListItemCategory: function(bird, birdName) {
		var birdLabel = bird.shown_on_map == 1 ? birdName : birdName + '<span class="meta_info">(Nicht auf Karte)</span>';
	
		var td = $('<td></td>').attr('class', 'td_category').append(
			$('<p></p>').css('display', 'none').html(birdLabel)
		);
		
		return td;
	},

	createListItemRemoveLink: function(birdType) {
		var td = $('<td></td>').addClass('td_selector_switcher').append(
			$('<p></p>').css('display', 'none').append(
				$('<a>entfernen</a>').attr({
					'href': '#',
					'class' : 'selector_switcher',
					'artnummer': birdType
				}).click(function(event){
					event.preventDefault();
					
					txRtpbirdfinderForm.removeSingleBirdSpecies(this, false);
				})
			)
		);
		
		return td;
	},
	
	removeSingleBirdSpecies: function(itemClicked, removeMultiple) {
		$('#birdfinder_table_selector_item_hidden_'+$(itemClicked).attr('artnummer')).remove();
		var item = $(itemClicked).parents().filter('tr.birdfinder_table_selector_item');
	
		var birdType = $(item).find('input.leafletgenerator_species_hidden').val();

		if(birdType) {
			txRtpbirdfinderMap.hideMarkersForBirdType(birdType);
			this.speciesSelected[birdType] = false;
			txRtpbirdfinderMap.hiddenBirdTypes[birdType] = false;
		}

		if(removeMultiple==false) {
			item.children('td').children('p').slideUp('fast', function(){
				$(this).parents().filter('tr.birdfinder_table_selector_item').remove();
				if($(this).parents().filter('td').hasClass('td_selector_switcher')) {
					txRtpbirdfinderForm.removeSingleBirdSpeciesFinalize(false);
				}
			});
		} else {
			item.remove();
			this.removeSingleBirdSpeciesFinalize(true);
		}
	},
	
	removeSingleBirdSpeciesFinalize: function(removeMultiple) {
		this.speciesDisplayed --;
		
		if(this.speciesDisplayed == 0) {
			this.toggleSpeciesList();
			if(removeMultiple==false) {
				this.updateAll();
			}
		} else {
			$('#birdfinder_table_selector tr').eq(0).addClass('first_row');
		}
	},
	
	removeAllBirdSpecies: function() {
		$.each($('td.td_selector_switcher p a'), function() {
			txRtpbirdfinderForm.removeSingleBirdSpecies(this, true);
		});
	},
	
	toggleSpeciesList: function() {
		$('#birdfinder_species_list').slideToggle();
	}
});

var tx_rtpleafletgenerator_print = function(options) {
	this.init(options);
}

$.extend(tx_rtpleafletgenerator_print.prototype, {
	options: {},

	init: function(options) {
		$.extend(this.options, options);
		
		$('#main_area').after('<form id="birdfinder_search_form"></form>');
		if(this.options.selectedCommunity) {
			this.setupCommunity();
		}
		
		if(this.options.selectedSpecies) {
			this.setupSpecies();
		}
	
		this.updateAll();
	},
	
	setupCommunity: function() {
		var communityId = this.options.selectedCommunity;

		$('#birdfinder_search_form').append(
			'<input type="hidden" id="birdfinder-form-community" name="tx_rtpbirdfinder_pi1[community]" value="'+communityId+'" />'
		);
	},
	
	setupSpecies: function() {
		if(this.options.selectedSpecies.length > 0) {
			for(i in this.options.selectedSpecies) {	
				$('#birdfinder_search_form').append(
					'<input type="hidden" id="birdfinder-form-species-'+this.options.selectedSpecies[i]+'" name="tx_rtpbirdfinder_pi1[species][]" value="'+this.options.selectedSpecies[i]+'" />'
				);
			}
		}
	},
	
	updateAll: function() {
		txRtpbirdfinderMap.updateMap();
	}
});




/*
 * ====  EXCURSION MEETINGPOINT ======
 *
 */



var Excoursion = function() {
	this.init();
}

$.extend(Excoursion.prototype, {

    updateMeetingPointForm: false,

    init: function(){

        GEvent.addListener(txRtpbirdfinderMap.map, "moveend", function() {
            if(txRtpbirdfinderMap.meetingpoint){
                txRtpbirdfinderMap.map.addOverlay(txRtpbirdfinderMap.meetingpoint);
            }
        });
        txRtpbirdfinderMap.map.removeMapType(G_HYBRID_MAP);
        var mapControl = new GMapTypeControl();
        txRtpbirdfinderMap.map.addControl(mapControl);



    },

    removeControlls: function(){

        txRtpbirdfinderMap.map.hideControls();

    },

    createMeetingPoint: function (position){
        if(txRtpbirdfinderMap.meetingpoint){
            txRtpbirdfinderMap.map.removeOverlay(txRtpbirdfinderMap.meetingpoint);
        }

        txRtpbirdfinderMap.meetingpoint = new GMarker(position, {draggable: true});

        txRtpbirdfinderMap.excursion = this;
        GEvent.addListener(txRtpbirdfinderMap.meetingpoint, "dragend", function() {

            txRtpbirdfinderMap.excursion.meetingPointToForm();

        });
        txRtpbirdfinderMap.map.addOverlay(txRtpbirdfinderMap.meetingpoint);

        txRtpbirdfinderMap.excursion.meetingPointToForm();
    },
    
    meetingPointToForm: function () {
        if (this.updateMeetingPointForm) {
            $('#meeting_point_lat').attr('value', txRtpbirdfinderMap.meetingpoint.getLatLng().lat());
            $('#meeting_point_lng').attr('value', txRtpbirdfinderMap.meetingpoint.getLatLng().lng());
        }
    },
    
    loadMeetingpoint: function () {
        var lat = $('#meeting_point_lat').attr('value');
        var lng = $('#meeting_point_lng').attr('value');

        if(lat && lng && !txRtpbirdfinderMap.meetingpoint){

           
            var meetingPointLatLng = new GLatLng (lat, lng);
            this.createMeetingPoint(meetingPointLatLng);
        }
    },

    setUpdateMeetingPointForm: function () {
        this.updateMeetingPointForm = true;
    }

});




var tx_rtpbirdfinder_excursion_bird_table = function() {
	this.init();
}

$.extend(tx_rtpbirdfinder_excursion_bird_table.prototype, {


    birdMarkersUrl: 'fileadmin/templates/img/leafletgenerator/gemeinde/marker/',

	init: function() {

	},

	update: function() {
        if(this.hasBirdTable()){
            $.ajax({
                excursionTable: this,
                type: 'GET',
                url: 'index.php',
                data: this.getMapPositionUrlParams(),
                dataType: 'json',
                success: function(response){
                    this.excursionTable.addBirdsToTable(response.list)
                }
            });
        }
	},

	filterBirds: function(birds)
	{
		var processedBirds = [];
		for (i = 0; i < birds.length; i++){
            var bird = birds[i];
			if(bird['population_map'] > 0){
				processedBirds[processedBirds.length] = bird;
			}
		}
		return processedBirds;
	},

    addBirdsToTable: function (birds)
    {
		birds = this.filterBirds(birds);
		
        var birdTableHtml = '<tr class="first"><td colspan="5">Brutpaare ausgewählter Arten (Stand: 2008)</td></tr>';
        var i = 0;

        if(birds.length == 0){
            $('#excursion_bird_table_wrap').css('display', 'none');
        }else{
            $('#excursion_bird_table_wrap').css('display', '');
        }
        for (i = 0; i < birds.length; i++){
            var bird = birds[i];
            if(i % 2 == 0 ){
                birdTableHtml += '<tr>';
                birdTableHtml += this.getBirdCell(bird);
                birdTableHtml += '<td class="space"></td>';
            }else{
                birdTableHtml += this.getBirdCell(bird);
                birdTableHtml += '</tr>';
            }
        }
        if(i % 2 == 1 ){
            birdTableHtml += '<td></td><td></td></tr>';
        }

        $('#excursion_bird_table').html(birdTableHtml);

    },

    getBirdCell: function (bird) {
        var birdIcon = '<img height="18" width="18" src="'+ this.birdMarkersUrl + 'm_' + bird['artnummer'] +'.png"/>';
        return '<td class="art_name">'+ birdIcon + ' ' + bird['art_de'] +'</td><td class="art_num" align="right">'+ bird['population_map'] +'</td>';
    },


	getMapPositionUrlParams: function() {
        var bounds = txRtpbirdfinderMap.map.getBounds();
        var urlParams =
            'eID=tx_rtpbirdfinder'
            + '&plugin=pi1'
            + '&tx_rtpbirdfinder_pi1[ne]=' + bounds.getNorthEast().toUrlValue()
            + '&tx_rtpbirdfinder_pi1[sw]=' + bounds.getSouthWest().toUrlValue()
            + '&tx_rtpbirdfinder_pi1[cmd]=listJson'
            + '&tx_rtpbirdfinder_pi1[zoom]='+txRtpbirdfinderMap.map.getZoom();

        //get values of all form fields
        urlParams = urlParams + '&' + $('#birdfinder_search_form').serialize();

        return urlParams;
	},

    hasBirdTable: function(){
        if ($('#excursion_bird_table')) {
            return true;
        }
        return false;
    }
});
