$(document).ready(function(){	
	
	//New URL submit
	$('#url_form').submit(function (){ 
			var url = $('#url').val();
			var custom = $('#custom').val();
			
			$('#show_new').slideUp();
			
			//Run some validation
			if(url.match(/^(http(s?):\/\/|ftp:\/\/{1})?((\w+\.){1,})\w{2,}/) == null)
			{
				$('.error').hide();
				$('#url_form').prepend('<div class="error">Digite uma URL válida</div>');
			}
			else if(custom.match(/^([a-zA-Z0-9_]){1,}$/) == null && custom != '')
			{
				$('.error').hide();
				$('#url_form').prepend('<div class="error">Digite um nome válido para a URL customizada</div>');
			}
			else
			{
				//Hide any errors
				$('.error').hide();
				$('#submit_btn').val('Encurtando...');
				$.ajax({
					url: site_url+'ajax/new_url',
					type: 'POST',
					data: 'custom='+custom+'&url='+escape(url),

					success: function(result){
						
						if(result == 'error')
						{
							$('#submit_btn').val('Tente novamente');
							alert('Houve um erro e sua URL não pode ser encurtada.');
						}
						else if(result == 'taken')
						{
							$('#submit_btn').val('Tente novamente');
							$('#url_form').prepend('<div class="error">O nome que você escolheu para sua URL customizada já está em uso.</div>');
						}
						else
						{
							//Parse the resulting JSON
							var data = eval('('+result+')');
							//Change URL input value back
							$('#url').val('http://');
							//Fade in the wrapper to show the new url
							$('#show_new').fadeIn();
							//Fille the new URL input with the short URL
							$('#new_url').val(site_url+data.key).select();
							//Reset the shorten btn text
							$('#submit_btn').val('Encurtar');
							//Add this link to the recent links shortened
							$('#recent_list').prepend('<li style="display:none" id="new-'+data.id+'"><a href="'+url+'" target="_blank">'+data.link_title+'</a><br /><span>Cliques: '+data.clicks+' Link: '+site_url+data.key+'</span></li>');
							$('#new-'+data.id).slideDown();
							//Show the recent list if it's not already being showed
							$('#recent_links').fadeIn();
							//Close the custom field and clear it
							$('#custom').val('');
							$('#custom_input').slideUp();
						}
					}
				});
			}
				
			return false; 
	});	
	
	//Select the value when the user clicks the new url
	$('#new_url').live('click',function (){ this.select();});
	
	//Clear the recent links
	$('#clear_recents').click(function (){
		$.get('/ajax/clear_recent');
		$('#recent_list').html('');
		$('#recent_links').fadeOut();
		return false;
	});
	
	//Switch the number of posts on the admin dashboard
	$('.show').click(function (){
		var show = this.id;
		$('#recent_list').html('');
		$('#spinner').fadeIn('fast');
		$('#recent_list').load(site_url+'ajax/get_links', {amount: show}, function(result){
			if(result != 'error')
			{
				$('#spinner').slideUp();
			}
		 });
		return false;
	});
	
	//Check for updates
	$('#update_check').click(function (){
		$.getJSON(site_url+'ajax/check_for_updates', function(data){ 
			if(data.status == 'none')
			{
				alert('Não há atualizações disponíveis');
			}
			else
			{
				if(confirm('Nova versão disponível: '+data.version+'\n\nDetalhes:\n'+data.notes+'\n\nClique em "OK" para atualizar'))
				{
					window.location=data.url;
				}
			}
		});
		return false;
	});
	
	//Custom link slide down
	$('#custom_link').click(function (){
		$('#custom_input').slideDown();
		return false;
	});
});




