
$(function () {

    $.validator.addMethod("letters", function (value, element) {
        return this.optional(element) || value == value.match(/^[a-zA-Z\s]*$/) || value == value.match(/^[\u0621-\u064A ]+$/);
    });

    'use strict';
    var $form = $("#form-video-create");
    $form.validate({
        lang: 'ar',
        rules: {
            category_id: {
                required: true
            },
            desc_ar: {
                required: true
            },
            desc_en: {
                required: true
            },
            video: {
                required: true
            },
        },
        submitHandler: function () {
            $form[0].submit();
        }
    });

});



function _(el) {
    return document.getElementById(el);
}


function uploadFile() {
    var file = _("book").files[0];
    if($('#update-file'))
    {
        $('#update-file').remove();
    }
    // alert(file.name+" | "+file.size+" | "+file.type);
    var formdata = new FormData();
    formdata.append("book", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "file_upload_parser.php");
    ajax.send(formdata);
}

function progressHandler(event) {
    $("#progressBar").show().css("display", "block");;
    // _("loaded_n_total").innerHTML = "تم تحميل " + event.loaded + " من " + event.total;
    var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = "  جاري التحميل " + Math.round(percent) + "%";
}

function completeHandler(event) {
    //   $("#progressBar").hide().css("display","none");
    _("status").innerHTML = "  تم التحميل بنجاح";
    // _("progressBar").value = 0; //wil clear progress bar after successful upload
}

function errorHandler(event) {
    _("status").innerHTML = "فشل التحميل";
}

function abortHandler(event) {
    _("status").innerHTML = "تم إلغاء التحميل";
}

$("#book").change(function () {
    uploadFile()
});