// BEGIN RESIZEPANEL SUBCLASS //
YAHOO.widget.ResizePanel = function(el, userConfig) {
    if (arguments.length > 0) {
        YAHOO.widget.ResizePanel.superclass.constructor.call(this, el, userConfig);
    }
}
YAHOO.widget.ResizePanel.CSS_PANEL_RESIZE = "yui-resizepanel";
YAHOO.widget.ResizePanel.CSS_RESIZE_HANDLE = "resizehandle";
YAHOO.extend(YAHOO.widget.ResizePanel, YAHOO.widget.Panel, {
    init: function(el, userConfig) {
        YAHOO.widget.ResizePanel.superclass.init.call(this, el);
        this.beforeInitEvent.fire(YAHOO.widget.ResizePanel);
        var Dom = YAHOO.util.Dom,
            Event = YAHOO.util.Event,
            oInnerElement = this.innerElement,
            oResizeHandle = document.createElement("DIV"),
            sResizeHandleId = this.id + "_resizehandle";
         oResizeHandle.id = sResizeHandleId;
         oResizeHandle.className = YAHOO.widget.ResizePanel.CSS_RESIZE_HANDLE;
        Dom.addClass(oInnerElement, YAHOO.widget.ResizePanel.CSS_PANEL_RESIZE);
        this.resizeHandle = oResizeHandle;
        function initResizeFunctionality() {
            var me = this,
                oHeader = this.header,
                oBody = this.body,
                oFooter = this.footer,
                nStartWidth,
                nStartHeight,
                aStartPos,
                nBodyBorderTopWidth,
                nBodyBorderBottomWidth,
                nBodyTopPadding,
                nBodyBottomPadding,
                nBodyOffset;
            oInnerElement.appendChild(oResizeHandle);
            this.ddResize = new YAHOO.util.DragDrop(sResizeHandleId, this.id);
            this.ddResize.setHandleElId(sResizeHandleId);
            this.ddResize.onMouseDown = function(e) {
                nStartWidth = oInnerElement.offsetWidth;
                nStartHeight = oInnerElement.offsetHeight;
                if (YAHOO.env.ua.ie && document.compatMode == "BackCompat") {
                    nBodyOffset = 0;
                } else {
                    nBodyBorderTopWidth = parseInt(Dom.getStyle(oBody, "borderTopWidth"), 10),
                    nBodyBorderBottomWidth = parseInt(Dom.getStyle(oBody, "borderBottomWidth"), 10),
                    nBodyTopPadding = parseInt(Dom.getStyle(oBody, "paddingTop"), 10),
                    nBodyBottomPadding = parseInt(Dom.getStyle(oBody, "paddingBottom"), 10),
                    nBodyOffset = nBodyBorderTopWidth + nBodyBorderBottomWidth + nBodyTopPadding + nBodyBottomPadding;
                }
                me.cfg.setProperty("width", nStartWidth + "px");
                aStartPos = [Event.getPageX(e), Event.getPageY(e)];
            };
            this.ddResize.onMouseUp = function(e) {
            	me.cfg.setProperty("width", oInnerElement.offsetWidth + "px");
            };
            this.ddResize.onDrag = function(e) {
                var aNewPos = [Event.getPageX(e), Event.getPageY(e)],
                    nOffsetX = aNewPos[0] - aStartPos[0],
                    nOffsetY = aNewPos[1] - aStartPos[1],
                    nNewWidth = Math.max(nStartWidth + nOffsetX, 10),
                    nNewHeight = Math.max(nStartHeight + nOffsetY, 10),
                    nBodyHeight = (nNewHeight - (oFooter.offsetHeight + oHeader.offsetHeight + nBodyOffset));
                me.cfg.setProperty("width", nNewWidth + "px");
                me.cfg.setProperty("height", nNewHeight + "px");
                if (nBodyHeight < 0) {
                    nBodyHeight = 0;
                }
                oBody.style.height =  nBodyHeight + "px";
            };
        }
    
        function onBeforeShow() {
           initResizeFunctionality.call(this);
           this.unsubscribe("beforeShow", onBeforeShow);
        }
    
        function onBeforeRender() {
            if (!this.footer) {
                this.setFooter("");
            }
            if (this.cfg.getProperty("visible")) {
                initResizeFunctionality.call(this);
            } else {
                this.subscribe("beforeShow", onBeforeShow);
            }
            this.unsubscribe("beforeRender", onBeforeRender);
        }
    
        this.subscribe("beforeRender", onBeforeRender);
        if (userConfig) {
            this.cfg.applyConfig(userConfig, true);
        }
        this.initEvent.fire(YAHOO.widget.ResizePanel);
    
    },
    
    toString: function() {
        return "ResizePanel " + this.id;
    },
    set_title: function(title) {
    	var header=this.header.firstChild.nextSibling;
    	if(header) header.innerHTML=title;
    },
    hide_footer: function() {
    	footer=this.footer;
    	if(footer) footer.style.display='none';
    },
    show_footer: function() {
    	footer=this.footer;
    	if(footer) footer.style.display='block';
    },
    fix_width: function()
    {
    	//IE doesn't automatically adjust the body width when content causes the panel to
    	//stretch. So call this after updating the content.
    	this.cfg.setProperty("width", this.innerElement.offsetWidth + "px");
    }
});

