$(document).ready(function() {
    
    $('#uploadForm').find('button[id="checkData"]').css({'visibility' : 'visible'});

    $('#uploadForm').find('input[id="uploadFile"]').attr("disabled","disabled");
    $('#uploadForm').find('input[id="upload"]').attr("disabled","disabled");
    $('#uploadForm').find('input[id="upload"]').css({'visibility' : 'hidden'});
    //$('#uploadForm').submit(function() {
    $('#uploadForm').find('button[id="checkData"]').click(function() {
        
        checkUser.userName = $(this).find('input[id="uploadUser"]').attr('value');
        checkUser.userPassword = $(this).find('input[id="uploadPassword"]').attr('value');
        checkUser.name = $(this).find('input[id="uploadName"]').attr('value');
        checkUser.userNumber = $(this).find('input[id="uploadCustomer"]').attr('value');
        checkUser.userClerk = $(this).find('input[id="uploadClerk"]').attr('value');
        

        checkUser.CheckUserData();

        /*$(this).ajaxSubmit({
            success: checkUser.CheckUserData()
        });*/

        return false;
        
    });
});




var checkUser = {

    userName : false,

    CheckUserData : function() {
        
        var userName = $('#uploadForm').find('input[id="uploadUser"]').attr('value');
        var userPassword = $('#uploadForm').find('input[id="uploadPassword"]').attr('value');
        var name = $('#uploadForm').find('input[id="uploadName"]').attr('value');
        var userNumber = $('#uploadForm').find('input[id="uploadCustomer"]').attr('value');
        var userClerk = $('#uploadForm').find('input[id="uploadClerk"]').attr('value');

        $.post("/xhr/checkUserData.php", {  userName:     userName,
                                            userPassword: userPassword,
                                            name:         name,
                                            userNumber:   userNumber,
                                            userClerk:    userClerk
                                         }, function(response){
                                                if(response == "true") {

                                                    $('.uploadError').remove();
                                                    
                                                    $('#uploadForm').find('button[id="checkData"]').attr("disabled","disabled");
                                                    $('#uploadForm').find('button[id="checkData"]').css({'visibility' : 'hidden'});

                                                    $('#uploadForm').find('input[id="uploadUser"]').attr("readonly","readonly");
                                                    $('#uploadForm').find('input[id="uploadPassword"]').attr("readonly","readonly");
                                                    $('#uploadForm').find('input[id="uploadName"]').attr("readonly","readonly");
                                                    $('#uploadForm').find('input[id="uploadCustomer"]').attr("readonly","readonly");
                                                    $('#uploadForm').find('input[id="uploadClerk"]').attr("readonly","readonly");

                                                    $('#uploadForm').find('input[id="uploadFile"]').removeAttr("disabled");
                                                    $('#uploadForm').find('input[id="upload"]').removeAttr("disabled");
                                                    $('#uploadForm').find('input[id="upload"]').css({'visibility' : 'visible'});

                                                    $('#uploadError').remove();
                                                    $('#uploadMessage').appendTo(".buttonCheck").css({'visibility' : 'visible'});



                                                    
                                                    /*document.getElementById("uploadForm").onsubmit = function(){
                                                        alert('submitted');
                                                        openProgressBar();
                                                    };*/


                                                    $('#uploadForm').submit(function() {
                                                        openProgressBar();
                                                    });

                                                } else {
                                                    $('#uploadError').appendTo(".buttonCheck").css({'visibility' : 'visible'});
                                                }
            });

        /*$(this).load(
            'xhr/checkUserData.php',
            {'userName' : checkUser.userName,
            'userPassword' : checkUser.userPassword,
            'name' : checkUser.name,
            'userNumber' : checkUser.userNumber,
            'userClerk' : checkUser.userClerk},
            function(response){
                if(response == "true") {
                    $('.uploadError').remove();
                    console.log("response IS true");
                    $('#uploadForm').find('button[id="checkData"]').attr("disabled","disabled");
                    $('#uploadForm').find('button[id="checkData"]').css({'visibility' : 'hidden'});

                    $('#uploadForm').find('input[id="uploadUser"]').attr("readonly","readonly");
                    $('#uploadForm').find('input[id="uploadPassword"]').attr("readonly","readonly");
                    $('#uploadForm').find('input[id="uploadName"]').attr("readonly","readonly");
                    $('#uploadForm').find('input[id="uploadCustomer"]').attr("readonly","readonly");
                    $('#uploadForm').find('input[id="uploadClerk"]').attr("readonly","readonly");

                    $('#uploadForm').find('input[id="uploadFile"]').removeAttr("disabled");
                    $('#uploadForm').find('input[id="upload"]').removeAttr("disabled");

                    $('.uploadMessage').appendTo(".buttonCheck").text("Authentication successful! Please select a file.");
                    
                    //$('#uploadForm').submit(function() {
                        //console.log("hochladen button");
                      //  openProgressBar();
                    //});
        
                    $('#upload').click(function() {
                        console.log("hochladen button");
                        openProgressBar()
                    });

                } else {
                    $('.uploadError').appendTo(".buttonCheck").text("Sorry, authentication failed.")
                                                              .css({"margin" : "15px 0 -20px 0"});
                }
            }
        );*/
    }
}





