$(document).ready(function () {
	// if ($('#userlist').length) Userlist.init();
	if ($('#map_canvas').length) {
		Map.init();
		$('#addlocation').click(function () { Map.addMarker(); });
		$('#resetview').click(function () { Map.resetView(); });
	}

	if( $('.comment-rating').length > 0 ) {
		initiateRatingLinks();
	}

	openForeignLinksExternally();
	
	handleSearchHelp();
});


var searchHelpOpen = false;
function handleSearchHelp(){
	$('#search-help-link').click(function(e) {
		if( !searchHelpOpen ) {
			$('#search-help-text').fadeIn("slow", function() {
				$('#search-help-link').fadeOut("slow", function() {
					$('#search-help-link').html('Hilfetext ausblenden').fadeIn("slow")
				});
			});
			searchHelpOpen = true;
		} else {
			$('#search-help-text').fadeOut("slow", function() {
				$('#search-help-link').fadeOut("slow", function() {
					$('#search-help-link').html('Hier klicken, für eine Erläuterung').fadeIn("slow")
				});
			});
			searchHelpOpen = false;
		}
		e.preventDefault();
	});
}

function openForeignLinksExternally() {
    var patternInternal = new RegExp('^(http://' + location.hostname + '|/|mailto:|#)');
    $('a').each(function() {
        if( !patternInternal.test( $(this).attr('href') ) ) {
            $(this).attr('target', '_blank');
        }
    });
}

function initiateRatingLinks() {
	$('.comment-rating a').click(function(e) {
		ratingUrl = $(this).attr('href');
		$.get(ratingUrl);
		ratingBox = $(this).parent();
		ratingBox.fadeOut("slow", function() {
			ratingBox.html('Danke für Ihre Stimme!').fadeIn("slow");
		});
		e.preventDefault();
	});
}

