/**************************************************************
 * Flash Client Application TestPage/SDK                      *
 *------------------------------------------------------------*
 * File: 		demo.js    		                                    *
 * Author:	BV 				                                        *
 * Desc:		This script handles the javascript functions      *
 *					for this testpage/sdk								              *
 *------------------------------------------------------------*
 *(C) Bentley Systems Netherlands BV, 2006                    *
 **************************************************************/

/**************************************************************
 ************ Constants and global variables ******************
 **************************************************************/
var isIE = (document.all) ? true : false;
var sVersion = "2.0.0";
var xmlns = "http://www.bentley.com/FlexiMap"
var xmlns_xsi = "http://www.w3.org/2001/XMLSchema-instance";
var xsi_schemaLocation = "http://www.bentley.com/FlexiMap FMRequest.xsd";
var tempXML;
var host = window.location.hostname;
var sqList = new Array(); //array to store all the available searches for a service

var bSecureService; // boolean defining if service is secure (useservicekey = true)

var exposedParams; //string that will be used to catch all the parameters exposed by Flash

// Global variables used in demo catch functions
var service;
var mapwidth;
var mapheight;
var mapresolution;
var xcoord;
var ycoord;
var servicekey;
var maplayers;
var fm;
var rlpoint = new Array();
var searchCoords;


/**************************************************************
 ************************* Functions **************************
 **************************************************************/

/*------------------------------------------------------------*
 * function called from report (shows links in report)        *
 *------------------------------------------------------------*/
function showLink(sUrl)
{

  window.open( sUrl );
				
  //if( null == parent.doc)
  //{
  //  doc.location.href = sUrl;
  //}
  //else
  //{
  //  parent.doc.location.href = sUrl;
  //}  
}


/*------------------------------------------------------------*
 * fleximap:                                                  *
 * This function will be used by Flash to expose parameters   *
 * Function must be named "fleximap" and accept 1 parameter   *
 * Content can be adjusted to suit specific needs             *
 *------------------------------------------------------------*/
function fleximap(params)
{
	//alert(params);
	var arrAllParams = params.split('|');
	for (var i = 0;i< arrAllParams.length;i++)
	{
		var tmp = arrAllParams[i];
		var arrOneParam = arrAllParams[i].split('=');
		var param = arrOneParam[0].toLowerCase();
		var val= arrOneParam[1];

		switch (param) {
		case 'fm':
			fm=val;
			break;
		case 'servicekey':
			servicekey=val;
			break;
		case 'service':
			service=val;
			break;
		case 'mapwidth':
			mapwidth=val;
			break;
		case 'mapheight':
			mapheight=val;
			break;
		case 'mapresolution':
			mapresolution=val;
			break;
		case 'xcoord':
			xcoord=val;
			break;
		case 'ycoord':
			ycoord=val;
			break;
		case 'maplayers':
			maplayers=val;
			break;
		case 'redline':
			if (val.toUpperCase()=='CLEAR') {
				rlpoint.length=0;
			}
			else {
				rlpoint.addItem(val);
			}
			break;
	 	case 'info':
			//infopoint.addItem(val);
			searchCoords=val;
			break;
		}
	}
	//now clear the variables that have been exposed
	exposedParams='';
	return;
}


/*------------------------------------------------------------*
 * addParams:                                                 *
 * This function will be used by Flash to expose parameters   *
 * Function must be named "addParams" and accept 1 parameter  *
 * ==============Content must NOT be changed================= *
 * If string from Flash is too long, this function will be    *
 * called until entire string is passed                       *
 *------------------------------------------------------------*/
function addParams(params)
{
	// DO NOT PUT ALERT BOXES IN THIS FUNCTION
	// FUNCTION IS CALLED WITH AN INTERVAL
	exposedParams += params;
}
/*------------------------------------------------------------*
 * submitParams:                                              *
 * This function will be called from Flash when the entire    *
 * string is transferred to addParams                         *
 * Now a function can be called to process the exposed params *
 *------------------------------------------------------------*/
function submitParams()
{
	//alert(exposedParams);

	//now call the function fleximap, to be backward compatible
	fleximap(exposedParams);
}

