﻿
/*********
* Javascript for multiple file tesUpload
* Copyright (C) Tomas Larsson 2006
* http://tomas.epineer.se/
*
* Modified by Krišjānis Nesenbergs 2007
*
* Licence:
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under this License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/

var masStatus = new Array(); //Contains row for each file with values [0=cancelled, 1=going to try to upload, 2=upload in progress, 3=upload successful will send]
var masSid = new Array();
var masPath = new Array();
var uploads_in_progress = 0;
var item_count = 0;
var uploading = false;
var cgiUrl = "/php_cgi/upload.cgi?sid=";
var progressUrl = '../../php_cgi/fileprogress.php';

function TesUploadCallback(file) {
    var i = 1 + 1; //fake function will be overwritten
}

/**************************************************** Ajax periodically called to upload *********************/

function PeriodicalAjax(url, parameters, frequency, decay, onSuccess, onFailure) {
    function createRequestObject() {
        var xhr;
        try {
            xhr = new XMLHttpRequest();
        }
        catch (e) {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xhr;
    }

    function send() {
        if (!stopped) {
            xhr.open('post', url, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() { self.onComplete(); };
            xhr.send(parameters);
        }
    }

    this.stop = function() {
        stopped = true;
        clearTimeout(this.timer);
    }

    this.start = function() {
        stopped = false;
        this.onTimerEvent();
    }

    this.onComplete = function() {
        if (this.stopped) return false;
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                if (xhr.responseText == lastResponse) {
                    decay = decay * originalDecay;
                } else {
                    decay = 1;
                }
                lastResponse = xhr.responseText;
                if (onSuccess instanceof Function) {
                    onSuccess(xhr);
                }
                this.timer = setTimeout(function() { self.onTimerEvent(); }, decay * frequency * 1000);
            } else {
                if (onFailure instanceof Function) {
                    onFailure(xhr);
                }
            }
        }
    }

    this.getResponse = function() {
        if (xhr.responseText) {
            return xhr.responseText;
        }
    }

    this.onTimerEvent = function() {
        send();
    }

    var self = this;
    var stopped = false;
    var originalDecay = decay || 1.2;
    decay = originalDecay;
    var xhr = createRequestObject();
    var lastResponse = "";
    this.start();
}

/*********************************************** Function which tracks progress and returns % ***********/

function ProgressTracker(sid, options) {

    this.onSuccess = function(xhr) {

        if (parseInt(xhr.responseText) >= 100) {
            periodicalAjax.stop();
            if (options.onComplete instanceof Function) {
                options.onComplete();
            }
        } else if (xhr.responseText && xhr.responseText != lastResponse) {
            if (options.onProgressChange instanceof Function) {
                options.onProgressChange(xhr.responseText);
            }
        }
    }

    this.onFailure = function(xhr) {
        if (options.onFailure instanceof Function) {
            options.onFailure(xhr.responseText);
        } else {
            alert(xhr.responseText);
        }
        periodicalAjax.stop();
    }

    var self = this;
    var lastResponse = -1;
    options = options || {};
    var url = options.url || progressUrl;
    //alert(url);
    var frequency = options.frequency || 0.5;
    var decay = options.decay || 2;
    var periodicalAjax = new PeriodicalAjax(url, 'sid=' + sid, frequency, decay, function(request) { self.onSuccess(request); }, function(request) { self.onFailure(request); });
}

//Most Modifications follow here...

function uploadFormString(number) {
    return '<form enctype="multipart/form-data" action="" method="post" target="iframe_upload" id="hidden_form' + number + '" name="hidden_form' + number + '" />    <input type="file" name="file' + number + '" id="file' + number + '" onchange="addToQueue(this);" /></form>';
}

