/** init part **/

/** globals **/

countryLoaded = false;
publicationLoaded = false;
sectorLoaded = false;

countryArr = new Array();
publicationArr = new Array();
sectorArr = new Array();

/**
 * init function for onload in body tag
 */
function init(baseUrl) {

	/* init filter region */
	var urlRegion = baseUrl + "/search/loadfilter/type/fRegion";
	new Ajax.Request(
		urlRegion,
		{
  			method: 'get',
  			requestHeaders: {Accept: 'application/json'},
  			onCreate: function () {
  				$('country-values').update('Loading ...');
  			},
  			onSuccess: function (transport) {
				var result = transport.responseText.evalJSON(true);
				for (i = 0; i<result.length; i++) {
					obj = new Object();
					obj['id'] = result[i].id;
					obj['name'] = result[i].name;
					obj['operator'] = result[i].operator;
					countryArr.push(obj);
				}
				refresh('country-values', countryArr);
				countryLoaded = true;
				showButtons();
  			}
		});

	/* init filter publication type */
	var urlPubType = baseUrl + "/search/loadfilter/type/fPubType";
	new Ajax.Request(
		urlPubType,
		{
  			method: 'get',
  			requestHeaders: {Accept: 'application/json'},
  			onCreate: function () {
  				$('publicationtype-values').update('Loading ...');
  			}, 
  			onSuccess:  function (transport) {
				var result = transport.responseText.evalJSON(true);
				for (i = 0; i<result.length; i++) {
					obj = new Object();
					obj['id'] = result[i].id;
					obj['name'] = result[i].name;
					obj['operator'] = result[i].operator;
					publicationArr.push(obj);
				}
				refresh('publicationtype-values', publicationArr);
				publicationLoaded = true;
				showButtons();
  			}
		});

	/* init filter publication type */
	var urlSector = baseUrl + "/search/loadfilter/type/fSector";
	new Ajax.Request(
		urlSector,
		{
  			method: 'get',
  			requestHeaders: {Accept: 'application/json'},
  			onCreate: function () {
  				$('sector-values').update('Loading ...');
  			}, 
  			onSuccess:  function (transport) {
				var result = transport.responseText.evalJSON(true);
				for (i = 0; i<result.length; i++) {
					obj = new Object();
					obj['id'] = result[i].id;
					obj['name'] = result[i].name;
					obj['operator'] = result[i].operator;
					sectorArr.push(obj);
				}
				refreshSector('sector-values', sectorArr);
				sectorLoaded = true;
				showButtons();
  			}
		});
}

/**
 * refresh the data (region and publication type)
 */
function refresh(targetId, dataArr) {
	// in case of only one element we print only the first one
	// otherwise all other
	if (dataArr.length == 1) {
		$(targetId).update(dataArr[0]['name']);
	} else { 
		// carful we start here with 1. because we do not want the first element
		$(targetId).update('');
		for (var i = 1; i < dataArr.length; i++) {			
			a = new Element('a', { 'class': 'span-link' , href: 'javascript:removeFilter(\'' + dataArr[i]['id'] + '\')' });
			a.update(dataArr[i]['operator'] + '&nbsp;' + dataArr[i]['name']);
			$(targetId).insert(a);		
		}
	}	
}

/**
 * refresh sector data
 */
function refreshSector(targetId, dataArr) {
	
	// if only one element is in the dataArr we do not want the treesector toggle icon.
	if (dataArr.length == 1) {
		$('toggle-icon-treesector').className = "invisible";
	} else {
		$('toggle-icon-treesector').className = "visible";
	}

	if (sectorPresentation == 'list') {
		refresh(targetId, dataArr);
	} else {
		dataArr = addMainCPVs(dataArr);
		dataArr.sort(sortById);
		if (dataArr.length == 1) {
			$(targetId).update(dataArr[0]['name']);
		} else {
			$(targetId).update('');
			for (var i = 1; i < dataArr.length; i++) {
				classLevel = '';
				// choose level and hidden/selected class
				if (dataArr[i]['operator'] == '=') {
					classLevel += ' sector-hidden';
				} else {
					level = getSectorLevel(dataArr[i]['id']);
					if (level > 0) {
						classLevel = 'level' + level;
					} else {
						classLevel = '';
					}
					classLevel += ' sector-selected';
				}
				// create div element
				div = new Element('div', { 'class': classLevel });
				if (dataArr[i]['operator'] == '=') { // add a span in case of  main cpv (operator = '=')
					span = new Element('span');
					span.update(dataArr[i]['name'] + ' (' + dataArr[i]['id'] + ')');
					div.insert(span);
				} else { // add anchor in case of selected cpv
					a = new Element('a', { 'class': 'div-link', href: 'javascript:removeFilter(\'' + dataArr[i]['id'] + '\')' });
					a.update(dataArr[i]['operator'] + '&nbsp;' + dataArr[i]['name']);
					div.insert(a)
				}
				$(targetId).insert(div);  
			}
		}
	}
}

