


Ext.onReady(function(){


	
    // turn on validation errors beside the field globally
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'qtip';
	Ext.form.Field.prototype.validationEvent = 'onBlur';
	

		
	setupValidations();
    
    
	//
    /* 
    var mapMenu = new Ext.menu.Menu({
    id: 'mapMenu',
         hidden: false,
    items: [
    	{
            text: 'All TV Shows',
            iconCls: 'noIcon',
            handler: function () { window.location.href="TVShows.jsp" }
        },
        {
            text: 'Food TV',
            iconCls: 'noIcon',
            handler: function () { window.location.href="FoodTV.jsp" }
        },
        { 
            text: 'Travel Channel',
            iconCls: 'noIcon',
            handler: function () { window.location.href="TravelChannel.jsp" }
        },
        {
            text: 'Diners DriveIns & Dives',
            iconCls: 'noIcon',
            handler: function () { window.location.href="DDD.jsp" }
        },
        {
            text: 'Man Vs. Food',
            iconCls: 'noIcon',
            handler: function () { window.location.href="MVF.jsp" }
        },
        {
            text: 'Rachel Ray',
            iconCls: 'noIcon',
            handler: function () { window.location.href="RR.jsp"  }
       },
        {
            text: 'Food Paradise',
            iconCls: 'noIcon',
            handler: function () { window.location.href="FoodParadise.jsp"  }
       }
     ]});
 	
	if (!Ext.isIE)
	{
		Ext.get('maplink').on('mouseover',function(){
			mapMenu.show('maplink');
			mapMenu.getEl().on('mouseleave',
				function(e){
					if (!e.within(Ext.get('maplink'),true,true))
					{
						mapMenu.hide(true);
					}
				});
		});
		
	
		
		Ext.get('maplink').on('mouseout',function(e){
			if (!e.within(mapMenu.getEl(),true,true))
			{
				mapMenu.hide(true);
			}
		});
	}

	*/
    new Ext.ToolTip({
        target: 'rpxlink',
        anchor: 'top',
        anchorOffset: 0, // center the anchor on the tooltip
        html: 'You can register and login using your Facebook, Twitter, Google, Yahoo or OpenID account.'
    });

});  //end onReady


function createToolTip(elemID, htmlBody)
{
    new Ext.ToolTip({
        target: elemID,
        html: htmlBody,
        width:250
    });

}

function createToolTipWithAnchor(elemID, htmlBody,anchor)
{
    new Ext.ToolTip({
        target: elemID,
        html: htmlBody,
        width:250,
        anchor: anchor,
        anchorOffset: 0 // center the anchor on the tooltip
     
    });

}

function createToolTipByURL(elemID, url)
{
    new Ext.ToolTip({
        target: elemID,
        autoLoad: {url: url},
        anchor: 'left',
        anchorOffset: 0, // center the anchor on the tooltip
        width:250
    });

}

function buildSearchHeader()
{

    
        var locationStore = new Ext.data.JsonStore({
    // store configs
	    autoDestroy: true,
	    url: '/MFSAjaxServlet?ACTION=GETLOCATIONS',
	    storeId: 'myStore',
	    // reader configs
	    root: 'Result',
	    idProperty: 'genField1',  
	    fields: ['genField1']
	});  
	
	var tagStore = new Ext.data.JsonStore({
    // store configs
	    autoDestroy: true,
	    url: '/MFSAjaxServlet?ACTION=GETTAGSCATS&TYPE=FOR',
	    storeId: 'myTagStore',
	    // reader configs
	    root: 'Result',
	    idProperty: 'description',  
	    fields: ['description']
	});  
    
    function ComboBoxRenderListener(c)
	{
		var e = c.getEl().up('.x-form-field-wrap');
		e.addClass('displayInline');
	}

    var searchfor = new Ext.form.ComboBox({
     	store: tagStore,
        displayField:'description',
        valueField:'description',
        typeAhead: false,
        forceSelection: false,
        mode: 'remote',
        minChars: 2,
        triggerAction: 'all',
        emptyText:'Enter a Tag or Keyword...',
        selectOnFocus:true,
        id:'searchfor',
        width:190,
        triggerClass:'displayNone',
        listeners: {
        	render: ComboBoxRenderListener
        },
        allowBlank: true
    });

    var searchwhere = new Ext.form.ComboBox({
       // tpl: '<tpl for="."><div ext:qtip="{state}. {nick}" class="x-combo-list-item">{state}</div></tpl>',
        store: locationStore,
        displayField:'genField1',
        valueField:'genField1',
        typeAhead: false,
        minChars:3,
        forceSelection: false,
        mode: 'remote',
        triggerAction: 'all',
        emptyText:'Enter a Location...',
        selectOnFocus:true,
        id:'searchwhere',
        width:190,
        triggerClass:'displayNone',
        listeners: {
        	render: ComboBoxRenderListener
        },
        allowBlank: false
    });




var hdrSearch = new Ext.form.BasicForm('form_id',{
	standardSubmit: true,
	url: 'T_Search.jsp'
});



var lbl1 = new Ext.form.Label({
	text:'Search For:',
	id:'searchlabel',
	cls:'searchHdrLabel'
});


var lbl2 = new Ext.form.Label({
	text:'Where:',
	cls:'searchHdrLabel'
});

var subBtn = new Ext.Button({
	text:'Search',
	id:'searchbtn',
	handler:function(){
		   	if(hdrSearch.isValid()) {
	     	hdrSearch.submit();
		} else {
			Ext.Msg.alert('Error', 'Please Complete the form!!!');
		}

	}
});



hdrSearch.add(searchfor);
hdrSearch.add(searchwhere);

lbl1.render('form_id');
searchfor.render('form_id');
lbl2.render('form_id');
searchwhere.render('form_id');
subBtn.render('form_id');

/*
var menu = new Ext.menu.Menu({
    id: 'mainMenu',
    items: [
        {
            text: 'Search For:',
            iconCls: 'noIcon',
            handler: function () { lbl1.setText('Search For: '); }
        },
        {
            text: 'Search Like:',
            iconCls: 'noIcon',
            handler: function () { lbl1.setText('Search Like:'); }
       }
     ]});

lbl1.getEl().on("click",function(){ menu.show('searchlabel');});
*/

}	//end build search header

