//////////////////////////////////////////////
// ColumnBrowser Object VERSION_0.8
//////////////////////////////////////////////
// The information control listens out for 
// URL load request, or Slice changes and 
// will load an HTML information page into 
// its container DOM element.
//   
// The information control will handle 
// any special slice or user related 
// information pages, that require requests 
// sent to the server.  The Front End Server 
// will handle the transformation from XML 
// to presentable HTML that the information 
// page displays.
//
//////////////////////////////////////////////

var InformationControl = Class.create();
InformationControl.prototype = {
//
// Member Variables
//The default id of the dom element to add the info control to
rsid: "ICContSfc",
//flag to indicate if the control has been added to parent dom element yet
init: false,
//the info url
url: "",
//flag to indiocate if content has been loaded already into info control
initialized: false,

useAnimation: false,

//
// Constructor
//	@rsid: render surface id
//	@hist: column history object
initialize: function(rsid, hist)
	{
		this.rsid = rsid || this.rsid;
		
		window.mSpaceInformationControl = this;
		
				
		//create the main control div
		this.csCont = Builder.node('div', {id: "ICCont"});
		this.cs = Builder.node('div', {id: "IC"}, [this.csCont]);	
		
		this.cancelBtn = Builder.node('img', {src: '/pics/InformationControl/Generic/cancel_btn.png'});
		
		// create the loading icon for when animation is turned off
		this.lcs_noanim = Builder.node('img', {id: 'loading_noanim', src: '/pics/InformationControl/Generic/loading_noanim.gif', style: 'position: absolute; right: 10px; top: 15px; display: none'});
		
		//create the information control loading surface
		this.lcs = Builder.node('div', { id: "ICls", style: 'display : none'}, 
																				[
																				 Builder.node('div', {className: 'loading'}, 
																							 								[
																															 	Builder.node('img', {src: '/pics/Common/loading.gif'}),
																																Builder.node('br'),
																																'Loading Information',
																																Builder.node('br'),
																																this.cancelBtn
																															]
																															)
																				]);
		//create loading surface bg
		this.lcsbg = Builder.node('div', { id: "IClsbg", style: 'display : none'});
			
		
		// Register Custom events (using Prototype)
		document.observe('InformationControl:SetUrl', 					this.SetUrl.bindAsEventListener(this));
		document.observe('InformationControl:SetUrlNoSlice',		this.SetUrlNoSlice.bindAsEventListener(this));		// Unused?
		document.observe('InformationControl:Refresh',			 		this.LoadContents.bindAsEventListener(this));			// Unused?
		document.observe('InformationControl:SubmitForm',		 		this.SubmitForm.bindAsEventListener(this));
		document.observe('InformationControl:StopLoading',	 		this.StopLoading.bindAsEventListener(this));			// Unused?
		document.observe('InformationControl:Resize',						this.ResizeContainer.bindAsEventListener(this));
		
		document.observe('Column:SelectItem', 									this.SelectItem.bindAsEventListener(this));
		document.observe('Column:SelectItemWithSlice',					this.SelectItemWithSlice.bindAsEventListener(this));	
		document.observe('Column:UnSelectItem',									this.SelectItem.bindAsEventListener(this));	
		
		document.observe('mSpaceHistory:HistoryChange',					this.HistoryChange.bindAsEventListener(this));	
		
		Event.observe(this.cancelBtn, "click", this.StopLoading.bindAsEventListener(this));
		
		this.Start(hist);	
	},
	
	
//Start the information control with a history object.
Start: function(histObj)
	{
		//if history object exists
		//load it
		if (histObj)
		{
			if (histObj["Info.Url"])
			{
				this.url = histObj["Info.Url"];
				this.LoadContents();
			}		
			else if (histObj["Column.SelectItemHistory"])
			{
				this.url = window.mSpaceApplication.GetServerUrl("infobox") + "&" + histObj["Column.SelectItemHistory"];
				document.fire('Log:Event', { type: "DataEvent", message: "[getinfo_history] " + this.url});
				this.LoadContents();
			}		
		}
	},

//External set url call.
SetUrl: function(e)
	{
		var url = e.memo;
	
		//Cancel any outstanding ajax calls
		document.fire('DataController:Cancel', this);
		
		var oldUrl = this.url;
			
		this.url = url;
		
		//Push the url onto the history stack.
		if (oldUrl!=url)
			document.fire('mSpaceHistory:AddHistory', { name: 'Info.Url', history: this.url });		
		
		//Get the column param string
		if (window.ColumnBrowser)
		{
			if (this.url.indexOf('?')==-1)
				this.url += "?";
			this.url += "&" + window.ColumnBrowser.GetColumnParamString();
		}		
		
		// Make sure that the jsmode variable is passed to the server (so that it is visible in the XSLT)
		this.url += "&jsmode=true";
		
		//load the contents of url request.
		this.LoadContents();
	},
	
//Open a url with no slice string appended
SetUrlNoSlice: function(url)
	{
		//Cancel any outstanding ajax calls
		document.fire('DataController:Cancel', this);
		//hide the light box if open
		document.fire('LightBox:Hide')
		
		var oldUrl = this.url;
			
		this.url = url;
		
		//Push the url onto the history stack.
		if (oldUrl!=url)
			document.fire('mSpaceHistory:AddHistory', { name: 'Info.Url', history: this.url });		
		
		this.LoadContents();
		

	},	
	
//Loads a url
//Loads the loading panel, and then does a data
//request call to get the information for the 
//current url.
LoadContents: function(e)
	{
		//If not already opened, 
		//load the control into the 
		//dom
		if (!this.init)
		{
			this.init = true;	
		
			this.csCont.innerHTML = $(this.rsid).innerHTML;
			//Append to main surface
			$(this.rsid).update();
			$(this.rsid).appendChild(this.cs);			
			$(this.rsid).appendChild(this.lcs);
			$(this.rsid).appendChild(this.lcsbg);
			this.cs.appendChild(this.lcs_noanim);
			
		}		
		
		//make sure the info box is at the top
		var infoTop = document.getElementById("infobox_top_element");
		if (infoTop)
		{
			//infoTop.scrollIntoView(false);
			new Effect.ScrollIntoViewTo("infobox_top_element");
		}
		
			
		var t = this;
		
		//Scriptaculous appear effects for the loading divs
		if(this.useAnimation)
		{
			Effect.Appear('ICls', { duration: 0.5 });
			Effect.Appear('IClsbg', 
							{
								to:0.75, 
								duration: 0.5 ,
								afterFinish: function()
												{
													//Call the data request with url
													document.fire('DataController:Request', { 'sender' : t, 'id' : 'infobox_get', 'type' : "GET", 'url' : t.url });
												}
							});
		}
		else
		{
			$("loading_noanim").style.display = '';
			document.fire('DataController:Request', { 'sender' : t, 'id' : 'infobox_get', 'type' : "GET", 'url' : t.url });
		}
	},

//loopp through form fields and add them to a 
//post based AJAX request.  USed for 
//secure communication of passwords etc, rather
//than plan text GET requests
SubmitForm: function(e)
	{
		var form = e.memo;		
				
		//Cancel any outstanding ajax calls
		document.fire('DataController:Cancel', this);
		//hide the light box if open
		document.fire('LightBox:Hide')
		
				
			var thisObj = this;
			
			//Look at the form and set any parameters in the form string, for the post data
			var formString = "";
			var formUrl = "";
			
			
			formUrl = form.action;
			
			//loop through form fields
			for (var i=0;i<form.elements.length;i++)
			{
				if (form.elements[i].name=="js_Url")
				{
					formUrl = form.elements[i].value;
				}
				else
				{
					if (i>0)
					{
						formString += "&";
					}
					formString += form.elements[i].name;
					formString += "=" + URLEncode(form.elements[i].value);
				}
			}
			
			
			this.url = formUrl + "&" + window.mSpaceApplication.sessionString;
			
			if (window.ColumnBrowser)
			{
				this.url += window.ColumnBrowser.GetColumnParamString();
			}			
			
			
			

			var t = this;
			
			if(this.useAnimation)
			{
				Effect.Appear('ICls', { duration: 0.5 });
				Effect.Appear('IClsbg', 
								{
									to:0.75, 
									duration: 0.5 ,
									afterFinish: function()
													{
														//send post request
														document.fire('DataController:Request', { 'sender' : t, 'id' : 'infobox_post', 'type' : "POST", 'postvars' :  formString,'url' : t.url });
													}
								});
			}
			else
			{
				$("loading_noanim").style.display = '';
				document.fire('DataController:Request', { 'sender' : t, 'id' : 'infobox_post', 'type' : "POST", 'postvars' :  formString,'url' : t.url });
			}
					
	},
	
HandleError: function(id, status)
{
		if((id=="infobox_post") || (id=="infobox_get"))
		{
			// Request a 404 Page	
			var t = this;
			document.fire('DataController:Request', { 'sender' : t, 'id' : 'infobox_404', 'type' : "POST", 'postvars' :  null,'url' : 'html/404.html' });
		}
		else if(id == "infobox_404")
		{
			// Could not find the 404 page so manually output a 404 error	
			$("loading_noanim").style.display = 'none';
			$("ICCont").update("404 Error - The Requested page could not be found");
			//$("IC").setStyle({height: $("ICCont").offsetHeight + "px"});
		}
},
	
//handle the response from a data request call
HandleResponse: function(id, data)
	{
		if ((id!="infobox_post") && (id!="infobox_get") && (id!="infobox_404"))
			return;
			
		//hide the light box if open
		document.fire('LightBox:Hide')
			
		this.initialized = true;
		
		//Animation Effects:
		//Hide the background content that is still visible by makeing opacity of
		//loading div 100.  Then load content in background, fade out loading div
		//again, and then resize the info panel to match new content.
		var sh = $("IC").offsetHeight;
		//$("IC").setStyle({height:(sh + "px"), overflow: 'hidden'});
		//Update the contents. this automatically executes any <SCRIPT elements
		
		if(this.useAnimation)
		{
			new Effect.Opacity('ICCont', 
							{ 
								duration: 0.5, 
								from: 1,
								to: 0,
								afterFinish: function()
												 {
														$("ICCont").update(data); 
														new Effect.Opacity('ICCont', 
																	  	{ 
																	  		duration: 0.5, 
																			from: 0,
																			to: 1,																		
																			afterFinish: function()
																						  {
							
																								$("ICCont").setStyle({height:'auto'});
																								var eh = $("ICCont").offsetHeight;
																								
																								//alert(eh);
																								
																								//Resize the info panel to new content
																								new Effect.MoveAndResizeTo("IC",
																													   parseFloat(Element.getStyle($("IC"),'top')  || 0),
																													   parseFloat(Element.getStyle($("IC"),'left')  || 0),
																													   parseFloat(Element.getStyle($("IC"),'width')  || 0),
																													   eh );
																								
																								Effect.Fade('ICls', { duration: 0.5 });
																								Effect.Fade('IClsbg', { from: 0.75, duration: 0.5 });	
																						  }
																		});
												 } 
																		 
							});
		}
		else
		{
			$("loading_noanim").style.display = 'none';
			$("ICCont").update(data);
			//$("IC").setStyle({height: $("ICCont").offsetHeight + "px"});
		}

		
		

		
		
		//mSpaceApplication.Resize();	
	},
	
//Listen out for Column browser selections, and external item clicks, 
//and load the correct server request infobox action, with the slice string
//and any selections passed as parameters
SelectItem: function(e)
	{
		var eventParams = e.memo;
		
		if ((eventParams.column) && (eventParams.listitem))
		{
			
			document.fire('DataController:Cancel', this);
			
			this.url = window.mSpaceApplication.GetServerUrl("infobox");

			// goaluri/goalcol are only sent when the item is selected from the info box
			// for this reason use this as the deciding factor as to which variables to use
			if(eventParams && eventParams.goalcol && eventParams.goaluri)
			{
				if ((eventParams) && (eventParams.goalcol))
				{
					this.url += "&columnclicked=" + URLEncode(eventParams.goalcol);
				}
				
				if ((eventParams) && (eventParams.goaluri))
				{
					this.url += "&itemclicked=" + URLEncode(eventParams.goaluri);
				}
			}
			else
			{
				//get column and item clicks
				if ((eventParams) && (eventParams.column))
				{
					this.url += "&columnclicked=" + URLEncode(eventParams.column.uri);
				}
				
				if ((eventParams) && (eventParams.listitem))
				{
					this.url += "&itemclicked=" + URLEncode(eventParams.listitem.uri);
				}		
			}

			//Get slice string
			if (window.ColumnBrowser)
			{
				this.url += window.ColumnBrowser.GetColumnParamString();
			}
			
			//DEPRECATED: used to send the advanced search string, to combine both 
			//advanced search and slice but this was confusing
			/*
			if (window.AdvancedSearch)
			{
				this.url += window.AdvancedSearch.GetSearchString();
			}*/
			
			document.fire('Log:Event', { type: "DataEvent", message: "[getinfo] " + this.url});
			this.LoadContents();
		}		
	},
	
//USed to imitate an item select, with a passed slice string, so it does not 
//use the current slice.. used by scratch pad, and possibly history as well.
SelectItemWithSlice: function(e)
	{
		var eventParams = e.memo;
		if ((eventParams) && (eventParams.column) && (eventParams.listitem))
		{
			
			document.fire('DataController:Cancel', this);
			
			this.url = window.mSpaceApplication.GetServerUrl("infobox");

			if (eventParams.column)
			{
				this.url += "&columnclicked=" + URLEncode(eventParams.column.uri);
			}
			
			if (eventParams.listitem)
			{
				this.url += "&itemclicked=" + URLEncode(eventParams.listitem.uri);
			}
						
			if (eventParams.sliceString)
			{
				this.url += eventParams.sliceString;
			}			
			
			document.fire('Log:Event', { type: "DataEvent", message: "[getinfo] " + this.url});
			this.LoadContents();
		}		
	},
	
//Load url or column selection history info pages
HistoryChange: function(e)
	{
		var histObj = null;
		
		if(e)
		{
			if(e.memo)
				histObj = e.memo;
			else
				histObj = e;
		}
		
		if (histObj["Info.Url"])
		{
			//load normal url			
			this.url = histObj["Info.Url"];
			this.LoadContents();
		}		
		else if (histObj["Column.SelectItemHistory"])
		{
			//load an info box call with slice etc.
			this.url = window.mSpaceApplication.GetServerUrl("infobox") + "&" + histObj["Column.SelectItemHistory"];
			document.fire('Log:Event', { type: "DataEvent", message: "[getinfo_history] " + this.url});
			this.LoadContents();
		}
		
	},

//Cancel the current loading request
StopLoading: function()
	{
		
		document.fire('DataController:Cancel', this);
		
		Effect.Fade('ICls', { duration: 0.5 });
		Effect.Fade('IClsbg', { from: 0.75, duration: 0.5 });
		
	},
	
//Resize the container to fit contents.
ResizeContainer: function(e)
	{
		$("ICCont").setStyle({height:'auto'});
		var eh = $("ICCont").offsetHeight;
		
		//alert(eh);
		
	
		new Effect.MoveAndResizeTo("IC",
							   parseFloat(Element.getStyle($("IC"),'top')  || 0),
							   parseFloat(Element.getStyle($("IC"),'left')  || 0),
							   parseFloat(Element.getStyle($("IC"),'width')  || 0),
							   eh );		
	}
	
}
