/**
* @fileoverview This file contains the static object ItemEditTab. 
* @author Sara Lin
* @version 0.1
*/

/**
* @namespace The ItemEditTab contains functionalities needed to edit properties of the item.
*/
var ItemEditTab = {
	/**  the current item object in the item tab */
	item: null,
	/** the currently active page, can be general information, predefined lists, or photos */
	activePage: null,
	/** the tab object item uses */
	tab: null,
	/** the item edit tab content */
	tabContent: null,

	/** Triggered by clicking on the edit button. Turn the item tab to item edit tab with the currently selected item information. 
	* @constructor
	* @param {object} item The item to be edited.
	*/
	load: function(item) {
		this.activePage = null;
		this.item = item;
		this.tab = Main.tabs.getTab('item');
		
		if (this.tab != null) {
			var thisObj = this;
			var url = encodeURL(base_url+'itemEdit/load', item.id);
			
			//get item edit tab content from controller/itemEdit/load/itemID
			new Ajax.Request(url, {
				onSuccess: function(response) {
					thisObj.tabContent = response.responseText;
					thisObj.tab.tabElem.innerHTML = response.responseText;
					thisObj.tabContent = thisObj.tab.tabElem;
					
					//observe page link events
					thisObj.observePageLinks();
					thisObj.loadGeneralEditPage(item.id, thisObj);
				}
			});
		}	
	},
	
	/** Either user clicks to turn off the item edit mode or user logs off.  Turn the item edit tab back to item tab. */
	unload: function() {
		if (this.tabContent != null) {
			//unload all pages
			if (this.generalEditPage.body!=null)
				this.generalEditPage.unload();
			if (this.listsEditPage.body!=null)
				this.listsEditPage.unload();
			if (this.photosEditPage.body!=null)
				this.photosEditPage.unload();
				
			//unobserve page link events
			this.unobservePageLinks();
			
			//controller/itemEdit/unload/itemID
			this.item = null;
			this.activePage = null;
			this.tabContent = null;
		}
	},

	/** attach event handlers to page links (generalEditLink and listEditLink). */
	observePageLinks: function() {
		if ($('generalEditLink'))
			Event.observe('generalEditLink', 'click', ItemEditTab.loadGeneralEditPage);
		if ($('listEditLink'))
			Event.observe('listEditLink', 'click', ItemEditTab.loadListsPage);
		if ($('photosEditLink'))
			Event.observe('photosEditLink', 'click', ItemEditTab.loadPhotosPage);
		Event.observe('edit-view', 'click', ItemTab.editTab);
		Event.observe('deleteItemLink', 'click', ItemEditTab.deleteItem);
	},
	
	/** dettach event handlers to page links (generalEditLink and listEditLink). */
	unobservePageLinks: function() {
		if ($('generalEditLink'))
			Event.stopObserving('generalEditLink', 'click', ItemEditTab.loadGeneralEditPage);
		if ($('listEditLink'))
			Event.stopObserving('listEditLink', 'click', ItemEditTab.loadListsPage);
		if ($('photosEditLink'))
			Event.stopObserving('photosEditLink', 'click', ItemEditTab.loadPhotosPage);
		Event.stopObserving('edit-view', 'click', ItemTab.editTab);
	},
	
	/**
	* delete the currently selected item.  prompts the administrator to confirm and reloads the map and close the tab.
	* @event
	*/
	deleteItem: function() {
		if (!confirm("Delete this item?"))
			return;
			
		var url = base_url+'itemEdit/delItem/'+ItemEditTab.item.id;
		new Ajax.Request(url, {
			onSuccess: function(response) {
				var floor = FloorManager.getCurrentFloor();
				if (floor) {
					floor.uploadFloor();
					Main.tabs._closeButton();
				}
			}
		});
	},
	
	/** 
	* load contents for the genearl edit page while hiding all others.  
	* @event
	*/
	loadGeneralEditPage: function(event) {
		if (ItemEditTab.generalEditPage.body == null)
			ItemEditTab.generalEditPage.load(ItemEditTab.item.id, ItemEditTab.switchPage, ItemEditTab.generalEditPage);
		else {
			ItemEditTab.switchPage(ItemEditTab.generalEditPage);
		}
	},
	
	/** 
	* load contents for the lists edit page while hiding all others.  
	* @event
	*/
	loadListsPage: function(event) {
		if (ItemEditTab.listsEditPage.body == null) {
			ItemEditTab.listsEditPage.load(ItemEditTab.item.id, ItemEditTab.switchPage, ItemEditTab.listsEditPage);
		}
		else {
			ItemEditTab.switchPage(ItemEditTab.listsEditPage);
		}
	},
	
	/** 
	* load contents for the photos edit page while hiding all others.  
	* @event
	*/
	loadPhotosPage: function(event) {
		if (ItemEditTab.photosEditPage.body == null) {
			ItemEditTab.photosEditPage.load(ItemEditTab.item.id, ItemEditTab.switchPage, ItemEditTab.photosEditPage);
		}
		else {
			ItemEditTab.switchPage(ItemEditTab.photosEditPage);
		}
	},
	
	/** hide all other pages; show the selected page 
	* @param {object} selectedPage
	*/
	switchPage: function(selectedPage) {
		if (ItemEditTab.activePage != null) {
			ItemEditTab.activePage.body.hide();
			ItemEditTab.activePage.link.className = '';
		}
		$(selectedPage.body).show();
		selectedPage.link.className = 'active';
		ItemEditTab.activePage = selectedPage;
	}
}