/*window.onload = function() {
    document.getElementById("uploadForm").onsubmit = function(){
        openProgressBar();
    };
}*/

interval = null;
interval_msec = 1000;
last_received = 0;
is_zero = 0;
is_started = 0;
time_since_start = 0;
last_ts = 0;
file_size = 0;
uuid = null;
req = null;

function fetch(uuid) {
    time_since_start += interval_msec;
    if (is_started) return;
    req = false;
    // basic object checking - forked from apple's xhr docs
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
      try {
        req = new XMLHttpRequest();
      } catch(e) {
        req = false;
      }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
      try {
        req = new ActiveXObject("Msxml2.XMLHTTP");
      } catch(e) {
        try {
          req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
          req = false;
        }
      }
    }
    if(!req) return;
    
    req.open("GET", "/progress", 1);
    req.setRequestHeader("X-Progress-Id", uuid);
    req.onreadystatechange = function () {
        if (!req) {
            window.clearTimeout(interval);
            return;
        }

        if (req.readyState == 1) {
            /**
        	* we might have 2 requests running at the same time if the connection
        	* is very slow
        	*/
            is_started = 1;
        } else if (req.readyState == 4) {
            is_started = 0;
            if (req.status == 200) {
                /* poor-man JSON parser */
                var upload = eval(req.responseText);

                if (upload.state == 'error') {
                    document.getElementById('statusbar').innerHTML = "upload failed with status 413, file is too large";
                } else if (upload.size == 0) {
                    window.clearTimeout(interval);

                    upload.size = file_size;
                    upload.received = file_size;
                }

                if (!file_size) file_size = upload.size;

                suffix = "";
                delta_bytes = upload.received - last_received;
                last_received = upload.received;
                if (delta_bytes) {
                    is_zero = 0;
                    throughput = delta_bytes / (time_since_start - last_ts) * 1000;
                    last_ts = time_since_start;

                    left_bytes = upload.size - upload.received;
                    left_time = left_bytes / throughput;

                    if (throughput < 10240) {throughput /= 1024;suffix = "kB/s";}
                    if (throughput > 10240) {throughput /= 1024;suffix = "MB/s";}

                    document.getElementById('statusbar').innerHTML = upload.received + "/"
                        + upload.size + " - " + Math.round(throughput)
                        + suffix + " - " + Math.round(left_time) + "s left";
                } else {
                    is_zero++;

                    if (is_zero > 10) {
                        document.getElementById('statusbar').innerHTML = "no progress since 10 polls, looks like you canceled the upload";
                        window.clearTimeout(interval);
                    }
                }

                /* change the width if the inner progress-bar */
                if (upload.state == 'done') {
                    bar = document.getElementById('progressbar');
                    w = 180;
                    bar.style.width = w + 'px';
                } else if (upload.state == 'uploading') {
                    bar = document.getElementById('progressbar');
                    w = 180 * upload.received / upload.size;
                    bar.style.width = w + 'px';
                }

                /* we are done, stop the interval */
                if (upload.state == 'done' || upload.state == 'error') {
                    window.clearTimeout(interval);
                }
            } else {
                window.clearTimeout(interval);
            }
        } else {
            /**
             * debugging, track the progress
              document.getElementById('statusbar').innerHTML = "req.readyState is " + req.readyState;
             */
        }
    }
    req.send(null);
}

function openProgressBar() {
    document.getElementById("upload").value=buttonText;
	document.getElementById("upload").disabled=true;

    /* generate random progress-id */
    uuid = "";
    for (i = 0; i < 32; i++) {
        uuid += Math.floor(Math.random() * 16).toString(16);
    }

    /* patch the form-action tag to include the progress-id */
    var action = document.getElementById("uploadForm").action;
    document.getElementById("uploadForm").action=action + "?X-Progress-ID=" + uuid;

    var progress = document.createElement("div");
    progress.setAttribute("id", "progress");
    progress.style.width = "182px";
    document.getElementById("uploadElement").appendChild(progress);

    var progressbar = document.createElement('div');
    progressbar.setAttribute("id", "progressbar");
    document.getElementById("progress").appendChild(progressbar);

    document.getElementById("progressbar").style.backgroundColor = "#284d94";
    document.getElementById("progressbar").style.backgroundImage = "url('/img/animation.gif')";
    document.getElementById("progressbar").style.width = "1px";
    document.getElementById("progressbar").innerHTML = "&nbsp;";

    var statusbar = document.createElement('div');
    statusbar.setAttribute("id", "statusbar");
    document.getElementById("uploadElement").appendChild(statusbar);

    /* call the progress-updater every <interval_msec> ms */
    interval = window.setInterval(
        function () {
            fetch(uuid);
        },
        interval_msec
    );
}

