var objEditWin={};
var objEditWinDesc={};
Ext.ns("AV");
AV.ContentWindow={
	formDirty: true,
	
	toggleSave: function(on) {
		if(on) {
			this.btnSave.enable();
		} else {
			this.btnSave.disable();
		}
	},

	getWindowHeight: function(config) {
		var bodydom=Ext.get(document.body);
		height=bodydom.dom.offsetHeight-10;
		return height;
	},

	sizeEditorContainers: function(config) {
		var cts=this.formWindow.body.select('.form-items-container');
		var ctheight=this.formWindow.el.child('.x-window-body').getHeight();
		var height=0;
		cts.each(function(el,ct,index) {
			height+=el.getHeight()+4;
		});
		var offset=70;
		var diff=ctheight-height-offset;
		if(diff<220) {
			diff=220; //200px high is minimum, but must set height of containing div to 220 to account for padding w/in the editor
		}
		if(config.editors.objEditWin&&config.editors.objEditWinDesc) {
			diff/2 < 220 ? half=220 : half=parseInt(diff/2);
			document.getElementById('div_objEditWinTarget').style.height=half+"px";
			document.getElementById('div_objEditWinDescTarget').style.height=half+"px";
		} else if(config.editors.objEditWin&&!config.editors.objEditWinDesc) {
			document.getElementById('div_objEditWinTarget').style.height=diff+"px";
		} else if(!config.editors.objEditWin&&config.editors.objEditWinDesc) {
			document.getElementById('div_objEditWinDescTarget').style.height=diff+"px";
		}
	},

	showWindow: function(config) {//url,width,height,title,editor config,edit/add,target

		Ext.QuickTips.init();

		// Zach - Override for setting animation duration
		Ext.override(Ext.Window,{
			defaultAnimShowCfg: {
				duration: .25,
				easing: 'easeNone',
				opacity: .5
			},
			defaultAnimHideCfg: {
				duration: .25,
				easing: 'easeNone',
				opacity: 0
			},
			animShow: function() {
				this.proxy.show();
				this.proxy.setBox(this.animateTarget.getBox());
				this.proxy.setOpacity(0);
				var b=this.getBox(false);
				b.callback=this.afterShow;
				b.scope=this;
				b.block=true;
				Ext.apply(b,this.animShowCfg,this.defaultAnimShowCfg);
				this.el.setStyle('display','none');
				this.proxy.shift(b);
			},
			animHide: function() {
				this.proxy.setOpacity(.5);
				this.proxy.show();
				var tb=this.getBox(false);
				this.proxy.setBox(tb);
				this.el.hide();
				var b=this.animateTarget.getBox();
				b.callback=this.afterHide;
				b.scope=this;
				b.block=true;
				Ext.apply(b,this.animHideCfg,this.defaultAnimHideCfg);
				this.proxy.shift(b);
			}
		});

		var height;
		if(!config.height) {
			height=this.getWindowHeight(config);
		} else {
			height=config.height;
		}
		var width;
		if(!config.width) {
			width=705;
		} else {
			width=config.width;
		}

		if(config.helpUrl) {
			this.helpUrl=config.helpUrl;
		}

		//will animate from the "Publish" button
		if (!config.target) {
			config.target=Ext.get(Ext.get(document.body).select('.clsSignIn').elements[0]);
		}
		AV.ContentWindow.minimizeTo = config.target;
		
		this.btnSave=new Ext.Button({
			text: "Save",
			iconCls: 'save-button',
			listeners: {
				click: {
					fn: function() {
						this.submitForm();
					},
					scope: this
				}
			}
		});

		this.btnDelete=new Ext.Button({
			text: "Delete",
			iconCls: 'delete-button',
			listeners: {
				click: {
					fn: function() {
						this.deletePost();
					},
					scope: this
				}
			}
		});

		this.btnCancel=new Ext.Button({
			text: "Cancel",
			iconCls: 'cancel-button',
			listeners: {
				click: {
					fn: function() {
						this.closeWindow();
					},
					scope: this
				}
			}
		});

		this.btnSubmit=new Ext.Button({
			text: "Submit",
			iconCls: "submit-button",
			listeners: {
				click: {
					fn: function() {
						this.submitForm();
					},
					scope: this
				}
			}
		});

		this.btnSendDiscussion=new Ext.Button({
			text: "Send Email",
			iconCls: 'send-email-button',
			visible: false,
			listeners: {
				click: {
					fn: function() {
						this.submitForm();
					},
					scope: this
				}
			}
		});

		var toolbarhidden=true;
		if(config.view) { toolbarhidden=false; }
		this.adminToolbar=new Ext.Toolbar({
			hidden: toolbarhidden
		});

		this.formWindow=new Ext.Window({
			title: config.title,
			layout: 'fit',
			width: width,
			border: true,
			bodyBorder: true,
			height: height,
			shadow: true,
			modal: true,
			animateTarget: config.target,
			animShowCfg: {
				duration: .5
			},
			animHideCfg: {
				duration: .5
			},
			closable: false,
			cls: 'editor-window',
			resizable: true,
			buttonAlign: "left",
			tbar: this.adminToolbar,
			fbar: this.getButtonArr(config),
			listeners: {
				render: { //mask and add close and help buttons
					fn: function(obj) {
						obj.el.mask();
						var text=this.formWindow.el.child(".x-window-header-text");
						text.wrap({
							tag: 'div',
							style: 'float:left;'
						});
						var header=this.formWindow.el.child(".x-window-header");
						var wrap=header.createChild({
							tag: 'div',
							id: 'buttonwrap'+this.formWindow.id,
							style: 'float:right;margin-top:-3px;width:110px;'
						});
						header.createChild({
							tag: 'div',
							style: 'clear:both;'
						});

						this.closeButton=new Ext.Component({
							renderTo: wrap,
							autoEl: {
								tag: 'div',
								style: 'float:right;width: 57px;height:18px;background-image:url(/library/OverrideImages/icons-close-help.png);cursor:pointer;background-position:0 0;'
							},
							listeners: {
								render: {
									fn: function(button) {
										button.el.on("click",function(e,dom,stuff) {
											this.closeWindow();
										},this);
									},
									scope: this
								}
							}
						});

						this.helpButton=new Ext.Component({
							renderTo: wrap,
							autoEl: {
								tag: 'div',
								style: 'float:left;width: 53px;height:18px;background-image:url(/library/OverrideImages/icons-close-help.png);cursor:pointer;background-position:0 -18px;'
							},
							listeners: {
								render: {
									fn: function(button) {
										button.el.on("click",function(e,dom,stuff) {
											this.showHelp(dom);
										},this);
									},
									scope: this
								}
							}
						});
						if(!config.helpUrl) {
							this.helpButton.el.setDisplayed(false);
						}

						var clear=new Ext.Component({
							renderTo: wrap,
							autoEl: {
								tag: 'div',
								style: 'clear:both;'
							}
						});
					},
					scope: this
				},
				show: {
					fn: function(obj) {
						//resize listener can't be inited in the listners because it fires when window resizes during animation
						this.formWindow.on("resize",function() {
							var obj={};
							if(document.getElementById("div_objEditWinTarget")&&document.getElementById("div_objEditWinDescTarget")) {
								obj={ editors: { objEditWin: true,objEditWinDesc: true} };
							} else if(document.getElementById("div_objEditWinTarget")) {
								obj={ editors: { objEditWin: true} };
							} else if(document.getElementById("div_objEditWinDescTarget")) {
								obj={ editors: { objEditWinDesc: true} };
							} else {
								obj={ editors: {} }
							}
							this.sizeEditorContainers(obj);
						},this);
						this.formWindow.on("beforehide",function() {
							this.formWindow.un("resize",function() { },this);
						},this);

						//this is here because IE is lame and height:'auto' doesn't work like other browsers
						//Ext tries to account for this in the mask() function, but the timing is off in this case.
						if(Ext.isIE) {
							var mask=obj.el.child('.ext-el-mask');
							mask.setHeight(height);
						}
						var self=this;
						setTimeout(function() {
							obj.load({
								url: config.url,
								loadScripts: true,
								method: "GET",
								scripts: true,
								text: "Loading...",
								callback: function(winbody,success,response,post) {
									if(success) {
										if(config.editors) {
											var temp=[];
											if(config.editors.objEditWin) { temp.push("objEditWin") }
											if(config.editors.objEditWinDesc) { temp.push("objEditWinDesc") }
											self.showEditors(temp,config);
										} else {
											self.formWindow.el.unmask();
										}
										winbody.setStyle('overflow','auto');
										self.formWindow.center();
										self.formWindow.syncShadow();
									} else {
										//handle error
										//alert(response.responseText);
									}
								},
								scope: self
							});
						},obj.animShowCfg.duration);
					},
					scope: this
				}
			}
		});

		this.formWindow.show();
		HM_f_HideAll(); //hide menu
	},

	updateContent: function(config) {
		this.formWindow.el.mask();
		//since the edit grid must be added to the window instead of just rendered to it
		//I put the call in to removeAll or the edit grid appears when update() is called
		this.formWindow.removeAll();
		this.formWindow.getUpdater().update({
			url: config.url,
			loadScripts: true,
			method: "GET",
			scripts: true,
			text: "Loading...",
			nocache: true,
			callback: function(obj,success,response,call) {
				if(success) {
					config.view?this.adminToolbar.show():this.adminToolbar.hide();
					var temp=[];
					if(config.editors.objEditWin) { temp.push("objEditWin") }
					if(config.editors.objEditWinDesc) { temp.push("objEditWinDesc") }
					this.showEditors(temp,config);
					this.updateButtons(this.getButtonArr(config));
					this.formWindow.setTitle(config.title);
					this.updateHelp(config);
				}
			},
			scope: this
		});
	},

	updateButtons: function(buttonArr) {
		this.formWindow.fbar.removeAll(false);
		this.formWindow.fbar.add(buttonArr);
		this.formWindow.fbar.doLayout();
	},

	updateHelp: function(config) {
		if(config.helpUrl) {
			this.helpUrl=config.helpUrl;
			this.helpButton.el.setDisplayed(true);
		} else {
			this.helpButton.el.setDisplayed(false);
		}
	},

	getButtonArr: function(config) {
		var buttonArr=[];
		if(config.edit) {
			buttonArr=[this.btnDelete,this.btnSave,this.btnCancel];
		} else if(config.add) {
			buttonArr=[this.btnSave,this.btnCancel];
		} else if(config.form) {
			buttonArr=[this.btnSubmit]
		} else if(config.discussionemail) {
			buttonArr=[this.btnSendDiscussion]
		}
		return buttonArr;
	},

	closeWindow: function() {
		this.formWindow.hide(AV.ContentWindow.minimizeTo,function(win) {
			delete(objEditWin);
			delete(objEditWinDesc);
			objEditWin =  {};
			objEditWinDesc = {};
			this.formWindow.close(true);
			this.formWindow.destroy();
			delete (this.formWindow)
		},this);
	},

	resetVars: function() {
		this.radiosRendered=false;
		this.dailyRendered=false;
		this.weeklyRendered=false;
		this.monthlyRendered=false;
		this.yearlyRendered=false;
		this.rendered=false;
		if(this.editors) {
			for(var a=0;a<this.editors.length;a++) {
				delete this.editors[a].onKeyPress;
			}
		}
	},

	closeHelp: function() {
		this.helpWin.close(true);
		this.helpWin.destroy();
		delete (this.helpWin);
	},

	showHelp: function(domBtn) {
		this.helpWin=new Ext.Window({
			cls: 'editor-window',
			width: 500,
			animateTarget: domBtn,
			closable: true,
			floating: true,
			draggable: true,
			modal: false,
			title: "Help",
			border: true,
			bodyBorder: true,
			autoLoad: {
				url: this.helpUrl,
				loadScripts: true,
				scripts: true,
				callback: function() {
					var self=this;
					setTimeout(function() {
						self.helpWin.syncShadow();
					},5);
				},
				scope: this
			}
		});
		this.helpWin.on("deactivate",function(win) {
			var maskZ=parseInt(this.formWindow.mask.dom.style.zIndex);
			win.el.setStyle('z-index',maskZ+1);
		},this);
		this.helpWin.on("show",function(win) {
			win.center();
		},this);
		this.helpWin.show();
	},

	showEditors: function(arrEditors,config) {
		var a;
		var temp=[];
		this.editors=[];
		for(a=0;a<arrEditors.length;a++) {
			temp[a]=false;
			if(typeof Ext.get("txt_"+arrEditors[a])=='object') {
				temp[a]=true;
			}
		}

		var self=this;
		for(a=0;a<temp.length;a++) {
			if(!temp[a]||!this.CSS_FILENAME) {
				setTimeout(function() {
					self.showEditors(arrEditors,config)
				},10);
				return false;
			}
		}
		for(a=0;a<arrEditors.length;a++) {
			this.editors[a]=new InnovaEditor(arrEditors[a]);
			this.editors[a].css="/library/css/"+this.CSS_FILENAME;
			this.editors[a].width="90%";
			this.editors[a].height="100%";
			//messenger service doesn't get some buttons and has neat styles.
			if(arrEditors[a]==="objEditWinDesc") { objEditWinDesc=this.editors[a] }
			if(arrEditors[a]==="objEditWin") { objEditWin=this.editors[a] }
			editorDoc_Init(this.editors[a]);
			//custom settings
			if(AV.site_type_id==2||AV.site_type_id==7) {
				//hide flash, media, documents, templates, bookmarks, and maps
				this.editors[a].btnFlash=false;
				this.editors[a].btnMedia=false;
				this.editors[a].useDocInsert=false;
				this.editors[a].useTemplate=false;
				this.editors[a].btnBookmark=false;
				this.editors[a].useMap=false;
			}
			if(config&&config.helpUrl.indexOf("MessengerService")!== -1) {
				this.editors[a].btnStyles=true;
				this.editors[a].useTemplate=true;
				this.editors[a].useMap=false;
				this.editors[a].btnMedia=false;
				this.editors[a].btnFlash=false;
				this.editors[a].arrStyle=[
					[".clsMainPane",false,"","line-height: normal; background-color: #ffffff !important; background-image: none !important; border: 1px inset #e0dfe3; height: 100%; margin: 0; padding: 0;"],
					[".ObjContainer",false,"","border: dotted 1px #000000;"],
					[".clsBodyText",false,"","background-color: #ffffff !important; background-image: none !important;"],
					[".clsSmallText",false,"","background-color: #ffffff !important; background-image: none !important;"],
					[".clsCaption",false,"","background-color: #ffffff !important; background-image: none !important;"],
					[".clsInstructions",false,"","background-color: #ffffff !important; background-image: none !important;"],
					[".clsLabelMand",false,"","background-color: #ffffff !important; background-image: none !important;"]
				];
			}
			editorDoc_PostInit(this.editors[a]);
			//6/4/09 - Zach: The following tracks keystrokes in the editor.  I don't know of another way
			//to handle the save button toggle
			//this.editors[a].onKeyPress=function() {
			//	AV.ContentWindow.formDirty=true;
			//	AV.ContentWindow.toggleSave(true);
			//};
		}
		this.sizeEditorContainers(config);
		var self = this
		setTimeout(function(){
			self.formWindow.el.unmask();
		},500);
	},

	showEmailWindow: function(type,link,address,title,summary,content,scope) {
		if(!scope) { scope=AV.ContentWindow; }

		var winid=scope.formWindow.id;

		scope.emailWindow=new Ext.Window({
			cls: 'editor-window',
			width: 500,
			animateTarget: this.btnEmail,
			closable: true,
			floating: true,
			draggable: true,
			modal: false,
			title: "Email "+type,
			border: true,
			bodyBorder: true,
			items: [
				new Ext.form.FormPanel({
					id: 'emailform'+winid,
					border: false,
					bodyBorder: false,
					items: [
						{
							xtype: 'hidden',
							name: 'link',
							value: link
						},
						{
							xtype: 'hidden',
							name: 'title',
							value: title
						},
						{
							xtype: 'hidden',
							name: 'summary',
							value: summary
						},
						{
							xtype: 'hidden',
							name: 'body',
							value: content
						},
						{
							xtype: 'textfield',
							fieldLabel: 'To',
							name: 'to',
							width: 300
						},
						{
							xtype: 'textfield',
							fieldLabel: 'From',
							name: 'from',
							width: 300,
							value: address
						},
						{
							xtype: 'textfield',
							fieldLabel: 'Subject',
							name: 'subject',
							width: 300
						},
						{
							xtype: 'textarea',
							fieldLabel: 'Note',
							name: 'note',
							width: 300
						}
					],
					buttons: [
						{
							text: "Send",
							handler: this.submitEmailForm.createDelegate(scope,[winid],true),
							iconCls: 'send-button',
							scope: this
						},
						{
							text: "Cancel",
							handler: function() {
								this.emailWindow.hide(this.btnEmail,function() {
									this.emailWindow.close(true);
									this.emailWindow.destroy();
									delete (this.emailWindow);
								},this)
							},
							iconCls: 'cancel-button',
							scope: this
						}
					]
				})
			]
		});
		this.emailWindow.on("deactivate",function(win) {
			var maskZ=parseInt(this.formWindow.mask.dom.style.zIndex);
			win.el.setStyle('z-index',maskZ+1);
		},this);
		this.emailWindow.show();
	},

	submitEmailForm: function(button,e,winid) {
		function isEmail(addr) {
			var regex=/^((?:(?:(?:[a-zA-Z0-9][\.\-\+_]*)*)[a-zA-Z0-9])+)\@((?:(?:(?:[a-zA-Z0-9][\.\-]?){0,62})[a-zA-Z0-9])+)\.([a-zA-Z0-9]{2,6})$/
			return regex.test(addr);
		}
		var form=Ext.getCmp('emailform'+winid).getForm();
		var values=form.getValues();
		var html="";
		var index=0;
		var go=true;
		for(var a in values) {
			if(a==="to"||a==="from") {
				if(!isEmail(values[a])) {
					form.items.items[index].markInvalid("This address is invalid.");
					go=false;
					break;
				}
			}
			form.el.dom[a].value=values[a];
			html+=form.el.dom[a].name+": "+form.el.dom[a].value+"<br/>";
			index++;
		}
		if(!go) { return false; }

		form.submit({
			url: '/Send_Email.asp',
			method: 'POST',
			success: function() {
				Ext.Msg.alert("Success!","Your message has been sent.");
				var self=this;
				setTimeout(function() {
					self.emailWindow.close(true);
					self.emailWindow.destroy();
					delete (self.emailWindow);
				},1000)
			},
			failure: function() {
				Ext.Msg.alert("Message Failed","Message could not be sent. Please check your values and try again.");
			},
			scope: this
		});
	},

	checkValue: function(value,message) {
		if(value==="") {
			Ext.MessageBox.alert("Error",message);
			return false;
		}
		return true;
	},

	floatElement: function(obj,which) {
		var n=obj.el.dom;
		while(n.className.indexOf("x-form-item")=== -1&&n.className.indexOf("x-btn")=== -1) {
			if(Ext.get(n).dom.type==="form") {
				return;
			} else {
				n=n.parentNode;
			}
		}
		Ext.get(n).setStyle("float",which);
		if(Ext.isIE) { //must set width of this container explicitly in IE.
			var width=obj.width;
			if(!width) { return; }
			var padding=obj.el.dom.parentNode.style.paddingLeft;
			padding=parseInt(padding.substring(0,padding.length-2))+3;
			if(!isNaN(padding)) {
				width+=padding;
			}
			n.style.width=width+"px";
		}
	},

	getErrorDiv: function(name) {
		var div=new Ext.Container({
			autoEl: {
				id: name+"_error"+this.formWindow.id,
				style: "float:left;display:none;",
				html: "<img src='/library/Ext/ext-3.1.0/resources/images/default/form/exclamation.gif' style='margin:2px 0px 0px 3px'/>"
			}
		});
		return div;
	},

	getClearDiv: function() {
		var div=new Ext.Container({
			xtype: "box",
			autoEl: {
				style: "clear:both;"
			}
		});
		return div;
	}
};