$(function() {
	$( '#url-form .submit' ).after( '<img id="loader" src="images/ajax-loader.gif" alt="Loading.."></img>' );
	$( '#loader' ).hide();
	
	$( '#scripts' ).hide();
	$( '#url-form' ).append( '<input type="hidden" name="js" value="1" />' );
	
	$( '#url' ).focus( function() {
		if( $( this ).val() == 'http://domain.tld' )
			$( this ).val( '' );
	} ).blur( function() {
		if( $( this ).val() == '' )
			$( this ).val( 'http://domain.tld' );
	} );
	
	$( '.submit' ).click( function() {
		var url = $( '#url' ).val();
		$( '#error' ).hide();
		
		if( url == '' || !url.match( /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:\/~\+#]*[\w\-\@?^=%&amp;\/~\+#])?/ ) ) {
			$( '#url-form' ).after( '<p id="error">Please enter a valid URL.</p>' );
			return false;
		}
		
		$( '#loader' ).show();
		
		var dataString = 'url=' + url + '&js=1';
		$.ajax({
			type: 'POST',
			url: 'form-handlers/process.php',
			data: dataString,
			success: function( result ) {
				$( '#results' ).html( '<p>Click on any of the scripts below to remove it from the final combination.</p>' + result + '<p><form id="script-form" action="form-handlers/compile.php" method="post"><input type="submit" class="submit" id="compile" value="Combine them! &raquo;" /></form></p>' );
				$( '#loader' ).hide();
			}
		});
		
		return false;
	});
	
	$( '.remove' ).live( 'click', function( event ) {
		$( this ).parent().slideUp();
		event.preventDefault();
	} );
	
	$( '#compile' ).live( 'click', function( event ) {
		var scripts = '';
		$( 'li:visible' ).each( function() {
			scripts += $( this ).children( 'a' ).html() + ',';
		} );
		
		scripts = scripts.substr( 0, scripts.length - 1 ); // strip last comma
		
		$( '#script-form' ).append( '<input type="hidden" name="url" value="' + $( '#url' ).val() + '" /><input type="hidden" name="scripts" value="' + scripts + '" />' ).submit();
	} );
});