var interval = null;

function openProgressBar(f) {
    /* generate random progress-id */
    var uuid = "";
    for (var i = 0; i < 32; i++) {
        uuid += Math.floor(Math.random() * 16).toString(16);
    }
    /* patch the form-action tag to include the progress-id */
    f.action = '/upload?iframe=1&X-Progress-ID='+uuid;
    f.target = 'uploadframe';
    
    var iframe = $('uploadframe');
    if (!iframe){
        iframe = new Element('iframe');
        iframe.id = 'uploadframe';
        iframe.name = 'uploadframe';
        iframe.width = '0';
        iframe.height = '0';
        iframe.frameborder = '0';
        iframe.border = '0';
        iframe.src = 'about:blank';
        f.parentNode.insertBefore(iframe, f);
        if(window.frames['uploadframe'].name != 'uploadframe') { window.frames['uploadframe'].name = 'uploadframe'; }
    }
    
    /* call the progress-updater every 1000ms */
    interval = window.setInterval(
        function () {
            fetch(uuid);
        },
        1000
    );
    
    return true;
}

function fetch(uuid) {
    new Ajax.Request('/progress', {
        method: 'get',
        requestHeaders: {
            'X-Progress-ID': uuid
        },
        onSuccess: function(resp){
            var res = eval(resp.responseText);
            if (res.state=='error'){
              window.clearInterval(interval);
              $('uploader').show();
              $('progress-title').hide();
              $('progress-bar').hide();    
              $('progress-totals').innerHTML = 'Upload Failed. HTTP Error '+res.status+'.';
              $('progress').show();
              $('uploadframe').remove();
            }
            else if (res.state=='done'){
              window.clearInterval(interval);
              $('uploader').hide();
              $('progress-title').hide();
              $('progress-bar').hide();    
              $('progress-totals').innerHTML = 'Done. Please wait...';
            }
            else if (res.state=='uploading'){
              $('uploader').hide();
              $('progress-title').show();
              $('progress-title').innerHTML = 'Uploading...';
              $('progress').show();
              $('progress-bar').show();
              var percent = Math.round(100*res.received/res.size);
              var total = Math.round(res.size/1024);
              var sent = Math.round(res.received/1024); 
              $('progress-totals').innerHTML = 'Total: '+total+' Kb / Sent: '+sent+' Kb' + ' ('+percent+'%)';
              $('progress-bar').firstChild.style.width = percent+'%';
            }
            else {
              $('progress').show();
              $('progress-bar').hide();
              $('progress-totals').innerHTML = 'Initializing upload...';
            }
            
        }
    });
}

