/**************************************************
FreeanceXMLParser.js
	XML parser for the freeance configuration libraries
	extends the base xml parser, adding appropriate
	functions for dealing with the possible freeance
	extensions and core modules.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Dependancies:
	XMLParser-base.js
	Util.js
	X.js

**************************************************/

FreeanceXMLParser = function(newID){};
FreeanceXMLParser.prototype = new XMLParser();
FreeanceXMLParser.prototype.constructor = FreeanceXMLParser;
FreeanceXMLParser.superclass = XMLParser.prototype;

FreeanceXMLParser.prototype.getApplicationConfig = function()
{
	var appNode = this.xmlDoc.getElementsByTagName('applicationConfig')[0];
	var styleindex=this.getNextNamedChildNodeIndex(appNode,0,"stylesheet");
	var customLayoutIndex = this.getNextNamedChildNodeIndex(appNode,0,"customOptions");
	var mapUnitIndex = this.getNextNamedChildNodeIndex(appNode,0,"mapUnits");
	var nodeIndex = this.getNextNamedChildNodeIndex(appNode,0,"userScripts");
	return {
		id: this.decodeSTRING(appNode.childNodes[this.getNextNamedChildNodeIndex(appNode,0,"applicationId")]),
		organization: this.decodeSTRING(appNode.childNodes[this.getNextNamedChildNodeIndex(appNode,0,"organization")]),
		title: this.decodeSTRING(appNode.childNodes[this.getNextNamedChildNodeIndex(appNode,0,"title")]),
		clientType: this.decodeSTRING(appNode.childNodes[this.getNextNamedChildNodeIndex(appNode,0,"clientType")]),
		stylesheet: (styleindex==-1)?'default':this.decodeSTRING(appNode.childNodes[styleindex]),
		administrator: this.decodeSTRING(appNode.childNodes[this.getNextNamedChildNodeIndex(appNode,0,"administrator")]),
		adminEmail: this.decodeSTRING(appNode.childNodes[this.getNextNamedChildNodeIndex(appNode,0,"adminEmail")]),
		customOptions: ((customLayoutIndex!=-1)?(this.parseApplicationCustomOptions(appNode.childNodes[customLayoutIndex])):(null)),
		mapUnits: (mapUnitIndex > -1)?(this.decodeSTRING(appNode.childNodes[mapUnitIndex])):('FT'),
		userScripts: (nodeIndex==-1)?(Array()):(this.parseUserScripts(appNode.childNodes[nodeIndex]))
	};
};

FreeanceXMLParser.prototype.parseUserScripts = function(parentNode)
{
	var config = [];
	var scriptNodes = parentNode.getElementsByTagName('scriptfile');
	for (var i=0;i<scriptNodes.length;i++)
		config.push(scriptNodes[i].getAttribute('url'));
	return config;
};

FreeanceXMLParser.prototype.parseApplicationCustomOptions = function (customNode)
{
	var activepanelindex=this.getNextNamedChildNodeIndex(customNode,0,"defaultActivePanel");
	var redrawIndex = this.getNextNamedChildNodeIndex(customNode,0,"mapAutoRedraw");
	var deselectIndex = this.getNextNamedChildNodeIndex(customNode,0,"clickDeselect");
	var freezeIndex = this.getNextNamedChildNodeIndex(customNode,0,"freezeTableHeader");
	var legendIndex=this.getNextNamedChildNodeIndex(customNode,0,"customLegendURL");
	var scriptIndex = this.getNextNamedChildNodeIndex(customNode,0,"customScriptURL");
	var expandSearchIndex =  this.getNextNamedChildNodeIndex(customNode,0,"expandSearch");
	var childNodes = customNode.childNodes;
	return {
		pageHeaderHeight: this.decodeINT(childNodes[this.getNextNamedChildNodeIndex(customNode,0,"pageHeaderHeight")]),
		rightPanelWidth: this.decodeINT(childNodes[this.getNextNamedChildNodeIndex(customNode,0,"rightPanelWidth")]),
		mapToolOptionHeight: this.decodeINT(childNodes[this.getNextNamedChildNodeIndex(customNode,0,"mapToolOptionHeight")]),
		vicinityMapWidthOpen: this.decodeINT(childNodes[this.getNextNamedChildNodeIndex(customNode,0,"vicinityMapWidthOpen")]),
		homeLinkHeight: this.decodeINT(childNodes[this.getNextNamedChildNodeIndex(customNode,0,"homeLinkHeight")]),
		defaultActivePanel: (activepanelindex>-1)?(this.decodeSTRING(childNodes[activepanelindex])):('userIntro'),
		mapAutoRedraw: (redrawIndex==-1)?(true):(this.decodeINT(childNodes[redrawIndex])==1),
		clickDeselect: (deselectIndex==-1)?(true):(this.decodeINT(childNodes[deselectIndex])==1),
		expandSearch: (expandSearchIndex==-1)?(false):(this.decodeINT(childNodes[expandSearchIndex])==1),
		freezeTableHeader: (freezeIndex==-1)?(true):(this.decodeINT(childNodes[freezeIndex])==1),
		customLegendURL: (legendIndex==-1)?(''):(this.decodeSTRING(childNodes[legendIndex])),
		customScriptURL: (scriptIndex==-1)?(''):(this.decodeSTRING(childNodes[scriptIndex])),
		showDisclaimer: (customNode.getElementsByTagName('showDisclaimer')[0])?(this.decodeSTRING(customNode.getElementsByTagName('showDisclaimer')[0]) == 'true'):(false),
		disclaimerText: (customNode.getElementsByTagName('disclaimerText')[0])?(this.decodeSTRING(customNode.getElementsByTagName('disclaimerText')[0])):(''),
		disclaimerURL: (customNode.getElementsByTagName('disclaimerURL')[0])?(this.decodeSTRING(customNode.getElementsByTagName('disclaimerURL')[0])):(''),
		layerControlLabel: (customNode.getElementsByTagName('layerControlLabel')[0])?(this.decodeSTRING(customNode.getElementsByTagName('layerControlLabel')[0])):('Layer Control'),
		selectionControlLabel: (customNode.getElementsByTagName('selectionControlLabel')[0])?(this.decodeSTRING(customNode.getElementsByTagName('selectionControlLabel')[0])):('Feature Selection Manager'),
		markupControlLabel: (customNode.getElementsByTagName('markupControlLabel')[0])?(this.decodeSTRING(customNode.getElementsByTagName('markupControlLabel')[0])):('Markup Tools'),
		bookmarkControlLabel: (customNode.getElementsByTagName('bookmarkControlLabel')[0])?(this.decodeSTRING(customNode.getElementsByTagName('bookmarkControlLabel')[0])):('Map Bookmarks')
	};
};

