var FileUploader = Class.create({
    ID_KEY           : 'APC_UPLOAD_PROGRESS',
    statusUrl        : '../../ajax/uploadStatus.php',
    pollDelay        : 0.5,

    form             : null, // HTML form element
    status           : null, // element where the upload status is displayed
    idElement        : null, // element that holds the APC upload ID
    iframe           : null, // iframe we create that form will submit to
    url_filename     : null,
	allowedExtensions: [],
	uploadFiles      : [],
	elmToCheck       : null,

    initialize : function(form, status, allowedExtensions, elmToCheck) {
        // initialize the form and observe the submit element
        this.form = $(form);

       	this.form.observe('submit', this._onFormSubmit.bindAsEventListener(this));

        // create a hidden iframe
        this.iframe = new Element('iframe', { name : '_upload_frame' }).hide();

        // make the form submit to the hidden iframe
        this.form.appendChild(this.iframe);
        this.form.target = this.iframe.name;

        // initialize the APC ID element so we can write a value to it later
        this.idElement = this.form.getInputs(null, this.ID_KEY)[0];

        // initialize the status container
        this.status = $(status);
		
		this.allowedExtensions = allowedExtensions;
		this.elmToCheck = elmToCheck;
    },

    generateId : function() {
        var now = new Date();
        return now.getTime();
    },

    delay : function(seconds) {
        var ms   = seconds * 1000;
        var then = new Date().getTime();
        var now  = then;

        while ((now - then) < ms)
            now = new Date().getTime();
    },

	isAlreadyUploaded : function(filename) {
		var count = this.uploadFiles.length;
		for (var i = 0; i < count; i++) {
			if (filename == this.uploadFiles[i]) {
				return true;
			}
		}
		return false;
	},

	removeFile : function(filename) {
		var count = this.uploadFiles.length;
		for (var i = 0; i < count; i++) {
			if (filename == this.uploadFiles[i]) {
				this.uploadFiles.splice(i, 1);
				continue;
			}
		}
	},

    _onFormSubmit : function(e) {
		if (!this.elmToCheck || (this.elmToCheck.checked)) {
			//make sure the file has an allowed extension
			if (e.target.image && this.allowedExtensions.indexOf(e.target.image.value.substring(e.target.image.value.lastIndexOf('.') + 1, e.target.image.value.length).toLowerCase()) > -1) {
				if (e.target.image.value.indexOf('/') > -1) {
					this.url_filename = e.target.image.value.substring(e.target.image.value.lastIndexOf('/') + 1, e.target.image.value.length);
				} else {
					this.url_filename = e.target.image.value.substring(e.target.image.value.lastIndexOf('\\') + 1, e.target.image.value.length);
				}
				this.url_filename = escape(this.url_filename);
				//make sure the file has not been uploaded yet
				if (!this.isAlreadyUploaded(this.url_filename)) {
					var id = this.generateId();
	
					this.idElement.value = id;
					this._monitorUpload(id);
				}
			}
		}
    },

    _monitorUpload : function(id) {
        var options = {
            parameters : 'id=' + id,
            onSuccess  : this._onMonitorSuccess.bind(this)
        };

        new Ajax.Request(this.statusUrl, options);
    },

    _onMonitorSuccess : function(transport) {
        var json = transport.responseJSON;

		if (!json.finished || (json.total > 320)) { //discard invalid files
			this.status.show();
			if (json.finished) {
				json.url_filename = this.url_filename;
				this.uploadFiles.push(this.url_filename);
			}
			this.status.fire("upload:Status", json);
			
			if (!json.finished) {
				this.delay(this.pollDelay);
				this._monitorUpload(json.id);
			}
		}
		if (json.finished) {
			this.status.hide();
		}
    }
});
