function roi_query_clicked() {
	var tool_type = "roi_query";
	var theTool = $("tool_" + tool_type);

	// Activate
	deactivate(active_tool());

	var query_url = "../../services/statcenter/query_form_gm.php";
	new Ajax.Request(query_url,
		{
			method: 'GET',
			onSuccess: show_roi_query
		});
}


function show_roi_query(oj) {
	var res = oj.responseText;
	var title = "Query with Region of Interest";

	gMapserver.RefreshMap = false;
	gCurrentPopup = new PopupWindow("roi_popup_window", "", {top: 30 + 'px', width: 800 + 'px', height: 'auto'});
	gCurrentPopup.show(title, res);

	if (gPolygons.length == 0 && assoc_array_length(gShapePolygons) == 0) {
		var theForm = document.forms['roi_query_form'];

		// IE is not able to detect the form generated within this function
		// by calling RoiPopup.show.
		if (theForm) {
			theForm.roi_options.checked = false;
			theForm.roi_options.disabled = true;
		}
	}

	// The query form should be shown before referring to the textbox in it.
	aAutoSuggestDataset = new AutoSuggest("search_box_dataset", "result_list");
	aAutoSuggestDataset.prepare();
	var url = g_DATASETS_URL + 'ajax_dataset_search.php';
	var delimiter = "+";
	var parseFunc = parseDataset;
	aAutoSuggestDataset.setFilter(url, parseFunc, delimiter);

	aAutoSuggestSpecies = new AutoSuggest("search_box_species", "result_list");
	aAutoSuggestSpecies.prepare();
	var url = g_SPECIES_URL + 'ajax_species_search.php';
	var delimiter = ",";
	var parseFunc = parseSpecies;
	aAutoSuggestSpecies.setFilter(url, parseFunc, delimiter);
}


function submit_roi_query(map_or_query) {
	if (inputCheck(map_or_query) == false) {
		return false;
	}

	var theForm = document.forms['roi_query_form'];
	var url = g_STAT_CENTER_URL + "ajax_stat.php";

	theForm['stat_action'].value = map_or_query;

	if (theForm['search_box_dataset'].value != "") {
		var datasets = theForm['search_box_dataset'].value;
		dataid_validation(datasets, "dataset");
		if (gValidatedDataid == "") {
			return false;
		}
		theForm['datasetid'].value = gValidatedDataid.replace(/\+/g, ",");
	}

	// The textbox contains scientific names. You need to convert them to ITIS numbers.
	// With ajax, the following codes calls ajax_species_search.php, which returns ITIS numbers.
	// The result is set in speciesTsnList.
	if(theForm['search_box_species'].value != "") {
		var species = theForm['search_box_species'].value;
		dataid_validation(species, "species");
		if (gValidatedDataid == "") {
			return false;
		}
		theForm['speciesTsnList'].value = gValidatedDataid;
	}

	if (theForm['roi_options'].checked && (gPolygons.length > 0 || assoc_array_length(gShapePolygons) > 0)) {
		set_coords(theForm["coords"]);
	}

	var data = $('roi_query_form').serialize();

	if (map_or_query == 'query') {
		var dataset_list = $("roi_query_result");
		dataset_list.update("<P>Please wait. Calculating...</P>");
		dataset_list.show();
		var onSuccess = show_roi_query_result;
	} else {
		var onSuccess = add_roi_query_to_map;
		$("result_list").hide();
	}

	new Ajax.Request(url,
		{
			onSuccess: onSuccess,
			parameters: data
		});
}

function set_coords(input_coords) {
	var coords = "";
	var delimiter = "";

	// Obtain all points from all polygons
	for (var k = 0; k < gPolygons.length; k++) {
		var aPolygon = gPolygons[k];

		for (var l = 0; l < aPolygon.getVertexCount(); l++) {
			var aVertex = aPolygon.getVertex(l);
			coords += delimiter + aVertex.lng() + "," + aVertex.lat();
			delimiter = ",";
		}
		delimiter = "|";	// Multiple polygons
	}
	input_coords.value = coords;

	for (var key in gShapePolygons) {
		if (typeof(gShapePolygons[key]) == "object" && gShapePolygons[key].status == "ON") {
			input_coords.value += delimiter + gShapePolygons[key].coords;
			delimiter = "|";
		}
	}
}

function obtainTsn(oj) {
	res  = oj.responseText;
	// Somehow the oj returns text with LF. So remove annyoing LF or CR, if any.
	res = res.strip();

	// AJAX returns species ITIS numbers, comma separated.
	var theForm = document.forms['roi_query_form'];
	theForm['speciesTsnList'].value = res;

	if (res == "") {
		return false;
	} else {
		return true;
	}
}


function update_search_box(dataid, box_name) {
	var textbox = $(box_name);
	if (textbox.type == 'textarea') {
		if (textbox.value != "") {
			textbox.value += "\n" + dataid;
		} else {
			textbox.value = dataid;	// Replace the value if the box is <INPUT type='text'>
		}
		var criteria = textbox.value.replace(/\r/g,'').split('\n');
		row_num = criteria.length;
		var textarea_row_height = row_num * 16 + 4;
		textbox.rows = row_num;
		textbox.setStyle({height: textarea_row_height + "px"});
	} else {
		textbox.value = dataid;	// Replace the value if the box is <INPUT type='text'>
	}
}

function show_roi_query_result(oj) {
	var res  = oj.responseText;

	var theForm = document.forms['roi_query_form'];

	if (theForm['stat_action'] == 'detail') {
		theForm['row_index'].value = "";
		theForm['stat_action'] = '';
		$("dataset_detail").update(res);
	} else {
		$("roi_query_result").update(res);
		result_ok = true;
	}
	return true;
}

function add_roi_query_to_map(oj) {
	var res  = oj.responseText;		// res = sql_where for the custom layer
	var params = $('roi_query_form').serialize();	// To save the criteria, send serialized form values as well.

	$('debug_info').update(res + "\n<BR>" + params);
	gCurrentPopup.close();
	gCurrentPopup = null;
	add_custom_layer(res, params);
}

function inputCheck(map_or_query) {
    var theForm = document.forms['roi_query_form'];

    if (theForm['byYear'].checked == false &&
		theForm['bySeason'].checked == false &&
		theForm['byMonth'].checked == false &&
		theForm['bySpecies'].checked == false ) {
		alert("At least one aggregation option should be checked to see summary data.");
		return false;
	}

    if (theForm.search_box_dataset.value == "" &&
        theForm.search_box_species.value == "" &&
        theForm.startYear.value == "" &&
        theForm.startMonth.value == "" &&
        theForm.startDay.value == "" &&
        theForm.endYear.value == "" &&
        theForm.endMonth.value == "" &&
        theForm.endDay.value == "") {
        alert("Please specify at least one criterion.");
        return false;
    }

    return true;
}