FreeanceXMLParser.prototype.getMapConfig = function()
{
	var mapNode = this.xmlDoc.getElementsByTagName('map')[0];
	var vmapNodes = mapNode.getElementsByTagName('vicinityMap');
	var loginQueryNodes = mapNode.getElementsByTagName("loginQuery");
	var printNodes = mapNode.getElementsByTagName("pdfPrintConfig");
	var exportNodes = mapNode.getElementsByTagName('exportConfig');
	var proxSearchNodes = mapNode.getElementsByTagName('proximitySearchConfig');
	var mapSchemeNodes = mapNode.getElementsByTagName('mapSchemeDefinitions');

	var legendAttributeIndex = this.__helper__getNextElementNamedChildNode(mapNode,0,"legendAttributes");
	var legendIndex = this.__helper__getNextElementNamedChildNode(mapNode,0,"legend");
	var legendAttributes = this.parseLegendAttributes(mapNode.childNodes[(legendAttributeIndex>-1)?legendAttributeIndex:legendIndex]);
	var seamlessPanIdx=this.__helper__getNextElementNamedChildNode(mapNode,0,"seamlessPan");
	var seamlessPan = false;
	if(seamlessPanIdx!=-1)
		seamlessPan=(mapNode.childNodes[seamlessPanIdx].getAttribute('enabled')=='true');
	var projectionId = 0;
	var projectionIdx = this.__helper__getNextElementNamedChildNode(mapNode,0,'projectionId');
	if(projectionIdx!=-1)
		projectionId=(mapNode.childNodes[projectionIdx].getAttribute('value')!=null)?(parseInt(mapNode.childNodes[projectionIdx].getAttribute('value'))):(this.decodeINT(mapNode.childNodes[projectionIdx]));

  var themeDefs = this.parseThemeDefinitions(mapNode.getElementsByTagName("themeDefinitions")[0]);
    
	var mapConfig = {
		configNode:mapNode,
		id: mapNode.getAttribute("id"),
		resourceId: this.decodeSTRING(mapNode.getElementsByTagName("resourceId")[0]),
		imsHostname: this.decodeSTRING(mapNode.getElementsByTagName("imsHostname")[0]),
		previousStates: this.decodeINT(mapNode.getElementsByTagName("previousStates")[0]),
		vmap: (vmapNodes.length)?this.parseVMapConfig(vmapNodes[0]):null,
		themes: themeDefs[0],
    layerOrder: themeDefs[1],
		activeTheme: this.decodeSTRING(mapNode.getElementsByTagName("activeTheme")[0]),
		themeGroups: this.parseThemeGroups(mapNode),
		legendAttributes: legendAttributes,
		labelConfig: null,
		loginQuery: (loginQueryNodes.length)?this.parseMapLoginQuery(loginQueryNodes[0]):null,
		printConfig: (printNodes.length)?this.parsePdfPrintConfig(printNodes[0]):{templates: new Array,defaultTemplate: -1},
		exportConfig:(exportNodes.length)?this.parseExportConfig(exportNodes[0]):null,
		scalebarConfig:null,
		geocodeConfig:null,
		directMappingConfig:null,
		mapSchemeConfig:(mapSchemeNodes.length)?this.parseMapSchemeConfig(mapSchemeNodes[0]):{mapSchemes:[],defaultMapScheme:0},
		seamlessPan:seamlessPan,
		projectionId:projectionId,
		coordZoomToTolerance:(mapNode.getElementsByTagName('coordZoomToTolerance')[0])?(parseInt(mapNode.getElementsByTagName('coordZoomToTolerance')[0].getAttribute('value'))):(500),
    coordZoomToStyle: (mapNode.getElementsByTagName('coordZoomToStyle')[0])?(mapNode.getElementsByTagName('coordZoomToStyle')[0].getAttribute("value")):'',
    coordDisplay: (mapNode.getElementsByTagName('coordDisplay')[0])?(mapNode.getElementsByTagName('coordDisplay')[0].getAttribute("value")):'dd',
    defaultSelection:mapNode.getElementsByTagName('themeDefinitions')[0].getAttribute("defaultSelection")
	};
	return mapConfig;
};

