//See HomePage.asp for definition of tools var.

// To Do 
/*
1) Namespace everything, no global vars --> Ext.ns('AV.mhp');
2) Place Icons in header, remove top toolbar
3) Example of adding "tool" to header for news begins at line 178 and is currently commented out.
4) don't forget about using xtype instead of new

Panel Factory Example
var cfg = { title: 'This is my panel' }, 
		pnl = AV.mhp.panelFactory(cfg);
AV.mhp  = {
	panelFactory: function(config)
	{
		var baseCfg = { 
			id: 'panel_cal',
			title: 'Upcoming Events',
			draggable: draggable,
			height: panelheight
		};
			
		baseCfg = Ext.apply(baseCfg, config);
	}
};
*/

var panels = [];

//--------------------
var loadingDiv = '<div style="text-align: center; margin-top: 3em;"><img src="/images/loading.gif" width="16" height="16" alt="" /><div style="font-size: 9px; color: #666; margin-top: 5px;">Loading...</div></div>';

var draggable = true;
if ((AV.site_type_id == '2' || AV.site_type_id == '7') && !isGA) {
	draggable = false;
}
var panelheight = 'auto';
var weatherheight = 'auto';
var welcomeheight = 'auto';
var newsheight = 'auto';
var docheight = 'auto';
if ((AV.site_type_id == '2' || AV.site_type_id == '7')) {
	weatherheight = 137;
	welcomeheight = 137;
	newsheight = 117;
	docheight = 117;
	panelheight = 95;
	if (isSA || isGA) {
		weatherheight = 150;
		welcomeheight = 150;
		newsheight = 145;
		docheight = 145;
		panelheight = 125;
	}
}

var panel_acct_items = [];
panel_acct_items.panel_acct_account = {
  id: 'panel_acct_account',
  title:'Activity',
  //contentEl: 'panel_acct_account_content',
  html: loadingDiv,
  autoDestroy: false,
  border: false,
  autoLoad: {
    url: '/member/HomePage_ajax.asp?l=acct_account&c=' + portalNumCols,
    timeout: 180
  }
};
panel_acct_items.panel_acct_profile = {
  id: 'panel_acct_profile',
  title:'Profile',
  //contentEl: 'panel_acct_profile_content',
  html: loadingDiv,
  autoDestroy: false,
  border: false,
  listeners: {activate: handleActivate}
};
panel_acct_items.panel_acct_subscriptions = {
  id: 'panel_acct_subscriptions',
  title:'Subscriptions',
  //contentEl: 'panel_acct_subscriptions_content',
  html: loadingDiv,
  autoDestroy: false,
  border: false,
  listeners: {activate: handleActivate}
};

var panel_acct_tabs_items;
if (showAcct === true)
{
  panel_acct_tabs_items = [panel_acct_items.panel_acct_account, panel_acct_items.panel_acct_profile, panel_acct_items.panel_acct_subscriptions];
}
else
{
  panel_acct_tabs_items = [panel_acct_items.panel_acct_profile, panel_acct_items.panel_acct_subscriptions];
}

var panel_acct_tabs = {
  id: 'panel_acct_tabs',
  width: '100%',
  xtype: 'tabpanel',
  //draggable: draggable,
  activeTab: 0,
  enableTabScroll: true,
  plain: true,
  height: 200,
  autoDestroy: false,
  defaults: { autoScroll: true, autoDestroy: false },
  items: panel_acct_tabs_items
};

panels.panel_acct = {
  id: 'panel_acct',
  //header: true,
  title: 'My Account',
  //headerAsText: false,
  draggable: draggable,
  style:'padding-top:0px;margin-top:5px;',
  tools: tools,
  autoDestroy: false,
  items: [panel_acct_tabs]
};

