
var _spinWnd;
var _targObj;
function checkminage(cbAge, cbTerm){
if(Ext.get(cbAge).dom.checked && Ext.get(cbTerm).dom.checked){
Ext.get('dvRegister').show(true);
}else{
Ext.get('dvRegister').hide(true);
}
}

function showTerms(tit,url){
    var win = new Ext.Window({
        title: tit,
        layout: 'fit',
		width:700,
        height: 500,
        plain: false,
        modal: true,
		autoScroll:true,
		buttonAlign:'center',
		bodyStyle:'padding:3px',
        autoLoad:url,        
        buttons: [{
            text: 'Close',
            handler: function(){                
                win.close();
            }
        }]
    });	
    win.show();
    return false;
}

function winkUser(to,repid){

Verisoul.UI.WinkPanel.display(to,repid);
return false;
}

function showProgressWindow(title, obj){
	Ext.MessageBox.show({
	   msg: title,
	   width:450,
	   wait:true,
	   waitConfig: {interval:100, text:'Please wait..'},
	   icon:'ext-mb-download',
	   animEl: Ext.getBody().id		   
	});		
	setTimeout(function(){
		Ext.MessageBox.hide();
	}, 4000);}
function logout(obj,title,url,p){
	var cWidth = (window.screen.width) / 2;
	var cHeight = (window.screen.height) / 2;
    new Ext.data.Connection().request({
        url: "/DesktopModules/UserSearch/UserList.aspx?cmd=lout",
        scope: this,
        method: 'POST',
        params: {"p": p}
    });
	//window.open(url,title,"menubar=0,location=1,status=0,scrollbars=1,width="+cWidth+",height=" + cHeight +",resizable=0");
	window.open(url);
	Ext.get(obj).hide();
	return false;
}
function promptLogin(sTitle, sMesg){
    Ext.MessageBox.alert(sTitle, sMesg);
    return false;
}
function redirectLogin(resp)
{
	if(typeof resp != 'undefined'){
		var obj = Ext.util.JSON.decode(resp.responseText);
		if(typeof obj  != 'undefined' && typeof obj.action != 'undefined' && obj.action == 'redirect'){
		   window.location = obj.url;
		}
	}
}
function requestSuccessful(response, options){
    var object = Ext.util.JSON.decode(response.responseText);
	setTimeout(function(){
		Ext.MessageBox.hide();
	}, 500);	
}
function mngFav(favId, act){
	showProgressWindow('Updating your Favourites list...', this);
    new Ext.data.Connection().request({
        url: "/DesktopModules/UserSearch/UserList.aspx?cmd=favs",
        scope: this,
        method: 'POST',
        params: {
            "action": act,
            "fuid": favId,
            "m": null
        },
        failure: requestFailed,
        success: requestSuccessful
    });
    return false;
}
function ShowCmt(uCmt, usrId){
    var win = new Ext.Window({
        title: uCmt,
        layout: 'fit',
		width:600,
        height: 300,
        closeAction: 'hide',
        plain: false,
        modal: true,
        items: new Ext.form.TextArea({
            id: 'bio',
            fieldLabel: 'Biography',
            allowBlank: false,
            emptyText: 'Please enter a Comment',
            width: 520,
            height: 200
        }),
        
        buttons: [{
            text: 'Submit',
			iconCls:'ncomments',
            handler: function(){
                var htmlWin = Ext.getCmp('bio');
				if(htmlWin.getValue() != "" && htmlWin.initialConfig.emptyText != htmlWin.getValue()){
					showProgressWindow('Posting comments...', this);
					new Ext.data.Connection().request({
						url: "/DesktopModules/UserSearch/UserList.aspx?cmd=comment",
						scope: this,
						method: 'POST',
						params: {
							"fuid": usrId,
							"cmt": htmlWin.getValue()
						},
						failure: requestFailed,
						success: requestSuccessful
					});
					Ext.getCmp('bio').reset();
					win.hide();
				}
            }
        }, {
            text: 'Close',
			iconCls:'ncancel',
            handler: function(){
                Ext.getCmp('bio').reset();
                win.hide();
            }
        }]
    });	
    win.show();
	Ext.getCmp("bio").focus(false,10);
    return false;
}
function blkUser(t,u){
   var msg = '<p class="Normal">Blocking the user will exclude the user from all of your future Search results.<br/><br/>Also, the user will not be able to send any Private Message or post a Comment on our Profile page.<br/><br/>You can unblock the user from <b>My Verisoul--&gt;Blocked Users</b> menu';
	Ext.MessageBox.confirm(t, msg, function bUser(obj){
        if (obj == "yes") {
		   showProgressWindow(String.format('Blocking user [{0}]...',u), this);		   
           Ext.Ajax.request({
				url: "/DesktopModules/UserSearch/UserList.aspx?cmd=blku",
				scope: this,
				method: 'POST',
				params: {
					"u": u,
					"a": "B"
				},
				failure: requestFailed,
				success: requestSuccessful
           });
        }
    });	
		
	return false;
}

function addFriendRequest(frnd){
   Ext.Msg.prompt('Send a friend request to ' + frnd, 'Please enter a display name:', function(btn, text){
    if (btn == 'ok' && text != ""){
		showProgressWindow(String.format('Sending request to [{0}]...',frnd), this);
		Ext.Ajax.request({
			url: "/DesktopModules/UserSearch/UserList.aspx?cmd=addf",
			scope: this,
			method: 'GET',
			params: {
				"f":frnd,
				"d": text
			},
			failure: requestFailed,
			success: requestSuccessful
		});
    }
	});	
    return false;
}

function removeFriend(frnd){
   Ext.Msg.prompt('Are you sure ? ', function(btn, text){
    if (btn == 'ok' && text != ""){
		showProgressWindow(String.format('Removing {0} from your list...',frnd), this);
		Ext.Ajax.request({
			url: "/UserList.aspx?cmd=remf",
			scope: this,
			method: 'POST',
			params: {
				"f":frnd
			},
			failure: requestFailed,
			success: requestSuccessful
		});
    }
	});	
    return false;
}