function trimString(str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

/**
 * User List
 * @author André Zahn
 */
var Userlist = {
	speedIn: 200,
	speedOut: 200,
	itemCounter: 0,
	idPrefix: 'useritem_',

	init: function () {
		$('#userlist div.item').each(function () {
			id = Userlist.idPrefix + Userlist.itemCounter++;
			$(this).attr('id', id);
			$(this).find('.over').hide(); // hide overlay

			// Add new element within each item for hover by copying
			var link = $(this).find('a.smallavatar').attr('href');
			var avatar = $(this).find('.smallavatar img').attr('src');
			$(this).find('.over').prepend(
				'<a href="' + link + '" class="bigavatar"><img src="' + avatar + '" onmouseout="Userlist.closeItemID(\'' + id + '\');" width="113" height="113" alt="Userfoto"/></a>'
			);

			// Item's over and out
			$(this).hover(
				// over
				function () {
					Userlist.openItem(this);
				},
				// out
				function () {
					Userlist.closeItem(this);
				}
			);

		});
	},

	openItem: function (element) {
		$(element).css('z-index', '1').find('.over').css('opacity', '1.0').stop().fadeIn(Userlist.speedIn);
	},

	closeItem: function (element) {
		$(element).css('z-index', '0').find('.over').stop().fadeOut(Userlist.speedOut);
	},

	closeItemID: function (id) {
		this.closeItem($('#' + id));
	}
}


/**
 * Latte Macchiato Map
 * @author André Zahn
 */
var Map = {
	map: null,
	centreLat: 51.25,
	centreLng: 10.0,
	zoom: 6,
	centreLatLng: null,
	currentMarker: {},
	openInfoWindow: null,
	infowindowList: [],
	markerList: [],
	addBubbleContent: '',

	init: function () {
		this.centreLatLng = new google.maps.LatLng(this.centreLat, this.centreLng);
		var myOptions = {
			zoom: this.zoom,
			center: this.centreLatLng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		this.loadMap();
		this.addBubbleContent = $('#bubblecontent').html();
		$('#bubblecontent').remove();
	},

	resetMap: function () {
		this.currentMarker = {};
		this.openInfoWindow = null;
		this.infowindowList = [];
		this.markerList = [];
		this.init();
	},

	resetView: function () {
		//this.debug('Reset view');
		this.map.setZoom(this.zoom);
		this.map.panTo(this.centreLatLng);
	},

	addMarker: function () {
		if (typeof this.currentMarker.marker != 'undefined') {
			this.removeCurrentMarker();
			// Only one new marker at the same time
			////this.debug('Only one new marker at the same time');
			//this.currentMarker.infowindow.open(this.map, this.currentMarker.marker);
			//return;
		}
		//this.debug('Marker added');

		this.closeInfoWindow();
		this.currentMarker.marker = new google.maps.Marker({
			position: this.map.getCenter(),
			map: this.map,
			draggable: true
		});
		this.currentMarker.marker.setIcon(new google.maps.MarkerImage(
			'/style/img/map/latte.png',
			new google.maps.Size(31, 44),
			new google.maps.Point(0, 0),
			new google.maps.Point(16, 38)
		));

		this.currentMarker.infowindow = new google.maps.InfoWindow({
			content: this.addBubbleContent
		});
		this.currentMarker.infowindow.open(this.map, this.currentMarker.marker);

		var latLng = this.currentMarker.marker.get_position();
		this.currentMarker.lat = latLng.lat();
		this.currentMarker.lng = latLng.lng();


		//this.currentMarker = { marker: marker, infowindow: infowindow },

		google.maps.event.addListener(this.currentMarker.marker, 'click', function() {
			Map.currentMarker.infowindow.open(this.map, Map.currentMarker.marker);
		});

		// Add dragging event listeners.
		google.maps.event.addListener(this.currentMarker.marker, 'dragstart', function() {
			//Map.debug('Start dragging...');
		});

		google.maps.event.addListener(this.currentMarker.marker, 'dragend', function() {
			var latLng = Map.currentMarker.marker.get_position();
			Map.currentMarker.lat = latLng.lat();
			Map.currentMarker.lng = latLng.lng();
			//Map.debug('Drag ended. Dropped at ' + latLng.lat() + ', ' + latLng.lng());
		});
	},

	removeCurrentMarker: function () {
		if (typeof this.currentMarker.marker == 'undefined') { return; } //this.debug('kein marker');
		//this.debug('Remove marker');
		this.currentMarker.marker.set_map(null);
		this.currentMarker.infowindow.close();
		this.currentMarker = {};
	},

	placeMarker: function (lat, lng, content) {
		var latLng = new google.maps.LatLng(lat, lng);
		var marker = new google.maps.Marker({
			position: latLng,
			map: this.map
		});

		marker.setIcon(new google.maps.MarkerImage(
			'/style/img/map/latte.png',
			new google.maps.Size(31, 44),
			new google.maps.Point(0, 0),
			new google.maps.Point(16, 38)
		));

		var infowindow = new google.maps.InfoWindow({
			content: content
		});

		this.markerList[this.markerList.length] = marker;
		this.infowindowList[this.infowindowList.length] = infowindow;

		google.maps.event.addListener(marker, 'click', function() {
			Map.closeInfoWindow();
			infowindow.open(this.map, marker);
			Map.openInfoWindow = infowindow;
		});
	},

	clearMarkers: function () {
		if (this.markerList.length) {
			if ($.browser.msie && $.browser.version == "6.0") {
				// marker.setMap(null); doesn't work for IE6 :(
				this.resetMap();
			} else {
				this.markerList.forEach(function (marker) {
					marker.setMap(null);
				});
			}
		this.markerList = [];
		}
	},

	closeInfoWindow: function () {
		// Close last opened infowindow
		if (Map.openInfoWindow != null) {
			Map.openInfoWindow.close();
			Map.openInfoWindow = null;
		}
	},

	loadMap: function () {
		this.clearMarkers();
		this.infowindowList = [];
		var time = new Date().getTime();
		$.getJSON('/mapservice/locations?' + time,
		function (data, status) {
			//Map.debug('AJAX status: ' + status);
			$.each(data.locations, function (i, location) {
				//Map.debug('json each: ' + i + ' => ' + location.lat);

				// Prepare description content
				var e = $('#bubblecontent2');
				e.find('.avatar img').attr('src', location.avatar);
				e.find('.username').text(location.user);
				e.find('p.text').text(location.desc);

				var description = $('#bubblecontent2').html();

				Map.placeMarker(location.lat, location.lon, description);
			});
		});
	},

	saveMarker: function () {
		//this.debug('Save marker');

		// Get and trim description
		var description = $('#markertext').val();
		var trimmed_desc = trimString(description);
		if (description.length != trimmed_desc.length) {
			$('#markertext').val(trimmed_desc);
			description = trimmed_desc;
		}

		var error = '';
		if (Map.currentMarker.lat == this.centreLat && Map.currentMarker.lng == this.centreLng) error = 'Bitte verschieben Sie das Latte-Macchiato-Glas an den gewünschten Ort.';
		else if (description == '') error = 'Bitte geben Sie eine kurze Beschreibung ein.';

		if (error) {
			alert(error);
		} else {
			var submitData = { 'lat': Map.currentMarker.lat, 'lon': Map.currentMarker.lng, 'desc': description }
			$.post('/mapservice/save', submitData,
				function (data, status) {
					//Map.debug('AJAX status: ' + status + ' data.debug: ' + data.debug + ' data.status: ' + data.status);

					if (status == 'success') {
						if (data.status == 'ok') {
							Map.removeCurrentMarker();
							Map.loadMap();
						} else {
							alert(data.status);
						}
					} else {
						alert('Beim Speichern ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.');
					}
				},
				'json'
			);
		}
	}
};


/**
 * Limit Textarea
 */
function areaLength(textareaID, charsID, maxlength) {
	var strlength = $('#' + textareaID).val().length;
	if (strlength > maxlength) {
		var text = $('#' + textareaID).val();
		$('#' + textareaID).val(text.substring(0, maxlength));
		strlength = maxlength;
	}
	var left = maxlength - strlength;
	$('#' + charsID).text(left);
}
