jQuery(function() {
    var api = "/wp-content/plugins/realschule/realschule.php";
    
    jQuery("#RSCodeForm").submit(function(form) {
        var code = jQuery("#RSCode").val();
        if(!code.match(/^[0-9]{10}$/i)) {
            alert("Der Code ist nicht gültig.\nEr muss 10 Zeichen lang sein und besteht nur aus Ziffern.");
            return false;
        }
        
        jQuery("#RSCodeForm, #RSResult").hide();
        jQuery("#RSWait").show();
        
        jQuery.ajax({
            url: api,
            method: "POST",
            dataType: "json",
            data: {
                action: "check",
                code: code
            },
            success: function(data) {
                processData(data)
            },
            error: function(xhr, status) {
                alert("Es ist ein Fehler aufgetreten.");
                jQuery("#RSCodeForm").show();
            },
            complete: function() {
                jQuery("#RSWait").hide();
            }
        });
        
        return false;
    });
    
    function processData(data) {
        if(data.error) {
            alert("Es ist ein Fehler aufgetreten:\n" + data.error);
            jQuery("#RSCodeForm").show();
            return;
        }
        
        jQuery("#RSResult").fadeIn();
    }
});

