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

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

	openForeignLinksExternally();

	// Facebook
	window.fbAsyncInit = function() {FB.init({status: true, cookie: true, xfbml: true});};
	var e = document.createElement('script');
	e.async = true;
	e.src = document.location.protocol + '//connect.facebook.net/de_DE/all.js';
	document.getElementById('fb-root').appendChild(e);

	// Init FB lazyload
	updateLazyloadFBLikeList();
	lazyloadFBLikeLoop();
	$(window).bind('scroll', function() {
		lastScrolled = new Date().getTime();
	});

});


var lastScrolled = 0;
var updateLazyloadFBLike = true;
var listLazyloadFBLike = [];
var lazyloadFBLikeLoop = function() {

	if (lastScrolled != 0) {
		var now = new Date().getTime();
		if ((now - lastScrolled) > 500) {
			updateLazyloadFBLike = true;
			lastScrolled = 0;
		}
	}

	if (updateLazyloadFBLike) {
		var viewportTop = $(window).scrollTop();
		var viewportBottom = viewportTop + $(window).height() + 100;
		for (var i in listLazyloadFBLike) {
			var obj = listLazyloadFBLike[i];
			if (obj != null && obj.y > viewportTop && obj.y < viewportBottom) {
				listLazyloadFBLike[i] = null;
				$(obj.element).toIframe();
			}
		}
		updateLazyloadFBLike = false;
	}
	setTimeout(lazyloadFBLikeLoop, 400);
};

var updateLazyloadFBLikeList = function() {
	var lazyLikeElements = $('.fb-like > a');
	listLazyloadFBLike = new Array(lazyLikeElements.length);
	var i = 0;
	lazyLikeElements.each(function() {
		listLazyloadFBLike[i++] = {
			element: this,
			y: $(this).offset().top
		};
	});
	setTimeout(updateLazyloadFBLikeList, 20000);
};




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*$/, '');
}


/**
 * Genusstester Map
 * @author André Zahn
 */
var Map = {
	map: null,
	centreLat: 51.25,
	centreLng: 10.0,
	zoom: 6,
	centreLatLng: null,
	currentMarker: {},
	openInfoWindow: null,
	infowindowList: [],
	markerList: [],
	addBubbleContent: '',
	markerImg: '/style/img/map/cappu.png',

	debug: function(msg) {
		//$('#debug').append(msg + "\n");
		//console.log(msg);
	},

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

	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(
			this.markerImg,
			new google.maps.Size(39, 39),
			new google.maps.Point(0, 0),
			new google.maps.Point(16, 33)
		));

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

		var latLng = this.currentMarker.marker.getPosition();
		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.getPosition();
			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.setMap(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(
			this.markerImg,
			new google.maps.Size(39, 39),
			new google.maps.Point(0, 0),
			new google.maps.Point(16, 33)
		));

		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 die Cappuccino-Tasse 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);
}


/**
 * Transform links into XFBML like buttons
 * @author André Zahn
 */
(function ($) {
	if (!$) return;
	$.fn.extend({
		toIframe: function(delay) {
			this.each(function() {
				var link = $(this).attr("href");
				if (link) {
					var html = '<fb:like href="'+ link + '" layout="button_count" show_faces="false" action="like" colorscheme="light" width="310"></fb:like>';
					$(this).parent().html(html);
					if (typeof(FB) != 'undefined') FB.XFBML.parse();
				}
			});
			return this;
		}
	});
})(jQuery);

