var map, infoWindow;
function gmInit() {
	var latlng = new google.maps.LatLng(52.3722064, 5.2180223); // Almere, NL
	var myOptions = {
		zoom: 13,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControl: false
	};
	map = new google.maps.Map(document.getElementById("googleMapCanvas"), myOptions);
}

// eventData = {id:123,, soortNaam:'filmvoorstelling', publieksNaam:html, adres:'breestraat 2d, beverwijk'}
function gmAddEventMarker(eventData, isCenter) {
	gmAddMarker(eventData.adres, isCenter, function(marker) {
		marker.set_title(eventData.publieksNaam);
		google.maps.event.addListener(marker, 'click', function() {
			var content = '<strong>'+ eventData.publieksNaam +' </strong><br>';
			if (typeof eventData.soortNaam != 'undefined') content += eventData.soortNaam;
			for (i in eventData.adres.split(',')) {
				if (i!=2) content += '<br/>'+ eventData.adres.split(',')[i];
			}
			content += '<br><a href="'+ eventData.url +'">Meer...</a>';
			if (typeof infoWindow != 'undefined') infoWindow.close();
			infoWindow = new google.maps.InfoWindow({
				'content': content
			});
			infoWindow.open(map,marker);
		});
	});
}

// organizationData = {id:123, name:html, address:'breestraat 2d, beverwijk'}
function gmAddOrganizationMarker(organizationData, isCenter) {
	gmAddMarker(organizationData.adres, isCenter, function(marker) {
		/* marker.set_title(organizationData.publieksNaam); */
		google.maps.event.addListener(marker, 'click', function() {
			var content = '<strong>'+ organizationData.publieksNaam +' </strong>';
			for (i in organizationData.adres.split(',')) {
				if (i!=2) content += '<br/>'+ organizationData.adres.split(',')[i];
			}
			content += '<br><a href="'+ organizationData.url +'">Meer...</a>';
			if (typeof infoWindow != 'undefined') infoWindow.close();
			infoWindow = new google.maps.InfoWindow({
				'content': content
			});
			 infoWindow.open(map, marker);
		});
	});
}

function gmAddMarker(addressString, isCenter, markerCallback) {
	var marker;
	geocoder = new google.maps.Geocoder();
	geocoder.geocode( { address: addressString }, function (results, status) {
		if (status == google.maps.GeocoderStatus.OK && results.length) {
			// You should always check that a result was returned, as it is
			// possible to return an empty results object.
			if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
				marker = new google.maps.Marker({
					position: results[0].geometry.location,
					map: map,
					icon: '/download/?id=10867053'
				});
				google.maps.event.addListener(marker, 'click', markerCallback(marker));
//				if(isCenter) {
//					map.set_center(results[0].geometry.location);
//				}
			}
		}
	});
	return marker;
}

// for css styles depending on javascript (label hiding, menu, etc)
$('body').addClass('hasJS');
$(document).ready(function(){
	var xmlHttpObjects = {};

	// hide labels
	$('input.hideMyLabel').labelHider();
	$('select.hideMyLabel').focus(function() {
			$('label.hideMe[for='+$(this).attr('id')+']').hide();
		});
	$('select.hideMyLabel').blur(function() {
		if ($(this).val() == '') {
			$('label.hideMe[for='+$(this).attr('id')+']').show();
		}
	});
	$('select.hideMyLabel > option[selected="selected"]').focus();

	// menu stuff
	$('#menuContainer').hover(function() {
		$('#menu ul, #subMenuBackground').show();
	}, function() {
		$('#menu ul, #subMenuBackground').hide();
	});
	$('#menu ul').each(function(){
		if ($(this).height() > $('#subMenuBackground').height()) $('#subMenuBackground').height($(this).height());
	});
	$('#menu > li').not('#menu > li.bottom').append('/');

	// show/hide the login/register form when not logged in. Show/hide the profile/logout template when logged in.
	$('#loginButton').click(function(){
		$('#loginContainer').toggle('fast');
	});

	// start frontpage search stuff //
	var filterClickCallback = function(event) {
		var gatewayAction, checkedDates = [], categories = [];

		$('#dateFilter input:checked').each(function(index,dom) { checkedDates.push($(dom).val()); });
		$('#categoryFilter input.checkBox:checked').each(function(index,dom) { categories.push($(dom).val()); });

		//calendar callback sends (date-)string as parameter
		gatewayAction = ((typeof event == 'string') || ($(event.currentTarget).attr('name').substr(0,8) != 'category'))?'getCategoryQuantitiesByDates':'getDateQuantitiesByCategory';

		if (typeof xmlHttpObjects[gatewayAction] != 'undefined') xmlHttpObjects[gatewayAction].abort();
		xmlHttpObjects[gatewayAction] = $.post('/gateway/gids2?localAction=' + gatewayAction,
    		{'checkedDates[]': checkedDates,
    		 'category': categories,
    		 'otherDate': $('#otherDate').val()},
    		function(data) {
				for(var i in data) {
					$('label[for='+((gatewayAction == 'getCategoryQuantitiesByDates')?'category':'date')+i+'] span').html('('+data[i]+')');
				}
			},
    		'json');
	};
	$('#searchColumn .checkBox').change(filterClickCallback);

	//filtercalendar
	$('#otherDate').datepicker({
		dateFormat: 'dd-mm-yy',
		onSelect: filterClickCallback,
		yearRange: '-0:+10',
		showOtherMonths: true,
		minDate: new Date(),
		prevText: '',
		nextText: ''
	});

	$('#date7').click(function(event) {
		if ($('#date7').attr('checked')) {
			$('#otherDate').show().datepicker("show").hide(); //the otherdate must be visible for calendar placement
		}
	});
	// end frontpage search stuff //

	$('#newsList > li > a, #eventList > li > a').each(function(){
		$(this).width($(this).parent().outerWidth()).height($(this).parent().outerHeight());
	});
	$('#scoreGraph input.star').rating();
	/*
	$('#scoreGraph').append('<span class="score0"></span>');
	$('#scoreGraph').mousemove(function(e){
		console.log(e);
	});
	*/
	$('#searchColumn .checkBox:first').change();
	$('#searchColumn .checkBox:last').change();

	$('#registerForm').validate({
		rules: {
			newPassword: "required",
			newPasswordCheck: {
				equalTo: "#newPassword"
			}
		}
	});
	$('#registerFormFallback').validate({
		rules: {
			newPassword: "required",
			newPasswordCheck: {
				equalTo: "#newPassword"
			}
		}
	});
	$('profileForm').validate();
	$('profileFormFallback').validate();
});