function forwardEmail(tit, u, i){
    var bfset = new Ext.form.FieldSet({
        title: '',
        labelWidth: 125,
		height:125,
        collapsible: false,
        autoHeight: false,
        cls: 'Normal',
        bodyStyle: 'padding:3px;',
        border: false,
        defaultType: 'textfield',
        items: [{
            fieldLabel: 'Your Name',
            id: 'fn',
            allowBlank: false,
            maxLength: 45,
            width: 250
        }, {
            fieldLabel: 'Your Email',
            id: 'f',
            vtype: 'email',
            allowBlank: false,
            maxLength: 200,
            width: 250
        }, {
            fieldLabel: 'To Name',
            id: 'tn',
            allowBlank: false,
            maxLength: 45,
            width: 250
        }, {
            fieldLabel: 'To Email',
            id: 't',
            vtype: 'email',
            allowBlank: false,
            maxLength: 200,
            width: 250
        }]
    });
    
    var win = new Ext.Window({
        title: tit,
        cls: 'Normal',
        width: 525,
        height: 350,
        closeAction: 'hide',
        plain: false,
        modal: true,
        items: [bfset, new Ext.form.TextArea({
            emptyText: 'Type a brief message',
            id: 'm',
            width: 515,
            allowBlank: false,
            maxLength: 200,
            height: 150
        })],
        buttons: [{
            text: 'Send',
			iconCls:'nforward',
            handler: function(){
                var htmlWin = Ext.getCmp('m');
                if (htmlWin.getValue() != "" && htmlWin.getValue() != htmlWin.initialConfig.emptyText && Verisoul.Util.isValid('tn') && Verisoul.Util.isValid('t')
				&& Verisoul.Util.isValid('fn') && Verisoul.Util.isValid('f')) {
					showProgressWindow('Forwarding profile to ' + Ext.get("t").getValue() +'...', this);				
                    Ext.Ajax.request({
                        url: "/DesktopModules/UserSearch/UserList.aspx?cmd=fwd",
                        scope: this,
                        method: 'GET',
                        params: {
                            "i": i,
                            "u": u,
                            "m": htmlWin.getValue(),
                            "fn": Ext.get("fn").getValue(),
                            "f": Ext.get("f").getValue(),
                            "t": Ext.get("t").getValue(),
                            "tn": Ext.get("tn").getValue()
                        },
                        failure: requestFailed,
                        success: requestSuccessful
                    });
                    Ext.getCmp('m').reset();
                    win.destroy();
                }else{
				Ext.MessageBox.alert('Forward Profile', 'Please enter values for all fields and try again');
				}
            }
        }, {
            text: 'Close',
			iconCls:'ncancel',
            handler: function(){
                Ext.getCmp('m').reset();
                win.destroy();
            }
        }]
    });
    win.show();
	Ext.getCmp("fn").focus(false,10);
    return false;
}
function reportUser(t, u, a){
	var win = new Ext.Window({
		title: t,
		layout: 'fit',
		width: 525,
		height: 300,
		closeAction: 'hide',
		plain: false,
		modal: true,
		items: new Ext.form.TextArea({
			id: 'report',
			width: 520,
			allowBlank: false,
			emptyText:'Please describe briefly the reason for reporting user',
			maxLength: 200,
			height: 150
		}),                
		buttons: [{
			text: 'Report',iconCls:'nreport',
			handler: function(){
				var htmlWin = Ext.getCmp('report');
				if (htmlWin.getValue() != "" && htmlWin.initialConfig.emptyText != htmlWin.getValue()) {
					showProgressWindow(String.format('Reporting user [{0}]...',u), this);
					Ext.Ajax.request({
						url: "/DesktopModules/UserSearch/UserList.aspx?cmd=rptu",
						scope: this,
						method: 'POST',
						params: {
							"u": u,
							"c": htmlWin.getValue(),
							"a": a
						},
						failure: requestFailed,
						success: requestSuccessful
					});
					Ext.getCmp('report').reset();
					win.hide();
				}
			}
		}, {
			text: 'Close',iconCls:'ncancel',
			handler: function(){
				Ext.getCmp('report').reset();
				win.hide();
			}
		}]
	});
	win.show();
	Ext.getCmp("report").focus(false,10);
    return false;
}
function GetShortString(str){
 if(str.length > 10)
  return str.substring(0,10) + "..";
  else 
  return str;
}
//Invite Google Contacts
function ShowGmailLogin() {
    var width = 650;
    var height = 600;
    var cWidth = (window.screen.width - width) / 2;
    var cHeight = (window.screen.height - height) / 2;
    var s = new VerisoulJS();
    var lUrl = s.getGConsent();
    window.location = lUrl;
    return false;
}
//Invite Live Contacts
function ShowLiveLogin() {
    var width = 650;
    var height = 600;
    var cWidth = (window.screen.width - width) / 2;
    var cHeight = (window.screen.height - height) / 2;

    var s = new VerisoulJS();
    var lUrl = s.getLiveConsent();
	window.location=lUrl;
    return false;
}
//Invite Yahoo Contacts
function ShowYLogin() {
    var width = 650;
    var height = 600;
    var cWidth = (window.screen.width - width) / 2;
    var cHeight = (window.screen.height - height) / 2;

    var s = new VerisoulJS();
    var lUrl = s.getYConsent();
	window.location=lUrl;
    return false;
}
function SelectAll() {
	var coll = document.getElementsByTagName("img");
	for (el = 0; el < coll.length; el++) {
		if (coll[el].name == "cbImage") {
			coll[el].src = "/images/checked.gif";
		}
	}	
	changeInviteClass(true);
	return false;
}
function ClearAll() {
	var coll = document.getElementsByTagName("img");
	for (el = 0; el < coll.length; el++) {
		if (coll[el].name == "cbImage") {
			coll[el].src = "/images/unchecked.gif";
		}
	}
	changeInviteClass(false);
	return false;
}
function changeInviteClass(sel){
	var elem = Ext.DomQuery.selectNode("table[className=inviteList]");
	if(elem != null)
	{
		coll = Ext.DomQuery.select("td", elem);
		for (el = 0; el < coll.length; el++) {
		    if (sel)
			{
				if(coll[el].className == "rowstyle")
					coll[el].className = "selrowstyle";	
			}
			else
			{
				if(coll[el].className == "selrowstyle")
					coll[el].className = "rowstyle";	
			}
		}
	}
	//inviterow
}

