// aimsQuery.js
aimsQueryPresent=true;
var showSampleValues=false;
var storedQueryCount = 0;
var storedQueryName = new Array();
var storedQueryString = new Array();
var storedQueryVariable = new Array();
var storedQueryVarCount = new Array();
var storedQueryFieldList = new Array();
var storedQueryIndex = 0;

// query form
function queryForm() {
  //koodi poistettu tarpeettomana 21.12.2001 / Jani
}

// find Form
function findForm() {
	//koodi poistettu tarpeettomana 21.12.2001 / Jani
}

// process query
function sendQueryString(newString) {
	newString = makeXMLsafe(newString);
	setQueryString=newString;
	selectionMode=1;
	selectData.length=1;
	LayerFields.length=1;
	LayerFieldType.length=1;
	LayerFieldCount=0;
	showBuffer=false;
	showRetrieveData();
	var theString = writeQueryXML(newString);
	sendToServer(imsQueryURL,theString,50);
}

// write out XML request to query attributes
function writeQueryXML(queryString) {
	if (swapSelectFields) {
		selectFields=selFieldList[ActiveLayerIndex];
	}
	var theString = '<?xml version="1.0" encoding="UTF-8"?>\n<ARCXML version="1.1">\n<REQUEST>\n';
	theString += '<GET_FEATURES outputmode="xml" geometry="false" envelope="true"';
	theString += ' compact="true" featurelimit="' + maxFeaturesReturned + '" beginrecord="' + queryStartRecord + '">\n';
	theString += '<LAYER id="' + ActiveLayer + '" />';
	if (useLimitExtent) {
		// keep this within the limitExtent
		theString += '<SPATIALQUERY subfields="' + selectFields + '" where="' + queryString + '">';
		theString += '<SPATIALFILTER relation="area_intersection">\n';
		//theString += '<ENVELOPE maxx="' + limitRight + '" maxy="' + limitTop + '" minx="' + limitLeft + '" miny="' + limitBottom + '" />\n';
		theString += '<ENVELOPE maxx="' + forceComma(limitRight) + '" maxy="' + forceComma(limitTop) + '" minx="' + forceComma(limitLeft) + '" miny="' + forceComma(limitBottom) + '" />\n';
		theString += '</SPATIALFILTER>\n';
		theString += '</SPATIALQUERY>\n';
	} else {
	//theString += '<QUERY subfields="' + selectFields + '" where="' + queryString + '" />';
	theString += '<SPATIALQUERY subfields="' + selectFields + '" where="' + queryString + '" />';
	}
	theString += '</GET_FEATURES>';
	theString += '</REQUEST>';
	theString += '</ARCXML>';
	selectLayer=ActiveLayer;
	selectType=ActiveLayerType;
	selectCount=0;
	hightlightedOne="";
	selectPoints.length=1;
	selectLeft.length=1;
	selectRight.length=1;
	selectTop.length=1;
	selectBottom.length=1;
	return theString;
}

// write out XML request to get field value samples
function writeFieldSample(theField,Haku,HakuLayer) {
	var theFields = theField;
        var theString = '<?xml version="1.0" encoding="UTF-8"?>\n<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="false"';
	theString += ' compact="true" featurelimit="' + numberDataSamples + '">\n';
        theString += '<LAYER id="' + HakuLayer + '" />';
        if(Haku == "osoite") {
            if(osoitepaikannus_geo == true) {
                if(municUpperCase == true)//Lisätty 16.5.2003 by Jani
                  kunta = kunta.toUpperCase();
	        if(haeosoitteita == false)
                    theString += '<QUERY subfields="' + theFields + '" where=" ' + geo_field + ' like \'A%\' AND ' + munic_field + ' = \'' + kunta + '\' "/>';
	        else
		    theString += '<QUERY subfields="' + theFields + '" where=" ' + geo_field + ' like \'' + tienalku + '\' AND ' + munic_field + ' = \'' + kunta + '\' "/>';
	    }
            else if(osoitepaikannus_rak == true) {
	        if(haeosoitteita == false)
                    theString += '<QUERY subfields="' + theFields + '" where=" ' + theFields +' like \'A%\' "/>';
	        else
		    theString += '<QUERY subfields="' + theFields + '" where=" ' + theFields + ' like \'' + tienalku + '\' "/>';
	    }
        }
        if(Haku == "numero") {
                theString += '<QUERY subfields="LAHIOSOITT" where=" ' + theFields +' LIKE \'' + tienimi + '\' "/>';
        }
        if(Haku == "nimisto" || Haku == "alue") {
                theString += '<QUERY subfields="' + theFields + '"/>';
        }
	theString += '</GET_FEATURES>';
	theString += '</REQUEST>';
	theString += '</ARCXML>';
	selectLayer=ActiveLayer;
	selectType=ActiveLayerType;
	selectCount=0;
	hightlightedOne="";
	selectPoints.length=1;
	selectLeft.length=1;
	selectRight.length=1;
	selectTop.length=1;
	selectBottom.length=1;
        //alert(theString);
	return theString;
}


