Ext.ns('Verisoul');
Ext.ns('Verisoul.UI.Toolbar');
Ext.ns('Verisoul.UI.Data');
Ext.ns('Verisoul.UI.Panel');

Verisoul.Util= function(){
	return{
		random:function(){
			return new Date().getTime();
		},
		isValid:function(id){
		     var fld = Ext.getCmp(id);
			if( fld != null && fld.validateValue(fld.getValue())) return true;
			else return false;
		}
	};	
}();

Verisoul.UI.Toolbar.InboxGridPagingBar = Ext.extend(Ext.PagingToolbar,{
	cmd:'',
	grid:'',
	ibmode:'',
    initComponent : function(){	

        this.prependButtons = true;	
		
		this.buttons = [
		new Ext.Button({
			tooltip:'Create New Message',
			text:'New Message',
			iconCls:'svw',
			handler:function(){
				sendPrivateMessage('','','',true);
			}
		}),'-',
		//this.addSeparator();
		new Ext.Button({
			tooltip:'Delete',
			text:'Delete',
			iconCls:'sdel',
			scope:this,
			handler:function(){
				var recs = Ext.getCmp(this.grid).getSelectionModel().getSelections();			
				if (recs != null && recs.length >0)
				{
				    
					Ext.MessageBox.confirm('Delete Message(s)', 'Are you sure you want to Delete ?', 
					function delRec()
					{
					    var id='';
					    Ext.each(recs,function(item,index,allItems){
						   if(id == '') id = item.get("i");
						   else id = id +","+item.get("i");
						});
						showProgressWindow('Deleting message', this);
						Ext.Ajax.request({
                        url: '/DesktopModules/UserSearch/UserList.aspx?cmd=dpm&ibmode='+this.ibmode,
                        scope: this,
                        method: 'post',
                        params: {"u": id},
						failure: function(){Ext.MessageBox.hide();},
						success: function(){Ext.MessageBox.hide();Ext.getCmp(this.grid).getStore().reload();}						
						});
					},this);
				}			
			}
		}), '-'];
				
		this.displayInfo = true;
		Verisoul.UI.Toolbar.InboxGridPagingBar.superclass.initComponent.call(this);
		this.displayItem = new Ext.Toolbar.TextItem({});
		this.updateInfo();
    }
});

