if(!LFM.Userstore) {
    LFM.Userstore = {};
}
LFM.Userstore.UploadHandler = Class.create();
LFM.Userstore.UploadHandler.prototype = {
    initialize: function (form, messages, params) {
        this.messages = messages;
        this.uploadTracker = false;
        this.tracker_id = 0;
        this.form = form;
        this.params = params ? params : {};
        if(params.onComplete) {
            this.onComplete = params.onComplete;
        }
        if(params.onStart) {
            this.onStart = params.onStart;
        }
    },
    
    setStatus: function (status) {
        if(this.progressMonitor) {
            this.status.update(status);
        }
    },
    
    setError: function (status) {
        if(this.progressMonitor) {
            this.status.hide();
            this.error_status.update(status);
            this.error_status.show();
        }
    },
    
    error: function(code, text) {
        if (code == 1 || code == 2) {
            this.setError(LFM.String.fileTooBig);
        } else if (code == 4) {
            this.setError(LFM.String.noFile);
        } else if (code == 5) {
            // Stop the upload iframe
            if (top.upload) {
                top.upload.stop();
            }
            this.setStatus(LFM.String.uploadCancelled);
        } else if (code == 105) {
            this.setError(this.messages.unsupportedFormat);
        } else {
            this.setError(this.messages.uploadError);
        }
        if(this.progressBar) {
            this.progressBarContainer.hide();
        }
        if(this.uploadTracker) {
            this.uploadTracker.stopTracking();
        }
        if ((code>200 && code<300) || this.checkup) {
            this.setStatus(this.messages.mayTakeLonger);
            this.doCheckup();
        } else if (this.onError) {
            this.onError(code, text);
        }
    },
    
    complete: function(fileID, type, verify) {
        if (this.uploadTracker) {
            this.uploadTracker.stopTracking(); 
        }
        if(this.progressBar) {
            this.progressBar.setStyle({
                width: "100%", display: ''
            });
            this.setStatus(this.messages.progressComplete);
        }
        if(this.progressMonitor)
            this.progressMonitor.hide();
        if(this.onComplete) {
            this.onComplete(fileID, type, verify);
        }
    },

    start: function(form) {
        this.form = $(form);
        if (!this.params.goToAction) {
            $A(this.form.elements).each(function (e) {
                if(e.getAttribute('name') == '_redirectAction') {
                    e.parentNode.removeChild(e);
                }
            });
            this.form.setAttribute('target', 'uploadFrame' + this.form.getAttribute('id'));
        }
        var fileInput = this.form.getInputs('file');
        if (!fileInput || !fileInput[0].value || fileInput[0].value=="") {
            this.error(4, "No File");
            return false;
        }
        var progressMonitorings = this.form.select(".progressMonitoring");
        if (progressMonitorings.length<1) {
            this.progressMonitor = false;
        } else {
            this.progressMonitor = this.form.down(".progressMonitoring");
            this.progressBarContainer = this.progressMonitor.down(".progressBar");
            this.progressBar = this.progressBarContainer.down("div");
            this.status = this.progressMonitor.down('.uploadStatus');
            this.status.show();
            this.error_status = this.form.down('.uploadError');
            this.error_status.hide();
        }
        
        if (this.onStart) {
            this.onStart();
        }
        
        if (this.progressMonitor) {
            if (this.uploadTracker) {
                this.uploadTracker.stopTracking();
                this.tracker_id += 1;
            }
            this.isprocessing = false;
            this.uploadTracker = new UploadTracker(this.form, this.uploadCallback.bind(this), this.tracker_id);
            this.watcherCounter = 0;
            this.progressMonitor.show();
            this.progressBarContainer.show();
            this.progressBar.show();
            this.progressBar.setStyle({
                width: "1%"
            });
        }
        this.setStatus(this.messages.uploading);
        return true;
    },

    processing: function() {
        this.isprocessing = true;
        this.setStatus(this.messages.processingMedia);
    },

    doCheckup: function() {
        this.checkup = true;
        this.checkupRetry = this.checkupRetry ? 0 : this.checkupRetry+1;

        if(this.checkupRetry > 15) {
            this.error(301, this.messages.failedRetrying);
            return;
        }
        setTimeout(this._doCheckup.bind(this), 1000);
    },

    _doCheckup: function() {
      var ajax = new Ajax.Request(
          'http://www.dev.last.fm:8090/usu/checkup.php',
          {
              method: 'post',
              parameters: 'onComplete=' + this.form.onComplete.value
                        + '&onError=' + this.form.onError.value
                        + '&requestID=' + this.form.requestID.value,
              onComplete: this.checkupReturn.bind(this),
              onError: this.checkupReturn.bind(this)
          }
      );
    },

    checkupReturn: function(resp) {
      resp.responseText.evalScripts();
    },

    uploadCallback: function(data, uploadID) {
        if (!(data && data.total && data.transferrate)) {
            return;
        }
        if (this.isprocessing) {
            return;
        }
        
        if ((data.done == this.lastdone) || (this.lastdone == undefined)) {
            this.watcherCounter++;
        }
        /*if(this.watcherCounter >= 30) {
            //upload possibly failed, force switch to checkup script.
            this.startCheckup();
            return;
        }*/
        var percent = Math.floor(data.done / data.total * 100);
        var transferrate = Math.floor(data.transferrate / 1024);
        var timeremaining = Math.floor(data.timeremaining);
        if (this.progressMonitor) {
            this.progressBar.setStyle({
                width: percent + "%"
            });
        }
        currentStatus = this.messages.progressDisplay;
        currentStatus = currentStatus.replace(/PERCENTUPLOADED/, percent);
        currentStatus = currentStatus.replace(/TRANSFERRATE/, transferrate);
        currentStatus = currentStatus.replace(/TIMEREMAINING/, timeremaining);
        this.setStatus(currentStatus);
    }
};

// from the onComplete function:
/*
Element.update(
    document.getElementsByClassName("uploadStatus")[0],
    "100% Complete"
);
Element.setStyle(
    document.getElementsByClassName("uploadBar")[0],
    {width: "100%", display: "block"}
);
$('status').innerHTML += "fileID: " + fileID;
$('status').innerHTML += " Type: " + type;
if(type=='image') {
    $('status').innerHTML += '<br /><a href="/userstore/view/' + fileID + '-{/literal}{$user->id}{literal}"><img src="http://www.dev.last.fm:8090/userstoreupload/app/server.php?id='+fileID+'&amp;u={/literal}{$user->id}{literal}&amp;ext=jpg&amp;v=160x160&amp;st=1&amp;' + Math.random() + '" border="0" /></a>';
} else if(type=='video') {
    $('status').innerHTML += '<br />Your video will be transcoded and ready soon';
    $('status').innerHTML += '<br /><a href="/userstore/view/' + fileID + '-{/literal}{$user->id}{literal}"><img src="http://www.dev.last.fm:8090/userstoreupload/app/server.php?id='+fileID+'&amp;u={/literal}{$user->id}{literal}&amp;ext=jpg&amp;v=image:160x120&amp;st=2&amp;' + Math.random() + '" border="0" /></a>';
}
$('status').innerHTML += '<br /><br />';
*/