//--------------------
panels.panel_news = {
	id: 'panel_news',
	title: 'Latest News',
	draggable: draggable,
	tools: tools,
	height: newsheight,
	autoScroll: true,
	autoDestroy: false,
	contentEl: 'panel_news_content',
	/*tools	: [ 
		{ id: 'gear', handler: function(evt, toolEl, pnl, toolCfg) { alert(pnl.getId()); } }, 
		{ id: 'close' }
	],*/
	tbar: new Ext.Toolbar({
		hidden: true,
		cls: 'home-panel-toolbar',
		items: [
			'->',
			new Ext.Button({
				id: "panel_news_edit",
				icon: "/images/icons/icon-pencil.png",
				menu: new Ext.menu.Menu({
					items: [],
					listeners: {
						itemclick: function(item, e) {
							var arr = item.id.split("|");
							var rec = Ext.getCmp('panel_news_edit').store.getAt(parseInt(arr[0]));
							var id = rec.get("db_id");
							var title = rec.get("link_text");
							AV.EditorLauncher.news(id, title, Ext.get("panel_news_edit"));
						},
						scope: this
					}
				})
			}),
			new Ext.Button({
				icon: "/images/icons/icon-small-add.png",
				listeners: {
					click: function(btn, e) {
						if (Ext.getCmp('panel_news_edit').store.getCount() == 10) {
							Ext.Msg.alert('Error', 'You are allowed to have no more than 10 news items.');
						} else {
						AV.EditorLauncher.news('', 'Add News Article', Ext.get(btn.id));
						}
					},
					scope: this
				}
			})
		]
	}),
	listeners: {
		/*
		afterRender: function(pnl) {
					// Get the span child of the header element and return an Ext element
			var hdrSpan = Ext.get(pnl.header.child('span')), 
					
					// New config button (Ext.DomHelper)
					oCfg = { tag: 'div', class: 'x-tool x-tool-gear', html: '&nbsp;'},
					
					// Insert a new 'button' dom element before the header span, and return the created dom element
					domCfg	= hdrSpan.insertSibling(oCfg , 'before', true  ),

					// Get the Ext element for the domCfg so we can attach an event
					elCfg = Ext.get(domCfg);
			
			// Attach a click event to the element we just created
			elCfg.on('click', function(oEvt, domEl, oPts) { alert('News Config'); } );

			//pnl.header.getEl().appendChild('<div class="x-tool x-tool-close">&nbsp;</div>');
		},
		*/
		render: function(obj) {
			if ((AV.site_type_id == '2' || AV.site_type_id == '7') && (isGA || isSA)) {
				obj.getTopToolbar().show();
			}
		}
	}
};

//--------------------
panels.panel_cal = {
	id: 'panel_cal',
	title: 'Upcoming Events',
	draggable: draggable,
	height: panelheight,
	tools: tools,
	autoDestroy: false,
	autoScroll: true, /*height will be set if # of calendar items makes the panel too large - see xsl */
	contentEl: 'panel_cal_content',
	tbar: new Ext.Toolbar({
		cls: "home-panel-toolbar",
		hidden: true,
		items: [
			'->',
			new Ext.Button({
				id: "panel_cal_edit",
				icon: "/images/icons/icon-pencil.png",
				menu: new Ext.menu.Menu({
					items: [],
					listeners: {
						itemclick: function(item, e) {
							var arr = item.id.split("|");
							var rec = Ext.getCmp('panel_cal_edit').store.getAt(parseInt(arr[0]));
							var id = rec.get("db_id");
							var id2 = rec.get("db_id2");
							var id3 = rec.get("db_id3");
							var title = rec.get("link_text");
							AV.ContentWindow.showWindow({ url: '/cal2/Ext/EventAdd.asp?event_id=' + id + '&event_date_id=' + id3, title: title, editors: { objEditWin: true }, helpUrl: '/cal2/EventHelp.asp', edit: true, target: Ext.get("panel_cal_edit"), loadFn: function() { AV.ContentWindow.showEditor("objEditWin"); AV.ContentWindow.formWindow.el.unmask(); } });
						},
						scope: this
					}
				})
			}),
			new Ext.Button({
				icon: "/images/icons/icon-small-add.png",
				listeners: {
					click: function(btn, e) {
						AV.ContentWindow.showWindow({ url: '/cal2/Ext/EventAdd.asp', title: 'Add Event', editors: { objEditWin: true }, helpUrl: '/cal2/EventHelp.asp', add: true, target: Ext.get(btn.id), loadFn: function() { AV.ContentWindow.showEditor("objEditWin"); AV.ContentWindow.formWindow.el.unmask(); } });
					},
					scope: this
				}
			})
		]
	}),
	listeners: {
		render: function(obj) {
			if ((AV.site_type_id == '2' || AV.site_type_id == '7') && (isGA || isSA)) {
				obj.getTopToolbar().show();
			}
		}
	}
};