FreeanceXMLParser.prototype.parseThemeGroups = function(mapNode)
{
	var config = [];
	//determine type of layer control to use
	var themeGroupDefinitionNodes = mapNode.getElementsByTagName("themeGroupDefinitions");
	var layerControlNodes = mapNode.getElementsByTagName("layerControl");
	if (themeGroupDefinitionNodes.length>0) //pre-4.2 format, map to new structure
	{
		config = this.parseOldThemeGroups(themeGroupDefinitionNodes[0]);
	}
	else
	{
		//top-level is an implicit group
		for (var i=0;i<layerControlNodes[0].childNodes.length;i++)
			if (layerControlNodes[0].childNodes[i].nodeName=='groupItem')
				config.push(this.parseThemeGroupItem(layerControlNodes[0].childNodes[i]));
	};
	return config;
};

FreeanceXMLParser.prototype.parseThemeGroupItem = function(groupItemNode){
	var config = {
		type:groupItemNode.getAttribute('type'),
		name:groupItemNode.getAttribute('name'),
		layerid:groupItemNode.getAttribute('layerid'),
		toggle:groupItemNode.getAttribute('toggle')=='on',
		children:[]
	};
	if(config.type=='group' || config.type=='radio_group')
		for(var i=0;i<groupItemNode.childNodes.length;i++)
			if(groupItemNode.childNodes[i].nodeName=='groupItem')
				config.children.push(this.parseThemeGroupItem(groupItemNode.childNodes[i]));
	return config;
};

FreeanceXMLParser.prototype.parseOldThemeGroups = function(parentNode)
{
	//dprintf('loading pre-4.2 style theme groups');
	var config = [];
	var childconfig = [];
	var groupMemberNodes = null;
	var groupNodes = parentNode.getElementsByTagName('themeGroup');
	if (groupNodes.length==1) //treat as single group with label
	{
		config.push({
			type: 'label',
			name: this.decodeSTRING(groupNodes[0].getElementsByTagName('themeGroupName')[0]),
			toggle: false
		});
		groupMemberNodes = groupNodes[0].getElementsByTagName('themeGroupMember');
		for (var i=0;i<groupMemberNodes.length;i++){
			config.push({
				type:'layer',
				layerid:this.decodeSTRING(groupMemberNodes[i]),
				toggle:true
			});
		}
	}
	else
	{
		for (var i=0;i<groupNodes.length;i++){
			childconfig = [];
			groupMemberNodes = groupNodes[i].getElementsByTagName('themeGroupMember');
			for (var j=0;j<groupMemberNodes.length;j++){
				childconfig.push({
					type:'layer',
					layerid:this.decodeSTRING(groupMemberNodes[j]),
					name:'',
					toggle:true,
					children:[]
				});
			}
			config.push({
				type: 'group',
				name: this.decodeSTRING(groupNodes[i].getElementsByTagName('themeGroupName')[0]),
				layerid:'',
				toggle: false,
				children: childconfig
			});
		}
	};
	return config;
};

XMLParser.prototype.parseBufferGroupConfig = function(){
	var configNode =  this.xmlDoc.getElementsByTagName('bufferGroups');
	var config = [];
	if(configNode.item(0)){
		var groupNodes = configNode.item(0).getElementsByTagName('bufferGroup');
		for(var i = 0; i < groupNodes.length; i++){
			var layers = [];
			var layerNodes = groupNodes[i].getElementsByTagName('layer');
			for(var j = 0; j < layerNodes.length; j++){
				if(this.decodeSTRING(layerNodes[j]) != ''){
					layers.push(this.decodeSTRING(layerNodes[j]));
				}
			}
			config.push({name: groupNodes[i].getAttribute('name'), group: layers, bufferlayer: groupNodes[i].getAttribute('layer')});
		}
	} 
	return config;
};