function showButtons() {
	if (countryLoaded && publicationLoaded && sectorLoaded ) {
		$('searchButton').disabled = false;
		$('saveButton').disabled = false;
	}
}

function getSectorLevel(sectorId) {
	if (sectorId.substring(2) == '000000') return 0;
	if (sectorId.substring(3) == '00000') return 1;
	if (sectorId.substring(4) == '0000') return 2;
	if (sectorId.substring(5) == '000') return 3;
	if (sectorId.substring(6) == '00') return 4;
	if (sectorId.substring(7) == '0') return 5;
	return 6;
}


/**
 * toggle input fields (visible or not)
 */
function toggle(rowid, toggleid, baseUrl) {
	if ($(rowid).style.display == 'none') {
		$(rowid).style.display = '';
		$(toggleid).style.backgroundImage = "url('" + baseUrl + "/img/resultset_previous_paddingtop2px.png')";
	} else {
		$(rowid).style.display = 'none';
		$(toggleid).style.backgroundImage = "url('" + baseUrl + "/img/resultset_next_paddingtop2px.png')";
	}
}

/**
 * toggle sector view (list or tree)
 */
function toggleSector(baseUrl) {
	if (sectorPresentation == 'list') {
		sectorPresentation = 'tree';
		$('toggle-icon-treesector').style.backgroundImage = "url('" + baseUrl + "/img/application_side_list.png')";
	} else {
		sectorPresentation = 'list';
		$('toggle-icon-treesector').style.backgroundImage = "url('" + baseUrl + "/img/application_side_tree.png')";
	}
	refreshSector('sector-values', sectorArr);
}

/**
 * build data when formular was submitted
 */
function submitData(form) {
	$(form).fRegion.value = countryArr.toJSON();
	$(form).fPubType.value = publicationArr.toJSON();
	$(form).fSector.value = sectorArr.toJSON();
	return true;
}

/**
 * generic add filter function
 * @param targetId the target id
 * @param sourceId the source selector id
 * @param dataArr the data array
 * @param operator the operator
 */
function addFilter(targetId, sourceId, dataArr, operator) {
	targetElement = document.getElementById(targetId);
	sourceElement = document.getElementById(sourceId);
	
	val = sourceElement[sourceElement.selectedIndex].value;
	txt = sourceElement[sourceElement.selectedIndex].text;
	
	if (filter_exists(val, dataArr) == false) {				
		if ((val != -1) && (val != '--')) {
			obj = new Object();
			obj['id'] = val;
			obj['name'] = txt;
			obj['operator'] = operator;
			dataArr.push(obj);
		}
	}
} 

/* add filters function for different cases */
function addCountryFilter(targetId, sourceId, operator) {
	addFilter(targetId, sourceId, countryArr, operator);
	refresh(targetId, countryArr);
}

function addPublicationFilter(targetId, sourceId, operator) {
	addFilter(targetId, sourceId, publicationArr, operator);
	refresh(targetId, publicationArr);
}

function addSectorFilter(targetId, sourceId, operator) {
	addFilter(targetId, sourceId, sectorArr, operator);
	refreshSector(targetId, sectorArr);
}

/**
 * generic remove of filter
 * @param id the id of the element who will be removed
 * @param targetId the targetId of the element for rendering
 * @param dataArr the data array
 */