// BEGIN RESIZEDIALOG SUBCLASS //
YAHOO.widget.ResizeDialog = function(el, userConfig) {
    if (arguments.length > 0) {
        YAHOO.widget.ResizeDialog.superclass.constructor.call(this, el, userConfig);
    }
}
YAHOO.widget.ResizeDialog.CSS_PANEL_RESIZE = "yui-resizepanel";
YAHOO.widget.ResizeDialog.CSS_RESIZE_HANDLE = "resizehandle";
YAHOO.extend(YAHOO.widget.ResizeDialog, YAHOO.widget.Dialog, {
    init: function(el, userConfig) {
        YAHOO.widget.ResizeDialog.superclass.init.call(this, el);
        this.beforeInitEvent.fire(YAHOO.widget.ResizeDialog);
        var Dom = YAHOO.util.Dom,
            Event = YAHOO.util.Event,
            oInnerElement = this.innerElement,
            oResizeHandle = document.createElement("DIV"),
            sResizeHandleId = this.id + "_resizehandle";
         oResizeHandle.id = sResizeHandleId;
         oResizeHandle.className = YAHOO.widget.ResizeDialog.CSS_RESIZE_HANDLE;
        Dom.addClass(oInnerElement, YAHOO.widget.ResizeDialog.CSS_PANEL_RESIZE);
        this.resizeHandle = oResizeHandle;
        function initResizeFunctionality() {
            var me = this,
                oHeader = this.header,
                oBody = this.body,
                oFooter = this.footer,
                nStartWidth,
                nStartHeight,
                aStartPos,
                nBodyBorderTopWidth,
                nBodyBorderBottomWidth,
                nBodyTopPadding,
                nBodyBottomPadding,
                nBodyOffset;
            oInnerElement.appendChild(oResizeHandle);
            this.ddResize = new YAHOO.util.DragDrop(sResizeHandleId, this.id);
            this.ddResize.setHandleElId(sResizeHandleId);
            this.ddResize.onMouseDown = function(e) {
                nStartWidth = oInnerElement.offsetWidth;
                nStartHeight = oInnerElement.offsetHeight;
                if (YAHOO.env.ua.ie && document.compatMode == "BackCompat") {
                    nBodyOffset = 0;
                } else {
                    nBodyBorderTopWidth = parseInt(Dom.getStyle(oBody, "borderTopWidth"), 10),
                    nBodyBorderBottomWidth = parseInt(Dom.getStyle(oBody, "borderBottomWidth"), 10),
                    nBodyTopPadding = parseInt(Dom.getStyle(oBody, "paddingTop"), 10),
                    nBodyBottomPadding = parseInt(Dom.getStyle(oBody, "paddingBottom"), 10),
                    nBodyOffset = nBodyBorderTopWidth + nBodyBorderBottomWidth + nBodyTopPadding + nBodyBottomPadding;
                }
                me.cfg.setProperty("width", nStartWidth + "px");
                aStartPos = [Event.getPageX(e), Event.getPageY(e)];
            };
            this.ddResize.onMouseUp = function(e) {
            	me.cfg.setProperty("width", oInnerElement.offsetWidth + "px");
            };
            this.ddResize.onDrag = function(e) {
                var aNewPos = [Event.getPageX(e), Event.getPageY(e)],
                    nOffsetX = aNewPos[0] - aStartPos[0],
                    nOffsetY = aNewPos[1] - aStartPos[1],
                    nNewWidth = Math.max(nStartWidth + nOffsetX, 10),
                    nNewHeight = Math.max(nStartHeight + nOffsetY, 10),
                    nBodyHeight = (nNewHeight - (oFooter.offsetHeight + oHeader.offsetHeight + nBodyOffset));
                me.cfg.setProperty("width", nNewWidth + "px");
                me.cfg.setProperty("height", nNewHeight + "px");

                if (nBodyHeight < 0) {
                    nBodyHeight = 0;
                }
                oBody.style.height =  nBodyHeight + "px";
            };
        }
        
        function onBeforeShow() {
           initResizeFunctionality.call(this);
           this.unsubscribe("beforeShow", onBeforeShow);
        }
    
        function onBeforeRender() {
            if (!this.footer) {
                this.setFooter("");
            }
            if (this.cfg.getProperty("visible")) {
                initResizeFunctionality.call(this);
            } else {
                this.subscribe("beforeShow", onBeforeShow);
            }
            this.unsubscribe("beforeRender", onBeforeRender);
        }
    
        this.subscribe("beforeRender", onBeforeRender);
        if (userConfig) {
            this.cfg.applyConfig(userConfig, true);
        }
        this.initEvent.fire(YAHOO.widget.ResizeDialog);
    
    },
    
    toString: function() {
        return "ResizeDialog " + this.id;
    },
    set_title: function(title) {
    	var header=this.header.firstChild.nextSibling;
    	if(header) header.innerHTML=title;
    },
    hide_footer: function() {
    	footer=this.footer;
    	if(footer) footer.style.display='none';
    },
    show_footer: function() {
    	footer=this.footer;
    	if(footer) footer.style.display='block';
    },
    fix_width: function()
    {
    	//IE doesn't automatically adjust the body width when content causes the panel to
    	//stretch. So call this after updating the content.
    	this.cfg.setProperty("width", this.innerElement.offsetWidth + "px");
    }

});