function SelectContact(el, hd, elref) {
	if (el.src.indexOf("images/checked.gif") >= 0) {
		el.src = el.src.replace("images/checked.gif", "images/unchecked.gif");
		document.getElementById(hd).value = "0";
		elref.parentNode.parentNode.parentNode.parentNode.parentNode.className = "rowstyle";
	}
	else {
		el.src = el.src.replace("images/unchecked.gif", "images/checked.gif");
		document.getElementById(hd).value = "1";
		elref.parentNode.parentNode.parentNode.parentNode.parentNode.className = "selrowstyle";
	}
}
function inviteVerisoul(){
	var tr = Ext.DomQuery.select("tr[class=invrowget]");

	var tbEmail = Ext.DomQuery.selectNode("input[class*=extecon]");
	if(tbEmail.value == "" || tbEmail.value.indexOf("@") <= 0 ) return false;
	
	var tbName = Ext.DomQuery.selectNode("input[class*=extncon]");
	if(tbName.value == "" ) return false;
	
	var carr = new Array();		
	Ext.each(tr,function(item,index,allItems){  
	  var imgn = Ext.DomQuery.selectNode("img[name=cbImage]", item);
	  if(imgn.src.indexOf("images/checked.gif") >= 0)
	  {
		var lblT = Ext.DomQuery.selectNode("span[name=lblTitle]", item);
		var lblE = Ext.DomQuery.selectNode("span[name=lblEmail]", item);
		var cc = {n:lblT.innerHTML,e:lblE.innerHTML};
		carr.push(cc);
	  }
	});

	var jstr = {f:tbName.value, em:tbEmail.value, cm:Ext.getCmp('txtInvMesg').getValue(), c:carr};
	
	showProgressWindow('Sending Invitations..', this);
	var s = new VerisoulJS();	
	s.inviteFriends(JSON.stringify(jstr),function(resp){
		var object = Ext.util.JSON.decode(resp.result);
		Ext.MessageBox.hide();		
		if (!object.success){
			Ext.MessageBox.show({
				title: object.title,
				msg: object.message,
				buttons: Ext.MessageBox.OK,
				icon: Ext.MessageBox.ERROR
			});
		}
	});
	return false;
}

function quickTour(){
    var ds = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url: "/DesktopModules/UserSearch/UserList.aspx?cmd=qt", method: "get", params: { "qtt": "d"}
		}),
		idProperty: 'm',
		reader: new Ext.data.JsonReader(
		{ id: "qtRdr", root: 'r', totalProperty: 't' },
		[
			{ name: 'm', type: 'string'},
			{ name: 'i', type: 'string'}
		])
	});
	
	ds.on({
		'loadexception': {
			fn: function(httpProxy, dataObject, arguments, exception) {
				Ext.MessageBox.alert("Load Error", String.format("Eeww..({0}) - {1}", arguments.status, arguments.statusText));
			}
		, scope: this
		},
		'load': {
			fn: function(str, options) {							
				var border = {
					id:'border-panel',
					title: '',
				    layout:'border',
				    bodyBorder: false,
					border:false,
					plain:true,
					defaults: {
						collapsible: true,
				        split: true,
						animFloat: false,
						autoHide: false,
						useSplitTips: true,
						bodyStyle: 'padding:15px'
					},
				    items: [{
				        region:'west',
						floatable: false,
						cmargins: '5 5 0 0',
				        width: 175,
				        minSize: 100,
				        maxSize: 250,			
						html: '<p>Secondary content like navigation links could go here</p>'
					},{			
						collapsible: false,
				        region:'center',
						autoLoad:ds.getAt(0).r.i,
						buttons:[new Ext.Button({id:'qtPrev',text:'Previous', hidden:true}), new Ext.Button({text:'Next', handler:function(){Ext.getCmp('qtPrev').show();}})]
					}]
				};
				var bd = Ext.getBody();
				var win = new Ext.Window({	
					layout      : 'fit',
					title: 'Verisoul.com Quick tour',
					width       : bd.dom.clientWidth * 0.7,
					height      : bd.dom.clientHeight * 0.7,
					closeAction :'hide',	
					plain       : true,
					items:border,
					modal:true
				});
				win.show();
				return false;
			}
		}
	});
}

String.prototype.ellipse = function(maxLength){
    if(this.length > maxLength){
        return this.substr(0, maxLength-3) + '...';
    }
    return this;
};

function requestFailed(response, options) {
	// The request to the server was unsuccessful.
	Ext.MessageBox.hide();
	Ext.MessageBox.show({
		title: 'Error Message',
		msg: "Please contact support with the following: " + "Status: " + response.status + ", Status Text: " + response.statusText,
		buttons: Ext.MessageBox.OK,
		icon: Ext.MessageBox.ERROR
	});	
}

//get saved search
function showSavedSearch(tab){
	var dsSaved = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({ url: '/DesktopModules/UserSearch/UserList.aspx?cmd=svdSrch', method: "get" }),
		idProperty: 'i',
		id:'dsSaved',
		reader: new Ext.data.JsonReader({ id: "sschRdr", root: 'r', totalProperty: 'tr' },
	[{ name: 't', type: 'string' },
		{ name: 'i', type: 'string', hidden: false },
		{ name: 'c', type: 'string' }
	]),
		remoteSort: true,
		autoLoad:false
	});

	var s = new Ext.Action({
	    text: 'Show Results',
		tooltip: 'Click to display matching Search results for the filter',
	    handler: function() {
	        var rec = Ext.getCmp("gdSaved").getSelectionModel().getSelected();
	        if (rec != null) showSearchResults(rec.get("i"));
	    },
	    disabled: true,
	    id: 'gtbS',
	    iconCls: 'ssch'
	});

	var v = new Ext.Action({
		text: 'View Filter',
		tooltip:'Click to view the filter',
		handler: function() {
			var rec = Ext.getCmp("gdSaved").getSelectionModel().getSelected();			
			if (rec != null) showSearch(rec.get("t"), rec.get("i"));
		},
		disabled:true,id:'gtbV',
		iconCls: 'svw'
	});

	var d = new Ext.Action({
		text: 'Delete',
		tooltip:'Click to Delete the Search filter',
		handler: function() {
		    var rec = Ext.getCmp("gdSaved").getSelectionModel().getSelected();			
			if (rec != null)
			{
				Ext.MessageBox.confirm('Delete Filter - ' + rec.get("t"), 'Are you sure you want to Delete ?', 
				function delRec()
				{
					new Ext.data.Connection().request({
                        url: "/DesktopModules/UserSearch/UserList.aspx?cmd=svdSrch",
                        scope: this,
                        method: 'POST',
                        params: {"dsid": rec.get("i")},
						failure: requestFailed,
						success: function(){						    
							Ext.getCmp("gdSaved").getStore().reload();
							Ext.getCmp("gtbS").disable();
							Ext.getCmp("gtbV").disable();
							Ext.getCmp("gtbD").disable();
						}
                    });
				});
			}
			
		},
		disabled:true,id:'gtbD',
		iconCls: 'sdel'
	});
			
	var pb = new Ext.PagingToolbar({
		pageSize: 10,
		store: dsSaved,
		displayInfo: false,
		displayMsg: 'Results {0} - {1} of {2}',
		emptyMsg: "No saved Search filters found",
		items:['-']
	});

	var grid = new Ext.grid.GridPanel({
		id:'gdSaved',
		ds: dsSaved,
		columns: [
		{ header: "Search Name", width: 350, sortable: true, dataIndex: 't' },
		{ header: "Created", width:125, sortable: true, dataIndex: 'c'}],
		height: 250,
		cls:'spanel',
		sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
		enableHdMenu: false,
		border:true,
		loadMask: true,
		bbar: pb,
		tbar:[s,v,d]
	});
	
	grid.on('rowclick', function(grid, rowIndex, e) {
		var rec = grid.store.getAt(rowIndex);
		Ext.getCmp("gtbS").enable();
		Ext.getCmp("gtbV").enable();
		Ext.getCmp("gtbD").enable();
	});
	tab.add(grid);
	tab.doLayout();	
	dsSaved.load({ start: 0, limit: 10});	
}