function addToQueue(ul) {
    document.getElementById("browse" + item_count).style.display = "none";
    item_count = item_count + 1;
    var newdiv = document.createElement('div');
    newdiv.setAttribute('id', 'browse' + item_count);
    newdiv.setAttribute('name', 'browse' + item_count);
    newdiv.innerHTML = uploadFormString(item_count);
    document.getElementById("inputs").appendChild(newdiv);
    masStatus[item_count - 1] = 1;
    masSid[item_count - 1] = hex_sha1(Math.random() + "_" + Date);
    var filepath = ul.value.split("\\");
    masPath[item_count - 1] = filepath[filepath.length - 1];
    var qu = document.getElementById("queue");
    var newdiv2 = document.createElement('div');
    newdiv2.setAttribute('id', 'q_item' + (item_count - 1));
    newdiv2.setAttribute('name', 'q_item' + (item_count - 1));
    newdiv2.setAttribute('class', 'smalltext');
    newdiv2.setAttribute('style', 'white-space:nowrap;');
    newdiv2.innerHTML = "<span id='remove_q" + (item_count - 1) + "' name='remove_q" + (item_count - 1) + "'><img src='/Images/site/remove.gif' onclick='removeItem(" + (item_count - 1) + ");' alt='X' /></span><span id='filename_q" + (item_count - 1) + "' name='filename_q" + (item_count - 1) + "'>&nbsp;" + masPath[item_count - 1] + "</span><span id='complete_q" + (item_count - 1) + "' name='complete_q" + (item_count - 1) + "' style='color:lime;display:none'>&nbsp;<img src='/Images/site/ok.gif' alt='ok'/></span>&nbsp;<div class='progresscontainer' style='display: none;'><div class='progressbar' id='progress_q" + (item_count - 1) + "' name='progress_q" + (item_count - 1) + "'></div></div>";
    qu.appendChild(newdiv2);
    uploads_in_progress = uploads_in_progress + 1;
    tryToUpload();
}

function removeItem(id) {
    var status = masStatus[id];
    masStatus[id] = 0;
    document.getElementById("q_item" + id).style.display = 'none';
    if(status==1||status==2) uploads_in_progress = uploads_in_progress - 1;
}

function tryToUpload() {
    //If there is something in queue to upload and right now there are no active uploads - procede
    if ((uploads_in_progress > 0) && (uploading == false)) {
        var x = 0;
        while ((x < (item_count)) && (masStatus[x] != 1)) x = x + 1;

        if (x < item_count) {
            if (masStatus[x] == 1) {
                //sagatvo uploadam
                uploading = true;
                document.getElementById("remove_q" + x).style.display = 'none';
                document.getElementById("hidden_form" + x).action = cgiUrl + masSid[x];
                masStatus[x] = 2;
                beginAsyncUpload(document.getElementById("hidden_form" + x), x);
            }
        }
    }
}

function beginAsyncUpload(ul, x) {
    ul.submit();
    var pb = document.getElementById("progress_q" + x);
    pb.parentNode.style.display = 'block';
    // pb.style.display='block';
    new ProgressTracker(masSid[x], {
        onComplete: function() {
            var inp_id = pb.id.replace("progress_q", "");
            uploads_in_progress = uploads_in_progress - 1;
            pb.parentNode.style.display = 'none';
        //    document.getElementById("complete_q" + inp_id).style.display = 'block';
            uploading = false;
            //    document.getElementById("remove_q" + inp_id).style.display = 'block';
            document.getElementById("filename_q" + inp_id).style.display = 'none';

            masStatus[inp_id] = 3;
            TesUploadCallback(masSid[inp_id]);
            tryToUpload();
        },
        onProgressChange: function(msg) {
            var pb = document.getElementById("progress_q" + x);
            if (pb && pb.style) {
                pb.style.width = parseInt(msg) + "%";
            }
        },
        onFailure: function(msg) {
            var inp_id = pb.id.replace("progress_q", "");
            pb.parentNode.style.display = 'none';
            alert(msg);
            uploads_in_progress = uploads_in_progress - 1;
            uploading = false;
            tryToUpload();
            document.getElementById("q_item" + inp_id).style.color = 'red';
            masStatus[inp_id] = 0;
        }
    });

}

/*function submitUpload(frm) {
    if (uploads_in_progress > 0) {
        alert("Upload in progress! Please wait while all selected files are uploaded or cancel them before submitting this form.");
    } else {
        document.getElementById("up_count").value = item_count;
        for (var a = 0; a < item_count; a++) {
            if (masStatus[a] == 3) document.getElementById("upload_values").innerHTML = document.getElementById("upload_values").innerHTML + '<input id="file' + a + '" type="hidden" name="file' + a + '" value="' + masSid[a] + '" />';
        }
        frm.submit();
    }
}*/