/**
* @namespace A collection of functions for editing the item's general properties.
*/
ItemEditTab.generalEditPage = {
	/** current page's link element */
	link: null,
	/** current page's content element */
	body: null,
	/** element that contains the status information of the form.  It is set to display:none by default, can be used to show error messages etc. */
	status: null,
	/** reset/cancel button for the edit form */
	resetBtn: null,
	/** the original name of the item, used to check whether the item name is changed.  If it is changed, then reload the map */
	originalItemName: null,
	
	/**
	* loads the edit form
	* @constructor
	* @param {number} itemID The id of the item.
	* @param {function} funCallBack Function set to be called after the page is loaded.
	* @param {object} funParams Parameter(s) for the funCallBack function.
	*/
	load: function(itemID, funCallBack, funParams) {
		if (this.body == null) {
			var thisObj = this;
			var url = encodeURL(base_url+'itemEdit/generalEditPage', itemID);

			new Ajax.Request(url, {
				onSuccess: function(response) {
					thisObj.body = response.responseText;
					new Insertion.Bottom($('itemEditContent'), response.responseText);
					thisObj.body = $('generalEditPage');
					thisObj.resetBtn = $$('#generalEditForm .cancel')[0];
					thisObj.status = $$('#generalEditForm .status')[0];
					thisObj.link = $('generalEditLink');
					thisObj.originalItemName = $('generalEditForm').getInputs('text', 'name')[0].value;
					
					thisObj.observeEvents();
					
					if (funCallBack)
						funCallBack(funParams);
				}
			});
		}
	},
	
	/** unload the page */
	unload: function() {
		if (ItemEditTab.generalEditPage.body != null) {
			this.unobserveEvents();
			$('itemEditContent').removeChild($('generalEditPage'));
			ItemEditTab.generalEditPage.body = null;
		}
	},
	
	/** attach the submit and reset/cancel event handlers to the edit form */
	observeEvents: function() {
		Event.observe('generalEditForm', 'submit', this.submit);
		Event.observe(this.resetBtn, 'click', this.reset);
	},
	
	/** dettach the submit and reset/cancel event handlers to the edit form */
	unobserveEvents: function() {
		Event.stopObserving('generalEditForm', 'submit', this.submit);
		Event.stopObserving(this.resetBtn, 'click', this.reset);
	},
	
	/** submit the edit form and show status
	* @event
	*/
	submit: function(event) {
		var element = Event.element(event).serialize(true);

		new Ajax.Request(base_url+'itemEdit/generalEditPage_Submit/', {
			method: 'post',
  		parameters: element,
  		onSuccess: function(response) {	
				var result = response.responseText.evalJSON();
				ItemEditTab.generalEditPage.status.innerHTML = result.status;
				ItemEditTab.generalEditPage.status.show();
				
				if (result.success==true && element.name!=ItemEditTab.generalEditPage.originalItemName) {
					var floor = FloorManager.getCurrentFloor();
					ItemEditTab.item.setName(element.name);
					floor.uploadFloor();
					ItemEditTab.tab.labelElem.firstChild.innerHTML = '<span>'+element.name+'</span>';
					ItemEditTab.generalEditPage.originalItemName = element.name;
				}
			}	
  	});
	},
	
	/** reset the edit form
	* @event
	*/
	reset: function(event) {
		var input = $('generalEditForm')['itemID'];
		var itemID = $F(input);
		ItemEditTab.generalEditPage.unload(itemID);
		ItemEditTab.generalEditPage.load(itemID, ItemEditTab.switchPage, ItemEditTab.generalEditPage);
	}
}