FreeanceXMLParser.prototype.parseMapSchemeConfig = function (mapSchemeConfigNode)
{
	var mapSchemeTags = this.__helper__getRemainingNextElementNamedChildNodes(mapSchemeConfigNode,0,"mapScheme");
	var defaultMapSchemeNode = mapSchemeConfigNode.childNodes[this.__helper__getNextElementNamedChildNode(mapSchemeConfigNode,0,"defaultScheme")];
	var mapSchemes = new Array;
	if (mapSchemeTags.length > 0)
	{
		for (var i = 0; i<mapSchemeTags.length; i++)
		{
			var currentMapSchemeId = parseInt(mapSchemeTags[i].getAttribute('id'));
      if(mapSchemeTags[i].getAttribute('link')){
        mapSchemes.push({
          id: currentMapSchemeId,
          name: this.decodeSTRING(mapSchemeTags[i].childNodes[this.__helper__getNextElementNamedChildNode(mapSchemeTags[i],0,"schemeName")]),
          link: mapSchemeTags[i].getAttribute('link'),
          clientType: mapSchemeTags[i].getAttribute('clientType')
        });
      }
      else if(mapSchemeTags[i].getAttribute('extLink')){
        mapSchemes.push({
          id: currentMapSchemeId,
          name: this.decodeSTRING(mapSchemeTags[i].childNodes[this.__helper__getNextElementNamedChildNode(mapSchemeTags[i],0,"schemeName")]),
          extLink: mapSchemeTags[i].getAttribute('extLink')
        });
      }
      else{
        var themes = new Object;
        var themeTags = this.__helper__getRemainingNextElementNamedChildNodes(mapSchemeTags[i],0,"theme");
        for (var currentTheme = 0; currentTheme < themeTags.length; currentTheme++)
        {
          themeId = themeTags[currentTheme].getAttribute('id');
          themes[themeId] = {
            id: themeId,
            display: parseInt(themeTags[currentTheme].getAttribute('display')),
            legend: themeTags[currentTheme].getAttribute('legend')
          }
        }
        var layerControl = null;
        var layerControlNode = mapSchemeTags[i].getElementsByTagName('layerControl')[0];
        if(layerControlNode){
        var config = [];
        for (var j=0;j<layerControlNode.childNodes.length;j++)
          if (layerControlNode.childNodes[j].nodeName=='groupItem')
            config.push(this.parseThemeGroupItem(layerControlNode.childNodes[j]));
          layerControl = config;
        }
        var hiddenQueryNodes = mapSchemeTags[i].getElementsByTagName('hiddenQuery');
        var hiddenQueries = {};
        for(var j = 0; j < hiddenQueryNodes.length; j++){
          hiddenQueries[hiddenQueryNodes[j].getAttribute('id')] = true;
        }
        var mapTool = null;
        if(mapSchemeTags[i].getElementsByTagName('mapTool')[0]){
          mapTool = mapSchemeTags[i].getElementsByTagName('mapTool')[0].getAttribute('name');
        }
        mapSchemes.push({
          id: currentMapSchemeId,
          name: this.decodeSTRING(mapSchemeTags[i].childNodes[this.__helper__getNextElementNamedChildNode(mapSchemeTags[i],0,"schemeName")]),
          themes: themes,
          layerControl: layerControl,
          hiddenQueries: hiddenQueries,
          mapTool: mapTool
        });
      }
		}
	}
	var defScheme = parseInt(this.decodeSTRING(defaultMapSchemeNode));
	if(isNaN(defScheme)){
		defScheme = 0;
	}
	return {
		mapSchemes: mapSchemes,
		defaultMapScheme: defScheme
	};
};

FreeanceXMLParser.prototype.parseVMapConfig = function(vmapNode)
{
	return {
		id: vmapNode.getAttribute("id"),
		resourceId: this.decodeSTRING(vmapNode.childNodes[this.getNextNamedChildNodeIndex(vmapNode,0,"resourceId")]),
		slaveType: this.decodeSTRING(vmapNode.childNodes[this.getNextNamedChildNodeIndex(vmapNode,0,"slaveType")]),
		boundBoxPercentMin: this.decodeDOUBLE(vmapNode.childNodes[this.getNextNamedChildNodeIndex(vmapNode,0,"boundBoxPercentMin")]),
		styleSheet: this.decodeSTRING(vmapNode.childNodes[this.getNextNamedChildNodeIndex(vmapNode,0,"styleSheet")])
	}
};

FreeanceXMLParser.prototype.getTemplateConfig = function(templateRootNode)
{
	var templateRootNode = this.xmlDoc.getElementsByTagName('templates')[0];
	var templates = new Object();
	var htmlString = '';
	for (var templateIndex = this.getNextNamedChildNodeIndex(templateRootNode,0,"template");templateIndex!=-1;templateIndex=this.getNextNamedChildNodeIndex(templateRootNode,templateIndex+1,"template"))
	{
		for (var lcv=0;lcv < templateRootNode.childNodes[templateIndex].childNodes.length;lcv++)
		{
			if (templateRootNode.childNodes[templateIndex].childNodes.item(lcv).nodeType == 4)
				htmlString = templateRootNode.childNodes[templateIndex].childNodes.item(lcv).nodeValue;
		};
		templates[templateRootNode.childNodes[templateIndex].getAttribute("id")] = htmlString;
	};
	return templates;
};

FreeanceXMLParser.prototype.getExtensionConfig = function()
{
	var extensionConfigNode = this.xmlDoc.getElementsByTagName('extensionConfig')[0];
	var extensions = new Object();
	var extensionNodes = extensionConfigNode.getElementsByTagName('extension');
	for(var lcv=0; lcv < extensionNodes.length;lcv++)
	{
		var extension = extensionNodes[lcv];
		var name = extension.getAttribute('name');
		var enabled = extension.getAttribute('enabled');
		var module = extension.getAttribute('module');
		extensions[name] = {
			enabled: (enabled == 'true'),
			dynamicfile: extension.getAttribute('dynamicfile'),
			compressedfile: extension.getAttribute('compressedfile'),
			module: module
		};
		if (extensions[name].enabled)
		{
			var forceLoad = extension.getAttribute('forceLoad');
			extensions[name].forceLoad = ((typeof(forceLoad)=='string')?((forceLoad == 'true')?true:false):(false));
		};
		extensions[name].loaded = false;
	};
	return(extensions);
};