/*------------------------------------------------------------*
 * getServicekey:                                             *
 * This function will start a serverside script to obtain a   *
 * service key.                                               *
 * Use of ServiceKey necessary if service is secure           *
 *------------------------------------------------------------*/
function getServiceKey()
{
  var selService = document.getElementById("services");
	var sServiceName = selService.options[selService.selectedIndex].value;
	var sUrl = 'servicekey.asp?' + sServiceName;
  parent.fraExec.location.href = sUrl;
}


/*------------------------------------------------------------*
 * storeServicekey:                                           *
 * This function will store the generated servicekey.         *
 * Will be used in buildStartParams.                          *
 * NOTE:This function is called from a child frame,           *
 * so parent needs to be used to access variables.            *
 *------------------------------------------------------------*/
function storeServiceKey(sKey)
{
	// store the generated key
	parent.document.frmmain.key.value = sKey;

	if (parent.bSecureService)
	{
		var sLogoHtml= '<center><img src="./images/bentleylogo_big2.gif"></center>';
	}
	else
	{
		var sLogoHtml= '<center><img src="./images/bentleylogo_big.gif"></center>';
	}
	sLogoHtml += '<center><font class="bannertlt"><b>';
	sLogoHtml += sKey;
	sLogoHtml += '</b></font></center>';
	var divFlash = parent.document.getElementById("flashMovie");
  divFlash.innerHTML = sLogoHtml;
}


/*------------------------------------------------------------*
 * showParams:                                                *
 * This function shows all the parameters exposed by Flash    *
 * These parameters have been "catched" & stored in function  *
 * "fleximap"                                                 *
 *------------------------------------------------------------*/
function showParams()
{
	var sHTMLtext = '<br><font class="txt"><b>Values that have been exposed by the flash movie:</b><br>';
	sHTMLtext += 'fm= ' + fm + '<br>';
	sHTMLtext += 'service= ' + service + '<br>';
	sHTMLtext += 'servicekey= ' + servicekey + '<br>';
	sHTMLtext += 'mapwidth= ' + mapwidth + '<br>';
	sHTMLtext += 'mapheight= ' + mapheight + '<br>';
	sHTMLtext += 'mapresolution= ' + mapresolution + '<br>';
	sHTMLtext += 'xcoord= ' + xcoord + '<br>';
	sHTMLtext += 'ycoord= ' + ycoord + '<br>';
	sHTMLtext += 'maplayers= ' + maplayers + '<br>';

	if (searchCoords != '')
	{
		sHTMLtext += 'search coordinates= ' + searchCoords + '<br>';
	}

  if(rlpoint.length > 0)
  {
    for(var idx = 0; idx < rlpoint.length; idx++)
    {
			sHTMLtext += 'redlined object= ' + rlpoint[idx] + '<br>';
    }
  }

	sHTMLtext += '</font>';

	var oInfo = document.getElementById("divInfo");
	oInfo.innerHTML = sHTMLtext;
	oInfo.style.height = '500px';
	oInfo.style.width = '350px';
	var oIFrame = parent.document.getElementById("fraExec");
	oIFrame.style.height = '0px';
}


/*------------------------------------------------------------*
 * showMap:                                                   *
 * This function will create and show a GetMap request        *
 * based on the parameters exposed by Flash                   *
 *------------------------------------------------------------*/
function showMap()
{
	var sHTMLtext ='<form name="infoForm" encoding="text/plain">';
  sHTMLtext += '<input type="hidden" name="xml"/></form>';
	document.getElementById("divInfo").innerHTML = sHTMLtext;
  setTimeout("ReCreateMap()", 100);
  return;
}


/*------------------------------------------------------------*
 * retrieveXML:                                               *
 * Post XML to server and return the XML response             *
 *------------------------------------------------------------*/
function retrieveXML(sendXML)
{
 
  var xmlObj;
  if(isIE)
  {
    xmlObj = new ActiveXObject("MSXML2.XMLHTTP");
  }
  else
  {
    xmlObj = new XMLHttpRequest();
  }
  xmlObj.open("POST","http://" + window.location.hostname + "/scripts/fleximap.dll", false);
  xmlObj.setRequestHeader("Content-Length", sendXML.length);
  xmlObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
  xmlObj.send(sendXML);

  return xmlObj.responseXML;
}