Verisoul.UI.Data.Dataview = Ext.extend(Ext.DataView, {
    pagingBar:'',
	maxPageCount:0,
	pageSize:10,
	initComponent: function(){		    		
		var ds = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: '/DesktopModules/UserSearch/UserList.aspx?cmd=rusr',method:'GET'
			}),
			baseParams:{limit:this.pageSize},
			reader: new Ext.data.JsonReader({
				totalProperty: 't',
				root: 'r',
				id: 'ord'
			}, [{ name: 'n'},{name:'a'},{name:'l'},{name: 'img'}, {name:'id'},{name:'fs'},{name:'bs'},{name:'cs'},{name:'fm'},{name:'ru'},{name:'pm'}]),
			autoLoad: true
		});	
		
		var s = new VerisoulJS();
		var locData = s.getLocaleData("2");
		locData = Ext.decode(locData);
		
		function dsLoaded(r, options, success) {
			this.maxPageCount = r.reader.jsonData.t;
			
		}
		
		ds.on("load",dsLoaded,this);
		
		Ext.apply(this, {
            store: ds,
            tpl: new Ext.XTemplate(
            '<tpl for=".">',				    
		    '<div class="ou-wrap" style="width:175px;height:200px;float:left;margin:5px;"><div class="x-clear"></div>',
			'<div class="x-box-tl">','<div class="x-box-tr">','<div class="x-box-tc">','</div></div></div>',
			'<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">',
			'<table>',
			'<tr>',
				'<td style="border-bottom:1px dotted #000;text-align:center;">',
					'<span class="Normal" style="font-weight:bold;">{n}</span>&nbsp;&nbsp;',
				'</td>',
			'</tr>',
			'<tr>',
				'<td style="padding:0px">',
					'<table class="Sample-Contact">',
						'<tr>',
							'<td style="width: 100px; height: 100px;">',
								'<a id="{id}User" class="verilink" href="/Search/tabid/55/m/sud/n/{n}/Default.aspx">',								
								'<img id="{id}usrImg" src="/ImgGen.axd?imgd={img}&amp;ims=l" align="top" style="border-width:0px;" title="Click here to see {n}\'s profile"/>',
								'</a>',
							'</td>',
						'</tr>',
						'<tr>',
							'<td align="center">',
								'<div id="{id}rtngUser" class="ratingStar" onclick="return false;">',
									'',
								'</div>',
							'</td>',
						'</tr>',
					'</table>',
				'</td>',
			'</tr>',
			'<tr>',
				'<td style="line-height:18px;">',
					'<input style="padding:0px 1px;" src="/images/icon_hostusers_16px.gif" name="{id}lnkPm" type="image" id="{id}lnkPm" title="Send {n} a Private message" onclick="return {pm};" />&nbsp;&nbsp;',				
					'<input style="padding:0px 1px;" src="/images/favorite_add.png" name="{id}lnkFav" type="image" id="{id}lnkFav" title="',locData.FavTitle,'" onclick="return {fs};" />&nbsp;&nbsp;',
					'<input style="padding:0px 1px;" src="/images/icon_bulkmail_16px.gif" name="{id}lnkForward" type="image" id="{id}lnkForward" title="',locData.FriendTitle,'" onclick="return {fm};" />&nbsp;&nbsp;',
					'<input style="padding:0px 1px;" src="/images/action_settings.gif" name="{id}lnkComments" type="image" id="{id}lnkComments" title="',locData.CommentTitle,'" value="Comments" onclick="return {cs};" />&nbsp;&nbsp;',
					'<input style="padding:0px 1px;" src="/images/block.png" name="{id}lnkBlock" type="image" id="{id}lnkBlock" title="',locData.BlkTitle,'" onclick="return {bs};" />&nbsp;&nbsp;',
					'<input style="padding:0px 1px;" src="/images/icon_viewstats_16px.gif" name="{id}lnkReport" type="image" id="{id}lnkReport" title="',locData.ReportTitle,'" onclick="return {ru};" />&nbsp;&nbsp;',
				'</td>',
			'</tr>',
			'</table>',
			'</div></div></div><div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
			'</div>',			
			'</tpl>',
			'<div class="x-clear"></div>'
            ),
            overClass: 'x-view-over',
            itemSelector: 'div.ou-wrap',
            loadMask: true
        });

		this.pagingBar = new Ext.PagingToolbar({
			pageSize: this.pageSize,
			store: ds,
			displayInfo: true,
			displayMsg: 'Showing Users {0} - {1} of {2}',			
			items: [
			'-']
	    });

        Verisoul.UI.Data.Dataview.superclass.initComponent.call(this);
	},
	
	onRender:function(ct, pos) {	
		var myStore = this.store;
		var pBar = this.pagingBar;
		new Ext.util.TaskRunner().start({
		    scope:this,
			run: function() {
			if(this.maxPageCount == 0) return;
			var str=pBar.cursor+pBar.pageSize;
			if(str>this.maxPageCount) pBar.first.handler(pBar,["first"]);
			else pBar.next.handler(pBar,["next"]);
		},
		interval: 180000
	});
	Verisoul.UI.Data.Dataview.superclass.onRender.call(this, ct, pos);
  }
});

Verisoul.UI.Data.Winkview = Ext.extend(Ext.DataView, {
    pagingBar:'',
	maxPageCount:0,
	winkType:'',
	pageSize:10,
	initComponent: function(){	
		this.loadingText = "Please wait";
		this.style= {overflow: 'auto'};
		var ds = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: '/DesktopModules/UserSearch/UserList.aspx?cmd=winkdet&t='+this.winkType,method:'GET'
			}),
			baseParams:{limit:this.pageSize},
			reader: new Ext.data.JsonReader({
				totalProperty: 't',
				root: 'r',
				id: 'id'
			}, [{ name: 'id'}, {name:'dm'}, {name:'cs'},{name:'wr'}]),
			autoLoad: true
		});	
				
		function dsLoaded(r, options, success) {
			this.maxPageCount = r.reader.jsonData.t;			
		}			
		
		ds.on("load",dsLoaded,this);
		ds.on("exception",function(proxy,type,action,opt,resp,args){
		alert(resp.responseText);
		},this);
		Ext.apply(this, {
            store: ds,
            tpl: new Ext.XTemplate(
            '<tpl for=".">',				    
		    '<div class="wnkGroup" style="border:#DFE8F6 solid 1px;">',
			'<div class="{cs}b">','<div class="wnkGroup">{dm}</div>','</div>',
			'<div>{wr}</div>',
			'</div>',			
			'</tpl>'
            ),
            overClass: 'x-view-over',
            itemSelector: 'div.wnkGroup',
            loadMask: true
        });

		this.pagingBar = new Ext.PagingToolbar({
			pageSize: this.pageSize,
			store: ds,
			displayInfo: true,
			displayMsg: 'Showing Winks {0} - {1} of {2}',			
			items: [
			'-']
	    });
		//this.autoScroll=true;
        Verisoul.UI.Data.Winkview.superclass.initComponent.call(this);
	}
});

