$(document).ready( function() {

    $('input[type="submit"]').attr('disabled', 'true');

    // Create an img object outside the viewing area. To test if the video ID is valid, we'll load its preview image from
    // YouTube into this img object. If the img object fires the "ready" event, the image is valid and the video ID exists.
    // If the img object fires the "error" event, the remote image doesn't exists an the video ID is invalid.
    $('#content').append('<img id="videoidTester" style="position: absolute; left: -9999px;" />');



    function checkVideoID() {
        $('#videoPreview').html('Loading preview...');
        var videoid = $('#videourl').val().replace(/^[^v]+v.(.{11}).*/,"$1"); // Regular expression extracts the video id from the URL
        $('#videoidTester').load( function() {

            $('#uploadInstructions').hide();
            $('#videourl').removeClass('error');
            $('#videoPreview').html('<object width="240" height="200" type="application/x-shockwave-flash" data="http://www.youtube.com/v/'+videoid+'"><param name="movie" value="http://www.youtube.com/v/'+videoid+'" /></object>');
            $('#videoid').val(videoid);
            $('input[type="submit"]').attr('disabled', '');
        });

        $('#videoidTester').error( function() {

            $('input[type="submit"]').attr('disabled', 'true'); 
            $('#videourl').addClass('error');
            $('#videoPreview').html('<span style="color: #d00;">Invalid YouTube URL.</span>');
            $('#videoid').val("");
            $('#uploadInstructions').show();
        });
        $('#videoidTester').attr('src','http://img.youtube.com/vi/'+videoid+'/2.jpg');

    }

    $('#videourl').blur( function() {checkVideoID();});

    $('#entryform').submit( function(){
        var errMsg = '';
        if ( $('#title').val() == '' ){ errMsg += '- Give your video a title.\n'; }
        if ( $('#videoid').val() == '' ){ errMsg += '- Make sure you have a valid YouTube URL.\n'; }
        if ( errMsg != '' ) { 
            alert("The form isn't complete:\n\n" + errMsg + "\nFix these problems, then re-submit the upload form.");
            return false;
        }
    });

});