YAHOO.util.Event.onDOMReady(function() {
	/**
	 * This class was created to:
	 *	-override the loadHandler object in YAHOO.widget.Tab to address YUI's 
	 * 		inability to handle Javascript in the response of Ajax requests
	 *	-create new methods to allow tabs to reload dynamically
	 *
	 * @author	WS
	 * @see	#2386
	 */
	YAHOO.widget.DynamicTab = function(userConfig) {
		YAHOO.widget.DynamicTab.superclass.constructor.call(this, userConfig);
		
		this.loadHandler = {
			success: function(o) {
				var response = o.responseText;
				if( doRedirect = /\[REDIRECT\]\[(.*?)\]/.exec(response))
				{
					window.location.href=doRedirect[1];
	 			} else {
					// most other JS libraries do this for us - why can't YUI?
					
					//Execute any javacript directly
					//NOTE - This will not parse correctly in IE if you surround the javascript in comment
					//tags, i.e. <!-- and -->
					var ScriptFragment = "<\s*script.*?>((\n|\r|\r\n|\n\r|.)*?)<\s*\/script";
					var match = new RegExp(ScriptFragment, "img");
					var scripts = o.responseText.match(match);
					
					if (scripts) {
						var match = new RegExp(ScriptFragment, "im");	
						var js = "";
						for (var s = 0; s < scripts.length; s++) {
							js += scripts[s].match(match)[1];
						}
						eval(js);
					}
					this.set("content", o.responseText);
	 			}
			},
			failure: function(o) {
			}
		};
	}
	YAHOO.extend(YAHOO.widget.DynamicTab, YAHOO.widget.Tab, {
		// overridden to add/remove the loading panel
		_dataConnect: function() {
			if (!YAHOO.util.Connect) {
				return false;
			}
			
			YAHOO.util.Dom.addClass(this.get("contentEl").parentNode, this.LOADING_CLASSNAME);
			// ideally this should be done in CSS, but IE seems to have real trouble
			// dealing with opacity (and the cursor property support seems wobbly too)
			YAHOO.util.Dom.setStyle(this.get("contentEl").parentNode, "opacity", 0.7);
			document.body.style.cursor = "wait";  
			
			// add loading panel
			var loadingPanel = document.createElement("div");
			loadingPanel.setAttribute("id", "loadingPanel");
			loadingPanel.setAttribute("class", "tab_reloading");
			
			// just to please IE
			loadingPanel.setAttribute("className", "tab_reloading");
			loadingPanel.innerHTML = "&nbsp;";
			
			var tabPanel = this.get("contentEl").parentNode.parentNode;
			tabPanel.appendChild(loadingPanel);
			
			this._loading = true; 
			this.dataConnection = YAHOO.util.Connect.asyncRequest(
			
				this.get("loadMethod"),
				this.get("dataSrc"), 
				{
					success: function(o) {
						this.loadHandler.success.call(this, o);
						this.set("dataLoaded", true);
						this.dataConnection = null;
						// remove loading panel (if any)
						var loadingPanel = document.getElementById("loadingPanel");
						if (loadingPanel) {
							try{
								var tabPanel = this.get("contentEl").parentNode.parentNode;
								tabPanel.removeChild(loadingPanel);
							}catch(e){}
						}
						YAHOO.util.Dom.removeClass(this.get("contentEl").parentNode, this.LOADING_CLASSNAME);
						YAHOO.util.Dom.setStyle(this.get("contentEl").parentNode, "opacity", 1.0);  
						document.body.style.cursor = "default";
						this._loading = false;
					},
					failure: function(o) {
						this.loadHandler.failure.call(this, o);
						this.dataConnection = null;
						// remove loading panel (if any)
						var loadingPanel = document.getElementById("loadingPanel");
						if (loadingPanel) {
							var tabPanel = this.get("contentEl").parentNode.parentNode;
							tabPanel.removeChild(loadingPanel);
						}
						YAHOO.util.Dom.removeClass(this.get("contentEl").parentNode, this.LOADING_CLASSNAME);
						YAHOO.util.Dom.setStyle(this.get("contentEl").parentNode, "opacity", 1.0);  
						document.body.style.cursor = "default";
						this._loading = false;
					},
					scope: this,
					timeout: this.get("dataTimeout")
				},
				
				this.get("postData")
			);
		},
		// reload the tab
		reload: function() {
			var datasrc = this.get("dataSrc");
			if (datasrc.indexOf("reloaded") == -1) {
				// set the 'reloaded' flag to indicate it is not a first-time dynamic
				// tab fetch
				this.set("dataSrc", datasrc + "&reloaded=1");
			}
			
			this._dataConnect();
		},
		// submit handler for when the submit button is clicked
		submit: function() {
			var forms = YAHOO.util.Dom.getElementsByClassName("yui-panel-form");
			var thisForm;
			// find the right form
			//alert(this.formId);
			for (var i = 0; i < forms.length; i++) {
				var formId = forms[i].id;
				//alert(formId);
				var controlId = formId.substring(formId.length - 6, formId.length - 5);
				if (controlId == this.formId || formId == this.formId) {
					thisForm = forms[i];
				}
			}
			if (this.get("dataSrc") == null) {
				// this is a static tab, add the datasrc manually
				this.set("dataSrc", thisForm.action);
			}
			YAHOO.util.Connect.setForm(thisForm);
			this.reload();
		},
		toString: function() {
			return "DynamicTab";
		},
    fix_width: function()
    {
    	//Ignore this one. Not required here.
    }
	});
});

