Wtf.grid.DynamicColumnModel = function(obj){
    var cols = [];
   for (var i = 0; i < obj.length; i++) {
        switch(obj[i].length) {
        case 0:
            cols[i] = obj[i];
            break;
        case 3:
            cols[i] = {header: obj[i][0],width: obj[i][1],dataIndex: obj[i][2]};
            break;    
        case 5:
            cols[i] = {header: obj[i][0],width: obj[i][1],dataIndex: obj[i][2],renderer: obj[i][3],editor:obj[i][4]};
            break;
        }
    }
    Wtf.grid.DynamicColumnModel.superclass.constructor.call(this, cols);
};

Wtf.extend(Wtf.grid.DynamicColumnModel, Wtf.grid.ColumnModel, {});


Wtf.WtfGridMaker = function(config) {
   Wtf.apply(this, config);
   
   this.columnModel = new Wtf.grid.DynamicColumnModel(config.columnModel);
   this.dataRecord = this.createRec(config.dataRecord);
   this.storeUrl = config.storeUrl;
   this.paging = config.paging;
   
   this.groupingView = new Wtf.grid.GroupingView({
        forceFit: true,
        showGroupName: false,
        enableGroupingMenu: true,
        hideGroupedColumn: false
   });
   
   this.columnModel.defaultSortable = true;
           
   this.dataReader = new Wtf.data.JsonReader({
        root: "data"
   }, this.dataRecord);
    
    this.dataStore = new Wtf.data.GroupingStore({
        proxy: new Wtf.data.HttpProxy({
            url: this.storeUrl
        }),
        reader: this.dataReader
    });    
    
    this.grid = new Wtf.grid.GridPanel({
        ds: this.dataStore,
        cm: this.columnModel,
        border: false,
        enableColumnHide: false,
        view: this.groupingView,
        trackMouseOver: true,
        loadMask: {
            msg: 'Loading...'
        },
        viewConfig: {
            forceFit: true
        }
    });      
    
    if(this.paging == true) {
        this.bbar = new Wtf.PagingToolbar({
                id: 'pgTbar' + this.id,
                pageSize: 5,
                store: this.dataStore,
                displayInfo: true,
                displayMsg: 'Displaying records {0} - {1} of {2}',
                emptyMsg: "No results to display",
                plugins: new Wtf.common.pPageSize({})
        });
    }
    
    Wtf.WtfGridMaker.superclass.constructor.call(this,{
        autoDestroy: true,
        border: false,
        layout: 'fit',
        items: [this.grid]
    });
}

Wtf.extend(Wtf.WtfGridMaker, Wtf.Panel, {
    
    ratingCell: function(text) {
        return '<img id="rating1" style="float:left;height:10px; width:10px " src="images/star.png"/><img id="rating2" style="float:left;height:10px; width:10px " src="images/star.png"/><img id="rating3" style="float:left;height:10px; width:10px " src="images/star.png"/><img id="rating4" style="float:left;height:10px; width:10px " src="images/star.png"/><img id="rating5" style="float:left;height:10px; width:10px " src="images/star.png"/>';
    },
    
    createRec: function(arr) {
        var tempArr = [];
        for(var i = 0;i < arr.length;i++){
            var obj={
                name: arr[i][0],
                type: arr[i][1]
            };
            tempArr.push(obj);
        }
        return Wtf.data.Record.create(tempArr);
    }
   
});

 Wtf.data.KwlDataReader = function(meta, recordType){
    
    this.meta = meta;
    this.recordType = recordType instanceof Array ? 
        Wtf.data.Record.create(recordType) : recordType;
};  
Wtf.data.KwlDataReader.prototype = {

};   
Wtf.extend(Wtf.data.KwlDataReader, Wtf.util.Observable); 

Wtf.data.KwlJsonReader = function(meta, recordType){
     meta = meta || {};
     Wtf.data.KwlJsonReader.superclass.constructor.call(this, meta, recordType);
      this.events = {
        aftereval : true
    };
     this.on("aftereval", this.jsonErrorResponseHandler);
    
};