Verisoul.UI.Data.FileUploadField = Ext.extend(Ext.form.TextField,  {
    /**
     * @cfg {String} buttonText The button text to display on the upload button (defaults to
     * 'Browse...').  Note that if you supply a value for {@link #buttonCfg}, the buttonCfg.text
     * value will be used instead if available.
     */
    buttonText: 'Browse...',
    /**
     * @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible
     * text field (defaults to false).  If true, all inherited TextField members will still be available.
     */
    buttonOnly: false,
    /**
     * @cfg {Number} buttonOffset The number of pixels of space reserved between the button and the text field
     * (defaults to 3).  Note that this only applies if {@link #buttonOnly} = false.
     */
    buttonOffset: 3,
    /**
     * @cfg {Object} buttonCfg A standard {@link Ext.Button} config object.
     */

    // private
    readOnly: true,
    
    /**
     * @hide 
     * @method autoSize
     */
    autoSize: Ext.emptyFn,
    
    // private
    initComponent: function(){
        Verisoul.UI.Data.FileUploadField.superclass.initComponent.call(this);
        
        this.addEvents(
            /**
             * @event fileselected
             * Fires when the underlying file input field's value has changed from the user
             * selecting a new file from the system file selection dialog.
             * @param {Verisoul.UI.Data.FileUploadField} this
             * @param {String} value The file value returned by the underlying file input field
             */
            'fileselected'
        );
    },
    
    // private
    onRender : function(ct, position){
        Verisoul.UI.Data.FileUploadField.superclass.onRender.call(this, ct, position);
        
        this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});
        this.el.addClass('x-form-file-text');
        this.el.dom.removeAttribute('name');
        
        this.fileInput = this.wrap.createChild({
            id: this.getFileInputId(),
            name: this.name||this.getId(),
            cls: 'x-form-file',
            tag: 'input', 
            type: 'file',
            size: 1
        });
        
        var btnCfg = Ext.applyIf(this.buttonCfg || {}, {
            text: this.buttonText
        });
        this.button = new Ext.Button(Ext.apply(btnCfg, {
            renderTo: this.wrap,
            cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '')
        }));
        
        if(this.buttonOnly){
            this.el.hide();
            this.wrap.setWidth(this.button.getEl().getWidth());
        }
        
        this.fileInput.on('change', function(){
            var v = this.fileInput.dom.value;
            this.setValue(v);
            this.fireEvent('fileselected', this, v);
        }, this);
    },
    
    // private
    getFileInputId: function(){
        return this.id+'-file';
    },
    
    // private
    onResize : function(w, h){
        Verisoul.UI.Data.FileUploadField.superclass.onResize.call(this, w, h);
        
        this.wrap.setWidth(w);
        
        if(!this.buttonOnly){
            var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset;
            this.el.setWidth(w);
        }
    },
    
    // private
    preFocus : Ext.emptyFn,
    
    // private
    getResizeEl : function(){
        return this.wrap;
    },

    // private
    getPositionEl : function(){
        return this.wrap;
    },

    // private
    alignErrorIcon : function(){
        this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
    }
    
});
Ext.reg('fileuploadfield', Verisoul.UI.Data.FileUploadField);