if (!YAHOO.ks) {
	YAHOO.namespace("ks");
}

YAHOO.util.Event.onDOMReady(function () {

	// Define various event handlers for Dialog   
	YAHOO.ks.handleSubmit = function(dialogObj) {   
		if (! dialogObj.ksClassName ) {
			var dialogObj = this;
		}
		if (! dialogObj.ksPostData ) {
			dialogObj.ksPostData = "";
		}
		if (! dialogObj.ksFileUpload ) {
			dialogObj.ksFileUpload = false;
		}	
//alert("do submit " + dialogObj.ksClassName + " form = " + dialogObj.ksFormName);
		var formObject = document.getElementById(dialogObj.ksFormName);
//alert(formObject);
		YAHOO.util.Connect.setForm(formObject, dialogObj.ksFileUpload);
		var callback = {
			//handle upload case. This function will be invoked after file upload is finished.
			success: function(o) {
				var response = o.responseText;
				
				// WS #2416 handle JSON response
				var isJSON, json;
				try {
					json = YAHOO.lang.JSON.parse(response);
					isJSON = true;
				} catch (e) {
					isJSON = false;
				}
				
				if (isJSON) {
					// this certainly needs work to be more generic
					// currently, it only works for the curriculum framework
					var success = json.success;	// flag whether the submission was successful or not
					var content = json.content;	// the content to display
					var target = json.target;	// the name of the target object in which to update
					var targetProperty = json.targetProperty;	// the property name of the target to update
					var customJs = json.customJs;	// string containing any custom javascript to execute
					var customJs2 = json.customJs2;	// string containing any custom javascript to execute
					
					if (target != null && target != "") {
						target = eval(target);
					}
					
					if (content != null && content != "") {
						// Execute any javacript directly
						// NOTE - This will not parse correctly in IE if you surround the javascript in comment
						// tags, i.e. <!-- and -->
						var scriptFragment = "<\s*script.*?>((\n|\r|\r\n|\n\r|.)*?)<\s*\/script";
						var match = new RegExp(scriptFragment, "img");
						var scripts = content.match(match);
					
						if (scripts) {
							var match = new RegExp(scriptFragment, "im");	
							var js = "";
							for (var s = 0; s < scripts.length; s++) {
								js += scripts[s].match(match)[1];
							}
							eval(js);
						}
					}
					
					var callerObj = o.argument;
					if (success) {
						if (target != null && targetProperty != null && targetProperty != "") {
							// this will obviously only work if target supports the set() method
							// if not, resort to customJs
							target.set(targetProperty, content);
						}
						callerObj.cancel();
						eval(customJs);
						eval(customJs2);
						YAHOO.util.Dom.setStyle(callerObj.element.firstChild.id, "opacity", 1.0);
						document.body.style.cursor = "default";
					} else {
						// not yet implemented
					}
					
				} else {
					if( doRedirect = /\[REDIRECT\]\[(.*?)\]/.exec(response))
					{
						window.location.href=doRedirect[1];
		 			} else {
						var callerObj = o.argument;
						//alert(response.substr(1,2000));
						callerObj.setBody(response);
						
						//Execute any javacript directly
						//NOTE - This will not parse correctly in IE if you surround the javascript in comment
						//tags, i.e. <!-- and -->
						var ScriptFragment = "<\s*script.*?>((\n|\r|\r\n|\n\r|.)*?)<\s*\/script";
						var match    = new RegExp(ScriptFragment, "img");
						var scripts  = response.match(match);
					
						if(scripts) {
							var match = new RegExp(ScriptFragment, "im");	
							var js = "";
						    for(var s = 0; s < scripts.length; s++) {
						        js += scripts[s].match(match)[1];
						 	}
						    try{
						    	eval(js);
							} catch(e)
							{
								alert(e.name + " - " + e.message);
								alert(js);
							}
						}
	
						YAHOO.util.Dom.setStyle(callerObj.element.firstChild.id, "opacity", 1.0);  
						
						//callerObj.focusFirst();
						if (callerObj.ksHideAfterSubmit) {
							callerObj.cancel();
						} else {
							callerObj.show();
							callerObj.render();
						}
						document.body.style.cursor="default";
						//callerObj.focusFirst(); //needs to be called a second time to work in IE..
		 			}
				}
				if (dialogObj.fix_width) {
					dialogObj.fix_width();
				}
	 		},
				
			upload: function(o) {
				var response = o.responseText;
				var callerObj = o.argument;
				response=response.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
				//alert(response.substr(0,4000));
				var r = YAHOO.lang.JSON.parse(response); 
				var ok=r.ok;
				var fail=r.fail;
				var message=r.message;
				
				if(r.update_top)
				{
					for(var i=0;i<r.update_top.length; i++)
					{
						eval('window.top.YAHOO.ks.'+ r.update_top[i].id +'_el.set(\''+ r.update_top[i].name +'\',\''+ r.update_top[i].value +'\');');
					}
				}
				if(r.call_javascript)
				{
					for(var i=0;i<r.call_javascript.length; i++)
					{
						eval(r.call_javascript[i].javascript);
					}
				}
				
				YAHOO.util.Dom.setStyle(callerObj.element.firstChild.id, "opacity", 1.0);  
				document.body.style.cursor="default";
				if(fail)
				{
					alert(message);
					//callerObj.focusFirst();
					callerObj.show();
					callerObj.render();
					//callerObj.focusFirst(); //needs to be called a second time to work in IE..
				} else
				{
					callerObj.hide();
				}
	 		},
				
			failure: function(o) {
					alert("Submission failed: " + o.statusText);
				var callerObj = o.argument;
					YAHOO.util.Dom.setStyle(callerObj.element.firstChild.id, "opacity", 1.0);  
				document.body.style.cursor="default";	
			},
				 
			timeout: 60000,   
			argument: dialogObj  				
		};
		if(dialogObj.ksFileUpload)
		{
			var action=formObject.action;
		} else if(dialogObj.ksCustomParam != null && dialogObj.ksCustomParam != "")
		{
			var action="./index.php?page=" + dialogObj.ksClassName + "&action=kn_update"+dialogObj.ksCustomParam;
		} else
		{
			var action="./index.php?page=" + dialogObj.ksClassName + "&action=kn_update";
		}
		var cObj = YAHOO.util.Connect.asyncRequest("POST", action, callback, dialogObj.ksPostData);
		YAHOO.util.Dom.setStyle(dialogObj.element.firstChild.id, "opacity", 0.7);  
		dialogObj.ksPostData = "";
		document.body.style.cursor="wait";
	};   

	YAHOO.ks.handleCancel = function() {   
		this.cancel();   
	}; 
	//This next bit looks painful, and it is...
	YAHOO.ks.handleParamSubmit1 = function(dialogObj) {
		if (! dialogObj.ksClassName ) {
			var dialogObj = this;
		}
		dialogObj.ksCustomParam=dialogObj.ksCustomParam1;
		YAHOO.ks.handleSubmit(dialogObj);
	}
	YAHOO.ks.handleParamSubmit2 = function(dialogObj) {
		if (! dialogObj.ksClassName ) {
			var dialogObj = this;
		}
		dialogObj.ksCustomParam=dialogObj.ksCustomParam2;
		YAHOO.ks.handleSubmit(dialogObj);
	}
	YAHOO.ks.handleParamSubmit3 = function(dialogObj) {
		if (! dialogObj.ksClassName ) {
			var dialogObj = this;
		}
		dialogObj.ksCustomParam=dialogObj.ksCustomParam3;
		YAHOO.ks.handleSubmit(dialogObj);
	}
	YAHOO.ks.handleParamSubmit4 = function(dialogObj) {
		if (! dialogObj.ksClassName ) {
			var dialogObj = this;
		}
		dialogObj.ksCustomParam=dialogObj.ksCustomParam4;
		YAHOO.ks.handleSubmit(dialogObj);
	}
	YAHOO.ks.manager = new YAHOO.widget.OverlayManager();
	
	YAHOO.ks.displayAndFocus = function(e, obj) {
		if(obj.hideAllOthers){	
			YAHOO.ks.manager.hideAll();
		}
		obj.show();
		obj.focus();
		document.body.style.cursor="default";
	}
	
	YAHOO.ks.displayAndFocusDialog = function(e, obj) {
		if(obj.hideAllOthers){	
			YAHOO.ks.manager.hideAll();
		}
		obj.show();
		obj.focus();
		window.scrollTo(0,0);	//#dgb 20090824 set focus to top of window again	
		document.body.style.cursor="default";
//		obj.focusFirst();	
		obj.blurButtons();
	}	
	
	YAHOO.ks.display = function(e, obj) {
		obj.show();
		document.body.style.cursor="default";
	}
	
	YAHOO.ks.showThisOnOk = function() {
		eval(this.ksLinkOkButtonTo + ".show()");
		document.body.style.cursor="default";
	}
	YAHOO.ks.submitThisOnOk = function() {
		this.cancel(); 
		eval('YAHOO.ks.handleSubmit(' + this.ksLinkOkButtonTo + ')');
	}
	
}
);