/*------------------------------------------------------------*
 * Array_addItem:                                             *
 *------------------------------------------------------------*/
function Array_addItem(item)
{
  this[this.length] = item;
  return item;
}
Array.prototype.addItem = Array_addItem;


/*------------------------------------------------------------*
 * ReCreateMap:                                               *
 * Create a GetMap request (called from showMap)              *
 *------------------------------------------------------------*/
function ReCreateMap()
{
  var frag;
  // Create a new XMLDOM object
  if(isIE)
  {
    frag = new ActiveXObject("Microsoft.XMLDOM");
  }
  else
  {
    frag = document.implementation.createDocument("", "", null);
  }

  var fragRoot = frag.createElement("fragroot");
  frag.appendChild(fragRoot);

  var fragRequest = frag.createElement("FMGetMap");
  fragRoot.appendChild(fragRequest);
  fragRequest.setAttribute("version", sVersion);
  fragRequest.setAttribute("xmlns", xmlns);
  fragRequest.setAttribute("xmlns:xsi", xmlns_xsi);
  fragRequest.setAttribute("xsi:schemaLocation", xsi_schemaLocation);

  var fragService = frag.createElement("Service");
  var fragServiceText = frag.createTextNode(service);
  fragService.appendChild(fragServiceText);
  fragRequest.appendChild(fragService);

	// add the servicekey element if needed
	if (bSecureService)
	{
		var secKey = parent.document.frmmain.key.value;
		if (secKey == '')
		{
			alert('This is a secure service, please get a valid servicekey');
			return false;
		}
		else
		{
			var fragServiceKey = frag.createElement("ServiceKey");
			var fragServiceKeyText = frag.createTextNode(secKey);
		  fragServiceKey.appendChild(fragServiceKeyText);
  		fragRequest.appendChild(fragServiceKey);
		}
	}

  var fragContentType = frag.createElement("ContentType");
  fragRequest.appendChild(fragContentType);
  fragContentType.appendChild(frag.createTextNode("image/png"));

  var fragMapWidth = frag.createElement("MapWidth");
  fragRequest.appendChild(fragMapWidth);
  fragMapWidth.appendChild(frag.createTextNode(mapwidth));

  var fragMapHeight = frag.createElement("MapHeight");
  fragRequest.appendChild(fragMapHeight);
  fragMapHeight.appendChild(frag.createTextNode(mapheight));

  var fragMapRes = frag.createElement("MapResolution");
  fragRequest.appendChild(fragMapRes);
  fragMapRes.appendChild(frag.createTextNode(mapresolution));

  var fragXCoord = frag.createElement("XCoord");
  fragRequest.appendChild(fragXCoord);
  fragXCoord.appendChild(frag.createTextNode(xcoord));

  var fragYCoord = frag.createElement("YCoord");
  fragRequest.appendChild(fragYCoord);
  fragYCoord.appendChild(frag.createTextNode(ycoord));

  if(rlpoint.length > 0)
  {
    var fragRLInfo = frag.createElement("RedlineInfo");
    fragRequest.appendChild(fragRLInfo);

    for(var idx = 0; idx < rlpoint.length; idx++)
    {
      var fragRedline = frag.createElement("Redline");
      fragRLInfo.appendChild(fragRedline);
      fragRedline.appendChild(frag.createTextNode(rlpoint[idx]));
    }
  }

  var sendXML;
  if(isIE)
  {
    sendXML = fragRequest.xml;
  }
  else
  {
    var ser = new XMLSerializer();
    sendXML = ser.serializeToString(fragRequest);
  }

  tempXML = sendXML;
  setTimeout("waitAndSend(document.infoForm)", 100);

  var oIFrame = document.getElementById('fraExec');
	oIFrame.style.height = '500px';
	var oInfo = document.getElementById("divInfo");
	oInfo.style.height = '0px';

  return;
}


/*------------------------------------------------------------*
 * waitAndSend:                                               *
 *------------------------------------------------------------*/
function waitAndSend(myForm)
{
  myForm.xml.value = tempXML;
  myForm.method = "post";
  myForm.action = "http://" + window.location.hostname + "/scripts/FlexiMap.dll";
  myForm.target= "fraExec";
  myForm.submit();
  return;
}


