var oauth_window = null;

function oauth_redirect() {
    var url = site_url + '/oauth/authenticate/';
    wait_for_oauth(url);
}

function wait_for_oauth(oauth_url) {
    oauth_window.location.href = oauth_url;

    $.timer(1000, function (timer) {
        if (oauth_window.closed) {
            window.location.href = $("#r").attr("value") + "?twitter#blogPostComment";
            timer.stop();
        }
    });
}

$(document).ready(function() {

    $('#submitForm').ajaxForm({
        dataType: 'json',
        beforeSubmit: sendingForm,
        success: processForm
    });

    function sendingForm(formData, jqForm, options) {
        $('#formContainer').fadeTo("slow", 0.35);
        $('#commentButton').hide();
        $('#commentButtonLoading').show();
    }

    function processForm(data) {
        if( data.status == "OK" ) {
            $('#formErrorBox').hide();
            $('#formContainer').slideUp();
            $('#postComment').hide();
            $('#formMessageBox').html(data.message).show();
            LoadComments();
            $('#commentLink').html( "Comments (" + data.commentcount + ")" );
        } else {
            $('#formErrorBox').html(data.message).slideDown("fast");
            $('#formContainer').fadeTo("fast", 100);
            $('#commentButton').show();
            $('#commentButtonLoading').hide();
        }
        window.location="#formMessage";
    }

    function LoadComments() {
        url = $("#r").attr("value");
        $("#commentListing").load( url + '?comments' );
    }

    $(".twitterLogin").click(function () {
        oauth_window = window.open('', '_blank', 'height=480,width=800,left=300,top=200,resizable=yes', true);
        oauth_redirect();
        return false;
    });

});