function showResetPwd()
{
		   var f = new Ext.FormPanel({
           labelWidth: 100,
           url: '/MFSAjaxServlet?ACTION=PWDRESET',
           frame: true,
           defaults: {width: 150},
           items: [
           			{
           				width:225,
           				html:'<span style="font-weight:normal">Enter your email address and we'+
           					' will reset your password and send you an email with your new password.</span><br/><br/>'
                    },
           
           			{
           			xtype: 'textfield',
                    fieldLabel: 'Email address',
                    name: 'email',
                    vtype: 'email'
                    } ],
           buttons: [{text: 'Reset Password',
               minWidth: 75,
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Resetting Password...',
	               			success: function(form, action) {
	       						Ext.Msg.alert('Password Reset','Your password has been resent to your email address.');
	    						resetDlg.close();
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            default:
						               Ext.Msg.alert("Error", 'Unable to reset password.  Please verify that your account is already registered with us.');
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {resetDlg.close()}}]
       });
       var resetDlg = new Ext.Window({
           height: 200,
           width: 300,
           closable: true,
           closeAction : 'close', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Reset Password',
           layout: 'fit',
           items: f
       });
       resetDlg.show();
}

function showLogin(redir)
{       // create the window on the first click and reuse on subsequent clicks
   
	   	     var f = new Ext.FormPanel({
           labelWidth: 100,
           url: '/A_DoLogin.jsp',
           frame: true,
           defaults: {width: 150},
           items: [
           			{xtype: 'hidden',
                    name: 'redir',
                    value: redir
                    },
           
           			{xtype: 'textfield',
                    fieldLabel: 'Email address',
                    name: 'email',
                    vtype: 'email'},
                   
                   {xtype: 'textfield',
                    inputType: 'password',
                    fieldLabel: 'Password',
                    name: 'password',
                    allowBlank: false},
                     {xtype: 'checkbox',
                    fieldLabel: 'Remember Me',
                    name: 'rememberme',
                    vtype: 'rememberme'},
                      new Ext.Panel({
                    fieldLabel:'Login with',
                    html:'<a  onclick="rpxLinkClick();return false;"   href="#">  <img style="vertical-align:text-bottom;"  alt="Login with Twitter, Facebook, Google, Yahoo! and more"  title="Login with Twitter, Facebook, Google, Yahoo! and more"   src ="v2images/rpx.png"/></a>'
                    
                    })
                    ],
           buttons: [{text: 'Login',
               minWidth: 75,
               type:'submit',
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Logging In...',
	               			success: function(form, action) {
	       						window.location.href=action.result.msg;
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            case Ext.form.Action.SERVER_INVALID:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {loginDlg.close()}},
               {text: 'Forgot Password',
                   minWidth: 75,
                   handler: function() {loginDlg.close();showResetPwd();}}
                   
                   ]
       });
	   
       var loginDlg = new Ext.Window({
           height: 200,
           width: 300,
           closable: true,
           closeAction : 'close', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Login',
           layout: 'fit',
           items: f
       });
       loginDlg.show(redir);
} //end showLogin

function getLoginForm(redir)
{
    var f = new Ext.FormPanel({
           labelWidth: 100,
           url: '/A_DoLogin.jsp',
           frame: true,
           defaults: {width: 150},
           items: [
           			{xtype: 'hidden',
                    name: 'redir',
                    value: redir
                    },
           
           			{xtype: 'textfield',
                    fieldLabel: 'Email address',
                    name: 'email',
                    vtype: 'email'},
                   
                   {xtype: 'textfield',
                    inputType: 'password',
                    fieldLabel: 'Password',
                    name: 'password',
                    allowBlank: false},
                     {xtype: 'checkbox',
                    fieldLabel: 'Remember Me',
                    name: 'rememberme',
                    vtype: 'rememberme'},
                      new Ext.Panel({
                    fieldLabel:'Login with',
                    html:'<a  onclick="rpxLinkClick();return false;"   href="#">  <img style="vertical-align:text-bottom;"  alt="Login with Twitter, Facebook, Google, Yahoo! and more"  title="Login with Twitter, Facebook, Google, Yahoo! and more"   src ="v2images/rpx.png"/></a>'
                    
                    })
                    ],
           buttons: [{text: 'Login',
               minWidth: 75,
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Logging In...',
	               			success: function(form, action) {
	       						window.location.href=action.result.msg;
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            case Ext.form.Action.SERVER_INVALID:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }}]
       });
	return f;
}

function getVerifForm(email)
{
    var f = new Ext.FormPanel({
           labelWidth: 100,
           url: '/MFSAjaxServlet?ACTION=DOVERIFYCODE',
           frame: true,
           width:300,
           defaults: {width: 150},
           items: [
           			           
           			{xtype: 'hidden',
                    value: email,
                    name: 'email',
                    vtype: 'email'},
                   
                   {xtype: 'textfield',
                    
                    fieldLabel: 'Verification Code',
                    name: 'token',
                    allowBlank: false}
                 
                    ],
           buttons: [{text: 'Verify Account',
               minWidth: 75,
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Verifying Account...',
	               			success: function(form, action) {
	       						//window.location.href=action.result.msg;
	       						pageTracker._trackEvent('Register', 'Site', email);
	       						Ext.Msg.alert("Token Verified.","Token Successfully Verified.<br/><br/>Click OK to continue");
	    						window.location.href="T_RatePlaces.jsp?IsNewUser=YES";
	    					},
	    					failure: function(form, action) {
	    					    switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            default:
						               Ext.Msg.alert("Invalid Token", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }}]
       });
	return f;
}


function getFBForm(nickname,email,token)
{
    var f = new Ext.FormPanel({
           labelWidth: 100,
           url: '/MFSAjaxServlet?ACTION=FBREGISTER',
           frame: true,
           width:300,
           defaults: {width: 150},
           items: [
           			           
           			{xtype: 'hidden',
                    value: email,
                    name: 'email',
                    vtype: 'email'},
                   {xtype: 'hidden',
                    value: token,
                    name: 'token',
                    },
                   
                   {xtype: 'textfield',
                    
                    fieldLabel: 'Nick Name',
                    name: 'nickname',
                    value:nickname,
                    allowBlank: false}
                 
                    ],
           buttons: [{text: 'Get Started!',
               minWidth: 75,
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Creating Account...',
	               			success: function(form, action) {
	       						//window.location.href=action.result.msg;
	       						pageTracker._trackEvent('Register', 'Site', email);
	       						window.location.href="T_RatePlaces.jsp?IsNewUser=YES";
	    					},
	    					failure: function(form, action) {
	    					    switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            default:
						               Ext.Msg.alert("Invalid Token", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }}]
       });
	return f;
}


function showContactUs()
{       // create the window on the first click and reuse on subsequent clicks
        var f = new Ext.FormPanel({
           labelWidth: 150,
           url: '/A_ContactUs.jsp',
           frame: true,
           defaults: {width: 250},
           items: [
           			{width:500,html:'<p>Your opinion is VERY important to us, let us know anything on your mind.</p><br/>'},
           
           			{xtype: 'textfield',
                    fieldLabel: 'Your Email Address',
                    name: 'email',
                    vtype: 'email',
                    allowBlank: false},
                   
                   {xtype: 'textfield',
                    inputType: 'textfield',
                    fieldLabel: 'Subject',
                    name: 'subject',
                    allowBlank: false},
                   
                   {xtype: 'textarea',
                    inputType: 'textarea',
                    fieldLabel: 'Message',
                    name: 'message',
                    allowBlank: false,
                   grow:true}
                     

                    ],
           buttons: [{text: 'Submit',
               minWidth: 75,
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Sending Message...',
	               			success: function(form, action) {
		       						 Ext.Msg.alert("Success","Your Message Has Been Sent.");
		       						 contactDlg.close();
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            case Ext.form.Action.SERVER_INVALID:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {contactDlg.close()}}]
       });

       var contactDlg = new Ext.Window({
           height: 300,
           width: 525,
           closable: true,
           closeAction : 'hide', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Contact Us',
           layout: 'fit',
           items: f
       });
       contactDlg.show();
} //end showLogin


function showQuickRate()
{
	var inserted = 0;
	var destStore = new Ext.data.JsonStore({
    // store configs
	    autoDestroy: true,
	    url: '/MFSAjaxServlet?ACTION=GETTAGSCATS&TYPE=LIKE',
	    storeId: 'myDestStore',
	    // reader configs
	    root: 'Result',
	    idProperty: 'categoryID',  
	    fields: ['description','categoryID']
	});  
	
    var destlist = new Ext.form.ComboBox({
     	store: destStore,
        displayField:'description',
        valueField:'categoryID',
        typeAhead: false,
        forceSelection: true,
        mode: 'remote',
        minChars: 2,
        triggerAction: 'all',
        emptyText:'Enter a Business Name',
        selectOnFocus:true,
        id:'quickrate',
        triggerClass:'displayNone',
        allowBlank: false,
        width:300,
        flex:1,
        listeners:{
        	'select': function(combo,record,index)
        	{
        	if (inserted==0){
	        	quickRate.insert(1,{
		           	id:'quickratediv',
		         	html:'',
		           	width:300,
		           	border: false,
		           	flex:1
		        });
	        }
	        inserted = 1;
	        quickRate.setHeight(275);
           	quickRate.center();
          	quickRate.doLayout();
        	
        	Ext.getCmp('quickratediv').body.load({
        		url : '/I_DestRank.jsp?DestID='+record.id ,
        		scripts: true
        	});
     		

        	//	alert(record.id);
        	/*	Ext.Ajax.request({
        		scripts: true,
				url : '/I_DestRank.jsp?DestID='+record.id , 
					method: 'GET',
					success: function ( result, request) { 
							//FINISH HERE
							Ext.getDom('quickratediv').innerHTML = result.responseText;				
	        			}
        		});*/
        }
    }
        
    });
    
	var quickRate = new Ext.Window({
		   height: 185,
           width: 400,
           closable: true,
           closeAction : 'close', 
           id: 'quickratedlg',
           modal: true,
           frame: true,
           resizable: false,
           title: 'Quick Rate',
           layout: {                   	
           	type:'vbox',
            padding:'5',
            align:'center'
           },
           items:[
            destlist,

           {
           	id:'instructions',
         	html:'<br/><b>Instructions:<br>Enter a business name to rate.  Rate it!<br/>'+
         	'Enter another business, rate it!<br/>Close the window your done.<br/>'+
         	'If you can\'t find the place you want to rate, you can add it by <a href="javascript:showAddPlaceFromSuggDlg()">clicking here.</a>',
           	width:300,
           	border: false,
           	flex:2
           }
           ]
    });
    quickRate.show();
}

function showRegister()
{       // create the window on the first click and reuse on subsequent clicks
        var f = new Ext.FormPanel({
           labelWidth: 100,
           url: '/A_DoRegister1.jsp',
           frame: true,
           defaults: {width: 150},
           items: [{xtype: 'textfield',
                    fieldLabel: 'Email address',
                    name: 'email',
                    validationEvent: 'onBlur',
                    vtype: 'email'},
                   {xtype: 'textfield',
                    fieldLabel: 'Nickname',
                    name: 'nickname',
                    vtype: 'nicknameUnique',
                    minLength: 4},
                   {xtype: 'textfield',
                    inputType: 'password',
                    fieldLabel: 'Password',
                    minLength: 6,
                    name: 'password',
                    allowBlank: false},
                    {xtype: 'textfield',
                    inputType: 'password',
                    fieldLabel: 'Verify Password',
                    name: 'password2',
                    minLength: 6,
                    allowBlank: false},
                    {xtype: 'textfield',
                    inputType: 'textfield',
                    fieldLabel: 'Your Location',
                    name: 'where',
                    allowBlank: false},
                              {xtype: 'checkbox',
                    fieldLabel: 'I agree with Terms and Conditions.',
                    name: 'terms'
                   },
                    
                      new Ext.Panel({
                    fieldLabel:'Register with',
                    html:'<a  onclick="rpxLinkClick();return false;"   href="#">  <img style="vertical-align:text-bottom;"  alt="Login with Twitter, Facebook, Google, Yahoo! and more"  title="Login with Twitter, Facebook, Google, Yahoo! and more"   src ="v2images/rpx.png"/></a>'
                    
                    })
                    ],
           buttons: [{text: 'Register',
               minWidth: 75,
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Registering...',
	               			success: function(form, action) {
	               				
	       						window.location.href='T_VerifyReqd.jsp';
	       						
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            case Ext.form.Action.SERVER_INVALID:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {regDlg.close()}}]
       });

       var regDlg = new Ext.Window({
           height: 300,
           width: 300,
           closable: true,
           closeAction : 'hide', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Register',
           layout: 'fit',
           items: f
       });
       regDlg.show();
} //end showRegister




function setupValidations()
{
	Ext.apply(Ext.form.VTypes, {
		nicknameUnique: function (val, field){
			Ext.Ajax.request({
				url : '/MFSAjaxServlet' , 
				params : { ACTION : 'NICKCHECK', nickname: val },
				method: 'GET',
				success: function ( result, request) { 
					if(result.responseText=='AVAILABLE')
					{
						
					}
					else
					{
						field.markInvalid("Nickname already taken.");
					}
					
				},
				failure: function ( result, request) { 
					 field.markInvalid("Error validating nickname.");
				}
				}); 
				return true;
			},	
			
		nicknameUniqueText: "Nickname already taken."
	});
}
			


function createFollowBtn(elemID,uid)
{
	var btn = new Ext.Button({
		text: 'Follow',
		scale: 'small',
		handler: function()
		{
			Ext.Ajax.request({
				url : 'MFSAjaxServlet' , 
				params : { ACTION : 'FOLLOW', uid2 : uid },
				method: 'GET',
				success: function ( result, request) {
					var ok = result.responseText;
					if (ok == 'OK')
					{
						btn.hide();
						createUnFollowBtn(elemID,uid);			
					}
					else
					{
						Ext.MessageBox.alert('Failed', 'Unable to follow.'); 			
					}
				},
				failure: function ( result, request) { 
					Ext.MessageBox.alert('Failed', 'Unable to follow.'); 
				} 
			});
		}	
	});
	btn.render(elemID);
}

function createUnFollowBtn(elemID,uid)
{
	var btn = new Ext.Button({
		text: 'Un-Follow',
		scale: 'small',
		handler: function()
		{
			Ext.Ajax.request({
				url : 'MFSAjaxServlet' , 
				params : { ACTION : 'UNFOLLOW', uid2 : uid },
				method: 'GET',
				success: function ( result, request) {
					var ok = result.responseText;
					if (ok == 'OK')
					{
						btn.hide();
						createFollowBtn(elemID,uid);			
					}
					else
					{
						Ext.MessageBox.alert('Failed', 'Unable to follow.'); 			
					}
				},
				failure: function ( result, request) { 
					Ext.MessageBox.alert('Failed', 'Unable to follow.'); 
				} 
			});
		}
	});
	btn.render(elemID);
}



function createRatingsGrid(uid, nick)
{
	var store = new Ext.data.JsonStore({
        root: 'Result',
        totalProperty: 'total',
        idProperty: 'id',
        remoteSort: true,
		url: '/MFSAjaxServlet?ACTION=GETUSERRATINGS&uid='+uid,
        fields: [
            'name', 
            {name: 'displayDate', mapping: 'displayDate', type: 'date', dateFormat: 'm/d/Y'},
		 	'rank', 'id','comments','city','state','userDislayStr'
         ]
        });

    store.setDefaultSort('creationDate', 'desc');
    
     function renderDestLink(value, p, record){
        return String.format(
                '<b><a href="dest{0}.html">{1}</a></b>',
                record.id, value);
    }
    
    function renderDate(value, p, r){
        return String.format('{0}', value.dateFormat('m/d/Y'));
    }
    
    function renderLocation(value, p, r){
        return String.format('{0}, {1}', value, r.data.state);
    }
 
    var title = "Your ";
    if (nick != null)
    	title = nick+"\'s ";
	
	  var grid = new Ext.grid.GridPanel({
        width:750,
        height:525,
        title:''+title+'Ratings',
        store: store,
        trackMouseOver:false,
        disableSelection:true,
        loadMask: true,
		    columns:[{
            id: 'destname', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: "Name",
            dataIndex: 'name',
            width: 250,
            sortable: true,
            renderer:renderDestLink
        },{
            header: "Location",
            dataIndex: 'city',
            width: 150,
            renderer: renderLocation,
            sortable: true
        },{
            header: "Rating",
            dataIndex: 'rank',
            width: 70,
            align: 'right',
            sortable: true
        },{
            id: 'date',
            renderer: renderDate,
            header: "Date",
            dataIndex: 'displayDate',
            width: 150,
            sortable: true
           
        }],
        bbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying Ratings {0} - {1} of {2}',
            emptyMsg: "No topics to display"
        })
        
       });
       store.load({params:{start:0, limit:25}});
	   ratingGrid = true;
       return grid;
		

}

function rpxLinkClick()
{
	return RPXNOW.show(RPXNOW.token_url,'https://thesuggestr.rpxnow.com/openid/v2/signin');
}

function showGetSuggestion(loggedIn)
{
	    
	        var locationStore = new Ext.data.JsonStore({
	    // store configs
		    autoDestroy: true,
		    url: '/MFSAjaxServlet?ACTION=GETLOCATIONS',
		    storeId: 'myStore',
		    // reader configs
		    root: 'Result',
		    idProperty: 'genField1',  
		    fields: ['genField1']
		});  
		
		var tagStore = new Ext.data.JsonStore({
	    // store configs
		    autoDestroy: true,
		    url: '/MFSAjaxServlet?ACTION=GETTAGSCATS&TYPE=FOR',
		    storeId: 'myTagStore',
		    // reader configs
		    root: 'Result',
		    idProperty: 'description',  
		    fields: ['description']
		});  
	    

	
	    var searchfor = new Ext.form.ComboBox({
	     	store: tagStore,
	        displayField:'description',
	        valueField:'description',
	        fieldLabel:'What are you searching for?',
	        labelStyle:'width:200px',
	        typeAhead: false,
	        forceSelection: false,
	        mode: 'remote',
	        minChars: 2,
	        triggerAction: 'all',
	        emptyText:'Enter a Tag or Keyword...',
	        selectOnFocus:true,
	        id:'searchforDlg',
	        name:'searchfor',
	        width:250,
	        triggerClass:'displayNone',
	        allowBlank: false
	    });
	
	    var searchwhere = new Ext.form.ComboBox({
	       // tpl: '<tpl for="."><div ext:qtip="{state}. {nick}" class="x-combo-list-item">{state}</div></tpl>',
	        store: locationStore,
	        displayField:'genField1',
	        valueField:'genField1',
	        typeAhead: false,
	        minChars:3,
	          labelStyle:'width:200px',
	      	name:'searchwhere',
	        fieldLabel:'Where would you like to look?',
	        forceSelection: false,
	        mode: 'remote',
	        triggerAction: 'all',
	        emptyText:'Enter a Location...',
	        selectOnFocus:true,
	        id:'searchwhereDlg',
	        width:250,
	        triggerClass:'displayNone',
	        allowBlank: false
	    });
	
	
	
	

	
	
	var subBtn = new Ext.Button({
		text:'Get Suggestion',
		id:'searchbtnDlg',
		handler:function(){
			   	if(hdrSearch.getForm().isValid()) {
			   	hdrSearch.getForm().getEl().dom.action = 'T_Search.jsp';
		     	hdrSearch.getForm().submit();
			} else {
				Ext.Msg.alert('Error', 'Please Complete the form!!!');
			}
	
		}
	});
	
	var msg = 'Getting a suggestion is as simple as telling us what your looking for and'+
	' where you are looking.  The what can be something general, like restaurant, or specific '+
	'like Pizza.  Don\'t worry you\'ll be able to narrow your search further on the next screen.<br/><br/>'
	
	if (loggedIn < 0)
		msg += '<span class=\'warn\'>Warning: You are not logged in which means you will not get the benefit of personalized suggestions!</span><br/><br/>';
	
	var hdrSearch = new Ext.form.FormPanel({
		standardSubmit: true,
		id: 'dlgsearch',
		url: 'T_Search.jsp',
		items: [
			{html:msg},
			searchfor,searchwhere],
		buttons: [subBtn]
	});
	
	//workaround for bug
	
	
	var getSuggDlg = new Ext.Window({
           height: 200,
           id:'getsuggdlg',
           width: 500,
           closable: true,
           closeAction : 'close', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Get Suggestions',
           layout: 'fit',
           items: hdrSearch
       });
       getSuggDlg.show();	

}

function setWhere(whereStr)
{
	if (Ext.getCmp('searchwhere')) {
		Ext.getCmp('searchwhere').setValue(whereStr);
	}
}	

function addToWishList(destid)
{
	Ext.Ajax.request({
				url : '/MFSAjaxServlet' , 
				params : { ACTION : 'ADDTOWISHLIST', DestID: destid },
				method: 'GET',
				success: function ( result, request) { 
					if(result.responseText=='OK')
					{
						Ext.Msg.show({
						   title:'Success.',
						   msg: 'Successfully added to wish list.',
						   buttons: Ext.Msg.OK,
						   icon: Ext.MessageBox.INFO
						});
					}
	
				},
				failure: function ( result, request) { 
					 Ext.Msg.show({
					   title:'Error',
					   msg: 'An error has occured.',
					   buttons: Ext.Msg.OK,
					   icon: Ext.MessageBox.ERROR
					});
				}
				}); 
}

function delFromWishList(destid)
{
	Ext.Ajax.request({
				url : '/MFSAjaxServlet' , 
				params : { ACTION : 'DELTOWISHLIST', DestID: destid },
				method: 'GET',
				success: function ( result, request) { 
					if(result.responseText=='OK')
					{
						Ext.Msg.show({
						   title:'Success.',
						   msg: 'Successfully removed from wish list.',
						   buttons: Ext.Msg.OK,
						   icon: Ext.MessageBox.INFO
						});
					}
	
				},
				failure: function ( result, request) { 
					 Ext.Msg.show({
					   title:'Error',
					   msg: 'An error has occured.',
					   buttons: Ext.Msg.OK,
					   icon: Ext.MessageBox.ERROR
					});
				}
				}); 
}
 
function resendVerification(email)
{
	var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
	myMask.show();
		Ext.Ajax.request({
				url : '/MFSAjaxServlet' , 
				params : { ACTION : 'GENVERIFYCODE', email: email },
				method: 'GET',
				success: function ( result, request) { 
				 	//alert(result.responseText);
				 	myMask.hide();
					if(result.responseText=='OK')
					{
						
						Ext.Msg.show({
						   title:'Success.',
						   msg: 'Verification Code sent to '+email,
						   buttons: Ext.Msg.OK,
						   icon: Ext.MessageBox.INFO
						});
					}
	
				},
				failure: function ( result, request) { 
					myMask.hide();
					 Ext.Msg.show({
					   title:'Error',
					   msg: 'An error has occured.',
					   buttons: Ext.Msg.OK,
					   icon: Ext.MessageBox.ERROR
					});
				}
				}); 
}

function showAddPlaceFromSuggDlg()
{
	var dlg = Ext.getCmp('quickratedlg');
	dlg.close();
	showAddPlace();
}

function showMustBeLoggedIn()
{
	
Ext.Msg.show({
   title:'You Must Be Logged In.',
   msg: 'Sorry - You must be registered and logged in to use this functionality.',
   buttons: Ext.Msg.OK,
   icon: Ext.MessageBox.ERROR
});
}

function showUnderContruction()
{
	
Ext.Msg.show({
   title:'Under Construction.',
   msg: 'Sorry - This feature is not yet complete.  Please contact us if you have any questions.',
   buttons: Ext.Msg.OK,
   icon: Ext.MessageBox.INFO
});
}


function showCheckin()
{       // create the window on the first click and reuse on subsequent clicks
        var f = new Ext.FormPanel({
           labelWidth: 100,
           url: '/A_DoCheckin.jsp',
           frame: true,
           defaults: {width: 250},
           items: [{xtype: 'textfield',
                    fieldLabel: 'Your Location',
                    name: 'location',
                    id:'hdrlocation',
                    validationEvent: 'onBlur'
                  },
                  {
                  	width:380,
           			items:new Ext.Panel({
           				width:280,
           				html: '<br/>Check-In Manually or <a href="T_UserHomePage.jsp?TAB=extaccts">click here</a> to link to your Twitter, FireEagle or BrightKite accounts.'
           			})
           			}
                  ],
           buttons: [{text: 'Check In',
               minWidth: 75,
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Checking In...',
	               			success: function(form, action) {
	       						Ext.getDom('hdrcheckin').innerHTML = Ext.getCmp('hdrlocation').getValue();
	       						createToolTipWithAnchor('hdrcheckin','You last checked in @ '+Ext.getCmp('hdrlocation').getValue()+' via theSUGGESTR just seconds ago.<br/><br/>Click the location above to check-in somewhere else.');
	       						checkDlg.close();
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            default:
						               Ext.Msg.alert("Error", "An error has occured: "+action.result.msg);
						               checkDlg.close();
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {checkDlg.close()}}]
       });

       var checkDlg = new Ext.Window({
           height: 200,
           width: 400,
           closable: true,
           closeAction : 'hide', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Check In',
           layout: 'fit',
           items: [f
           		  ]
       });
       checkDlg.show();
} //end showCheckin


 function updateDestRatingEXT(dest,user,value,isDestPage)
 {

Ext.Ajax.request({
   url: 'AJAX_AddDestRating.jsp?DestID='+dest+'&Rating='+value,
   success: function(o) {
   	if (isDestPage!=1)
  		document.getElementById('ratinglabel_'+dest).innerHTML='<b>Average Rating:</b> '+o.responseText+'<br><b>Your Rating: </b>'+getvaluedisplay(value);
  	else
  		document.getElementById('ratinglabel_'+dest).innerHTML='<b>Average Rating:</b> <span class="destPageSummary">'+o.responseText+'</span><br><b>Your Rating: </b>'+getvaluedisplay(value);
  	pageTracker._trackEvent('Rating', 'Dest'+dest, 'User'+user);
   },
   failure: updateFail,
   headers: {
       'my-header': 'foo'
   },
   params: { foo: 'bar' }
});
Ext.Ajax.defaultHeaders = {
    'Powered-By': 'Ext'
};
}
 
  function updateFail()
 {
 alert('fail');
 }
 
 function setSlider(uid,destid,val)
 {
 	setSlider(uid,destid,val,-1);
 }
 
 function setSlider(uid,destid,val,isDestPage){
    if(val=="")
    val=0;
    
    var tip = new Ext.ux.SliderTip({
        getText: function(slider){
                return getvaluedisplay(slider.getValue());
        }
    });
    var slider2=new Ext.Slider({
        renderTo: 'ratingdiv_'+destid,
        width: 100,
        increment: 1,
        minValue: 0,
        maxValue: 100,
        plugins: tip,
        value:val,
        listeners: 
        {
            changecomplete: function(slider,newValue)
            {                                    
                updateDestRatingEXT(destid,uid,newValue,isDestPage);
            }        
        }
        
    });  
}
Ext.ux.SliderTip = Ext.extend(Ext.Tip, {
    minWidth: 10,
    offsets : [0, -10],
    init : function(slider){
        slider.on('dragstart', this.onSlide, this);
        slider.on('drag', this.onSlide, this);
        slider.on('dragend', this.hide, this);
        slider.on('destroy', this.destroy, this);
    },

    onSlide : function(slider){
        this.show();
        this.body.update(this.getText(slider));
        this.doAutoWidth();
        this.el.alignTo(slider.thumb, 'b-t?', this.offsets);
    },

    getText : function(slider){
        return String(slider.getValue());
    }
});


function getvaluedisplay(rat)
{
	if (rat >= 90)
				{
				   return String.format('<b><font color="#62d645">{0} (Amazing)</font></b>', rat);
					
				 }
				else if (rat >= 75)
				{
				return String.format('<b><font color="#71c920">{0} (Excellent)</font></b>', rat);
					
				}
				else if (rat >=50)
				{
				return String.format('<b><font color="#b5c320">{0} (Good)</font></b>', rat);
					
				}
				else if (rat >=25)
				{
				return String.format('<b><font color="#d2ae27">{0} (Fair)</font></b>', rat);
				   
				}
				else if (rat > 0)
				{
					return String.format('<b><font color="#c33029">{0} (Poor)</font></b>', rat);
					
				}
				else 
				{
					return String.format('<b><font color="#c33029">{0} (Terrible)</font></b>', rat);
					
				}
}var ratingGrid = false;
var baseHeight = 770;

function initUserHomePage(uid,usrlogourl,nosuggs)
{

	var acPanel = getAccountPanel(usrlogourl);
	var dashboard;
	if (nosuggs==true)
	{
		dashboard = getNoSuggDashboard();
	}
	else
	{
		dashboard = getUserDashboard();
	}
     var viewport = new Ext.Container({
        renderTo:'main',
        layout:'fit',
       	id:'vport',
        items:[{
            xtype: 'grouptabpanel',
    		tabWidth: 130,
    		activeGroup: 0,
    		id: 'userhomepanel',
    		layoutOnTabChange: true,

    		items: [{
    			mainItem: 0,
    			id: 'dashboardgroup',
					 defaults:{autoScroll: false},
      				 plain:true,
    			items: [
                {
                    title: 'Dashboard',
                    tabTip: 'Dashboard tabtip',
      				id: 'dashboard',
   					items:[
						dashboard
   					],
   					listeners:{ activate:function(p) {resizeWindow(baseHeight);}}               
                },
                {
    				title: 'My Suggestions',
                    layout: 'fit',
                    iconCls: 'x-icon-tickets',
                    tabTip: 'View Personalized Suggestions',
                    style: 'padding: 10px;',
                    id: 'mysuggpanel',
                    autoLoad: {url:'/A_MySuggestions.jsp',scripts:true,
                    	callback: function() { 
							  var newpanel = Ext.get('mysuggpage');
							  resizeWindow(newpanel.getHeight()+40);
						}
					},
					listeners:{
						activate:function(p)
						{
							var newpanel = Ext.get('mysuggpage');
							if (newpanel!=null)
								resizeWindow(newpanel.getHeight()+40);
						}
					}
						
    			}, 
                 {
    				title: 'My Wish List',
                    iconCls: 'x-icon-tickets',
                    tabTip: 'View Your Wish List',
                    style: 'padding: 10px;',
                  autoLoad: {url:'/A_WishList.jsp',scripts:true,
                    	callback: function() { 
							  var newpanel = Ext.get('wishlistpage');
							  resizeWindow(newpanel.getHeight()+40);
						}
					},
					listeners:{
						activate:function(p)
						{
							var newpanel = Ext.get('wishlistpage');
							if (newpanel!=null)
								resizeWindow(newpanel.getHeight()+40);
						}
					}
    			},
    			{
    				title: 'My Maps <img src="v2images/new_icon_psw.gif"/>',
                    iconCls: 'x-icon-tickets',
                    tabTip: 'See maps of your suggestions and wishlist.',
                    style: 'padding: 10px;',
                    autoLoad: {url:'/A_MyMaps.jsp',
                    	callback: function() { }
                    	}	
                    ,
   					listeners:{ activate:function(p) {resizeWindow(baseHeight);}}	
    			},
    			{
    				title: 'I\'m Following',
                    iconCls: 'x-icon-tickets',
                    tabTip: 'See all the people you\'re following.',
                    style: 'padding: 10px;',
    				autoLoad: {url:'/A_UHFollowing.jsp?profileid='+uid,scripts:true,
                    	callback: function() { }
                    	}
                    ,
   					listeners:{ activate:function(p) {resizeWindow(baseHeight);}}				
    			},	
    			{
    				title: 'My Followers',
                    iconCls: 'x-icon-tickets',
                    tabTip: 'See all the people following you.',
                    style: 'padding: 10px;',
    				autoLoad: {url:'/A_UHFollowers.jsp?profileid='+uid,script:true,
                    	callback: function() { }
                    	}	
                    ,
   					listeners:{ activate:function(p) {resizeWindow(baseHeight);}}				
    			},
    			{
    				title: 'My Ratings',
    				iconCls: 'x-icon-tickets',
                    tabTip: 'See All Your Ratings.',
                    style: 'padding: 10px;',
    				
    				listeners:{
                    	activate: function(p)
                    	{
                    		if (ratingGrid == false)
                    		{
                    			p.add({
                    				border:false,
                    				html:'<h1>Your Ratings</h1>The number of ratings is the number one thing that effects your suggestibility.  You can rate more places by <a href="T_RatePlaces.jsp">click here.</a><br/><br/>'
                    			});
	                    		p.add(createRatingsGrid(uid));
	                    		resizeWindow(baseHeight);
	                    		p.doLayout();
	                    	}
                    	}
                    }
                 }
    			]
            }, {
                expanded: true,
                id: 'cities',
                items: [{
                    title: 'My Cities',
                    tabTip: 'Configuration tabtip',
                    style: 'padding: 10px;',
                    autoLoad: {url:'/A_MyCityList.jsp',script:true,
                    		callback: function() { 
                    			getAddNewCityForm();
                    		}
               		 }
               		 ,
   					listeners:{ activate:function(p) {resizeWindow(baseHeight);}}	 	
                }]
            },
            {
                expanded: true,
                listeners:{ beforetabchange:function(p,nt,ot) {
					if(nt.getId()=='changepass')
					{
						showChangePwd();
						return false;
					}
					else 
						return true;
					}
				},       
                id: 'accountgroup',
                items: [{
                    title: 'My Account',
                    tabTip: 'Change Account Information',
                    style: 'padding: 10px;',
                    layout: 'vbox',
                    border:false,
                    layoutConfig: {align : 'stretch',pack  : 'start'},
              
   					listeners:{ activate:function(p) {resizeWindow(baseHeight);}},
                    items:[{html:'<h1>Account Info</h1>',border:false},{border:false,layout: 'ux.center',items: acPanel}]
                },
                {
                	title: 'Change Password',
                	iconCls: 'x-icon-tickets',
                    tabTip: 'Change Your Password',
                    id: 'changepass'       
                	
                  
                },
                {
                    title: 'Invite Friends',
                    iconCls: 'x-icon-tickets',
                    tabTip: 'Invite Some Friends',
                    style: 'padding: 10px;',
                    
                    autoLoad: {url:'/A_InviteMultipleFriends.jsp',scripts:true,
                    	callback: function() { }
                    	},
   					listeners:{ activate:function(p) {resizeWindow(baseHeight);}}
                }, 
                {
                    title: 'External Accounts',
                    iconCls: 'x-icon-tickets',
                    tabTip: 'See Your External Account Links',
                    style: 'padding: 10px;',
                    autoLoad: {url:'/A_LinkedAccounts.jsp',scripts:true,
                    	callback: function() { }
                    	},
   					listeners:{ activate:function(p) {resizeWindow(baseHeight+400);}}
                },
                {
                    title: 'Alerts',
                    iconCls: 'x-icon-tickets',
                    tabTip: 'See Your Automatic Alert Settings',
                    style: 'padding: 10px;',
                    id: 'alertpanel',
                    listeners:{
                    	activate: function(p)
                    	{
                    		Ext.getCmp('alertpanel').body.load({
							    url:'/A_AlertSettings.jsp',
							    scripts:true
							});
							resizeWindow(baseHeight);
                    	}
                    	
                    }
              
                },
             /*   {
                    title: 'My Favorites',
                    iconCls: 'x-icon-tickets',
                    tabTip: 'Your Favorite Places',
                    style: 'padding: 10px;',
                    html: 'test'
                }
                , */
               {
                    title: 'View Profile',
                    iconCls: 'x-icon-tickets',
                    tabTip: 'View Your Public Profile',
                    style: 'padding: 10px;',
                    listeners:{
                    	activate: function(p)
                    	{
                    		window.location.href = 'user'+uid+'.html';
                    	}
                    }
                }
                ]
            }
            ]
		}]
    });
	

}

function showTwitterSettings(opt1,opt2)
{
		   var f = new Ext.FormPanel({
           labelWidth: 150,
           url: '/MFSAjaxServlet?ACTION=TWITTERSETTINGS',
           frame: false,
           width: 300,
           header: false,
           border: false,
           defaults: {width: 250},
           title: 'Twitter Settings',
           items: [
			{
				xtype: 'checkbox',
				fieldLabel: 'Post Activity to Twitter',
				name: 'posttotwitter',
				checked: opt1
			}, 
			{
				xtype: 'checkbox',
				fieldLabel: 'Send Location Infomation',
				name: 'postlocation',
				checked: opt2
			}
			],
			 buttons: [{text: 'Submit Changes',
               minWidth: 75,
               handler: function() {

               			f.getForm().submit({
               				waitMsg:'Submitting...',
	               			success: function(form, action) {
	       						Ext.Msg.alert('Changes Saved','Your Changes Have Been Saved.');
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            default:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               	
               		 }}]
			});
			f.render('twittersettings');
}

function showChangePwd()
{
		   var f = new Ext.FormPanel({
           labelWidth: 100,
           url: '/MFSAjaxServlet?ACTION=PWDCHANGE',
           frame: true,
           defaults: {width: 150},
           items: [
           			{
           				width:225,
           				html:'<span style="font-weight:normal">Please enter your current and new passwords.</span><br/><br/>'
                    },
           
           			{
           			xtype: 'textfield',
           			inputType: 'password',
                    fieldLabel: 'Current Password',
                    name: 'currentpass',
                    allowBlank: false
                    },
                    {
           			xtype: 'textfield',
           			inputType: 'password',
                    fieldLabel: 'New Password',
                    name: 'newpass1',
                    minLength: 6,
                    allowBlank: false
                   
                    },
                    {
           			xtype: 'textfield',
           			inputType: 'password',
                    fieldLabel: 'Verify Password',
                    name: 'newpass2',
                    minLength: 6,
                    allowBlank: false
                    }
                    ],
           buttons: [{text: 'Change Password',
               minWidth: 75,
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Changing Password...',
	               			success: function(form, action) {
	       						Ext.Msg.alert('Password Change','Your password has been changed.');
	    						changePassDlg.close();
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            default:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {changePassDlg.close()}}]
       });
       var changePassDlg = new Ext.Window({
           height: 240,
           width: 300,
           closable: true,
           closeAction : 'close', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Change Password',
           layout: 'fit',
           items: f
       });
       changePassDlg.show();
}

function resizeWindow(h)
{
	var vport = Ext.getCmp('vport');
	vport.setHeight(h+40);
	vport.doLayout();
}

//not used but example of expanding tab panel
function showNoSuggWarning()
{
	var dboard = Ext.getCmp("acctdetails");
	dboard.insert(0, new Ext.Panel({
				        title: 'No Suggestions Available',
				        id: 'suggwarning',
				        collapsible:false,
				        applyTo: 'suggwarning',					
				        frame:'true',
				        bodyStyle: 'padding-bottom:13px;',			 
				        width:735      
						})
					);
	var vport = Ext.getCmp('vport');
	var h = Ext.getCmp('suggwarning').getHeight();
    vport.setHeight(vport.getHeight()+h+40);  //<-- this works
	dboard.doLayout();
	vport.doLayout();
	
}

function addCity(loc,id)
{
	var fullLoc = loc;
	if (loc.length > 14)
		loc = loc.substring(0,11)+ '...';
	var cityList = Ext.ComponentMgr.get('cities');
	var pane = new Ext.Panel({
		      		title: loc,
		      		tabTip: fullLoc,
                    iconCls: 'x-icon-tickets',
                    style: 'padding: 10px;',
                    html: 'Loading...',
    				listeners:{
                    	activate: function(p)
                    	{
                    		window.location.href = 'T_NeighborhoodPage.jsp?location='+fullLoc;
                    	}
                    }
              });
    cityList.add(pane);
    cityList.doLayout();
}

function changeToMyCities()
{
	var panel = Ext.ComponentMgr.get('cities');
	panel.setActiveTab(0);
}
 
function changeToMySuggestions()
{
	var panel = Ext.ComponentMgr.get('dashboardgroup');
	panel.setActiveTab(1);
}
	
function changeToFollowersUH()
{
	var panel = Ext.ComponentMgr.get('dashboardgroup');
	panel.setActiveTab(4);
}

function changeToFollowingUH()
{
	var panel = Ext.ComponentMgr.get('dashboardgroup');
	panel.setActiveTab(3);
}

function changeToMyRatings()
{
	var panel = Ext.ComponentMgr.get('dashboardgroup');
	panel.setActiveTab(5);
}

function changeToInviteFriends()
{
	var panel = Ext.ComponentMgr.get('accountgroup');
	panel.setActiveTab(2);
}

function changeToExtAcct()
{
	var panel = Ext.ComponentMgr.get('accountgroup');
	panel.setActiveTab(3);
}

function changeToHomePageSummary()
{
	var panel = Ext.ComponentMgr.get('dashboardgroup');
	panel.setActiveTab(0);
} 

function removeMyCity(regid)
{
	var item = Ext.get('reg'+regid);
	item.fadeOut({remove:true});
}

function getAddNewCityForm()
{

        var locationStore = new Ext.data.JsonStore({
    // store configs
	    autoDestroy: true,
	    url: '/MFSAjaxServlet?ACTION=GETLOCATIONS',
	    storeId: 'myStore',
	    // reader configs
	    root: 'Result',
	    idProperty: 'genField1',  
	    fields: ['genField1']
	});   
	
	var fs = new Ext.FormPanel({
        frame: false,
        title:'Add New Favorite City',
        labelAlign: 'right',
        labelWidth: 50,
        id:'addnewcityform',
        waitMsgTarget: true,
        header:false,
        border:false,
    	 items: [
            new Ext.form.FieldSet({
                title: 'Add New Favorite City',
                defaultType: 'textfield',
				autoHeight:true,
				cls: 'bigfieldset',
			    items: [    
			    		{
			    		xtype:'combo',
				        store: locationStore,
				        displayField:'genField1',
				        valueField:'genField1',
				        typeAhead: false,
				        minChars:3,
				        forceSelection: false,
				        fieldLabel:'Location',
				        mode: 'remote',
				        triggerAction: 'all',
				        emptyText:'',
				        selectOnFocus:true,
				        name: 'location',
				      	width:168,
				        triggerClass:'displayNone',
				        style: {marginLeft:'3px'},
				       
				        allowBlank: false
   		 			}, {
                    	fieldLabel: 'Label',
                        name: 'label',
                        allowBlank:false,
                        width:150
                    }
                   	]
                   })]});
     var submit = fs.addButton({
        text: 'Submit',
        disabled:false, 
        handler: function(){
            fs.form.submit({
                url:'A_AddNewFavCity.jsp',	
                waitMsg:'Saving Data...',
                success: function (form, action) {
                	var tplData = '<div id="reg{0}" style="width:100%;padding-bottom:5px;text-align:left">'+
                	'<div style="float:right"><a href="javascript:removeMyCity(\'{0}\');">Remove</a></div>'+
                	'<span style="font-size:110%">{1} ({2})</span></div>';
                	var tpl = new Ext.DomHelper.createTemplate(tplData);               	
                	
                	var location = action.result.location;
                	var label = action.result.label;
                	var key = action.result.key;
                	
                	tpl.append('mycitylist',[key,label,location]);
                	form.reset();
                    //Ext.MessageBox.alert('Message', 'Saved OK '+label);
                },
                failure:function(form, action) {
                    Ext.MessageBox.alert('Message', 'Save failed');
                }
            });
        }
    });             
	
	fs.render('addnewcity'); 
}

function getAccountPanel(usrlogourl)
{
	  var fs = new Ext.FormPanel({
        frame: false,
        title:'Account Information',
        labelAlign: 'right',
        labelWidth: 150,
        width:'70%',
       id:'accountinfoform',
        fileUpload:true,
        waitMsgTarget: true,
        header:false,
        border:false,	
        autoHeight:true,
        listeners: {
        	beforerender:  function(){      
        	this.form.load({
            url:'/A_GetAccountInfoJSON.jsp', 
            method:'GET',
            success:function(form, action) {
            },        	
            failure:function(form, action) {
                Ext.MessageBox.alert('Message', 'Load failed');
          	  }
        	});
        }
        }, 
        	
        
        items: [
            new Ext.form.FieldSet({
                title: 'Account Information',
                defaultType: 'textfield',
				autoHeight:true,
				hideBorders:true,
				hideLabel:true, 
			   items: [{
                        fieldLabel: 'Email',
                        name: 'email',
                        readOnly:true,
                        xtype:'displayfield',
                        width:250
                    }, {
                        fieldLabel: 'Nickname',
                        name: 'nickname',
                        allowBlank: false,
                        width:250,
                        vtype:'nicknameUnique'
                    }, {
                        fieldLabel: 'Name',
                        name: 'name',
                        width:250
                    }, {
                        fieldLabel: 'Zip Code',
                        name: 'zip',
                        width:250
                    },
                    {
                        fieldLabel: 'My URL',
                        name: 'webURL',
                        vtype: 'url',
                        width:250
                    },
                    {
 						xtype:'box'
						 ,anchor:''
						 ,isFormField:true
						 ,fieldLabel:'Current Icon'
						 ,autoEl:{
						 	tag:'div', children:[{
						 		id: 'logourlimg',
						 		tag:'img'
						 		,qtip:'You can also have a tooltip on the image'
						 		,src:usrlogourl
						 	}]
						   }
					},
                    {
                        fieldLabel: 'Your Icon',
                        name: 'logoURLFile',
                        inputType: 'file',
                        width:250
                    },
                    {
                    	xtype: 'textarea',
                    	fieldLabel: 'About Me',
                        name: 'aboutMe',
                        width:250
                    },
                    {
                    	xtype: 'checkbox',
                    	fieldLabel: 'Receive Newsletter',
                        name: 'getNewsLetter',
                        width:90
                    },
                    {
                    	xtype: 'checkbox',
                    	fieldLabel: 'Email On New Suggestion',
                        name: 'emailOnSuggestion',
                        width:90
                    },
                    {
                    	xtype: 'checkbox',
                    	fieldLabel: 'Receive Site Announcements',
                        name: 'emailOnAnnouncement',
                        width:90
                    }
                    
                    ]
             })]
     });
     
   var submit = fs.addButton({
        text: 'Submit',
        disabled:false,
        handler: function(){
            fs.form.submit({
                url:'A_SetAccountInfoJSON.jsp',	
                waitMsg:'Saving Data...',
                success: function (form, action) {
                	Ext.getDom('logourlimg').src = action.result.newlogo;
                    Ext.MessageBox.alert('Message', 'Your Information Has Been Saved');
                },
                failure:function(form, action) {
                    Ext.MessageBox.alert('Message', 'Save failed');
                }
            });
        }
    });
    
;
     return fs;
}

function getNoSuggDashboard()
{
	   		return new Ext.Container({
   							layout:'table',
   							defaults:{ bodyStyle:'padding:20px;padding-top:10px;padding-bottom:10px;border-width:0px;vertical-align:top'},
   							layoutConfig:{ columns:3},
   							extraCls:'noBorder',
   							id:'UHtablebody',

   							items:[
   							{
   								colspan:3,
   								html:'<h1>Your Dashboard</h1>'
   							},
   							{
   								colspan:3,
   						
   								id:'acctdetails',
   								items: new Ext.Panel({
						        title: 'Your Account Details',
						        collapsible:false,
						        applyTo: 'userstats',					
						        frame:'true',			 
						        width:735      
						   		 })
   							},	{
   								colspan:3,
   						
   								id:'nosugg',
   								items: new Ext.Panel({
						        title: 'Getting Personalized Suggestions',
						        collapsible:false,
						        applyTo: 'nosuggs',					
						        frame:'true',			 
						        width:735      
						   		 })
   							}
   							]
   							});
   							
   							
}

function getUserDashboard()
{
   		return new Ext.Container({
   							layout:'table',
   							defaults:{ bodyStyle:'padding:20px;padding-top:10px;padding-bottom:10px;border-width:0px;vertical-align:top'},
   							layoutConfig:{ columns:3},
   							extraCls:'noBorder',
   							id:'UHtablebody',

   							items:[
   							{
   								colspan:3,
   								html:'<h1>Your Dashboard</h1>'
   							},
   							{
   								colspan:3,
   						
   								id:'acctdetails',
   								items: new Ext.Panel({
						        title: 'Your Account Details',
						        collapsible:false,
						        applyTo: 'userstats',					
						        frame:'true',			 
						        width:735      
						   		 })
   							},
   							{
   								items: new Ext.Panel({
						        title: 'Your Personal Suggestions',
						        collapsible:false,
						        applyTo: 'panel',
						        tabTip: 'test',
						        
						        frame:'true',
						        width:330
						        
						   		 }),
						   		width:385
   							},
   							{
   								html:'',
   								width:20
   							},
   							{
								items: new Ext.Panel({
						        title: 'Recent Ratings In Your Favorite Places',
						        collapsible:false,
						        applyTo: 'panel2',
						        tabTip: 'test',
						        frame:'true',
						        width:330
						        
						   		 }),
   								width:385
   							},

   							{
   								items: new Ext.Panel({
						        title: 'Ratings By Friends',
						        collapsible:false,
						        applyTo: 'panel3',
						        tabTip: 'test',
						        frame:'true',
						        width:330
						        
						   		 })
   							},
   							{
   								html:'',
   								width:20
   							},
   							{
   								items: new Ext.Panel({
						        title: 'People Like Me',
						        collapsible:false,
						        applyTo: 'panel4',
						        tabTip: 'test',
						        frame:'true',
						        width:330
						        
						   		 })
   							} 							
   							]
   						}
			);
}



function removeRPXAccount(acctType,acctID,trID)
{
	Ext.Ajax.request({
    url: 'RemoveExtAcct.jsp?type='+acctType+'&rpxid='+acctID,
    timeout: 5000,
    method: 'GET',
    success: function(xhr) {
        	var item = Ext.get(trID);
			item.fadeOut({remove:true});
    }
}); 
}

function removeAccount(acctType)
{
	Ext.Ajax.request({
    url: 'RemoveExtAcct.jsp?type='+acctType,
    timeout: 5000,
    method: 'GET',
    success: function(xhr) {
        	var item = Ext.getDom(acctType+'status');
			item.innerHTML = 'Link removed';
    }
}); 
}


function showAddAccountInfo(site,sitelabel)
{       // create the window on the first click and reuse on subsequent clicks
        var f = new Ext.FormPanel({
           labelWidth: 100,
           url: '/MFSAjaxServlet?ACTION=UPDATEEXTACCOUNT',
           frame: true,
           defaults: {width: 150},
           items: [{xtype: 'textfield',
                    fieldLabel: 'Account Name',
                    name: 'USER',
                    allowBlank:false},
                   
                   {xtype: 'textfield',
                    inputType: 'password',
                    fieldLabel: 'Password',
                    name: 'PASS',
                    allowBlank: false},
                    {xtype: 'hidden', name:'ACCTTYPE', value: site}
                    ],
           buttons: [{text: 'Submit', 
               minWidth: 75,
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Submitting...',
	               			success: function(form, action) {
	       						dlg.close();
	       						Ext.getDom(site+'status').innerHTML = 'Account Linked';
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            case Ext.form.Action.SERVER_INVALID:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {dlg.close()}}]
       });

       var dlg = new Ext.Window({
           height: 200,
           width: 300,
           closable: true,
           closeAction : 'hide', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Update '+sitelabel+' account information',
           layout: 'fit',
           items: f
       });
       dlg.show();
}

function showInviteFriend()
{       // create the window on the first click and reuse on subsequent clicks
        var f = new Ext.FormPanel({
           labelWidth: 150,
           url: '/A_InviteFriends.jsp',
           frame: true,
           defaults: {width: 250},
           items: [
           			{width:450,html:'<p>One of the keys to our personalized suggestions is to get as many ratings and people as possible using the site.  By inviting some friends you\'ll help make the site more valuable for yourself and others.  THANKS!</p><br/>'},
           
           			{xtype: 'textfield',
                    fieldLabel: 'Friend\'s Email',
                    name: 'email1',
                    vtype: 'email',
                    allowBlank: false},
                   
           			{xtype: 'textfield',
                    fieldLabel: 'Friend\'s Email',
                    name: 'email2',
                    vtype: 'email',
                    allowBlank: true},
                   
           			{xtype: 'textfield',
                    fieldLabel: 'Friend\'s Email',
                    name: 'email3',
                    vtype: 'email',
                    allowBlank: true}
                     

                    ],
           buttons: [{text: 'Send Invitations',
               minWidth: 75,
               handler: function() {
               		if (f.getForm().isValid())
               		{
               			f.getForm().submit({
               				waitMsg:'Logging In...',
	               			success: function(form, action) {
		       						 Ext.Msg.alert("Success","Your Invitations Have Been Sent.");
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            case Ext.form.Action.SERVER_INVALID:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {inviteDlg.close()}}]
       });

       var inviteDlg = new Ext.Window({
           height: 300,
           width: 500,
           closable: true,
           closeAction : 'hide', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Invite Friends',
           layout: 'fit',
           items: f
       });
       inviteDlg.show();
} //end showInviteFriend

function showNewUserWelcome()
{
	Ext.MessageBox.show({
           title: 'Welcome',
           width: 600,
           msg: '<h1>Welcome to theSUGGESTR.com</h1><span class="paratext">We appreciate you joining our new site and hope you find our suggestions useful.  '+
           '<br/><br/>To help you get started here are a list of ways that make it easy to get accurate suggestions quickly.'+
           '<ul class="normallist"><li><a href="T_RatePlaces.jsp">Rate</a> at least 20 businesses.</li>'+
           '<li>Add new favorite cities.</li>'+
           '<li>Invite friends to join.</li>'+
           '</ul><br/>Don\'t forget you can also get assistance by clicking the <a href="T_MoreInfo.jsp">Learn More</a> link.'+
           
           '</span>',
           buttons: Ext.MessageBox.OK,
           animEl: Ext.getBody()
       });
	
}

function showGoogleCallback()
{
	Ext.MessageBox.show({
           title: 'Welcome',
           width: 400,
           msg: 'Your account has been successfully linked with Google.<br/><br/>Your Maps should be available via Google shortly.',
           buttons: Ext.MessageBox.OK,
           animEl: Ext.getBody()
       });
	
}var ratingGrid = false;

function initUserProfile(uid,usrnick,usrlogourl,isBlog)
{
	
	var hideBlog = !isBlog;
 
 var divtitle="Recent Suggestions for "+usrnick;
 if(isBlog)
 	divtitle="Recent Blog Posts by " +usrnick;
     var viewport = new Ext.Container({
        renderTo:'main',
        layout:'fit',
        height: 800,		//need to figure out how to get it working dynamically
        id: 'upvport',
        items:[{
            xtype: 'grouptabpanel',
    		tabWidth: 130,
    		activeGroup: 0,
    		id: 'userprofile',
    		layoutOnTabChange: true,
	
    		items: [{
    			mainItem: 0,
    			deferredRender: false, 
    			id: 'upgroup',
					 defaults:{autoScroll: true},
      				 plain:true,
    			items: [
                {
                    title: 'Profile',
                    tabTip: 'View User Profile',
                    layout: 'fit',
					id: 'profileid',
					deferredRender: false, 
   					items:[
   						{
   							layout:'table',
   							defaults:{ bodyStyle:'padding:5px;padding-left:20px;padding-top:10px;border-width:0px;vertical-align:top'},
   							layoutConfig:{ columns:3},
   							extraCls:'noBorder',
   							id:'UPtablebody',
							
   							items:[
   							{
   								colspan:3,
   								html:'<h1>'+usrnick+'\'s Profile&nbsp;<div id="followbutton"></div> </h1>'
   							},
   				
   							{
   								colspan:3,
   								items: new Ext.Panel({
   							    title: 'Stats',
						        collapsible:false,
						        applyTo: 'userstats',					
						        frame:'true',			 
						        width:735      
						   		 })
   							},
  							 							{
   								items: new Ext.Panel({
						        title: 'Recent Ratings by '+usrnick,
						        applyTo: 'recentratings',
						        tabTip: 'test',
						        frame:'true',
						        width:330,
						        height:240
						        
						   		 }),
						   		width:385
   							},
   							{
   								html:'',
   								width:20
   				 			},
   							{
								items: new Ext.Panel({
						        title: divtitle,
						         applyTo: 'panel',
						        tabTip: 'test',
						        frame:'true',
						        width:330,
						        height:240
						        
						   		 }),
						   		width:385
   							},

              				]
            		}
            		]
			},
			
        		{
        			title: 'All Ratings',
        			tabtip: 'View All Ratings',
        			style: 'padding: 10px;',
        			listeners:{
                    	activate: function(p)
                    	{
                    		if (ratingGrid == false)
                    		{
	                    		p.add(createRatingsGrid(uid,usrnick));
	                    		p.doLayout();
	                    	}
                    	}
                    }
        		}
        		,
        		{
        			title: 'Following',
        			tabtip: 'View who '+usrnick+' is following.',
        			autoLoad: {url:'/A_UPFollowing.jsp?profileid='+uid,script:true,
                    	callback: function() { }
                    	}
                    	
        		}
        		,
        		{
        			title: 'Followers',
        			tabtip: 'View '+usrnick+'\s followers.',
        			html: 'tmp',
        			autoLoad: {url:'/A_UPFollowers.jsp?profileid='+uid,script:true,
                    	callback: function() { }
                    	}
        		},
        		
            		{
            			title: 'Tag Cloud',
						id:'tagpanel',
						deferredRender: false,
						style: 'padding: 10px;',
						items:[ 
						{
   								
   								html:'<h1>'+usrnick+'\'s Tag Cloud </h1><div id="utagcloud"></div>'
   						},
						new Ext.Panel({
				        title: usrnick+'\'s Tag Cloud',
				        applyTo: 'tagclouddiv',
				        frame:'true',
				        width:735,
				        deferredRender: false
				   		 })]
   							 
   					}
        		
            		
			
			]
		}]
	}]
    });
    
    var tCloudStore = getTagCloudStore(uid);
    
       	var cloud = new Ext.ux.TagCloud({
           store: tCloudStore, 
           displayField: 'tagtext', 
           weightField: 'count', 
           displayWeight: true
           }
   	);
   	
   	cloud.render('utagcloud');
   	
   	tCloudStore.load();
   
    
}

function resizeUPWindow(h)
{
	var vport = Ext.getCmp('upvport');
	vport.setHeight(h+40);
	vport.doLayout();
}

function changeUPTab(tabID)
{
	var panel = Ext.ComponentMgr.get('upgroup');
	panel.setActiveTab(tabID);
}

function changeToFollowersUP()
{
	var panel = Ext.ComponentMgr.get('upgroup');
	panel.setActiveTab(3);
}

function changeToFollowingUP()
{
	var panel = Ext.ComponentMgr.get('upgroup');
	panel.setActiveTab(2);
}

function getTagCloudStore(userid)
{
        var tcStore = new Ext.data.JsonStore({
    // store configs
	    autoDestroy: true,
	    url: '/MFSAjaxServlet?ACTION=GETUSERTAGCLOUD&userid='+userid,
	    storeId: 'tcStore',
	    // reader configs
	    root: 'Result',
	    idProperty: 'tagid',  
	    fields: ['tagid','tagtext','count']
	});   
	return tcStore;
}
var ratingGrid = false;
var markersmainpage=[];
var markersbestof=[];
var baseHeightNP = 760;

function showInfoMainPage(id)
{

	var m= markersmainpage[id-1];
	GEvent.trigger(m, 'click'); 
}

function showInfoBestOfPage(id)
{

	var m= markersbestof[id-1];
	GEvent.trigger(m, 'click'); 

}

function changeNPTab(tabID)
{
	var panel = Ext.ComponentMgr.get('npgroup');
	panel.setActiveTab(tabID);
}

function initNeigborhoodPage(city,state,lat,lng,uid)
{

	var tCloudStore = getNPTagCloudStore(lat,lng);

     var viewport = new Ext.Container({
        layout:'fit',
          
        items:[{
            xtype: 'grouptabpanel',
    		tabWidth: 150,
    		activeGroup: 0,
    		id: 'npage',
    		layoutOnTabChange: true,
	
    		items: [{
    			mainItem: 0,
    			id: 'npgroup',
					 defaults:{autoScroll: false},
					 deferredRender: false,
      				 plain:true,
    			items: [
                {
                    title: city,
                    tabTip: 'Overview of '+city+', '+state,
                    layout: 'fit',
					id: 'npdashboard',
					listeners:{ activate:function(p) {resizeNPWindow(baseHeightNP);}},
   					items:[
   						{
   							layout:'table',
   							defaults:{ bodyStyle:'padding:5px;padding-left:20px;padding-top:10px;border-width:0px;vertical-align:top'},
   							layoutConfig:{ columns:3},
   							extraCls:'noBorder',
   							id:'NPtablebody',
							
   							items:[
   							{
   								colspan:3,
   								html:'<h1><div id="followbutton" style="float:right"></div>'+city+', '+state+' </h1>'
   							},
   							{
   								items: new Ext.Panel({
							        title: 'Stats',
							        collapsible:false,
							        applyTo: 'stats',					
							        frame:'true',
							        height:250,			 
							     	width:330    
						   		}),
						   		witdth:380 
						   		
   							},
   							{
   								width:10,
   								html:''
   							},
   							{
   								items: new Ext.Panel({
					                layout: 'fit',
					                title: 'Map of '+city+' '+state,
					                width:330,
					                height:230,
					                items: {
					                    xtype: 'gmappanel',
					                    region: 'center',
					                    zoomLevel: 12,
					                    gmapType: 'map',id:'gMapMainPage',
					                    mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
					                    mapControls: ['GSmallZoomControl3D','NonExistantControl']
					                }
					            })
						   		
   							},
   							{
   								items: new Ext.Panel({
							        title: 'Most Popular Places',
							        collapsible:false,
							        applyTo: 'popular',					
							        frame:'true',
							        height:250,			 
							     	width:330    
						   		}),
						   		width:380 
						   		
   							},
   							{
   								width:10,
   								html:''
   							},
   							{
   								items: new Ext.Panel({
							        title: 'Recent Ratings',
							        collapsible:false,
							        applyTo: 'ratings',					
							        frame:'true',
							        height:250,			 
							     	width:330    
						   		}),
						   		witdth:380 
						   		
   							}
              				]
            		}
            		]
			},
			
        		{
        			title: 'Best Of',
        			tabtip: 'Best Of',
        			id:'bestofpanel',
        			style: 'padding: 10px;',
        			border:false,
        			deferredRender: false,
        			listeners: {
        				activate : function()
        				{
        					 addDestToBestOfPage();
        					 var newpanel = Ext.get('bestof');
        					 resizeNPWindow(newpanel.getHeight()+60);
   						}
        			},
					items: [{
						layout: 'column',
						border:false,
        		
						items:[{
							columnWidth:.5,
							items: new Ext.Panel({
						        title: 'Best Of',
						        collapsible:false,
						        contentEl: 'bestof',					
						        frame:'true', 
						        deferredRender: false
							})
							},
							{
								columnWidth:.03,
								html: '&nbsp;',
								border:false
        		
							},
							{
							columnWidth:.47,
							items: new Ext.Panel({
				                layout: 'fit',
				                title: 'Best of '+city+' '+state,
				                width:351,
				                deferredRender: false,
				                header: false,
				                height:330,
				                items: {
				                		deferredRender: false,
      									width:330,
					                    xtype: 'gmappanel',
					                    region: 'center',
					                    zoomLevel: 12,
					                    gmapType: 'map',
					                    id:'gMapBestOfPage',
					                    mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
					                    mapControls: ['GSmallZoomControl3D','NonExistantControl']
					                }
					            })
					       }
					       ]
					    }]
												
        		}
        		, 
        		{
        			title: 'Top Locals',
        			tabtip: 'Top Locals',
        			style: 'padding: 10px;',
        	        items: new Ext.Panel({
				        title: 'Top Locals',
				        collapsible:false,
				        applyTo: 'toplocals',					
				        frame:'true'
					}),
					listeners:{ activate:function(p) {resizeNPWindow(baseHeightNP);}}
   					
        		}
        		,
        		{
        			title: 'Tag Cloud',
        			tabtip: 'Tag Cloud',
        			style: 'padding: 10px;',
        			listeners:{ activate:function(p) {resizeNPWindow(baseHeightNP);}},
   				
        			items:  new Ext.Panel({
        				   items: new Ext.ux.TagCloud({
					           store: tCloudStore, 
					           displayField: 'tagtext', 
					           weightField: 'count', 
					           displayWeight: true,
					           listeners: {
					           	tagselect : function(cloud, record, index){
					                //alert('You clicked on "'+record.get('tagtext')+'"!');
					                var loc = city+" "+state;;
					                window.location.href = 'T_Search.jsp?searchfor='+record.get('tagtext')+'&searchwhere='+loc;
					              }
					           }
					       }),
					       title: 'Tag Cloud for '+city
         			})
                    	
        		}

        		
            		
			
			]
		}]
	}]
    });
    
    if (uid>=1)
    {
    	var grp = Ext.getCmp('npgroup');
    	
    	grp.add(
        		{
        			title: 'My '+city,
        			tabtip: 'My City',
        			id: 'mynpdashboard',
        			listeners:{ activate:function(p) {resizeNPWindow(baseHeightNP);}},
   				
        			layout: 'fit',
   					items:[
   						{
   							layout:'table',
   							defaults:{ bodyStyle:'padding:5px;padding-left:20px;padding-top:10px;border-width:0px;vertical-align:top'},
   							layoutConfig:{ columns:3},
   							extraCls:'noBorder',
   							id:'myNPtablebody',
   							items:[
   							{
   								colspan:3,
   								html:'<h1><div id="followbutton" style="float:right"></div>My '+city+', '+state+' </h1>'
   							},
   							{
   								  items: new Ext.Panel({
							        title: 'My Personal Suggestions',
							        collapsible:false,
							        renderTo: 'mynpsugg',					
							        frame:'true',
							        height:250,			 
							     	width:330,
				     		     	autoLoad: {url:'/I_MySuggestionPanel.jsp?lat='+lat+'&lng='+lng,scripts:true,
                 							callback: function() { }
                 						}    
						   		}),
						   		width:380 
   							},
   							{
   								width:10,
   								html:''
   							},
   							{
   								  items: new Ext.Panel({
							        title: 'My Friends Ratings',
							        collapsible:false,
							        applyTo: 'myfriendratings',					
							        frame:'true',
							        height:250,			 
							     	width:330    
						   		}),
						   		width:380 
   							},
   							 {
   								  items: new Ext.Panel({
							        title: 'My Wish List',
							        collapsible:false,
							        applyTo: 'mywishlist',					
							        frame:'true',
							        height:250,			 
							     	width:330
				     				
                 					}),    
						   		
						   		width:380 
   							},
   							{
   								width:10,
   								html:''
   							}
   							,
   							{
   								  items: new Ext.Panel({
							        title: 'Locals Like Me',
							        collapsible:false,
							        applyTo: 'simusers',					
							        frame:'true',
							        height:250,			 
							     	width:330    
						   		}),
						   		width:380 
   							}
   							]
   						}]
        		});
    }
 
    viewport.render('main');
 
    tCloudStore.load();
    addDestToMainPage();
    
    
}

function resizeNPWindow(h)
{
	var vport = Ext.getCmp('npage');
	vport.setHeight(h+40);
	vport.doLayout();
}

function getNPTagCloudStore(lat,lng)
{
        var tcStore = new Ext.data.JsonStore({
    // store configs
	    autoDestroy: true,
	    url: '/MFSAjaxServlet?ACTION=GETNPTAGCLOUD&lat='+lat+'&lng='+lng,
	    storeId: 'tcStore',
	    // reader configs
	    root: 'Result',
	    idProperty: 'tagid',  
	    fields: ['tagid','tagtext','count']
	});   
	return tcStore;
}
var ratingGrid = false;
var suggPanel;
var suggPanel2;

function initRatePlaces(uid,currentPage,isNewUser)
{

	suggPanel = new Ext.Panel({
			        title: 'Your Suggestibility',
			        collapsible:false,
			        contentEl: 'suggestibility',					
			        frame:'true',			 
			        width:245      
		   		 });
	suggPanel2 = new Ext.Panel({
		        title: 'Your Suggestibility',
		        collapsible:false,
		        contentEl: 'suggestibility2',					
		        frame:'true',			 
		        width:245      
	   		 });
	   		 
	 var newuser = '';
	 if (isNewUser==true)
	 	newuser = '<br><span style="font-size:120%">Thanks for registering!  Our number one goal is to provide you with your own Personalized Suggestions, but to do this we need you to rate some places first so we can learn about your taste\'s.  <br><br>You can start by telling us about some of your favorite places (below) or you can <a href="javascript:switchToManual();">click here</a> to rate some popular place. <BR><BR>Once you are done you can <a href="T_UserHomePage.jsp">continue to your home page</a> but remember that rating places is the key to receiving accurate suggestions!</span><br/><br/>';
	 	  		 

     var viewport = new Ext.Container({
        renderTo:'main',
        layout:'fit',
       	height:1300,		//should be dynamic
       	tabWidth: 130,
        items:[{
            xtype: 'grouptabpanel',
    		tabWidth: 130,
    		activeGroup: 0,
    		id: 'rateplacepanel',
    		layoutOnTabChange: true,
			  deferredRender: false,
    		items: [{
    			mainItem: 0,
    			  deferredRender: false,
    			id: 'rateplacesgroup',
					 defaults:{autoScroll: true},
      				 plain:true,
    			items: [
                {
                    title: 'Rate Places',
                    tabTip: 'Rate Places',
                    layout: 'fit',
                    deferredRender: false,
                    defaults:{ bodyStyle:'padding:20px;padding-top:10px;border-width:0px;vertical-align:top'},   					
					 id:'placelistman',
                    items:[{
	                    layout: 'table',
	                   
	                    layoutConfig:{ columns:2},
	               		width:790,
						defaults:{ bodyStyle:'padding:0px;padding-top:10px;border-width:0px;vertical-align:top'},   					
						items:[
							{
							  colspan:2,
							  html:'<h1>Improve Your Suggestions - Rate Places</h1>'+newuser
							},
							{
								bodyStyle:'padding:5px;border-width:0px;',
								id:'rateplacetab',
							 	autoLoad: {url:'/A_RatePlacesMans.jsp',scripts:true},
							 	width:500
							},
							{
								
								items:
								[
								 suggPanel,
	
								 new Ext.Panel({
								 	title: 'Looking to rate someplace else?',
								 	id:'moreplaces',
								 	defaults:{ bodyStyle:'margin-top:10px;padding:20px;padding-top:10px;border-width:0px;vertical-align:top'},   					
									items:[
									{
										html:'Know the name of what you want to rate?<br/><a href="javascript:showQuickRate()">Click Here.</a>'+
										'<br/><br/>Want to add a new business?<br/><a href="javascript:showAddPlace()">Click Here.</a>'
									}
									]
									})
								]
							}
						   	 
					
						]
					}]
				},
				 {
                    title: 'Popular Ratings',
                    tabTip: 'Popular Ratings',
                    layout: 'fit',
                    deferredRender: false,
                    defaults:{ bodyStyle:'padding:20px;padding-top:10px;border-width:0px;vertical-align:top'},   					
					 id:'placelist',
                    items:[{
	                    layout: 'table',
	                    deferredRender: false,
	                    layoutConfig:{ columns:2},
	               		width:790,
						defaults:{ bodyStyle:'padding:0px;padding-top:10px;border-width:0px;vertical-align:top'},   					
						items:[
							{
							  colspan:2,
							  html:'<h1>Improve Your Suggestions - Rate Places</h1>'
							},
							{
								bodyStyle:'padding:5px;border-width:0px;',
								id:'rateplacetab2',
							 	autoLoad: {url:'/A_RatePlaces.jsp',scripts:true},
							 	width:500
							},
							{
								
								items:
								[
								 suggPanel2,
								 new Ext.Panel({
								 	title:'Rate More Places?',
								 	id:'ratemore2',
								 	defaults:{ bodyStyle:'margin-top:10px;padding:20px;padding-top:10px;border-width:0px;vertical-align:top'},   					
					
									items:[
			        				{
			        					html:'Click below to load more places to rate.'
			        				},
									new Ext.Button({
									text:'Rate More Places',
									id:'ratemorebtn2',
									handler:function(){
										 currentPage = currentPage + 1;
									  	 Ext.get('rateplacetab2').load({url:'/A_RatePlaces.jsp?pagenum='+(currentPage),scripts:true});
										}
									})
									]
								 }),
								 new Ext.Panel({
								 	title: 'Looking to rate someplace else?',
								 	id:'moreplaces2',
								 	defaults:{ bodyStyle:'margin-top:10px;padding:20px;padding-top:10px;border-width:0px;vertical-align:top'},   					
									items:[
									{
										html:'Know the name of what you want to rate?<br/><a href="javascript:showQuickRate()">Click Here.</a>'+
										'<br/><br/>Want to add a new business?<br/><a href="javascript:showAddPlace()">Click Here.</a>'
									}
									]
									})
								]
							}
						   	 
					
						]
					}]
				},
				{
					contentEl: 'ffplugin',
								
					title: 'FireFox Plug-In'
				}
				]}	
				]
			}] 
  	});

}

function addRatePlacesCity(loc,id)
{
	var fullLoc = loc;
	if (loc.length > 14)
		loc = loc.substring(0,11)+ '...';
	var cityList = Ext.ComponentMgr.get('rateplacesgroup');
	var pane = new Ext.Panel({
					layout: 'fit',
		      		title: loc,
		      		tabTip: fullLoc,
                    iconCls: 'x-icon-tickets',
                    style: 'padding: 10px;',
                    items:[{
	                    layout: 'table',
	                   
	                    layoutConfig:{ columns:2},
	               		width:790,
						defaults:{ bodyStyle:'padding:20px;padding-top:10px;border-width:0px;vertical-align:top'},   					
						items:[
							{
							  colspan:2,
							  html:'<h1>Improve Your Suggestions - Rate Places</h1>'
							},
							{
								autoLoad: {url:'/A_RatePlaces.jsp',scripts:true},
							 	width:420
							},
							{
								items:suggPanel
							}

					
						]
					}]
              });
    cityList.add(pane);
    cityList.doLayout();
}
 
function doAjax() 
{
	Ext.Ajax.request({
		url : 'MFSAjaxServlet' , 
		params : { ACTION : 'GETSUGGESTIBILITY' },
		method: 'GET',
		success: function ( result, request) { 
			var jsonData = Ext.util.JSON.decode(result.responseText);
			var score = jsonData.Result[0].score;
			var count = jsonData.Result[0].numRatings;
			var oldScore = Ext.getDom('suggestibilityscore').innerHTML;
			var oldNumRatings = Ext.getDom('placesrated').innerHTML;
			if (score > oldScore)
			{
				updateScore(score);
			}
			if (count > oldNumRatings)
			{
				updateCount(count);
			}
			
		},
		failure: function ( result, request) { 
			Ext.MessageBox.alert('Failed', 'Successfully posted form: '); 
		} 
});
}
		
function updateScore(newScore)
{
			Ext.get('suggestibilityscore').highlight("ff009c", {
			    attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
			
			    endColor: "EFEFDF",
			    easing: 'easeIn',
			    duration: 1
			});
			Ext.getDom('suggestibilityscore').innerHTML = newScore;
			Ext.get('suggestibilityscore2').highlight("ff009c", {
			    attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
			
			    endColor: "EFEFDF",
			    easing: 'easeIn',
			    duration: 1
			});
			Ext.getDom('suggestibilityscore2').innerHTML = newScore;
}

function updateCount(newCount)
{
			Ext.get('placesrated').highlight("ff009c", {
			    attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
			
			    endColor: "EFEFDF",
			    easing: 'easeIn',
			    duration: 1
			});
			Ext.getDom('placesrated').innerHTML = newCount;
			
			Ext.get('placesrated2').highlight("ff009c", {
			    attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
			
			    endColor: "EFEFDF",
			    easing: 'easeIn',
			    duration: 1
			});
			Ext.getDom('placesrated2').innerHTML = newCount;
}

function initRatePlacesManual(uid)
{
	var destStore = new Ext.data.JsonStore({
    // store configs
	    autoDestroy: true,
	    url: '/MFSAjaxServlet?ACTION=GETTAGSCATS&TYPE=LIKE',
	    storeId: 'myDestStore',
	    // reader configs
	    root: 'Result',
	    idProperty: 'categoryID',  
	    fields: ['description','categoryID']
	});  
	
    var destlist1 = new Ext.form.ComboBox({
     	store: destStore,
        displayField:'description',
        valueField:'categoryID',
        typeAhead: false,
        forceSelection: true,
        mode: 'remote',
        minChars: 2,
        triggerAction: 'all',
        emptyText:'Enter a Business Name',
        selectOnFocus:true,
        id:'rbox1',
        triggerClass:'displayNone',
        allowBlank: false,
        width:250,
        flex:1,
        listeners:{
        	'select': function(combo,record,index)
        	{
        		var p = new	Ext.Panel({
		           	id:'r1ratingdiv',
		         	html:'',
		           	width:200,
		           	border: false,
		           	flex:1
		        });
		        p.render('r1rating');
		        Ext.getCmp('r1ratingdiv').body.load({
        		url : '/I_DestRank.jsp?DestID='+record.id ,
        		scripts: true
        		});
 
        	}
        }
        });
        
           var destlist2 = new Ext.form.ComboBox({
     	store: destStore,
        displayField:'description',
        valueField:'categoryID',
        typeAhead: false,
        forceSelection: true,
        mode: 'remote',
        minChars: 2,
        triggerAction: 'all',
        emptyText:'Enter a Business Name',
        selectOnFocus:true,
        id:'rbox2',
        triggerClass:'displayNone',
        allowBlank: false,
        width:250,
        flex:1,
        listeners:{
        	'select': function(combo,record,index)
        	{
        		var p = new	Ext.Panel({
		           	id:'r2ratingdiv',
		         	html:'',
		           	width:200,
		           	border: false,
		           	flex:1
		        });
		        p.render('r2rating');
		        Ext.getCmp('r2ratingdiv').body.load({
        		url : '/I_DestRank.jsp?DestID='+record.id ,
        		scripts: true
        		});
 
        	}
        }
        });
        
                   var destlist3 = new Ext.form.ComboBox({
     	store: destStore,
        displayField:'description',
        valueField:'categoryID',
        typeAhead: false,
        forceSelection: true,
        mode: 'remote',
        minChars: 2,
        triggerAction: 'all',
        emptyText:'Enter a Business Name',
        selectOnFocus:true,
        id:'rbox3',
        triggerClass:'displayNone',
        allowBlank: false,
        width:250,
        flex:1,
        listeners:{
        	'select': function(combo,record,index)
        	{
        		var p = new	Ext.Panel({
		           	id:'r3ratingdiv',
		         	html:'',
		           	width:200,
		           	border: false,
		           	flex:1
		        });
		        p.render('r3rating');
		        Ext.getCmp('r3ratingdiv').body.load({
        		url : '/I_DestRank.jsp?DestID='+record.id ,
        		scripts: true
        		});
 
        	}
        }
        });
         
    destlist1.render('r1input');
    destlist2.render('r2input');
    destlist3.render('r3input');
}

function rateMoreMan()
{
       Ext.getCmp('rateplacetab').body.load({url:'/A_RatePlacesMans.jsp',scripts:true});
}

function switchToPlugin()
{
	var panel = Ext.ComponentMgr.get('rateplacesgroup');
	panel.setActiveTab(2);
}

function switchToManual()
{
	var panel = Ext.ComponentMgr.get('rateplacesgroup');
	panel.setActiveTab(1);
}



var ratingGrid = false;
var suggPanel;

function initFirstRatePlaces(uid,currentPage)
{

	suggPanel = new Ext.Panel({
			        title: 'Your Suggestibility',
			        collapsible:false,
			        contentEl: 'suggestibility',					
			        frame:'true',			 
			        width:320,
			        id:'suggestibility2'    
		   		 });

     var viewport = new Ext.Container({
        renderTo:'main',
        layout:'fit',
       	height:1400,		//should be dynamic
       	tabWidth: 130,
        items:[{
            xtype: 'grouptabpanel',
    		tabWidth: 130,
    		activeGroup: 0,
    		id: 'rateplacepanel',
    		layoutOnTabChange: true,
			
    		items: [{
    			mainItem: 0,
    			
    			id: 'rateplacesgroup',
					 defaults:{autoScroll: true},
      				 plain:true,
    			items: [
                {
                    title: 'Welcome',
                    tabTip: 'Welcome',
                    layout: 'fit',
                    defaults:{ bodyStyle:'padding:20px;padding-top:10px;border-width:0px;vertical-align:top'},   					
					 id:'placelist',
                    items:[{
	                    layout: 'table',
	                   
	                    layoutConfig:{ columns:2},
	               		width:790,
						defaults:{ bodyStyle:'padding:20px;padding-top:10px;border-width:0px;vertical-align:top'},   					
						items:[
							{
							  colspan:2,
							  html:'<h1>Welcome to theSUGGESTR.com</h1><br><span class="largeText">Thanks for registering!  Our number one goal is to provide you with your own Personalized Suggestions, but to do this we need you to rate some places first so we can learn about your taste\'s.  <br><br>Start by rating some places from your hometown (listed below) or <a href="javascript:showQuickRate()">click here</a> to tell us your favorite places.  <BR><BR>Once you are done you can <a href="T_UserHomePage.jsp">continue to your home page</a> but remember that rating places is the key to receiving accurate suggestions!</span>'
							},
							{
								bodyStyle:'padding:5px;border-width:0px;',
								id:'rateplacetab',
							 	autoLoad: {url:'/A_RatePlaces.jsp',scripts:true},
							 	width:425
							},
							{
								
								items:
								[
								 
								
									new Ext.Panel({
								 	title:'Rate More Places?',
								 	id:'ratemore',
								 	defaults:{ bodyStyle:'margin-top:10px;padding:20px;padding-top:10px;border-width:0px;vertical-align:top'},   					
					
									items:[
			        				{
			        					html:'Click below to load more places to rate.'
			        				},
									new Ext.Button({
									text:'Rate More Places',
									id:'ratemorebtn',
									handler:function(){
										 currentPage = currentPage + 1;
									  	 Ext.get('rateplacetab').load({url:'/A_RatePlaces.jsp?pagenum='+(currentPage),scripts:true});
										}
									})
									]
								 }),suggPanel
								]
							}
						   	 
					
						]
					}]
				}
				]}	
				]
			}]
  	});

}

function addRatePlacesCity(loc,id)
{
	var fullLoc = loc;
	if (loc.length > 14)
		loc = loc.substring(0,11)+ '...';
	var cityList = Ext.ComponentMgr.get('rateplacesgroup');
	var pane = new Ext.Panel({
					layout: 'fit',
		      		title: loc,
		      		tabTip: fullLoc,
                    iconCls: 'x-icon-tickets',
                    style: 'padding: 10px;',
                    items:[{
	                    layout: 'table',
	                   
	                    layoutConfig:{ columns:2},
	               		width:790,
						defaults:{ bodyStyle:'padding:20px;padding-top:10px;border-width:0px;vertical-align:top'},   					
						items:[
							{
							  colspan:2,
							  html:'<h1>Improve Your Suggestions - Rate Places</h1>'
							},
							{
								autoLoad: {url:'/A_RatePlaces.jsp',scripts:true},
							 	width:420
							},
							{
								items:suggPanel
							}

					
						]
					}]
              });
    cityList.add(pane);
    cityList.doLayout();
}
 
function doFTAjax() 
{
	Ext.Ajax.request({
		url : 'MFSAjaxServlet' , 
		params : { ACTION : 'GETSUGGESTIBILITY' },
		method: 'GET',
		success: function ( result, request) { 
			var jsonData = Ext.util.JSON.decode(result.responseText);
			var score = jsonData.Result[0].score;
			var count = jsonData.Result[0].numRatings;
			var oldScore = Ext.getDom('suggestibilityscore').innerHTML;
			var oldNumRatings = Ext.getDom('placesrated').innerHTML;
			if (score > oldScore)
			{
				updateftScore(score);
			}
			if (count > oldNumRatings)
			{
				updateftCount(count);
			}
			
		},
		failure: function ( result, request) { 
			Ext.MessageBox.alert('Failed', 'Successfully posted form: '); 
		} 
});
}
		
function updateftScore(newScore)
{
			Ext.get('suggestibilityscore').highlight("ff009c", {
			    attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
			
			    endColor: "EFEFDF",
			    easing: 'easeIn',
			    duration: 1
			});
			Ext.getDom('suggestibilityscore').innerHTML = newScore;
}

function updateftCount(newCount)
{
			Ext.get('placesrated').highlight("ff009c", {
			    attr: "background-color", //can be any valid CSS property (attribute) that supports a color value
			
			    endColor: "EFEFDF",
			    easing: 'easeIn',
			    duration: 1
			});
			Ext.getDom('placesrated').innerHTML = newCount;
}

 var addPlaceSearch;
 var extResultList;
 var addPlaceSearchDlg;
 
function showAddPlace()
{
	var searchCount=0;
       addPlaceSearch = new Ext.FormPanel({
           labelWidth: 100,
           url: '/MFSAjaxServlet?ACTION=MATCHDEST',
           frame: false,
           flex:1,
           border: false,
           defaults: {width: 250},
              items: [{xtype: 'textfield',
                    fieldLabel: 'Business Name',
                    name: 'what',
                    allowBlank:false,
                    emptyText:'Enter a Business Name'},
                   {xtype: 'textfield',
                    fieldLabel: 'Location',
                    name: 'where',
                    allowBlank:false,
                    emptyText:'Enter a Location'}
                   ],
            buttons: [{text: 'Search',
               minWidth: 75,
               handler: function() {
               		if (addPlaceSearch.getForm().isValid())
               		{
               		
               			if (searchCount==0){
			           		addPlaceSearchDlg.add({
			           			id:'resdivoutter',
			           			width:300,
			           			html:'<div id=\'resdiv\'>Testing Result Panel</div>',
			          			flex:3,
			          			border: false
			           		});
			           		addPlaceSearchDlg.setHeight(500);
			           		addPlaceSearchDlg.center();
			           	}
			           	searchCount++;
		           		addPlaceSearchDlg.doLayout();
               			addPlaceSearch.getForm().submit({
               				waitMsg:'Searching...',
	               			success: function(form, action) {
	               				//alert(action.result.msg);
	       						var obj = Ext.util.JSON.decode(action.result.msg);
	       						
	       						var tplData = '<div id="dest{0}" style="font-size:125%;width:100%;padding-bottom:5px;text-align:left">'+
								'<b><a href="dest{0}.html">{1}</a></b> - {2}</div>';
			                	var tpl = new Ext.DomHelper.createTemplate(tplData);               	
	       						var arLen= obj.Result.length;
	       						if (arLen > 5)
	       							arLen = 5;
	       						if (arLen == 0)
	       						{
	       							doExtLookup();
	       						}
	       						else
	       						{	
		       						Ext.DomHelper.overwrite('resdiv', '<div style=\'font-size:120%\'><b>Are you looking for any of these places?</b><br/> (Click name if find a match)<br/><br/></div>');
									for ( var i=0, len=arLen; i<len; ++i ){
										var did = obj.Result[i].id;
				                		var label = obj.Result[i].name;
				                		var location =  obj.Result[i].city +", "+obj.Result[i].state;
				                		tpl.append('resdiv',[did,label,location]);;
										
									}
						
									Ext.DomHelper.append('resdiv','<br/><div style=\'text-align:center;font-size:130%\'><a href="javascript:doExtLookup();"><b>None of these? Click Here.</a></div>');
								}

	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            case Ext.form.Action.SERVER_INVALID:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {addPlaceSearchDlg.close()}}] 
         });
      
    
      addPlaceSearchDlg = new Ext.Window({
           height: 200,
           width: 450,
           closable: true,
           closeAction : 'close', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Add New Business',
            listeners : {
                show : function(){
                    this.doLayout()
                }
            },
           layout: {
                 type:'vbox',
                 padding:'5',
                 align:'stretch'
             },

           items: [
           		addPlaceSearch
           		] 
       });
       addPlaceSearchDlg.show();

}

function doExtLookup()
{
	Ext.Ajax.request({
		url : 'MFSAjaxServlet' , 
		params : { ACTION : 'MATCHDESTEXT', what : addPlaceSearch.getForm().findField('what').getValue(), where : addPlaceSearch.getForm().findField('where').getValue() },
		method: 'GET',
		success: function ( result, request) { 
				var obj = Ext.util.JSON.decode(result.responseText);	
				extResultList = obj;			
   				var tplData = '<div id="extdest{0}" style="font-size:125%;width:100%;padding-bottom:5px;text-align:left">'+
				'<b><a href="javascript:addExtDest({0});">{1}</a></b> - {2}</div>';
              	var tpl = new Ext.DomHelper.createTemplate(tplData);               	
   				var arLen= obj.Result.length;
   				Ext.DomHelper.overwrite('resdiv', '<div style=\'font-size:120%\'><b>How about any of these places?</b><br/> (Click name if find a match)<br/><br/></div>');
				for ( var i=0, len=arLen; i<len; ++i ){
					var did = i;
              		var label = obj.Result[i].bizName;
              		var location =  obj.Result[i].city +", "+obj.Result[i].state;
              		tpl.append('resdiv',[did,label,location]);
			}
			if (arLen >0)
			{
				Ext.DomHelper.append('resdiv','<br/><div style=\'text-align:center;font-size:130%\'><a href="javascript:doManualLookup();"><b>None of these? Click Here.</a></div>');
			}
		}
		,
		failure: function ( result, request) { 
			Ext.MessageBox.alert('Failed', 'An error has occurred. '); 
		} 
		});
}

function addExtDest(idx)
{
	var sObj = extResultList.Result[idx];
	var name = sObj.bizName;
	var address = sObj.address;
	var city = sObj.city;
	var state = sObj.state;
	var country = sObj.country;
	var zip = sObj.zip;
	var phone = sObj.telephone;
	var url = sObj.webUrl;
	var lat = sObj.lat;
	var lng = sObj.lng;
	addDest(name,address,city,state,country,zip,phone,url,lat,lng);
}


function addDest(name,address,city,state,country,zip,phone,url,lat,lng)
{

		Ext.Ajax.request({
		url : 'MFSAjaxServlet' , 
		params : { ACTION : 'ADDDEST',
					name : name, address : address, city : city, 
					state : state, country : country, zip : zip, phone : phone, url:url,
					lat:lat,lng:lng},
		method: 'GET',
		success: function ( result, request) { 
			var obj = Ext.util.JSON.decode(result.responseText);
			window.location.href = 'dest'+obj.msg+'.html';
		},
		failure: function ( result, request) { 
			Ext.MessageBox.alert('Failed', 'An error has occurred.'); 
		} 
		});	

}

function doManualLookup()
{
	addPlaceSearchDlg.hide();
	var addPlaceManual = new Ext.FormPanel({
           labelWidth: 100,
           url: '/MFSAjaxServlet?ACTION=ADDDEST',
           frame: false,
           flex:4,
           border: false,
           defaults: {width: 250},
              items: [{xtype: 'textfield',
                    fieldLabel: 'Business Name',
                    name: 'name',
                    allowBlank:false,
                    emptyText:''},
                   {xtype: 'textfield',
                    fieldLabel: 'Address',
                    name: 'address',
                    allowBlank:false,
                    emptyText:''},
                   {xtype: 'textfield',
                    fieldLabel: 'Location',
                    name: 'location',
                    allowBlank:false,
                    emptyText:' City State/Region Country'},
                    {xtype: 'textfield',
                    fieldLabel: 'Phone #',
                    name: 'phone',
                    allowBlank:true,
                    emptyText:''},
                    {xtype: 'textfield',
                    fieldLabel: 'Website',
                    name: 'url',
                    allowBlank:true,
                    emptyText:''}
                   ],
            buttons:
             [{text: 'Submit',
               minWidth: 75,
               handler: function() {
               		if (addPlaceManual.getForm().isValid())
               		{
               			addPlaceManual.getForm().submit({
               				waitMsg:'Searching...',
	               			success: function(form, action) {
	               				window.location.href = 'dest'+action.result.msg+'.html';
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            case Ext.form.Action.SERVER_INVALID:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {addDlg.close()}}] 
         });
      
    
      var addDlg = new Ext.Window({
           height: 350,
           width: 450,
           closable: true,
           closeAction : 'close', 
           modal: true,
           frame: true,
           border: false,
           resizable: false,
           title: 'Add New Business',
           layout: {
                 type:'vbox',
                 padding:'5',
                 align:'stretch'
             },

           items: [
           {flex:1,border: false,
            html: '<b>Since we could not find a match you will need to enter in the details'+
            ' manually.</b>'
            },
           		addPlaceManual
           		] 
       });
       addDlg.show();


}		var gMapContainer;
		var mapControl;	


function loadDestMap(lat,lon,name,address,city,state,zip){
var where=address+' , '+city+' , '+state+' , '+zip;
var mappanel = new Ext.Panel({
                layout: 'fit',
                title: 'Map of '+name,
                 applyTo: 'mappanel',
                width:375,
                height:350,
                header: false,
                items: {
                    xtype: 'gmappanel',
                    region: 'center',
                    zoomLevel: 14,
                    gmapType: 'map',id:'gMapContainer',
                    mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
                    mapControls: ['GSmallZoomControl3D','NonExistantControl'],
                    setCenter: {
                      lat: lat,
                	  lng: lon
 
                  
                    }
                }
            });       
    }
    
var globalstore;   
function createDestRatingsGrid(id,userid)
{


	var store = new Ext.data.JsonStore({
        root: 'Result',
        totalProperty: 'total',
        idProperty: 'id',
        remoteSort: true,
		url: '/MFSAjaxServlet?ACTION=GETENTRIESJSON&USERID='+userid+'&DESTID='+id,
        fields: [
            'creator','bloguser','userID','correlation', {name: 'displayDate', mapping: 'displayDate', type: 'date', dateFormat: 'm/d/Y'},'comment', 'logoURL','rank','id'
         ]
        });

    store.setDefaultSort('displayDate', 'desc');
        Ext.QuickTips.init();
    
   function renderDate(value, p, r){
        return String.format('{0}', value.dateFormat('m/d/Y'));
    }
    
    function getRating(value,p,r)
    {
	//if(r.data.comment!=null)
    	//return String.format('<img ext:qtip="{0}" src="v2images/tag_green.gif">'+getvaluedisplay(value),r.data.comment);
    //else
    return String.format(getvaluedisplay(value));
    }
    
    
      function renderAuthor(value, p, r){
     
      if(value>0)
      {
	      var r2 = value * 100;
		  var corrint=Math.round(r2);
		
		  var cs=corrint+'';
		var c = cs.charAt(0);
		
		var str = ""+c;
		if (corrint > 99)
			str = "10";
		if (corrint <= 10)
			str = "1";
		
		var img2 = str+"meter.png";
			if(r.data.bloguser=="1")
        	{
	        return String.format('<a href="User{2}.html"><img alt=\"Featured Blog\" title=\"Featured Blog\" src=\"v2images/blogicon12.png\">&nbsp;{0}</a> <img ext:qtip="Your tastes are {1}% similar." src="v2images/'+img2+'">', r.data.creator,cs,r.data.userID);
	        }
	        else
        		return String.format('<a href="User{2}.html">{0}</a> <img ext:qtip="Your tastes are {1}% similar." src="v2images/'+img2+'">', r.data.creator,cs,r.data.userID);
       }
        else{
        	if(r.data.bloguser=="1")
        	{
	        return String.format('<a href="User{1}.html"><img alt=\"Featured Blog\" title=\"Featured Blog\" src=\"v2images/blogicon12.png\">&nbsp;{0}</a>', r.data.creator,r.data.userID);
    	    }
	        else
        		return String.format('<a href="User{1}.html">{0}</a>', r.data.creator,r.data.userID);
        }
    }
    
    	  var grid = new Ext.grid.GridPanel({
        width:640,
        height:600,
        store: store,
        trackMouseOver:false,
        disableSelection:true,
        applyTo:'ratingsgrid',
        loadMask: true,
		    columns:[{
            id: 'id', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: "Who (Click to sort by similarity)",
            dataIndex: 'correlation',
            width: 350,
            renderer:renderAuthor,
           sortable:true
        },{
            header: "Rating",
            dataIndex: 'rank',
            width: 150,
            align: 'right',
            sortable: true,
            renderer:getRating
        },{
            id: 'date',
            header: "Date",
            dataIndex: 'displayDate',
            width: 150,
            sortable: true,
            renderer:renderDate
           
        }],
         viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true,
            getRowClass : function(record, rowIndex, p, store){
                if(this.showPreview){
                if(record.data.comment==null)
                	p.body="";
                else
                    p.body = '<p>'+record.data.comment+'</p>';
                return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }
        },
        bbar: new Ext.PagingToolbar({
            pageSize: 20,
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying Ratings {0} - {1} of {2}',
            emptyMsg: "No topics to display"
        })
        
       });
       store.load({params:{start:0, limit:20}});
globalstore=store;
}

    function reloadGridCommentsOnly(val)
    {
    if(val.checked==true)
    	globalstore.load({params:{ORDERBY:'commentsonly',start:0,limit:20}});
    else
    	globalstore.load({params:{start:0,limit:20}});
    }
 
 
 function showEditMsg(destid)
 {
 	var fs = new Ext.FormPanel({
 		frame: false,
        title:'Add / Edit Comment',
        labelAlign: 'top',
        labelWidth: 0,
        id:'editcomment',
        waitMsgTarget: true,
        url:'A_SetDestCommentJSON.jsp',
        header:false,
        border:false,
               listeners: {
        	beforerender:  function(){      
        	this.form.load({
            url:'/A_GetDestCommentJSON.jsp?destid='+destid, 
            method:'GET',
            success:function(form, action) {
				editDlg.show(); 
				return true;           	
            },        	
            failure:function(form, action) {
                Ext.MessageBox.alert('Message', 'You must rate this place before you can comment on it.');
          	  }
        	});
        }
        },
        items: [{
                   name: 'eid',
                   xtype:'hidden'
                  
               },
               {
                   name: 'destid',
                   xtype:'hidden'
                  
               },
                {
                   fieldLabel:'Please enter your comment',
                   name: 'comment',
                   id: 'comment',
                   allowBlank: false,
                   xtype: 'htmleditor',
			       enableColors: false,
			       enableAlignments: false,
			       width:400
                
               }],
        buttons: [{text: 'Submit',
               minWidth: 75,
               handler: function() {
               		if (fs.getForm().isValid())
               		{
               			fs.getForm().submit({
               				waitMsg:'Adding comment...',
	               			
	               			success: function(form, action) {
	       					//	Ext.Msg.alert("Success", 'Comment Updated');
	       						editDlg.close();
	    					},
	    					failure: function(form, action) {
						        switch (action.failureType) {
						            case Ext.form.Action.CLIENT_INVALID:
						                Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
						                break;
						            case Ext.form.Action.CONNECT_FAILURE:
						                Ext.Msg.alert("Failure", "Ajax communication failed");
						                break;
						            case Ext.form.Action.SERVER_INVALID:
						               Ext.Msg.alert("Failure", action.result.msg);
	      						 }
	   						 }
               			}
               			);
               		}
               		else
               		{
               			Ext.Msg.alert('Error', 'Please Complete the form!');
               		}
               		 }},
               {text: 'Cancel',
                   minWidth: 75,
                   handler: function() {editDlg.close()}}]
        });
      var editDlg = new Ext.Window({
           height: 350,
           width: 450,
           closable: true,
           closeAction : 'close', 
           modal: true,
           frame: true,
           resizable: false,
           title: 'Add/Edit Comment',
           layout: 'fit',
           items: fs
       });
        fs.getForm().load({
            url:'/A_GetDestCommentJSON.jsp?destid='+destid, 
            method:'GET',
            success:function(form, action) {
				editDlg.show(); 
				return true;           	
            },        	
            failure:function(form, action) {
                Ext.MessageBox.alert('Message', 'You must rate this place before you can comment on it.');
          	  }
        	});
 	       
}

function createTabs(editDisabled, ownerDisabled, videoDisabled,offerDisabled)
{
	var aTab = 0;
	if (ownerDisabled == false)
		aTab = 3;
    var tabs = new Ext.TabPanel({
        renderTo: 'mainAdditonalInfo',
        id: 'tabs',
        activeTab: aTab,
        frame:true,
        plain:true,
        height:725,
        defaults:{autoHeight: true},
        items:[
            {contentEl:'ratingtab', title: 'Reviews'},
            {contentEl:'detailstab', title: 'Details'},
            {contentEl:'editorialtab', title: 'Editorial', disabled: editDisabled},
            {contentEl:'ownertab', title: 'Owner\'s Message',disabled: ownerDisabled},
            {contentEl:'videotab', title: 'Videos',disabled: videoDisabled},
            {contentEl:'offertab', title: 'Offers',disabled: offerDisabled}
            
        ]
    })
}

function switchToDetails()
{
	var panel = Ext.ComponentMgr.get('tabs');
	panel.setActiveTab(1);
}

function switchToReviews()
{
	var panel = Ext.ComponentMgr.get('tabs');
	panel.setActiveTab(0);
}


    var tempIdCounter = 0;
    
    
 function addTag(dest,tag,userid)
 {

Ext.Ajax.request({
   url: '/TagServlet?ACTION=ADDTAG&ItemID='+dest+'&Tag='+tag+'&USERID='+userid,
   success: function(o) {
  },
   failure: function(o){},
   headers: {
       'my-header': 'foo'
   },
   params: { foo: 'bar' }
});
// Default headers to pass in every request
Ext.Ajax.defaultHeaders = {
    'Powered-By': 'Ext'
}; 
}
 
    
    
    function initTags(uid,destid)								
		{
		Ext.override(Ext.ux.form.SuperBoxSelect, {
  			  beforeBlur: Ext.emptyFn
		});

		 
			var loggedin=true;
			if( uid==null || uid=="-1" || uid=="")
				loggedin=false;
			
				
			var store2 = new Ext.data.JsonStore({
	        root: 'Result',
	        			    autoDestroy: true,
	        			    storeId: 'store2',
	        
	         totalProperty: 'total',
	        idProperty: 'tagid',
	        url: '/TagServlet?ACTION=GETTAG&CurrentTag=',
	        fields: [
	            'tagtext','tagid' ,'count']
	        });
			
		
				var tcStore = new Ext.data.JsonStore({
		    // store configs
			    autoDestroy: true,
			    url: '/TagServlet?ACTION=GETCLOUDJSON&ItemID='+destid+'&LoggedIn='+loggedin,
			    storeId: 'tcStore',
			    // reader configs
			    root: 'Result',
			    idProperty: 'tagid',  
			    fields: ['tagid','tagtext','count']
			});   
				
			  	var cloud = new Ext.ux.TagCloud({
           			store: tcStore, 
           			displayField: 'tagtext', 
           			weightField: 'count', 
           			displayWeight: true
           			
           			}
   					);
   					
   			cloud.on('tagselect', function(cloud, record, index){
                //alert('You clicked on "'+record.get('tagtext')+'"!');
                var zip = Ext.getDom('postalcode').innerHTML;
                window.location.href = 'T_Search.jsp?searchfor='+record.get('tagtext')+'&searchwhere='+zip;
            });
   					
   	
   				cloud.render('tagcloud');
   				tcStore.load();
    if(uid!=null)
    {			
		var form2 = new Ext.form.FormPanel({
            id:'f2Form',
			renderTo: 'f2',
           	bodyStyle: 'border:0;',
			width: 240,
			labelWidth:0,
            items: [{
				allowBlank:true,
				hideLabel:true,
                allowAddNewData: true,
                id:'tagselector',
                xtype:'superboxselect',
                fieldLabel:'',
                emptyText: 'Enter a tag',
                resizable: true,
                name: 'tags',
                anchor:'100%',
                store: store2,
                displayField: 'tagtext',
                valueField: 'tagtext',
                extraItemCls: 'x-tag',
                minChars:2,
                listeners: {
                    beforeadditem: function(bs,v){
                        //console.log('beforeadditem:', v);
                        //return false;
                    },
                    additem: function(bs,v){
                   
                        //console.log('additem:', v);
                    },
                    beforeremoveitem: function(bs,v){
                        //console.log('beforeremoveitem:', v);
                        //return false;
                    },
                    removeitem: function(bs,v){
                        //console.log('removeitem:', v);
                    },
                    newitemdata: function(bs,v){
                        //console.log('removeitem:', v);
                        bs.setValueEx({tagtext:v});
                    }
                    
                    
                } 
             },
             {
             	border: false,
             	html:'<span style="font-size:85%">Hit <b>Enter</b> to add a brand new tag.</span>'
             }
            ],
			buttons: [{
                text: 'Add Tags',
                scope: this,
                handler: function(){
                	
                    
                    
					var tags=Ext.getCmp('tagselector').getValue();
					//alert(tags);
					var myArray = tags.split(",");
					for (var i = 0 ; i < myArray.length ; i++){
           			//alert(myArray[i]);
           			addTag(destid,myArray[i],uid);
           			}
                    tcStore.load();
                    cloud.render('tagcloud');
   				    
                    Ext.getCmp('tagselector').reset();

                }
            }]

        });  
        
     }   
        }
        
Ext.ns('Ext.ux.window'); 

/**
 * @class Ext.ux.window.MessageWindowGroup
 * @extends Ext.WindowGroup
 * An object that represents a group of {@link Ext.ux.window.MessageWindow} instances
 * and provides position management in addition to the standard Window Group features.
 * @constructor
 */
Ext.ux.window.MessageWindowGroup = function (config) {
    config = config || {};
    var mgr = new Ext.WindowGroup();
    mgr.positions = [];
    Ext.apply(mgr, config);
    return mgr;
};

/**
 * @class Ext.ux.window.MessageWindowMgr
 * @extends Ext.ux.window.MessageWindowGroup
 * The default global Message Window group that is available automatically.  To have
 * more than one group of Message Windows to utilize separate positioning in addition
 * to the standard Window Manager features create additional instances of 
 * {@link Ext.ux.window.MessageWindowGroup} as needed.
 * @singleton
 */
Ext.ux.window.MessageWindowMgr = Ext.ux.window.MessageWindowGroup(); 

/**
 * @class Ext.ux.window.MessageWindow
 * @extends Ext.Window
 * <p>If you are looking for a lightweight implementation of Toast or Notification windows this is
 * <b>NOT</b> the class you want.  This class builds upon the implementation by <i>Edouard Fattal</i>.
 * This class creates a specialized Window for notification messages and offers the following features:</p>
 * 
 * <br>Demo link: <a href="http://extjs-ux.org/repo/authors/mjlecomte/trunk/Ext/ux/window/msgWindow.html">here</a>
 * <br>Forum thread: <a href="http://extjs.com/forum/showthread.php?t=48135">here</a><br>
 * 
 * <b>Features:</b>
 * <ul>
 * <li>+ Message windows may be bound to any element through configuration.</li>
 * <li>+ A single Message Window may be reused or multiple Message Windows may be used simultaneously.</li>
 * <li>+ Message windows can be managed by groups.</li>
 * <li>+ Several configurable options.</li>
 * <li>++ By default, Message Window will not steal focus.</li>
 * </ul>
 * <br>
 * <b>Known issues/caveats/bugs/roadmap:</b>
 * <ul>
 * <li>+ config for custom showFx incomplete </li>
 * <li>+ vertical location of subsequent windows may overlap if height changes.</li>
 * <li>+ add config to limit drag options (for example lock x or y axis, etc.)</li>
 * </ul>
 * @author Michael LeComte (<a href="http://extjs.com/forum/member.php?u=6834">mjlecomte</a>), inspired by Ext.ux.Notification\ToastWindow (Edouard Fattal)
 * @license <a href="http://www.gnu.org/licenses/lgpl.html">LGPL 3.0</a>
 * @version 0.3 - April 20, 2009
 */
Ext.ux.window.MessageWindow = Ext.extend(Ext.Window, {

    /**
     * @cfg {String} hideAction
     * The action to take after the message window has been hidden. The default is <tt>'close'</tt> which
     * will close() the window. The other supported value is <tt>'hide'</tt> which will keep the window
     * available to be redisplayed via the {@link #show} method.
     */
    hideAction: 'close',

    /**
     * @cfg {Boolean} autoHide
     * {@link #autoHide}
     * True to have message window automatically hide itself (defaults to true).
     */
    autoHide: true,

    /**
     * @cfg {Boolean} autoHeight
     * True to use height:'auto', false to use fixed height (defaults to false).
     */
    autoHeight: false,
			
    /**
     * @cfg {String} bodyStyle
     * Custom CSS styles to be applied to the body element in the format expected by 
     * Ext.Element.applyStyles (defaults to 'text-align:left;padding:10px;').
     */
    bodyStyle: 'text-align:left;padding:10px;',

    /**
    * @cfg {String} baseCls
    * The base CSS class to apply to this panel's element (defaults to 'x-window').
    */

    /**
     * @cfg {String} buttonAlign
     * The alignment of any buttons added to this panel. Valid values are 'right', 'left',
     * and 'center' (defaults to 'center').
     */
    buttonAlign: 'center',

    /**
     * @cfg {String} cls
     * An optional extra CSS class that will be added to this component's Element (defaults
     * to 'x-notification'). This can be useful for adding customized styles to the component
     * or any of its children using standard CSS rules.
     */
    cls: 'x-notification',

    /**
     * @cfg {Boolean} constrain
     * True to constrain the window to the viewport, false to allow it to fall outside of
     * the viewport (defaults to true).  Optionally the header only can be constrained using
     * {@link #constrainHeader}.
     */
    constrain: true,

    /**
     * @cfg {Boolean} constrainHeader
     * True to constrain the window header to the viewport, allowing the window body to fall
     * outside of the viewport, false to allow the header to fall outside the viewport (defaults
     * to true).  Optionally the entire window can be constrained using {@link #constrain}.
     */
    constrainHeader: true,

    /**
     * @cfg {Boolean} draggable
     * True to allow the window to be dragged by the header bar, false to disable dragging
     * (defaults to true).  Note that by default the window will be centered in the viewport,
     * so if dragging is disabled the window may need to be positioned programmatically after
     * render (e.g., myWindow.setPosition(100, 100);).
     */
    draggable: true,

    /** @cfg {Boolean} floating */
    /** @private */
    floating: true,

    /**
     * @cfg {Boolean} focusOnShow
     * True to focus the window when shown (defaults to false).
     */

    /** @cfg {Boolean} frame */
    /** @private */
    frame: true,
    
    /**
     * @cfg {Ext.ux.window.MessageWindowGroup} manager
     * A reference to the MessageWindowGroup that should manage this Message Window (defaults 
     * to {@link Ext.ux.window.MessageWindowMgr}). Specify a reference to an instance unless
     * you want a new manager for each instance:
     * <pre><code>
     * var group2 = new Ext.ux.window.MessageWindowGroup({
     *     //override any defaults or add to base class instance
     *     groupId: 2, //groupId not implemented at this time
     *     zseed: 2000 //change the zseed (default = 9000)
     * });
     * var mw1 = new Ext.ux.window.MessageWindow({
     *     manager: group2//specify the MessageWindowGroup manager (instead of using default manager)
     * });
     * var mw2 = new Ext.ux.window.MessageWindow({
     *     manager: group2//specify the MessageWindowGroup manager (instead of using default manager)
     * });
     * var mw3 = new Ext.ux.window.MessageWindow({
     *     //will use default manager
     * });
     * </pre></code>
     */

    /**
     * @cfg {Function} handleHelp
     * Handler function when the help tool is clicked (defaults to {@link Ext#emptyFn}). 
     * @param {Object} event The click event.
     * @param {Object} toolEl The tool Element.
     * @param {Object} panel The host Panel.
     */
    handleHelp: Ext.emptyFn,

    /**
     * @cfg {Boolean} help
     * True to display tools for help.  Defaults to true.
     */
    help: true,

    /**
     * @cfg {Object} hideFx
     * Config object for hide effects settings. An example with defaults shown:
     * <pre><code>
     * hideFx: {
     *     delay: 5000,  //time in milliseconds to delay the start of the effect
     *     duration: 0.25, //duration of the effect
     *     mode: 'standard', // null = will not hide
     *                       // 'standard' = traditional window hide (vanish)
     *                       // 'standard' = traditional window hide (vanish)
     *                       // anything else will use the default of ghost
     *     useProxy: true //default is false to hide window instead
     * }
     * </code></pre>
     */
    hideFx: {
        delay: 5000
    },

    /**
     * @cfg {String} hoverCls
     * An extra CSS class that will be added to this component's Element when
     * hovering over (defaults to 'msg-over').
     */
    hoverCls: 'msg-over',

    /**
     * @cfg {String} iconCls
     * A CSS class that will provide a background image to be used as the header icon (defaults
     * to 'x-icon-information'). An example custom icon class would be something like: 
     * .my-icon { background: url(../images/my-icon.gif) 0 6px no-repeat !important;} 
     */
    iconCls: 'x-icon-information',

    /**
     * @cfg {Boolean} maximizable
     * True to display the 'maximize' tool button and allow the user to maximize the window, false to hide the button
     * and disallow maximizing the window (defaults to false).  Note that when a window is maximized, the tool button
     * will automatically change to a 'restore' button with the appropriate behavior already built-in that will
     * restore the window to its previous size.
     */

    /**
     * @cfg {Boolean} minimizable
     * True to display the 'minimize' tool button and allow the user to minimize the window, false to hide the button
     * and disallow minimizing the window (defaults to false).  Note that this button provides no implementation --
     * the behavior of minimizing a window is implementation-specific, so the minimize event must be handled and a
     * custom minimize behavior implemented for this option to be useful.
     */

    /**
     * @cfg {Number} minHeight
     * The minimum height in pixels allowed for this window (defaults to 100).  Only applies when resizable = true.
     */
    minHeight: 40,

    /**
     * @cfg {Number} minWidth
     * The minimum width in pixels allowed for this window (defaults to 200).  Only applies when resizable = true.
     */
    minWidth: 200,

    /**
     * @cfg {Boolean} modal
     * True to make the window modal and mask everything behind it when displayed, false to display it without
     * restricting access to other UI elements (defaults to false).
     */

    /**
     * @cfg {Array} msgs
     * An array to hold the message queue for refreshing messages.  Body of the message window will be updated
     * from the <b>text</b> element.
     * <b>Example</b>:
     * <pre><code>
     * msgs: [
     *     {text: 'Some text message 1', url:'http://extjs.com/support/training/'},
     *     {text: 'Some text message 2 &raquo;', url:'http://extjs.com/support/training/'}
     * ],
     * </code></pre>
     * The first message that will be displayed uses the <b>Title</b> and <b>html</b> config options.
     */
    msgs: [],

    /**
     * @cfg {Boolean} monitorResize
     * This is automatically managed based on the value of constrain and constrainToHeader
     */
    monitorResize : true,

    /**
     * @cfg {Function} onEsc
     * Allows override of the built-in processing for the escape key. Default action
     * is to close the Window (performing whatever action is specified in {@link #closeAction}.
     * To prevent the Window closing when the escape key is pressed, specify this as
     * Ext.emptyFn (See {@link Ext#emptyFn}).
     */

    /**
     * @cfg {Object} origin
     * Config object for the message origin with the following sample of default properties:
     * <b>Example</b>:
     * <pre><code>
     * //configure a different origin than the default bottom right corner of the window:
     * origin: {
     *     //get window's Ext.element:
     *     el: Ext.get('northRegion'), //element to align to (defaults to document)
     *     increment: true, // default is to increment position of subsequent messages
     *     pos: "bl-bl", // position to align to (see {@link Ext.Element#alignTo} for more details defaults to "br-br").
     *     offX: 10,     // amount to offset horizontally (-20 by default)
     *     offY: 0       // amount to offset vertically (-20 by default)
     *     spaY: 5       // vertical spacing between adjacent messages (5 by default)
     * },
     * </code></pre>
     */

    /**
     * @cfg {Boolean} pinOnClick
     * True to display the 'pin' tool button and allow the user to pin the window, false
     * to hide the button and disallow pinning the window (defaults to true).
     */
    pinOnClick: true,

    /**
     * @cfg {String} pinState
     * Specify the initial pin state when the window is first shown. Specify null, 'pin', or the default
     * 'unpin'. <pre>
     * pinState  effect
     * --------  ------
     * null      window will show/hide itself, user can not control
     * 'pin'     window will initially show itself in pinned state, user will need to click unpin to hide
     * 'unpin'   window will initially show itself in unpinned state, user will need to click pin to keep open
     * </pre>
     */
    pinState: 'unpin',

    /**
     * @cfg {Boolean} plain
     * True to render the window body with a transparent background so that it will blend into the framing
     * elements, false to add a lighter background color to visually highlight the body element and separate it
     * more distinctly from the surrounding frame (defaults to false).
     */
    plain: false,
    
    /**
     * @cfg {Boolean} resizable
     * True to allow user resizing at each edge and corner of the window, false to disable resizing (defaults to false).
     */
    resizable: false,

    /**
     * @cfg {String} resizeHandles
     * A valid {@link Ext.Resizable} handles config string (defaults to 'all').  Only applies when resizable = true.
     */

    /**
     * @cfg {String} textHelp
     * Qtip text to display for help tool (defaults to 'Get hel').  Only applicable if help = true. 
     */
    textHelp: 'Get help',

    /**
     * @cfg {String} textPin
     * Qtip text to display for pin tool.  Only applicable if {@link pinState} == 'pin' or 'unpin'.
     */
    textPin: 'Pin this to prevent closing',

    /**
     * @cfg {String} textUnpin
     * Qtip text to display for unpin tool.  Only applicable if {@link pinState} == 'pin' or 'unpin'.
     */
    textUnpin: 'Unpin this to close',

    /**
     * @cfg {Number} x
     * The X position of the left edge of the Window on initial showing. Defaults to centering the Window within
     * the width of the Window's container {@link Ext.Element Element) (The Element that the Window is rendered to).
     */

    /**
     * @cfg {Number} y
     * The Y position of the top edge of the Window on initial showing. Defaults to centering the Window within
     * the height of the Window's container {@link Ext.Element Element) (The Element that the Window is rendered to).
     */

    /** @private */
    initHidden : true,

    /** @private */
    initComponent : function () {

        Ext.apply(this, {
            collapsible: false,
            footer: false,
            minHeight: 20,
            stateful: false
        });
        
        //if interval is specified automatically show message windows
        if (this.interval) {
            this.startAutoRefresh();
        } 
        //set up automatic hide/close of window if so configured
        if (this.autoHide) {
            if (this.pinState === 'unpin') {
                this.task = new Ext.util.DelayedTask( this[this.hideAction], this, [this.animateTarget]);
            }
        } 
//new
        else {
			this.closable = true;
		}
//added this.closable
        
        //call parent
        Ext.ux.window.MessageWindow.superclass.initComponent.call(this);

        //add listeners
        this.on({
            mouseout: {
                scope: this,
                fn: this.onMouseout
            }
        });

        //add events
        this.addEvents(
            /**
             * @event activate
             * Fires after the window has been visually activated via {@link setActive}.
             * @param {Ext.ux.window.MessageWindow} this
             */
            /**
             * @event deactivate
             * Fires after the window has been visually deactivated via {@link setActive}.
             * @param {Ext.ux.window.MessageWindow} this
             */
            /**
             * @event resize
             * Fires after the window has been resized.
             * @param {Ext.ux.window.MessageWindow} this
             * @param {Number} width The window's new width
             * @param {Number} height The window's new height
             */
            /**
             * @event maximize
             * Fires after the window has been maximized.
             * @param {Ext.ux.window.MessageWindow} this
             */
            /**
             * @event minimize
             * Fires after the window has been minimized.
             * @param {Ext.ux.window.MessageWindow} this
             */
            /**
             * @event restore
             * Fires after the window has been restored to its original size after being maximized.
             * @param {Ext.ux.window.MessageWindow} this
             */
            /**
             * @event pinned
             * Fires after the window has been pinned.
             * @param {Ext.ux.window.MessageWindow} this
             */
            'afterpin',
            /**
             * @event unpinned
             * Fires after the window has been unpinned.
             * @param {Ext.ux.window.MessageWindow} this
             */
            'afterunpin',
            /**
             * @event click
             * Fires after the window has been clicked.
             * @param {Ext.ux.window.MessageWindow} this
             * @param {Ext.ux.window.MessageWindow} msg The message from the message array if configured.
             */
            'click');

        this.initFx();
    },

    //override
    /** @private */
    initEvents: function () {
        
        //use a slighly enhanced Ext.ux.window.MessageWindowMgr instead of the default WindowMgr
        this.manager = this.manager || Ext.ux.window.MessageWindowMgr;

        //the parent class will register, so no need to do it here:
        //this.manager = this.manager || Ext.WindowMgr;
        
        Ext.ux.window.MessageWindow.superclass.initEvents.call(this);
    },

    focus: function () {
        Ext.ux.window.MessageWindow.superclass.focus.call(this);
    },
    
    /** @private */
    toFront: function () {
        if(this.manager.bringToFront(this)){
            //only focus if configured as such
            if(this.focusOnShow){
                this.focus();
            }
        }
        return this;
    },

    /** @private */
    initTools: function () {
        if (this.pinOnClick) {
            this.addTool({
                id: 'unpin', // image points left
                handler: this.handlePin,
                //set initial visibility (also check if pinState is null)
                hidden: (!this.pinState || this.pinState === 'pin'), 
                qtip: this.textPin,
                scope: this
            });
    
            this.addTool({
                id: 'pin',// image points down
                handler: this.handleUnpin,
                hidden: (!this.pinState || this.pinState === 'unpin'), 
                qtip: this.textUnpin,
                scope: this
            });
        }
        if (this.help) {
            this.addTool({
                id: 'help',
                handler: this.handleHelp,
                qtip: this.textHelp,
                scope: this
            });
        }

        // let the default tools be applied farthest to the right
        Ext.ux.window.MessageWindow.superclass.initTools.apply(this, arguments);
    },

    /** @private */
    onRender: function (ct, position) {
        Ext.ux.window.MessageWindow.superclass.onRender.call(this, ct, position);
        //after call to parent class onRender this.el exists.

        //clip part of the window (for example the recurring messages that
        //eject from a border have the bottom rounded edge, etc. clipped off.
        if (this.clip) {
            switch (this.clip) {
            case 'bottom':
                Ext.destroy(this.getEl().child('.' + this.baseCls + '-bl'));
                break;
            }
        }

        //add a class when hovering over in order to disable
        //any updates to the window while hovering over
        if (true) {
            this.el.addClassOnOver(this.hoverCls);
        }
        
        //add click listener to body
        Ext.fly(this.body.dom).on('click', this.handleClick, this);
    },

////////////////////////////////
// Temporary override?
    /**
     * Closes the window, removes it from the DOM and destroys the window object.  The beforeclose event is fired
     * before the close happens and will cancel the close action if it returns false.
     */
//    close : function(){
    close : function(animateTarget){
        if(this.fireEvent("beforeclose", this) !== false){
//            this.hide(null, function(){
            this.hide(animateTarget, function(){
                this.fireEvent('close', this);
                this.destroy();
            }, this);
        }
    },
/////////////////////////////////

    /**
     * Toggles the active pin state.
     */
    togglePinState: function (event) {
        if (this.pinOnClick) {
            //check which tool is visible
            if (this.tools.unpin.isVisible()) {
                this.handlePin(event, this.tools.unpin, this);
            } else {
                this.handleUnpin(event, this.tools.pin, this);
            }
        }
    },

    /**
     * Override to the Panel Class createElement method.  This method is called by
     * Panel Class' onRender().  Normally the panel class will create a header in the
     * *-tc class, to utilize the default box class for styling we'll move the header
     * inside the *-mc class to utilize  
Ext.Element.boxMarkup:
<div class="{0}-tl">
    <div class="{0}-tr">
        <div class="{0}-tc">
            ##HEADER##
            <div class="{0}-header {0}-draggable">
                <div class="x-tool x-tool-close">
                </div>
                <span class="{0}-header-text">
                </span>
            </div>
        </div>
    </div>
</div>
<div class="{0}-ml">
    <div class="{0}-mr">
        <div class="{0}-mc">
            <div class="{0}-body">
                CONTAINER
                ###############
            </div>
        </div>
    </div>
</div>
<div class="{0}-bl">
    <div class="{0}-br">
        <div class="{0}-bc">
        </div>
    </div>
</div>   



 <div class="x-box-bwrap" id="ext-gen117">
    <div class="x-box-ml">
        <div class="x-box-mr">
            <div class="x-box-mc">
                <div style="-moz-user-select: none;" id="ext-gen116" class="x-box-header x-unselectable x-window-draggable">
                    <div id="ext-gen128" class="x-tool x-tool-help">
                    </div>
                    <span class="x-box-header-text" id="ext-gen126"><h2>Title</h2></span>
                </div>
                <div class="x-box-body" id="ext-gen118" style="height: auto; width: 72px;">
                    Message
                </div>
            </div>
        </div>
    </div>
    <div class="x-box-bl x-panel-nofooter">
        <div class="x-box-br">
            <div class="x-box-bc"/>
        </div>
    </div>
</div>
     * @param {Object} name
     * @param {Object} pnode
     *///override panel class method:
    // private
    createElement : function (name, pnode) {
        if (this.shiftHeader) {
            switch (name) {
            case 'header':
                //don't create header yet if putting inside mc, do it when tbar is done
                return;
            case 'tbar':
                Ext.ux.window.MessageWindow.superclass.createElement.call(this, 'header', pnode);
                Ext.ux.window.MessageWindow.superclass.createElement.call(this, name, pnode);
                return;
            }
        }
        //caught the ones we needed to, call the default implementation
        Ext.ux.window.MessageWindow.superclass.createElement.call(this, name, pnode);
    },

    //override/disable focus, see above.
    focus: Ext.emptyFn, 

    /** @private */
    getState : function () {
        return Ext.apply(Ext.ux.window.MessageWindow.superclass.getState.call(this) || {}, this.getBox());
    },

    /**
     * Handler for when the message window body is clicked
     * @param {Object} event The click event.
     */
    handleClick: function (event) {
        this.fireEvent('click', this, this.msg);
        this.togglePinState(event);
    },

    /**
     * Handler for when pin button is clicked
     * @param {Object} event The click event.
     * @param {Object} toolEl The tool Element.
     * @param {Object} panel The host Panel.
     */
    handlePin: function (event, toolEl, panel) {
        //hide the unpin button
        toolEl.hide();
        
        //show the pin button
        this.tools.pin.show();

        this.cancelHiding();
        
        this.fireEvent('afterpin', this);
    },

    /**
     * Handler for when pin button is clicked
     * @param {Object} event The click event.
     * @param {Object} toolEl The tool Element.
     * @param {Object} panel The host Panel.
     */
    handleUnpin: function (event, toolEl, panel) {

        //hide the pin button
        toolEl.hide();
        
        //show the unpin button
        this.tools.unpin.show();

        this[this.hideAction](this.animateTarget);

        this.fireEvent('afterunpin', this);
    },

    /**
     * cancel hiding of the window if {@link #autoHide} is true
     */
    cancelHiding: function () {
        this.addClass('fixed');
        if (this.autoHide) {
            if (this.pinState === 'unpin') {
                this.task.cancel();
            }
        }
        if (this.tools.pin) {
            //show the pin button
            this.tools.pin.show();
        }
        if (this.tools.unpin) {
            //make sure the unpin button is hidden
            this.tools.unpin.hide();
        }
 },

    /** @private */
    initFx : function () {
        this.showFx = this.showFx || {};
        Ext.applyIf(this.showFx, {
            align: 'b',
            duration: 1,
            callback: this.afterShow,
            scope: this
        });

        this.hideFx = this.hideFx || {};
        Ext.applyIf(this.hideFx, {
            block: false,//default for window is true
            callback: this.afterHide,
            easing: 'easeOut',//'easeNone';
            remove: true,
            scope: this
        });

        this.origin = this.origin || {};
        Ext.applyIf(this.origin, {
            el: Ext.getDoc(), //defaults to document
            increment: true, //whether to increment position of subsequent messages
            pos: "br-br",//position to align to (see {@link Ext.Element#alignTo} for more details defaults to "br-br").
            offX: -30, //amount to offset horizontally --changed by apapf to avoid scroll bar.
            offY: -20, //amount to offset vertically
            spaY: 5    //vertical spacing between adjacent messages
        });
    },


    getAnimEl : function (fx) {
        var animEl;

        //animate using a proxy instead of actual element if so configured
        if (fx.useProxy) {
            animEl = this.proxy;
            this.proxy.setOpacity(0.5);
            this.proxy.show();
            var tb = this.getBox(false);
            this.proxy.setBox(tb);
            this.el.hide();
            //Ext.apply(fx, tb);
        } else {
            animEl = this.el;
        }
        
        return animEl;
    },

    //override parent method
    /** @private */
    animHide : function () {

        //remove the position of this element from the manager
        this.manager.positions.remove(this.pos);

        // configured Fx and element to hide
        var fx = this.hideFx, w = this.getAnimEl(fx);
        
        switch (fx.mode) {
            case 'none':
                break;
            case 'slideIn':
                w[fx.mode]("b", fx);
                //w.slideIn("b", fx);
                break;
            case 'custom':
                Ext.callback(fx.callback, fx.scope, [this, w, fx]);//callback(cb,scope,args,delay)
                break;
            case 'standard':
                fx.duration = fx.duration || 0.25;
                fx.opacity = 0;
                w.shift(fx);
                break;
            default:
                fx.duration = fx.duration || 1;
                w.ghost("b", fx);
                break;
        }
    },

    //override parent method
    /** @private */
    afterShow: function () {
        Ext.ux.window.MessageWindow.superclass.afterShow.call(this);
        
        //if user moves remove from position manager and cancel hiding
		this.on('move', function(){
            //remove the position of this element from the manager
            this.manager.positions.remove(this.pos);
            this.cancelHiding();
		}, this);

        if (this.autoHide) {
           if (this.pinState === 'unpin') {
                this.task.delay(this.hideFx.delay);
            }
        }
    },

    /** @private */
    animShow: function () {

        //don't update if hovering over message
        //check if visible so it will show initially
        if (this.el.isVisible() && this.el.hasClass(this.hoverCls)) {
            return;
        }

        if (this.msgs.length > 1) {
            this.updateMsg();
        }

        //element to hide and configured Fx
        var fx = this.showFx, el = this.el;

        this.position(el);
        el.slideIn(fx.align, fx);
    },

    /**
     * some cleanup still needed this method
     * sizing / placement issues when height of windows changes
     * should recalculate placement based on window height
     */
    position : function (el) {

        var y,
            // push down instead of up if align top
            dir = (this.showFx.align.substr(0,1) == 't') ? 1 : -1;            

        //track positions of each instance
        this.pos = 0;

        if (this.origin.increment) {
            while (this.manager.positions.indexOf(this.pos) > -1) {
                this.pos++;
            }
            this.manager.positions.push(this.pos);
        }

        //set the window size
        this.setSize(this.width || this.minWidth, this.height || this.minHeight);

        //increment the vertical position of the window
        if (this.origin.increment) {
            y = this.origin.offY + ((this.getSize().height + this.origin.spaY) * this.pos * dir);            
        } else {
            y = 0;
        }

        el.alignTo(
            this.origin.el, // element to align to.
            this.origin.pos,        // position to align to (see {@link Ext.Element#alignTo} for more details).
            [ this.origin.offX, y ] // Offset the positioning by [x, y]: 
        );
    },

    onMouseout: function () {
        //console.info('in onMouseout');
        //console.info(arguments);
    },


    /**
     * @param {Object} el
     * @param {Object} x
     * @param {Object} y
     * @private
     */
	positionPanel: function (el, x, y) {
        if(x && typeof x[1] == 'number'){
            y = x[1];
            x = x[0];
        }
        el.pageX = x;
        el.pageY = y;
       	
        if(x === undefined || y === undefined){ // cannot translate undefined points
            return;
        }
        
        if(y < 0){ y = 10; }
        
        var p = el.translatePoints(x, y);
        el.setLocation(p.left, p.top);
        return el;
    },

    /**
     * Specify the message to be shown
     * @param {String} msg Message to update the body with.
     */
    setMessage: function (msg) {
        this.body.update(msg);
    },

    /**
     * Set the title of the message window
     * @param {String} title Title of Window
     * @param {String} iconCls icon to use in header area
     */
    setTitle: function (title, iconCls) {
        Ext.ux.window.MessageWindow.superclass.setTitle.call(this, title, iconCls || this.iconCls);
    },

    /**
     * Start recurring messages
     * @param {Boolean} update Whether to update the message before starting automatic refreshes.
     */

    startAutoRefresh : function(update){
        if(update){
            this.updateMsg(true);
        }
        if(this.autoRefreshProcId){
            clearInterval(this.autoRefreshProcId);
        }
        // native javascript function to delay for a specified time before triggering the
        // execution of a specific function. After triggering the called function the command
        // doesn't complete. Instead it waits for the specified time again and then triggers
        // the function again and continues to repeat this process of triggering the function
        // at the specified intervals until either the web page is unloaded or the clearInterval
        // function is called.
        this.autoRefreshProcId = setInterval(this.animShow.createDelegate(this, []), this.interval);
    },

    /**
     * Stop recurring messages
     */
    stopAutoRefresh : function(){
        if(this.autoRefreshProcId){
            clearInterval(this.autoRefreshProcId);
        }
    },

    /**
     * Update the message
     * @param {String} msg The updated msg
     */
    updateMsg: function (msg) {

        //don't update if hovering over message
        if (this.el && !this.el.hasClass(this.hoverCls)) {

            if (msg) {
//                console.info('message passed');   
            } else {
                this.msgIndex = this.msgs[this.msgIndex + 1] ? this.msgIndex + 1 : 0;
                this.msg = this.msgs[this.msgIndex];
            }

            //update the innerHTML of element
            //this.el.dom.update(this.msg.text);
            this.body.update(this.msg.text);
        } else {
            //console.info('hovering');
        }
    }    
});

//register the xtype
Ext.reg('message-window', Ext.ux.window.MessageWindow);    	//samples http://extjs-ux.org/repo/authors/mjlecomte/trunk/Ext/ux/window/msgWindow.html
       var topGroup = new Ext.ux.window.MessageWindowGroup({groupId:0});
       var cornerGroup = new Ext.ux.window.MessageWindowGroup({groupId:1});
       var midGroup = new Ext.ux.window.MessageWindowGroup({groupId:2});
       
       function messageOnTop(titleMsg,msg) {
       		
       		
    		w = new Ext.ux.window.MessageWindow({
    			title: titleMsg,
    			autoDestroy: true,//default = true
                autoHeight: true,
    			autoHide: true,//default = true
                bodyStyle: 'text-align:center',
                closable: true,
                help: false,
                hideFx: {
                    delay: 10000,
                    //duration: 0.25,
                    mode: 'standard',//null,'standard','custom',or default ghost
                    useProxy: false //default is false to hide window instead
                },
    			html: msg,
    			iconCls: 'x-icon-error',

                manager: topGroup,//specify the MessageWindowGroup manager (instead of using default manager)
                origin: {
                    pos: "t-t",//position to align to (see {@link Ext.Element#alignTo} for more details defaults to "br-br").
                    offX: 0, //amount to offset horizontally (-20 by default)
                    offY: 0, //amount to offset vertically (-20 by default)
                    spaY: 5    //vertical spacing between adjacent messages
                },
                pinOnClick: false,
                showFx: {
                    align: 't',
                    delay: 0,
                    duration: 1, //defaults to 1 second
                    mode: 'standard',//null,'standard','custom',or default ghost
                    useProxy: false //default is false to hide window instead
                },
                width: 800 //optional (can also set minWidth which = 200 by default)
    		});
            
            w.show(Ext.getDoc());
    	}
    	
    	       function messageInCenter(titleMsg,msg) {
       		
       		
    		w = new Ext.ux.window.MessageWindow({
    			title: titleMsg,
    			autoDestroy: true,//default = true
                autoHeight: true,
    			autoHide: true,//default = true
                bodyStyle: 'text-align:left',
                closable: true,
                help: false,
                hideFx: {
                    delay: 10000,
                    //duration: 0.25,
                    mode: 'standard',//null,'standard','custom',or default ghost
                    useProxy: false //default is false to hide window instead
                },
    			html: msg,
  
                manager: midGroup,//specify the MessageWindowGroup manager (instead of using default manager)
                origin: {
                    pos: "c-c",//position to align to (see {@link Ext.Element#alignTo} for more details defaults to "br-br").
                    offX: 0, //amount to offset horizontally (-20 by default)
                    offY: 0, //amount to offset vertically (-20 by default)
                    spaY: 5    //vertical spacing between adjacent messages
                },
                pinOnClick: false,
                showFx: {
                    align: 't',
                    delay: 1,
                    duration: 0.5, //defaults to 1 second
                    mode: 'standard',//null,'standard','custom',or default ghost
                    useProxy: false //default is false to hide window instead
                },
                width: 700 //optional (can also set minWidth which = 200 by default)
    		});
            
            w.show(Ext.getDoc());
    	}

    	
    	    function messageInCorner(titleMsg,msg) {
    		new Ext.ux.window.MessageWindow({
    			title: titleMsg,
    			autoDestroy: true,//default = true
                autoHeight: true,
    			autoHide: true,//default = true
                bodyStyle: 'text-align:center',
                closable: false,
      			manager: cornerGroup,
                hideFx: {
                    delay: 7000,
                    //duration: 0.25,
                    mode: 'standard',//null,'standard','custom',or default ghost
                    useProxy: false //default is false to hide window instead
                },
    			html: msg,
    			iconCls: 'x-icon-error',

                showFx: {
                    delay: 0,
                    duration: 1, //defaults to 1 second
                    mode: 'standard',//null,'standard','custom',or default ghost
                    useProxy: false //default is false to hide window instead
                },
                width: 250 //optional (can also set minWidth which = 200 by default)
    		}).show(Ext.getDoc()); 

    		}var gMapContainer;
var mapControl;	
var searchMarkers=[];

function loadMap(name){


var mappanel = new Ext.Panel({
                layout: 'fit',
                title: 'Map of '+name,
                applyTo: 'mappanel',
                width:375,
                height:420,
                header: false,
                items: {
                    xtype: 'gmappanel',
                    region: 'center',
                    gmapType: 'map',id:'gMapContainer',
                    mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
                    mapControls: ['GSmallZoomControl3D','NonExistantControl']
        
                }
            });
            
            
        
    }
    

function createReSearchBtn(searchfor)
{
	var btn = new Ext.Button({
		text:'Refine Search',
		id:'researchbtn',
		handler:function(){
		
			var cost = getCostForSearch();
			//contruct A_SearchResults.jsp URL
			var u = 'A_SearchResults.jsp?reSearch=y&searchfor='+searchfor+getMapCoordsForSearch()+'&cost='+cost+"&"+getOrderBy()+getAddlTagsForURL();
			//alert(u);
			Ext.get('searchResults').load({
        		url : u,
        		scripts: true
        	});
		}
	});
	btn.render('researchbtndiv');
}   

function createOrderByLoggedIn()
{

var orderbyval1 = new Ext.form.Hidden({
	id:'orderbyval1',
	name:'orderbyval1',
	value:'PREDSCORE',
	renderTo: 'orderbydiv'
	});
	
	var orderbyval2 = new Ext.form.Hidden({
	id:'orderbyval2',
	name:'orderbyval2',
	value:'NUMRATINGS',
	renderTo: 'orderbydiv'
	});


 var menu1 = new Ext.menu.Menu({
    id: 'ob1',
    items: [
    	{
            text: 'Predicted Rating',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = 'Predicted Rating';orderbyval1.setValue('PREDSCORE');  }
        },
        {
            text: 'Average Rating',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = 'Average Rating';orderbyval1.setValue('RATING');  }
        }
        ,
       {
            text: '# Friend Ratings',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = '# Friend Ratings';orderbyval1.setValue('NUMFRIENDRATINGS'); }
       },
        {
            text: '# Friend Comments',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = '# Friend Comments'; orderbyval1.setValue('NUMFRIENDCOMMENTS'); }
       },
        {
            text: '# Ratings',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = '# Ratings';orderbyval1.setValue('NUMRATINGS'); }
       },
        {
            text: '# Comments',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = '# Comments';orderbyval1.setValue('NUMCOMMENTS'); }
       }
       ,
        {
            text: 'Distance',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = 'Distance';orderbyval1.setValue('DISTANCE'); }
       }
     ]});
     
   var menu2 = new Ext.menu.Menu({
    id: 'ob2',
    items: [
        	{
            text: 'Predicted Rating',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = 'Predicted Rating';orderbyval2.setValue('PREDSCORE');  }
        },
        {
            text: 'Average Rating',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = 'Average Rating';orderbyval2.setValue('RATING');  }
        }
        ,
       {
            text: '# Friend Ratings',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = '# Friend Ratings';orderbyval2.setValue('NUMFRIENDRATINGS'); }
       },
        {
            text: '# Friend Comments',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = '# Friend Comments'; orderbyval1.setValue('NUMFRIENDCOMMENTS'); }
       },
        {
            text: '# Ratings',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = '# Ratings';orderbyval2.setValue('NUMRATINGS'); }
       },
        {
            text: '# Comments',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = '# Comments';orderbyval2.setValue('NUMCOMMENTS'); }
       }
       ,
        {
            text: 'Distance',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = 'Distance';orderbyval2.setValue('DISTANCE'); }
       }
     ]});
     
	Ext.get('orderby1').on("click",function(){ menu1.show('orderby1');});
	Ext.get('orderby2').on("click",function(){ menu2.show('orderby2');});
} 

function createOrderBy()
{
var orderbyval1 = new Ext.form.Hidden({
	id:'orderbyval1',
	name:'orderbyval1',
	value:'RATING',
	renderTo: 'orderbydiv'
	});
	
	var orderbyval2 = new Ext.form.Hidden({
	id:'orderbyval2',
	name:'orderbyval2',
	value:'NUMRATINGS',
	renderTo: 'orderbydiv'
	});

 var menu1 = new Ext.menu.Menu({
    id: 'ob1',
    items: [
        {
            text: 'Average Rating',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = 'Average Rating'; orderbyval1.setValue('RATING');  }
        }
        ,
        {
            text: '# Ratings',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = '# Ratings'; orderbyval1.setValue('NUMRATINGS'); }
       },
        {
            text: '# Comments',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = '# Comments';  orderbyval1.setValue('NUMCOMMENTS');}
       }
       ,
        {
            text: 'Distance',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby1').innerHTML = 'Distance'; orderbyval1.setValue('DISTANCE');}
       }
     ]});
     
   var menu2 = new Ext.menu.Menu({
    id: 'ob2',
    items: [
        {
            text: 'Average Rating',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = 'Average Rating'; orderbyval2.setValue('RATING');  }
        }
        ,
        {
            text: '# Ratings',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = '# Ratings'; orderbyval2.setValue('NUMRATINGS'); }
       },
        {
            text: '# Comments',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = '# Comments';  orderbyval2.setValue('NUMCOMMENTS');}
       }
       ,
        {
            text: 'Distance',
            iconCls: 'noIcon',
            handler: function () { Ext.getDom('orderby2').innerHTML = 'Distance'; orderbyval2.setValue('DISTANCE');}
       }
     ]});
     
	Ext.get('orderby1').on("click",function(){ menu1.show('orderby1');});
	Ext.get('orderby2').on("click",function(){ menu2.show('orderby2');});
}

function createCostBoxes()
{
	var myCheckboxGroup = new Ext.form.CheckboxGroup({
    id:'costgroup',
    xtype: 'checkboxgroup',
    fieldLabel: 'Cost',
    itemCls: 'x-check-group-alt',
    // Put all controls in a single column with width 100%
    columns: 1,
    items: [
        {boxLabel: '<b>$</b>', name: 'cb-col-1',id:'cost1'},
        {boxLabel: '<b>$$</b>', name: 'cb-col-2',id:'cost2'},
        {boxLabel: '<b>$$$</b>', name: 'cb-col-3',id:'cost3'},
        {boxLabel: '<b>$$$$</b>', name: 'cb-col-4',id:'cost4'},
        {boxLabel: '<b>$$$$$</b>', name: 'cb-col-5',id:'cost5'}
    ]
	});
	myCheckboxGroup.render("costdiv");
}
     
function hoverOverLink(id)
{

	var m= searchMarkers[id-1];
	GEvent.trigger(m, 'click'); 

}  

function getOrderBy()
{
	var o1= Ext.getCmp('orderbyval1').getValue();
	var o2= Ext.getCmp('orderbyval2').getValue();
	return "orderby1="+o1+"&orderby2="+o2;
}

function getCostForSearch()
{
	var c1 = Ext.getCmp('cost1').getValue();
	var c2 = Ext.getCmp('cost2').getValue();
	var c3 = Ext.getCmp('cost3').getValue();
	var c4 = Ext.getCmp('cost4').getValue();
	var c5 = Ext.getCmp('cost5').getValue();
	var msg = '';
	if (c1)
		msg += '1,';
	if (c2)
		msg += '2,';	
	if (c3)
		msg += '3,';
	if (c4)
		msg += '4,';	
	if (c5)
		msg += '5,';
		
	return msg;
}  

function getMapCoordsForSearch()
{

		var map=getMap();
		var glatlng=map.getCenter();
		if(glatlng==null || glatlng=="null")
		{
			//means map isnt ready to be used for search			
			return null;
		
		}
		else
		{
			var b=map.getZoom();
			
			var c=map.getBounds();
			var g1=c.getSouthWest();
			var g2=c.getNorthEast();
			var lat=glatlng.lat();
			var lng=glatlng.lng();
			var lat1=g1.lat();
			var lat2=g2.lat();
			var lng1=g1.lng();
			var lng2=g2.lng();
			//note we use lat1 twice since we wont the top two corners
			return "&LATCENTER="+lat+"&LNGCENTER="+lng+"&LAT1="+lat1+"&LAT2="+lat1+"&LNG1="+lng1+"&LNG2="+lng2;
	
		}
}

function getAddlTagsForURL()
{
		var tags=Ext.getCmp('tagselector').getValue();
		//alert(tags);
		var myArray = tags.split(",");
		var str = "";
		for (var i = 0 ; i < myArray.length ; i++){
        			
        	str += "&addltag="+myArray[i];		
        		
        }
        return str;
}

function reloadAddlTagStore()
{
	var sCmp = Ext.getCmp('tagselector');
	var str = sCmp.getStore();
	str.reload(null);
}

function createAddlTags()
{
		Ext.override(Ext.ux.form.SuperBoxSelect, {
  			  beforeBlur: Ext.emptyFn
		});
	var store2 = new Ext.data.JsonStore({
	        root: 'Result',
	        			    autoDestroy: true,
	        			    storeId: 'store2',
	         totalProperty: 'total',
	        idProperty: 'tagid',
	        url: '/TagServlet?ACTION=GETTAGSREFINESEARCH&CurrentTag=',
	        fields: [
	            'tagtext','tagid' ,'count']
	        });
	        
	var form2 = new Ext.form.FormPanel({
            id:'f2Form',
			renderTo: 'addltagdiv',
            autoHeight: true,
			bodyStyle: 'border:0;',
			width: 240,
			labelWidth:0,
            items: [{
				allowBlank:true,
				hideLabel:true,
                allowAddNewData: true,
                id:'tagselector',
                xtype:'superboxselect',
                fieldLabel:'',
                emptyText: 'Enter a tag',
                resizable: true,
                name: 'tagselector',
                anchor:'100%',
                store: store2,
                displayField: 'tagtext',
                valueField: 'tagtext',
                extraItemCls: 'x-tag',
                stackItems:true,
                minChars:0,
                listeners: {
                    beforeadditem: function(bs,v){
                        //console.log('beforeadditem:', v);
                        //return false;
                    },
                    additem: function(bs,v){
                            bs.collapse();                                                         
                    },
                    beforeremoveitem: function(bs,v){
                        //console.log('beforeremoveitem:', v);
                        //return false;
                    },
                    removeitem: function(bs,v){
                        //console.log('removeitem:', v);
                    }
                    
                    
                } 
             }] 
            
        });  
        
}

function loadSearchPage(page)
{
        	Ext.get('searchResults').load({
        		url : '/A_SearchResults.jsp?page='+page ,
        		nocache: true,
        		scripts: true
        	});

}
     
  Ext.namespace('Ext.ux.form');
/**
 * <p>SuperBoxSelect is an extension of the ComboBox component that displays selected items as labelled boxes within the form field. As seen on facebook, hotmail and other sites.</p>
 * <p>The SuperBoxSelect component was inspired by and based on the BoxSelect component found here: http://efattal.fr/en/extjs/extuxboxselect/</p>
 * 
 * @author <a href="mailto:dan.humphrey@technomedia.co.uk">Dan Humphrey</a> created for ******CENSORED******
 * @class Ext.ux.form.SuperBoxSelect
 * @extends Ext.form.ComboBox
 * @constructor
 * @component
 * @version 1.0b1
 * @license Unlikely
 * 
 */
Ext.ux.form.SuperBoxSelect = function(config) {
    Ext.ux.form.SuperBoxSelect.superclass.constructor.call(this,config);
    this.addEvents({
        /**
         * Fires before an item is added to the component via user interaction. Return false from the callback function to prevent the item from being added.
         * @event beforeadditem
         * @memberOf Ext.ux.form.SuperBoxSelect
         * @param {SuperBoxSelect} this
         * @param {Mixed} value The new item value
         */
        'beforeadditem' : true,
        /**
         * Fires after a new item is added to the component.
         * @event additem
         * @memberOf Ext.ux.form.SuperBoxSelect
         * @param {SuperBoxSelect} this
         * @param {Mixed} value The new item value
         */
        'additem' : true,
        /**
         * Fires when the allowAddNewData config is set to true, and a user attempts to add an item that is not in the data store.
         * @event additem
         * @memberOf Ext.ux.form.SuperBoxSelect
         * @param {SuperBoxSelect} this
         * @param {Mixed} value The new item value
         */
        'newitemdata' : true,
        /**
         * Fires when an item's remove button is clicked. Return false from the callback function to prevent the item from being removed.
         * @event beforeremoveitem
         * @memberOf Ext.ux.form.SuperBoxSelect
         * @param {SuperBoxSelect} this
         * @param {Mixed} value The item value
         */
        'beforeremoveitem' : true,
        /**
         * Fires after an item has been removed.
         * @event removeitem
         * @memberOf Ext.ux.form.SuperBoxSelect
         * @param {SuperBoxSelect} this
         * @param {Mixed} value The item value
         */
        'removeitem' : true
    });
};
/**
 * @private hide from doc gen
 */
Ext.ux.form.SuperBoxSelect = Ext.extend(Ext.ux.form.SuperBoxSelect,Ext.form.ComboBox,{
    /**
     * @cfg {Boolean} allowAddNewData When set to true, allows items to be added (via the setValueEx and addItem methods) that do not already exist in the data store. Defaults to false.
     */
    allowAddNewData: false,
    /**
     * @cfg {Boolean} backspaceDeletesLastItem When set to false, the BACKSPACE key will focus the last selected item. When set to true, the last item will be immediately deleted. Defaults to true.
     */
    backspaceDeletesLastItem: true,
    /**
     * @cfg {String} classField The underlying data field that will be used to supply an additional class to each item.
     */
    classField: null,
    /**
     * @cfg {String} clearBtnCls An additional class to add to the in-field clear button.
     */
    clearBtnCls: '',
    /**
     * @cfg {String/XTemplate} displayFieldTpl A template for rendering the displayField in each selected item. Defaults to null.
     */
    displayFieldTpl: null,
    /**
     * @cfg {String} extraItemCls An additional css class to apply to each item.
     */
    extraItemCls: '',
    /**
     * @cfg {String/Object/Function} extraItemStyle Additional css style(s) to apply to each item. Should be a valid argument to Ext.Element.applyStyles.
     */
    extraItemStyle: '',
    /**
     * @cfg {String} expandBtnCls An additional class to add to the in-field expand button.
     */
    expandBtnCls: '',
    /**
     * @cfg {Boolean} fixFocusOnTabSelect When set to true, the component will not lose focus when a list item is selected with the TAB key. Defaults to true.
     */
    fixFocusOnTabSelect: true,
    /**
     * @cfg {Boolean} navigateItemsWithTab When set to true the tab key will navigate between selected items. Defaults to true.
     */
    navigateItemsWithTab: true,
    /**
     * @cfg {Boolean} pinList When set to true the select list will be pinned to allow for multiple selections. Defaults to true.
     */
    pinList: true,
    /**
     * @cfg {Boolean} preventDuplicates When set to true unique item values will be enforced. Defaults to true.
     */
    preventDuplicates: true,
    /**
     * @cfg {Boolean} removeValuesFromStore When set to true, selected records will be removed from the store. Defaults to true.
     */
    removeValuesFromStore: true,
    /**
     * @cfg {String} renderFieldBtns When set to true, will render in-field buttons for clearing the component, and displaying the list for selection. Defaults to true.
     */
    renderFieldBtns: true,
    /**
     * @cfg {Boolean} stackItems When set to true, the items will be stacked 1 per line. Defaults to false which displays the items inline.
     */
    stackItems: false,
    /**
     * @cfg {String} styleField The underlying data field that will be used to supply additional css styles to each item.
     */
    styleField : null,
    /**
     * @cfg {String} valueDelimiter The delimiter to use when joining and splitting value arrays and strings.
     */
    valueDelimiter: ',',
    initComponent:function() {
        this.items = new Ext.util.MixedCollection(false);
        this.usedRecords = new Ext.util.MixedCollection(false);
        this.hideTrigger = true;
        this.grow = false;
        this.resizable = false;
       	this.multiSelectMode = false;
       	
        Ext.ux.form.SuperBoxSelect.superclass.initComponent.call(this);
    },
    onRender:function(ct, position) {
        Ext.ux.form.SuperBoxSelect.superclass.onRender.call(this, ct, position);
        
        this.el.removeClass('x-form-text');
        this.el.addClass('x-superboxselect-input-field');
        
        this.wrapEl = this.el.wrap({
            tag : 'ul'
        });
        
        var extraClass = (this.stackItems === true) ? 'x-superboxselect-stacked' : '';
        
        if(this.renderFieldBtns){
        	extraClass += ' x-superboxselect-display-btns';
       	}
        this.outerWrapEl = this.wrapEl.wrap({
            tag : 'div',
            cls: 'x-form-text x-superboxselect ' + extraClass
        });
        
        this.inputEl = this.el.wrap({
            tag : 'li',
            cls : 'x-superboxselect-input'
        });
        
        if(this.renderFieldBtns){
        	this.setupFieldButtons();
        	this.manageClearBtn();
        }
        
        this.setupFormInterception();
    },
    setupFieldButtons : function(){
    	this.buttonWrap = this.outerWrapEl.createChild({
    		cls: 'x-superboxselect-btns'
    	});
    	this.buttonClear = this.buttonWrap.createChild({
    		tag:'div',
    		cls: 'x-superboxselect-btn-clear ' + this.clearBtnCls
    	});
    	
    	this.buttonExpand = this.buttonWrap.createChild({
    		tag:'div',
    		cls: 'x-superboxselect-btn-expand ' + this.expandBtnCls
    	});
    	
    	this.initButtonEvents();
    },
    initButtonEvents : function() {
    	this.buttonClear.addClassOnOver('x-superboxselect-btn-over');
    	this.buttonClear.on('click',function(e){
    		e.stopEvent();
    		if(this.disabled){
    			return;
    		}
    		this.clearValue();
    		this.el.dom.focus();
    	},this);
    	
    	this.buttonExpand.addClassOnOver('x-superboxselect-btn-over');
    	this.buttonExpand.on('click',function(e){
    		e.stopEvent();
    		if(this.disabled){
    			return;
    		}
    		if(this.isExpanded()){
    			this.multiSelectMode = false;
    		}else if(this.pinList){
    			this.multiSelectMode = true;
    		}
    		this.onTriggerClick();
    	},this);
    },
    removeButtonEvents : function() {
    	this.buttonClear.removeAllListeners();
    	this.buttonExpand.removeAllListeners();
    },
    clearCurrentFocus : function(){
    	if(this.currentFocus){
    		this.currentFocus.onLnkBlur();
			this.currentFocus = null;
    	}    		
    },
    initEvents : function(){
		this.el.on("keydown", this.onKeyDownHandler, this);
        this.el.on("keyup", this.onKeyUpBuffered,  this);
        this.el.on("click", function(){
        	this.clearCurrentFocus();  			
        	this.collapse();
        	this.autoSize();
        },  this);
        this.el.on('focus', this.clearCurrentFocus,this);
        this.el.on("blur", function(){
        	this.clearCurrentFocus();
			if(this.el.dom.value !== ''){
				this.applyEmptyText();
        		this.autoSize();
			}
		}, this);
		this.on('collapse',function(){
			this.multiSelectMode = false;
		},this);
		this.on('expand',this.clearCurrentFocus,this);
		
		this.wrapEl.on('click', function(e){
            e.stopEvent();
            this.collapse();
            this.el.dom.focus();
            this.clearCurrentFocus();
        }, this);
        this.outerWrapEl.on('click', function(e){
            e.stopEvent();
            this.collapse();
            this.el.dom.focus();
            this.clearCurrentFocus();
        }, this);
        
        var el = this.el;
        Ext.apply(this.inputEl, {
            'focus': function(){
                el.focus();
            }
        });
        
        Ext.ux.form.SuperBoxSelect.superclass.initEvents.call(this);
	    this.keyNav.tab = function(e){
 	      	if(this.fixFocusOnTabSelect && this.isExpanded()){
            	e.stopEvent();
                this.el.blur();
                this.onViewClick(false);
                this.focus(false,10);
                return true;
	        }
	 
            this.onViewClick(false);
			if(this.el.dom.value !== ''){
				this.setRawValue('');
			}
	
            return true;
        };
        
        this.keyNav.down = function(e){
        
        	if(!this.isExpanded() && !this.currentFocus){
           		this.onTriggerClick();
            }else{
                this.inKeyMode = true;
                this.selectNext();
            }
        };
        
        this.keyNav.enter = function(e){
            this.onViewClick();
            this.delayedCheck = true;
            this.unsetDelayCheck.defer(10, this);
            return true;
        };
    },
    markInvalid : function(msg){
        if(!this.rendered || this.preventMark){ // not rendered
            return;
        }
        this.outerWrapEl.addClass(this.invalidClass);
        msg = msg || this.invalidText;

        switch(this.msgTarget){
            case 'qtip':
                this.el.dom.qtip = msg;
                this.el.dom.qclass = 'x-form-invalid-tip';
                this.wrapEl.dom.qtip = msg;
                this.wrapEl.dom.qclass = 'x-form-invalid-tip';
                if(Ext.QuickTips){ // fix for floating editors interacting with DND
                    Ext.QuickTips.enable();
                }
                break;
            case 'title':
                this.el.dom.title = msg;
                this.wrapEl.dom.title = msg;
                this.outerWrapEl.dom.title = msg;
                break;
            case 'under':
                if(!this.errorEl){
                    var elp = this.getErrorCt();
                    if(!elp){ // field has no container el
                        this.el.dom.title = msg;
                        break;
                    }
                    this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
                    this.errorEl.setWidth(elp.getWidth(true)-20);
                }
                this.errorEl.update(msg);
                Ext.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
                break;
            case 'side':
                if(!this.errorIcon){
                    var elp = this.getErrorCt();
                    if(!elp){ // field has no container el
                        this.el.dom.title = msg;
                        break;
                    }
                    this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
                }
                this.alignErrorIcon();
                this.errorIcon.dom.qtip = msg;
                this.errorIcon.dom.qclass = 'x-form-invalid-tip';
                this.errorIcon.show();
                this.on('resize', this.alignErrorIcon, this);
                break;
            default:
                var t = Ext.getDom(this.msgTarget);
                t.innerHTML = msg;
                t.style.display = this.msgDisplay;
                break;
        }
        this.fireEvent('invalid', this, msg);
    },
    clearInvalid : function(){
        if(!this.rendered || this.preventMark){ // not rendered
            return;
        }
        this.outerWrapEl.removeClass(this.invalidClass);
        switch(this.msgTarget){
            case 'qtip':
                this.el.dom.qtip = '';
                this.wrapEl.dom.qtip ='';
                break;
            case 'title':
                this.el.dom.title = '';
                this.wrapEl.dom.title = '';
                this.outerWrapEl.dom.title = '';
                break;
            case 'under':
                if(this.errorEl){
                    Ext.form.Field.msgFx[this.msgFx].hide(this.errorEl, this);
                }
                break;
            case 'side':
                if(this.errorIcon){
                    this.errorIcon.dom.qtip = '';
                    this.errorIcon.hide();
                    this.un('resize', this.alignErrorIcon, this);
                }
                break;
            default:
                var t = Ext.getDom(this.msgTarget);
                t.innerHTML = '';
                t.style.display = 'none';
                break;
        }
        this.fireEvent('valid', this);
    },
    // private
    alignErrorIcon : function(){
        if(this.wrap){
            this.errorIcon.alignTo(this.wrap, 'tl-tr', [Ext.isIE ? 5 : 2, 3]);
        }
    },
    expand : function(){
        if(this.isExpanded() || !this.hasFocus){
            return;
        }
        this.list.alignTo(this.outerWrapEl, this.listAlign);
        this.list.show();
        this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
        Ext.getDoc().on('mousewheel', this.collapseIf, this);
        Ext.getDoc().on('mousedown', this.collapseIf, this);
        this.fireEvent('expand', this);
    },
    restrictHeight : function(){
    	var st = this.innerList.dom.scrollTop;
    	this.innerList.dom.style.height = '';
        var inner = this.innerList.dom;
        
        var pad = this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight;
        var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
        var ha = this.getPosition()[1]-Ext.getBody().getScroll().top;
        var hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height;
        var space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset-pad-5;
        h = Math.min(h, space, this.maxHeight);

        this.innerList.setHeight(h);
        this.list.beginUpdate();
        this.list.setHeight(h+pad);
        this.list.alignTo(this.outerWrapEl, this.listAlign);
        this.list.endUpdate();
        
        if(this.multiSelectMode){
        	this.innerList.dom.scrollTop = st;
        }
    },
    validateValue: function(val){
        if(this.items.getCount() == 0){
            if(this.allowBlank){
                 this.clearInvalid();
                 return true;
             }else{
                 this.markInvalid(this.blankText);
                 return false;
             }
        }else{
            this.clearInvalid();
            return true;
        }
    },
    setupFormInterception : function(){
        //intercept form.getValues to ensure that the input element is not included as an empty field
        var form;
        this.findParentBy(function(p){ 
            if(p.getForm){
                form = p.getForm();
            }
        });
        if(form){
	        var formGet = form.getValues;
	        form.getValues = function(asString){
	            if(this.items.getCount() > 0){
	                this.el.dom.disabled = true;
	            }
	            var oldVal = this.el.dom.value;
	            this.setRawValue('');
	            var vals = formGet.call(form, asString);
	            this.el.dom.disabled = false;
	            this.setRawValue(oldVal);
	            return vals;
	        }.createDelegate(this);
        }
    },
    onResize : function(w, h, rw, rh){
        this._width = w;
        ie8 = Ext.isIE && !Ext.isIE6 && !Ext.isIE7;
        var reduce = Ext.isIE6 ? 4 : Ext.isIE7 ? 1 : ie8 ? 1 : 0;
        this.outerWrapEl.setWidth(w-reduce);
        if(this.renderFieldBtns){
        	reduce +=  (this.buttonWrap.getWidth() + 20);
        	this.wrapEl.setWidth(w - reduce);
        }
        Ext.ux.form.SuperBoxSelect.superclass.onResize.call(this, w, h, rw, rh);
        this.autoSize();
    },
    onEnable: function(){
        Ext.ux.form.SuperBoxSelect.superclass.onEnable.call(this);
        this.items.each(function(item){
            item.enable();
        });
        this.initButtonEvents();
    },
    onDisable: function(){
        Ext.ux.form.SuperBoxSelect.superclass.onDisable.call(this);
        this.items.each(function(item){
            item.disable();
        });
        this.removeButtonEvents();
    },
    clearValue : function(){
        Ext.ux.form.SuperBoxSelect.superclass.clearValue.call(this);
        this.removeAllItems();
    },
    onKeyUp : function(e) {
        if (this.editable !== false && !e.isSpecialKey() && (!e.hasModifier() || e.shiftKey)) {
            this.lastKey = e.getKey();
            this.dqTask.delay(this.queryDelay);
        }
    },
    onKeyDownHandler : function(e,t) {
    	if((e.getKey() === e.DELETE || e.getKey() === e.SPACE)&& this.currentFocus){
    		e.stopEvent();
    		var toDestroy = this.currentFocus;
    		this.on('expand',function(){this.collapse();},this,{single: true});
    		var nextFocus, idx = this.items.indexOfKey(this.currentFocus.key);
    		
    		this.clearCurrentFocus();
    		
    		if(idx < (this.items.getCount() -1)){
    			nextFocus = this.items.itemAt(idx+1);
    		}
    		
    		toDestroy.preDestroy(true);
    		if(nextFocus){
    			(function(){
    				nextFocus.onLnkFocus();
    				this.currentFocus = nextFocus;
    			}).defer(200,this);
    		}
    	
    		return true;
    	}
    	
        var val = this.el.dom.value, it;
		//ctrl+enter for new items
        if(e.getKey() === e.ENTER){
            if (val !== "") {
				e.stopEvent();
				if (e.ctrlKey) {
					this.collapse();
					this.setRawValue('');
					this.fireEvent('newitemdata', this, val);
				}
				else {
					if (!this.isExpanded()) {
						this.setRawValue('');
						this.fireEvent('newitemdata', this, val);
					}
					else {
						this.onViewClick();
						this.delayedCheck = true;
						this.unsetDelayCheck.defer(10, this);
					}
				}
			}else{
				if(!this.isExpanded()){
            		return;
        		}
				this.onViewClick();
				this.delayedCheck = true;
				this.unsetDelayCheck.defer(10, this);
			}
            return true;
        }
        	
        if(val !== '') {
        	return;
        }
        
    	//select first item
    	if(e.getKey() === e.HOME){
    		e.stopEvent();
    		if(this.items.getCount() > 0){
    			this.collapse();
    			it = this.items.get(0);
    			it.el.focus();
    			
    		}
    		return true;
    	}
    	//backspace remove
        if(e.getKey() === e.BACKSPACE){
        	e.stopEvent();
        	if(this.currentFocus) {
        		var toDestroy = this.currentFocus;
	    		this.on('expand',function(){this.collapse();},this,{single: true});
	    		var nextFocus, idx = this.items.indexOfKey(toDestroy.key);
	    		
	    		this.clearCurrentFocus();
	    		if(idx < (this.items.getCount() -1)){
	    			nextFocus = this.items.itemAt(idx+1);
	    		}
	    		
	    		toDestroy.preDestroy(true);
	    		
	    		if(nextFocus){
	    			(function(){
	    				nextFocus.onLnkFocus();
	    				this.currentFocus = nextFocus;
	    			}).defer(200,this);
	    		}
	    		
	    		return;
        	}else{
                it = this.items.get(this.items.getCount() -1);
                if(it){
                	if(this.backspaceDeletesLastItem){
                		this.on('expand',function(){this.collapse();},this,{single: true});
                    	it.preDestroy(true);
                	}else{
                		if(this.navigateItemsWithTab){
                			it.onElClick();
                		}else{
                			this.on('expand',function(){
                				this.collapse();
                				this.currentFocus = it;
            					this.currentFocus.onLnkFocus.defer(20,this.currentFocus);
                			},this,{single: true});
                		}
                	}
                }
                return true;
            }
        }
        
        if(!e.isNavKeyPress()){
    		this.multiSelectMode = false;
    		this.clearCurrentFocus();
    		return;
    	}
        //arrow nav
        if(e.getKey() === e.LEFT || (e.getKey() === e.UP && !this.isExpanded())){
        	e.stopEvent();
            this.collapse();
            //get last item
            it = this.items.get(this.items.getCount()-1);
            if(this.navigateItemsWithTab){ 
            	//focus last el
                if(it){
                	it.focus(); 
                }
            }else{
            	//focus prev item
            	if(this.currentFocus){
            		var idx = this.items.indexOfKey(this.currentFocus.key);
            		this.clearCurrentFocus();
            		
            		if(idx !== 0){
            			this.currentFocus = this.items.itemAt(idx-1);
            			this.currentFocus.onLnkFocus();
            		}
            	}else{
            		this.currentFocus = it;
            		if(it){
            			it.onLnkFocus();
            		}
            	}
            }
            return true;
        }
        if(e.getKey() === e.DOWN){
        	if(this.currentFocus){
        		this.collapse();
        		e.stopEvent();
        		var idx = this.items.indexOfKey(this.currentFocus.key);
        		if(idx == (this.items.getCount() -1)){
		    		this.clearCurrentFocus.defer(10,this)
        		}else{
        			this.clearCurrentFocus();
        			this.currentFocus = this.items.itemAt(idx+1);
        			if(this.currentFocus){
        				this.currentFocus.onLnkFocus();
        			}
        		}
        		return true;
        	}
        }
        if(e.getKey() === e.RIGHT){
            this.collapse();
            it = this.items.itemAt(0);
            if(this.navigateItemsWithTab){ 
            	//focus first el
                if(it){
                	it.focus(); 
                }
            }else{
            	if(this.currentFocus){
            		var idx = this.items.indexOfKey(this.currentFocus.key);
            		this.clearCurrentFocus();
            		if(idx < (this.items.getCount() -1)){
            			this.currentFocus = this.items.itemAt(idx+1);
            			if(this.currentFocus){
            				this.currentFocus.onLnkFocus();
            			}
            		}
            	}else{
            		this.currentFocus = it;
            		if(it){
            			it.onLnkFocus();
            		}
            	}
            }
            return;
        }
    },
    reset :  function(){
        Ext.ux.form.SuperBoxSelect.superclass.reset.call(this);
        this.autoSize();
        this.setRawValue('');
        this.el.focus();
    },
    applyEmptyText : function(){
        if(this.items.getCount() > 0){
            this.el.removeClass(this.emptyClass);
            this.setRawValue('');
            return;
        }
        if(this.rendered && this.emptyText && this.getRawValue().length < 1){
            this.setRawValue(this.emptyText);
            this.el.addClass(this.emptyClass);
        }
    },
    /**
     * Removes all items from the SuperBoxSelect component
     * @methodOf Ext.ux.form.SuperBoxSelect
     * @name removeAllItems
     */
    removeAllItems: function(){
        this.items.each(function(item){
            item.preDestroy(true);
        },this);
        this.manageClearBtn();
    },
    resetStore: function(){
        if(!this.removeValuesFromStore){
            return;
        }
        this.usedRecords.each(function(rec){
            this.store.add(rec);
        },this);
        this.sortStore();
    },
    sortStore: function(){
        var ss = this.store.getSortState();
        if(ss && ss.field){
            this.store.sort(ss.field, ss.direction);
        }
    },
    getCaption: function(dataObject){
        if(typeof this.displayFieldTpl === 'string') {
            this.displayFieldTpl = new Ext.XTemplate(this.displayFieldTpl);
        }
        var caption, recordData = dataObject instanceof Ext.data.Record ? dataObject.data : dataObject;
      
        if(this.displayFieldTpl) {
            caption = this.displayFieldTpl.apply(recordData);
        } else if(this.displayField) {
            caption = recordData[this.displayField];
        }
        
        return caption;
    },
    addRecord : function(record){
        var display = record.data[this.displayField];
        var caption = this.getCaption(record);
        var val = record.data[this.valueField];
        var cls = this.classField ? record.data[this.classField] : '';
        var style = this.styleField ? record.data[this.styleField] : '';
        
        if(this.removeValuesFromStore){
            this.usedRecords.add(val,record);
            this.store.remove(record);
        }
        
        this.fireEvent('additem',this,val);
        
        this.addItemBox(val,display,caption,cls,style);
    },
    createRecord : function(recordData){
        if(!this.recordConstructor){
            var recordFields = [
                {name: this.valueField},
                {name: this.displayField}
            ];
            if(this.classField){
                recordFields.push({name: this.classField});
            }
            if(this.styleField){
                recordFields.push({name: this.styleField});
            }
            this.recordConstructor = Ext.data.Record.create(recordFields);
        }
        return new this.recordConstructor(recordData);
    },
    /**
     * Adds an item to the SuperBoxSelect component if the {@link #Ext.ux.form.SuperBoxSelect-allowAddNewData} config is set to true.
     * @methodOf Ext.ux.form.SuperBoxSelect
     * @name addItem
     * @param {Object} newItemObject An object literal containing the property names and values for an item. The property names must match those specified in {@link #Ext.ux.form.SuperBoxSelect-displayField}, {@link #Ext.ux.form.SuperBoxSelect-valueField} and {@link #Ext.ux.form.SuperBoxSelect-classField} 
     */
    addItem : function(newItemObject){
        
        var val = newItemObject[this.valueField];

        if(this.disabled) {
            return false;
        }
        if(this.preventDuplicates && this.hasValue(val)){
            return;
        }
        
        //use existing record if found
        var record;
        if(record = this.findRecord(this.valueField, val)){
            this.addRecord(record);
            return;
        }
        
        //else it's a new item
        if(!this.allowAddNewData){
            return;
        }
        var rec = this.createRecord(newItemObject);
        this.store.add(rec);
        this.addRecord(rec);
        
        return true;
    },
    addItemBox : function(itemVal,itemDisplay, itemCaption, itemClass, itemStyle) {
        var parseStyle = function(s){
            var ret = '';
            if(typeof s == 'function'){
                ret = s.call();
            }else if(typeof s == 'object'){
                for(p in s){
                    ret+= p +':'+s[p]+';';
                }
            }else if(typeof s == 'string'){
                ret = s + ';';
            }
            return ret;
        };
        var itemKey = Ext.id(null,'sbx-item');
        var box = new Ext.ux.form.SuperBoxSelectItem({
            owner: this,
            renderTo: this.wrapEl,
            cls: this.extraItemCls + ' ' + itemClass,
            style: parseStyle(this.extraItemStyle) + ' ' + itemStyle,
            caption: itemCaption,
            display: itemDisplay,
            value:  itemVal,
            key: itemKey,
            listeners: {
                'remove': function(item){
                    if(this.fireEvent('beforeremoveitem',this,item.value) === false){
                        return;
                    }
                    this.items.removeKey(item.key);
                    if(this.removeValuesFromStore){
                        if(this.usedRecords.containsKey(item.value)){
                            this.store.add(this.usedRecords.get(item.value));
                            this.usedRecords.removeKey(item.value)
                            this.sortStore();
                            if(this.view){
                                this.view.render();
                            }
                        }
                    }
                    this.fireEvent('removeitem',this,item.value);
                },
                destroy: function(){
                	this.collapse();
                    this.autoSize();
                    this.validateValue();
                    this.manageClearBtn();
                },
                scope: this
            }
        });
        box.render();

        box.hidden = this.el.insertSibling({
            tag:'input', 
            type:'hidden', 
            value: itemVal,
            name: (this.hiddenName || this.name)
        },'before');

        this.items.add(itemKey,box);
        this.applyEmptyText();
        this.autoSize();
        this.validateValue();
        this.manageClearBtn();
    },
    manageClearBtn : function(){
    	if(!this.renderFieldBtns){
    		return;
    	}
    	var cls = 'x-superboxselect-btn-hide';
    	if(this.items.getCount() == 0){
    		this.buttonClear.addClass(cls);
    	}else{
    		this.buttonClear.removeClass(cls);
    	}
    },
    findInStore : function(val){
        var index = this.store.find(this.valueField, val.trim());
        if(index > -1){
            return this.store.getAt(index);
        }
        return false;
    },
    /**
     * Returns a String value containing a concatenated list of item values. The list is concatenated with the {@link #Ext.ux.form.SuperBoxSelect-valueDelimiter}.
     * @methodOf Ext.ux.form.SuperBoxSelect
     * @name getValue
     * @return {String} a String value containing a concatenated list of item values. 
     */
    getValue : function() {
        var ret = [];
        
        this.items.each(function(item){
        
            ret.push(item.value);
        });
        return ret.join(this.valueDelimiter);
    },
    /**
     * Returns an Array of item objects containing the {@link #Ext.ux.form.SuperBoxSelect-displayField}, {@link #Ext.ux.form.SuperBoxSelect-valueField} and {@link #Ext.ux.form.SuperBoxSelect-classField} properties.
     * @methodOf Ext.ux.form.SuperBoxSelect
     * @name getValueEx
     * @return {Array} an array of item objects. 
     */
    getValueEx : function() {
        var ret = [];
        this.items.each(function(item){
            var newItem = {};
            newItem[this.valueField] = item.value;
            newItem[this.displayField] = item.display;
            newItem[this.classField]= item.cls;
            ret.push(newItem);
        });
        return ret;
    },
    /**
     * Sets the value of the SuperBoxSelect component.
     * @methodOf Ext.ux.form.SuperBoxSelect
     * @name setValue
     * @param {String} value a String value containing a concatenated list of item values. The list should be concatenated with the {@link #Ext.ux.form.SuperBoxSelect-valueDelimiter  
     */
    setValue: function(value){
        this.removeAllItems();
        this.store.clearFilter();
        this.resetStore();
        
        values = value.split(this.valueDelimiter);
        
        Ext.each(values,function(val){
            var record;
            if(record = this.findRecord(this.valueField, val)){
                this.addRecord(record);
            }
        },this);
        
    },
    /**
     * Sets the value of the SuperBoxSelect component, adding new items that don't exist in the data store if the {@link #Ext.ux.form.SuperBoxSelect-allowAddNewData} config is set to true.
     * @methodOf Ext.ux.form.SuperBoxSelect
     * @name setValue
     * @param {Array} data An Array of item objects containing the {@link #Ext.ux.form.SuperBoxSelect-displayField}, {@link #Ext.ux.form.SuperBoxSelect-valueField} and {@link #Ext.ux.form.SuperBoxSelect-classField} properties.  
     */
    setValueEx : function(data){
        this.removeAllItems();
        this.store.clearFilter();
        this.resetStore();
        
        if(!Ext.isArray(data)){
            data = [data];
        }
        Ext.each(data,function(item){
            this.addItem(item);
        },this);
    },
    /**
     * Returns true if the SuperBoxSelect component has a selected item with a value matching the 'val' parameter.
     * @methodOf Ext.ux.form.SuperBoxSelect
     * @name hasValue
     * @param {Mixed} val The value to test.
     * @return {Boolean} true if the component has the selected value, false otherwise.
     */
    hasValue: function(val){
        var has = false;
        this.items.each(function(item){
            if(item.value == val){
                has = true;
                return false;
            }
        },this);
        return has;
    },
    onSelect : function(record, index) {
        var val = record.data[this.valueField];
        
        if(this.preventDuplicates && this.hasValue(val)){
            return;
        }
        
        this.setRawValue('');
        this.lastSelectionText = '';
        
        if(this.fireEvent('beforeadditem',this,val) !== false){
            this.addRecord(record);
        }
        if(this.store.getCount() == 0 || !this.multiSelectMode){
        	this.collapse();
        }else{
        	this.restrictHeight();
        }
    },
    onDestroy : function() {
        this.items.each(function(item){
            item.preDestroy(true);
        },this);
    
        this.inputEl.removeAllListeners();
        this.inputEl.remove();
        if(this.renderFieldBtns){
        	this.buttonClear.removeAllListeners();
        	this.buttonClear.remove();
        	this.buttonExpand.removeAllListeners();
        	this.buttonExpand.remove();
        	this.buttonWrap.remove();
        }
        this.wrapEl.removeAllListeners();
        this.wrapEl.remove();
        
        this.outerWrapEl.removeAllListeners();
        this.outerWrapEl.remove();
        
        Ext.ux.form.SuperBoxSelect.superclass.onDestroy.call(this);
    },
    autoSize : function(){
        if(!this.rendered){
            return;
        }
        if(!this.metrics){
            this.metrics = Ext.util.TextMetrics.createInstance(this.el);
        }
        var el = this.el;
        var v = el.dom.value;
        var d = document.createElement('div');

        if(v === "" && this.emptyText && this.items.getCount() < 1){
            v = this.emptyText;
        }
        d.appendChild(document.createTextNode(v));
        v = d.innerHTML;
        d = null;
        v += "&#160;";
        var w = Math.max(this.metrics.getWidth(v) +  24, 24);
        if(typeof this._width != 'undefined'){
            w = Math.min(this._width, w);
        }
        this.el.setWidth(w);
        
        if(Ext.isIE){
            this.el.dom.style.top='0';
        }
    }
});
Ext.reg('superboxselect', Ext.ux.form.SuperBoxSelect);
/*
 * @private
 */
Ext.ux.form.SuperBoxSelectItem = function(config){
    Ext.apply(this,config);
    Ext.ux.form.SuperBoxSelectItem.superclass.constructor.call(this); 
};
/*
 * @private
 */
Ext.ux.form.SuperBoxSelectItem = Ext.extend(Ext.ux.form.SuperBoxSelectItem,Ext.Component, {
    initComponent : function(){
        Ext.ux.form.SuperBoxSelectItem.superclass.initComponent.call(this); 
    },
    onElClick : function(e){
    	this.owner.clearCurrentFocus();
    	this.owner.collapse();
    	if(this.owner.navigateItemsWithTab){
    		this.focus();
    	}else{
    		this.owner.el.dom.focus();
    		var that = this;
    		(function(){
    			this.onLnkFocus();
    			this.owner.currentFocus = this;
    		}).defer(10,this)
    	}
    },
    
    onLnkClick : function(e){
        if(e) {
        	e.stopEvent();
        }
        this.preDestroy();
        if(!this.owner.navigateItemsWithTab){
        	this.owner.el.focus();
        }
    },
    onLnkFocus : function(){
        this.el.addClass("x-superboxselect-item-focus");
        
    },
    
    onLnkBlur : function(){
        this.el.removeClass("x-superboxselect-item-focus");
    },
    
    enableElListeners : function() {
        this.el.on('click', this.onElClick, this, {stopEvent:true});
       
        this.el.addClassOnOver('x-superboxselect-item x-superboxselect-item-hover');
    },

    enableLnkListeners : function() {
        this.lnk.on({
            'click': this.onLnkClick,
            'focus': this.onLnkFocus,
            'blur':  this.onLnkBlur,
            scope: this
        });
    },
	
    enableAllListeners : function() {
        this.enableElListeners();
        this.enableLnkListeners();
    },
    disableAllListeners : function() {
       	this.el.removeAllListeners();
        this.lnk.un('click', this.onLnkClick, this);
        this.lnk.un('focus', this.onLnkFocus, this);
        this.lnk.un('blur', this.onLnkBlur, this);
    },
    //autoEl : 'li',
    onRender : function(ct, position){
    	
        Ext.ux.form.SuperBoxSelectItem.superclass.onRender.call(this, ct, position);
		
        if(this.el){
        	this.el.remove();
        }
        
        this.el = ct.createChild({ tag: 'li' }, ct.last());
        this.el.addClass('x-superboxselect-item');
		
        var btnEl = this.owner.navigateItemsWithTab ? ( Ext.isSafari ? 'button' : 'a') : 'span';
        var itemKey = this.key;
        
		Ext.apply(this.el, {
            'focus': function(){
            	this.down(btnEl +'.x-superboxselect-item-close').focus();
            },
            'preDestroy': function(){
                this.preDestroy();
            }.createDelegate(this)
        });
        
        this.enableElListeners();

        this.el.update(this.caption);

		var cfg = {
            'tag': btnEl,
            'class': 'x-superboxselect-item-close',
            tabIndex : this.owner.navigateItemsWithTab ? '0' : '-1'
        };
        if(btnEl === 'a'){
        	cfg.href = '#';
        }
    	this.lnk = this.el.createChild(cfg);
    	
    	
        if(!this.disabled) {
            this.enableLnkListeners();
        }else {
            this.disableAllListeners();
        }
        
        this.on({
            'disable': this.disableAllListeners,
            'enable': this.enableAllListeners,
            scope: this
        });

        this.setupKeyMap();
    },
    setupKeyMap : function(){
    	new Ext.KeyMap(this.lnk, [
            {
                key: [Ext.EventObject.BACKSPACE, Ext.EventObject.DELETE, Ext.EventObject.SPACE],
                fn: function(){
                    if(this.fireEvent('remove', this) !== false){
                        this.preDestroy();
                        this.on('expand',function(){this.collapse();},this,{single: true});
                    }
                }.createDelegate(this)
            },
            {
                key: [Ext.EventObject.RIGHT,Ext.EventObject.DOWN],
                fn: function(){
                    this.moveFocus('right');
                }.createDelegate(this)
            },
            {
                key: [Ext.EventObject.LEFT,Ext.EventObject.UP],
                fn: function(){
                    this.moveFocus('left');
                }.createDelegate(this)
            },
            {
                key: [Ext.EventObject.HOME],
                fn: function(){
                    l = this.owner.items.get(0);
	        		l.el.focus();
                }.createDelegate(this)
            },
            {
                key: [Ext.EventObject.END],
                fn: function(){
                    this.owner.el.focus();
                }.createDelegate(this)
            },
            {
                key: Ext.EventObject.ENTER,
                fn: function(){
                }.createDelegate(this)
            }
        ]).stopEvent = true;
    },
    /*
     * @private
     */
    moveFocus : function(dir) {
    	var el;
        if(dir === 'left'){
            el = this.el.prev();
        } else {
            el = this.el.next();
        }
        if(!el){
            el = this.owner.el;
        }   
        el.focus();
    },
    /*
     * @private
     */    
    preDestroy : function(supressEffect) {
    	if(this.fireEvent('remove', this) === false){
    		return;
    	}
        var actionDestroy = function(){
        	if(this.owner.navigateItemsWithTab){
        		this.moveFocus('right');
        	}
        	this.hidden.remove();
            this.hidden = null;
            this.destroy();
        };
        
        if(supressEffect){
            actionDestroy.call(this);
        } else {
            this.el.hide({
                duration: .2,
                callback: actionDestroy,
                scope: this
            });
        }
        return this;
    },
    onDestroy : function() {
       	this.lnk.removeAllListeners();
        this.lnk.remove();
        this.el.removeAllListeners();
        this.el.remove();
        
        Ext.ux.form.SuperBoxSelectItem.superclass.onDestroy.call(this);
    }
});