

var AjaxClient = Class.create({
	initialize : function()
	{
		this.serverPath = "/ajax/server.php";
		this.callbackFailure = undefined;
		this.callbackSuccess = undefined;
	},
	RunCommand : function(obj, command, params, callbackSuccess, callbackFailure, isAsync)
	{
		if(isAsync == undefined) isAsync = true;
		
		this.callbackSuccess = callbackSuccess;
		this.callbackFailure = callbackFailure;
		if(params != undefined)
		{
			params['c'] 	= command;
			params['obj'] 	= obj;
			params['rid'] 	= Math.floor(Math.random()*10000); // generate random number

			// make the ajax call;
			new Ajax.Request(this.serverPath,{
				parameters : params,
				asynchronous : isAsync,
				onSuccess : this.onSuccess.bind(this),
				onFailure : this.onFailure.bind(this)
			});
		}
	},
	onSuccess : function(transport)
	{
		// Check we got a valid response from the server
		var validResponse = transport.responseText.indexOf('{');
		if (validResponse != 0)
		{
			this.onFailure(transport);
		}
		else
		{
			var ob = transport.responseText.evalJSON();
			if(ob.RESULT == 'FAIL')
				this.onFailure(transport, ob);
			else
			{
				if(this.callbackSuccess != undefined)
					this.callbackSuccess(ob.RESPONSE,transport);
			}
		}
	},
	onFailure : function(transport, ob)
	{
		var error = "Command failed: ";
		if(ob != undefined)
			error += ob.RESPONSE;
		else
			error += transport.responseText;
			
		if(this.callbackFailure != undefined)
			this.callbackFailure(error, ob)
		else
			alert(error);
	}
});


function shorten(text, len)
{
	if(text.length > len)
		return text.substr(0,len) + '..';
	else
		return text;
}

/**
  *	Adjusts the height of the inner content div to match the right hand column length.
  * The 1.05 (5%) adjustment factor is there... well, just because. It needs to be there. Just trust me, okay?
  * Cheers, DW.
**/
var originalContentHeight = 0;

function adjustHeight(delayMilliseconds)
{
	if (originalContentHeight == 0) {
		originalContentHeight = $('contentInner').getHeight();
	}
	var newHeight = ($('colRight').getHeight() * 1.05);
	if (originalContentHeight < newHeight) {
		$('contentInner').setStyle({height: newHeight.toString() + 'px' });
	}
}


function specialShowSaveButton(saveButton)
{
	// make the button slide down when showing
	Effect.BlindDown(saveButton, {duration:.1});
}

function specialHideSaveButton(saveButton)
{
	// make the button slide down when showing
	Effect.BlindUp(saveButton, {duration:.1});
}

var AJAX_RunCommand_ID = 0;
var AJAX_Client_Callbacks = {};
var AJAX_Client_Objects = {};

var DEFAULT_ENTER_TEXT = 'Enter notes here...';

var AJAX_Client = Class.create({
	initialize : function()
	{
		this.AJAX_API = "/ajax/server.php";
		this.CallBacks = null;
	},
	RunCommand: function(object, command, params, callback, callbackObject)
	{
		AJAX_RunCommand_ID++;
		
		var self = this;
		AJAX_Client_Callbacks[AJAX_RunCommand_ID] = callback;
		AJAX_Client_Objects[AJAX_RunCommand_ID] = callbackObject;
		
		params['c'] 	= command;
		params['obj'] 	= object;
		params['rid'] 	= AJAX_RunCommand_ID;
		
		new Ajax.Request(self.AJAX_API,
		{
			parameters: params,
			onComplete: self.CommandDidComplete,
			onFailure: self.CommandDidFail
		});
	},
	CommandDidFail: function(transport)
	{
		alert("Command failed: "+ transport.responseText);
	},
	CommandDidComplete: function(transport)
	{
		// Check we got a valid response from the server
		var validResponse = transport.responseText.indexOf('{');
		
		if (validResponse != 0)
		{
			alert("Command failed: "+ transport.responseText);
			return;
		}
		else
		{
			var result = transport.responseText.evalJSON();
			var callback = AJAX_Client_Callbacks[result.rid];
			var object = AJAX_Client_Objects[result.rid];
			
			if (callback && object)
			{
				callback(object, result);
			}
			else if (callback)
			{
				callback(result);
			}
		}
	}
});

// WidgetController base class
var WidgetController = Class.create({
	initialize : function()
	{
		
	},
	
	FailedWithError: function(result)
	{
		alert("Error: " + result.ERROR);
		return;
	}
});