FreeanceXMLParser.prototype.parseThemeDefinitions = function (newNode)
{
	var themeDefinitions = {};
	var themeElements = newNode.getElementsByTagName('theme');
  var layerOrder = [];
	for (var i=0;i<themeElements.length;i++)
	{
		themeDefinitions[themeElements[i].getAttribute("id")] = this.parseTheme(themeElements[i]);
    layerOrder.push(themeElements[i].getAttribute("id"));
	};
	return [themeDefinitions,layerOrder];
};


FreeanceXMLParser.prototype.parseTheme = function (themeNode)
{
	var hideThemeValue = themeNode.getAttribute("hideTheme");
	var selectNodes = themeNode.getElementsByTagName('selectOptions');
	var bufferNodes = themeNode.getElementsByTagName('bufferOptions');
	var themeFieldsNodes = themeNode.getElementsByTagName('themeFields');
	var themeAttributes = {
		id: themeNode.getAttribute("id"),
		hideTheme: (hideThemeValue==null)?false:(hideThemeValue == 'true'),
		themeName: escapeHTML(this.decodeSTRING(themeNode.getElementsByTagName('themeName')[0])),
		selectOptions: (selectNodes.length>0)?(this.parseThemeSelectOptions(selectNodes[0])):null,
		bufferOptions: (bufferNodes.length>0)?(this.parseThemeBufferOptions(bufferNodes[0])):null,
		visibility: false,
		altLegends: new Array(),
		themeFields: themeFieldsNodes.length?this.decodeSTRING(themeFieldsNodes[0]).parseJSON():{}
	};
	var altLegends = themeNode.getElementsByTagName('altLegend');
	for(var lcv=0;lcv < altLegends.length;lcv++)
	{
		themeAttributes["altLegends"].push({
			legendName: this.decodeSTRING(altLegends[lcv].getElementsByTagName("legendName")[0]),
			legendLabel: this.decodeSTRING(altLegends[lcv].getElementsByTagName("legendLabel")[0])
		});
	};
	return themeAttributes;
};


FreeanceXMLParser.prototype.parseThemeSelectOptions = function(newNode)
{
	var keyfieldTypeNodes = newNode.getElementsByTagName('keyFieldType');
	var zoomRatioNodes = newNode.getElementsByTagName('zoomExtentRatio');
	var sqlParamNodes = newNode.getElementsByTagName('sqlParams');
	return {
		styleSheet: this.decodeSTRING(newNode.getElementsByTagName("styleSheet")[0]),
		fieldList: this.decodeSTRING(newNode.getElementsByTagName("fieldList")[0]),
		limit: this.decodeINT(newNode.getElementsByTagName("limit")[0]),
		tolerance: this.decodeDOUBLE(newNode.getElementsByTagName("tolerance")[0]),
		idField: this.decodeSTRING(newNode.getElementsByTagName("idField")[0]),
		keyField: this.decodeSTRING(newNode.getElementsByTagName("keyField")[0]),
		keyFieldType: (keyfieldTypeNodes.length)?this.decodeSTRING(keyfieldTypeNodes[0]):"OID",
		zoomExtentRatio:(zoomRatioNodes.length)?this.decodeDOUBLE(zoomRatioNodes[0]):1.2,
		resultTemplate: this.decodeSTRING(newNode.getElementsByTagName("resultTemplate")[0]),
		sqlParams: (sqlParamNodes.length)?this.parseChainedQuerySqlParams(sqlParamNodes[0]):null
	};
};



FreeanceXMLParser.prototype.parseChainedQuerySqlParams = function(sqlParamsNode)
{
	var sqlParams = [];
	var sqlParamNodeList = sqlParamsNode.getElementsByTagName('sqlParam');
	var currentParam = null;
	for(var lcv=0;lcv < sqlParamNodeList.length;lcv++)
	{
		var theNode = sqlParamNodeList[lcv];
		currentParam = {
			pdqIdentifier: this.decodeSTRING(theNode.getElementsByTagName("pdqIdentifier")[0]),
			fieldList: []
		};
		var fieldListNode = theNode.getElementsByTagName("fieldList")[0];
		var fieldNodeList = fieldListNode.getElementsByTagName('field');
		for(var fieldIndex=0;fieldIndex < fieldNodeList.length;fieldIndex++)
		{
			currentParam["fieldList"].push({
				fieldName: this.decodeSTRING(fieldNodeList[fieldIndex].getElementsByTagName("fieldName")[0]),
				pdqFieldName: this.decodeSTRING(fieldNodeList[fieldIndex].getElementsByTagName("pdqFieldName")[0])
			});
		};
		if (this.getNextNamedChildNodeIndex(theNode,0,"queryType") > -1)
		{
			currentParam["queryType"] = this.decodeSTRING(theNode.getElementsByTagName("queryType")[0]);
			currentParam["numRows"] = this.decodeINT(theNode.getElementsByTagName("numRows")[0]);
			currentParam["startAt"] = this.decodeINT(theNode.getElementsByTagName("startAt")[0]);
		}
		else  // do not want.  use full select instead
		{
			currentParam["queryType"] = '';
			currentParam["numRows"] = 0;
			currentParam["startAt"] = 0;
		};
		sqlParams.push(currentParam);
	};
	if (sqlParams.length == 0)
		sqlParams = null;
	return(sqlParams);
};