function showSearch(sHead, srchId) {
	var win = new Ext.Window({
		title: sHead,
		layout: 'fit',
		width: 525,
		height: 300,
		closeAction: 'hide',
		plain: true,
		modal: true,
		autoLoad: { url: '/DesktopModules/UserSearch/UserList.aspx?cmd=showSrch', scope: this, params: { "sId": srchId} },
		buttons: [{
			text: 'Close',
			handler: function() {
				win.hide();
			} }]
		});
		win.show();
		return false;
}
function sendPrivateMessage(to,sub,mesg,tnb){
	var ds = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url: '/DesktopModules/UserSearch/UserList.aspx?cmd=gusr',method: "post", params: { "u": ''}
		}),
		reader: new Ext.data.JsonReader({
			root: 'r',	
			totalProperty: 't',			
			id: 'i'
		}, [
			{name: 'f'},
			{name: 'd'},
			{name: 'l'},
			{name: 'i', hidden:true}
		]),
		autoLoad:false
	});

	ds.on({		
		'beforeload': {
			fn: function(str, options) {			   
				options.params.u = Ext.get('toc').dom.value;
			}
		}
	});
	
	// Custom rendering Template
	var resultTpl = new Ext.XTemplate(
		'<tpl for="."><div class="search-item">',
		    '<table><tr><td class="Normal" style="font-weight:bold;line-height:20px;width:150px;">{d}</td><td class="Normal">{l} {f}</td></tr></table>',
		'</div></tpl>'
	);
	
	var val;
	var form = new Ext.form.FieldSet({
		title: '',
		labelWidth: 55,
		defaultType: 'textfield',
		border: false,
		items: [{
			fieldLabel: 'Send To',
			name: 'toc',
			id:'toc',
			displayField:'d',
			valueField:'d',
			allowBlank:false,
			pageSize: 10,
			mode: 'remote',
			itemSelector: 'div.search-item',
			anchor:'95%',
			height:20,			
			store:ds,
			tpl: resultTpl,
			xtype:'combo',
			forceSelection:true,
			minChars: 2,
			hideTrigger:true,
			selectOnFocus: false
		},{
			fieldLabel: 'Subject',
			name: 'subject',
			id:'subject',
			allowBlank:false,
			anchor: '95%'
		}, {
			xtype: 'htmleditor',
			hideLabel: true,
			id:'msg',
			autoScroll:true,
			emptyText: 'Type a brief message',
			enableSourceEdit:false,enableLinks:false,
			allowBlank:false,
			name: 'msg',
			anchor: '100% -75'
		}]
	});    
	
	if(!tnb) Ext.getCmp('toc').disable();
	
	if (to != "") Ext.getCmp("toc").setValue(to);
	if (sub != "") Ext.getCmp("subject").setValue(sub);
	if (mesg != "") Ext.getCmp("msg").setValue(mesg);
	
	var window = new Ext.Window({
		title: 'Send a Private Message',
		width: 550,
		height:300,
		modal:true,
		minWidth: 300,
		minHeight: 200,
		layout: 'fit',
		plain:true,
		bodyStyle:'padding:2px;',
		//buttonAlign:'center',
		items: form,
		buttons: [{
			text: 'Send',
			iconCls:'nforward',
			autoWidth:true,
			handler:function(){
                var htmlWin = Ext.get('msg');
				var to = Ext.getCmp("toc");
                if (htmlWin.getValue() != "" && to.getValue() != "") {
					showProgressWindow('Sending Private message...', this);				
                    Ext.Ajax.request({
                        url: '/DesktopModules/UserSearch/UserList.aspx?cmd=spm',
                        scope: this,
                        method: 'POST',
                        params: {
                            "m": htmlWin.getValue(),
                            "s": Ext.get("subject").getValue(),
                            "t": Ext.get("toc").getValue()
                        },
						failure: requestFailed,
						success: requestSuccessful						
                    });
                    Ext.getCmp('msg').reset();
                    window.destroy();
                }			
			}
		},{
			text: 'Cancel',
			iconCls:'ncancel',
			handler:function(){window.destroy();}
		}]
	});
	window.show();
	if(tnb) Ext.getCmp("toc").focus(false,10);	
	else Ext.getCmp("subject").focus(false,10);
	return false;
}