var ProfileWidgetController = Object.extend(Class.create({}), WidgetController).addMethods({
	initialize : function()
	{
		this.ajaxClient = new AJAX_Client();
		this.sidebarDivs = {};
		this.objectID = null;
		this.objectType = null;
		this.inLibrary = 0;
		this.calendarDates = [];
		this.products = [];
		this.tasks = $A();
	},
	LoadSidebar : function(elements, id, obj)
	{

		//alert($(div));
		//$(div).insert("Sidebar here");
		this.objectID = id;
		this.objectType = obj;
		this.ajaxClient.RunCommand('Profile', 'LoadObjectState', {'id': this.objectID, 'type': this.objectType}, this.DidLoadSidebar, this);
		this.sidebarDivs = elements;
	},
	
	// Callback methods get "self" back as a refernce to this object as we loose it when we do an async call
	DidLoadSidebar : function(self, result)
	{
		if (result.RESULT == 'OK')
		{		
			// Hide loading message
			$(self.sidebarDivs.loading).hide();
			$(self.sidebarDivs.loaded).show();
		
			// Check results and update display
			data = result.RESPONSE;
		
			// Load library data
			self.LoadLibraryData(self, result);
			
			// Load existing calendar dates and display
			self.LoadCalendarData(self, result);
			self.ShowDates();
			$(self.sidebarDivs.calendarAddDateButton).observe('click', function(event){
				self.AddDate();
			});

			// observe task adding button
			self.LoadTaskData(self, result);
			$(self.sidebarDivs.tasksAddButton).observe('click', function(event){
				// only allow adding task if there
				// isn't already a task in assign to mode
				var found = false;
				if($('profileTaskList').select("input[value='Assign']").each(function(el){
					if(el.visible())
						found = true;
				}));
				
				if(found)
					alert("Can't add new task until all tasks have been assigned and saved!");
				else
					self.AddTask();
			});
			
			// Load existing products and display
			self.LoadProductData(self, result);
			self.ShowProducts();
			self.WireProductEventHandlers();
			// start out with one product
			self.AddProduct();
			
			
			//TODO: DW: HERE:
			adjustHeight(0);
			
			$('colRight').observe('click', function(event) {
				adjustHeight(0);
			});
	
		}
		else
		{
			self.FailedWithError(result);
		}
	},
	
	LoadProductData : function(self, result)
	{
		for (var i=0; i<data.products.length; i++)
		{
			var row = data.products[i];
			var product = new Product(row.Object_ID, row.Object_Type, row.Product_ID, row.Product_Name);
			self.products.push(product);
		}
	},
	
	LoadCalendarData : function(self, result)
	{
		for (var i=0; i<data.calendarDates.length; i++)
		{
			var row = data.calendarDates[i];
			var reminder = {
				'enabled' : row.Reminder_Enabled,
				'gap' : row.Reminder_Gap,
				'custom' : row.Reminder_Custom
			};
			var calDate = new CalendarDate(row.Object_ID, row.Object_Type, row.Calendar_Record_ID, row.Calendar_Date, row.Notes, reminder);
			self.calendarDates.push(calDate);
		}
	},
	
	LoadTaskData : function(self, result)
	{
		$(this.sidebarDivs.tasksDiv).update();
		for (var i=0; i<data.tasks.length; i++)
		{
			var row = data.tasks[i];
			var task = new Task(row.Object_ID, row.Object_Type, row.User_Task_ID, row.Notes, 
				row.Assigned_To_ID, row.Assigned_To_Name, row.Assigned_To_Email, row.Assigned_By_Name, row.Date_Created,
				row.Is_Completed, row.Is_Emailed, row.Type);
			var index = self.tasks.push(task)-1;
			this.ShowTask(index);
			// if only partly done then setup as edit
			if(row.Assigned_To_ID == -1)
				task.EditAssignedTo();
		}
	},
	LoadLibraryData: function(self, result)
	{
		if (data.inLibrary == 1) {
			$(self.sidebarDivs.libraryEnabledInput).value = 1;
			self.inLibrary = 1;
			$('profileLibraryAddDiv').hide();
			$('profileLibraryDeleteDiv').show();
			self.ShowNotes();
		}
		else {
			$('profileLibraryAddDiv').show();
			$('profileLibraryDeleteDiv').hide();
			self.HideNotes();
		}
		if (data.libraryNotes.length > 0) {
			$(self.sidebarDivs.libraryNotes).value = data.libraryNotes;
		}
		else
			$(self.sidebarDivs.libraryNotes).value = DEFAULT_ENTER_TEXT;
		
		// DEBUGGING
		
		
		// Now bind to the onChange event for both the checkbox and the notes
		$(self.sidebarDivs.libraryAddLink).observe('click', function(event){
			var element = event.element();
			var enabledInput = $(self.sidebarDivs.libraryEnabledInput);
			if($(enabledInput).value == 0)
			{
			 	self.ajaxClient.RunCommand('Profile', 'SaveToLibrary', 
											{'id': self.objectID, 'type': self.objectType, 'notes': self.removeDefaultText($F(self.sidebarDivs.libraryNotes))}, 
											self.DidSaveToLibrary, self);
				$(enabledInput).value = 1;
			}
		});
		$(self.sidebarDivs.libraryDeleteLink).observe('click', function(event){
			var element = event.element();
			var enabledInput = $(self.sidebarDivs.libraryEnabledInput);
			if($(enabledInput).value == 1)
			{
				self.ajaxClient.RunCommand('Profile', 'RemoveFromLibrary', 
											{'id': self.objectID, 'type': self.objectType, 'notes': self.removeDefaultText($F(self.sidebarDivs.libraryNotes))}, 
											self.DidRemoveFromLibrary, self);
				$(enabledInput).value = 0;
			}
		});
		
		$(self.sidebarDivs.libraryNotes).observe('change', function(event){

			if (self.inLibrary)
			{
				self.ajaxClient.RunCommand('Profile', 'UpdateLibraryRecord', 
											{'id': self.objectID, 'type': self.objectType, 'notes': self.removeDefaultText($F(self.sidebarDivs.libraryNotes))}, 
											self.DidUpdateLibraryRecord, self);
			}
		});
		
		$(self.sidebarDivs.libraryNotesSave).observe('click', function(event){
			if (self.inLibrary)
			{
				self.ajaxClient.RunCommand('Profile', 'UpdateLibraryRecord', 
											{'id': self.objectID, 'type': self.objectType, 'notes': self.removeDefaultText($F(self.sidebarDivs.libraryNotes))}, 
											self.DidUpdateLibraryRecord, self);
			}
			
			specialHideSaveButton(self.sidebarDivs.libraryNotesSave);
		}.bind(this));
		
		$(self.sidebarDivs.libraryNotes).observe('focus', function(event){
			// show the save button
			specialShowSaveButton(self.sidebarDivs.libraryNotesSave);
			
			if ($F(event.element()) == DEFAULT_ENTER_TEXT)
			{
				$(event.element()).value = '';
			}
		}.bind(this));

		$(self.sidebarDivs.libraryNotes).observe('blur', function(event){
			// show the save button
			if ($F(event.element()) == '')
			{
				$(event.element()).value = DEFAULT_ENTER_TEXT;
			}
		}.bind(this));
	},
	removeDefaultText : function(text)
	{
		if(text == DEFAULT_ENTER_TEXT)
			return '';
		else
			return text;
	},
	DidSaveToLibrary : function(self, result)
	{
		self.inLibrary = 1;
		self.ShowNotes();
		//$(self.sidebarDivs.status).replace('Saved: '+ NiceTime());
		//alert('done');		
	},
	
	DidRemoveFromLibrary : function(self, result)
	{
		self.inLibrary = 0;
		self.HideNotes();
		//$(self.sidebarDivs.status).replace('Removed: '+ NiceTime());
		//alert('done');
	},
	
	DidUpdateLibraryRecord : function(self, result)
	{
		// Called each time the library record is updated
		//$(self.sidebarDivs.status).replace('Saved: '+ NiceTime());
	},
	
	ShowNotes: function()
	{
		// setup default animation for expanding/contract
		$(this.sidebarDivs.libraryNotesDiv).show();
		$('profileLibraryAddDiv').hide();
		$('profileLibraryDeleteDiv').show();
	},
	
	HideNotes: function()
	{
		$(this.sidebarDivs.libraryNotesDiv).hide();
		$('profileLibraryAddDiv').show();
		$('profileLibraryDeleteDiv').hide();
	},
	
	ShowDates: function()
	{
		// Clear the dates
		$(this.sidebarDivs.calendarDatesDiv).update();

		// Now render them all

		for (var i=0; i<this.calendarDates.length; i++)
		{
			$(this.sidebarDivs.calendarDatesDiv).insert(this.calendarDates[i].GetHtml());
			this.calendarDates[i].DidRender(this.DidRemoveDate.bind(this));
		}
	},
	
	ShowProducts: function()
	{
		// Clear the products
		$(this.sidebarDivs.productsDiv).update();

		// Now render them all
		for (var i=0; i<this.products.length; i++)
		{
			$(this.sidebarDivs.productsDiv).insert(this.products[i].GetHtml());
			this.products[i].DidRender(this.DidRemoveProduct.bind(this));
		}
	},
	ShowTask : function(index)
	{
		if(index == 0)
			$(this.sidebarDivs.tasksDiv).insert({top:this.tasks[index].GetHtml()});
		else
			$(this.sidebarDivs.tasksDiv).insert(this.tasks[index].GetHtml());
		
		this.tasks[index].DidRender(this.DidRemoveTask.bind(this));
	},
	WireProductEventHandlers : function()
	{
		// Deal with selecting to a new product
		$(this.sidebarDivs.productsSelector).observe('change', this.onProductSelectorChange.bind(this));
		$(this.sidebarDivs.productsGoButton).observe('click', this.onAddNewProductGo.bind(this));
	},
	onProductSelectorChange : function(event)
	{
		if ($F(this.sidebarDivs.productsSelector) == 'ADD')
		{
			$(this.sidebarDivs.productsNewProduct).show();
			$(this.sidebarDivs.productsNewProduct).value = 'Enter a name..';
			$(this.sidebarDivs.productsGoButton).show()
			$(this.sidebarDivs.productsNewProduct).focus();
			$(this.sidebarDivs.productsNewProduct).select();
			this.addingExistingProduct = 0;
		}
		else
		{
			this.addingExistingProduct = 1;
			$(this.sidebarDivs.productsNewProduct).hide();
			$(this.sidebarDivs.productsGoButton).hide()			
			this.AddExistingProduct();
		}
	},
	AddExistingProduct : function()
	{
		// make sure its not lines or the select product test
		if($F(this.sidebarDivs.productsSelector) != '')
		{
			var prodID = $F(this.sidebarDivs.productsSelector);
			this.ajaxClient.RunCommand('Profile', 'SaveProductToObject', {'id': this.objectID, 'type': this.objectType, 'productID': prodID}, function(result) {
				var userProdID = result.RESPONSE.User_Product_ID;
				var productData = result.RESPONSE.Product;
			
				// Hide the go button and the dropdown
				//this.HideNewProductSelector();
			
				var product = new Product(this.objectID, this.objectType, productData.Product_ID, productData.Name);
				this.products.push(product);
				this.ShowProducts();
				this.AddProduct();
			}.bind(this));
		}
	},
	onAddNewProductGo : function(event)
	{
		// now we need to add a new product to the system (user product) and link it to this object
		var newProductName = $F(this.sidebarDivs.productsNewProduct);
	
		this.ajaxClient.RunCommand('Profile', 'SaveNewProductToObject', {'id': this.objectID, 'type': this.objectType, 'productName': newProductName}, function(result) {
			var userProdID = result.RESPONSE.User_Product_ID;
			var productData = result.RESPONSE.Product;
		
			// Hide the go button and the dropdown
			//this.HideNewProductSelector();
			$(this.sidebarDivs.productsNewProduct).hide();
			$(this.sidebarDivs.productsGoButton).hide();
			
			var product = new Product(this.objectID, this.objectType, productData.Product_ID, productData.Name);
			this.products.push(product);
			this.ShowProducts();
			this.AddProduct();
		}.bind(this));
	},
	AddProduct: function()
	{
		this.ajaxClient.RunCommand('Profile', 'LoadUserProductOptions', {'id': this.objectID, 'type': this.objectType}, function(result) {
			
			// clear out the select
			$(this.sidebarDivs.productsSelector).update();
			
			var html = "<option value=''>Assign a Product</option>";
			html += "<option value=''>------------------</option>";
			var productLists = result.RESPONSE;
			
			if (productLists.UserProducts)
			{
				// User products
				for (var i=0; i<productLists.UserProducts.length; i++)
				{
					html += "<option value='"+ productLists.UserProducts[i].Product_ID +"' title='"+productLists.UserProducts[i].Name+"'>";
					html += shorten(productLists.UserProducts[i].Name,20) + " </option>";
				}
			}
			html += "<option value=''>------------------</option>";
			html += "<option value='ADD'>Add New Product...</option>";
			
			// In "existing productMode"
			this.addingExistingProduct = 1;

			// Show the go button
			//$(this.sidebarDivs.productsGoButton).show();
		
			$(this.sidebarDivs.productsSelector).insert(html);
			$(this.sidebarDivs.productsSelector).selectedIndex = 0;
			
		}.bind(this));
	},
	AddTask : function()
	{
		var task = new Task(this.objectID, this.objectType, -1, "", -1, "","","",null,null,"Company");
		task.Save(function(result){		
			// Now push it to our array and then show the dates
			task.taskID = result.taskID;

			//var index = self.tasks.push(task)-1;
			this.tasks.unshift(task);
			this.ShowTask(0);
			task.EditAssignedTo();
		}.bind(this), this);
	},
	DidRemoveTask : function(result)
	{
		// remove from the array
		var newTasks = $A();
		this.tasks.each(function(task){
			if(result.id != task.taskID)
				newTasks.push(task);
		});
		this.tasks = newTasks;
	},
	HideNewProductSelector : function()
	{
		$(this.sidebarDivs.productsGoButton).hide();
		if ($('newProductSelector')) { $('newProductSelector').stopObserving(); }
		$(this.sidebarDivs.productsGoButton).stopObserving();
		$(this.sidebarDivs.productsAddDiv).update();
	},
	AddDate: function()
	{
		// Create a new date and save it to the database
		var date = new DateUtilities();
		
		var calDate = new CalendarDate(this.objectID, this.objectType, 0, date.Today(), DEFAULT_ENTER_TEXT, null);
		
		calDate.Save(function(self, result){		
			// Now push it to our array and then show the dates
			calDate.dateID = result.RESPONSE.dateID;

			self.calendarDates.unshift(calDate);
			self.ShowDates();	
		}, this);

	},
		
	DidRemoveDate: function(id) 
	{
		var calDate = this.FindDate(id);
		
		if (calDate)
		{
			calDate.Delete(function(self, result)
			{
				// Update the calendar dates array and remove the record
				var newDatesArray = [];

				for(i=0; i<self.calendarDates.length; i++)
				{
					var row = self.calendarDates[i]; 
					if (row.dateID != id)
					{
						newDatesArray.push(row);
					}
				}
				// setup the dates
				self.calendarDates = newDatesArray;
				
				// Then redisplay all the dates to the page
				self.ShowDates();
			}, this);
		}
	},
	
	DidRemoveProduct: function(id) 
	{
		var product = this.FindProduct(id);
		
		if (product)
		{
			product.Delete(function(self, result){
				var newProductsArray = [];

				for(i=0; i<self.products.length; i++)
				{
					var row = self.products[i]; 
					if (row.productID != id)
					{
						newProductsArray.push(row);
					}
				}

				self.products = newProductsArray;
				self.ShowProducts();
				self.AddProduct();
			}, this);
		}
		
		//this.HideNewProductSelector();
	},
	
	FindDate: function(id)
	{
		for(i=0; i<this.calendarDates.length; i++)
		{
			var row = this.calendarDates[i];
			if (row.dateID == id)
			{
				return row;
			}
		}
		return null;
	},
	
	FindProduct: function(id)
	{
		for(i=0; i<this.products.length; i++)
		{
			var row = this.products[i];
			if (row.productID == id)
			{
				return row;
			}
		}
		return null;
	}

});

