
/**
     @requires dragdrop.js
    @requres swf_ajax.js for SimpleRequest
 */ 
	/**
 		@constructor
		@param options initialization properties
		@param {String} [options.id]  id attribute for the div.
		@param {String} [options.style]  initial style attribute for the div.
		@param {String} [options.cssClass]  additional class attribute for the div.
		@param {String} [options.paddingLeft=40]  
		@param {String} [options.paddingRight=40]  
		@param {String} [options.paddingTop=40]  
		@param {String} [options.top]
		@param {String} [options.left]
		@param {String} [options.width]
		@param {String} [options.height]
		@param {String} [options.title]
			also will look for the <title> tag in the content (does not work on IE)
			then look for an element with id = maple-title and use the contents as the title. 
		@param {String} options.type must be 'url' or 'static'
		@param {Boolean} options.modal true if dialog should be modal.
		@param {String} options.positionType either 'center' to center the dialog, or 'absolute' or 'relative'
		
		Parameters for url type dialogs
		@param {String} options.url the url for the contents.
		@param {String} options.params the params for the url contents.
		@param {String} options.method the method (get or post) for the url contents.

		Parameters for static type dialogs
		@param {Maple.Button[]} [options.buttons] array of button definitions.  If none are specified, then an OK button is shown.
		
		Callback functions -
		@param (Function) [options.onClosed] called when the user closes the dynamic window 
		@param (Function) [options.onLoaded] called when the call to the url has been completed and loaded 
	*/