function loadInbox(){
 var tb = [
	{
		text:'Refresh',
		iconCls:'add',
		xtype:'button'
	},{
        id:'rmChatUser',
		text:'Remove',
		xtype:'button',
		disabled:true,
		iconCls:'remove',
        handler: function(){
            Ext.Msg.alert('Message', 'The Settings tool was clicked.');
        }}
    ];
	
	var json = [
	{"text" : "Inbox","width":"100", "id" : "100000", "leaf" : true, "cls" : "file", "t":"inb"},
	{"text" : "Sent Items","width":"100", "id" : "100001", "leaf" : true, "cls" : "file", "t":"si"}
	];

	var tree = new Ext.tree.TreePanel({
        useArrows:true,
		title:'Private Messages',
		id:'inboxtree',
        autoScroll:true,
		border:true,
		width:150,
		height:600,
        animate:true,
		plain:false,
		region:'west',
        containerScroll: true,
		rootVisible:false,

        root: {
            nodeType: 'async',
            text: 'My Buddies',
			width:300,
            draggable:false,
            id:'source',
			children:json
        },
		listeners:{
			click: { fn: function(node, obj) {
				var profileTabs = Ext.getCmp('inboxtabPanel');
				var tbP;
				if(node.attributes.t == "inb"){
					tbP = profileTabs.getItem("favGrid");
					profileTabs.getItem("favGrid").getStore().reload();
					tbP.show();
				}
				else if(node.attributes.t == "si"){
					tbP = profileTabs.getItem("sentitems");

					if (tbP == null)			
					{
						var ds1 = new Ext.data.Store({
								proxy: new Ext.data.HttpProxy({ url:"/DesktopModules/UserSearch/UserList.aspx?cmd=loadsi", method: "post"}),
								idProperty: 'i',
								disableCaching: true,
								baseParams:{"dm":"0"},
								reader: new Ext.data.JsonReader(
							{ id: "srchRdr", root: 'r', totalProperty: 't' },
							[{ name: 'f'},{ name: 's'},{ name: 'd'},{ name:'i', hidden:true},{ name:'m', hidden:true},{name:'n', hidden:true},{name:'b',hidden:true}]),
								remoteSort: true
							});
						
						var pagingBar1 = new Verisoul.UI.Toolbar.InboxGridPagingBar({
							pageSize: 20,
							store: ds1,
							grid:'sentitems',
							ibmode:'si',
							displayInfo: true,
							displayMsg: 'Messages {0} - {1} of {2}',
							emptyMsg: "No Messages"
						});
							
						// create grid
						var sm1 = new Ext.grid.CheckboxSelectionModel();
						tbP = new Ext.grid.GridPanel({
							ds: ds1,
							sm:sm1,
							colModel: new Ext.grid.ColumnModel({columns:[
								{ header: "To", width: 175, sortable: true, dataIndex: 'f', renderer: function (value,p,r){
								  if(r.data.n == '0') return '<span style="font-weight:bold">'+value+'</span>';
								  else return value;			   
								}},
								{ header: "Subject", width: 350, sortable: true, dataIndex: 's'},
								
								{ header: "Sent", width: 200, sortable: true, dataIndex: 'd'}
							]}),
							width: 800,
							height: 500,
							enableHdMenu: false,							
							closable:true,
							loadMask:true,
							id:'sentitems',
							title:'Sent Messages',
							tbar: pagingBar1
						});
						
						ds1.load();
						profileTabs.add(tbP).show();	
						//Add event handlers for Grid
						tbP.on('rowdblclick', function(grid, rowIndex, e) {
							var rec = grid.store.getAt(rowIndex);
							var profileTabs = Ext.getCmp('inboxtabPanel');
							var tbPSI = profileTabs.getItem(rec.get('i') +'-' +rec.get('m'));

							if (tbPSI == null)			
							{
							    var dbled = false;
								var ftip;
								var rtip;
								if(rec.get('b')== "1"){
									dbled = true;
									ftip = rec.get("f") + ' is currently not open for Private Messaging';
									rtip = rec.get("f") + ' is currently not open for Private Messaging';
								}
								else
								{
									ftip = 'Forward this message';
									rtip = 'Reply to ' + rec.get("f");
								}
								
								var fwd = new Ext.Action({
									text: 'Forward',
									scope: this,
									tooltip:ftip,
									disabled:dbled,
									id: 'actnFwd' + rec.get('i'),
									params: { "s": "Fw: " + rec.get('s'), "pnl": rec.get('i') +'-' +rec.get('m')},
									handler: function(obj) {  
										var pnl = Ext.getCmp(obj.params.pnl);
										var bdy = pnl.body.dom.innerHTML.replace("pmHead","Normal");
										bdy = bdy.replace("pmBody","Normal");
										sendPrivateMessage('',obj.params.s,'<br/><br/><hr/><div class="Normal">'+bdy+'</div>',true);
									},
									iconCls: 'forwardMsg'
									});
								
								var rep = new Ext.Action({
									text: 'Reply',
									scope: this,
									tooltip:rtip,
									disabled:dbled,									
									id: 'actnReply' + rec.get('i'),
									params: { "s": "Re: " + rec.get('s'), "pnl": rec.get('i') +'-' +rec.get('m'), "f":rec.get("f")},
									handler: function(obj) {  
										var pnl = Ext.getCmp(obj.params.pnl);
										var bdy = pnl.body.dom.innerHTML.replace("pmHead","Normal");
										bdy = bdy.replace("pmBody","Normal");
										sendPrivateMessage(obj.params.f,obj.params.s,'<br/><br/><hr/><div class="Normal">'+bdy+'</div>',true);
									},
									iconCls: 'replyMsg'
									});

								tbPSI = new Ext.Panel({
									id:rec.get('i') +'-' +rec.get('m'),
									title:rec.get('s'),
									autoLoad:{url:'/DesktopModules/UserSearch/UserList.aspx?cmd=gpm',params:{"m":rec.get('m'), "u":rec.get('i')}, method:'post'},
									layout:'fit',
									tbar:[fwd,'-',rep],
									autoScroll:true,
									closable:true
								});
								profileTabs.add(tbPSI);			
							}
							profileTabs.setActiveTab(tbPSI);		
						});	
	
					}
					else
					{
						profileTabs.getItem("sentitems").getStore().reload();
					}
					profileTabs.setActiveTab(tbP);		
				}
            }}
		}
    });
	
	var tabPanel = new Ext.TabPanel({
		resizeTabs: true, // turn on tab resizing
		minTabWidth: 115,
		id:'inboxtabPanel',
		activeTab: 0,
		enableTabScroll: true,
		width:650,
		height:600,
		region:'center',
		bodyBorder: false,
		floatable: false,
		defaults: { autoScroll: true,bodyStyle: 'padding:0px' }
	});
	
	var ds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({ url:"/DesktopModules/UserSearch/UserList.aspx?cmd=loadInb", method: "post"}),
            idProperty: 'i',
			disableCaching :true,autoLoad:true,
			baseParams:{"i":"0",limit:20},
            reader: new Ext.data.JsonReader(
		{ id: "srchRdr", root: 'r', totalProperty: 't' },
		[{ name: 'f'},{ name: 's'},{ name: 'd'},{ name:'i', hidden:true},{ name:'m', hidden:true},{name:'n', hidden:true},{name:'b',hidden:true}]),
            remoteSort: true
        });
    
	var pagingBar = new Verisoul.UI.Toolbar.InboxGridPagingBar({
		pageSize: 20,
		store: ds,
		displayInfo: true,
		grid:'favGrid',
		ibmode:'ib',
		displayMsg: 'Messages {0} - {1} of {2}',
		emptyMsg: "No Messages"
	});
		
	// create grid
	var sm = new Ext.grid.CheckboxSelectionModel();
	var grid = new Ext.grid.GridPanel({
		ds: ds,
		sm:sm,
		colModel: new Ext.grid.ColumnModel({columns:[
            
			{ header: "From", width: 175, sortable: true, dataIndex: 'f', renderer: function (value,p,r){
			  if(r.data.n == '0') return '<span style="font-weight:bold">'+value+'</span>';
			  else return value;			   
			}},
			{ header: "Subject", width: 350, sortable: true, dataIndex: 's'},
			
			{ header: "Sent", width: 200, sortable: true, dataIndex: 'd'}
        ]}),
		width: 800,
		height: 500,
		enableHdMenu: false,
		//layout:'fit',
		loadMask:true,
		id:'favGrid',
		title:'Inbox',
		tbar: pagingBar
	});

	var inbPanel = new Ext.Panel({
		layout:'border',
		renderTo:'inbox',
		height:500,
		width:1000,
		defaults: {
			split: false,
			bodyStyle: 'padding:0px;'
		},
		items:[tree,tabPanel]
	});
	
	tabPanel.add(grid).show();
	tabPanel.doLayout();
	inbPanel.doLayout();
	//ds.load();
	
	//Add event handlers for Grid
	grid.on('rowdblclick', function(grid, rowIndex, e) {
		var rec = grid.store.getAt(rowIndex);
		var profileTabs = Ext.getCmp('inboxtabPanel');
		var tbP = profileTabs.getItem(rec.get('i') +'-' +rec.get('m'));

		if (tbP == null)			
		{
			var dbled = false;
			var ftip;
			var rtip;
			if(rec.get('b')== "1"){
				dbled = true;
				ftip = rec.get("f") + ' is currently not open for Private Messaging';
				rtip = rec.get("f") + ' is currently not open for Private Messaging';
			}
			else
			{
				ftip = 'Forward this message';
				rtip = 'Reply to ' + rec.get("f");
			}
		    var fwd = new Ext.Action({
                text: 'Forward',
                scope: this,
				tooltip:ftip,disabled:dbled,
                id: 'actnFwd' + rec.get('i'),
                params: { "s": "Fw: " + rec.get('s'), "pnl": rec.get('i') +'-' +rec.get('m')},
                handler: function(obj) {  
                    var pnl = Ext.getCmp(obj.params.pnl);
					var bdy = pnl.body.dom.innerHTML.replace("pmHead","Normal");
					bdy = bdy.replace("pmBody","Normal");
                    sendPrivateMessage('',obj.params.s,'<br/><br/><hr/><div class="Normal">'+bdy+'</div>',true);
                },
                iconCls: 'forwardMsg'
				});
			
			var rep = new Ext.Action({
                text: 'Reply',
                scope: this,
                id: 'actnReply' + rec.get('i'),
				tooltip:rtip,disabled:dbled,
                params: { "s": "Re: " + rec.get('s'), "pnl": rec.get('i') +'-' +rec.get('m'), "f":rec.get("f")},
                handler: function(obj) {  
                    var pnl = Ext.getCmp(obj.params.pnl);
					var bdy = pnl.body.dom.innerHTML.replace("pmHead","Normal");
					bdy = bdy.replace("pmBody","Normal");
                    sendPrivateMessage(obj.params.f,obj.params.s,'<br/><br/><hr/><div class="Normal">'+bdy+'</div>',true);
                },
                iconCls: 'replyMsg'
				});
				
		    tbP = new Ext.Panel({
			    id:rec.get('i') +'-' +rec.get('m'),
			    title:rec.get('s'),
				autoLoad:{url:'/DesktopModules/UserSearch/UserList.aspx?cmd=gpm',params:{"m":rec.get('m'), "u":rec.get('i')}, method:'post'},
				layout:'fit',
				tbar:[fwd,'-',rep],
				autoScroll:true,
				closable:true
			});
			
			profileTabs.add(tbP);			
		}
		profileTabs.setActiveTab(tbP);		
	});		
	
	
}