var Product = Class.create({
	initialize : function(objID, objType, productID, name)
	{
		this.productID		= productID;
		this.objectID		= objID;
		this.objectType 	= objType;
		this.productName	= name;
		this.ajaxClient 	= new AJAX_Client();
	},
	
	GetHtml : function()
	{
		var html = "<div id='objectProductDiv_" + this.productID + "' class='productWrapper' style='border-bottom: 1px solid #ddd;padding-bottom:2px;margin-bottom: 4px;'>";
		html 	+= "<div style='float:left;width:130px;'>"+this.productName+"</span></div>";
		html 	+= "<div style='float:right;cursor:pointer;'><img src='/images/myeiatrack/grey-close-button.png' id='removeProductButton_"+this.productID+"' /></div>";
		html	+= "<div style='clear:both;'></div>";
		html 	+= "</div>";
		
		return html;
	},
	
	DidRender: function(callback)
	{
		$('removeProductButton_'+this.productID).observe('click', function(event){		
			var buttonID = event.target.id;
			var productID = buttonID.substr(buttonID.indexOf('_') + 1);
			callback(productID);
		}.bind(this));
	},
	
	Delete : function(callback, object)
	{
		$('removeProductButton_'+this.productID).stopObserving();
		this.ajaxClient.RunCommand('Profile', 'RemoveProductFromObject', 
									{'productID': this.productID, 'id': this.objectID, 'type': this.objectType}, 
									callback, object);
	},
	
	Save : function(callback, object)
	{
		this.ajaxClient.RunCommand('Profile', 'SaveProductToObject', 
									{'id': this.objectID, 'type': this.objectType, 'productID': this.productID}, 
									callback, object);
	}
	
});