// send find request
function getFind(theValue) {
  //koodi poistettu tarpeettomana 21.12.2001 / Jani
}
// write out find form
function writeFindRequest(findQuery,fieldList) {
	var theString = '<?xml version="1.0" encoding="UTF-8"?>\n<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" geometry="false" envelope="true"';
	theString += ' compact="true" featurelimit="' + maxFeaturesReturned + '" beginrecord="' + queryStartRecord + '">\n';
	theString += '<LAYER id="' + ActiveLayer + '" />\n';
	if (useLimitExtent) {
		// keep this within the limitExtent
		theString += '<SPATIALQUERY subfields="' + fieldList + '" where="' + findQuery + '" />';
		theString += '<SPATIALFILTER relation="area_intersection">\n';
		theString += '<ENVELOPE maxx="' + forceComma(limitRight) + '" maxy="' + forceComma(limitTop) + '" minx="' + forceComma(limitLeft) + '" miny="' + forceComma(limitBottom) + '" />\n';
        	theString += '</SPATIALFILTER>\n';
		theString += '</SPATIALQUERY>\n';
	} else {
	theString += '<QUERY subfields="' + fieldList + '" where="' + findQuery + '" />';
	}
	theString += '</GET_FEATURES>\n';
	theString += '</REQUEST>\n';
	theString += '</ARCXML>';
	selectLayer=ActiveLayer;
	selectType=ActiveLayerType;
	selectCount=0;
	hightlightedOne="";
	selectPoints.length=1;
	selectLeft.length=1;
	selectRight.length=1;
	selectTop.length=1;
	selectBottom.length=1;
	return theString;
}