/*----------------------------------------------------------------*
 * Search:                                                        *
 * Constructor for SearchObject                                   *
 *----------------------------------------------------------------*/
function Search(SQname, colnames, aliases)
{
	this.name = SQname;				// Initialize SearchName
  this.columns = colnames;	// Initialize column names (seperated by pipes)
  this.aliases = aliases;		// Initialize column aliases (seperated by pipes)
	this.answers ='';					// Used to store the answers (seperated by pipes)
}


/*------------------------------------------------------------*
 * getServices:                                               *
 * Get a list of available services on this Server            *
 * This function is called in the onload event of the website *
 *------------------------------------------------------------*/
function getServices()
{
  var frag;
  if(isIE)
  {
    frag = new ActiveXObject("Microsoft.XMLDOM");
  }
  else
  {
    frag = document.implementation.createDocument("", "", null);
  }

  var fragRoot = frag.createElement("fragroot");
  frag.appendChild(fragRoot);

  var fragRequest = frag.createElement("FMGetServiceList");
  fragRoot.appendChild(fragRequest);
  fragRequest.setAttribute("version", sVersion);
  fragRequest.setAttribute("xmlns", xmlns);
  fragRequest.setAttribute("xmlns:xsi", xmlns_xsi);
  fragRequest.setAttribute("xsi:schemaLocation", xsi_schemaLocation);

  var sendXML;
  if(isIE)
  {
    sendXML = fragRequest.xml;
  }
  else
  {
    var ser = new XMLSerializer();
    sendXML = ser.serializeToString(fragRequest);
  }

  var responseXML = retrieveXML(sendXML);
  var responseTag = responseXML.documentElement.tagName;

  var elServices = responseXML.documentElement.getElementsByTagName("Services")[0];
  var cboServ = document.getElementById("services");

  cboServ.options.length = 0;
  cboServ.options[0] = new Option("-- Select --", "");

  for(idx = 0; idx < elServices.childNodes.length; idx++)
  {
    elItem = elServices.childNodes[idx];
    if(elItem.childNodes.length > 0)
    {
    	cboServ.options[cboServ.options.length] = new Option(elItem.childNodes[0].nodeValue, elItem.childNodes[0].nodeValue);
		}
  }
  return true;
}


/*----------------------------------------------------------------*
 * getAvailSearches:                                              *
 * Parse SendFlashGUI and retrieve info for the avaiable Searches *
 * This function is called after selecting a service              *
 *----------------------------------------------------------------*/
