/**
  * Floco.data.UserStore Class
  *
  * @author Joshua Suggs
  * @version 1.0
  *
  * @class Floco.data.UserStore
  * @extends Ext.util.Observable
  * Class to handle server side user authentication. Expects JSON response.
  
  * @constructor
  * @param {Object} config
  */
Floco.data.UserStore = function(config){
    this.baseParams = {};
    this.requestMethod = "POST";
    Ext.apply(this, config);
    
    if(this.ap){
        this.adminProperty = this.ap;
        delete this.ap;
    }
    
    this.addEvents({
        "beforeload" : true,
        "load" : true,
        "loadexception" : true,
        "authexception" : true,
		"authsuccess" : true
    });
    
    Floco.data.UserStore.superclass.constructor.call(this);
    
    if(this.autoLoad) {
        this.load.defer(10, this);
    }
};
Ext.extend(Floco.data.UserStore, Ext.util.Observable, {
    load : function(callback, scope) {
        if(this.fireEvent("beforeload", this, callback) !== false){
            this.transId = Ext.Ajax.request({
                method:this.requestMethod,
                url:this.url,
				params: this.params,
                success: this.handleResponse,
                failure: this.handleFailure,
                scope: this,
                argument: {callback: callback, scope: scope}
            });
        }else{
            if(typeof callback == "function"){
                callback.call(scope || this, this);
            }
        }
    },
    
    isLoading : function(){
        return this.transId ? true : false;
    },
    
    handleResponse : function(response){
        this.transId = false;
        var a = response.argument;
        this.processResponse(response, a.callback, a.scope);
        this.fireEvent("load", this, response);
    },
    
    processResponse : function(response, callback, scope){
        var json = response.responseText;
        try {
            var o = eval("("+json+")");
            if(o.authenticated){
                Ext.apply(this, o);
                this.isAdmin = o.data.admin;
				this.fireEvent('authsuccess', this, o);
            }else{
                this.isAdmin = false;
                this.fireEvent('authexception', this, o);
            }

            // if(typeof callback == "function"){
            //     callback.call(scope || this, this);
            // }
        }catch(e){
            this.handleFailure(response);
        }
    },
    
    handleFailure : function(response){
        this.transId = false;
        this.fireEvent('loadexception', this, response);
    }
});
Ext.reg("userstore", Floco.data.UserStore);