window.addEvent('domready', function(){
	$('submit').onclick = function() { shortify(); }
	
	$('input').onkeypress = function(e) { 
		var key=e.keyCode || e.which;
		
		if (key == 13){
			shortify();
		}
	}
	
	$('result').onclick = function() { 
		if(confirm('Do you want to copy the URL to your clipboard?')){
			var contents = $('result').innerHTML;
		
			toClipboard(contents);

			alert('URL copied to your clipboard!');
		}
	}
	
	$('info').addEvents({
		'mouseenter': function(){
			this.set('tween', {
				duration: 1000,
				transition: Fx.Transitions.Bounce.easeOut
			}).tween('margin-top', '0px');
		},
		'mouseleave': function(){
			this.set('tween', {}).tween('margin-top', '-97px');
		}
	});

});

function shortify(){
	slideup();
	
	var result = $('input').value;
	
	if(result == ''){
		$('result').set('text', 'Please enter a URL you want to shorten!');
		slidedown();
	} else {
		new Request({
			url: '/?generate='+encodeURIComponent(result),
	
			onSuccess: function(txt){
				$('result').set('text', txt);
				
				slidedown();
			},
	
			onFailure: function(){
				$('result').set('text', 'Sorry, an error occured while generating the URL.');
				
				slidedown();
			}
		}).send();
	}
}

function slideup(){
	var element = $('options');
	
	element.set('tween', {
		duration: 500,
		transition: Fx.Transitions.Bounce.easeOut
	}).tween('height', '15px');
}

function slidedown(){
	var element = $('options');
	
	element.set('tween', {
		duration: 1500,
		transition: Fx.Transitions.Bounce.easeOut
	}).tween('height', '50px');	
}

function toClipboard(contents) {
  var flashcopier = 'flashcopier';
  if(!document.getElementById(flashcopier)) {
    var divholder = document.createElement('div');
    divholder.id = flashcopier;
    document.body.appendChild(divholder);
  }
  document.getElementById(flashcopier).innerHTML = '';
  var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(contents)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
  document.getElementById(flashcopier).innerHTML = divinfo;
}