Verisoul.UI.Toolbar.Notification = Ext.extend(Ext.Toolbar,{
    logged:'',
    initComponent : function(){
	    if(window.location.protocol.indexOf("https") >= 0){if(Ext.get("v-notif-div") != null) Ext.get("v-notif-div").hide();return;}
		Verisoul.UI.Toolbar.Notification.superclass.initComponent.call(this);
		var ds = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: '/UserList.aspx?cmd=winkbar&chk='+Verisoul.Util.random(),method:'GET'
			}),
			reader: new Ext.data.JsonReader({
				totalProperty: 't',
				root: 'r',
				id: 'id'
			}, [{ name: 'id'},{name:'h'},{name:'c'},{name:'tl'},{name:'fn'},{name:'p'}]),
			autoLoad:false
		});
		
		function dsLoaded(str, r, options) {
			var menu = new Ext.menu.Menu();
			Ext.each(r,function (obj,i,all){
				var tcmp = {id:"wnk"+obj.data.id,tooltip:obj.data.tl, text:obj.data.h,iconCls:obj.data.c,scope:this,handler:function(){eval("this."+obj.data.fn)(obj.data.id,obj.data.tl);}};			    
				this.add(tcmp);	
				this.add("-");
			}, this);				
			this.doLayout();
		
			var _notifWnd;
            var me = Ext.get("v-notif-div");
			new Ext.util.TaskRunner().start({
				scope:this,
				run: function() {
				    Ext.Ajax.request({
					url:'/UserList.aspx?cmd=gntf',					
					method:'GET',
					success:function(res,req){
					    var msg = res.responseText;
						if(msg == '') {
						return;
						}
						var object = Ext.util.JSON.decode(msg);
						if(object.m != ""){					
							if(!_notifWnd){					     
								_notifWnd = Ext.DomHelper.insertAfter('notifCnt', {id:'v-notif-div-msg'}, true);
								_notifWnd.alignTo('notifCnt', 'tl-bl',[0,10]);
							}
							_notifWnd.dom.innerHTML="";	
							_notifWnd.insertHtml("afterBegin", String.format('<h3>{0}</h3>', object.m));			
							_notifWnd.slideIn('t').pause(4).ghost("t", {remove:false});
						}
						
						Ext.each(object.w, function(obj,i,all){
							var cmp = Ext.getCmp("wnk"+obj.i);
							cmp.setText(obj.t);
							var ca = obj.c.split();
							cmp.removeClass(ca[0]);
							cmp.removeClass("tbold");
							cmp.addClass(obj.c);
						});
						
						Ext.getCmp("v-notif-wnk").doLayout();
					},
					failure:function(res,req){}
					});			
				},
				interval: 300000
			});			
		}
			
		ds.on("load",dsLoaded,this);
		ds.load();		
	},
	showLogin:function(){
	 Ext.MessageBox.alert('Show Winks', 'Please Login/Register to see the winks you recieved');
	},
	createBox: function(t){
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3></div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    },
	showWinks:function(wid,tl){
	   var wView=new Verisoul.UI.Data.Winkview({
			winkType:wid
		});
		
		var win = new Ext.Window({
			title: tl,
			layout: 'fit',
			width:500,
			height: 300,
			closeAction: 'hide',
			autoScroll:true,
			plain: false,
			modal: true,
			tbar:wView.pagingBar,
			items: wView,			
			buttons: [{
				text: 'Close',
				iconCls:'ncancel',
				handler: function(){						
					win.hide();
				}
			}]
		});	
		win.show();	
	}
});
Verisoul.UI.Notification = function(){
	var _notifWnd;
  
   return{
		display:function(){
			if(!_notifWnd){
				_notifWnd = Ext.DomHelper.insertFirst('notifCnt', {id:'v-notif-div'}, true);				
			}
			_notifWnd.alignTo('notifCnt', 't-t');
			new Verisoul.UI.Toolbar.Notification({id:'v-notif-wnk', renderTo:'v-notif-div',cls:'notiftb',width:700,border:false,enableOverflow:true});
		}
   };
}();

Verisoul.UI.WinkPanel = function(){
   return{
		display:function(to,repid){
			var ds = new Ext.data.Store({
				proxy: new Ext.data.HttpProxy({
					url: '/UserList.aspx?cmd=winks&usr='+to,method:'GET'
				}),
				reader: new Ext.data.JsonReader({
					totalProperty: 't',
					root: 'r',					
					id: 'id'
				}, [{ name: 'id'},{name:'h'},{name:'c'}]),
				autoLoad:true
			});	
			
			function dsLoaded(str, r, options) {
				var winks=[];
				Ext.each(r,function (obj,i,all){
					winks[i]=new Ext.form.Radio({name:'winkgrp',itemCls:obj.data.c,title:obj.data.h,boxLabel: obj.data.h , inputValue:obj.data.id,
					listeners: {check: function(obj,check){
					if(check) {Ext.getCmp('wnkSendBtn').enable();}else{Ext.getCmp('wnkSendBtn').disable();}}}
					});
				}, this);

				var wnk = new Ext.Window({width:300,height:200,layout:'fit',modal: true,closeAction:'close',
					buttons:[{text:'Send',iconCls:'nWinkb',id:'wnkSendBtn', disabled:true, handler:function(){
						if(Ext.getCmp('wnkrdgrp').items.get(0).getGroupValue() == null || Ext.getCmp('wnkrdgrp').items.get(0).getGroupValue() == '')
						return;
						showProgressWindow('Sending Wink...', this);
						new Ext.data.Connection().request({
							url: "/UserList.aspx?cmd=sndwnk",
							scope: this,
							method: 'GET',
							params: {
								"w": Ext.getCmp('wnkrdgrp').items.get(0).getGroupValue(),
								"u": to,
								"r":repid
							},
							failure: requestFailed,
							success: requestSuccessful
						});
						return false;
					}}],
					title:'<p style="font-size:medium;">Select a Wink to send</p>', items:
				{ xtype: 'radiogroup', id:'wnkrdgrp', cls:'wnkGroup', columns:3,vertical:true, items:winks}});
				wnk.show();			
			}	
			
			ds.on("load",dsLoaded,this);
		},
		showLogin:function(){
		 Ext.MessageBox.alert('Send Wink', 'Please Login/Register to send the Wink');
		},
		sendWink:function(usr,wink){
		alert(Ext.getCmp('wnkrdgrp').getValue().getValue());
		}
   };
}();