function getAvailSearches()
{
  var selService = document.getElementById("services");
	var sServiceName = selService.options[selService.selectedIndex].value;
	sqList = new Array();

  var frag;
  if(isIE) {
    frag = new ActiveXObject("Microsoft.XMLDOM");
  }
  else {
    frag = document.implementation.createDocument("", "", null);
  }

  var fragRoot = frag.createElement("fragroot");
  frag.appendChild(fragRoot);

  var fragRequest = frag.createElement("FMGetFlashGUI");
  fragRoot.appendChild(fragRequest);
  fragRequest.setAttribute("version", sVersion);
  fragRequest.setAttribute("xmlns", xmlns);
  fragRequest.setAttribute("xmlns:xsi", xmlns_xsi);
  fragRequest.setAttribute("xsi:schemaLocation", xsi_schemaLocation);

  var fragService = frag.createElement("Service");
  var fragServiceText = frag.createTextNode(sServiceName);
  fragService.appendChild(fragServiceText);
  fragRequest.appendChild(fragService);

  var fragMapW = frag.createElement("MapWidth");
  var fragMapWtxt = frag.createTextNode("100");
  fragMapW.appendChild(fragMapWtxt);
  fragRequest.appendChild(fragMapW);

  var fragMapH = frag.createElement("MapHeight");
  var fragMapHtxt = frag.createTextNode("100");
  fragMapH.appendChild(fragMapHtxt);
  fragRequest.appendChild(fragMapH);

  var sendXML;
  if(isIE) {
    sendXML = fragRequest.xml;
  }
  else {
    var ser = new XMLSerializer();
    sendXML = ser.serializeToString(fragRequest);
  }

  var responseXML = retrieveXML(sendXML);
  var responseTag = responseXML.documentElement.tagName;


	// clear dropdownlist for avail searches
  var cboSearches = document.getElementById("searches");
  cboSearches.options.length = 0;
  cboSearches.options[0] = new Option("-- Select --", "");
	var divCols = document.getElementById("divCols");
	divCols.innerHTML = '';

  // check if GetFlashGUI returned an error
  var errNode = responseXML.documentElement.getElementsByTagName("ServiceException")[0];
	if (errNode)
	{
		alert('GetFlashGUI request returned an error.\nThe currently selected service cannot be used in this testpage.');
		return false;
	}

  // check if service key is needed
  var keyNode = responseXML.documentElement.getElementsByTagName("UseServiceKey")[0];
	if (keyNode.firstChild.nodeValue.toLowerCase() == 'true')
	{
		bSecureService = true;
		parent.document.frmmain.key.value = '';
		var sLogoHtml= '<center><img src="./images/bentleylogo_big2.gif"></center>';
	}
	else
	{
		bSecureService = false;
		var sLogoHtml= '<center><img src="./images/bentleylogo_big.gif"></center>';
	}
  var divFlash = document.getElementById("flashMovie");
  divFlash.innerHTML = sLogoHtml;



  var TNode = responseXML.documentElement.getElementsByTagName("SearchQueries")[0];
	for (var ch_node = TNode.firstChild; ch_node != null; ch_node = ch_node.nextSibling)
	{
		var sSQAlias = ch_node.getAttribute("alias");
		var sSQName = ch_node.getAttribute("name");
		if (sSQAlias == "")
		{
		  sSQAlias = sSQName;
		}
		cboSearches.options[cboSearches.options.length] = new Option(sSQAlias, sSQName);

		// loop through all columns and strore them in Javascript SQ Objects
	  var sCols='';
	  var sAliases='';
		for (var col_node = ch_node.childNodes[0].firstChild; col_node != null; col_node = col_node.nextSibling)
		{
			sCols += "|" + col_node.firstChild.nodeValue;
			sAliases +=  "|" + col_node.getAttribute("label");
		}
		sCols = sCols.substr(1);
		sAliases = sAliases.substr(1);
		var oSearch = new Search(sSQName,sCols,sAliases);
		sqList.addItem(oSearch);

	}
  return true;
}


/*----------------------------------------------------------------*
 * getSearchCols:                                                 *
 * Get all columns for currently selected Search                  *
 * This function is called after selecting a search               *
 *----------------------------------------------------------------*/
function getSearchCols()
{
  // clear current searchcolumns
	var divCols = document.getElementById("divCols");
	divCols.innerHTML = '';

	var selSearch = document.getElementById("searches");
	var sSearchName = selSearch.options[selSearch.selectedIndex].value;
	for(var i = 0; i < sqList.length; i++) {
		var oSearch = sqList[i];
		if (sSearchName == oSearch.name)
		{
			var sHtml='';
			var arrCols = oSearch.columns.split('|');
			var arrAlias = oSearch.aliases.split('|');
			for(var j = 0; j < arrCols.length; j++)
			{
				sHtml += '<font class="txtsmall">' + arrAlias[j] +  ':</font><br><select style="width: 150px;" id=' + arrCols[j] + ' name=' + arrCols[j] + ' onchange="getQuestion('+ (j+1) +')"></select><br>';
			}
			divCols.innerHTML = sHtml;
		}
	}
	// now load the first question
	getQuestion(0);
}


/*----------------------------------------------------------------*
 * getQuestion:                                                   *
 * Create GetList request for current question                    *
 * Show result in dropdownlist                                    *
 *----------------------------------------------------------------*/
