function checkSearchCriteria(form) {
	var inputs = form.getElementsByTagName('input');
	var municipality = document.getElementById('municipality');
	var errors = [];
	if (municipality.selectedIndex == -1) {
		errors.push('valitse kohteen sijainti');
	}
	var selections = false;
	for (var i = 0, j = inputs.length; i < j; i++) {
		if (inputs[i].type == 'checkbox' && inputs[i].checked) {
			selections = true;
			break;
		}
	}
	if (!selections) {
		errors.push('valitse ainakin yksi suunnittelutarve tai -ammatti');	
	}
	if (errors.length) {
		alert('Hakeaksesi suunnittelijoita ' + errors.join(' ja ') + '.');
	}
	return errors.length === 0;
}

function regionChange(selector, regionMode) {
	var region = selector.options[selector.selectedIndex].value;
	var query = '';
	if (region) {
		query = '?r=' + region;
	}
	if (regionMode) {
		if (query) {
			query += '&';
		} else {
			query = '?';
		}
		query += 'rm=1';
	}
	makeRequest('axml/municipalities.xml' + query, updateMunicipalities);
}

function updateMunicipalities(request) {
	var xml = getXmlDoc(request);
	if (xml) {
		var municipalities = xml.getElementsByTagName('municipality');
		var selector = document.getElementById('municipality');
		while(selector.hasChildNodes()) {
			selector.removeChild(selector.childNodes[0]);
		}
		var option = null;
		var regions = xml.getElementsByTagName('region');
		if ( regions.length == 1 ) {
			//var region = regions[0];
			//option = document.createElement('option');
			//option.text = region.getAttribute('name') + ' - kaikki kunnat';
			//option.setAttribute('id', 'r' + region.getAttribute('id'));
			//option.setAttribute('value', region.getAttribute('id'));
			//selector.options[selector.options.length] = option;
		}
		for(var i = 0, j = municipalities.length; i < j; i++) {
			option = document.createElement('option');
			option.text = municipalities[i].firstChild.data;
			option.setAttribute('id', 'municipality' + municipalities[i].getAttribute('region') + municipalities[i].getAttribute('id'));
			option.setAttribute('value', municipalities[i].getAttribute('id'));
			selector.options[selector.options.length] = option;
		}

		// This event is listened by selectAllMunicipalities function.
		$.event.trigger('updateMunicipalitiesCompleted');
	}
}

function selectMunicipality(selector) {
	var display = document.getElementById('munsel');
	while(display.hasChildNodes()) display.removeChild(display.childNodes[0]);
	display.appendChild(document.createTextNode(selector.options[selector.selectedIndex].text));
}

/**
 * Select all municipalities.
 *
 * All municipalities are added to selection #munsel.
 * All municipalityIds are added to hidden field #selectedValues separated by comma.
 *
 * @param bool wholeCountry	If true select municipalities from whole country. Otherwise select all municipalities from selected province.
 */
function selectAllMunicipalities(wholeCountry) {

	// This part of function should be executed after ajax call is completed successfully.
	// So bind custom eventlistener
	$(document).bind('updateMunicipalitiesCompleted', function() {
		// First remove selected municipalities if any to prevent duplicates.
		removeMunicipalities();
		
		// Create HTML for <options> and keep record of municipality ids.
		var innerHTML = '';
		var selectedValues = new Array();
		$('#municipality option').each(function() {
			innerHTML += '<option id="s' + this.id + '" value="' + this.value + '">' + this.text + '</option>';
			selectedValues[selectedValues.length] = this.value;
		});
		// Insert HTML and municipality ids to hidden field.
		$('#munsel').append(innerHTML);
		$('#selectedValues').val(selectedValues.join(','));
		
		// Unbind this eventlistener to prevent action when it's not wanted.
		$(document).unbind('updateMunicipalitiesCompleted');
	});
	
	// Execute regionChange ajax call only if Whole country option isn't selected
	if (wholeCountry && $('#region').val() != '') {
		$('#region').val('');
		$('#region').change();
	} else {
		// Fire event if the Whole country selection was allready selected.
		$.event.trigger('updateMunicipalitiesCompleted');
	}
	
}

function addMunicipality(selector) {
	var selectedBox = document.getElementById('munsel');
	var option = selector.options[selector.selectedIndex];
	var options = selectedBox.childNodes;
	var found = false;
	var selectedType = option.id.substring(0,1);
	var regionId = option.id.substring(1,3);
	var tempRegionId = null;
	for(var i = 1; i < options.length; i++) {
		if ( options[i].value == option.value ) {
			found = true;
		}
		if (selectedType == 'r') {
			tempRegionId = options[i].id.substring(2,4);
			if ( tempRegionId == regionId || regionId == null ) {
				selectedBox.removeChild(options[i--]);
			} else if ( tempRegionId == null ) {
				found = true;
			}
		}
		if (selectedType == 'm' && options[i].value != null && options[i].value.length == 2) {
			tempRegionId = options[i].id.substring(2,4);
			if ( tempRegionId == regionId || tempRegionId == null ) {
				found = true;
			}
		}
	}
	if ( !found ) {
		var newOption = document.createElement('option');
		newOption.setAttribute('id', 's' + option.id);
		newOption.setAttribute('value', option.value);
		newOption.text = option.text;
		selectedBox.options[selectedBox.options.length] = newOption;
	} else {
		alert('Olet jo valinnut kyseisen kunnan!');
	}
	var values = new Array();
	for(var i = 1; i < options.length; i++) {
		values[i] = options[i].value;
	}
	document.getElementById('selectedValues').value = values.join(',');
}

function removeMunicipality(selectedBox) {
	selectedBox.removeChild(selectedBox.options[selectedBox.selectedIndex]);
	initMunicipalities(selectedBox);
}

/**
 * Remove municipalities from #munsel selection and municipality ids from #selectedValues hidden field.
 */
function removeMunicipalities() {
	$('#munsel option').remove();
	$('#selectedValues').val('');
}

function initMunicipalities(selectedBox) {
	var options = selectedBox.childNodes;
	var values = new Array();
	for(var i = 1; i < options.length; i++) {
		values[i] = options[i].value;
	}
	document.getElementById('selectedValues').value = values.join(',');
}

function viewRefImage(image, refid) {
	document.getElementById('refimg' + refid).src = image.src.replace('thumbnail', '408');
	var caption = document.getElementById('caption' + refid);
	while(caption.firstChild) caption.removeChild(caption.firstChild)
	caption.appendChild(document.createTextNode(image.title))
}