Verisoul.UI.Toolbar.Userbar = Ext.extend(Ext.Toolbar,{
    logged:'',
	title:'',
	favAction:'', //a or d
	userImage:'',
	friend:'',
    initComponent : function(){
		Verisoul.UI.Toolbar.Userbar.superclass.initComponent.call(this);
		var d=false;
		if (this.logged == "0" || this.logged == "") d=true;
		
		var imActn = new Ext.Action({
			tooltip: 'Add/Remove ' + this.title + ' to/from your Friend&quot;s list',
			scope: this,
			disabled:d,
			width:55,
			cls:'toolBtn',
			text:'Add Friend',
			id: 'imActn' + this.title,
			params: { "fid": this.title},
			iconCls: 'addFnd'
        });		
		if (this.friend == "1") {
			imActn.setHandler(function() { removeFriend(this.title); }, this);
			imActn.setText('Remove Friend');
			imActn.setIconClass('remFnd');
		} else {
			imActn.setHandler(function() { addFriendRequest(this.title); }, this);
			imActn.setText('Add Friend');
			imActn.setIconClass('addFnd');
		}
		this.add(imActn);
		this.add('-');
		this.add(new Ext.Action({
			text:'Wink',
			toottip:'Send a Wink',
			disabled:d,
			width:55,
			scope:this,id:'wnkActn'+this.title,
			params:{"fid":this.title},
			handler: function(obj) {
				winkUser(obj.params.fid);
			},
			iconCls: 'nWinkb'
		}));
		this.add('-');
		this.add(new Ext.Action({
			text: 'Send Message',
			scope: this,
			disabled:d,
			width:55,
			id: 'actnPm' + this.title,
			tooltip:'Send ' + this.title + ' a Private message',
			params: { "fid": this.title },
			handler: function(obj) {
				sendPrivateMessage(obj.params.fid, '','',false);
			},
			iconCls: 'pmUser'
		}));
		this.add('-');
		var favTitle = "Add Favourite";
		var favCss = "addFav";
		var ftip = 'Add ' + this.title + ' to my favourites list';
		if(this.favAction == "d"){
			ftip = 'Remove ' +this.title + ' from my favourites list';
			favTitle = "Remove Favourite";
			favCss = "remFav";
		}
		
		this.add(new Ext.Action({
			text: favTitle,
			id: 'actnFav' + this.title,
			disabled:d,
			tooltip:ftip,
			width:55,
			params: { "fid": this.title,"mode":this.favAction },
			handler: function(obj) {
				mngFav(obj.params.fid, obj.params.mode);
				if(obj.params.mode == "a")
				{
				obj.setIconClass("remFav");
				obj.setText("Remove Favourite");
				obj.params.mode = "d";
				}else
				{
				obj.setIconClass("addFav");
				obj.setText("Add Favourite");
				obj.params.mode = "a";
				}
			},
			iconCls: favCss
        }));
		this.add('-');
		this.add(new Ext.Action({
                text: 'Forward',
				width:55,
                scope: this,
                id: 'actnFwd' + this.title,
				tooltip: "Forward " + this.title + "'s profile to your friend(s)",
                params: { "fid": this.title, "img":this.userImage },
                handler: function(obj) {
                    forwardEmail('Forward to a friend', obj.params.fid, obj.params.img);
                },
                iconCls: 'forward'
        }));
		this.add('-');
		this.add(new Ext.Action({
			text: 'Post Comments',
			width:55,
			id: 'actnCmt' + this.title,
			disabled:d,
			params: { "fid": this.title },
			tooltip:'Leave Comments for ' + this.title,
			handler: function(obj) {
				return ShowCmt('Leave Comments', obj.params.fid);
			},
			iconCls: 'cmtsApp'
        }));
		this.add('-');
		this.add(new Ext.Action({
			text: 'Block',
			scope: this,
			width:55,
			disabled:d,
			tooltip:'Block ' + this.title + ' from messaging me and exclude from all Searches',
			id: 'blkActn' + this.title,
			params: { "fid": this.title },
			handler: function(obj) {
				blkUser('Block User', obj.params.fid);
			},
			iconCls: 'blkuser'
        }));
		this.add('-');
		this.add(new Ext.Action({
			text: 'Report Abuse',
			scope: this,
			width:55,
			id: 'rptActn' + this.title,
			tooltip: 'Report abusive/offensive usage of Verisoul.com terms',
			params: { "fid": this.title },
			handler: function(obj) {
				reportUser('Report User', obj.params.fid, 'R');
			},
			iconCls: 'abuser'
        }));		
	},
	showLogin:function(){
	 Ext.MessageBox.alert('Show Winks', 'Please Login/Register to see the winks you recieved');
	}
});