var Task = Class.create({
	initialize : function(objID, objType, taskID, notes, assignedToID, assignedToName, assignedToEmail, assignedByName, createdOn, isCompleted, isEmailed, type)
	{
		this.objectID		 = objID;
		this.objectType 	 = objType;
		this.taskID			 = taskID;
		this.notes			 = notes;
		this.assignedToID	 = assignedToID;
		this.assignedToName	 = assignedToName;
		this.assignedToEmail = assignedToEmail;
		if(this.assignedToEmail != "")
		{
			this.validEmail = (this.assignedToEmail.search(/@/) != -1)?true:false;
		}	
		else
			this.validEmail = false;
		this.isEmailed 		 = isEmailed
		this.assignedByName  = assignedByName;
		this.createdOn		 = createdOn;
		this.isCompleted	 = isCompleted;
		this.ajaxClient 	 = new AjaxClient(); // we need fail callback
		this.NOTETEXT		 = 'Enter Task Desc..';
		this.inAssignToState = true;
		this.taskType 		 = type;
	},
	GetHtml : function()
	{
		if(this.taskType == 'Mine')
			return this._getHtmlAssigned_TO_Me();
		else
			return this._getHtmlAssigned_BY_Me()
		
	},
	_getHtmlAssigned_BY_Me : function()
	{
		var html = "<div id='objectTaskDiv_" + this.taskID + "'>";
		html 	+= "<div class='checkBox'>";
		html 	+= "<span style='padding-left:2px;float:left;' id='taskAssignedTo_"+this.taskID+"'>";
		if(this.assignedToID != -1)
			html += this.buildStaticBox();
		else
			html += "Loading...";
		html	+= "</span>";
		html	+= "<a style='float:right; margin-right:19px' title='Click to remove task' id='removeTaskButton_"+this.taskID+"' href='javascript:void(0)'>";
		html	+= "<img style='border:none' src='/images/myeiatrack/grey-close-button.png'></img></a>";
		html 	+= "<div style='clear:both;'></div>";
		html 	+= "</div><div id='noteContainer_"+this.taskID+"'>";
		html	+= "<div class='textBoxWrap'><span class='textBoxWrapInner'><textarea id='taskNotes_" + this.taskID + "' ";
		html	+= (this.isCompleted == 'Y')?" class='completed'> ":">";
		html    += (this.notes=='')?this.NOTETEXT:this.notes;
		html	+= "</textarea><div id='taskAction_"+ this.taskID +"' class='actionBottom' >";
		html	+= "<a id='taskEmail_"+ this.taskID + "' class='email' href='javascript:void(0)' ";
		html	+= (this.assignedToEmail == "")?" style='display:none' ":"";
		html	+= (this.isCompleted == 'Y')?" style='display:none;border:none;'>":">";
		html	+= "<img id='taskEmailImage_"+ this.taskID +"' ";
		html	+= (this.isEmailed == 'Y')?" src='/images/myeiatrack/email-button-tick.gif' title='An email has been sent'":"src='/images/myeiatrack/email-button.gif' title='click to email recipient'";
		html	+= " style='none;'></img>";
		html	+= "</a><span id='taskCompletedTick_"+ this.taskID + "' title='This task has been completed by the recipient' ";
		html	+= (this.isCompleted != 'Y')?" style='display:none' ":"";
		html	+= ">Task Completed</span></div></span>";
		html	+= "</div><input type='button' class='button' title='Click to save note' value='Save'";
		html	+= " id='taskSaveButton_"+this.taskID+"' style='display:none'/></div></div>";
		html 	+= "</div>";
		return html;
	},
	_getHtmlAssigned_TO_Me : function()
	{

		var createDate = (this.createdOn.indexOf(' ') != -1)?this.createdOn.substring(0,this.createdOn.indexOf(' ')):this.createdOn;

		var html = "<div id='objectTaskDiv_" + this.taskID + "'>";
		html 	+= "<div class='checkBox blueCheckbox'>";
		html 	+= "<span id='taskAssignedFrom_"+this.taskID+"'>";
		html	+= "<div><font size=-2>From:</font> <b>"+this.assignedByName + "</b></div><font size=-2>";
		html	+= Calendar.printDate(Calendar.parseDate(createDate,false), "%b %d, %Y") + "</font></span></div>";

		html 	+= "<div id='noteContainer_"+this.taskID+"'>";
		html	+= "<div class='textBoxWrap'>";
		html	+= "<span class='textBoxWrapInner blueWrapInner'>";
		html	+= "<div id='taskNotes_" + this.taskID + "'";
						html	+= (this.isCompleted == 'Y')?" class='completed'> ":">";
						html    += (this.notes=='')?"No Description Provided":this.notes;
		html	+= "</div>";
		html	+= "<div id='taskAction_"+ this.taskID +"' class='actionBottom'>"
						html	+= "<input type='checkbox' id='completeTaskButton_"+this.taskID+"' ";
						html	+= (this.isCompleted == 'Y')?" checked ":"";
						html	+= "/><label for='completeTaskButton_"+this.taskID+"'>Done</label>";
		html	+= "</div>";
		html	+= "</span>";
		html	+= "</div>";
		html	+= "</div>";
		
		return html;
	},
		
	DidRender: function (callback)
	{
		if(this.taskType != 'Mine')
			this._didRenderMine(callback);
		else
			this._didRenderCompany(callback);
	},
	
	_didRenderMine : function(callback)
	{
		$('removeTaskButton_'+this.taskID).observe('click', function(event){
			this.Delete(callback,undefined);
		}.bind(this));
		
		this.wireUpStaticBox();
		
		$("taskNotes_" + this.taskID).observe('focus', function(event)
		{
			if(this.isCompleted == 'Y')
			{
				if(!this.confirmAbandonCompleted())
				{
					$('removeTaskButton_'+this.taskID).focus();
					return;
				}
			}
			$("taskSaveButton_" + this.taskID).value = 'Save';
			specialShowSaveButton("taskSaveButton_" + this.taskID);
			if ($F(event.element()) == this.NOTETEXT)
			{
				$(event.element()).value = '';
			}
		}.bind(this));

		$("taskSaveButton_" + this.taskID).observe('click', function(event)
		{
			var val = $("taskSaveButton_" + this.taskID).value;
			if(val == 'Assign')
				this.onChangeSelector(event);
			else
			{
				this.Update();
				specialHideSaveButton("taskSaveButton_" + this.taskID);
			}
		}.bind(this));
		
		$("taskNotes_" + this.taskID).observe('blur', function(event)
		{
			if ($F(event.element()) == '')
			{
				$(event.element()).value = this.NOTETEXT;
				this.notes = "";
			}
			else
			{
				this.notes = $F(event.element().id);
			}
			this.Update();
		}.bind(this));
		
		$("taskEmail_" + this.taskID).observe('click', function(event)
		{
			// fire up the popup
			var popup = new EmailTaskPopup(this.assignedToName,this.isEmailed,
						window.location.toString(),this.onSendEmail.bind(this));
			// show the popup
			popup.render(event);
		}.bind(this));
		
	},
	onSendEmail : function(callback)
	{
		// email has been sent so update the icon for the image
		this.ajaxClient.RunCommand('Task', 'SendTaskEmail', 
									{'id': this.objectID, 'type': this.objectType, 'taskID': this.taskID }, 
		function(result)
		{
			// update the image of the email
			this.isEmailed = 'Y';
			$('taskEmailImage_'+this.taskID).src = "/images/myeiatrack/email-button-tick.gif";
			$('taskEmailImage_'+this.taskID).title = 'An email has been sent';

			// Success
			callback(true);
		}.bind(this),
		
		function(error, ob)
		{
			// for debugging only
			//alert(error);
			// Failure
			alert('Sending email failed. Please try again later');
			callback(false)
		}.bind(this),true);
	},
	_didRenderCompany: function(callback)
	{
		$('completeTaskButton_'+this.taskID).observe('click', function(event){
			var element = event.element();
			if(element.checked)
				this.toggleDoneUndo('Done');
			else
				this.toggleDoneUndo('Undo');
		}.bind(this));
		
	},	
	toggleDoneUndo : function(type)
	{
		if(type == 'Done')
		{
			this.isCompleted = 'Y'
			$("taskNotes_" + this.taskID).addClassName('completed');
		}
		else
		{
			this.isCompleted = 'N';
			$("taskNotes_" + this.taskID).removeClassName('completed');
		}
		this.Update();
	},
	EditAssignedTo : function()
	{
		// get a list of the current users in the system
		this.toggleEditAssigned(true);
		this.ajaxClient.RunCommand('Profile', 'GetUsersInCompany', {}, function(results)
		{
			
			// loop through users and load into select
			var html = "";
			html += "<select style='width:115px' id='taskAssignedSelector_"+this.taskID+"' name='taskAssignedSelector_"+this.taskID+"'>";
			html += "<option value=''>(assign task)</option>";
			html += "<option value=''>--------------</option>";
			
			// loop through
			$A(results.userList).each(function(user)
			{
				var combined = user.ID;
				if(Timmer(user.Email) != "" && user.Email.indexOf("@") != -1)
					combined += "^";
					
				// skip people without names
				if(Timmer(user.Name) == "")
					return;
					
				html += "<option value='"+combined+"' title='"+user.Name+"' ";
				if(user.ID == this.assignedToID)
					html += " selected ";
				html += ">"+shorten(user.Name,20)+"</option>";
			}.bind(this));
			
			//html += "<input id='taskAssignButton_"+this.taskID+"' type='button' value='Assign'/>";
			
			$("taskAssignedTo_"+this.taskID).update();
			$("taskAssignedTo_"+this.taskID).update(html);
			$("taskAssignedSelector_"+this.taskID).focus();
			
		}.bind(this),undefined,true);
		
	},
	onChangeSelector : function(event)
	{
		// get the selected item
		var selector = $("taskAssignedSelector_"+this.taskID);
		var selected_UserID = selector.options[selector.selectedIndex].value;
		var selected_ValidEmail = false;
		if(selected_UserID.search(/\^$/i) != -1)
		{
			selected_UserID = selected_UserID.replace(/\^$/,"");
			selected_ValidEmail = true;
		}
		var selected_UserName = selector.options[selector.selectedIndex].text;
		if(selected_UserID != '')
		{
			if(selected_UserID != this.assignedToID)
			{
				this.assignedToID = selected_UserID;
				this.assignedToName = selected_UserName;
				this.validEmail = selected_ValidEmail;
				this.isEmailed = 'N';
			}
			$("taskAssignedTo_"+this.taskID).update();
			$("taskAssignedTo_"+this.taskID).update(this.buildStaticBox());
			this.wireUpStaticBox();
			this.Update();
			this.toggleEditAssigned(false);
			//$("taskNotes_" + this.taskID).focus();
		}		
	},
	buildStaticBox : function()
	{
		var html = "<font size=-2>To:</font> <input id='staticAssignedTo_"+ this.taskID + 
			"' type='text' class='text' title='Click to re-assign task' value=\""+shorten(this.assignedToName,20)+"\" />";
		return html;
	},
	wireUpStaticBox : function()
	{
		if($("staticAssignedTo_"+this.taskID) != undefined)
		{
			$("staticAssignedTo_"+this.taskID).observe('click', function(event){
				if(this.isCompleted == 'Y')
				{
					if(this.confirmAbandonCompleted())
						this.EditAssignedTo();
					else
						$('removeTaskButton_'+this.taskID).focus();
					
				}
				else
					this.EditAssignedTo();
			}.bind(this));
		}
	},
	confirmAbandonCompleted : function()
	{
		var result = false;
		if(confirm('This task has been completed, this action\nwill clear the completed status. Continue?'))
		{
			this.isCompleted = 'N';
			$("taskCompletedTick_"+ this.taskID).hide();
			$("taskNotes_" + this.taskID).removeClassName('completed');
			$("taskEmail_"+ this.taskID).show();
			result = true;
		}
		return result;
	},
	toggleEditAssigned : function(turnOn)
	{
		if(turnOn)
		{
			this.inAssignToState = true;
			// disable everything
			$('taskNotes_'+this.taskID).hide();
			$('taskAction_'+this.taskID).hide();
			$("taskSaveButton_" + this.taskID).value = 'Assign';
			$("taskSaveButton_" + this.taskID).setStyle({bottom: '0px', marginBottom : '10px'});
			specialShowSaveButton("taskSaveButton_" + this.taskID);
		}
		else
		{
			this.inAssignToState = true;
		    $('taskNotes_'+this.taskID).show();
			$('taskAction_'+this.taskID).show();
			if(this.validEmail)
				$('taskEmail_'+this.taskID).show();
			else
				$('taskEmail_'+this.taskID).hide();
			
			// reset email
			if(this.isEmailed == 'N')
			{
				$('taskEmailImage_'+this.taskID).src = "/images/myeiatrack/email-button.gif";
				$('taskEmailImage_'+this.taskID).title = 'click to email recipient';
			}
			
			specialHideSaveButton("taskSaveButton_" + this.taskID);
			//$('taskNotesStatic_'+this.taskID).hide();
			$("taskSaveButton_" + this.taskID).setStyle({bottom: '12px'});
		}
	},
	Delete : function(callback, object)
	{
		if($("taskAssignedSelector_"+this.taskID) != undefined)
			$("taskAssignedSelector_"+this.taskID).stopObserving();
		$('removeTaskButton_'+this.taskID).stopObserving();
		$('objectTaskDiv_'+this.taskID).remove();
		
		this.ajaxClient.RunCommand('Profile', 'RemoveTask', 
									{'taskID': this.taskID}, 
									callback, null,true);
	},
	Save : function(callback, object)
	{
		this.ajaxClient.RunCommand('Profile', 'SaveTask', 
									{'id': this.objectID, 'type': this.objectType,  
									'assignedTo': this.assignedToID, 'notes' : this.notes }, 
									callback, null, true);
	},
	Update: function(callback, object)
	{
		this.ajaxClient.RunCommand('Profile', 'UpdateTask', 
									{'taskID': this.taskID, 'notes': this.notes, 'assignedTo' : this.assignedToID,
									'isCompleted': this.isCompleted, 'isEmailed': this.isEmailed }, 
									callback, null, true);
	}
});

