$(document).ready(function() {
    $('#loginForm').ajaxForm({
        beforeSubmit: presubmit,
        dataType: 'json',
        success: postsubmit
    });
});

function presubmit() {
    clearHintBlocks();
    if (typeof presubmit_extra == 'function') presubmit_extra();
}

function postsubmit(data) {
    if (typeof postsubmit_extra == 'function') postsubmit_extra(data);
    if (processLogin(data) == true) {
        if (typeof postsubmit_on_success == 'function') postsubmit_on_success(data);
    } else {
        if (typeof postsubmit_on_failure == 'function') postsubmit_on_failure(data);
    }
}

function clearHintBlocks() {
    $("[id^=HINTDIV]").hide();
    return true;
}

function processLogin(data) {
    if(data['status']==1) { // Auto redirect
        if(typeof redirectURL !== 'undefined') 
        window.location.replace(redirectURL);
        return true;
    } else if(data['status']==2) { // Show modal
        $("#modalTitle").html(data['modal']['title']);
        $("#modalContent").html(data['modal']['content']);
        $("#modalBlock").fadeIn("slow");
        $.timer(data['modal']['timeout'], function(timer) {
            $("#modalBlock").fadeOut("slow");
            timer.stop();
        });
        return true;
    } else { // Show errors
        for (error in data['errors']) {
            if(undefined === data['errors'][error].length) {
                for (err in data['errors'][error]) {
                    // Nested Errors
                    $("[id=HINTDIV"+err+"]").html(data['errors'][error][err]);
                    $("[id=HINTDIV"+err+"]").show();
                    $("[id=HINTDIV"+err+"pointer]").show();
                }
            } else {
                $("[id=HINTDIV"+error+"]").html(data['errors'][error]);
                $("[id=HINTDIV"+error+"]").show();
                $("[id=HINTDIV"+error+"pointer]").show();
            }
        }
        return false;
    }
}

function redirect(url) {
    window.location.replace(url);
}