function getQuestion(iQNum)
{
  var selService = document.getElementById("services");
	var sServiceName = selService.options[selService.selectedIndex].value;
	var selSearch = document.getElementById("searches");
	var sSearchName = selSearch.options[selSearch.selectedIndex].value;
	var oSearch;

	for(var i = 0; i < sqList.length; i++)
	{
		if (sSearchName == sqList[i].name)
		{
			oSearch = sqList[i];
			break;
		}
	}
	var arrCols = oSearch.columns.split('|');
	if (iQNum == arrCols.length)
	{
		storeAnswers(oSearch,iQNum);
		buildStartParams(1);
	}
	else
	{
		var frag;
		if(isIE)
		{
			frag = new ActiveXObject("Microsoft.XMLDOM");
		}
		else
		{
			frag = document.implementation.createDocument("", "", null);
		}

		if (iQNum == 0) // first question, load all distinct values
		{
			var fragRoot = frag.createElement("fragroot");
			frag.appendChild(fragRoot);

			var fragRequest = frag.createElement("FMGetList");
			fragRoot.appendChild(fragRequest);
			fragRequest.setAttribute("version", sVersion);
			fragRequest.setAttribute("xmlns", xmlns);
			fragRequest.setAttribute("xmlns:xsi", xmlns_xsi);
			fragRequest.setAttribute("xsi:schemaLocation", xsi_schemaLocation);

			var fragService = frag.createElement("Service");
			var fragServiceText = frag.createTextNode(sServiceName);
			fragService.appendChild(fragServiceText);
			fragRequest.appendChild(fragService);

			// add the servicekey element if needed
			if (bSecureService)
			{
				var secKey = parent.document.frmmain.key.value;
				if (secKey == '')
				{
					alert('This is a secure service, please get a valid servicekey');
					// now clear the lists with the questions
					selSearch.selectedIndex=0;
					var divCols = document.getElementById("divCols");
					divCols.innerHTML = '';
					return false;
				}
				else
				{
					var fragServiceKey = frag.createElement("ServiceKey");
					var fragServiceKeyText = frag.createTextNode(secKey);
				  fragServiceKey.appendChild(fragServiceKeyText);
		  		fragRequest.appendChild(fragServiceKey);
				}
			}

			var fragSQ = frag.createElement("SearchQuery");
			fragSQ.setAttribute("name", sSearchName);
			fragRequest.appendChild(fragSQ);
			var fragSQCol = frag.createElement("Column");
			fragSQCol.setAttribute("name", arrCols[iQNum]);
			fragSQ.appendChild(fragSQCol);

		}
		else // not the first question,we need answers to previous questions
		{
			// store answer to previous questions
			storeAnswers(oSearch,iQNum);
			var arrAnswers = oSearch.answers.split('|');

			// now create the GetList request for the new question
			var fragRoot = frag.createElement("fragroot");
			frag.appendChild(fragRoot);

			var fragRequest = frag.createElement("FMGetList");
			fragRoot.appendChild(fragRequest);
			fragRequest.setAttribute("version", sVersion);
			fragRequest.setAttribute("xmlns", xmlns);
			fragRequest.setAttribute("xmlns:xsi", xmlns_xsi);
			fragRequest.setAttribute("xsi:schemaLocation", xsi_schemaLocation);

			var fragService = frag.createElement("Service");
			var fragServiceText = frag.createTextNode(sServiceName);
			fragService.appendChild(fragServiceText);
			fragRequest.appendChild(fragService);

			// add the servicekey element if needed
			if (bSecureService)
			{
				var secKey = parent.document.frmmain.key.value;
				if (secKey == '')
				{
					alert('This is a secure service, please get a valid servicekey');
					return false;
				}
				else
				{
					var fragServiceKey = frag.createElement("ServiceKey");
					var fragServiceKeyText = frag.createTextNode(secKey);
				  fragServiceKey.appendChild(fragServiceKeyText);
		  		fragRequest.appendChild(fragServiceKey);
				}
			}

			var fragSQ = frag.createElement("SearchQuery");
			fragSQ.setAttribute("name", sSearchName);
			fragRequest.appendChild(fragSQ);

			//loop through old question and answers
			for(var iCnt = 0; iCnt < iQNum; iCnt++) {
				var fragSQCol = frag.createElement("Column");
				fragSQCol.setAttribute("name", arrCols[iCnt]);
				fragSQCol.appendChild(frag.createTextNode(arrAnswers[iCnt]));
				fragSQ.appendChild(fragSQCol);
			}
			// now the latest Question
			var fragSQCol = frag.createElement("Column");
			fragSQCol.setAttribute("name", arrCols[iQNum]);
			fragSQ.appendChild(fragSQCol);
		}

		// occupy a dropdownlist with the result
		var sendXML;
		if(isIE)
		{
			sendXML = fragRequest.xml;
		}
		else
		{
			var ser = new XMLSerializer();
			sendXML = ser.serializeToString(fragRequest);
		}

		var responseXML = retrieveXML(sendXML);
		var responseTag = responseXML.documentElement.tagName;

		if(responseTag == "FMServiceExceptionReport")
		{
			alert("An error has occurred:\nReason: " +
				responseXML.getElementsByTagName("Reason")[0].childNodes[0].nodeValue + "\nDescription: " +
				responseXML.getElementsByTagName("Description")[0].childNodes[0].nodeValue);
			return false;
		}

		//alert(new XMLSerializer().serializeToString(responseXML.documentElement));
		var elColumn = responseXML.documentElement.getElementsByTagName("Column")[0];
		var droplist = document.getElementById(arrCols[iQNum]);
		droplist.options.length = 0;
		droplist.options[0] = new Option("-- Select --", "");

		for(idx = 0; idx < elColumn.childNodes.length; idx++)
		{
			elItem = elColumn.childNodes[idx];
			if(elItem.childNodes.length > 0)
			{
				droplist.options[droplist.options.length] = new Option(elItem.childNodes[0].nodeValue, elItem.childNodes[0].nodeValue);
			}
		}
	}
  return true;
}


