var mapZoomLevel = 5,
	photoAreaRadiusKilometers = 30,
	photoAreaRadiusLatitudeDegrees = photoAreaRadiusKilometers / 111,
	firstShowing = true,
	originalTitle, spinButtonContent, map, largePhotoMaxWidth, largePhotoMaxHeight



// start = true | false
function wait(start) {
	if (start) $('#spin').attr('disabled', 'disabled').html('<img src=\'images/loading.gif\' width=\'16\' height=\'16\' alt=\'\' />')
	else $('#spin').removeAttr('disabled').html(spinButtonContent)
}



function removeLargePhoto() {
	$('#largePhotoContainer').css('display', 'none')

	$('#largePhoto').attr('src', '')
	$('#largePhotoLink').attr('href', '').empty()
	$('#photoAuthor').attr('href', '').empty()
}



function permalink(cityID) {
	return 'http://'+location.host+'/#city'+cityID
}



function showCity(cityID, alreadyInDestinationList) {
	wait(true)

	removeLargePhoto()

	$.get('getCity.php', cityID ? {ID: cityID} : $('#filters').serialize(), function() {
		if (!window.city) {
			wait(false)

			return
		}

		location.replace('#city'+city.ID)

		addthis_share.url = location.href
		addthis.button('.addthis_button')

		var fullName = city.name+', '+(city.regionName ? city.regionName+', ' : '')+city.countryName

		document.title = originalTitle+' - '+fullName
		$('#city').text(fullName)
		$('#population').text(city.population == 0 ? 'Unknown' : city.population)
		$('#wikipediaLink').attr('href', 'http://en.wikipedia.org/w/index.php?title=Special:Search&search='+encodeURIComponent(city.name))
		$('#permalink').attr('href', permalink(city.ID))
		if (!alreadyInDestinationList) $('#destinations').prepend('<li style=\'list-style-image: url("images/flags/'+city.countryID.toLowerCase()+'.png");\'><a href=\''+permalink(city.ID)+'\' onclick=\'showCity('+city.ID+', true); return false\'>'+fullName+'</a></li>')

		var place = new GLatLng(city.latitude, city.longitude)

		if (firstShowing) {
			map = new GMap2(document.getElementById('map'))
			map.setCenter(place, mapZoomLevel)
			map.addControl(new GSmallZoomControl3D())

			var ads = new GAdsManager(map, 'pub-5271778819072814', {
				style: G_ADSMANAGER_STYLE_ADUNIT,
				channel: '9049660005',
				minZoomLevel: mapZoomLevel
			})
			ads.enable()

			firstShowing = false
		}
		else {
			map.panTo(place)
		}

		map.clearOverlays()
		map.addOverlay(new GMarker(place, {clickable: false, title: city.name}))

		var photoAreaRadiusLongitudeDegrees = photoAreaRadiusKilometers * 360 / ( 2 * Math.PI * 6365 * Math.cos(city.latitude * Math.PI / 180) )

		$.getJSON('http://www.panoramio.com/map/get_panoramas.php?callback=?', {
			order: 'popularity',
			set: 'full',
			from: 0,
			to: 7,
			minx: city.longitude - photoAreaRadiusLongitudeDegrees,
			miny: city.latitude - photoAreaRadiusLatitudeDegrees,
			maxx: city.longitude + photoAreaRadiusLongitudeDegrees,
			maxy: city.latitude + photoAreaRadiusLatitudeDegrees,
			size: 'medium'
		}, function(data) {
			var photos = data.photos

			$('#photos').empty()

			for (var i = 0; i < photos.length; i++) {
				$('#photos').append(
					$(document.createElement('img'))
					.attr({
						src: photos[i].photo_file_url.replace('/medium/', '/square/'),
						alt: ''
					})
					.data('info', {
						largePhotoURL: photos[i].photo_file_url,
						largePhotoWidth: photos[i].width,
						largePhotoHeight: photos[i].height,
						largePhotoPage: photos[i].photo_url,
						author: photos[i].owner_name,
						authorURL: photos[i].owner_url,
						photoTitle: photos[i].photo_title ? photos[i].photo_title : '(Untitled)'
					})
					.mouseenter(function() {
						var info = $(this).data('info')

						removeLargePhoto()

						var ratio = info.largePhotoWidth / info.largePhotoHeight

						if (info.largePhotoWidth > info.largePhotoHeight) {
							info.largePhotoWidth = largePhotoMaxWidth
							info.largePhotoHeight = parseInt(largePhotoMaxWidth / ratio)
						}
						else {
							info.largePhotoWidth = parseInt(largePhotoMaxHeight * ratio)
							info.largePhotoHeight = largePhotoMaxHeight
						}

						$('#largePhotoContainer').width(info.largePhotoWidth)
						$('#largePhoto').attr({'src': info.largePhotoURL, height: info.largePhotoHeight})
						$('#largePhotoLink').attr('href', info.largePhotoPage).text(info.photoTitle)
						$('#photoAuthor').attr('href', info.authorURL).text(info.author)

						$('#largePhotoContainer').css('display', 'block')
					})
				)
			}

			wait(false)
		})
	}, 'script')
}



$(document).ready(function() {
	var locationHash = location.hash.match(/^#city(\d+)$/)
	originalTitle = document.title
	$('#contact').attr('href', 'mai'+'lto'+':spi'+'n@s'+'pinth'+'eglobe.n'+'et')
	spinButtonContent = $('#spin').html()
	largePhotoMaxWidth = parseInt($('#map').css('width'))
	largePhotoMaxHeight = parseInt(largePhotoMaxWidth / 1.3333)

	showCity(locationHash ? locationHash[1] : null)
})