FreeanceXMLParser.prototype.parseThemeBufferOptions = function(newNode)
{
	var areaStyleNodes= newNode.getElementsByTagName("areaStyleSheet");
	var areaStyle = (areaStyleNodes.length>0)?this.decodeSTRING(areaStyleNodes[0]):'';
	var bufferAttributes = {
		styleSheet: this.decodeSTRING(newNode.getElementsByTagName("styleSheet")[0]),
		areaStyleSheet: areaStyle,
		fieldList: this.decodeSTRING(newNode.getElementsByTagName("fieldList")[0]),
		limit: this.decodeINT(newNode.getElementsByTagName("limit")[0]),
		resultTemplate: this.decodeSTRING(newNode.getElementsByTagName("resultTemplate")[0]),
		invalidTemplate: this.decodeSTRING(newNode.getElementsByTagName("invalidTemplate")[0]),
		maxSelect: this.decodeINT(newNode.getElementsByTagName("maxSelect")[0])
	};
	var sqlParamsIndex = this.getNextNamedChildNodeIndex(newNode,0,"sqlParams");
	bufferAttributes["sqlParams"] = (sqlParamsIndex > -1)?this.parseChainedQuerySqlParams(newNode.childNodes[sqlParamsIndex]):null;
	if (this.getNextNamedChildNodeIndex(newNode,0,"filterQueries") != -1)
	{
		var queryListNode = newNode.childNodes[this.getNextNamedChildNodeIndex(newNode,0,"filterQueries")];
		bufferAttributes["filterQueries"] = new Object;
		for (var queryIndex = this.getNextNamedChildNodeIndex(queryListNode,0,"query");queryIndex!=-1;queryIndex=this.getNextNamedChildNodeIndex(queryListNode,queryIndex+1,"query"))
		{
			bufferAttributes["filterQueries"][this.decodeSTRING(queryListNode.childNodes[queryIndex])] = null;
		}
	}
	else
		bufferAttributes["filterQueries"] = null;
	if (this.getNextNamedChildNodeIndex(newNode,0,"export_csv")!=-1)
	{
		if (!bufferAttributes["export"])
			bufferAttributes["export"] = new Object;
		bufferAttributes["export"].csv = new Object;
		if(this.decodeSTRING(newNode.childNodes[this.getNextNamedChildNodeIndex(newNode,0,"export_csv")]) == 'true')
		{
			bufferAttributes["export"].csv.enabled = true;
			bufferAttributes["export"].csv.delim = this.decodeSTRING(newNode.childNodes[this.getNextNamedChildNodeIndex(newNode,0,"export_csv_delim")]);
			if(this.decodeSTRING(newNode.childNodes[this.getNextNamedChildNodeIndex(newNode,0,"export_csv_includefieldnames")])=='true')
				bufferAttributes["export"].csv.includeFieldNames = true;
			else
				bufferAttributes["export"].csv.includeFieldNames = false;
		}
		else
			bufferAttributes["export"].csv.enabled = false;
	};
	return bufferAttributes;
};

FreeanceXMLParser.prototype.parseLegendAttributes = function (newNode)
{
	return (newNode.nodeName=='legendAttributes')?{
		width: this.decodeINT(newNode.getElementsByTagName('width')[0].getElementsByTagName('int')[0]),
		height: this.decodeINT(newNode.getElementsByTagName('height')[0].getElementsByTagName('int')[0]),
		color: this.decodeSTRING(newNode.getElementsByTagName('color')[0].getElementsByTagName('string')[0]),
		font: this.decodeSTRING(newNode.getElementsByTagName('font')[0].getElementsByTagName('string')[0]),
		fontSize: this.decodeINT(newNode.getElementsByTagName('fontSize')[0].getElementsByTagName('int')[0]),
		valueFontSize: this.decodeINT(newNode.getElementsByTagName('valueFontSize')[0].getElementsByTagName('int')[0]),
		cellSpacing: this.decodeINT(newNode.getElementsByTagName('cellSpacing')[0].getElementsByTagName('int')[0])
	}:{
		width: newNode.getAttribute('width'),
		height: parseInt(newNode.getAttribute('height')),
		color: newNode.getAttribute('color'),
		font: newNode.getAttribute('font'),
		fontSize: newNode.getAttribute('fontSize'),
		valueFontSize: parseInt(newNode.getAttribute('valueFontSize')),
		cellSpacing: parseInt(newNode.getAttribute('cellSpacing'))
	};
};

FreeanceXMLParser.prototype.parseMapExportConfig = function(newNode)
{
	return {enabled: newNode.getAttribute('enabled')};
};