//replace the original function parseFieldSamples with this function parseFieldSamples
// parse layer field value samples
function parseFieldSamples(theReply,Haku) {
	var fList="";
	var lpos1 = 1, lpos2 = 1, epos = 1, spos = 1;
	var morePoints=true, moreFeatures=true;
	var pos = 0, startpos = 0, endpos = 0;
	var featureCount = justGetFeatureCount(theReply);
	hasmorevalue = justGetHasMoreValue(theReply);
	var tempString="";
	var k = 1;
	var sdLeng = 0;
        //alert(theReply);
        if(Haku == "osoite") {
            if(osoitelista.length>0) {
                osoitelista.length=0;
            }
        }
        if(Haku == "numero") {
        if(numerolista.length>0) {
                numerolista.length=0;
            }
        }
        if(Haku == "nimisto") {
            if(nimistolista.length>0) {
                nimistolista.length=0;
            }
        }
        if(Haku == "alue") {
            if(aluelista.length>0) {
                aluelista.length=0;
            }
        }

	if(featureCount > 0) {
	// Add the first sample value
		for (var i=0;i<1;i++) {
			if (selectData.length>0) {
				selectData.length=0;
			}
			pos = theReply.indexOf("<FIELDS ",endpos);
			if(Haku == "osoite")
                          startpos = pos + 9 + osoitekentanpituus;
                        if(Haku == "numero")
                          startpos = pos + 9 + numerokentanpituus;
                        if(Haku == "nimisto")
                          startpos = pos + 9 + nimistokentanpituus;
                        if(Haku == "alue")
                          startpos = pos + 9 + aluekentta[valittu_aluejako].length;


                        endpos =theReply.indexOf(' />',startpos);
			inData = theReply.substring(startpos,endpos);
                        selectData[i] = inData;
		}

		// Add additional sample values
		for (var i=1;i<featureCount;i++) {
			pos = theReply.indexOf("<FIELDS ",endpos);
			if(Haku == "osoite")
                          startpos = pos + 9 + osoitekentanpituus;
                        if(Haku == "numero")
                          startpos = pos + 9 + numerokentanpituus;
                        if(Haku == "nimisto")
                          startpos = pos + 9 + nimistokentanpituus;
                        if(Haku == "alue")
                          startpos = pos + 9 + aluekentta[valittu_aluejako].length;

                        endpos =theReply.indexOf(' />',startpos);
			inData = theReply.substring(startpos,endpos);
			sdLeng = selectData.length;

			for (var j=0;j<sdLeng;j++){
				if (selectData[j] == inData){
					addValue = false;
					break;
				} else {
					addValue = true;
				}
			}

			if(addValue) {
				selectData[k] = inData;
				k = k + 1;
			}
		}

	}
	else {
		selectData.length=0;
		kohteitanolla = true;
	}

	if(selectData.length>0) {
		var testSample = selectData[0];
		testPos = testSample.indexOf('"');
		testStartPos = testPos+1;
		testEndPos = testSample.indexOf('"',testStartPos);
		testValue = testSample.substring(testStartPos,testEndPos);
		testLeng = testValue.length;
		//Test for non-numeric characters in the string
		for (l=0;l<testLeng;l++){
			testChar = testValue.substring(l+1);
			testChar = Number(testChar);
			if (isNaN(testChar)) {
				var charSort = true;
				break;
			}
		}
                if(Haku == "numero")
                  charSort = true;
		if (charSort) {
			selectData.sort();
		}
		else {
                        selectData.sort(compare);
		}

		for(var loop=0;loop<selectData.length;loop++){
			selectData[loop] = PoistaHipsut(selectData[loop]);
                        selectData[loop] = Muunnavalilyonti(selectData[loop]);
                }
	}
        if(Haku == "osoite") {
            for(var loop=0;loop<selectData.length;loop++){
                osoitelista[loop] = selectData[loop];
            }
        }
	if(Haku == "numero") {
		var selects = new Array();

		for(var loop=0;loop<selectData.length;loop++) {
			var selectdata_sp = selectData[loop].split(/[a-z|-]/);
			
			if(selects[parseInt(selectdata_sp[0])] == null)
				selects[parseInt(selectdata_sp[0])] = new Array();
			selects[parseInt(selectdata_sp[0])][selects[parseInt(selectdata_sp[0])].length] = selectData[loop];
		}
		numerolista = selects.join(",").split(",");
            parent.TextFrame.document.location = appDir + "addmatch_buil.html";
        }
        if(Haku == "nimisto") {
            nimistolista[0] = "-Valitse kohde-";
            for(var loop=0;loop<selectData.length;loop++){
                nimistolista[loop + 1] = selectData[loop];
            }
		parent.ToolFrame.document.location = appDir + "toolframe.html";
        }
        if(Haku == "alue") {
            aluelista[0] = "-Valitse kaikki alueet-";
            for(var loop=0;loop<selectData.length;loop++){
                aluelista[loop + 1] = selectData[loop];
            }
            sendMapXML();
            parent.TextFrame.document.location = appDir + "areaSearch.html";
        }
}

//add this below the new function parseFieldSamples
//function to compare numeric values for function parseFieldSamples numeric sort
function compare(a,b){

	var aPos = a.indexOf('"');
	var aStartPos = testPos+1;
	var aEndPos = a.indexOf('"',aStartPos);
	var aValue = a.substring(aStartPos,aEndPos);
	var aNum = Number(aValue);

	var bPos = b.indexOf('"');
	var bStartPos = testPos+1;
	var bEndPos = b.indexOf('"',bStartPos);
	var bValue = b.substring(bStartPos,bEndPos);
	var bNum = Number(bValue);

	return aValue - bValue;

	return 0;

}

