// ===========================================================================================
// NAVIGATION MAP CLIENT SIDE INTERFACE
//-------------------------------------------------------------------------------

// Ensure 'undefined' is defined.
var undefined;

var TASK_BROWSE = 0;
var TASK_SEARCH = 2;
var TASK_SEARCH_RESULTS = 3;

// opens Report List Page and applies search corresponding to the search criteria
// values submitted in function's four string arguments

function SearchReportFolders(i_SearchString, i_SearchRange, i_SearchType, i_SearchProperties)
{
	var ObjWdsForm = document.getElementById("WdsForm");	
	ObjWdsForm.IF_Task.value = 3
	ObjWdsForm.IF_SearchString.value = i_SearchString;
	ObjWdsForm.IF_SearchRange.value = i_SearchRange;	
	// possible values are AND, OR, EXACT and ANY_EQUAL
	// with geographies mapped to item codes we recommend using ANY_EQUAL
	ObjWdsForm.IF_SearchType.value = i_SearchType;
	ObjWdsForm.IF_SearchProperties.value = i_SearchProperties;
	ObjWdsForm.IF_SearchFromMap.value = "True";
	ObjWdsForm.action = G_strRootPath + "/ReportFolders/reportFolders.aspx";
	executeWait(ObjWdsForm);
}


// ----------------------------------------------------------------------------
// opens report specified by its unique Id in table view mode and applies
// geographical selection in i_strSelection -- january 2005 - EMC3
function OpenReportWithItemsSelected2(i_nReportId, i_nMapDim, i_strSelection)
{
	if (typeof(ObjWdsForm) == 'undefined') {
           location = G_strRootPath + "/statec/TableViewer/tableView.aspx?ReportId=" + i_nReportId + "&IF_SearchString=" + i_strSelection;	
	}
	else {
		CreateHiddenFormField(ObjWdsForm, "WD_MapDimension", i_nMapDim);
		GenerateNewWindow("_Wds2", "/TableViewer/tableView.aspx?ReportId=" + i_nReportId + "&IF_SearchString=" + i_strSelection);
	}
}

// ----------------------------------------------------------------------------
// opens report specified by its unique Id in table view mode and applies
// item selection corresponding to the search criteria submitted in the second
// argument
function OpenReportWithItemsSelected(i_ReportId, i_SearchString, i_SearchType)
{
   // the search will look in table items only (PROP_ITEMS)
	if (typeof(ObjWdsForm) == 'undefined') {
		location = G_strRootPath + "/TableViewer/tableView.aspx?ReportId=" + i_ReportId;
	}
	else {
		ObjWdsForm.IF_SearchString.value = i_SearchString;
		ObjWdsForm.IF_SearchType.value = i_SearchType;
		ObjWdsForm.action = G_strRootPath + "/TableViewer/tableView.aspx?ReportId=" + i_ReportId;
		executeWait(ObjWdsForm);
	}
}

// ----------------------------------------------------------------------------
// opens Report List Page and applies item selection profiles submitted as string
// containing a list of unique profile Ids separated by commas

function ActivateProfiles(i_ProfileIds, i_ProfileNames)
{
   var objForm = ObjWdsForm;
   var astrProfiles = new Array;
   var nIndex;
   var strStatus;   

   if (typeof(objForm) == 'undefined') {
		location = G_strRootPath + "/ReportFolders/reportFolders.aspx";
   }
   else {
	  astrProfiles = i_ProfileIds.split(",");
	  strStatus = "";
      for (nIndex = 0; nIndex < astrProfiles.length; nIndex++) {
      strStatus = strStatus + "1,"
      }	
      objForm.PR_ProfileApplied.value = "True";
      objForm.PR_NumberOfProfiles.value = astrProfiles.length;
      objForm.PR_ActiveProfileList.value = i_ProfileIds;
      objForm.PR_MostRecentlyUsedProfileIds[0].value = i_ProfileIds;
      objForm.PR_MostRecentlyUsedProfileNames[0].value = i_ProfileNames;
      objForm.PR_MostRecentlyUsedProfileStatus[0].value = strStatus;      
	  objForm.action = G_strRootPath + "/ReportFolders/reportFolders.aspx";
	  executeWait(objForm);
   }
}

// ----------------------------------------------------------------------------
// opens Report Folders page without applying search
function GoToReportFolders()
{
	if (typeof(ObjWdsForm) == 'undefined') {
		location = G_strRootPath + "/ReportFolders/reportFolders.aspx";
	}
	else {
		ObjWdsForm.action = G_strRootPath + "/ReportFolders/reportFolders.aspx";
		executeWait(ObjWdsForm);
	}
}

