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

var CasaService = {
	
	// CASA SERVICES -------------------------------------------------------

	// EA lister and searcher
	EA_LISTER: 'ea.lister',
	EA_SEARCHER: 'ea.searcher',
	
	// Admin case lister and searcher
	ADMIN_CASE_LISTER: 'admin.case.lister',
	ADMIN_CASE_SEARCHER: 'admin.case.searcher',

	// Get EA profile data
	EA_PROFILE: 'ea.profile',
	EA_CREDIT: 'ea.credit',
	
	// Support EA address management
	REGISTER_ADDRESS_MANAGE: 'register.address.manage',
	REGISTER_ADDRESS_ADD: 'register.address.add',
	REGISTER_ADDRESS_REFINE: 'register.address.refine',
	// Address search
	REGISTER_GETPROPERTY: 'register.getproperty',
	REGISTER_SELECTADDRESS: 'register.selectaddress',
	REGISTER_SELECTUPRN: 'register.selectuprn',
	// EA update
	REGISTER_EAUPDATE: 'register.eaupdate',
	
	REGISTER_CASE_CANCEL: 'register.case.cancel',
	REGISTER_CASE_APPEAL: 'register.case.appeal',
	REGISTER_CASE_REMOVE: 'register.case.remove',
	
	// Case services
	CASE_CANCEL: 'case.cancel',
	CASE_DISCARDPROPERTY: 'case.discardproperty',
	CASE_XML: 'case.xml',

	// QA services
	QA_REGISTRATION: 'qa.registration',

	CASA_REPORTS: 'casa.reports',
	
	// Import EAs
	IMPORT_EAS: 'import.eas',
	
	UPLOAD_URL: 'classes/service/casa/UploaderService.php',
	
	handleEAAdminEvent: function(event, context) {
		var element = Event.element(event);	
		if (element.id.endsWith(Service.SCOPE_SEPARATOR + 'import')) {
			CasaService.importEAs();
		} else if (element.id.endsWith(Service.SCOPE_SEPARATOR + 'register')) {
			CasaService.registerEAUpdate();
		}	
	},
	
	handleEvent: function(event, context) {
		var element = Event.element(event);	
		if (element.id.endsWith(Service.ID_SEPARATOR + 'download')) {
			CasaService.download(context, element.id);
		} else if (element.id.endsWith(Service.SCOPE_SEPARATOR + 'address.add')) {
			CasaService.addressAdd(context);
		} else if (element.id.endsWith(Service.SCOPE_SEPARATOR + 'address.refine')) {
			CasaService.addressRefine(context);
		}	
	},
			
	/**
	* 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) {
		
			// CASA SERVICES
			case CasaService.CASE_XML:
				var caseID = root.getElementsByTagName('message')[0].firstChild.data;
				// Now go an get the XML
				CasaService.downloadXML(Context.QA, caseID);
				break;
			case CasaService.EA_CREDIT:
				alert('The refund was successful.');
				var idElement = Context.EAS + Service.SCOPE_SEPARATOR + Widget.EA_VIEWER + Service.SCOPE_SEPARATOR + Entity.EA + Service.SCOPE_SEPARATOR + 'id';
				var entityID = $F(idElement);
				Entity.view(Context.EAS, Entity.EA, null, entityID);			
				break;
			case CasaService.CASE_CANCEL:
			case CasaService.QA_REGISTRATION:
				dirty.remove(Context.CASES);
				AdminService.clearLock(Context.CASES, Entity.CASE);
				Entity.view(Context.CASES, Entity.CASE, null, Entity.getEntityID(Context.CASES, Entity.CASE));
				break;
			case CasaService.CASE_DISCARDPROPERTY:
			case CasaService.REGISTER_SELECTADDRESS:
			case CasaService.REGISTER_GETPROPERTY:
			case CasaService.REGISTER_SELECTUPRN:
				// Force a refresh of the case editor
				Entity.edit(Context.CASES, Entity.CASE, Entity.getEntityID(Context.CASES, Entity.CASE), true);
				//Entity.view(Context.CASES, Entity.CASE, null, Entity.getEntityID(Context.CASES, Entity.CASE));
				break;
		
			case CasaService.REGISTER_EAUPDATE:
				alert('EA Registration was successful');
				break;
			case CasaService.REGISTER_CASE_CANCEL:
				alert('The case\'s Commercial Register report status is now set to: cancelled');
				break;
			case CasaService.REGISTER_CASE_APPEAL:
				alert('The case\'s Commercial Register report status is now set to: appeal');
				break;
			case CasaService.REGISTER_CASE_REMOVE:
				alert('The case\'s Commercial Register report status is now set to: removed');
				break;
			case CasaService.IMPORT_EAS:
				if (!gotError) {
					alert('Import successful.');
				}
				break;
			case CasaService.REGISTER_ADDRESS_ADD:
				if (!gotError) {
					alert('The request was received by the Commercial Register who will notify you of the outcome, by email, within 24 hours.');
				}
				break;
			case CasaService.REGISTER_ADDRESS_REFINE:
				if (!gotError) {
					alert('The request was successful. An email has been send with the UPRN and address details.');
				}
				break;
			
			case CasaService.CASA_REPORTS:
				// If we get here then there is something to report so back to the server to force a file save dialog
				var pars = 'service=' + CasaService.CASA_REPORTS;
				var reportID = root.getElementsByTagName('reportID')[0].firstChild.data;
				
				pars += '&' + 'reportID=' + reportID;
				pars += '&' + 'generateReport=' + 'true';
				
				try{
					var month = root.getElementsByTagName('month')[0].firstChild.data;
					if(typeof(month)!= undefined && month != null && month != ""){
						pars += '&month='+month;
					}
				}catch(err){;}
				
				try{
					var year = root.getElementsByTagName('year')[0].firstChild.data;
					if(typeof(year)!= undefined && year != null && year != ""){
						pars += '&year='+year;
					}
				}catch(err){;}
				
				// Forces a file save dialog
				document.location = 'requestBroker.php?' + pars;		
				break;
			default:
				break;
		}
		if (message.length > 0 && !gotError && service != CasaService.CASE_XML) {
			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 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;
		$(target).update(content);
		
		if(context==Context.QACASES){
			if(service==QAService.QA_CASE_VIEWER){
				var context = root.getElementsByTagName('context')[0].firstChild.data;
				Service.ListFiles(context,Entity.QACASE);
			}
		}
	},

     // CASA ADMIN SERVICES
     
    eaCredit: function(entityID, creditCount, reason, option){
		document.body.style.cursor = 'wait';
		var pars = 'service=' + CasaService.EA_CREDIT;
    	pars += '&' + 'entityID=' + entityID;
    	pars += '&' + 'creditCount=' + creditCount;
    	pars += '&' + 'reason=' + reason;
    	pars += '&' + 'option=' + option;
    	
    	var onSuccessFunction = 'CasaService.success';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
    	
    },
	
	listEAs: function(context) {
		var entity = Entity.EA;
		var pars = 'service=' + CasaService.EA_LISTER;
		pars += '&' + 'target=' + 'eas-lister-ea';
		pars += '&' + 'context=' + context;
		pars += '&' + 'entity=' + entity;
		pars += '&' + 'widget=' + Widget.LISTER;
		pars += '&' + 'size=15';
		pars += '&' + 'disabled=false';
		var eventHandler = 'Entity.view(\'' + context + '\',\'' + entity + '\',\'@id\')'
		pars += '&' + 'eventHandler=' + eventHandler;
		
		// Collect the searcher radio option
		var radioID = context + Service.SCOPE_SEPARATOR + Widget.EA_SEARCHER + Service.SCOPE_SEPARATOR + 'radio';
		var option = getRadioValue(radioID);
		var termID = context + Service.SCOPE_SEPARATOR + Widget.EA_SEARCHER + Service.SCOPE_SEPARATOR + 'term';
		var term = $(termID).value;
		
		// Check term is OK and matches selected radio option
		if (option == 'ea') {
			if (term.length == 0) {
				document.body.style.cursor = '';
				alert('Please enter a 6 digit EA certificate number without the LCEA prefix');
				return;
			}
			var regex = /^[0-9]{6}$/;
		    var value = term.replace(regex, '');
			if (value.length > 0) {
				document.body.style.cursor = '';
				alert('Your EA Certificate Number is invalid: A 6 digit number is required');
				return;			
			}
		} else if (option == 'name') {
			if (term.length == 0) {
				document.body.style.cursor = '';
				alert('Please enter a name.');
				return;
			}
		}
		
		pars += '&' + 'option=' + option;
		pars += '&' + 'term=' + term;
			
		var onSuccessFunction = 'CasaService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	},
	
	searcherEAs: function(context) {
		var entity = Entity.EA;
		var pars = 'service=' + CasaService.EA_SEARCHER;
		pars += '&' + 'target=' + 'eas-searcher-ea';
		pars += '&' + 'context=' + context;
		pars += '&' + 'entity=' + entity;
		pars += '&' + 'widget=' + Widget.EA_SEARCHER;
		var onSuccessFunction = 'CasaService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	},

	searcherAdminCases: function(context) {
		var entity = Entity.CASE;
		var pars = 'service=' + CasaService.ADMIN_CASE_SEARCHER;
		pars += '&' + 'target=' + context+'-searcher-case';
		pars += '&' + 'context=' + context;
		pars += '&' + 'entity=' + entity;
		pars += '&' + 'widget=' + Widget.ADMIN_CASE_SEARCHER;
		var onSuccessFunction = 'CasaService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	},
	
	listAdminCases: function(context) {
		var entity = Entity.CASE;
		var pars = 'service=' + CasaService.ADMIN_CASE_LISTER;
		pars += '&' + 'target=' + 'admincases-lister-case';
		pars += '&' + 'context=' + context;
		pars += '&' + 'entity=' + entity;
		pars += '&' + 'widget=' + Widget.LISTER;
		pars += '&' + 'size=15';
		pars += '&' + 'disabled=false';
		var eventHandler = 'Entity.view(\'' + context + '\',\'' + entity + '\',\'@id\')'
		pars += '&' + 'eventHandler=' + eventHandler;
		
		// Collect the searcher radio option
		var radioID = context + Service.SCOPE_SEPARATOR + Widget.ADMIN_CASE_SEARCHER + Service.SCOPE_SEPARATOR + 'radio';
		var option = getRadioValue(radioID);
		var termID = context + Service.SCOPE_SEPARATOR + Widget.ADMIN_CASE_SEARCHER + Service.SCOPE_SEPARATOR + 'term';
		var term = $(termID).value;
		// Check term is OK and matches selected radio option
		if (option == 'ea') {
			if (term.length == 0) {
				document.body.style.cursor = '';
				alert('Please enter a 6 digit EA certificate number without the LCEA prefix');
				return;
			}
			var regex = /^[0-9]{6}$/;
		    var value = term.replace(regex, '');
			if (value.length > 0) {
				document.body.style.cursor = '';
				alert('Your EA Certificate Number is invalid: A 6 digit number is required');
				return;			
			}
		} else if (option == 'uprn') {
			if (term.length == 0) {
				document.body.style.cursor = '';
				alert('Please enter a 12 digit UPRN');
				return;
			}
			var regex = /^[0-9]{12}$/;
		    var value = term.replace(regex, '');
			if (value.length > 0) {
				document.body.style.cursor = '';
				alert('Your UPRN is invalid: A 12 digit number is required');
				return;			
			}
		} else if (option == 'rrn') {
			if (term.length == 0) {
				document.body.style.cursor = '';
				alert('Please enter a valid RRN');
				return;
			}
			var regex = /^([0-9]{4}-){4}[0-9]{4}$/;
		    var value = term.replace(regex, '');
			if (value.length > 0) {
				document.body.style.cursor = '';
				alert('Your RRN is invalid.');
				return;			
			}
		} else {
			if (term.length == 0) {
				document.body.style.cursor = '';
				alert('Please enter an integer case ID');
				return;
			}
			var regex = /^\d+$/;
		    var value = term.replace(regex, '');
			if (value.length > 0) {
				document.body.style.cursor = '';
				alert('Your Case ID is invalid: An integer is required');
				return;			
			}
		}


		pars += '&' + 'option=' + option;
		pars += '&' + 'term=' + term;
			
		var onSuccessFunction = 'CasaService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	},

	reports: function(reportID) {
		var pars = 'service=' + CasaService.CASA_REPORTS;
		pars += '&' + 'reportID=' + reportID;
		
		//Check siblings for a month and year filter
		var siblings = $(reportID).siblings();
		siblings.each(function(node){
		  if($(node).readAttribute("name") == "month"){
			  var value = $(node).options[$(node).options.selectedIndex].value;
			  pars += '&month='+value;
		  }
		  else if($(node).readAttribute("name") == "year"){
			  var value = $(node).options[$(node).options.selectedIndex].value;
			  pars += '&year='+value;
		  }
	   });			
		// Check whether report status
		var onSuccessFunction = 'CasaService.success';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
	},
     
    /**
     * Change a case's report status in the commercial register
     */
    registerChangeReportStatus: function(service){
		var idPrefix = Context.ADMINCASES + Service.SCOPE_SEPARATOR + Service.BUTTONS + Service.SCOPE_SEPARATOR + Entity.CASE + Service.SCOPE_SEPARATOR;
		var reasonFieldID = idPrefix + 'reason';
		var reason = $(reasonFieldID).value;
		if (reason.trim().length == 0) {
			alert('Please supply a reason for the change of status.');
			return;
		}
    	var message = 'You are about to request that the Commercial Register changes the status of a lodged EPC. Click OK to continue.';
    	if (service == CasaService.REGISTER_CASE_CANCEL) {
    		message = 'You are about to request that the Commercial Register sets the status this case\'s lodged EPC to \'cancelled\'. This operation cannot be reversed. Click OK to continue.';   		
    	} else if (service == CasaService.REGISTER_CASE_APPEAL) {
   			message = 'You are about to request that the Commercial Register sets the status this case\'s lodged EPC to \'appeal\'. Click OK to continue.';   		   		
    	}
		var answer = confirm(message);
		if (answer) {		
	 		document.body.style.cursor = 'wait';
			var pars = 'service=' + service;
	    	pars += '&' + 'entityID=' + Entity.getEntityID(Context.ADMINCASES, Entity.CASE);
			pars += '&' + 'reason=' + reason;
	    	
	    	var onSuccessFunction = 'CasaService.success';
			var onFailureFunction = 'Service.failure';
			new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
		}
    },
    
    // CASA EA SERVICES
    
 	addresses: function(context) {
		var pars = 'service=' + CasaService.REGISTER_ADDRESS_MANAGE;
		pars += '&' + 'context=' + context;
		pars += '&' + 'target=' + 'address-management';
		pars += '&' + 'widget=' + Widget.REGISTER_ADDRESS;
    	var onSuccessFunction = 'CasaService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});   	
	},
	
  	addressAdd: function(context) {
   		var formID = 'addresses-form';
		var pars = 'service=' + CasaService.REGISTER_ADDRESS_ADD;
		pars += '&' + 'context=' + context;
		// Check the data
		var validationMessage = '';
   		var idPrefix = 'addresses-registerAddress-';
		
		// Check the location
		var value = $(idPrefix + 'location.add').options.selectedIndex;
		if (value == 0) {
			validationMessage += 'Please select a location.'
		}
		
		var value = $(idPrefix + 'address1').value;
		if (value.length == 0) {
			if (validationMessage.length > 0) validationMessage += ', Address 1 is empty';
			else validationMessage += 'Address 1 is empty';
		}
		/*
		value = $(idPrefix + 'address2').value;
		if (value.length == 0) {
			if (validationMessage.length > 0) validationMessage += ', Address 2 is empty';
			else validationMessage += 'Address 2 is empty';
		}
		*/
		value = $(idPrefix + 'posttown').value;
		if (value.length == 0) {
			if (validationMessage.length > 0) validationMessage += ', Post Town is empty';
			else validationMessage += 'Post Town is empty';
		}
		value = $(idPrefix + 'postcode').value;
		if (value.length == 0) {
			if (validationMessage.length > 0) validationMessage += ', Post Code is empty';
			else validationMessage += 'Post Code is empty';
		} else if (!checkPostCode(value)) {
			if (validationMessage.length > 0) validationMessage += ', Post Code is invalid';
			else validationMessage += 'Post Code is invalid';
		}
		if (validationMessage.length > 0) {
			alert('There were problems: ' + validationMessage);
			return;
		}
		
		var answer = confirm('You are about to request that a new address is added to the Commercial Register. Click OK to continue.');
		if (answer) {		
			// Collect the data for sending
			var data = $(formID).serialize();				
			pars += '&' + data;
			
	    	var onSuccessFunction = 'CasaService.success';
			var onFailureFunction = 'Service.failure';
			new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});  
		} 	
	},
	
   	addressRefine: function(context) {
  		var formID = 'addresses-form';
		var pars = 'service=' + CasaService.REGISTER_ADDRESS_REFINE;
		pars += '&' + 'context=' + context;
		
		// Check the data
		var validationMessage = '';
   		var idPrefix = 'addresses-registerAddress-';
		
		// Check the location
		var value = $(idPrefix + 'location.refine').options.selectedIndex;
		if (value == 0) {
			validationMessage += 'Please select a location. '
		}
		
		
		var buildingPartValue = $(idPrefix + 'buildingpart').value;
		var siteBuildingValue = $(idPrefix + 'sitebuilding').value;
		if (buildingPartValue.length == 0 && siteBuildingValue.length == 0) {
			validationMessage += 'You must supply either one or both of Building Part and Site Building.';
		}
		value = $(idPrefix + 'uprn').value;
		if (value.length == 0) {
			if (validationMessage.length > 0) validationMessage += ' The Base UPRN is empty';
			else validationMessage += 'The Base UPRN is empty';
		} else {
			var regex = /^[0-9]{8}$/;
		    value = value.replace(regex, '');
			if (value.length > 0) {
				if (validationMessage.length > 0) validationMessage += ' The Base UPRN is invalid. An 8 digit number is required.';
				else validationMessage += 'The Base UPRN is invalid. An 8 digit number is required.';
			}
		}
		if (validationMessage.length > 0) {
			alert('There were problems: ' + validationMessage);
			return;
		}

		var answer = confirm('You are about to request a refinement to an existing address. Click OK to continue.');
		if (answer) {		
			// Collect the data
			var data = $(formID).serialize();				
			pars += '&' + data;
			
	    	var onSuccessFunction = 'CasaService.success';
			var onFailureFunction = 'Service.failure';
			new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});  
		} 	
	},
 
 	download: function(context, downloadID) {
		var pars = 'service=' + Service.DOWNLOAD;
		pars += '&' + 'context=' + context;
		pars += '&' + 'downloadID=' + downloadID;
		document.location = Service.URL + '?' + pars;
	},
	
	/**
	 * Download lodged XML file defined by an RRN entered on QA screen
	 * @param String context context ID
	 * @param int caseID the case ID
	 */
 	downloadXML: function(context, caseID) {
		var pars = 'service=' + Service.DOWNLOAD;
		pars += '&' + 'context=' + context;
		pars += '&' + 'downloadID=' + caseID;
		document.location = Service.URL + '?' + pars;
	},

	/**
	 * Download a case file from list on Case admin screen
	 * @param String context context ID
	 * @param int caseID the case ID
	 * @param int fileID the file ID
	 */
 	downloadCaseFile: function(context, caseID, fileID) {
		var pars = 'service=' + Service.DOWNLOAD;
		pars += '&' + 'context=' + context;
		pars += '&' + 'downloadID=' + caseID;
		pars += '&' + 'fileID=' + fileID;
		document.location = Service.URL + '?' + pars;
	},
	
	/**
	 * Invoked by onClick handler on items in file list on Case admin screen
	 * @param int caseID the case ID
	 * @param int fileID the file ID
	 */
	caseFile: function(caseID, fileID) {
		var context = Context.ADMINCASES;
		CasaService.downloadCaseFile(context, caseID, fileID);
	},
	
   	caseXML: function(context) {
		var message = '';
		var pars = 'service=' + CasaService.CASE_XML;
		pars += '&' + 'context=' + context;
		var rrn = $('qa-xml-rrn').value;
		if (rrn.length == 0) {
			message += 'Please enter an RRN.\n'
		}
		
		var regex = /^([0-9]{4}-){4}[0-9]{4}$/;
		if (!rrn.match(regex)) {
			message += 'Please enter a valid RRN.\n';
			
		}
		if (message.length > 0) {
			alert(message);
			exit;
		}

		pars += '&' + 'rrn=' + rrn;
    	var onSuccessFunction = 'CasaService.success';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});   	
	},
  
 	eaProfile: function(context, profileID){
		var pars = 'service=' + CasaService.EA_PROFILE;
		pars += '&' + 'context=' + context;
		pars += '&' + 'target=' + 'profile';
		pars += '&' + 'widget=' + Widget.EA_PROFILE;
		if (profileID != undefined && profileID != null && profileID.length > 0) {
			pars += '&' + 'profileID=' + profileID;
		}
    	var onSuccessFunction = 'CasaService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});   	
	},
    
 	changeProfile: function(context){
		var pars = 'service=' + CasaService.EA_PROFILE;
		pars += '&' + 'context=' + context;
		pars += '&' + 'target=' + 'profile';
		pars += '&' + 'widget=' + Widget.EA_PROFILE;

		var elementID = Context.EAPROFILE + Service.SCOPE_SEPARATOR + 'selectprofile';	
		var profileID = $(elementID).options[$(elementID).options.selectedIndex].value;
		if (profileID != undefined && profileID != null && profileID.length > 0) {
			pars += '&' + 'profileID=' + profileID;
		}
    	var onSuccessFunction = 'CasaService.contentSuccess';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});   	
	},
	
 	changeProfileAdmin: function(){
		var elementID = Context.EAS + Service.SCOPE_SEPARATOR + 'selectprofile';
		var profileID = $(elementID).options[$(elementID).options.selectedIndex].value;
		Entity.view(Context.EAS, Entity.EA, 'eas-lister-ea-select', null, profileID);
	},
	
 	importEAs: function() {
		// Collect values and invoke service
		document.body.style.cursor = 'wait';
		var pars = 'service=' + CasaService.IMPORT_EAS;
		var onSuccessFunction = 'CasaService.success';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
		
	},
    
    fileUpload: function(context) {
  		// Check the build type option (EPC only)
		var message = "";
  		var idPrefix = 'cases-editor-case-';
		try {
			var value = $(idPrefix + 'build_type').options.selectedIndex;
			if (value == 0) {
				message += 'Please select a Build Type option.\n'
			}
 		} catch(err) {;}
 		// Check the data gathering option
		var value = $(idPrefix + 'data_gathering').options.selectedIndex;
		if (value == 0) {
			message += 'Please select a Data Gathering option.\n'
		}
		if (message.length > 0) {
			alert(message);
			exit;
		}
     	// Collect the candidate file name
   		try {
     		// Try EPC first
 			var xmlFile = $F(context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'xml');
		
			// Client-side validation
			var validationReport = CasaService.qaRegistrationValidation(xmlFile);
			if (validationReport.length > 0) {
				alert(validationReport);
				return;
			}
     	} catch(err) {
      		// Could be DEC or AC     		
 	 		try {
				var decFile = $F(context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'dec');
				// Client-side validation
				var validationReport = CasaService.qaDECRegistrationValidation(decFile);
				if (validationReport.length > 0) {
					alert(validationReport);
					return;
				}
			} 
			catch (err) {
				var acFile = $F(context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'ac');
				// Client-side validation
				var validationReport = CasaService.qaACRegistrationValidation(acFile);
				if (validationReport.length > 0) {
					alert(validationReport);
					return;
				}
			}
    		
     	}

		// Ask for confirmation
		var answer = confirm('Upload may take a few minutes and cannot be interrupted. Click OK to continue.');
		if (answer) {		
			// File upload is not supported by XMLHTTP so we don't have asynchronous upload. Means we sit here for a bit
	 		var formID = context + Service.SCOPE_SEPARATOR + Entity.CASE + Service.SCOPE_SEPARATOR + 'form';
	 		$(formID).action = CasaService.UPLOAD_URL;
			$(formID).submit();
			// Back to the default action URL
	 		$(formID).action = 'javascript:void(0)'; 
		}		   
    },

    qaRegistration: function(context) {
 		var message = "";
  		var idPrefix = 'cases-editor-case-';
 		// Check the build type option (EPC only)
		try {
			var value = $(idPrefix + 'build_type').options.selectedIndex;
			if (value == 0) {
				message += 'Please select a Build Type option.\n'
			}
 		} catch(err) {;}
 		// Check the data-gathering option
		var value = $(idPrefix + 'data_gathering').options.selectedIndex;
		if (value == 0) {
			message += 'Please select a Data Gathering option.\n'
		}
		if (message.length > 0) {
			alert(message);
			exit;
		}
   		var answer = confirm('Your uploaded file will be submitted for QA checks and lodgement. Lodgment may take a few minutes. Click OK to continue.');
		if (answer) {		   	
	 		document.body.style.cursor = 'wait';
	 		var pars = 'service=' + CasaService.QA_REGISTRATION;
	 		pars += '&' + 'entityID=' + Entity.getEntityID(Context.CASES, Entity.CASE);
	  		var onSuccessFunction = 'CasaService.success';
			var onFailureFunction = 'Service.failure';
			new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
		}
    },
    
    qaRegistrationValidation: function(xmlFile) {
    	var validationReport = "";
       	if (xmlFile.length == 0) validationReport += "\nPlease select an EPC XML file.";
    	else if (!xmlFile.endsWith('.xml') && !xmlFile.endsWith('.XML')) validationReport += "\nThe selected EPC file is not an XML file."; 
    	return validationReport;
     
    },
    
    qaACRegistrationValidation: function(xmlFile) {
    	var validationReport = "";
       	if (xmlFile.length == 0) validationReport += "\nPlease select an AC XML file.";
    	else if (!xmlFile.endsWith('.xml') && !xmlFile.endsWith('.XML')) validationReport += "\nThe selected AC file is not an XML file."; 
    	return validationReport;
     
    },

    qaDECRegistrationValidation: function(decFile) {
    	var validationReport = "";
       	if (decFile.length == 0) {
 			var radioID = Context.CASES + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'uploadtype';
			var option = getRadioValue(radioID);
       		switch(option) {
       			case '0':
 		       		validationReport += "\nPlease select a combined DEC-AR XML file.";
       				break;
       			case '1':
 		       		validationReport += "\nPlease select a DEC only XML file.";
       				break;
       			case '2':
		       		validationReport += "\nPlease select an AR only XML file.";
       				break;
       			default:
		       		validationReport += "\nPlease select an XML file.";
       				break;
       		}
       	}
	   	else if (!decFile.endsWith('.xml') && !decFile.endsWith('.XML')) validationReport += "\nThe selected DEC file is not an XML file."; 
     	return validationReport;
     
    },
        
    registerEAUpdate: function() {
		document.body.style.cursor = 'wait';
		var pars = 'service=' + CasaService.REGISTER_EAUPDATE;
		
		var onSuccessFunction = 'CasaService.success';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
    
    },

    registerGetProperty: function(context) {
		document.body.style.cursor = 'wait';
		var pars = 'service=' + CasaService.REGISTER_GETPROPERTY;

		// Collect the radio selection and the search term		
		var radioID = context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'getproperty' + Service.SCOPE_SEPARATOR + 'radio';
		var option = getRadioValue(radioID);
		pars += '&' + 'option=' + option;
		//pars += '&' + 'option=' + 'postcode';
		var postcodeID = context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'getproperty' + Service.SCOPE_SEPARATOR + 'postcode';
		var postcodeValue = $(postcodeID).value;
		var uprnID = context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'getproperty' + Service.SCOPE_SEPARATOR + 'uprn';
		var uprnValue = $(uprnID).value;
		var buildingID = context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'getproperty' + Service.SCOPE_SEPARATOR + 'building';
		var buildingValue = $(buildingID).value;
		var streetID = context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'getproperty' + Service.SCOPE_SEPARATOR + 'street';
		var streetValue = $(streetID).value;
		var townID = context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'getproperty' + Service.SCOPE_SEPARATOR + 'town';
		var townValue = $(townID).value;
		
		if (option == 'postcode') {
			if (postcodeValue.length == 0) {
				document.body.style.cursor = '';
				alert('Please enter a post code');
				return;
			}
			if (!checkPostCode(postcodeValue)) {
				document.body.style.cursor = '';
				alert('Your post code is invalid');
				return;			
			}
		} else if (option == 'uprn') {
			if (uprnValue.length == 0) {
				document.body.style.cursor = '';
				alert('Please enter a 12 digit UPRN');
				return;
			}
			var regex = /^[0-9]{12}$/;
		    var value = uprnValue.replace(regex, '');
			if (value.length > 0) {
				document.body.style.cursor = '';
				alert('Your UPRN is invalid: A 12 digit number is required');
				return;			
			}
		} else {
			if (streetValue.length == 0 && townValue.length == 0) {
				document.body.style.cursor = '';
				alert('Please enter a street name and town');
				return;
			}
			if (streetValue.length > 0 && townValue.length == 0) {
				document.body.style.cursor = '';
				alert('Please enter a town');
				return;
			}
			if (streetValue.length == 0 && townValue.length > 0) {
				document.body.style.cursor = '';
				alert('Please enter a street name');
				return;
			}
		}
		
		pars += '&' + 'postcode=' + postcodeValue;
		pars += '&' + 'uprn=' + uprnValue;
		pars += '&' + 'building=' + buildingValue;
		pars += '&' + 'street=' + streetValue;
		pars += '&' + 'town=' + townValue;
		pars += '&' + 'entityID=' + Entity.getEntityID(Context.CASES, Entity.CASE);

		var onSuccessFunction = 'CasaService.success';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
    
    },
    
    caseCancel: function(){
		document.body.style.cursor = 'wait';
		var pars = 'service=' + CasaService.CASE_CANCEL;
    	pars += '&' + 'entityID=' + Entity.getEntityID(Context.CASES, Entity.CASE);
    	
    	var onSuccessFunction = 'CasaService.success';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
    	
    },
    
    caseDiscardProperty: function(){
		document.body.style.cursor = 'wait';
		var pars = 'service=' + CasaService.CASE_DISCARDPROPERTY;
    	pars += '&' + 'entityID=' + Entity.getEntityID(Context.CASES, Entity.CASE);
    	var onSuccessFunction = 'CasaService.success';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});   	
    },
 
    multiAddress: function(context){
 		document.body.style.cursor = 'wait';
    	var pars = 'service=' + CasaService.REGISTER_SELECTADDRESS;

		// Collect the radio selection and the search term		
		try {
			var multiAddressID = context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'multiaddress' + Service.SCOPE_SEPARATOR + 'select';
			var multiAddressValue = $(multiAddressID).value;
			if (multiAddressValue.length == 0) {
				alert('Please select an address');
				return;
			}			
		} catch(err) {
			alert('There are no properties available. Please use the Discard Property button and select a new property.');
			return;			
		}
		pars += '&' + 'moniker=' + $(multiAddressID).value;
		pars += '&' + 'entityID=' + Entity.getEntityID(Context.CASES, Entity.CASE);
		
		var onSuccessFunction = 'CasaService.success';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
    },

    multiUPRN: function(context){
		document.body.style.cursor = 'wait';
    	var pars = 'service=' + CasaService.REGISTER_SELECTUPRN;

		// Collect the radio selection and the search term		
		
		var multiUPRNID = context + Service.SCOPE_SEPARATOR + Widget.CASE_EDITOR + Service.SCOPE_SEPARATOR + 'multiuprn' + Service.SCOPE_SEPARATOR + 'select';
		var multiUPRNValue = $(multiUPRNID).value;
		if (multiUPRNValue.length == 0) {
			alert('Please select an address');
			return;
		}
		pars += '&' + 'uprn=' + $(multiUPRNID).value;
		pars += '&' + 'entityID=' + Entity.getEntityID(Context.CASES, Entity.CASE);
		
		var onSuccessFunction = 'CasaService.success';
		var onFailureFunction = 'Service.failure';
		new Ajax.Request(Service.URL, {parameters:pars, onSuccess:eval(onSuccessFunction), onFailure:eval(onFailureFunction)});
    }
    
	
	
}