/**
* @namespace A collection of functions for editing the item's list properties.
*/
ItemEditTab.listsEditPage = {
	/** current page's link element */
	link: null,
	/** current page's content element */
	body: null,
	/** element that contains the status information of the form.  It is set to display:none by default, can be used to show error messages etc. */
	status: null,
	/** currently selected list category */
	selectedValues: null,
	/** default selected value */
	defaultSelectedValues: null,
	/** default predefined item value for a selected list category */
	defaultPredefinedItemValues: null,
	
	/** 
	* load the edit list form
	* @constructor
	* @param {number} itemID the id of the item
	* @param {function} funCallBack Function set to be called after the page is loaded.
	* @param {object} funParams Parameter(s) for the funCallBack function.
	*/
	load: function(itemID, funCallBack, funParams) {
		if (this.body == null) {
			var thisObj = this;
			var url = encodeURL(base_url+'itemEdit/listEditPage', itemID);

			new Ajax.Request(url, {
				onSuccess: function(response) {
					new Insertion.Bottom($('itemEditContent'), response.responseText);
					thisObj.body = $('itemListEditPage');
					thisObj.status = $$('#listEditForm .status')[0];
					thisObj.link = $('listEditLink');
					thisObj.selectedValues = $$('#selectedListValues .value')[0];
					thisObj.defaultSelectedValues = thisObj.selectedValues;
					thisObj.defaultPredefinedItemValues = $('predefinedItemValues').innerHTML;
					
					Event.observe('predefinedItemLists', 'change', ItemEditTab.listsEditPage.listSelectOnchange);
					
					if (funCallBack)
						funCallBack(funParams);
				}
			});
		}
	},
		
	/** unload the page */
	unload: function() {
		if (ItemEditTab.listsEditPage.body != null) {
			this.unobserveEvents();
			$('itemEditContent').removeChild($('itemListEditPage'));
			ItemEditTab.listsEditPage.body = null;
		}
	},
	
	/** @ignore */
	observeEvents: function() {
	},
	
	/** @ignore */
	unobserveEvents: function() {
		Event.stopObserving('predefinedItemLists', 'change', ItemEditTab.listsEditPage.listSelectOnchange);
	},
	
	/**
	* Event handler for selecting a different list property.  The property's corresponding list values and the item's selected list values would be loaded.
	* @event
	*/
	listSelectOnchange: function(event) {
		var el = Event.element(event);
		el = $(el);
		var propName = el.getValue();
		
		if (el.options[el.selectedIndex].className!='empty') {
			var url = base_url+'itemEdit/listEditPage_Onchange';
			var queryArray = new Array(ItemEditTab.item.id,propName);
			url = encodeURL(url, queryArray);
			
			new Ajax.Request(url, {
				onSuccess: function(response) {
					$('predefinedItemValues').innerHTML = response.responseText;
					if ($('predefinedItemValues')) {
						var html = $('predefinedItemValues').innerHTML;
					}
					ItemEditTab.listsEditPage.loadSelectedListValues(propName);
					Event.observe($('listEditForm'), 'submit',ItemEditTab.listsEditPage.addListValue);
				}
			});
		} else {
			$('predefinedItemValues').innerHTML = this.defaultPredefinedItemValues;
			this.selectedValues.innerHTML = this.defaultSelectedValues;
		}
	},
	
	/**
	* add list values to the item, refresh the selected values list
	* @event
	*/
	addListValue: function(event) {
		var elements = Event.element(event).serialize(true);
		var addEl = $$('#predefinedItemValues select')[0];
		
		if (addEl.options[addEl.selectedIndex].className=='empty')
			alert("Please select a list value!");
		else {
			//add new value to the item list values
			var url = base_url+'itemEdit/listEditPage_AddValue';
			var queryArray = new Array(ItemEditTab.item.id,elements.predefinedItemLists,elements.predefinedItemValues);
			url = encodeURL(url, queryArray);
			
			new Ajax.Request(url, {
				onSuccess: function(response) {
					//refresh selected list values
					ItemEditTab.listsEditPage.loadSelectedListValues(elements.predefinedItemLists);
				}
			});
		}
	},
	
	/** 
	* load all the predefined list values of the property
	* @param {string} propName the name of the list porperty
	*/
	loadSelectedListValues: function(propName) {
		var url = base_url+'itemEdit/listEditPage_SelectedValues';
		var queryArray = new Array(ItemEditTab.item.id,propName);
		url = encodeURL(url, queryArray);

		new Ajax.Request(url, {
			onSuccess: function(response) {
				ItemEditTab.listsEditPage.selectedValues.innerHTML = response.responseText;
				//alert($('selectedListValues').innerHTML);
				$$('#selectedListValues .delete').each(function(el) {
					Event.observe($(el),'click',ItemEditTab.listsEditPage.deleteListValue);
				});
			}
		});
	},
	
	/** delete a selected value, refresh the selected values list
	* @event
	*/
	deleteListValue: function(event) {
		var propName = $F($('listEditForm')['predefinedItemLists']);
		var value = Event.element(event).parentNode.className;
		
		//add new value to the item list values
		var url = base_url+'itemEdit/listEditPage_DeleteValue';
		var queryArray = new Array(ItemEditTab.item.id,propName,value);
		url = encodeURL(url, queryArray);
		
		new Ajax.Request(url, {
			onSuccess: function(response) {
				//refresh selected list values
				ItemEditTab.listsEditPage.loadSelectedListValues(propName);
			}
		});
	}
}