Verisoul.UI.Data.UsersGrid = Ext.extend(Ext.grid.GridPanel, {
	border: true,
	serviceUrl:'',
    initComponent: function() {		
		var store = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({ url: this.serviceUrl}),
            idProperty: 'name',
            disableCaching: true,
            reader: new Ext.data.JsonReader(
				{ root: 'data', totalProperty: 'totalRecs' },
				[
					{ name: 'name', type: 'string' },
					{ name: 'usrImg', type: 'string' },
					{ name: 'l', type: 'string' },
					{ name: 'age', type: 'string' },
					{ name: 'location', type: 'string' }, { name: 'g', type: 'string', hidden: true }, { name: 'f', type: 'string', hidden: true },
					{ name: 'fav' }
				]),
            remoteSort: true
        });
		var pagingBar = new Ext.PagingToolbar({
            pageSize: 10,
            store: store,
            displayInfo: false,
            displayMsg: 'Results {0} - {1} of {2}',
            emptyMsg: "Please modify your Search and try again",
            items: ['-']
        });
		
		Ext.apply(this, {		   
			loadMask: true,
			store: store,
			columns: [{ header: "Click to view details", width: 'auto', sortable: true, dataIndex: 'name', renderer: this.userRender}],
            enableHdMenu: false,
			//defaults: { bodyStyle: 'padding:0px;' }
			tbar: pagingBar                        
		});

        Verisoul.UI.Data.UsersGrid.superclass.initComponent.apply(this, arguments);
		this.doLayout();
    },
	onRender: function() {
		//this.store.load();
		Verisoul.UI.Data.UsersGrid.superclass.onRender.apply(this, arguments);
	},
	userRender: function(value, p, r) {
		var s = "<table padding=\"0\" margin=\"0\"><tr><td valign=\"top\">";
		s += "<img src=\"/DesktopModules/UserSearch/ImgGen.axd?imgd=" + r.data['usrImg'] + "&ims=l&g=" + r.data['g'] + "\"/></td>";
		s += "<td valign=\"top\" align=\"left\" style=\"padding:2px;\">";
		s += "<b>" + r.data['name'] + "</b><br/>";
		s += r.data['age'] + "<br/>";
		s += r.data['location'] + "<br/>";
		s += "</td></tr></table>";
		return s;
	}
});

