/** 
 * Function called onclick ( input searchSelect class) 
 * that does the get request to our url and parses the result.
 * Receives the form as parameter.
 */
function getEscapedRegionName(form, sourceElementId, destinationElementId){//it uses a specific form because a field like sourceRegion.id could coexist with another one named the same attached to another form.
    var sourceRegionId = form.elements[sourceElementId].value;
	$.ajax({
		   type: "GET",
		   url: "/eshop/region/viewEscapedRegionNameEmpty.htm",
		   data: ({ "regionId": sourceRegionId}),
		   success: function(data){
				document.getElementById(destinationElementId).value=jQuery.trim(data);
		   		}
		 });
   	
}

/**
 * Makes a synchronous call to the server to obtain the escaped names of the region with the specified id. 
 * @param regionId the region id.
 * @returns the escaped name of the region.
 */
function getAsyncEscapedRegionName(regionId){
	var regionName;
	$.ajax({
		   async: false,
		   type: "GET",
		   url: "/eshop/region/viewEscapedRegionNameEmpty.htm",
		   data: ({ "regionId": regionId}),
		   success: function(data){
				regionName = jQuery.trim(data);
		   }
		 });
	
	return regionName;
}

/**
 * 
 * @param selectId the id of the select that needs to be filled in.
 */
function buildSourceRegionSelect(selectId, tableModelName, selectedId){
	$.ajax({
		   async: true,
		   type: "GET",
		   url: "/eshop/region/loadSourceRegion.htm",
		   success: function(data){
			   var tableData = data[tableModelName];
			   if (tableData) {
					var sortedData = sortModel(tableData);
					populateSelect(selectId, sortedData, selectedId);
					$('select[id="'+ selectId + '"] > option[value="'+ selectedId +'"]:first').attr('selected','selected');
			   }
		   },
	       error: function(data, options, error) {
		    	// ignore any errors
	    	}
		 });
}

/**
 * 
 * @param selectId the id of the select that needs to be filled in.
 */
function buildDestinationRegionSelect(selectId, tableModelName, selectedId){
	$.ajax({
		async: true,
		type: "GET",
		url: "/eshop/region/loadDestinationRegion.htm",
		success: function(data){
			var tableData = data[tableModelName];
			if (tableData) {
				var sortedData = sortModel(tableData);
				populateSelect(selectId, sortedData, selectedId);
				$('select[id="'+ selectId + '"] > option[value="'+ selectedId +'"]:first').attr('selected','selected');
			}
		},
        error: function(data, options, error) {
	    	// ignore any errors
    	}
	});
}

function populateSelect(selectId, regions, selectedId){
	var data = {"data": regions};
	$('select[id="'+ selectId + '"]').setData(
			{data: data,
			 selectedIDs:[selectedId]
			}
	);
}

/**
 * Finds the position of the separator.
 * @param data the array of regions.
 * @returns the index where the separator is.
 */
function getSeparatorIdx(data){
	var separatorIdx;
	$.each(data, function(idx, itm) 
	{ 
		if (itm[1].indexOf("----") >= 0){
			separatorIdx = idx;
		}
	});
	return separatorIdx;
}

/**
 * Sorts a model of regions that is formed by 2 other models splitted by a separator that contains '---'.
 * It sorts each of the 2 models separatly and then reunites them in one array.
 * @param tableData
 * @returns the array with the 2 sorted models and the separator.
 */
function sortModel(tableData){
	
	var quickSearch=new Array(); 
	var regions=new Array();
	var breakIdx = getSeparatorIdx(tableData);
	$.each(tableData, function(idx, itm) 
	{ 
		if(idx < breakIdx) {
			quickSearch.push(itm);
		} 
		if(idx > breakIdx){
			regions.push(itm);
		}
	});
	sortRegions(quickSearch);
	sortRegions(regions);
	
	var sortedData = new Array();
	$.merge(sortedData, quickSearch);
	sortedData.push(tableData[breakIdx]);
	$.merge(sortedData, regions);
	
	return sortedData;
}

/**
 * Sorts 2 regions depending on their names.
 * @param data the array of regions to be sorted.
 */
function sortRegions(data){
	
	data.sort(function(a, b){
		var nameA=$(a)[1].toLowerCase();
		var nameB=$(b)[1].toLowerCase();
		 if (nameA < nameB) //sort string ascending
		  return -1;
		 if (nameA > nameB)
		  return 1;
		 return 0 ;//default return value (no sorting)
	});
}