var DynamicDivWindow = Class.create(
 	{
 		/** @scope DynamicDivWindow.prototype */ 
 		
 		/**
 		@ignore
 		*/
 		initialize: function(options)
		{
			var headEle, hl;
			hl = $$('head');
			if(hl.size() > 0)
			{
				headEle = hl[0];
			}
	
			if(!$('editorCSS'))
			{
				if(headEle)
				{
					headEle.insert(new Element('LINK',{rel:'stylesheet',href:'/js/navigation/editor.css',id:'editorCSS'}));
				}
			}
			
			this.onBeforeClose = null;
			this.onClosed = null;
			this.onLoaded = null;
			this.modal = false;	
			this.titleBar = null;
			this.scrollBody = null;
			this.paddingRight = 40;
			this.paddingLeft = 40;
			this.paddingTop = 40;
			this.height = 500;
			this.movable = true;
			
			this.titleContainer = null;
			var eleParams = new Object();
			if(options['id'])
			{
				eleParams['id'] =options['id'];
			}
			if(options['style'])
			{
				eleParams['style'] =options['style'];
			}
			else
			{
				eleParams['style'] = "display:none";	
			} 
			
			if(options['movable'])
			{
			   this.movable = Boolean.valueOf(options['movable']);
			}
			
			/* gets inserted last */
			this.outer = new Element("DIV",eleParams);
			this.outer.setStyle({top:'-100000px',display:"block"});
			
			this.outer.addClassName("DynamicDivEx");
			if(options['cssClass'])
				this.outer.addClassName(options['cssClass']);
			if(options['onLoaded'])
				this.onLoaded = options['onLoaded'];
			if(options['onClosed'])
				this.onClosed = options['onClosed'];
			if(options['onBeforeClose'])
			{
				this.onBeforeClose = options.onBeforeClose; 
			}
		
			if(options['paddingRight'])
				this.paddingRight = options['paddingRight'];
			if(options['paddingLeft'])
				this.paddingLeft = options['paddingLeft'];
			if(options['paddingTop'])
				this.paddingTop = options['paddingTop'];
		

		this.titleBar = new Element("H2");
		this.titleBar.addClassName("DynamicDivEx");
		this.titleContainer = new Element("div");
		this.titleContainer.addClassName("titleContainer");
		this.titleContainer.addClassName("inlineBlock");
		var img = new Element("img",{src:'/images/close_icon.gif'});
		img.observe("click",this.doClose_DynamicDivEx.bind(this));
		this.titleContainer.insert(this.titleBar);
		if(options['title'])
		{
			this.titleBar.update(options['title']);
		}

		this.titleContainer.insert(img);
		this.outer.insert(this.titleContainer);
		this.scrollBody = new Element("DIV");
		this.scrollBody.addClassName("DynamicScroller");
		if(options['type'] == 'static')
		{
			var comp = new Element("div");
			comp.addClassName("component");
			comp.insert(this.scrollBody);
			this.outer.insert(comp);
			var bd = new Element("div",{style:'text-align:center'});
			if(options['buttons'] && options['buttons'].length >  0)
			{
				options['buttons'].each(function(e,i)
					{
						var b = new Element("input",{type:'button',value:e.caption});
						b.observe('click',e.onclick);
						b.addClassName("button");
						bd.insert(b);
					});
			}
			else
			{
				var okb = new Element("input",{type:'button',value:'OK'});
				okb.onclick = this.doClose_DynamicDivEx.bind(this);
				okb.addClassName("button");
				bd.insert(okb);
			}
			comp.insert(bd);
		}
		else
		{
			this.outer.insert(this.scrollBody);
		}

		this.scrollBody.closeDiv = this.doClose_DynamicDivEx.bind(this);
		this.outer.closeDiv = this.doClose_DynamicDivEx.bind(this);
		this.closeDiv = this.doClose_DynamicDivEx.bind(this);

		if(options['modal'] && options['modal'] == "true")
			this.modal = true;

		if(this.modal)
		{
			var hd = Maple.setHaze($("wrap"), true,true);

			this.modalHaze = hd;
			this.outer.setStyle("z-index:"+(hd.getStyle("z-index")+2));
			
			//so that the haze cursor doesn't display in the new window
			this.outer.style.cursor = "default";
		}

		if(options["title"])
			this.titleBar.update(options["title"]);
		
		if(options["top"])
		{
			this.outer.style.position = "absolute";
			this.outer.style.top = options["top"];
		}
		if(options["left"])
		{
			this.outer.style.position = "absolute";
			this.outer.style.left = options["left"];
		}
		if(options["width"])
		{
			this.outer.style.width = options["width"];
			this.wasAutoW = options["width"] === "auto";
			
		}
		if(options["height"])
		{
			this.wasAutoH = options["height"] === "auto";
			this.outer.style.height = options["height"];
			if(!this.wasAutoH)
				this.height = options["height"];
		}
		
		/*  only insert the node after everything is loaded - when about to calculate size */
		if(document.body)
		{
			$(document.body).insert(this.outer);
		}

		try
		{
			var posType = options["positionType"];
			if(posType && posType == "center")
				this.outer.displayCenter = true;
			else
			{
				for(var p in options)
				{
					if(window['console'])
						console.debug("options["+p+"] = " + options[p]);
				}
			}
		}
		catch (e)
		{
			alert("e: " + e);
		}
			
		$(this.outer).identify();
		
		if(options["url"])
		{
			var url = options["url"];
			var urlParameters = null;
			if(options["params"])
				urlParameters = options["params"];
			var method = "get";
			if(options["method"])
				method = options["method"];
			new SimpleRequest(this.scrollBody,url,method,urlParameters,this.onRequestComplete_DynamicDivEx.bind(this));
		}
		else
		{
				this.outer.style.zIndex = this.topZIndex;
			this.topZIndex++;
		}

      
        

		if(window.Draggable && this.movable==true)
		{
			new Draggable(this.outer,{handle:this.titleContainer});
		}

		},
		observe:function(evtid,fcn)
		{
			this.outer.observe(evtid,fcn);
		},
		
		getContentElement:function()
		{
			return this.scrollBody;
		},
		
		/**
			@function
			centers the dialog in the window.
		*/
		centerOuter:function()
		{
			var winDim;
			if(this.outer && this.outer.getScreenDimension)
			{
				winDim = this.outer.getScreenDimension();
			}
			else
			{
				winDim = Maple.getScreenDimension();
			}
			
				winH = winDim.height;
				winW = winDim.width;
				var w = this.outer.getWidth();
				var h = 0;
				if(this.wasAutoH)
					h = this.outer.getHeight();
				else
					h = parseInt(this.outer.style.height);

				this.outer.style.zIndex = this.getTopZIndex();
				
				this.outer.style.position = "absolute";
				this.outer.style.display = "block";
				if(this.scrollBody)
				{
					var sbl = this.scrollBody.down("DIV");
					if(!sbl || sbl.getWidth() < 10)
					{
						sbl = this.scrollBody.down("FORM");
					}
					if(sbl && sbl.getWidth() > 0)
					{
						if(w > sbl.getWidth())
							w = sbl.getWidth();
						else
							w = Math.min(sbl.getWidth(),w);
					}
				}

				var t = document.body.offsetTop + ((winH- h)/2);
				var l =  document.body.offsetLeft + ((winW-w)/2);
			
				if(t <= document.body.offsetTop)
				{
					t = document.body.offsetTop + this.paddingTop;
				}
				//add the amount the user is scrolled down
				t += document.body.cumulativeScrollOffset().top;
				if(l <= document.body.offsetLeft)
				{
					l = document.body.offsetLeft + this.paddingLeft;
				}
				
				if(l+w > document.body.offsetLeft+document.body.offsetWidth)
				{
					w = w - ((l+w) - document.body.offsetWidth) -this.paddingRight;
				}
				else
				{
//					this.outer.style.width="auto";
				}				

				//this.outer.style.width = w + 20;
				w += 40;
				h += 30;
				if(h < 100)
				{
					h = 200;
				}
				if(w < 100)
				{
					w = 200;
				}
				
				this.outer.setStyle({height:h+"px",width:w+"px", top:t+"px", left:l+"px"});
				//this.scrollBody.setStyle({width:'auto'});
				//this.outer.style.width="auto";
		},
		/**
			@private
			@function
			closes the dialog and removes it from the dom
		*/
		doClose_DynamicDivEx : function()
		{
			if(this.onBeforeClose)
			{
				if(!this.onBeforeClose())
				{
					return;
				}
			}
	
			if(this.modalHaze)
			{
				this.modalHaze.remove();
			}
			
			if(this.outer)
			{
				
				this.outer.fire("maple:dynawinClose",{element:this});
				Maple.removeTinyMCEEditors(this.outer);
				this.outer.remove();
			}
			
			if(this.onClosed)
				this.onClosed();

		},
		/**
			@private
			@function
			callback for url content is return.  Looks for the title in the content
			to update the title bar.
			Then centers in the window if needed.
		*/
		onRequestComplete_DynamicDivEx : function(t)
		{
			var tEle = this.outer.down("title");
			if(!tEle)
			{
				tEle = this.outer.down("#maple-title");
			}
			var thtml = "";
			 
			if(tEle)
			{
				thtml += tEle.innerHTML;
				if(this.titleBar)
				{
					if(thtml != "")
						this.titleBar.update(thtml);
				}
			}
			
			if(this.outer.displayCenter)
			{
				if(this.wasAutoH)
					this.outer.setStyle({height:'auto'});
				else
				{
					//handle % and px in value
					if(isNaN(this.height))
						this.outer.setStyle({height:this.height});
					else
						this.outer.setStyle({height:this.height + "px"});
				}
				
				if(this.wasAutoW)
				{
					this.outer.setStyle({width:'auto'});
				}
				this.centerOuter();
			}

			if(this.titleBar && this.scrollBody)
			{
				var oH = this.outer.offsetHeight;
				var tH = this.titleContainer.offsetHeight;
				var dH = oH - tH;
				var pct = Math.round((dH*100)/oH);
				pct -= 2;
				
				// this.scrollBody.setStyle({width:"100%", height:pct+"%"}); 
				this.scrollBody.setStyle({width:"100%", height:(dH - 5)+"px"}); 
			}

			if(this.onLoaded)
				this.onLoaded().bind(this);
		},
		/**
			@private 
			@function
			returns the topmost z-index.
		*/
		getTopZIndex:function()
		{
			var maxZ = 0;
			$$("div").each(function (e,i) {var z = e.getStyle("z-index") ;
						if(z && isNaN(z) == false && Number(z) > maxZ) { maxZ = z;};});
			
			var newZ = Number(maxZ);
			if(isNaN(newZ))
			{
				newZ = 0;
			}	
		
			return (newZ + 1);
		},
		/**
			@methodOf DynamicDivWindow
			@description returns the outer div of the dialog.
		*/
		getDivElement:function() { return $(this.outer);}
		
		});