Verisoul.UI.Data.UserView = Ext.extend(Ext.DataView, {
    serviceUrl:'',
	pageSize:8,
	//pagingBar:'',
	storeCallback:'',
	selectedCallback:'',
	initComponent: function(){		    		
		this.store = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({ url: this.serviceUrl}),
            idProperty: 'name',
            disableCaching: true,
            reader: new Ext.data.JsonReader(
				{ root: 'data', totalProperty: 'totalRecs' },
				[
					{ name: 'name', type: 'string' },
					{ name: 'usrImg', type: 'string' },
					{ name: 'l', type: 'string' },
					{ name: 'age', type: 'string' },
					{ name: 'location', type: 'string' }, { name: 'g', type: 'string', hidden: true }, { name: 'f', type: 'string', hidden: true },
					{ name: 'fav' }
				]),
            remoteSort: true,
			baseParams:{limit:this.pageSize}
        });
		//this.pagingBar = 
					
		Ext.apply(this, {
            store: this.store,
            tpl: new Ext.XTemplate(
				'<tpl for=".">',				    
				'<div class="uimgwrap" id="{name}">',	
				'<div><img src=\"/DesktopModules/UserSearch/ImgGen.axd?imgd={usrImg}&ims=l&g={g}" /></div>',
				'<div class="Normal">',
				'<div><b>{name}</b></div>',
				'<div>{age}</div><div>{location}</div>',
				'</div>',
				'</div>',	
				'</div>',
				'</tpl>',			
				'<div class="x-clear"></div>'
            ),
            overClass: 'x-view-over',
            itemSelector: 'div.uimgwrap',
            loadMask: true
        });

        Verisoul.UI.Data.UserView.superclass.initComponent.call(this);
	},
	onClick:function(dataView, index, node, e){
		Verisoul.UI.Data.UserView.superclass.onClick.apply(this, arguments);
	    var rec = this.getRecord(this.getSelectedNodes()[0]);	
		this.selectedCallback(rec);
	},
	onRender: function() {
		Verisoul.UI.Data.UserView.superclass.onRender.apply(this, arguments);
		var lmask = new Ext.LoadMask(this.getEl(),{msg:'Refreshing users list..', store:this.store});
	    this.store.load({ start: 0, limit: this.pageSize, callback:this.storeCallback});
		this.on({'onClick':this.onClick,scope:this});			
	}
});

Verisoul.UI.Panel.UserViewPanel = Ext.extend(Ext.Panel, {
	serviceUrl:'',
	grid:'',
	initComponent: function(){	
		Verisoul.UI.Panel.UserViewPanel.superclass.initComponent.call(this);
		this.grid = new Verisoul.UI.Data.UserView({
            id: 'pfvGrid',
			serviceUrl:this.serviceUrl,            
			//autoScroll:true,
			bodyStyle:'padding:0px',
			multiSelect: false,   
			singleSelect:true,			
            border: false,
			scope:this,
			storeCallback:this.dsLoaded.createDelegate(this),
			selectedCallback:this.selectedCall.createDelegate(this),
            loadmask: true
        });	
		this.add(new Ext.PagingToolbar({
            pageSize: 8,
			width:this.width,
            store: this.grid.store,
            displayInfo: true,
            displayMsg: 'Users {0} - {1} of {2}',
            emptyMsg: "Please modify your Search and try again",
            items: ['-']
        }));
		this.add(this.grid);
		
		//this.bbar = [new Ext.Button({text:'anil'})];
	},
	onRender: function() {
		Verisoul.UI.Panel.UserViewPanel.superclass.onRender.apply(this, arguments);
	},
	addUserTab: function(rec, close) {
		var tit = rec.get('name');
		var uImg = rec.get('usrImg');            
		
		var pnl = getBlogView(tit);
		var ublg = new Ext.Panel({
			id: 'tb' + tit,
			title: GetShortString(tit),
			iconCls: 'tabs',
			height: 1200,
			width:900,
			layout: 'border',
			border: false,
			frame: false,
			autoScroll: true,
			tbar: new Verisoul.UI.Toolbar.Userbar({ logged: this.logged, title: tit, userImage: uImg, favAction: rec.get("fav"), friend: rec.get("f") }),
			closable: close,
			defaults: {
				split: false,
				animFloat: true,
				autoHide: false,
				bodyStyle: 'padding:0px'
			},
			items: [
				{
					title: '',
					id: 'inner' + tit,
					region: 'center',
					layout:'anchor',
					layoutConfig:'100% 100%',
					border: false,
					height:600,
					width:700,
					autoScroll: true,
					autoLoad: { url: usrUrl + "showDetails=" + tit + "&uImg=" + uImg, scope: this }						
				},pnl
			]
		});
		
		ublg.doLayout();
		ublg.show();
		this.profileTabs.add(ublg).show();
		Ext.getCmp('inner'+tit).doLayout();
		this.profileTabs.doLayout();
		var uoDiv = Ext.getCmp('uoDv' + tit);
		new Ext.LoadMask(uoDiv.getEl(), { msg: "Loading Comments. Please wait...", store: uoDiv.store });
		uoDiv.store.load({ params: { start: 0, limit: 25} });
	},
	selectedCall: function(rec)
	{
		var tbP = this.profileTabs.getItem('tb' + rec.get('name'));
		 if (tbP != null)
			this.profileTabs.setActiveTab(tbP);
		else
			this.addUserTab(rec, true);
	},
	getStore:function(){return this.grid;},
	dsLoaded: function(r, options, success) {
            //If there is a user id in the "uid" param, then we need to show the user in the tabs 
			var ds = this.grid.store;
            if (ds.reader != null) {
                var rdrD = ds.reader.jsonData;
                if (rdrD == null || typeof rdrD == 'undefined') return;
                l = rdrD.l;
                if (rdrD.uid != 'undefined' && rdrD.uid != null) {
                    var recId = this.grid.store.find("name", rdrD.uid);
                    if (recId < 0) {
                        Ext.Ajax.request({
                            url: '/UserList.aspx?cmd=ldusr&uid=' + rdrD.uid,
                            method: 'GET',
							scope:this,
                            success: function(resp) {
                                var recM = Ext.data.Record.create([{ name: 'name' }, { name: 'usrImg' }, { name: 'age' }, { name: 'location' }, { name: 'g' }, { name: 'fav'}]);
                                var recd = Ext.decode(resp.responseText);
                                var rec = new recM({
                                    name: recd.name,
                                    usrImg: recd.usrImg,
                                    age: recd.age,
                                    location: recd.location,
                                    g: recd.g,
                                    fav: recd.fav
                                });
                                this.addUserTab(rec, false);
                            }
                        });
                    } else {
                        var rec = this.grid.store.getAt(recId);
                        var tbP = this.profileTabs.getItem('tb' + rec.get('name'));
                        if (tbP != null){
                            this.profileTabs.setActiveTab(tbP);
						}
                        else{
							this.addUserTab(rec, false);
						}
                    }
                }
            }
    }
});

