/* Licence:
 *   Use this however/wherever you like, just don't blame me if it breaks anything.
 *
 * Credit:
 *   If you're nice, you'll leave this bit:
 *
 *   Class by Pierre-Alexandre Losson -- http://www.telio.be/blog
 *   email : plosson@users.sourceforge.net
 */

var elements, uploadButton;
var progressBarHandler;
var uploadId;
var failures = 0;
var failures2 = 0;

function refreshProgress()
{
    var sUrl = "ajaxUploadStatus.action?update=" + uploadId + "&preventCache=" + new Date().getTime();
    YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            try {
                var jsonResponse = eval("(" + response.responseText + ")");
                updateProgress(jsonResponse);
            } catch(e) {
                updateProgress(null);
            }
        },

        failure : function(response) {
            if (failures2 > 20)
                $('uploadProgressBar').update("Error uploading file. Try again.");
            failures2++;
            updateProgress(null);
        },
        timeout: 30000
    });
}

function updateProgress(uploadInfo)
{
    if (!uploadInfo) {
        window.setTimeout('refreshProgress()', 1000);
    } else if (uploadInfo.totalSize == 0) {
        if (failures < 5) {
            $('ajaxVideoUploadStatus_timeElapsed').update("Waiting when upload starts...");
            window.setTimeout('refreshProgress()', 1000);
        } else {
            $('ajaxVideoUploadStatus_timeElapsed').update("Cannot upload file. Make sure it doesn't exceed 2GB.");
        }
        failures++;
    } else if (uploadInfo.inProgress) {
        disableButton(uploadButton);
        disableElements(elements);

        var percent = (uploadInfo.bytesRead / uploadInfo.totalSize) * 100;

        var KB = 1024;
        var MB = KB*KB;
        var GB = MB*KB;
        var totalSize = uploadInfo.totalSize < KB
            ? uploadInfo.totalSize + "b" :
            uploadInfo.totalSize < MB ? (uploadInfo.totalSize / KB).toFixed(2) + "K" :
            uploadInfo.totalSize < GB ? (uploadInfo.totalSize / MB).toFixed(2) + "M" :
            (uploadInfo.totalSize / GB).toFixed(2) + "G";

        var bytesRead = uploadInfo.bytesRead < KB
            ? uploadInfo.bytesRead + "b" :
            uploadInfo.bytesRead < MB ? (uploadInfo.bytesRead / KB).toFixed(2) + "K" :
            uploadInfo.bytesRead < GB ? (uploadInfo.bytesRead / MB).toFixed(2) + "M" :
            (uploadInfo.bytesRead / GB).toFixed(2) + "G";

        progressBarHandler.setPercentage('' + Math.ceil(percent));
        $('uploadProgressBar').title = uploadInfo.elapsedTime;
        $('ajaxVideoUploadStatus_timeElapsed').update(uploadInfo.elapsedTime + ". Uploaded: " + bytesRead + " of " + totalSize);
        window.setTimeout('refreshProgress()', 1000);
    } else {
        progressBarHandler.setPercentage('100');
        setTimeout("hideProgressBar()", 1500);
        enableButton(uploadButton);
        enableElements(elements);
    }

    return true;
}

function hideProgressBar() {
    $('uploadProgressBar').style.display = 'none';
}

function startProgress(path)
{
    if ($('uploadProgressBar')) { //    elements = sourceForm.elements;
        $('uploadProgressBar').style.display = 'block';
        disableButton(uploadButton);
        disableElements(elements);

        uploadId = new Date().getTime();
        failures = 0;

        progressBarHandler = new JS_BRAMUS.jsProgressBar(
                $('ajaxVideoUploadStatus'),
                1,
        {
            height:11,
            barImage    : Array(
                    path + '/images/bramus/percentImage_back4.png',
                    path + '/images/bramus/percentImage_back3.png',
                    path + '/images/bramus/percentImage_back2.png',
                    path + '/images/bramus/percentImage_back1.png'
                    )
        }
                );
        progressBarHandler.setPercentage('0');

        // wait a little while to make sure the upload has started ..
        window.setTimeout("refreshProgress()", 1500);
    }
    return true;
}

function disableButton(uploadButton) {
//    uploadButton.onclick = "return false;";
}

function enableButton(uploadButton) {
//    uploadButton.onclick = "return true;";
}

function enableElements(elements) {
    //    for (var i in elements) {
    //        if (elements[i].type == 'file') {
    //            elements[i].disabled = false;
    //        }
    //    }
}

function disableElements(elements) {
    //    for (var i in elements) {
    //        if (elements[i].type == 'file') {
    //            elements[i].disabled = true;
    //        }
    //    }
}