DynamicDivWindow.isContained = function(ele)
{
	var ret=false;
	var p = ele;
	while(p && p.nodeName != 'BODY' && !ret)
	{
		ret = $(p).hasClassName("DynamicScroller");
		if(!ret)
			p = $(p).parentNode;
	}
	return ret;
};
DynamicDivWindow.closeMyDiv = function(ele)
{
	var ret=false;
	var p = $(ele);
	while(p && p.nodeName != 'BODY' && !ret)
	{
		if($(p).hasClassName)
		{
			ret = $(p).hasClassName("DynamicScroller");
			if(!ret)
				p = $(p).parentNode;
		}
		else
		{
			p = null;
		}
	}
	if(ret)
	{
		p.closeDiv();
	}
	
	return ret;
};
	
onAfterToggle = function(eff)
{
	var h = $(eff.element).titleEle;
	if(h)
	{
		imglist = h.select("div.collapsedIcon","div.expandedIcon");
		if(imglist && imglist.length > 0)
		{
			if($(eff.element).visible())
			{
				$(imglist[0]).removeClassName("collapsedIcon");
				$(imglist[0]).addClassName("expandedIcon");

				Event.fire(document.body, "maple:itemToggled", {'itemId':h.id, 'value':true});			
			}
			else
			{
				$(imglist[0]).addClassName("collapsedIcon");
				$(imglist[0]).removeClassName("expandedIcon");

				Event.fire(document.body, "maple:itemToggled", {'itemId':h.id, 'value':false});
							
				var obj = $$('input[type=text]', 'textarea').find(function(e){return true;});
				if(obj)
				{
					if(obj.activate && obj.visible())
						obj.activate();
					if(obj.blur && obj.visible())
						obj.blur();
				}
			}
		}
		else
			alert("no imglist for " + eff.element.id);
		
	}
	
}