var CalendarDate = Class.create({
	initialize : function(objID, objType, id, date, notes, reminder)
	{
		this.objectID		= objID;
		this.objectType 	= objType;
		this.dateID 		= (id) ? id : 0;
		this.theDate 		= (date) ? date : '';
		this.notes			= (notes) ? notes : '';
		this.saved			= false;
		this.dateFormatter 	= new DateFormatter("DD-MON-YYYY"); // ONLY Supports DD-MON-YYYY for now
		this.ajaxClient 	= new AJAX_Client();

		var dater = new DateUtilities();
		if(!reminder)
			reminder = {};
		this.reminder		= 
		{	
			'enabled' : (reminder.enabled)?reminder.enabled:'No',
			'gap' : (reminder.gap)?reminder.gap:'Week',
			'custom' : (reminder.custom)?reminder.custom:dater.jumpTo(-7)
		};
	},
	
	GetHtml : function()
	{
		var html = "<div id='calendarDateDiv_" + this.dateID + "' class='calendarDateContainer'>";
		html 	+= "<div class='checkBox'>";
		// The date selector.
		html 	+= "<input type='text' class='text' title='Click to modify date...' value='" + Calendar.printDate(Calendar.parseDate(this.theDate,false), "%b, %d %Y");
		html    += "' id='calendarDateValue_" + this.dateID + "' style='float:left;margin-top:3px;'>";
		//Delete button.
		html	+= "<img src='/images/myeiatrack/grey-close-button.png' id='removeDateButton_"+this.dateID+"' style='float:right;margin-right:19px;margin-top:1px;cursor:pointer;'>";
		//html	+= "<img src='/images/myeiatrack/close_16x16.gif' id='removeDateButton_"+this.dateID+"' style='float:right;margin-right:19px;margin-top:1px;cursor:pointer;'>";
		html	+= "</div>";
		// The text box.
		html 	+= "<span class='textBoxWrapInner'><div class='textBoxWrap' style='background:none !important;'><textarea id='calendarDateNotes_" + this.dateID + "'>";
		html    += (this.notes=='')?DEFAULT_ENTER_TEXT:this.notes;
		html	+= "</textarea>";
		// Alarm button.
		html	+= "<a href='javascript:void(0);' id='calendarReminder_"+this.dateID+"'>";
		html	+= "<img style='border:none;margin-right:16px;padding-bottom:18px;float:right;' id='calendarReminderImg_" + this.dateID + "' ";
		if(this.reminder.enabled == 'Yes')
			html	+= "src='/images/myeiatrack/alarm-clock-small.png' title='Reminder is On'";
		else
			html	+= "src='/images/myeiatrack/alarm-clock-small-off.png' title='Reminder is Off'";
		html	+= " /></a>";
		html	+= "</div></span>";
		// Save button.
		html	+= "<input id='calendarDateSave_"+this.dateID+"' type='button' ";
		html	+= "style='display:none' class='button' title='Click to save note' value='Save'/></div>";
		
		return html;
	},
	
	DidRender: function (callback)
	{
		$('removeDateButton_'+this.dateID).observe('click', function(event){
			var buttonID = event.target.id;
			var dateID = buttonID.substr(buttonID.indexOf('_') + 1);
			callback(dateID);
		}.bind(this));
		
		var self = this;
		
		// new calendar control
		Calendar.setup({ 
			dateFormat: "%b, %d %Y",
			inputField: 'calendarDateValue_' + this.dateID, 
			trigger: 	'calendarDateValue_' + this.dateID,
			onSelect: function(){
				self.theDate = Calendar.printDate(Calendar.parseDate($F('calendarDateValue_' + self.dateID),false), "%d-%b-%Y")
				// self.theDate = $F('calendarDateValue_' + self.dateID);
				self.Update();
				this.hide();
			}
		});
			
		$('calendarDateNotes_'+ this.dateID).observe('focus', function(event){
			specialShowSaveButton("calendarDateSave_" + this.dateID);
			if ($F('calendarDateNotes_'+ this.dateID) == DEFAULT_ENTER_TEXT)
			{
				$('calendarDateNotes_'+ this.dateID).value = '';
			}
		}.bind(this));
		$('calendarDateNotes_'+ this.dateID).observe('blur', function(event){
			if ($F('calendarDateNotes_'+ this.dateID) == '')
			{
				$('calendarDateNotes_'+ this.dateID).value = DEFAULT_ENTER_TEXT;
			}
		}.bind(this));
		
		$('calendarDateNotes_'+ this.dateID).observe('change', function(event){
			this.notes = $F(event.target.id);
			this.Update();
		}.bind(this));
		
		$("calendarDateSave_"+this.dateID).observe('click', function(event){
			this.notes = $F('calendarDateNotes_'+this.dateID);
			this.Update();
			specialHideSaveButton("calendarDateSave_" + this.dateID);
		}.bind(this));
		
		// click the reminder button
		$("calendarReminder_"+this.dateID).observe('click', function(event){
			// fire up the popup
			var popup = new ReminderPopup(this.theDate,Object.clone(this.reminder),this.OnReminderSave.bind(this));
			// show the popup
			popup.render(event);
		}.bind(this));
		
	},
	OnReminderSave : function(reminder)
	{
		this.reminder = reminder;
		if(this.reminder.enabled == 'Yes')
		{
			$('calendarReminderImg_'+this.dateID).src = '/images/myeiatrack/alarm-clock-small.png';
			$('calendarReminderImg_'+this.dateID).title = 'Reminder is On';
		}
		else
		{
			$('calendarReminderImg_'+this.dateID).src = '/images/myeiatrack/alarm-clock-small-off.png';
			$('calendarReminderImg_'+this.dateID).title = 'Reminder is Off';
		}
		this.Update();
	},
	Delete : function(callback, object)
	{
		$('removeDateButton_'+this.dateID).stopObserving();
		this.ajaxClient.RunCommand('Profile', 'RemoveFromCalendar', 
									{'dateID': this.dateID}, 
									callback, object);
	},
	
	Save : function(callback, object)
	{
		this.ajaxClient.RunCommand('Profile', 'SaveToCalendar', 
									{'id': this.objectID, 'type': this.objectType, 'date': NiceDateOnly(), 'notes': ''}, 
									callback, object);
	},
	
	Update: function(callback, object)
	{
		this.ajaxClient.RunCommand('Profile', 'UpdateCalendar', 
									{'dateID': this.dateID, 'date': this.theDate, 'notes': this.notes,
									'reminder': $H(this.reminder).toJSON() }, 
									callback, object);
	}
	
});