Wtf.extend(Wtf.data.KwlJsonReader, Wtf.data.KwlDataReader, {
    read : function(response){
        var json = response.responseText;
        var o = eval("("+json+")");
        if (o && o.valid==false) {
            signOut("timeout");
        }
        else
            o = o.data;
        if(!o) {
            throw {message: "JsonReader.read: Json object not found"};
        }
        if(o.metaData){
            delete this.ef;
            this.meta = o.metaData;
            this.recordType = Wtf.data.Record.create(o.metaData.fields);
            this.onMetaChange(this.meta, this.recordType, o);
        }
        return this.readRecords(o);
    },
       
    onMetaChange : function(meta, recordType, o){

    },

    jsonErrorResponseHandler:function (json, reader, response) {
          if (json && !json.valid) {
		signOut("timeout");
          }
    },
    
    simpleAccess: function(obj, subsc) {
    	return obj[subsc];
    },

	
    getJsonAccessor: function(){
        var re = /[\[\.]/;
        return function(expr) {
            try {
                return(re.test(expr))
                    ? new Function("obj", "return obj." + expr)
                    : function(obj){
                        return obj[expr];
                    };
            } catch(e){}
            return Wtf.emptyFn;
        };
    }(),

    
    readRecords : function(o) {
        this.jsonData = o;
        var s = this.meta, Record = this.recordType,
            f = Record.prototype.fields, fi = f.items, fl = f.length;
        if (!this.ef) {
            if(s.totalProperty) {
	            this.getTotal = this.getJsonAccessor(s.totalProperty);
            }
            if(s.successProperty) {
                this.getSuccess = this.getJsonAccessor(s.successProperty);
            }
            this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
            if (s.id) {
                    var g = this.getJsonAccessor(s.id);
                    this.getId = function(rec) {
                            var r = g(rec);
                            return (r === undefined || r === "") ? null : r;
                    };
            } else {
                    this.getId = function(){return null;};
            }
            this.ef = [];
            for(var i = 0; i < fl; i++){
                f = fi[i];
                var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
                this.ef[i] = this.getJsonAccessor(map);
            }
        }

    	var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
    	if(s.totalProperty){
            var v = parseInt(this.getTotal(o), 10);
            if(!isNaN(v)){
                totalRecords = v;
            }
        }
        if(s.successProperty){
            var v = this.getSuccess(o);
            if(v === false || v === 'false'){
                success = false;
            }
        }
        var records = [];
        for(var i = 0; i < c; i++){
                var n = root[i];
            var values = {};
            var id = this.getId(n);
            for(var j = 0; j < fl; j++){
                f = fi[j];
            var v = this.ef[j](n);
            values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
            }
            var record = new Record(values, id);
            record.json = n;
            records[i] = record;
        }
        return {
            success : success,
            records : records,
            totalRecords : totalRecords
        };
    }
});

Wtf.Ajax.requestEx = function(config, scope, successCallback, failureCallback){
    Wtf.Ajax.request({
        method: "POST",
        url: config.url,
        scope: scope,
        params: Wtf.urlEncode(config.params),
        success: function(request, response){
            var res = null;
            try{
                var restext = request.responseText.trim();
                if(restext && (restext.length > 0)){
                    res = eval( '(' + restext + ')');
                    if(res && res.valid){
                        try{
                            if(successCallback){
                                successCallback.call(this, res.data, response);
                            }
                        } catch (e){
                            clog(e);
                        }
                    }
                    else if(res && (res.valid == false)){         
                        signOut("timeout");
                    }
                }
            } catch (e){
                clog(e);
                if(failureCallback)
                    failureCallback.call(this, request, response);                
            }
        },
        failure: function(request, response){
            if(failureCallback)
                failureCallback.call(this, request, response);
        }
    });
}

function clog(e){
    if(console && console.debug && e){
        console.debug(e.toString());
    }
}


Wtf.changePassWin = function(config){
    Wtf.apply(this, config);
    Wtf.changePassWin.superclass.constructor.call(this,{
        iconCls:'winicon',
        resizable:false,
        width:380,
        modal:true,
        height:250,
        title:'Change Password',
        buttons:[{
            text:"Change",
            scope:this,
            handler:function(){
                if(this.pass.form.isValid()){
                    if(this.newPass.getValue() == this.cNewPass.getValue()){
                        this.pass.form.submit({
                            waitMsg: 'Loading...',
                            scope : this,
                            params: {
                                mode : 6,
                                userid : loginid
                            },
                            failure: function(request, response){
                                Wtf.Msg.alert('Error', 'Error connecting to server',function(btn){
                                    if(btn=="ok"){
                                        this.close();
                                    }
                                },this);  
                            },
                            success: function(request, response){
                                var obj = Wtf.decode(response.response.responseText);
                                if(obj.flag!=null){
                                    if(obj.flag==1){
                                        Wtf.Msg.alert('Alert', 'Please enter the correct old password',function(btn){
                                            if(btn=="ok"){
                                            
                                            }
                                        },this);  
                                    }else{
                                    Wtf.Msg.alert('Alert', 'Password changed successfully',function(btn){
                                        if(btn=="ok"){
                                            this.close();
                                        }
                                    },this);  
                                    }
                                }
                            }
                        });
                    }else{
                        Wtf.Msg.alert('Alert', 'Entered passwords do not match',function(btn){
                            if(btn=="ok"){
                                
                            }
                        },this);              
                    }
                }
            }
        },{
            text:'Cancel',
            scope:this,
            handler:function(){
                this.close();
            }
        }],
        layout:'border',
        items:[{
            region:'north',
            height : 75,
            border : false,
            bodyStyle : 'background:white;border-bottom:1px solid #bfbfbf;',
            html : getHeader('web/images/ack40.gif',"Change Password", "Enter password details") 
        },{
            region:'center',
            layout:'fit',
            border:false,
            bodyStyle : 'background:#f1f1f1;border-bottom:1px solid #bfbfbf;padding:10px',
            items:[
                this.pass = new Wtf.form.FormPanel({
                    url: 'web/phpfiles/person.php',
                    waitMsgTarget: true,
                    method : 'POST',
                    border:false,
                    labelWidth:160,
                    items:[
                        this.oldPass = new Wtf.form.TextField({
                            allowBlank:false,
                            fieldLabel:'Old Password*',
                            name:'oldpass',
                            inputType:'password'
                        }),
                        this.newPass = new Wtf.form.TextField({
                            allowBlank:false,
                            fieldLabel:'New Password*',
                            name:'newpass',
                            inputType:'password'
                        }),
                        this.cNewPass = new Wtf.form.TextField({
                            allowBlank:false,
                            fieldLabel:'Confirm New Password*',
                            name:'newpass',
                            inputType:'password'
                        })
                    ]
                })
            ]
        }]
    });
};

Wtf.extend(Wtf.changePassWin,Wtf.Window,{
    
});