//this can accept an event or an element (look into a better way??)
//called with an event from configCollapsables()
//called with an element from WEB-INF/jsp/adm/content/tab/scoring.jsp
toggleCollapse = function(eventOrEleObj)
{
	var element;
	
	try
	{
		element = eventOrEleObj.element();
	}
	catch(e)
	{
		element = eventOrEleObj;
	}
	
	//don't allow toggle if clicking on a link
	if("A" == element.tagName || "a" == element.tagName || "input" == element.tagName || "INPUT" == element.tagName)
	{
		return;
	}
	
	var dispEle = this.dispEle;
	$(dispEle).titleEle = $(this);
	Effect.toggle($(dispEle),'blind',{duration:.5,afterFinish:onAfterToggle});
}

// editor and stuff
var configCollapsables = function(item)
{
	 var items = $$("div.collapsable");
	 
	 if(item)
	 {
	 	items = new Array();
	 	items[0] = item;
	 }
	 else
	 {
		 items = $$("div.collapsable");
	 }
	 
	 if(items && items.length > 0)
	 {
	 	for(var i=0;i<items.length;i++)
	 	{
	 			
	 		var cd = items[i];
	 		var cd2 = cd.down("h2");
	 		var dispd = cd.select("div.hideable")[0];
	 		if(cd2 && dispd)
	 		{
	 			cd2.identify();
	 			cd2.dispEle = dispd;
	 			cd2.toggleCollapse = toggleCollapse.bind(cd2);
	 			cd2.observe('click',cd2.toggleCollapse);
	 		}
	 	}
	 }
};