function loadBlockedUsers(){
	var ds = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({ url:"/DesktopModules/UserSearch/UserList.aspx?cmd=bu"}),
		idProperty: 'n',
		reader: new Ext.data.JsonReader(
			{ id: "srchRdr", root: 'r', totalProperty: 't' },
			[{ name: 'n', type: 'string' },
			 { name: 'u', type: 'string' },
			 { name: 'd', type: 'string' }
			]),
		remoteSort: true
	});
	
	var pbar = new Ext.PagingToolbar({
            pageSize: 10,
            store: ds,
            displayInfo: false,
            displayMsg: 'Results {0} - {1} of {2}',
            emptyMsg: "No users found",
            items: [
            '-']
        });
	ds.load({ start: 0, limit: 10});	
	var sm = new Ext.grid.CheckboxSelectionModel();
	var grid = new Ext.grid.GridPanel({
		id:'button-grid',
		store: ds,
		cm: new Ext.grid.ColumnModel([
			sm,
			{id:'n',header: "User Name", width: 150, sortable: true, dataIndex: 'n'},{dataIndex:'u',hidden:true},
			{header: "Date Blocked", width: 150, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'd'}
		]),
		sm: sm,
		viewConfig: {
			forceFit:true
		},
		bbar:pbar,
		tbar:[{xtype:'label',
				text:'Enter a User name '
		},
		{
				xtype:'textfield',
				id:'usr'
			},	{
				text:'Block',
				tooltip:'Block the typed User',
				iconCls:'remove'
			}, '-',{
				text:'Unblock',
				tooltip:'Unblock the selected User',
				iconCls:'add',
				handler:function(){
				    var gr = Ext.getCmp('button-grid');
					var rows = gr.getSelectionModel().getSelections();
					if(rows == null || typeof rows == 'undefined' || rows.length == 0) return;
					
					var p = "";
					for(var i=0; i<rows.length; i++)
					{					
						if (p == "") p = rows[i].data.u;
						else p += "," + rows[i].data.u;
					}
					
					Ext.Ajax.request({
		                url: "/DesktopModules/UserSearch/UserList.aspx?cmd=ublk",
		                method: 'GET', scope: this, params: { "p": p },
						failure:function(){
						Ext.getCmp('button-grid').getStore().removeAll();
						Ext.getCmp('button-grid').getStore().reload();
						},
		                success: function(r, o) {
							Ext.getCmp('button-grid').getStore().removeAll();
		                    Ext.getCmp('button-grid').getStore().reload();
		                }
					});
				}
			}, '-',{
				text:'Unblock All',
				tooltip:'Unblock all the Users',
				iconCls:'add',
				handler:function(){					
					Ext.Ajax.request({
		                url: "/DesktopModules/UserSearch/UserList.aspx?cmd=ublk",
		                method: 'GET', scope: this, params: { "p": -1 },
		                success: function(r, o) {
		                    Ext.getCmp('button-grid').getStore().reload();
		                }
					});
				}
			}],
		width:600,
		height:300,
		frame:true,
		title:'List of Blocked Users',
		iconCls:'icon-grid',
		renderTo: 'bu',
		emptyText:'No Users found'
	});
}

