var active_link = '';
var vidcast_id = 0;
$(document).ready(function() {
    // Ajax handling
    $.ajax({
        cache: false
    });
    $("#videoControlContent").ajaxError(function(event, request, settings, error) {
        $(this).html("<p>Oops, there was a problem with that request. Please try again.</p><p>Here's what I know: " + request.responseText + "</p>");
    });
    $("#x3LiveLoading").ajaxStart(function() {
        $(this).show();
    });
    $("#x3LiveLoading").ajaxStop(function() {
        $(this).hide();
    });

    vidcast_id = $("#vidcastID").attr("value");

    // Tab control
    $("#videoControl .tabs a[rel]").each(function (i) {
        if( $(this).hasClass('active') ) {
            active_link = $(this).attr("rel");
            loadTab(active_link);
        }
    });
    $("#videoControl .tabs a[rel]").click( function() {
        if( active_link != $(this).attr("rel") ) {
            loadTab($(this).attr("rel"));
        }
        return false;
    });

    $('#submitForm').livequery(function() {
        $(this).ajaxForm({
            dataType: 'json',
            beforeSubmit: sendForm,
            success: processForm
	});
    });
});

function loadTab(tab) {
    $("#videoControlContent").slideUp('fast', function() {
        $("#videoControl .tabs a[rel=" + active_link + "]").removeClass('active');
        $("#videoControlContent").load("/tv/?nocache&t=" + tab + "&vid=" + vidcast_id, function() {
            $("#videoControlContent").slideDown('fast', function() {
                $("#videoControl .tabs a[rel=" + tab + "]").addClass('active');
                active_link = tab;
            });
        });
    });
}

function sendForm(formData, jqForm, options) {
    $('#formContainer').livequery( function() {
        $(this).fadeTo("slow", 0.35);
    });
}

function processForm(data) {
    if( data.status == "OK" )
    {
        $('#formErrorBox').livequery(function() {
            $(this).hide();
        });

        $('#formMessageBox').livequery( function() {
            $(this).html(data.message).show();
        });

        $('#formContainer').livequery( function() {
            $(this).slideUp("fast");
        });

        $("#commentContainer").livequery( function() {
            $(this).load("/tv/?t=comments&vid=" + vidcast_id + "&comments&nocache" );
        });
    }
    else
    {
        $('#formErrorBox').livequery( function() {
            $(this).html(data.message).show();
        });

        $('#formContainer').livequery( function() {
            $(this).fadeTo("fast", 100);
        });
    }
    
}