var MapleSplitter = Class.create({
		initialize:function(dragElement,params)
		{
			this.myParams = new Object();
			this.myParams['constraint'] ='horizontal';
			this.myParams['onStart'] = this.onStartResize;
			this.myParams['onDrag'] = this.onResizeDrag;
			
		if(!params)
		{
			params = new Object();
		}
		
		this.myParams = Object.extend(this.myParams,params);
		
		if(! this.myParams.sizeTargetL)
		{
			throw "sizeTargetL must be specified";
		}
		if(! this.myParams.sizeTargetR)
		{
			throw "sizeTargetR must be specified";
		}

		this.dragEle = $(dragElement);
		this.dragEle.observe("mousedown",this.myParams.onStart.bind(this));
		this.myParams.sizeTargetR.width = this.myParams.sizeTargetR.offsetWidth; 
		this.myParams.sizeTargetL.width = this.myParams.sizeTargetL.offsetWidth; 
					var il = this.myParams.sizeTargetL.down("div.resizable");
				if(il)
				{
					var w = this.myParams.sizeTargetL.width;
					il.setStyle({width:w+"px"});
				}
				il = this.myParams.sizeTargetR.down("div.resizable");
				if(il)
				{
					var w = this.myParams.sizeTargetR.width;
					il.setStyle({width:w+"px"});
				}
		
		},
		onStartResize:function(event)
		{
			if(!this.dragFcn)
			{
				this.dragFcn = this.onResizeDrag.bind(this);
				this.endDragFcn = this.onEndDrag.bind(this);
			}
			Event.observe(document.body,"mousemove",this.dragFcn);
			Event.observe(document,"mouseup",this.endDragFcn);
			this.startX = event.pointerX();
			this.startL = Number(this.myParams.sizeTargetL.width);
			this.startR = Number(this.myParams.sizeTargetR.width);
			this.myParams.sizeTargetL.addClassName("no-selection");
			this.myParams.sizeTargetR.addClassName("no-selection");
			this.enableDocumentSelection(false);
			
		},
		onEndDrag:function(event)
		{
			Event.stopObserving(document.body,"mousemove",this.dragFcn);
			Event.stopObserving(document,"mouseup",this.endDragFcn);
			this.myParams.sizeTargetL.removeClassName("no-selection");
			this.myParams.sizeTargetR.removeClassName("no-selection");
			this.enableDocumentSelection(true);
		},
		onResizeDrag:function(event)
		{
			var delta = event.pointerX() - this.startX;
	
			if((this.startR - delta) > 0 && (this.startL + delta) > 0)
			{
					this.myParams.sizeTargetR.width = (this.startR - delta);
				this.myParams.sizeTargetL.width = (this.startL + delta); 
				var il = this.myParams.sizeTargetL.down("div.resizable");
				if(il)
				{
					var w = this.myParams.sizeTargetL.width;
					il.setStyle({width:w+"px"});
				}
				il = this.myParams.sizeTargetR.down("div.resizable");
				if(il)
				{
					var w = this.myParams.sizeTargetR.width;
					il.setStyle({width:w+"px"});
				}
			}
		},
		// This works for Safari & IE7, and it is safely ignored in Firefox.  You'll have 
// to add a "-moz-user-select:none;" to whatever you don't want selected in Firefox.
		enableDocumentSelection : function (enable) {
  			if(enable) {
    			document.onselectstart = _original_onselectstart;
  			}
	  		else {
	    		_original_onselectstart = document.onselectstart;
	    		document.onselectstart = function() { return false; }
	  		}
		}
		
		
	});




