
var gpsWatchID=0;

function updateTweet() {
	if ($.trim($('#title').val())!='') {
		$('#twitter_status_init').hide();
		$('#twitter_status').show();
		if ($('#twitter_status_changed').val()=='0') $('#twitter_status').val($.trim($('#title').val()));
	}
}

function initPost() {
	//Escondemos a caixa do tweet
	$('#twitter_status').hide();
	//Evento para a caixa de título da foto
	$('#twitter_status').keyup(function() {
		$('#twitter_status_changed').val('1');
	});
	$('#twitter_status').blur(function() {
		$('#twitter_status_changed').val('1');
	});
	//Evento para a caixa de título da foto
	$('#title').keyup(function() {
		updateTweet()
	});
	$('#title').blur(function() {
		updateTweet()
	});
	//Validação do formulário
	$("#upload_form").validate({
		submitHandler: function(form) {
			$('#submitButton').html('Your photo is beeing uploaded. Please wait...');
			form.submit();
		}
	});
	//Links de autorização do Flickr
	$("#flickrAuthLink2").hide();
	$("#flickrAuthLink").click(function() {
		$("#flickrAuthLink").hide();
		$("#flickrAuthLink2").show();
		alert("A new window will be open. Please return to this page after the authorization.");
	});
	//GPS
	initGPS();
}


function initGPS() {
	//GPS
	$('#gps_pos').hide();
	$('#gps').change(function() {
		gps();
	});
	if (!($.geolocation.support())) {
		$('#geo').hide();
	}
}

function gps() {
		if($("#gps").val()==1) {
			getLocation();
		} else {
			//Stop the watch
			//...
			//Clear position screen
			$('#gps_pos').hide();
			$('#gps_pos').html('');
		}
	}
	
function getLocation() {
	$('#gps_pos').show();
	$('#gps_pos').html('Locating...');
	if ($.geolocation.support()) {
		$.geolocation.find(function(location){
			setPos(location);
		},
		function() {
			$('#gps_pos').html('Your device/browser does not support geolocation');
		},
		{
			track: 'watchPosition',
			highAccuracy: true
		});
	} else {
		$('#gps_pos').html('Your device/browser does not support geolocation');
	}
}

function setPos(location) {
	var lat=location.latitude;
	var lon=location.longitude;
	if (parseFloat(lat)!=0 && parseFloat(lon)!=0) {
		$('#gps_lat').val(lat);
    $('#gps_lon').val(lon);
		$('#gps_pos').html('Current position: '+roundNumber($('#gps_lat').val(),5)+' , '+roundNumber($('#gps_lon').val(),5));
	} else {
		alert('a');
	}
}

	function roundNumber(num, dec) {
		var result = Math.round(parseFloat(num)*Math.pow(10,dec))/Math.pow(10,dec);
		return result;
	}