// ----------------------------------------------------------------------------
// used by mapping client to submit error in displaying map
function SubmitErrorConditionFromMappingClient()
{
    var objForm = ObjWdsForm;

	if (typeof(ObjWdsForm) == 'undefined') {
		location = document.location.pathname;
	}
	else {
        objForm.NM_NavMapError.value = "Error";	
		ObjWdsForm.action = document.location.pathname;
		executeWait(ObjWdsForm);
	}
}

//------------------------------------------------------------------------------
// takes boolean corresponding to help display mode and opens appropriate
// help file

function OnHelpWindow(bOnTab)
{
   var szAnchor = "MapView.htm";
   OpenHelpWindow(szAnchor, bOnTab);
}

// The functions below are included in the interface, but their purpose is to 
// exercise client side server request with getInfoForMap.aspx file
//------------------------------------------------------------------------------
// This function loads the XML document from the specified URL, and when
// it is fully loaded, passes that document and the url to the specified
// handler function. This function works with any XML document
function getXMLData(i_url, i_handler)
{

   var strRequest = "";
   var xmlHttp;
	var url;
    ObjWdsForm.NM_MapProperties.value = "sample";
   // I shouldn't use this to differentiate between IE and Netscape.
	// Use the standard DOM Level 2 technique, if it is supported
	if( document.implementation && document.implementation.createDocument ) {
		// Create a new XML request object.
      xmlHttp = new XMLHttpRequest();
   }
	// Otherwise use Microsoft's proprietary API for Internet Explorer
   else {
		// Create a new XML request object.
		try
		{
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch( ex )
		{
			try
			{
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch( ex )
			{
				//alert( ex )
			}
		}
   }
	if (xmlHttp != undefined) {
      // Specify a function to get called when the XML is loaded
		xmlHttp.onreadystatechange = function()
		{
			if (xmlHttp.readyState == 4) {
				i_handler(xmlHttp.responseXML, i_url);
			}
		}
      xmlHttp.open("POST", i_url, true);
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlHttp.setRequestHeader("Accept-Language", G_strLanguage);
      strRequest = createRequest(ObjWdsForm);
      xmlHttp.send(strRequest);
	}
}

//------------------------------------------------------------------------------
// This function creates a string from the FORM elements, so that it can be posted
// to the server.
function createRequest(i_clForm)
{
   var clFormField;
   var clFormFields;
   var strName;
   var strTag;
   var strValue;
   var strRequest = "";
   var unIndex;
   var unFieldCount = 0;

   // Make sure the form object is defined.
   if (i_clForm != undefined) {
      clFormFields = i_clForm.childNodes;
      // For each INPUT form field, create a string "name=value".  Join all of
      // these strings with the "&" character.  The result will look something
      // like: "sWD_TableId=1&sWD_ChartType=5&PR_ProfileApplied=False".
      for (unIndex = 0; unIndex < clFormFields.length; unIndex++) {
         clFormField = clFormFields.item(unIndex);
         // Only use "element" nodes.
         if (clFormField.nodeType == 1) {
            strTag = clFormField.tagName;
            // Only use INPUT tags.
            if (strTag.toUpperCase() == "INPUT") {
               // Don't add "&" if it's the first INPUT tag found.
               if (unFieldCount > 0) {
                  strRequest += "&";
               }
               strName = clFormField.getAttribute("name");
               strRequest += strName + "=";
               strValue = clFormField.getAttribute("value");
               strRequest += URIencode(strValue);
               unFieldCount++;
            }
         }
      }
   }

   return strRequest;
}

//--------------------------------------------------------------------------------------------
// This function gets the new XML data 
function receiveXMLData( xmldoc, url){
	//debug( "ğreceiveXMLData( " + url + " )" );

	// Check for errors in loading the XML (IE).
	if( xmldoc.parseError && ( xmldoc.parseError.errorCode != 0 ) )
		{
		alert( "parseError " + xmldoc.parseError.reason + " (" + xmldoc.parseError.errorCode + ")" );
		//debug( "ĞreceiveXMLData() failed" );
		return;
		}
	// Check for errors in loading the XML (NN).
	if( xmldoc.documentElement == null )
		{
		alert( "Error loading XML file." );
		//debug( "ĞreceiveXMLData() failed" );
		return;
		}
	//debug( "ĞreceiveXMLData()" );
	parseXMLData(xmldoc);
}


//--------------------------------------------------------------------------------------------
// This function provides an example of parsing of the XML string received from the server  
function parseXMLData(xmldoc){
   // The dimension indexes as specified in the XML document by the "id" attribute of each dimension
   var rowDimIDs = new Array();
   var colDimIDs = new Array();
   var otherDimIDs = new Array();

	//debug( "ğparseXMLData( " + url + " )" );

	// Check for errors in loading the XML (IE).
	if( xmldoc.parseError && ( xmldoc.parseError.errorCode != 0 ) )
		{
		alert( "parseError " + xmldoc.parseError.reason + " (" + xmldoc.parseError.errorCode + ")" );
		//debug( "ĞparseXMLData() failed" );
		return;
		}
	// Check for errors in loading the XML (NN).
	if( xmldoc.documentElement == null )
		{
		alert( "Error loading XML file." );
		//debug( "ĞparseXMLData() failed" );
		return;
		}

	// Get the row, column and other labels.
	var isGroup;
	var index;
	var dimIndex;
	var rowLabelArrays;
	var colLabelArrays;
	var otherLabelArray;
	var otherIDs;
	var otherIsGroup
	var colLabelSpans;
	var rowLabelSpans;
	var rowCount = 0;
	var colCount = 0;

	// Get the other dimension labels and IDs
	var otherDim;
	var otherLabel;
	var otherLabels;
	var dimID;
	var otherDims = xmldoc.getElementsByTagName("OtherDim");
	otherLabelArray = new Array(otherDims.length);
	otherIDs = new Array(otherDims.length);
	otherIsGroup = new Array(otherDims.length);
	for (dimIndex = 0; dimIndex < otherDims.length; dimIndex++) {
		otherDim = otherDims[dimIndex];

		// get the dimension ID from the <OtherDimLabel> tag
		otherLabel = otherDim.getElementsByTagName("OtherDimLabel")[0];		
		dimID = otherLabel.getAttribute("id");
		otherDimIDs[dimIndex] = parseInt(dimID.substr(3));

		// get the item label from the <ItemLabel> tag
		otherLabels = otherDim.getElementsByTagName("ItemLabel")[0];
		isGroup = otherLabels.getAttribute("isgroup");
		if (isGroup == "y") {
			otherIsGroup[dimIndex] = true;
		}
		else {
			otherIsGroup[dimIndex] = false;
		}
		otherIDs[dimIndex] = otherLabels.getAttribute("itemcode");
		otherLabelArray[dimIndex] = otherLabels.firstChild.data;
	}

	// Get the column labels, IDs and spans
	var colDim;
	var colLabel;
	var colLabels;
	var colSpan;
	var colIDs;
	var colIsGroup;
	var colDims = xmldoc.getElementsByTagName("ColDim");
	colLabelArrays = new Array(colDims.length);
	colIDs = new Array(colDims.length);
	colIsGroup = new Array(colDims.length);
	colLabelSpans = new Array(colDims.length);
	for (dimIndex = 0; dimIndex < colDims.length; dimIndex++) {
		colDim = colDims[dimIndex];

		// get the dimension ID from the <DimLabel> tag
		colLabel = colDim.getElementsByTagName("DimLabel")[0];		
		dimID = colLabel.getAttribute("id");
		colDimIDs[dimIndex] = parseInt(dimID.substr(3));

		// get the item label and span from the <ColLabel> tag
		colLabels = colDim.getElementsByTagName("ColLabel");
		colLabelArrays[dimIndex] = new Array(colLabels.length);
		colIDs[dimIndex] = new Array(colLabels.length);
		colIsGroup[dimIndex] = new Array(colLabels.length);
		colLabelSpans[dimIndex] = new Array(colLabels.length - 1);
		for (index = 0; index < colLabels.length; index++) {
			colLabel = colLabels[index];
			isGroup = colLabel.getAttribute("isgroup");
			if (isGroup == "y") {
				colIsGroup[dimIndex][index] = true;
			}
			else {
				colIsGroup[dimIndex][index] = false;
			}
			colIDs[dimIndex][index] = colLabel.getAttribute("itemcode");
			colLabelArrays[dimIndex][index] = colLabel.firstChild.data;

			// get the span of nesting dimension labels
			if (dimIndex < colDims.length - 1) {
				colSpan = null;
				colSpan = colLabel.attributes.getNamedItem("colspan");
				if (colSpan == null) {
					colLabelSpans[dimIndex][index] = 1;
				}
				else {
					colLabelSpans[dimIndex][index] = parseInt(colSpan.firstChild.data);
				}
			}
		}
	}
	colCount = colLabelArrays[colDims.length - 1].length;

	// Get the footnote indicators
	var footIndicators = new Array();
	var footnotes;
	var pos;
	footnotes = xmldoc.getElementsByTagName("Footnote");
	for (index = 0; index < footnotes.length; index++) {
		footnote = footnotes[index];
		pos = footnote.getAttribute("position");
		pos = parseInt(pos);
		footIndicators[pos] = footnote.getElementsByTagName("FootnoteLang")[0].getAttribute("indicator");
	}
	
	// Get the row labels and cell values.
	var rowIndex;
	var rowLabel;
	var rowLabels;
	var rowDims = xmldoc.getElementsByTagName("RowDim");
	var row;
	var rowSpan;
	var rows = xmldoc.getElementsByTagName("Row");
	var rowLabelCounts = new Array(rowDims.length);
	var rowDataArray = new Array();
	var cells;
	var cell;
	var rowData;
	var dimIndex;
	var footIndex;
	var rowIsGroup;
	var rowIDs;

	rowLabelArrays = new Array(rowDims.length);
	rowIDs = new Array(rowDims.length);
	rowIsGroup = new Array(rowDims.length);
	rowLabelSpans = new Array(rowDims.length - 1);
	for (index = 0; index < rowDims.length; index++) {
		rowLabelArrays[index] = new Array();
		rowIDs[index] = new Array();
		rowIsGroup[index] = new Array();
		rowLabelCounts[index] = 0;
		if (index < rowDims.length - 1) {
			rowLabelSpans[index] = new Array();
		}

		// get the dimension ID from the <RowDim> tag
		dimID = rowDims[index].getAttribute("id");
		rowDimIDs[index] = parseInt(dimID.substr(3));
	}
	for (rowIndex = 0; rowIndex < rows.length; rowIndex++) {
		row = rows[rowIndex];
		rowLabels = row.getElementsByTagName("RowLabel")
		for (index = 0; index < rowLabels.length; index++) {
			dimIndex = rowDims.length - rowLabels.length + index;

			// get the item label and span from the <RowLabel> tag
			rowLabel = rowLabels[index];
			isGroup = rowLabel.getAttribute("isgroup");
			if (isGroup == "y") {
				rowIsGroup[dimIndex][rowLabelCounts[dimIndex]] = true;
			}
			else {
				rowIsGroup[dimIndex][rowLabelCounts[dimIndex]] = false;
			}
			rowIDs[dimIndex][rowLabelCounts[dimIndex]] = rowLabel.getAttribute("itemcode");
			rowLabelArrays[dimIndex][rowLabelCounts[dimIndex]] = rowLabel.firstChild.data;

			// get the span of nesting dimension labels
			if (dimIndex < rowDims.length - 1) {
				rowSpan = null;
				rowSpan = rowLabel.attributes.getNamedItem("rowspan");
				if (rowSpan == null) {
					rowLabelSpans[dimIndex][rowLabelCounts[dimIndex]] = 1;
				}
				else {
					rowLabelSpans[dimIndex][rowLabelCounts[dimIndex]] = parseInt(rowSpan.firstChild.data);
				}
			}
			rowLabelCounts[dimIndex]++;
		}
		cells = row.getElementsByTagName("C");
		rowData = new Array();
		for (index = 0; index < cells.length; index++) {
			rowData[index] = "";
			cell = cells[index];
			footnotes = cell.getElementsByTagName("F");
			if (footnotes.length > 0) {
				// there are footnotes
				rowData[index] = "(";
				for (footIndex = 0; footIndex < footnotes.length; footIndex++) {
					pos = footnotes[footIndex].getAttribute("pos");
					pos = parseInt(pos);
					if (footIndex > 0) {
						rowData[index] = rowData[index] + ",";
					}
					rowData[index] = rowData[index] + footIndicators[pos];
				}
				rowData[index] = rowData[index] + ") ";
			}
			rowData[index] = rowData[index] + cell.firstChild.data;
		}
		rowDataArray[rowIndex] = rowData;
	}
	rowCount = rowLabelArrays[rowDims.length - 1].length;
}

// -----------------------------------------------------------------------------
function Task(i_nTask)
{
	ObjWdsForm.sRF_Task.value = i_nTask;
	if (i_nTask == TASK_SEARCH) {
		ObjWdsForm.action = "../ReportFolders/AdvancedSearch.aspx";
	}
	executeWait(ObjWdsForm);
}

// ----------------------------------------------------------------------------
function submitNPSForm()	{
	if (ObjWdsForm.RF_SearchString != undefined)	{
		var szWord = ObjWdsForm.RF_SearchString.value;
	}
	//var szLink = "http://www.gouvernement.lu/functions/search/simpleResultPage.php?search_text=" + szWord + "&baseQuery=";
	var szLink = "/fr/functions/search/simpleResultPage.php?search_text=" + szWord + "&baseQuery=";
	ObjWdsForm.action = szLink;
	ObjWdsForm.submit();
}

