/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/* Function used to add an element to the list
	* elem: text of the element
	* id: id of the element, if it is 0 it means we ignore it
	* listelem: list element to add to
	* update: indicates if the select must be updated
*/
function list_add(elem, id, listelem, update) {
	var ext = elem.substring(elem.lastIndexOf('.') + 1,elem.length)
	var extra = "";
	if (ext && /^(jpg|JPG|png|jpeg|gif)$/.test(ext)) {
		extra = '<img src="' + base_url +'/uploads/images/thumb/' + elem + '" />';
	}

	// We create a elem, append it to the list and set the action when the delete icon is clicked
	var lielem = $('<li>' + elem + extra + '<img src="' + base_url + '/img/del.gif" class="list_del_img" />' + '</li>').data("id",id);
	$(lielem).appendTo(listelem + ' ul').find(".list_del_img").each(function() {
		$(this).click(function() {
			$(this).parent().remove();
			list_update(listelem);
		});
	});
	$(listelem + " ul").sortable('refresh');

	// If we have only 3 arguments (update has not been set) or update is true
	if ((arguments.length <= 3) || (update == true)) {
		list_update(listelem);
	}
}

// function called when a change has ocurred to update the select
function list_update(listelem) {
	var selectelem = listassocations[listelem];
	$(selectelem).html("");

	$(listelem + " ul li").each(function() {
		var text = $(this).html().split("<",1);
		var elem;
		if ($(listelem).data("useids")) {
			elem = $('<option value="' + $(this).data("id") + '" selected="true">' + text + '</option>');
		} else {
			elem = $('<option selected="true">' + text + '</option>');
		}
		$(selectelem).append(elem);
	});
}

// Array used to keep the associations between the list element and the select element
var listassocations = new Array();

// Function used to created the sortable list
function create_ordered_list(listelem, selectelem, useids){
	listassocations[listelem] = selectelem;

	if (arguments.length <= 2) {
		useids = false;
	}

	$(listelem).data("useids", useids);

	// For each element on the select we add an element to the sortable list
	$(selectelem + ' :selected').each(function(i, selected){
		if (trim($(selected).text()) != '') {
			var id = 0;
			if (useids) {
				id = $(selected).attr("value");
			}
			list_add($(selected).text(), id, listelem, false); // we add it to the list without updating the select
		}
	});

	$(listelem + " ul").sortable({ opacity: 0.8, cursor: 'move',
		update: function(event, ui) { list_update(listelem); }
	});
}