/*----------------------------------------------------------------*
 * storeAnswers:                                                  *
 * Store the selected answers to search questions                 *
 * This function is called from getQuestion                       *
 *----------------------------------------------------------------*/
function storeAnswers(oSearch, iQuestionNum)
{
	var arrCols = oSearch.columns.split('|');
	var sAnswer='';
	for(var i = 0; i < iQuestionNum; i++)
	{
		var oCol = document.getElementById(arrCols[i]);
		sAnswer += '|' + oCol.options[oCol.selectedIndex].value;
	}
	oSearch.answers = sAnswer.substr(1);
}


/*---------------------------------------------------------------------*
 * buildStartParams:                                                   *
 * Initialize Flash with parameters provided in the website            *
 * This function is called from getQuestion OR the "start Flash"Button *
 *---------------------------------------------------------------------*/
function buildStartParams(startMode)
{
  // variables that we always need
  var selService = document.getElementById("services");
	var sServiceName = selService.options[selService.selectedIndex].value;

	// build string with startparmaters for Flash Client
	var sClientParams = "fmClient.swf?fm=http://"+ host + "/Scripts/FlexiMap.dll";
	sClientParams += "&commurl=report.asp&commtarget=fraExec";
	sClientParams += "&service=" + sServiceName;

	var startlyrs = document.getElementById("startlyrs").value;
	if (startlyrs != ''){
		sClientParams += "&startlayers=" + startlyrs;
	}

	// add the servicegroup parameter if needed
	var servgroup = document.getElementById("servicegroup").value;
	if (servgroup != '')
	{
		sClientParams += "&servicegroup=" + servgroup;
	}

	// add the highlight parameter if needed
	var bHlite = document.getElementById("highlight").checked;
	if (bHlite)
	{
		sClientParams += "&highlight=true";
	}


	// add the servicekey parameter if needed
	if (bSecureService)
	{
		var secKey = parent.document.frmmain.key.value;
		if (secKey == '')
		{
			alert('This is a secure service, please get a valid servicekey');
			return false;
		}
		else
		{
			sClientParams += "&servicekey=" + secKey;
		}
	}


	switch (startMode)
  {
	  case 0: //start flash without sq or xy parameters
			//only servicename and optionally servicegroup) need to be passed
			break;

	  case 1: //start flash with sq parameters

			var selSearch = document.getElementById("searches");
			var sSearchName = selSearch.options[selSearch.selectedIndex].value;
			var oSearch;
			//-- Get the right search object
			for(var i = 0; i < sqList.length; i++) {
				if (sSearchName == sqList[i].name)
				{
					oSearch = sqList[i];
					break;
				}
			}
			var arrCols = oSearch.columns.split('|');
			var arrAnswers = oSearch.answers.split('|');
			var sPairs='';
			for(var j = 0; j < arrCols.length ; j++) {
				sPairs += '&' + arrCols[j] + '=' + arrAnswers[j];
			}

			sClientParams += "&sq=" + sSearchName + sPairs;
			break;

		case 2: //start flash with xy parameters

		  var x = document.getElementById("xcoord").value;
		  var y = document.getElementById("ycoord").value;
			var mapres = document.getElementById("mapres").value;

			var lyrs = document.getElementById("lyrs").value;
			var keys = document.getElementById("keys").value;

			if (x !='' && y !='' && mapres !='') {
				sClientParams += "&xcoord=" + x + "&ycoord=" + y;
				sClientParams += "&mapresolution=" + mapres;

				sClientParams += "&layers=" + lyrs;
				sClientParams += "&keys=" + keys;
		}
  		break;

	}

	// call function that (re)initializes Flash
	startFlash(sClientParams);
	//alert(sClientParams);

}