FreeanceXMLParser.prototype.parsePdfPrintConfig = function (newNode)
{
	var printConfig = {
		templates: [],
		defaultTemplate: parseInt(newNode.getAttribute('defaultTemplate'))
	};
	var templateNodes = newNode.getElementsByTagName('template');
	for(var i=0;i<templateNodes.length;i++)
	{
		var tnode=templateNodes[i];
		var inputNodes = tnode.getElementsByTagName('userinput');
		var userinput = [];
		for (var j=0;j<inputNodes.length;j++){
			var inode=inputNodes[j];
			userinput.push({
					id:inode.getAttribute('id'),
					description:inode.getAttribute('description'),
					maxlength:parseInt(inode.getAttribute('maxlength'))
			});
		};
		printConfig.templates.push({
			displayName: this.decodeSTRING(tnode.getElementsByTagName("displayname")[0]),
			templateName: this.decodeSTRING(tnode.getElementsByTagName("templatename")[0]),
			orientation: tnode.getAttribute('orientation'),
			unit: tnode.getAttribute('unit'),
			width: parseFloat(tnode.getAttribute('width')),
			height: parseFloat(tnode.getAttribute('height')),
			mapwidth: parseFloat(tnode.getAttribute('mapwidth')),
			mapheight: parseFloat(tnode.getAttribute('mapheight')),
			userinput: userinput
		});
	};
	if ((printConfig.templates.length > 0)&&(printConfig.defaultTemplate==-1))
		printConfig.defaultTemplate = 0;
	if (printConfig.templates.length==0)
		printConfig.defaultTemplate = -1;
	printConfig.activeTemplate = printConfig.defaultTemplate;
	return printConfig;
};

FreeanceXMLParser.prototype.parseMapLoginQuery = function(queryNode)
{
	//var definedQueryNode = queryNode.childNodes[this.getNextNamedChildNodeIndex(queryNode,0,"definedQuery")];
	return null;//this.parseDefinedQuery(definedQueryNode);
};


FreeanceXMLParser.prototype.parseDefinedQuery = function(queryNode)
{
	var requestNode = queryNode.getElementsByTagName('request')[0];
	var fieldsNode = queryNode.getElementsByTagName('fieldList')[0];
	var exportNode = queryNode.getElementsByTagName('exportQuery')[0];
	var templateNode = queryNode.getElementsByTagName('resultTemplates')[0];
	var fieldList = this.parseQueryFields(fieldsNode);
	var exportConfig = (!exportNode)?({
			csv:{
				enabled: false,
				delim:',',
				includeFieldNames:true
			},
			xml:{
				enabled: false
			}
		}):({
			csv:{
				enabled: (this.decodeSTRING(exportNode.getElementsByTagName('export_csv')[0])=='true'),
				delim:this.decodeSTRING(exportNode.getElementsByTagName('export_csv_delim')[0]),
				includeFieldNames:(this.decodeSTRING(exportNode.getElementsByTagName('export_csv_includefieldnames')[0])=='true')
			},
			xml:{
				enabled: (this.decodeSTRING(exportNode.getElementsByTagName('export_xml')[0])=='true')
		}
	});

	var displayIndex = this.getNextElementNamedChildNode(queryNode,0,"display");
	var dbtypeindex = this.getNextElementNamedChildNode(requestNode,0,"dbtype");
	var config = {
		id: queryNode.getAttribute('id'),
		display: (displayIndex>-1)?(this.decodeSTRING(queryNode.childNodes[displayIndex])=='true'):true,
		title: this.decodeSTRING(queryNode.getElementsByTagName('title')[0]),
		description: this.decodeSTRING(queryNode.getElementsByTagName('description')[0]),
		HTMLForm: this.decodeSTRING(queryNode.getElementsByTagName('HTMLForm')[0]),
		fieldList:fieldList,
		request:{
			dbtype: (dbtypeindex>-1)?(this.decodeSTRING(requestNode.childNodes[dbtypeindex])):'',
			requestMethod: this.decodeSTRING(requestNode.childNodes[this.getNextElementNamedChildNode(requestNode,0,"requestMethod")]),
			pdqIdentifier: this.decodeSTRING(requestNode.childNodes[this.getNextElementNamedChildNode(requestNode,0,"pdqIdentifier")])
		},
		export_:exportConfig,
		templates:{
			validTemplate:this.decodeSTRING(templateNode.getElementsByTagName('validTemplate')[0]),
			invalidTemplate:this.decodeSTRING(templateNode.getElementsByTagName('invalidTemplate')[0]),
			emptyTemplate:this.decodeSTRING(templateNode.getElementsByTagName('emptyTemplate')[0]),
			pageRows:this.decodeINT(templateNode.getElementsByTagName('pageRows')[0])
		},
		suggestConfig:[],
		zoomto:{
			enabled: false,
			queryfield:'',
			layerfield:'',
			layerfieldtype:12,
			layerid:'',
			stylesheet:'',
			auto: false
		}
	};
	var zoomto = null;
	var zoomtoNode = null;
	for (var i=0;i<queryNode.childNodes.length;i++)
		if(queryNode.childNodes[i].nodeName=='zoomto')
			zoomtoNode = queryNode.childNodes[i];

	if(zoomtoNode){
		config["zoomto"]={
			enabled: (zoomtoNode.getAttribute("enabled") == "1"),
			queryfield:zoomtoNode.getAttribute("queryfield"),
			layerfield:zoomtoNode.getAttribute("layerfield"),
			layerfieldtype:zoomtoNode.getAttribute("layerfieldtype"),
			layerid:zoomtoNode.getAttribute("layerid"),
			stylesheet:zoomtoNode.getAttribute("stylesheet"),
			auto:(zoomtoNode.getAttribute("auto") == "true"),
			autoMaplink:(zoomtoNode.getAttribute("autoMaplink") == "true"),
			maplinkLayer:zoomtoNode.getAttribute("maplinkLayer")
		}
	};
	var suggestNodeIndex = this.getNextElementNamedChildNode(queryNode,0,"suggestConfig");
	if (suggestNodeIndex!=-1)
	{
		var suggestConfigNode = queryNode.childNodes[suggestNodeIndex];
		var suggestNodes = suggestConfigNode.getElementsByTagName('suggestInput');
		var snode=null;
		for (var i=0;i<suggestNodes.length;i++)
		{
			snode=suggestNodes[i];
			config.suggestConfig.push({
				pdqfield: snode.getAttribute('pdqfield'),
				elementId: snode.getAttribute('elementId'),
				resultElementId: snode.getAttribute('resultElementId'),
				timeout: parseInt(snode.getAttribute('timeout')),
				dbid: snode.getAttribute('dbid'),
				tablename: snode.getAttribute('tablename'),
				fieldname: snode.getAttribute('fieldname'),
				resultlimit: parseInt(snode.getAttribute('resultlimit'))
			});
		}
	};
	return config;
};