var AjaxUtilities = {
	RemoveRecordAndRow : function(rowID, p, c, f) {
		var ajaxClient = new AJAX_Client();
		
		if (confirm('Are you sure you want to delete this?')) {
			ajaxClient.RunCommand(c, f, p, function() {
				$(rowID).remove();
			}, null);
		}
	}
};

var DateFormatter = Class.create({
	initialize : function()
	{
		// TODO - make this more flexible - currently only outputs with format DD-MON-YYYY
		this._monthMap = {0: "Jan", 1: "Feb", 2: "Mar", 3: "Apr", 4: "May", 5: "Jun", 6: "Jul", 7: "Aug", 8: "Sep", 9: "Oct", 10: "Nov", 11: "Dec"};
	},
	Format : function(theDate)
	{
		// TODO - make this deal with dates not just in the format YYYY-MM-DD
		var dateParts = theDate.split('-');
		var year = dateParts[0];
		var month = parseInt(dateParts[1]);
		var day = parseInt(dateParts[2]);
		
		// Now format it - hard coded for now
		var result = day + "-" + this._monthMap[month-1] + "-" + year;
				
		return result;
	}
});

var DateUtilities = Class.create({
	initialize : function()
	{
		// TODO - make this more flexible - currently only outputs with format DD-MON-YYYY
		this._monthMap = {0: "Jan", 1: "Feb", 2: "Mar", 3: "Apr", 4: "May", 5: "Jun", 6: "Jul", 7: "Aug", 8: "Sep", 9: "Oct", 10: "Nov", 11: "Dec"};
	},
	Today : function()
	{
		var date = new Date();
		var day = date.getDate();

		var theDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + day;
		
		return theDate;
	},
	jumpTo : function(days, from, format)
	{
		var d = new Date();
		var start = (from)?from:d.getTime();
		var f = (format)?format:"%Y-%m-%d";
		d.setTime(start+days*86400000);
		return Calendar.printDate(d,f);
	}
});