function removeFilter(id) {

	// interate thru all elements. except the first one.
	for (var i = 1; i < countryArr.length; i++) {
		if (countryArr[i]['id'] == id) {
			countryArr.splice(i, 1);
		}
	}

	for (var i = 1; i < publicationArr.length; i++) {
		if (publicationArr[i]['id'] == id) {
			publicationArr.splice(i, 1);
		}
	}
	
	for (var i = 1; i < sectorArr.length; i++) {
		if (sectorArr[i]['id'] == id) {
			sectorArr.splice(i, 1);
		}
	}

	refresh('country-values', countryArr);	
	refresh('publicationtype-values', publicationArr);
	refreshSector('sector-values', sectorArr);	
}



/**
 * sector search 
 */
function doSearchSector(baseUrl, itemId) {

	if ($(itemId).value.length < 3) {
		$('sectorSearchResult').innerHTML = '';
		return;
	}
	
	var url = baseUrl + "/search/sector/query/" + $(itemId).value;
	new Ajax.Request(
		url,
		{
  			method: 'get',
  			requestHeaders: {Accept: 'application/json'},
  			onCreate: function () {
  				$('sectorSearchResult').update('Loading ...');
  			},
  			onSuccess: renderSectorResult
		});
}

function submitSector(event, baseUrl, itemId) {
    var rt = true;
    var keycode = null;
    if ( window.event ) {
        keycode = window.event.keyCode;
    } else if ( event ) {
        keycode = event.which;
    } 
    if ( keycode != null ) {  
        if (keycode == 13) {
        	doSearchSector(baseUrl, itemId);
            rt = false;
        }
    } 
    return rt;
}


function renderSectorResult(transport) {
	var result = transport.responseText.evalJSON(true);
	if (result.length > 0) {
		var tmp = '<select name="sector" id="sector-selector" size="5">';
		for (i = 0; i<result.length; i++) {
			c = '';
			if (filter_exists(result[i].code, sectorArr)) {
				c = 'class="included"';
			}
			tmp += '<option ' + c + ' value="' + result[i].code + '">' + result[i].text + ' (' + result[i].code + ')</option>';
		}
		tmp += '</select>';
	} else {
		var tmp = '<div style="border:1px solid gray; padding:2px;">no results</div>';
	}
	$('sectorSearchResult').innerHTML = tmp;
}

function clearSectorSearch() {
	$('sectorSearchResult').innerHTML = '';
	$('sector').value = '';
}

/**
 * sort function for sorting sector array by id.
 */
function sortById(a, b) {
	
	if (a.operator == '=') {
		v1 = a.id - 1;
		v2 = b.id;
	} else {
		v1 = a.id;
		v2 = b.id - 1;
	}
	return v1 - v2;
}

function addMainCPVs(selectedCPVArr) {
	retArr = new Array();
	mappedMainCPVs = new Array();
	mainCPVArr = mainCPVString.evalJSON(true);
	
	retArr.push(selectedCPVArr[0]); // save the first element
	
	for (var i = 1; i < selectedCPVArr.length; i++) { // starting at 1. first element is placeholder.
		retArr.push(selectedCPVArr[i]); // ATTENTION the selected CPV must be added after the main cpvs. otherwise the order is wrong!!! 
		prefixSelected = selectedCPVArr[i]['id'].substring(0, 2); 
		for(var j = 0; j < mainCPVArr.length; j++) {
			prefixMain =  mainCPVArr[j]['id'].substring(0, 2);
			if (prefixSelected == prefixMain) {
				if (!in_array(prefixMain, mappedMainCPVs)) {
					retArr.push(mainCPVArr[j]);
					mappedMainCPVs.push(prefixMain);
				} 
			}
		}
	}
	
	return retArr;
}

function in_array(value, dataArr) {
	for(var i = 0; i < dataArr.length; i++) {
		if (value == dataArr[i]) return true;
	}
	return false;
}

/**
 * checks if a filter already is added (exists in the array)
 */
function filter_exists(filter, dataArr) {
	for (var i = 0; i < dataArr.length; i++) {
		if (filter == dataArr[i]['id']) return true;
	}
	return false;
}

