/**
* Methods and fields for making calls on IES services
*/

var ApplicationService = {
	
	CASE_TABS: 'caseTabs',
	DEC_SAVE: 'decSave',
	AR_SAVE: 'arSave',
	GENERATE: 'generate',
	CASE_SEARCH: 'caseSearch',
	
	handleEvent: function(event, context) {
		var element = Event.element(event);
		if (element.id.endsWith(Service.SCOPE_SEPARATOR + 'register')) {
			$('flashPanel').update("");
			Entity.create(ApplicationContext.REGISTER, EntityEA.entityName);
		}
	},
						
	/**
	* General success handler for services that are not returning XHTML, i.e. services without a widget
	*/
	success: function(xhrObject) {
		document.body.style.cursor = "";
		var gotError = false;
		var xmlObject = XML.getXMLObject(xhrObject);
		// Look for an error
		var root = xmlObject.getElementsByTagName('error')[0];
		var message = "";
		if (root != undefined) {
			gotError = true;
			message = root.getElementsByTagName('message')[0].firstChild.data;
			alert(message);			
			//return;
		} else {
			root = xmlObject.getElementsByTagName('success')[0];
			try {
				message = root.getElementsByTagName('message')[0].firstChild.data;
			} catch(err) {;};
		}

		var service = root.getElementsByTagName('service')[0].firstChild.data;
		switch(service) {
		
			// Application SERVICES
			default:
				break;
		}
		if (message.length > 0 && !gotError) {
			alert(message);
		}
	},

	contentSuccess: function(xhrObject) {
		
		document.body.style.cursor = "";
		var xmlObject = XML.getXMLObject(xhrObject);
		// Look for an error
		var error = xmlObject.getElementsByTagName('error')[0];
		if (error != undefined) {
			var message = error.getElementsByTagName('message')[0].firstChild.data;
			alert(message);
			return;
		}
		
//var string = (new XMLSerializer()).serializeToString(xmlObject);
//alert(string);

		var root = xmlObject.getElementsByTagName('success')[0];
		var service = root.getElementsByTagName('service')[0].firstChild.data;
	  var context = root.getElementsByTagName('context')[0].firstChild.data;
		var target = root.getElementsByTagName('target')[0].firstChild.data;
		var content = root.getElementsByTagName('content')[0].firstChild.data;
		var entity = root.getElementsByTagName('entity')[0].firstChild.data;
		
		$(target).update(content);

		switch (service) {
			case Service.VIEWER:
				switch (entity) {
					case EntityCase.entityName:
						switch (target) {
							case "cases-entityCase":
								// Initial click on the case list
								var entityID = root.getElementsByTagName('entityID')[0].firstChild.data;
								var buttonsTarget = context + Service.SCOPE_SEPARATOR + Service.BUTTONS + Service.SCOPE_SEPARATOR + entity;
								Service.buttons(buttonsTarget, context, Widget.VIEWER_BUTTONS, entity, entityID);
								
								var caseType = Entity.getEntityFieldValue(ApplicationContext.CASES, EntityCase.entityName, 'type');
								// Tabs are disabled by default in applicationEventHandler and enabled here after the viewer has loaded
								// ApplicationService.caseTabs('casesetup', context, ApplicationWidget.CASE_SETUP_TAB, entity, entityID);
								if (caseType == EntityCase.CASETYPE_BOTH || caseType == EntityCase.CASETYPE_DEC) {
									ApplicationService.decMenu('casedec-menu-editor-benchmarkcategories');
									ApplicationService.decContent('casedec-menu-editor-benchmarkcategories');
									document.getElementById('subtabs').tabber.tabEnable(1);
								} else {
									document.getElementById('subtabs').tabber.tabDisable(1);
								}
								if (caseType == EntityCase.CASETYPE_BOTH || caseType == EntityCase.CASETYPE_AR) {
									ApplicationService.arMenu('casear-menu-editor-introductoryquestions');
									ApplicationService.arContent('casear-menu-editor-introductoryquestions');
									document.getElementById('subtabs').tabber.tabEnable(2);
								} else {
									document.getElementById('subtabs').tabber.tabDisable(2);
								}
				
								ApplicationService.caseTabs('casegenerate', context, ApplicationWidget.CASE_GENERATE_TAB, entity, entityID);
								document.getElementById('subtabs').tabber.tabEnable(3);
								
								break;
								
							case "casear-content":
								ApplicationService.enableSortableList();

							  break;
						}
				}
				break;

			case Service.EDITOR_SAVE:
				switch (entity) {
					case EntityEA.entityName:
						switch (context) {
							case ApplicationContext.REGISTER:
							case ApplicationContext.REGISTERCONFIRM:
								// On successful registration or registration confirmation request, clear the buttons
								$(context + Service.SCOPE_SEPARATOR + Service.BUTTONS + Service.SCOPE_SEPARATOR + entity).update("");
								break;
						}
						break;
						
					case EntityCase.entityName:
						var dirtyID = dirty.getDirty(context);
						if (dirtyID > 0) dirty.remove(context);
						dirty.remove(context);
						EntityCase.list(context);
						EntityCase.view(context, entity, null, Entity.getEntityID(context, entity));
						break;
				}
				break;
				
			case ApplicationService.DEC_SAVE:
				// Redisplay menu after a successful save.  The 'casedec-menu-current' is a hidden field brought in by
				// the CaseDECMenuWidget
				ApplicationService.decMenu('casedec-menu-editor-' + $('casedec-menu-current').value);
				break;
				
			case ApplicationService.AR_SAVE:
				// Redisplay menu after a successful save.  The 'casear-menu-current' is a hidden field brought in by
				// the CaseARMenuWidget
				ApplicationService.arMenu('casear-menu-editor-' + $('casear-menu-current').value);
				ApplicationService.enableSortableList();
				break;
				
			case Service.EDITOR_DUPLICATE:
				dirty.remove(context);

				var entity = root.getElementsByTagName('entity')[0].firstChild.data;
				var entityID = root.getElementsByTagName('entityID')[0].firstChild.data;
				var selection = new Selection(entity, entityID);
				
				Entity.list(context, entity, 'EntityCase.view(\'' + context + '\',\'' + entity + '\',\'@id\')', selection, null);
				Entity.edit(context, entity, entityID);
				
				break;
				
			default:
				break;
		}
	},
	
	/**
	 * Make case tabs service request
	 */
	caseTabs: function(target, context, widget, entity, entityID, onSuccessFunction) {
		var pars = 'service=' + Service.VIEWER;
		pars += '&' + 'target=' + target;
		pars += '&' + 'context=' + context;
		pars += '&' + 'widget=' + widget;
		pars += '&' + 'entity=' + entity;
		if (entityID != undefined && entityID != null) pars += '&' + 'entityID=' + entityID;
		if (onSuccessFunction == undefined || onSuccessFunction == null) onSuccessFunction = 'ApplicationService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	},
	
	
	enableSortableList: function(){
		var dragsort = ToolMan.dragsort();
		var junkdrawer = ToolMan.junkdrawer();

   	 	dragsort.makeListSortable(dragsort, $("cases-casear-paybackrecommendations-list"),
			function(item) {
				// Limit to vertical dragging
				item.toolManDragGroup.verticalOnly();
			}
   		 );
	},
	
	decMenu: function(elementID) {
		var parts = elementID.split("-");
		var sectionID = parts[parts.length - 1];
		var entityID = Entity.getEntityID(ApplicationContext.CASES, EntityCase.entityName);
		
		var pars = 'service=' + Service.VIEWER;
		pars += '&' + 'target=casedec-menu';
		pars += '&' + 'context=' + ApplicationContext.CASES;
		pars += '&' + 'widget=' + ApplicationWidget.CASE_DEC_MENU;
		pars += '&' + 'entity=' + EntityCase.entityName;
		pars += '&' + 'section=' + sectionID;
		pars += '&' + 'entityID=' + entityID;

		var onSuccessFunction = 'ApplicationService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	},
	
	arMenu: function(elementID) {
		var parts = elementID.split("-");
		var sectionID = parts[parts.length - 1];
		var entityID = Entity.getEntityID(ApplicationContext.CASES, EntityCase.entityName);
		
		var pars = 'service=' + Service.VIEWER;
		pars += '&' + 'target=casear-menu';
		pars += '&' + 'context=' + ApplicationContext.CASES;
		pars += '&' + 'widget=' + ApplicationWidget.CASE_AR_MENU;
		pars += '&' + 'entity=' + EntityCase.entityName;
		pars += '&' + 'section=' + sectionID;
		pars += '&' + 'entityID=' + entityID;

		var onSuccessFunction = 'ApplicationService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	},
	
	decContent: function(elementID) {
		var parts = elementID.split("-");
		var sectionID = parts[parts.length - 1];
		var entityID = Entity.getEntityID(ApplicationContext.CASES, EntityCase.entityName);
		
		var pars = 'service=' + Service.VIEWER;
		pars += '&' + 'target=casedec-content';
		pars += '&' + 'context=' + ApplicationContext.CASES;
		pars += '&' + 'widget=' + ApplicationWidget.CASE_DEC_CONTENT;
		pars += '&' + 'entity=' + EntityCase.entityName;
		pars += '&' + 'section=' + sectionID;
		pars += '&' + 'entityID=' + entityID;

		var onSuccessFunction = 'ApplicationService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	},
	
	arContent: function(elementID) {
		var parts = elementID.split("-");
		var sectionID = parts[parts.length - 1];
		var entityID = Entity.getEntityID(ApplicationContext.CASES, EntityCase.entityName);
		
		var pars = 'service=' + Service.VIEWER;
		pars += '&' + 'target=casear-content';
		pars += '&' + 'context=' + ApplicationContext.CASES;
		pars += '&' + 'widget=' + ApplicationWidget.CASE_AR_CONTENT;
		pars += '&' + 'entity=' + EntityCase.entityName;
		pars += '&' + 'section=' + sectionID;
		pars += '&' + 'entityID=' + entityID;

		var onSuccessFunction = 'ApplicationService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	},
	
	decGenerate: function() {
		var entityID = Entity.getEntityID(ApplicationContext.CASES, EntityCase.entityName);
		var includeXML=false;
		if($('casegenerate-entityCase-dec-xml'))
			var includeXML = $('casegenerate-entityCase-dec-xml').checked;
		
		var pars = 'service=' + ApplicationService.GENERATE;
		pars += '&' + 'target=generate';
		pars += '&' + 'context=' + ApplicationContext.CASES;
		pars += '&' + 'includeXML=' + includeXML;
		pars += '&' + 'entity=' + EntityCase.entityName;
		pars += '&' + 'entityID=' + entityID;

		document.location = Service.URL + '?' + pars;
	},
	
	arGenerate: function() {
		var entityID = Entity.getEntityID(ApplicationContext.CASES, EntityCase.entityName);
		var includeXML = $('casegenerate-entityCase-ar-xml').checked;
		
		var pars = 'service=' + ApplicationService.GENERATE;
		pars += '&' + 'target=generate';
		pars += '&' + 'context=' + ApplicationContext.CASES;
		pars += '&' + 'includeXML=' + includeXML;
		pars += '&' + 'entity=' + EntityCase.entityName;
		pars += '&' + 'entityID=' + entityID;

		document.location = Service.URL + '?' + pars;
	},
	
	combinedGenerate: function() {
		var entityID = Entity.getEntityID(ApplicationContext.CASES, EntityCase.entityName);
		var includeXML = $('casegenerate-entityCase-combined-xml').checked;
		
		var pars = 'service=' + ApplicationService.GENERATE;
		pars += '&' + 'target=generate';
		pars += '&' + 'context=' + ApplicationContext.CASES;
		pars += '&' + 'includeXML=' + includeXML;
		pars += '&' + 'entity=' + EntityCase.entityName;
		pars += '&' + 'entityID=' + entityID;

		document.location = Service.URL + '?' + pars;
	},
	
	/**
	* Make searcher service request
	* @param context the context of the request
	* @param entity the name of the entity being edited
	* @param service the editor service required
	* @param widget the buttons widget to use
	* @param entity the entity type
	* @param entityID the id of an entity instance
	*/
	searcher: function(target, context, widget, entity, onSuccessFunction) {
		var pars = 'service=' + ApplicationService.CASE_SEARCH;
		pars += '&' + 'target=' + target;
		pars += '&' + 'context=' + context;
		pars += '&' + 'widget=' + widget;
		pars += '&' + 'entity=' + entity;
		if (onSuccessFunction == undefined || onSuccessFunction == null) onSuccessFunction = 'Service.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	}
}
