//==========================================================================

// the stylesheet object, loaded only once..
var stylesheetDoc;
function initialize()
{

    loadStylesheet("../../includes/css/report.xsl");

}

function loadStylesheet(stylesheet)
{
	var xmlHttp=getXMLHTTPRequest();
	xmlHttp.open("GET", stylesheet, false);        
	xmlHttp.send(null);
	if(this.DOMParser) // browsers with native functionality
	{
		var dp = new DOMParser();
		stylesheetDoc = dp.parseFromString(xmlHttp.responseText, "text/xml");
		//alert("loaded");
	}
	else if(window.ActiveXObject) // Internet Explorer? 
	{
		stylesheetDoc = createMsxml2DOMDocumentObject();         
		stylesheetDoc.async = false;         
		stylesheetDoc.load(xmlHttp.responseXML);
		//alert("loaded");
	}
}

//==========================================================================

//var obj;
//var reportDivId = "testDiv";

// Creates the XMLHTTP Request object
function getXMLHTTPRequest()
{
	var xRequest=null;
	if (typeof ActiveXObject != "undefined")
	{
		xRequest = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else if (window.XMLHttpRequest)
	{	    
		xRequest = new XMLHttpRequest();
	}
	return xRequest;
}

//==========================================================================

function createMsxml2DOMDocumentObject()
{
  // will store the reference to the MSXML object
  var msxml2DOM;
  // MSXML versions that can be used for our grid
  var msxml2DOMDocumentVersions = new Array("Msxml2.DOMDocument.6.0",
                                            "Msxml2.DOMDocument.5.0",
                                            "Msxml2.DOMDocument.4.0");
  // try to find a good MSXML object
  for (var i=0; i < msxml2DOMDocumentVersions.length && !msxml2DOM; i++) 
  {
    try 
    { 
      // try to create an object
      msxml2DOM = new ActiveXObject(msxml2DOMDocumentVersions[i]);
    } 
    catch (e) {}
  }
  // return the created object or display an error message
  if (!msxml2DOM)
    alert("Please upgrade your MSXML version from \n" + 
          "http://msdn.microsoft.com/XML/XMLDownloads/default.aspx");
  else 
    return msxml2DOM;
}

//==========================================================================

// Performs a GET to our processSQL.aspx web page with the query
function sendRequest(type, query, changefunc, controlId, sBody)
{
//alert(controlId);
//alert(changefunc);
//alert(sBody);

	var obj=getXMLHTTPRequest(); 
	//var reportDivId = "reportDiv";
	if (obj!=null)
	{	
		//obj.onreadystatechange = changefunc;
		obj.onreadystatechange= function() {
// when readyState is 4, we read the server response
			if(obj.readyState == 4)
			{
		// continue only if HTTP status is "OK"
				if(obj.status == 200)
				{				
					changefunc(obj, controlId);
					obj.close();
				}
			}
			else 
			{          
				alert("Error loading page\n"+ obj.status +":"+ obj.statusText);
			}
		}		
		obj.open(type, query, true);
		obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		obj.send(sBody);
	}
	return false;
}

//==========================================================================

function convertMS(responseTxt)
{
	try
	{
	//Create a xml tag in run time
		var testandoAppend = document.createElement('xml');
	//Put the requester.responseText in the innerHTML of the xml tag
		testandoAppend.setAttribute('innerHTML',responseTxt);
	//Set the xml tag's id to _formjAjaxRetornoXML
		testandoAppend.setAttribute('id','_formjAjaxRetornoXML');
	//Add the created tag to the page context
		document.body.appendChild(testandoAppend);

	//Now we can get the xml tag and put it on a var
		xmlDoc = document.getElementById('_formjAjaxRetornoXML');
	//So we have a valid xml we can remove the xml tag
		document.body.removeChild(document.getElementById('_formjAjaxRetornoXML'));
		return xmlDoc;
	}
	catch(e)
	{
		alert(e.message);
	}
}

//==========================================================================

function updateReport(obj, reportDivId)
{
	//alert(reportDivId);
	// read the response
	response = obj.responseText;
	var reportDivCtrl = document.getElementById(reportDivId);
	// server error?
	if (response.indexOf("ERRNO") >= 0 
		|| response.indexOf("error") >= 0
		|| response.length == 0)
	{
		// display error message
		alert(response.length == 0 ? "Server serror." : response);
		return;
	}

	xmlResponse = obj.responseXML;
	// browser with native functionality?    
	if(window.XMLHttpRequest && window.XSLTProcessor && 
	  window.DOMParser)
	{
		// load the XSLT document
		var xsltProcessor = new XSLTProcessor();
		xsltProcessor.importStylesheet(stylesheetDoc);
		// generate the HTML code for the new page of products
		page = xsltProcessor.transformToFragment(xmlResponse, document);
		// display the page of products
		//var gridDiv = document.getElementById(reportDivId);
		reportDivCtrl.innerHTML = "";
		//gridDiv.innerHTML = "";
		//gridDiv.appendChild(page);		
		reportDivCtrl.appendChild(page);
	} 
	
	// Internet Explorer code
	else if (window.ActiveXObject) 
	{
		//alert("Inside else");
		xmlResponse = convertMS(obj.responseText)
		// load the XSLT document
		var theDocument = createMsxml2DOMDocumentObject();
		theDocument.async = false;
		//alert(response);
		theDocument.load(xmlResponse);
		// display the page of products
		//var gridDiv = document.getElementById("testDiv");
		reportDivCtrl.innerHTML = theDocument.transformNode(stylesheetDoc);
		//alert(stylesheetDoc);		
		//alert(reportDivCtrl);
		//alert(reportDivCtrl.innerHTML);
		//gridDiv.innerHTML = theDocument.transformNode(stylesheetDoc);
		
	}	
}

//==========================================================================

function addGridRow(gridtbl, griddefrow)
{
	tr = gridtbl.insertRow(gridtbl.rows.length);
	for(var i=0; i<griddefrow.cells.length; i++) {
		var oldCell = griddefrow.cells[i];
		var newCell = document.createElement("TD");
		var str = oldCell.innerHTML;
		var newval = "" + (gridtbl.rows.length);
		str = str.replace(/__ROW__/g, newval);
		newCell.innerHTML = str;
		tr.appendChild(newCell);
	}
}

//==========================================================================


function FillComboForReport(obj, controlId)
{	  
    //alert("Fill combo called");  
	var xmlDoc = obj.responseXML;
	//alert(xmlDoc);
	var ctrl = document.getElementById(controlId);	
	//alert(ctrl);
    var selectedIndex = xmlDoc.getElementsByTagName('SelectedIndex').item(0);
    var selection = -1;
    if(selectedIndex != null)
    {
        selection = selectedIndex.firstChild.data;
        //alert(selection);
    }
    //alert(selectedIndex);
    var node = xmlDoc.getElementsByTagName(controlId).item(0);	
	//alert(node);	

	if (node == null) 
	{
		return;
	}
	ctrl.length = 0;
	var no = new Option();
	no.value = 0;
	no.text = 'None';
	ctrl[0] = no;
				
	subnode_list_front = node.getElementsByTagName('Front');
	subnode_list_back = node.getElementsByTagName('Back');
	
	node = subnode_list_front.item(0);
	
	for(i=0;i<subnode_list_front.length;i++)
	{		
		if(subnode_list_front(i).firstChild)
		{
		    var no = new Option();
		    no.value = subnode_list_back(i).firstChild.data;
		    no.text = subnode_list_front(i).firstChild.data;
		    ctrl[i+1] = no;	
		    if(no.value == selection)
		    {
		        ctrl.value = no.value;
		        //alert(ctrl.value);
		    }	    
		 }
	}
	
}

function FillControlForReport(obj, controlId)
{
	var xmlDoc = obj.responseXML;  
	var ctrl = document.getElementById(controlId);	
	ctrl.value = "";
    var node = xmlDoc.getElementsByTagName(controlId).item(0);
    if(node != null)
    {
	    var node_val = node.firstChild.data;
	    ctrl.value = node_val;
	}	
}

function FillCheckBoxControlForReport(obj, controlId)
{
	var xmlDoc = obj.responseXML;  
	var ctrl = document.getElementById(controlId);	
	
    var node = xmlDoc.getElementsByTagName(controlId).item(0);
    if(node != null)
    {
	    var node_val = node.firstChild.data;
	    if(node_val == "on")
	        ctrl.checked = true;
	    else
	        ctrl.checked = false;
	}	
}
function FillMessageStringForReport(obj, controlId)
{
	var xmlDoc = obj.responseXML;  
	var node;		
	var messageDivControl = document.getElementById(controlId);
    messageDivControl.innerHTML = "";

	node = xmlDoc.getElementsByTagName(controlId).item(0);
	if(node != null)
	{
	    var node_val = node.firstChild.data;
	    messageDivControl.innerHTML = node_val;	
	}
}

//==========================================================================

function getRequestBody(form, ajaxParam)
{
	var aParams = new Array();
	for (var i = 0; i < form.elements.length; i++)
	{	
		if(form.elements[i].disabled==false)
		{
			if(form.elements[i].type=='radio')
			{		    
				if(form.elements[i].checked)
				{
					sParam = encodeURIComponent(form.elements[i].name);
			        sParam += "=";			    
					sParam += encodeURIComponent(form.elements[i].value);
					aParams.push(sParam);
				}
			}
			else if(form.elements[i].type=='checkbox')
			{
				if(form.elements[i].checked)
				{
					sParam = encodeURIComponent(form.elements[i].name);
			        sParam += "=";			        
			        sParam += encodeURIComponent(form.elements[i].value);			        
			        aParams.push(sParam);
			     }
			}
			else
			{
				sParam = encodeURIComponent(form.elements[i].name);
		        sParam += "=";
				sParam += encodeURIComponent(form.elements[i].value);
				aParams.push(sParam);
		    }
		}
	}
	sParam = "ACTION=";
	sParam += ajaxParam;	
	aParams.push(sParam);		
	
	return aParams.join("&");
}