//----------------------
// TO DO: Make value for default splitbutton value dependent on # and type of payment providers TS 1/26/2009
panels.panel_payment = {
	id: 'panel_payment',
	title: 'Pay Online',
	draggable: draggable,
	autoDestroy: false,
	//height: Ext.isIE ? 101 : 115,
	height: panelheight,
	tools: tools,
	bodyStyle: "text-align:center",
	contentEl: 'panel_payment_content',
	items: [
		new Ext.Container({
			autoEl: {
				tag: "div",
				style: "text-align:left;padding:8px 10px 12px;font-weight:bold",
				html: "Pay your assessment online."
			}
		}),
		new Ext.SplitButton({
			text:"Pay Online",
			id:"pay-online-button",
			width: 100,
			style: "margin:auto;",
			value: "/RequestStatus/Status_po.asp?assn_id=" + AV.assn_id,
			menu: [],
			listeners: {
				click: function(btn,e){
					location.href = btn.value;
				},
				scope: this
			}
		})
	]
}


//--------------------
var zipTest = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
Ext.apply(Ext.form.VTypes, {
    //  vtype validation function
    US_zip_code: function(val, field) {
        return zipTest.test(val);
    },
    // vtype Text property: The error text to display when the validation function returns false
   US_zip_codeText: 'Not a valid US zip Code.  Must be in the formats "99999" or "99999-9999".',
    // vtype Mask property: The keystroke filter mask
   US_zip_codeMask: /[\d\-]/i
});

panels.panel_weather = {
	id: 'panel_weather',
	title: 'Weather',
	draggable: draggable,
	style: "padding-top:0px;margin-top:5px;",
	tools: tools,
	height: weatherheight,
	autoDestroy: false,
	contentEl: 'panel_weather_content',
	tbar: new Ext.Toolbar({
		cls: "home-panel-toolbar",
		hidden: true,
		id: "panel_weather_tbar",
		items: [
			'->',
			{
				icon: "/images/icons/icon-pencil.png",
				id: "btn_edit_weather",
				listeners: {
					click: function(btn, e) {
						var win = new Ext.Window({
							modal					: true,
							width					: 250,
							animateTarget	: Ext.get("btn_edit_weather"),
							animShowCfg		: { duration: .5 },
							animHideCfg		: { duration: .5 },

							title					: "Edit Zip Code",
							bodyStyle			: "padding:5px;background-color:#fff;",
							items: [ 
								/*new Ext.FormPanel(*/{
									xtype: 'form',
									id: "panel_weather_edit",
									margins: 5,
									labelWidth: 75,
									border: false,
									items: [
										new Ext.form.TextField({
											id: 'weather_zip',
											fieldLabel: "Zip Code",
											width: 100,
											vtype: 'US_zip_code',
											value: AV.weather_zip,
											validationEvent: 'onblur',
											listeners: {
												render: function(obj) {
													obj.el.dom.setAttribute('maxLength', 5);
												}
											}
										})
									]
								}
							],
							buttons: [
								{
									text: "Save",
									iconCls: "MHP_save-button",
									listeners: {
										click: function(btn, e) {
											if (Ext.getCmp("panel_weather_edit").getForm().isValid()) {
												Ext.Ajax.request({
													url: 'HomePage_ajax.asp?z=' + Ext.getCmp('weather_zip').getValue(),
													success: function(response, options) {
														if (response.responseText === 'OK') {
															AV.weather_zip = Ext.getCmp('weather_zip').getValue();
															win.hide(win.minimizeTo,function(win) {
																win.close(true);
																win.destroy();
																delete (win);
															},this);
															//reload weather image for the new zip
															var img_weather = Ext.get('weather_img').dom;
															if (!AV.img_weather_src_orig) {
																AV.img_weather_src_orig = img_weather.src;
															}
															img_weather.src = '../Library/Ext/ext-3.0.3/resources/images/default/shared/blue-loading.gif';
															img_weather.onload = function() {
																img_weather.src = AV.img_weather_src_orig + '&r=' + Math.random();	//added Math.random to avoid cached image								                                
																img_weather.onload = function() { };  //unattach to avoid endless loop
															};
														}
													},
													failure: function(response, options) {
														//alert(response.responseText);
													}
												});
											}
										},
										scope: this
									}
								},
								{
									text: "Cancel",
									iconCls: "MHP_cancel-button",
									listeners: {
										click: function(btn, e) {
											win.hide(win.minimizeTo,function(win) {
												win.close(true);
												win.destroy();
												delete (win);
											},this);
										},
										scope: this
									}
								}
							]
						});
						win.minimizeTo=Ext.get("btn_edit_weather");
						win.show();
					},
					scope: this
				}
			}
		]
	}),
	listeners: {
		render: function(obj) {
			if ((AV.site_type_id == '2' || AV.site_type_id == '7') && (isGA || isSA)) {
				obj.getTopToolbar().show();
			}
		}
	}
};

