/**
 * author: David Joseph
 *
 * Retrieve data via a JQuery get request with a query parameter q,
 * parse the data into an array
 * and fill a given selectbox with the retrieved options
 * @param requestUrl: requesturl to retrieve data, data has to be in following format:
 *  textvalue1|id1
 *  textvalue2|id2
 * @param selectBox: selectbox that has to be updated with the new options
 */
function ajaxUpdateSelectBox(requestUrl, selectBox) {
	ajaxUpdateSelectBoxWithErrorMessage(requestUrl, selectBox, 'No matching options found');
}

function ajaxUpdateSelectBoxWithErrorMessage(requestUrl, selectBox, errorMessage) {
	if (requestUrl && selectBox) {
		//retrieve all text and values via a jquery get request
		jQuery.get(requestUrl, function(data) {
			data = parseData(data);
			addOptionsToSelectBox(selectBox, data , null, errorMessage);
		});
	}
}

function ajaxUpdateSelectBox(requestUrl, selectBox, selectedId) {
    if (requestUrl && selectBox) {
		//retrieve all text and values via a jquery get request
		jQuery.get(requestUrl, function(data) {
			data = parseData(data);
			addOptionsToSelectBox(selectBox, data, selectedId, 'No matching options found');
		});
	}    
}

function addOptionsToSelectBox(selectBox, options, selectedId, noChildrenFoundErrorMessage) {
	//remove all current options from the selectbox
	selectBox.length = 0;

	if (options) {
		for (var i=0; i < options.length; i++) {
			var newOption = document.createElement('option');
			var row = options[i];
			if (!row) continue;
			//each option consists of a array with a text and a value
			newOption.text = row[0];
			newOption.value = row[1];
			if (selectedId && row[1] == selectedId) {
				newOption.selected = true;
			}
			selectBox.options[selectBox.options.length] = newOption;
		}
	} else {
        var newOption = document.createElement('option');
        if (noChildrenFoundErrorMessage != '') {
            newOption.text = noChildrenFoundErrorMessage;
        } else {
            newOption.text = 'No matching options found';
        }
        newOption.value = '';
        selectBox.options[selectBox.options.length] = newOption;    
    }
}

/**
 *  function borrowed from jquery.autocomplete.js which is used to
 *  split data in the following format:
 *  textvalue1|id1
 *  textvalue2|id2
 *  and convert it to an array of rows with value & id
 **/
function parseData(data) {
	if (!data) return null;
	var parsed = [];
	var rows = data.split('\n');
	for (var i=0; i < rows.length; i++) {
		var row = jQuery.trim(rows[i]);
		if (row) {
			parsed[parsed.length] = row.split('|');
		}
	}
	return parsed;
};