FreeanceXMLParser.prototype.parseQueryFields = function(fieldsNode)
{
	var fieldsConfig = new Array();
	for (var fieldIndex=this.__helper__getNextElementChildNode(fieldsNode,0);fieldIndex!=-1;fieldIndex=this.__helper__getNextElementChildNode(fieldsNode,fieldIndex+1))
	{
		var currentNode = fieldsNode.childNodes[fieldIndex];
		var newField = {
			fieldType: currentNode.nodeName,
			caption: '',
			fieldName: '',
			width: 0,
			defaultValue: '',
			initialValue: '',
			optionList: [],
			dynamicList:{
				dbid: '',
				table:'',
				valuefield: '',
				labelfield: '',
				whereclause:'',
				limit:10
			}
		};
		for (var i=0;i<currentNode.childNodes.length;i++){
			var fieldOptionNode=currentNode.childNodes[i];
			switch(fieldOptionNode.nodeName){
				case 'caption':
				case 'fieldName':
				case 'defaultValue':
				case 'initialValue':
					newField[fieldOptionNode.nodeName]=this.decodeSTRING(fieldOptionNode);
					break;
				case 'width':
					newField['width']=this.decodeINT(fieldOptionNode);
					break;
				case 'optionList':
					newField['optionList'] = this.parseOptionList(fieldOptionNode);
					break;
				case 'dynamicList':
					newField['dynamicList']['dbid']=fieldOptionNode.getAttribute('dbid');
					newField['dynamicList']['table']=fieldOptionNode.getAttribute('table');
					newField['dynamicList']['valuefield']=fieldOptionNode.getAttribute('valuefield');
					newField['dynamicList']['labelfield']=fieldOptionNode.getAttribute('labelfield');
					newField['dynamicList']['whereclause']=fieldOptionNode.getAttribute('whereclause');
					newField['dynamicList']['limit']=parseInt(fieldOptionNode.getAttribute('limit'));
					break;
			};
		}
		fieldsConfig.push(newField);
	}
	return fieldsConfig;
};

FreeanceXMLParser.prototype.parseOptionList = function(listParentNode)
{
	var optionList = new Array;
	for (var optionIndex=this.__helper__getNextElementChildNode(listParentNode,0);optionIndex!=-1;optionIndex=this.__helper__getNextElementChildNode(listParentNode,optionIndex+1))
	{
		var currentNode = listParentNode.childNodes[optionIndex];
		switch (currentNode.nodeName)
		{
			case 'option':
				optionList.push({
					type: 'option',
					value: currentNode.getAttribute("value"),
					label: currentNode.getAttribute("label")
				});
				break;
			case 'optgroup':
				optionList.push({
					type: 'optgroup',
					label: currentNode.getAttribute("label"),
					value: this.parseOptionList(currentNode)
				});
				break;
			default:
				break;
		}
	}
	return optionList;
};

FreeanceXMLParser.prototype.getQueryConfig = function()
{
	var config = {};
	var queryParentNode = this.xmlDoc.getElementsByTagName('queryConfig')[0];
	var definedQueryNodes = queryParentNode.getElementsByTagName('definedQuery');
	for (var i=0;i<definedQueryNodes.length;i++)
		config[definedQueryNodes[i].getAttribute("id")] = this.parseDefinedQuery(definedQueryNodes[i]);
	return config;
};


