var organisationLists = new Object();

function addEvent(obj, evType, fn){
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, false);
		return true;
	}
	else if (obj.attachEvent) {
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	}
	else {
		return false;
	}
}

function removeEvent(obj, type, fn) {
	if(obj.removeEventListener) {
		obj.removeEventListener(type, fn, false);
	} else if(obj.detachEvent) {
		obj.detachEvent('on'+type, fn);
	}
}

function suggestParentOrganisation() {
	var schedule = document.getElementById('schedule').options[document.getElementById('schedule').selectedIndex].value;
	var orgVal = document.getElementById('parentorganisation').value.toLowerCase();
	if(document.getElementById('parentorganisation').value.length > 1 && organisationLists[ schedule ]) {
		var sugPlace = document.getElementById('organisationsuggestions');
		var links = sugPlace.getElementsByTagName('a');
		for(var i = 0; i < links.length; i++) {
			removeEvent(links[i], 'click', suggestionClicked);
		}
		while(sugPlace.hasChildNodes()) {
			sugPlace.removeChild(sugPlace.firstChild);
		}
		if(organisationLists[ schedule ].length > 0) {
			var sugTitle = document.createElement('h3');
			sugTitle.appendChild(document.createTextNode('Do you mean?'));
			sugPlace.appendChild(sugTitle);
			var sugList = document.createElement('ul');
			for(var i = 0; i < organisationLists[ schedule ].length; i++) {
				if(organisationLists[ schedule ][i].Accountname.toLowerCase().indexOf(orgVal) > -1) {
					var sug = document.createElement('li');
					var sugLink = document.createElement('a');
					sugLink.setAttribute('href', '#');
					sugLink.appendChild(document.createTextNode(organisationLists[ schedule ][i].Accountname));
					sug.appendChild(sugLink);
					sugList.appendChild(sug);
				}
			}
			sugPlace.appendChild(sugList);
			// add events to all the links
			links = sugPlace.getElementsByTagName('a');
			for(var i = 0; i < links.length; i++) {
				addEvent(links[i], 'click', suggestionClicked);
			}
		}
		var sugHelp = document.createElement('p');
		sugHelp.appendChild(document.createTextNode('Can\'t find what you\'re looking for? Try contacting the name of the organisation you are working for to clarify the name on their licence agreement. Alternatively, try calling us on 020 8254 5580 and we will try to help you find the right organisation.'));
		sugPlace.appendChild(sugHelp);
	}
	else {
		var sugPlace = document.getElementById('organisationsuggestions');
		while(sugPlace.hasChildNodes()) {
			sugPlace.removeChild(sugPlace.firstChild);
		}
	}
}

function suggestionClicked(evt) {
	evt = (evt) ? evt : ((window.event) ? window.event : null);
	if(evt.preventDefault) {
		evt.preventDefault();
	}
	evt.returnValue = false;
	var clickedlink = (evt.target) ? evt.target : evt.srcElement;
	document.getElementById('parentorganisation').value = clickedlink.childNodes[0].nodeValue;
	return false;
}

function handleFetchingOrganisations(orgs) {
	document.getElementById('organisationsuggestions').innerHTML = '';
	if(orgs.PRODUCT) {
		organisationLists[ orgs.PRODUCT ] = orgs.ORGANISATIONLIST['M3CrmAccount'];
	}
}

function errorFetchingOrganisations(statusCode, statusMsg) {
	document.getElementById('organisationsuggestionerror').innerHTML = 'Error processing organisations: ' + statusCode + ', ' + statusMsg;
}

function scheduleChanged() {
	var schedule = document.getElementById('schedule').options[document.getElementById('schedule').selectedIndex].value;
	if(!organisationLists[ schedule ]) {
		document.getElementById('organisationsuggestions').innerHTML = '<em>Fetching organisation suggestions...</em> <img src="/furniture/ajax-loader-sm.gif" alt="loading organisation names" />';
		var service = new suggestOrganisation();
		service.setErrorHandler(errorFetchingOrganisations);
		service.setCallbackHandler(handleFetchingOrganisations);
		service.getOrganisationList(schedule);
	}
}

function checkForm(evt) {
	var cansubmit = true;
	var ipts = document.getElementById('sublicenceform').getElementsByTagName('input');
	for(var i = 0; i < ipts.length; i++) {
		if(ipts[i].type == 'text' && ipts[i].value == '') {
			alert('Please enter a value for ' + ipts[i].id);
			ipts[i].focus();
			cansubmit = false;
		}
	}
	if(document.getElementById('email').value.search(/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/) == -1) {
		alert('Please enter a valid email address');
		document.getElementById('email').focus();
		cansubmit = false;
	}
	if(!document.getElementById('agreeterms').checked) {
		alert('You must agree to the terms and conditions before proceeding');
		document.getElementById('agreeterms').focus();
		cansubmit = false;
	}
	if(!cansubmit) {
		evt = (evt) ? evt : ((window.event) ? window.event : null);
		if(evt.preventDefault) {
			evt.preventDefault();
		}
		evt.returnValue = false;
		return false;
	}
}

function initialiseSubLicenceScreen() {
	addEvent(document.getElementById('parentorganisation'), 'keyup', suggestParentOrganisation);
	addEvent(document.getElementById('sublicenceform'), 'submit', checkForm);
	addEvent(document.getElementById('schedule'), 'change', scheduleChanged);
	scheduleChanged();
	var orgSuggests = document.getElementById('organisationsuggestions').getElementsByTagName('a');
	for(var i = 0; i < orgSuggests.length; i++) {
		addEvent(orgSuggests[i], 'click', suggestionClicked);
	}
}

addEvent(window, 'load', initialiseSubLicenceScreen);