//////////////////////////////////////////////
// ScratchPad Object 
//////////////////////////////////////////////
//
// The scratch pad control is a popup window 
// that allows users to add items of interest 
// to, for persistent storage and tagging.  
// Any list item can be added to the scratch 
// pad, and a user does not need to be logged 
// into the system to add items, however, 
// tagging functionality is limited to logged 
// in users and goal items.
//
//////////////////////////////////////////////

var ScratchPad = Class.create();
ScratchPad.prototype = {

//local variables
//control surface
ctlsfc: null,
//render surface id, usually body
rsid: null,
//list of items
itemList: new Array(),
//list of groups: not currently used
groupList: new Array(),
//intial tag box text
intitalTagBoxText: "Enter Tags...",
//tag box ok text.
okTagBoxText: "Items Tagged!",
//last position
lastX: 20,
lastY: 20,
//
// Constructor
initialize: function(oo)
	{
		
		//Inherit all the passed object options
		Object.extend(this, oo);
		
		
		//show the open scratch pad button 
		//so that its only visible when dynamic
		//version of the site is being used.
		if (this.openBtnID)
		{
			var btn = document.getElementById(this.openBtnID);
			if (btn)
			{
				btn.style.display="";
			}
		}
		
		//build scratch pad dom
		var tagBox = Builder.node('div',{id: "SPTagPnl", className: "SPTagPnl"},
														 [
														  	Builder.node('input',{id: "SPTagBx", type: "text", value: this.intitalTagBoxText}),
															Builder.node('input',{id: "SPTagBtn", type: "button", value: "Tag"})
														 ]);
		
		if(!mSpaceApplication.GetConfig('CommercialServer'))
			tagBox = Builder.node('div');
		
		this.ctlsfc = Builder.node('div', {id: "SP", className: 'Draggable', style: "left: -8000px; display: none; width: 200px; height: " + Math.min(300, (getWindowHeight())) + "px;"},
						[
						 	Builder.node('div',{id: "SPHdr", className: 'DraggableHdr'},
										 [
										  	Builder.node('div',{id: "SPClsBtn", className: 'DraggableClsBtn', title: "Close the Scratch Pad"}),
											Builder.node('div',{className: "DraggableIcon", title: "Close the Scratch Pad"}),
											"Scratch Pad"
										 ]),
							Builder.node('div',{className: 'DraggableBody'},
										 [
											Builder.node('div',{id: "SPContLst"}),
											Builder.node('div',{id: "SPGroupLst"}),
											Builder.node('div',{id: "SPControlsCont"},
														 [
														 		Builder.node('input', {id: 'SPSelectAll', type: 'button', value: 'Select All'}),
														 		Builder.node('input', {id: 'SPSelectNone', type: 'button', value: 'Select None'}),
														 ]),
											tagBox
										 ]),
							Builder.node('div',{id: "SPFtr", className: 'DraggableFtr'},
										 [
										  	Builder.node('div',{id: "SPDelBtn", title: "Delete currently checked items"}),
											Builder.node('div',{id: "SPReszBtn", className: 'DraggableResizeBtn', title: "Resize the Scratch Pad"})
										 ])
						]);	
			
		
		//If the render surface id is null, then append to the document body
		if (this.rsid==null)
		{
			document.body.appendChild(this.ctlsfc);
		}
		else
		{
			document.getElementById(this.rsid).appendChild(this.ctlsfc);
		}
		
		
		//Subscribe Events
		document.observe('mSpaceApplication:PageResize',			this.Resize.bindAsEventListener(this));
		
		document.observe('Column:DoubleClick',								this.AddItem.bindAsEventListener(this));
		
		document.observe('ScratchPad:Add',										this.AddItem.bindAsEventListener(this));
		document.observe('ScratchPad:ItemClick',							this.ItemClick.bindAsEventListener(this));
		document.observe('ScratchPad:Open',										this.Open.bindAsEventListener(this));
		document.observe('ScratchPad:Close',									this.Close.bindAsEventListener(this));
			
		//Register Dom event
		
		Event.observe("SPDelBtn", "click", this.DeleteItems.bindAsEventListener(this));	
		Event.observe("SPClsBtn", "click", this.Close.bindAsEventListener(this));		
		Event.observe("SPSelectAll", "click", this.SelectAll.bindAsEventListener(this));
		Event.observe("SPSelectNone", "click", this.SelectNone.bindAsEventListener(this));	
		
		if(mSpaceApplication.GetConfig('CommercialServer'))
		{
			Event.observe("SPTagBtn", "click", this.TagItems.bindAsEventListener(this));
			Event.observe("SPTagBx", "click", this.BlurTagBox.bindAsEventListener(this));	
		}
		
		//Load any items stored already
		this.LoadCookie();
		
		//Make the item draggable: scriptaculous function
		new Draggable("SP",{handle:"SPHdr"});
		
		//Make the object resizable: custom scriptaculous function
		var t = this;
		new Resizable("SP",{handle:"SPReszBtn", min: [80,80], change: function(){t.Resize();} });
	},

//Resize the contents of the 
//scratch pad div
Resize: function()
	{
		var tagPnlHeight = 0;
		
		if(mSpaceApplication.GetConfig('CommercialServer'))
			tagPnlHeight = $("SPTagPnl").offsetHeight;
		
		$("SPContLst").style.height = IEINT($("SP").clientHeight - ($("SPFtr").offsetHeight + $("SPHdr").offsetHeight + tagPnlHeight + $("SPGroupLst").offsetHeight + $("SPControlsCont").offsetHeight)) + "px";
		
		if(mSpaceApplication.GetConfig('CommercialServer'))
		{
			var size = ($("SP").clientWidth - $("SPTagBtn").offsetWidth - 10);
			
			if (size<0)
				size = 0;
		
			$("SPTagBx").style.width = size +  "px";
		}
	},
	
//open the scratch pad
Open: function(e)
	{
		$("SP").show();
		$("SP").style.left = this.lastX + "px";
		$("SP").style.top = this.lastY + "px";
		this.Resize();
	},

//close the scratch pad
Close: function(e)
	{
		this.m_DragWindow = false;
		this.lastX = $("SP").offsetLeft;
		this.lastY = $("SP").offsetTop;
		$("SP").style.left = "-8000px";	
		$("SP").hide();
	},
	
//add an item to the scratch pad
AddItem: function(e)
	{
		var eventParams = e.memo;
		var dataObj = {};
		
		//make sure sp is open
		this.Open();
		
		//create an object options
		//to pass to new list item
		dataObj.tp = "GOAL";
		dataObj.sliceStr = "";
		if (window.ColumnBrowser)
		{
			//get the current slice string
			dataObj.sliceStr += window.ColumnBrowser.GetColumnParamString({uri: eventParams.listitem.uri, coluri: eventParams.column.uri});
		}	
		dataObj.listitem = eventParams.listitem.uri;
		dataObj.column = eventParams.column.uri;
		dataObj.title = eventParams.listitem.label;
		dataObj.title2 = eventParams.column.label;
		if (eventParams.noselect)
			dataObj.noselect = eventParams.noselect;
	
		//create a new list item
		var newItem = new ScratchPadListItem(this.itemList.length);
		
		//Add new item to list
		newItem.SetItem(dataObj);
		
		this.itemList.push(newItem);
		
		$("SPContLst").appendChild(newItem.ctlsfc);
		
		//Update cookies
		this.UpdateCookies();
	},
	
//Delete an item from list
//Loop through, and see which 
//items are checked, and delete them
DeleteItems: function(eventParams)
	{
		var newArray = new Array();
		for (var i=0;i<this.itemList.length;i++)
		{
			var li = this.itemList[i];
			if (li.chkBx.checked)
			{
				$("SPContLst").removeChild(li.ctlsfc);
			}
			else
			{
				newArray.push(li);
			}
		}	
		
		this.itemList = newArray;
		
		//update cookies
		this.UpdateCookies();
		
	},

// Select all items in the Scratchpad list	
SelectAll: function()
	{
		for (var i=0;i<this.itemList.length;i++)
		{
			var li = this.itemList[i];
			li.chkBx.checked = true;
		}
	},

// Unselect all items in the Scratchpad list	
SelectNone: function()
	{
		for (var i=0;i<this.itemList.length;i++)
		{
			var li = this.itemList[i];
			li.chkBx.checked = false;
		}
	},
	
//Tag the currently selected items, with the
//values from the tag input box
TagItems: function(eventParams)
	{
		if (($("SPTagBx").value=="") || (this.intitalTagBoxText==$("SPTagBx").value) || (this.okTagBoxText==$("SPTagBx").value))
			return;
			
		var itemArray = new Array();
		for (var i=0;i<this.itemList.length;i++)
		{
			var li = this.itemList[i];
			if (li.chkBx.checked)
			{
				itemArray.push(li.dataObj.listitem);
			}
		}		
		
		//Call the Tag Control to tag the array of items
		//with the tags
		if (itemArray.length<1)
			return;
		var thisObj = this;
		document.fire('TagControl:AddTag',{ items : itemArray, tags : $("SPTagBx").value, input: 'SPTagBx', isPublic: true, notifyFunction: function(param) {thisObj.TagReturnedOk(param);}});
	},
	
//Handle a response from the server
//on tag completion
TagReturnedOk: function(success)
	{
		//If the results ok 
		//then flash the tag box to indicate success
		if (success=="ok")
		{
		
			this.m_highlightTagBoxCount = 0;
			
			$("SPTagBx").value = this.okTagBoxText;
			$("SPTagPnl").addClassName("SPTagPnlHigh");
			
			var thisObj = this;
			setTimeout(function() { $("SPTagPnl").removeClassName("SPTagPnlHigh"); $("SPTagBx").value = thisObj.intitalTagBoxText;}, 3000);
		}
		
	},
	
//then the user clicks the tag box, hide the default message
BlurTagBox: function(e)
	{
		if ((this.intitalTagBoxText==$("SPTagBx").value) || (this.okTagBoxText==$("SPTagBx").value))
		{
			$("SPTagBx").value = "";
			$("SPTagBx").className = "tagBox";
		}
	},
	
//When an item is clicked
//re load the slice at the time, and make the
//selection automatically
ItemClick: function(e)
	{		
		var li = e.memo;
		
		if (li.dataObj.noselect)
			return;
			
		var col = new Object();
		col.uri = li.dataObj.column;
		
		
		var litem = new Object();
		litem.uri = li.dataObj.listitem;		
		
		document.fire('Column:SelectItemWithSlice', { listitem: litem, column: col, sliceString: li.dataObj.sliceStr });		
	},
	
//Store all the items within the scratchpad
//as cookies on the client for persistant storage
UpdateCookies: function()
	{
		var cookieArray = new Array();
		for (var i=0;i<this.itemList.length;i++)
		{
			cookieArray.push(this.itemList[i].GetObject());
		}
		
		var cookieString = URLEncode(Ob2Str(cookieArray));
		
		
		setCookie( 'mspace_scratchpad', cookieString, 365*10, '/', '', '' );
		
	},
	
//Load any persistant items from a client cookie
LoadCookie: function()
	{
		var cookieString = getCookie('mspace_scratchpad');
		if (cookieString)
		{						
			try
			{
				var cookieArray = eval(URLDecode(cookieString));
				
				for (var i=0;i<cookieArray.length;i++)
				{
					var newItem = new ScratchPadListItem(this.itemList.length, cookieArray[i]);					
					
					this.itemList.push(newItem);
					
					$("SPContLst").appendChild(newItem.ctlsfc);
				}
			}
			catch (e)
			{
				alert("Error Loading Scratchpad: " + e.message);
			}
		}
	}
	
	
}