function loadOnlineUsers(){	
	var ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/DesktopModules/UserSearch/UserList.aspx?cmd=gonl',method:'GET'
        }),
        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'},{name:'im'},{name:'wn'}])
    });		
	
	var s = new VerisoulJS();
	var locData = s.getLocaleData("2");
	locData = Ext.decode(locData);
	
	ds.on('loadexception',function(){
			var d = Ext.get('online');
			d.dom.innerHTML='<p style="font-size:x-small">' + locData.NoOnline + '</p>';
		});
	
	//ds.on('load', function(){	
	var pb = new Ext.PagingToolbar({
		pageSize: 25,
		store: ds,
		displayInfo: true,
		displayMsg: locData.Paging,			
		items: [
		'-']
	});
	
	var t = new Ext.XTemplate('<tpl for=".">',				    
		'<div style="width:220px;float:left;"><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 colspan="2">',
				'<table style="width: 100%;padding:2px;">',
					'<tr>',
						'<td style="border-bottom:1px dotted #000;text-align:center;" colspan="2">',
							'<span class="Normal" style="font-weight:bold;">{n}</span>',
						'</td>',
					'</tr>',
				'</table>',
			'</td>',
		'</tr>',
		'<tr>',
			'<td style="width: 100px; height: 100px;" valign="top" align="center">',
				'<img id="{id}usrImg" src="/ImgGen.axd?imgd={img}&amp;ims=m" align="top" style="border-width:0px;" />',
			'</td>',
			'<td valign="top" class="Normal" style="width: 175px">',
				'<div>',
					'<span class="olbl">',locData.Name,'</span>',
					'<span>{n}</span>',
				'</div>',
				'<div>',
					'<span class="olbl">',locData.GenderA,'</span>',
					'<span>{a}</span>',					
				'</div>',
				'<div>',
					'<span class="olbl">',locData.Location,'</span>',
					'<span>{l}</span>',
				'</div>',
				'<div>',
					'<br/><a id="{id}User" class="verilink" href="/public/{n}">',locData.ViewDetails,'</a>',
				'</div>',
			'</td>',
		'</tr>',
		'<tr>',
			'<td colspan="2">',
				'<input style="padding:0px 1px;" src="/images/wink.gif" name="{id}lnkWink" type="image" id="{id}lnkWink" title="Send a Wink to {n}" onclick="return {wn};" />&nbsp;&nbsp;',							
				'<input style="padding:0px 1px;" src="/images/user_add.gif" name="{id}lnkFrnd" type="image" id="{id}lnkFrnd" title="Add/Remove {n} as your friend" onclick="return {im};" />&nbsp;&nbsp;',				
				'<input style="padding:0px 1px;" src="/images/icon_hostusers_16px.gif" name="{id}lnkPm" type="image" id="{id}lnkPm" title="Send 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>'
	);
		
	var dv = new Ext.DataView({
		store: ds,
		tpl: t,
		height:550,
		id:'uoDv',
		border:true,
		multiSelect: false,
		bodyStyle:'padding:0px',
		frame:true,
		overClass: 'x-view-over',
		itemSelector: 'div.ou-wrap',
		emptyText: 'No Users Online'		
	});
	
	var panel = new Ext.Panel({
		id:'images-view',
		frame:true,
		plain:true,
		border:true,
		autoWidth:true,height:400,		
		collapsible:false,
		bodyStyle:'padding:0px',
		renderTo:'dnn_ContentPane',
		title:'',
		items:[dv],
		tbar:pb
	});
	new Ext.LoadMask(dv.getEl(), {msg:"Please wait...", store:ds});		
	ds.load();
}

function loadImageGrid(elem, targ){
	var ds = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url: '/DesktopModules/UserSearch/UserList.aspx?cmd=imgGrid',method:'GET'
		}),
		
		reader: new Ext.data.JsonReader({
			totalProperty: 't',
			root: 'r'
		}, [{name: 'i'}, {name:'f'},{name:'d'},{name:'s'}]),
		autoLoad: false
	});	
	
	
	var pb = new Ext.PagingToolbar({
		pageSize: 10,
		store: ds,
		displayInfo: false,
		displayMsg: 'Results {0} - {1} of {2}',
		emptyMsg: "No Images in your profile",
		items:['-',{xtype:'button', disabled:true, id:'imgDfltBtn', text:'Set as Default', iconCls:'defimg',handler:function(obj){		
			var gr = Ext.getCmp('usrImagesGrid');
			var row = gr.getSelectionModel().getSelected();
			if(row == null || typeof row == 'undefined') return;		
			showProgressWindow('Setting Default image..', this);
			Ext.Ajax.request({
				url: "/DesktopModules/UserSearch/UserList.aspx?cmd=sdimg",
				method: 'GET', scope: this, params: { "p": row.data.i},
				failure:function(){
					setTimeout(function(){Ext.MessageBox.hide();}, 1000);
					Ext.getCmp('usrImagesGrid').getStore().removeAll();
					Ext.getCmp('usrImagesGrid').getStore().reload();				
				},
				success: function(r, o) {
					setTimeout(function(){Ext.MessageBox.hide();}, 1000);				
					Ext.getCmp('usrImagesGrid').getStore().removeAll();
					Ext.getCmp('usrImagesGrid').getStore().reload();
				}
			});		
		}},'-',
		{xtype:'button', disabled:true, id:'imgDelBtn', text:'Delete', iconCls:'delrec',handler:function(obj){
            Ext.MessageBox.confirm('Delete Image', 'Are you sure you want to delete the Image? <br/>Once deleted, image cannot be recovered', function bUser(obj){
				if (obj == "yes") {		
					var gr = Ext.getCmp('usrImagesGrid');
					var row = gr.getSelectionModel().getSelected();
					if(row == null || typeof row == 'undefined') return;		
					showProgressWindow('Deleting image..', this);
					Ext.Ajax.request({
						url: "/DesktopModules/UserSearch/UserList.aspx?cmd=dimg",
						method: 'GET', scope: this, params: { "p": row.data.i},
						failure:function(){
							setTimeout(function(){Ext.MessageBox.hide();}, 1000);
							Ext.getCmp('usrImagesGrid').getStore().removeAll();
							Ext.getCmp('usrImagesGrid').getStore().reload();				
						},
						success: function(r, o) {
							setTimeout(function(){Ext.MessageBox.hide();}, 1000);				
							Ext.getCmp('usrImagesGrid').getStore().removeAll();
							Ext.getCmp('usrImagesGrid').getStore().reload();					
							var tg = Ext.get('imageBlock');
							tg.applyStyles("background:transparent url(/images/s.gif) no-repeat top left;");
						}
					});		
				}
			})}},
		'-']
	});
	
	ds.load();
	
	var sm1 = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
	var grid = new Ext.grid.GridPanel({
		store: ds,
		id:'usrImagesGrid',
		sm:sm1,
		tbar:pb,
		bodyStyle:'padding:3px;',
		loadMask:true,
		cm: new Ext.grid.ColumnModel([
			sm1,
			{header: "Image", width: 125, sortable: true, dataIndex: 'i', renderer: function (value,p,r){
				return String.format('<img src="/ImgGen.axd?imgd={0}&ims=m">',r.data.i);			   
			}},
			{header: "File name", width: 100, dataIndex: 'f', sortable: true},
			{header: "Date Uploaded", width: 115, dataIndex: 'd', sortable: true},          
			{header: "Status", width: 70, dataIndex: 's', renderer: function (value,p,r){
				if(r.data.s == "") return r.data.s;
				else
				return String.format('<div class="defimg">{0}</div>',r.data.s);			   
			}}
		]),		
		renderTo:elem,
		height:400,
		autoScroll:true,
		width:450
	});
	
	function showImage(g,index,e){
	    Ext.getCmp('imgDfltBtn').enable();
		Ext.getCmp('imgDelBtn').enable();
		var rec = g.store.getAt(index);
		var tg = Ext.get(targ);
		tg.applyStyles(String.format("background:transparent url(/ImgGen.axd?imgd={0}&ims=xl) no-repeat top left;",rec.get("i")));
	}
	
	grid.on('rowdblclick', showImage);	
	grid.on('rowclick', showImage);							
}

