/**
  * Floco.ext.UploadButton Class
  *
  * @author Joshua Suggs
  * @version 1.1
  *
  * @class Floco.ext.UploadButton
  * @extends Ext.Button
  * Button class to facilitate a file upload
  
  * @constructor
  * @param {Object} config
  */

Floco.ext.UploadButton = Ext.extend(Ext.Button, {
	window : false,
	
    form : null,
    
    input: false,
    
    validFileTypes: [],

	enableWaitMsg: true,
    
    initComponent : function(){
        Floco.ext.UploadButton.superclass.initComponent.call(this);
        
        this.addEvents({
            beforeload: true,
            success: true,
            failure: true,
            fileexception: true
        });

        if(typeof this.fTypes === "string"){
            this.validFileTypes = [this.fTypes];
        }else if(this.fType == "*"){
			this.validFileTypes = [];
		}else{
            this.validFileTypes = this.fTypes;
        }
        delete(this.fTypes);
        
        if(this.fMsg) {
            this.invalidFileMsg = this.fMsg;
        }
        delete(this.fMsg);
    },

    onRender : function(ct, position){
        Floco.ext.UploadButton.superclass.onRender.call(this, ct, position);

		this.on('click', this.showWindow, this);
    },

	showWindow : function(){
		this.window = this.initWindow();
		this.initInputEl();
		this.window.show();
	},

	initWindow : function(){
		if(!this.window) {
			win = new Ext.Window({
				autoCreate:true,
				title:'File upload',
				resizable:false,
				constrain:true,
				constrainHeader:true,
				minimizable:false,
				maximizable:false,
				stateful:false,
				modal:true,
				shim:true,
				buttonAlign:'center',
				width:300,
				height:100,
				minHeight:80,
				plain:true,
				footer:true,
				closable:true,
				closeAction:'hide',
				buttons:[{
					text: 'Cancel',
					handler: function(){
						win.hide();
					}
				}]
			});
			win.render(document.body);
			win.getEl().addClass('x-window-dlg');
			win.form = win.body.createChild({
				tag: 'form',
	            method : 'POST',
	            id: this.formId || Ext.id(),
	            enctype: 'multipart/form-data'
			});
		}
		return win;
	},
    
    initInputEl : function(){
        if(this.input){
            this.input.remove();
        }
        
        var o = {
            tag: 'input', 
            type:'file', 
            name:'upload_file',
            size: 20, 
            cls:'x-btn-file',
            id: Ext.id()
        };
        this.input = this.window.form.insertFirst(o);

		this.input.center(this.window.body);

        if(this.tooltip){
          if(typeof this.tooltip == 'object'){
              Ext.QuickTips.register(Ext.apply({
                  target: this.input
                  }, this.tooltip));
          } else {
              this.input.dom[this.tooltip] = this.tooltip;
          }
        }

        this.input.on("change", this.onInputChange, this);
    },

    onInputChange : function(e){
        this.fileName = this.input.getValue();
        this.fileExt = this.parseExt(this.fileName);
        
        if(this.validateFile()){
            this.submitForm(e);
        } else {
          this.fireEvent("fileexception", this, this.fileName, this.validFileTypes);
          
          if(Ext.isEmpty(this.invalidFileMsg)){
              var str = "Only the following file types are allowed: <b>{0}</b>.";
              this.invalidFileMsg = String.format(str, this.validFileTypes.join(','));
          }
          Ext.Msg.alert('Invalid File Type!', this.invalidFileMsg);
          this.initInputEl();
        }
    },
    
    submitForm : function(e){
        if(this.fireEvent("beforeload", this, e) !== false){
			this.window.hide();
			
			if(this.enableWaitMsg)
				this.waitMsg = Ext.MessageBox.wait(this.loadMsg || "Processing...");
					
            this.transID = Ext.Ajax.request({
                url: this.url,
                method: 'post',
                isUpload: true,
                form: this.window.form,
                scope: this,
                params: Ext.apply(this.baseParams,{ext:this.fileExt}),
                success: this.handleResponse
            });
        }
    },
    
    handleResponse : function(res){
        this.transId = false;
        var r = Ext.decode(res.responseText);
        if(r.success){
            this.fireEvent("success", this, r, res);
        } else {
            this.fireEvent("failure", this, res, r.fault);
            
        }
		if(this.enableWaitMsg) this.waitMsg.hide();
        this.initInputEl();
    },
    
    isUploading : function(){
        return this.transId ? true : false;
    },

    parseExt : function(fn){
         var p = fn.split('.');
         if(p.length == 1){
             return null;
         } else {
             return p.pop();
         }
    },
    
    validateFile : function(){
        if (this.validFileTypes.length > 0 && this.fileExt) {
            return this.validFileTypes.indexOf(this.fileExt) != -1;
        } else {
            return true;
        }
    }
});
Ext.reg('uploadbutton', Floco.ext.UploadButton);