//////////////////////////////////////////////
// ScratchPadListItem Object 
//////////////////////////////////////////////
//
// This object is a cusom list item implementation
// similar to that of the list controls list items
// 
// It adds a checkbox control to the list item
// so items can be selected and changed in multiples.
//
//////////////////////////////////////////////

var ScratchPadListItem = Class.create();
ScratchPadListItem.prototype = {

//local variables
ctlsfc: null,
title: "Scratch Pad Item",
sliceStr: "",
li: null,
col: null,
chkBx: null,

//Data Object
dataObj: {title: "item"},
//
// Constructor
initialize: function(no, dataObj)
	{
		this.dataObj = dataObj || this.dataObj;
			
		var currClass = "Even SPLI";
		if (isOdd(no))
		{
			currClass = "Odd SPLI"
		}		
		
		//build the dom layout
		
		this.chkBx = Builder.node('input', {className: "chk", type: "checkbox", checked: false});
		
			this.lbl = Builder.node('div', {className: "Lbl"}, [this.dataObj.title]);
			this.libtn = Builder.node('a', {className: currClass}, 
									  [									   
									   this.lbl
									  ]);
			
			
		
			//Create the main holder
			this.ctlsfc = Builder.node('div', {className: "Li"},
									[
									 	Builder.node('div', {className: "LiCont"},
													 [	
													  this.chkBx,
													  this.libtn
													 ])										
									]);
			
			//Register events	
			Event.observe(this.libtn, "click", this.MouseClickListItem.bindAsEventListener(this));
	},
	
//Set the associated data object
SetItem: function(dataObj)
	{
		this.dataObj = dataObj;
		
		this.lbl.innerHTML = dataObj.title;
		this.lbl.innerHTML += " (" + dataObj.title2 + ")";
		
	},
	
//Send a scratch pad click event
MouseClickListItem: function(e, element)
	{
		document.fire('ScratchPad:ItemClick', this);
	},
	
//get the current data object
GetObject: function()
	{		
		return this.dataObj;
	}
	
}