/*----------------------------------------------------------------*
 * startFlash:                                                    *
 * Initialize Flash with specific startparameters                 *
 * This function is called from buildStartParams OR highlightObj  *
 *----------------------------------------------------------------*/
function startFlash(sClientParams)
{
	var mapWidth=450;
	var mapHeight=500;

	var flashHtml = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'";
	flashHtml += "codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0'";
	flashHtml += "WIDTH='"+ mapWidth + "' HEIGHT='"+ mapHeight + "' id='fmClient' ALIGN='middle'>";
	flashHtml += "<param name=movie value='"+ sClientParams + "'>";
	flashHtml += "<param name=allowScriptAccess value='sameDomain'>";
	flashHtml += "<param name=quality value='high'>";
	flashHtml += "<param name=bgcolor value='#'>";
	flashHtml += "<param name=scale value='noscale'>";
	flashHtml += "<embed src='"+ sClientParams + "' quality=high bgcolor=# WIDTH='"+ mapWidth + "' HEIGHT='"+ mapHeight + "' scale='noscale' NAME='fmClient'";
	flashHtml += "align='middle' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed>";
	flashHtml += "</object>";

/*

	var flashHtml = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'";
	flashHtml += "codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0'";
	flashHtml += "WIDTH='100%' HEIGHT='100%' id='fmClient' ALIGN='middle'>";
	flashHtml += "<param name=movie value='"+ sClientParams + "'>";
	flashHtml += "<param name=allowScriptAccess value='sameDomain'>";
	flashHtml += "<param name=quality value='high'>";
	flashHtml += "<param name=bgcolor value='#'>";
	flashHtml += "<param name=scale value='noscale'>";
	flashHtml += "<param name=wmode value='transparent'>";
	flashHtml += "<embed src='"+ sClientParams + "' quality=high wmode='transparent' bgcolor=# WIDTH='" + mapWidth + "' HEIGHT='" + mapHeight + "' scale='noscale' NAME='fmClient'";
	flashHtml += "align='middle' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer'></embed>";
	flashHtml += "</object>";
*/


//	alert(flashHtml);

  var divFlash = document.getElementById("flashMovie");
  divFlash.innerHTML = flashHtml;


	var divonTop = document.getElementById("onTop");
  //divonTop.innerHTML = 'dit is een ontop test';

}


/*----------------------------------------------------------------*
 * highlightObj:                                                  *
 * Initialize Flash with layer and keys	parameters to highlight   *
 * This function is called from a Report                          *
 *----------------------------------------------------------------*/
function highlightObj(param)
{
	var sClientParams = "fmClient.swf?fm=http://"+ host + "/Scripts/FlexiMap.dll";
	sClientParams += "&commurl=report.asp&commtarget=fraExec";
	sClientParams += "&service=" + service;

	if (maplayers != ''){
		sClientParams += "&startlayers=" + maplayers;
	}

	// add the servicekey parameter if needed
	if (bSecureService)
	{
		var secKey = parent.document.frmmain.key.value;
		if (secKey == '')
		{
			alert('This is a secure service, please get a valid servicekey');
			return false;
		}
		else
		{
			sClientParams += "&servicekey=" + secKey;
		}
	}
	sClientParams += "&highlight=true";
	sClientParams += "&xcoord=" + xcoord + "&ycoord=" + ycoord;
	sClientParams += "&mapresolution=" + mapresolution;
	sClientParams += "&" + param;

	// now start Flash
	startFlash(sClientParams);
}