//--------------------
panels.panel_messages = {
	id: 'panel_messages',
	title: 'Latest Messages',
	draggable: draggable,
	tools: tools,
	autoDestroy: false,
	contentEl: 'panel_messages_content'
};

//--------------------
panels.panel_resource = {
	id: 'panel_resource',
	title: 'Latest Documents',
	draggable: draggable,
	height: docheight,
	tools: tools,
	autoScroll: true,
	autoDestroy: false,
	contentEl: 'panel_resource_content',
	tbar: new Ext.Toolbar({
		cls: "home-panel-toolbar",
		hidden: true,
		items: [
			'->',
			new Ext.Button({
				id: "panel_resource_edit",
				icon: "/images/icons/icon-pencil.png",
				menu: new Ext.menu.Menu({
					items: [],
					listeners: {
						itemclick: function(item,e) {
							var arr = item.id.split("|");
							var rec = Ext.getCmp('panel_resource_edit').store.getAt(parseInt(arr[0]));
							var id = rec.get("db_id");
							var doc_filename = rec.get("attr_value");
							var title = rec.get("link_text");
							AV.EditorLauncher.document(id, default_doc_cat_id, title, Ext.get("panel_resource_edit"))
						},
						scope: this
					}
				})
			}),
			new Ext.Button({
				icon: "/images/icons/icon-small-add.png",
				listeners: {
					click: function(btn,e) {
						if (Ext.getCmp('panel_resource_edit').store.getCount() == 10) {
							Ext.Msg.alert('Error','You are allowed to have no more than 10 documents.');
						} else {
						AV.EditorLauncher.document('', default_doc_cat_id, 'Add Resource Item', Ext.get(btn.id));
						}
					},
					scope: this
				}
			})
		]
	}),
	listeners: {
		render: function(obj) {
			if ((AV.site_type_id == '2' || AV.site_type_id == '7') && (isGA || isSA) ) {
				obj.getTopToolbar().show();
			}
		}
	}
};

//--------------------
panels.panel_discuss = {
	id: 'panel_discuss',
	title: 'Latest Discussion',
	draggable: draggable,
	tools: tools,
	autoDestroy: false,
	contentEl: 'panel_discuss_content'
};

//--------------------
panels.panel_gallery = {
	id: 'panel_gallery',
	title: 'Latest Images',
	draggable: draggable,
	tools: tools,
	autoDestroy: false,
	height: 180,
	autoScroll: true,
	contentEl: 'panel_gallery_content'
};

//--------------------
panels.panel_classifieds = {
	id: 'panel_classifieds',
	title: 'Latest Classifieds',
	draggable: draggable,
	tools: tools,
	autoDestroy: false,
	contentEl: 'panel_classifieds_content'
};

//--------------------
panels.panel_board = {
	id: 'panel_board',
	title: 'Board Items',
	draggable: draggable,
	//contentEl: 'panel_board_content',
	tools: tools,
	html: loadingDiv,
	autoDestroy: false,
	autoLoad: {
		url: '/member/HomePage_ajax.asp?l=items_board&w=' + ttWidth,
		timeout: 90,
		scripts: true
	}
};