Verisoul.UI.Panel.BlogViewPanel = Ext.extend(Ext.Panel, {
	initComponent: function(){
		Verisoul.UI.Panel.BlogViewPanel.superclass.initComponent.call(this);
		this.store = new Ext.data.Store({
			id:'blogStore'+ud,
			proxy: new Ext.data.HttpProxy({
				//url: usrUrl + "cmd=lblg&uid=" + ud,
				url:this.serviceUrl,
				method: "post"
			}),
			idProperty: 'id',
			reader: new Ext.data.JsonReader({
				id: "lblgRdr",
				root: 'r',
				totalProperty: 't'
			}, [{
				name: 'n',
				type: 'string'
			}, {
				name: 'i',
				type: 'string'
			}, {
				name: 'id',
				type: 'string'
			}, {
				name: 'd',
				type: 'string'
			}, {
				name: 'c',
				type: 'string'
			}, {
				name: 'rb',
				type: 'string'
			}]),autoLoad:true
		});
		this.store.on('loadexception', function(){
			var tt = new Ext.XTemplate('<tpl for=".">', '<span class="Normal"><br/><b style="padding:10px">{t}</b></span>', '</tpl>');
			tt.overwrite(Ext.getCmp('uoDv').getEl(), {
				t: 'No Comments found. Be the first to Post a Comment.'
        });
		
    });
	},
	onRender: function() {
		Verisoul.UI.Panel.BlogViewPanel.superclass.onRender.apply(this, arguments);
		this.add(new Ext.PagingToolbar({
			pageSize: 25,
			store: this.store,
			displayInfo: true,
			width:this.width,			
			displayMsg: 'Comments {0} - {1} of {2}',
			emptyMsg: "No Comments found",
			items: ['-']
		}));
		var t = new Ext.XTemplate('<tpl for=".">', '<table style="background-color:white;width:100%;">', '<tr>', '<td style="width: 64px; height: 64px;padding-right:10px;">', '<table style="border:none;">', '<tr>', '<td valign="top" align="center" border="0">', '<img id="{id}usrImg" src="/ImgGen.axd?imgd={i}&amp;ims=m" align="top" />', '</td>', '</tr>', '</table>', '</td>', '<td valign="top" class="Normal" align="left">', '<span class="Normal" style="padding:4px 0px">Posted by <b>{n}</b> on {d}&nbsp;&nbsp;<input src="/images/icon_viewstats_16px.gif" name="{id}ReportB" type="image" id="{id}ReportB" title="Report" onclick="return {rb};" />&nbsp;&nbsp;</span>', '<div style="padding-top:2px">', '{c}', '</div>', '</td>', '</tr>', '</table>', '<hr/></tpl>');
		var dv = new Ext.DataView({
			store: this.store,
			tpl: t,
			height: this.height-32,
			id: 'uoDv'+this.user,
			border: true,		
			multiSelect: false,
			frame: true,
			itemSelector: 'ou-wrap',
			emptyText: 'No Comments found. Be the first to Post a Comment.'
		});	
		this.add(dv);		
	}
});