function NiceDate()
{
	var time = NiceTime() + " " + NiceDateOnly();
	
	return time;
}

function NiceDateOnly()
{
	var monthMap = {
		0: "Jan", 1: "Feb", 2: "Mar", 3: "Apr", 4: "May", 5: "Jun", 6: "Jul", 7: "Aug", 8: "Sep", 9: "Oct", 10: "Nov", 11: "Dec"
	};
	
	var date = new Date();
	var day = date.getDate();
	
	var theDate = day + "-" + monthMap[date.getMonth()] + "-" + date.getFullYear();
	
	return theDate;
}

function NiceTime()
{
	var date = new Date();
	var hours = date.getHours();
	var amPm = (hours > 12) ? 'PM' : 'AM';	
	hours = (hours > 12) ? hours - 12 : hours;
	var mins = date.getMinutes();
	mins = (mins < 10) ? "0" + mins : mins;
	
	var time = hours + ":" + mins + " " + amPm;
	
	return time;
}

function Timmer(str)
{
	return str.replace(/^\s*([\S\s]*?)\s*$/, '$1');
}

var ReminderPopup = Class.create({
	initialize : function(theDate,reminderOb,saveCallback)
	{
		this.theDate = (theDate)?theDate:Date();
		this.popupDiv = $('calendarReminderPopup');
		this.onSaveCallback = saveCallback;
		this.reminderOb = reminderOb;
		
		// init the box
		FancyZoomBox.init();
		
		FancyZoomBox.callbackEnd = function(){
			if($('zoom_content') != undefined)
				$('zoom_content').removeClassName('reminder_pop_out');
		}
		
	},
	render : function(event)
	{
		FancyZoomBox.showImmediate(this.popupDiv,340,190,event.pointerX(), event.pointerY(), this.onPopupRendered.bind(this));
	},
	refreshUI : function()
	{
		if($('calendarReminderEnabled').checked)
		{
			$('calendarReminderContent1').hide();
			$('calendarReminderContent2').show();
		}
		else
		{
			$('calendarReminderContent2').hide();
			$('calendarReminderContent1').show();
		}
			
		if(this.reminderOb.gap == 'Custom')
		{
			$('calendarReminderCustomContainer').show();
			$('calendarReminderInAdvance').hide();
		}
		else
		{
			$('calendarReminderCustomContainer').hide();
			$('calendarReminderInAdvance').show();
		}
	},
	onPopupRendered : function()
	{
		// is it enabled
		$('calendarReminderEnabled').checked = (this.reminderOb.enabled == 'Yes')?true:false;
			
		// setup calendarReminderList
		var reminderList = $('calendarReminderList');
		var found = false;
		for(var counter=0; counter < reminderList.options.length; counter++ )
		{
			if(reminderList.options[counter].value == this.reminderOb.gap)
			{
				found = true;
				break;
			}
		}
		reminderList.selectedIndex = (found)?counter:0;
		var customDate = Calendar.parseDate(this.reminderOb.custom,false);
		var theDate = Calendar.parseDate(this.theDate,false);
		if(Calendar.dateToInt(customDate) > Calendar.dateToInt(theDate))
			this.reminderOb.custom = this.theDate;
			
		$('calendarReminderCustom').value = Calendar.printDate(Calendar.parseDate(this.reminderOb.custom,false), "%b, %d %Y")
					
		// wire up event handlers
		$('calendarReminderEnabled').observe('click', function(event){
			this.reminderOb.enabled = ($F('calendarReminderEnabled'))?'Yes':'No';
			this.refreshUI();
		}.bind(this));

		$('calendarReminderList').observe('change', function(event){
			// get the selected item
			if($('calendarReminderList').selectedIndex != -1)
			{
				this.reminderOb.gap = $('calendarReminderList').options[$('calendarReminderList').selectedIndex].value;
				var dateUtil = new DateUtilities();
				switch(this.reminderOb.gap)
				{
					case "Day":
						this.reminderOb.custom = dateUtil.jumpTo(-1,theDate.getTime(),"%d-%b-%Y");
						$('calendarReminderCustom').value = Calendar.printDate(Calendar.parseDate(this.reminderOb.custom,false),"%b, %d %Y");
						break;
					case "Week":
						this.reminderOb.custom = dateUtil.jumpTo(-7,theDate.getTime(),"%d-%b-%Y");
						$('calendarReminderCustom').value = Calendar.printDate(Calendar.parseDate(this.reminderOb.custom,false),"%b, %d %Y");
						break;
					case "Month":
						this.reminderOb.custom = dateUtil.jumpTo(-30,theDate.getTime(),"%d-%b-%Y");
						$('calendarReminderCustom').value = Calendar.printDate(Calendar.parseDate(this.reminderOb.custom,false),"%b, %d %Y");
						break;
					default:
						break;
				}
			}
			else
				this.reminderOb.gap = '';
			this.refreshUI();
		}.bind(this));
		
		var self = this;
		Calendar.setup({ 
			dateFormat: "%b, %d %Y",
			inputField: 'calendarReminderCustom', 
			trigger: 	'calendarReminderCustom',
			max: Calendar.dateToInt(Calendar.parseDate(this.theDate,false)),
			onSelect: function(){
				self.reminderOb.custom = Calendar.printDate(Calendar.parseDate($F('calendarReminderCustom'),false),"%d-%b-%Y");
				this.hide();
			}
		});
		
		// on save
		$('calendarReminderSave').observe('click',function(event)
		{
			// call back to parent
			this.onSaveCallback(this.reminderOb);
			FancyZoomBox.hide(event);
		}.bind(this));
		
		// close
		$('calendarReminderCancel').observe('click',function(event){ FancyZoomBox.hide(event);});
		
		$('zoom_content').addClassName('reminder_pop_out');
		
		this.refreshUI();
	}
});