function getHTMLContent(id) {
	var panels = oPanels.panels;
	for (var a = 0; a < panels.length; a++) {
		if (panels[a].panel_id === id) {
			return panels[a].panel_content.replace(/&lt;/gi,"<").replace(/&gt;/gi,">");
		}
	}
}
//--------------------
panels.panel_welcome = {
	id: 'panel_welcome',
	title: 'Welcome',
	draggable: draggable,
	tools: tools,
	autoDestroy: false,
	autoScroll: true,
	height: welcomeheight,
	header: true,
	bodyStyle: 'padding-top:5px;',
	style: "padding-top:0px;margin-top:5px;",
	preventBodyReset: true,
	tbar: new Ext.Toolbar({
		cls: "home-panel-toolbar",
		hidden: true,
		id: "panel_html_tbar",
		items: [
			'->',
			{
				id: "btn_edit_welcome",
				icon: "/images/icons/icon-pencil.png",
				listeners: {
					click: function(btn,e) {
						if(!panels.panel_welcome.welcometext) {
							panels.panel_welcome.welcometext = getHTMLContent("panel_welcome");
						}
						var cssfilename = "";
						var win = new Ext.Window({
							modal: true,
							height: 350,
							width: 690,
							layout:'fit',
							animateTo: Ext.get("btn_edit_welcome"),
							animShowCfg: { duration: .5 },
							animHideCfg: { duration: .5 },
							title: "Edit Welcome HTML",
							bodyStyle: "padding:5px;background-color:#fff;",
							items: [
								new Ext.FormPanel({
								  id: "panel_html_edit",
									margins: 5,
									labelWidth: 75,
									height:'auto',
									border: false,
									items: [
										new AV.EditorPanel({
											id: "panel_welcome_editor",
											type:"objEditWin",
											height:'100%',
											hideLabel:true,
											text: panels.panel_welcome.welcometext,
											valuefield: "attr_val"
										})
									]
								})
							],
							buttons: [
								{
									text: "Save",
									iconCls:  "MHP_save-button",
									listeners: {
										click: function(btn,e) {
											var html = "";
											if(objEditWin) {
												if(objEditWin.getXHTMLBody) {
													html = objEditWin.getXHTMLBody().replace(/\&amp;/gi,"&");
												} else if(objEditWin.getHTMLBody) {
													html = objEditWin.getHTMLBody().replace(/\&amp;/gi,"&");
												} else {
													html = objEditWin.getContentBody();
												}
											} else {
												return;
											}
											if (html.length > 1200) {
												Ext.Msg.alert('Error','<div style="width:350px;">There is a 1200 Character limit for the Welcome Panel HTML.<br/>You currently have '+html.length+' characters.</div>');
												return;
											}
											var urlHtml = Ext.urlEncode({ c: html });
											Ext.Ajax.request({
												url: "HomePage_ajax.asp?m=savePanelHtml&p=panel_welcome&t=Welcome&r=2&"+urlHtml,
												callback: function(obj,success,request) {
													if (success) {
														panels.panel_welcome.welcometext = html;
														Ext.getCmp("panel_welcome").body.update('<div id="panel_welcome_content" class="portal_panel">' + html + '</div>');
														win.hide(win.minimizeTo,function(win) {
															win.close(true);
															win.destroy();
															delete (win);
														},this);
													}
												}
											});
										},
										scope: this
									}
								},
								{
									text: "Cancel",
									iconCls:  "MHP_cancel-button",
									listeners: {
										click: function(btn,e) {
											delete(objEditWin);
											delete(objEditWinDesc);
											objEditWin = {};
											//Ticket 73071 make compatible with editor 
											objEditWin.checkFocus = function() { return false;}
											objEditWinDesc = {};
											win.hide(win.minimizeTo,function(win) {
												win.close(true);
												win.destroy();
												delete (win);
											},this);
										},
										scope: this
									}
								}
							],
							listeners: {
								show: function(obj) {
									var editor = new InnovaEditor("objEditWin");
									editor.css=cssFile;
									editor.width="90%";
									editor.height="100%";
									objEditWin=editor;
									editorDoc_Init(objEditWin);
									//custom settings
									objEditWin.btnFlash=false;
									objEditWin.btnMedia=false;
									//objEditWin.useDocInsert=false;
									objEditWin.useTemplate=false;
									objEditWin.btnBookmark=false;
									objEditWin.useMap=false;
									editorDoc_PostInit(objEditWin);
								}
							}
						});
						win.minimizeTo = Ext.get("btn_edit_welcome");
						win.show();
					},
					scope: this
				}
			}
		]
	}),
	listeners: {
		render : function(obj) {
			panels.panel_welcome.welcometext = unescape(getHTMLContent("panel_welcome"));
			obj.body.update('<div id="panel_welcome_content" class="portal_panel">'+panels.panel_welcome.welcometext+'</div>');
			if ((AV.site_type_id == '2' || AV.site_type_id == '7') && (isGA || isSA) ) {
				obj.getTopToolbar().show();
			}
		},
		scope: this//end render
	}//end listeners
};

//----------------------------------------
var panel_acct_profile_clicked = 0;
var panel_acct_subscriptions_clicked = 0;
function handleActivate(tab) {
  switch (tab.id)
  {
    case 'panel_acct_profile':
      if (panel_acct_profile_clicked === 0) {
        tab.load({
          url: '/member/HomePage_ajax.asp?l=acct_profile&c=' + portalNumCols + '&v=' + isVertical
        });
        panel_acct_profile_clicked = 1;
      }
      break;
    case 'panel_acct_subscriptions':
      if (panel_acct_subscriptions_clicked === 0) {
        tab.load({
          url: '/member/HomePage_ajax.asp?l=acct_subscriptions&c=' + portalNumCols
        });
        panel_acct_subscriptions_clicked = 1;
      }
      break;
    default:
      break;
  }
}