function loadBuddies(){
	var ds = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({ url:"/DesktopModules/UserSearch/UserList.aspx?cmd=buds"}),
		idProperty: 'n',
		reader: new Ext.data.JsonReader(
			{ id: "srchRdr", root: 'r', totalProperty: 't' },
			[{ name: 'u'},
			 { name: 'n'},
			 { name: 'd', type: 'date' },
			 { name: 's'},{name:'c'}
			]),
		remoteSort: true,
		listeners:{loadexception:function(obj,opt,resp,e){
			redirectLogin(resp);
		}}
	});
	
	var pbar = new Ext.PagingToolbar({
            pageSize: 10,
            store: ds,
            displayInfo: false,
            displayMsg: 'Results {0} - {1} of {2}',
            emptyMsg: "You have no Buddies.",
            items: [
            '-']
        });
	ds.load({ start: 0, limit: 10});	
	var sm = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
	
	function handleFriend(act){
		var gr = Ext.getCmp('button-grid');
		var rows = gr.getSelectionModel().getSelections();
		if(rows == null || typeof rows == 'undefined' || rows.length == 0) return;
		showProgressWindow('Updating friend status...', this);
		var p = "";
		for(var i=0; i<rows.length; i++)
		{					
			if (p == "") p = rows[i].data.u;
			else p += "," + rows[i].data.u;
		}
				
		Ext.Ajax.request({
			url: "/DesktopModules/UserSearch/UserList.aspx?cmd=budact",
			method: 'POST', scope: this, params: { "a": act,"p":p },
			failure:function(){
			Ext.getCmp('button-grid').getStore().removeAll();
			Ext.getCmp('button-grid').getStore().reload();
			},
			success: function(r, o) {
				Ext.getCmp('button-grid').getStore().removeAll();
				Ext.getCmp('button-grid').getStore().reload();
			}
		});	
	}
	
	function rowclicks(grid,index,e){
		var rows = grid.getSelectionModel().getSelections();
	     if(rows == null || typeof rows == 'undefined' || rows.length == 0){
		 Ext.getCmp('btnAccept').enable();
		Ext.getCmp('btnDeny').enable();
		Ext.getCmp('btnRemove').enable();
		return;
		 }
		var rec = grid.store.getAt(index);
		Ext.getCmp('btnAccept').disable();
		Ext.getCmp('btnDeny').disable();
		Ext.getCmp('btnRemove').disable();
		if(rec.data.c == 'P' || rec.data.c == 'p') {Ext.getCmp('btnAccept').enable();Ext.getCmp('btnDeny').enable();}	  
		else if (rec.data.c == 'D' || rec.data.c == 'd') {
		  Ext.getCmp('btnRemove').enable();
		  Ext.getCmp('btnAccept').enable();	
		} else if(rec.data.c == 'A' || rec.data.c == 'a')  Ext.getCmp('btnRemove').enable();
	}
	
	var mnu = new Ext.menu.Menu({
	id:'BuddyMenu'
	});
	
	mnu.add({text:'Accept Request',iconCls:'add',id:'BuddyAccept'});	
	mnu.add({text:'Deny Request',iconCls:'remove',id:'DenyAccept'});
	mnu.add('-');
	mnu.add({text:'Remove',iconCls:'remove',id:'BuddyRemove'});
	mnu.items.get('BuddyAccept').on('click',function(item){handleFriend('A');});
	mnu.items.get('DenyAccept').on('click',function(item){handleFriend('D');});
	mnu.items.get('BuddyRemove').on('click',function(item){handleFriend('R');});
	
	
	var grid = new Ext.grid.GridPanel({
		id:'button-grid',
		store: ds,
		cm: new Ext.grid.ColumnModel([
			sm,
			{id:'u',header: "User Name", width: 150, sortable: true, dataIndex: 'u'},
			{dataIndex:'n',header: "Display Name", width: 150, sortable: true},
			{dataIndex:'s',header: "Status", width: 150, sortable: true},{dataIndex:'c',hidden: true},
			{header: "Date", width: 100, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'd'}
		]),
		sm: sm,
		bodyStyle:"padding:0px",
		viewConfig: {
			forceFit:true
		},
		bbar:pbar,
		tbar:[{
				text:'Accept',id:'btnAccept',
				tooltip:'Accept the request',disabled:true,
				iconCls:'add',handler:function(){handleFriend('A');}
			}, '-',{
				text:'Deny',id:'btnDeny',
				tooltip:'Deny friend request',disabled:true,
				iconCls:'remove',
				handler:function(){handleFriend('D');}
			}, '-',{
				text:'Remove',id:'btnRemove',
				tooltip:'Remove friend',disabled:true,
				iconCls:'remove',
				handler:function(){handleFriend('R');}
			}],
		width:600,
		height:300,
		frame:true,
		enableHdMenu:false,
		title:'Buddies',
		renderTo: 'budpane',
		emptyText:'You have no buddies.',
		listeners: {
		"rowclick":{fn:rowclicks},
		"rowdblclick":{fn:rowclicks},
		"rowcontextmenu":{
			fn: function(grd,rowindex,e){
				  e.stopEvent();	
				  var rec = grid.store.getAt(rowindex);
				  mnu.items.get('BuddyAccept').disable();
				  mnu.items.get('DenyAccept').disable();				  
				  mnu.items.get('BuddyRemove').disable();
				  if(rec.data.c == 'P' || rec.data.c == 'p') {mnu.items.get('BuddyAccept').enable();	 mnu.items.get('DenyAccept').enable();} 
				  else if (rec.data.c == 'D' || rec.data.c == 'd') {
					  mnu.items.get('BuddyRemove').enable();
					  mnu.items.get('BuddyAccept').enable();	
				  } else if(rec.data.c == 'A' || rec.data.c == 'a')  mnu.items.get('BuddyRemove').enable();
				  mnu.showAt(e.getXY());				  
				},scope:this
			}
		}
	});
}

function updWinkStatus(wink,status){
	showProgressWindow('Updating Wink...', this);
	new Ext.data.Connection().request({
		url: "/UserList.aspx?cmd=updwnkstat",
		scope: this,
		method: 'POST',
		params: {
			"w": wink,
			"s": status
		},
		failure: requestFailed,
		success: requestSuccessful
	});
	return false;
}