var EmailTaskPopup = Class.create({
	initialize : function(toName, isEmailed, url, callback)
	{
		this.popupDiv = $('taskEmailPopup');
		this.toName = toName;
		this.isEmailed = isEmailed;
		this.url = url.substring(0,url.indexOf('&'));
		this.onSendCallback = callback;

		// init the box
		FancyZoomBox.init();
		FancyZoomBox.callbackEnd = function(){
			if($('zoom_content') != undefined)
				$('zoom_content').removeClassName('email_pop_out');
		}
	},
	render : function(event)
	{
		$('taskSendButton').show();
		$('taskEmailSpinner').hide();
		FancyZoomBox.showImmediate(this.popupDiv,320,140,event.pointerX(), event.pointerY(), this.onPopupRendered.bind(this));
	},
	onPopupRendered : function()
	{
		// set vars
		//$('taskEmailPopup_Email').update(this.toEmail);
		$('taskEmailPopup_To').update(this.toName);
		if(this.isEmailed == 'Y')
			$('taskEmailSend').value = 'Resend';
		else
			$('taskEmailSend').value = 'Send';
		
		// wire up the events
		$('taskEmailSend').observe('click', function(event)
		{
			event.stop();
			$('taskSendButton').hide();
			$('taskEmailSpinner').show();
			// show the spinner
			this.onSendCallback(function(result)
			{
				// had to take out passing in the event as it was lost
				FancyZoomBox.hide();
		 	}.bind(this));
		
		}.bind(this));
		
		$('taskEmailCancel').observe('click', function(event)
		{
			FancyZoomBox.hide(event);
		}.bind(this));
		
		$('zoom_content').addClassName('email_pop_out');
	}
});