/**
* @namespace A collection of functions for editing the item's photos, not implemented.
*/
ItemEditTab.photosEditPage = {
	/** current page's link element */
	link: null,
	/** current page's content element */
	body: null,
	/** photo add form */
	photoAddForm: null,
	/** container to display added photos */
	photosContainer: null,
	/** element that contains the status information of the form.  It is set to display:none by default, can be used to show error messages etc. */
	status: null,
	
	/** 
	* load the edit photo form
	* @constructor
	* @param {number} itemID the id of the item
	* @param {function} funCallBack Function set to be called after the page is loaded.
	* @param {object} funParams Parameter(s) for the funCallBack function.
	*/
	load: function(itemID, funCallBack, funParams) {
		if (this.body == null) {
			var thisObj = this;
			var url = encodeURL(base_url+'itemEdit/photosEditPage', itemID);

			new Ajax.Request(url, {
				onSuccess: function(response) {
					new Insertion.Bottom($('itemEditContent'), response.responseText);
					thisObj.body = $('photosEditPage');
					thisObj.status = $$('#photosEditForm .status')[0];
					thisObj.link = $('photosEditLink');
					thisObj.photoAddForm = $('photoAddForm');
					thisObj.observeEvents();
					
					if (funCallBack)
						funCallBack(funParams);
				}
			});
		}
	},
	
	/** unload the page */
	unload: function() {
		if (ItemEditTab.photosEditPage.body != null) {
			this.unobserveEvents();
			$('itemEditContent').removeChild($('photosEditPage'));
			ItemEditTab.photosEditPage.body = null;
		}
	},
	
	observeEvents: function() {
		Event.observe($('submitPhoto'), 'click', this.submit);
		Event.observe($('cancelPhoto'), 'click', this.reset);
		$$('#photosEditPage .delete').each(function(el) {
			Event.observe($(el), 'click', ItemEditTab.photosEditPage.deletePhoto);
		});
	},
	
	/** @ignore */
	unobserveEvents: function() {
		Event.stopObserving($('submitPhoto'), 'click', this.submit);
		Event.stopObserving($('cancelPhoto'), 'click', this.reset);
		$$('#photosEditPage .delete').each(function(el) {
			Event.stopObserving($(el), 'click', ItemEditTab.photosEditPage.deletePhoto);
		});
	},
	
	/** 
	* submit the edit form and show status
	* @event
	*/
	submit: function(event) {
		if ($('uploadPhoto').value.lastIndexOf(".jpg")==-1) {
			alert("Error: only .jpg file allowed!");
			return;
		}
		$('photoAddForm').submit();
		Form.reset($('photoAddForm'));
	},
	
	
	/** 
	* reset the edit form
	* @event
	*/
	reset: function(event) {
		Form.reset($('photoAddForm'));
	},
	
	/**
	* delete the selected photo
	* @event
	*/
	deletePhoto: function(event) {
		var element = Event.element(event);
		var photoID = element.id.split("_")[1];
		var url = encodeURL(base_url+'itemEdit/photosEditPage_Delete', photoID);
		var thisObj = this;
		
		new Ajax.Request(url, {
			onSuccess: function(response) {
				ItemEditTab.photosEditPage.refreshPhotos();
			}
		});
	},
	
	/**
	* refresh the add form and photos on the page
	*/
	refreshPhotos: function() {
		var url = encodeURL(base_url+'itemEdit/refreshPhotos', ItemEditTab.item.id);
		var thisObj = this;
		
		$$('#photosEditPage .delete').each(function(el) {
			Event.stopObserving($(el), 'click', ItemEditTab.photosEditPage.deletePhoto);
		});
		
		new Ajax.Request(url, {
			onSuccess: function(response) {
				$('photosEditList').innerHTML = response.responseText;
				$$('#photosEditPage .delete').each(function(el) {
					Event.observe($(el), 'click', ItemEditTab.photosEditPage.deletePhoto);
				});
			}
		});
	}
}