// Variable declaration for use of AJAX.js
var isIE = false;
var msIE_version;
var xmlhttp;
var xslthttp;
var CallerID = "";
var xmlUrl = "";
var xsltUrl = "";
var processXslt = false;
var arrParams = new Array();
var webServiceNS = "Sykes.APAC.HRRS.Careers.Services"; // change the namespace of service here
// Namespace above will vary depending on the request from the web service

// Check the type of browser using, if IE or non-IE - this is recommended if you are using cross-browser technology
if (window.XMLHttpRequest)
{
	isIE = false;
	//alert("This page only supports IE version 5.5 or higher");
	CheckBrowser();
	if ( msIE_version >= 7 ) {
		isIE = true;
	}
}
else if (window.ActiveXObject)
{
	isIE = true;
}

// function check browser information such as, versions
function CheckBrowser()
{
	var ua = window.navigator.userAgent;
	var msIE = ua.indexOf ( "MSIE " );
	if ( msIE > 0 )      // is Microsoft Internet Explorer; return version number
	{
		var msIEversion = ua.substring ( msIE+5, ua.indexOf ( ".", msIE ) );
		msIE_version = msIEversion;
		if ( msIEversion < 5.5 )
		{
			//location.href = "http://www.sykesasia.com/SykesPortal/";
			//alert("This page only serves Internet Explorer 5.5 or higher");
		}
	}
}

// create function below to act like methods
// function was created to support other loadXML and xml to other browsers
if (!isIE)
{
	Document.prototype.loadXML = function(strXML) {
		//create a DOMParser
		var objDOMParser = new DOMParser();
		//create new document from string
		var objDoc = objDOMParser.parseFromString(strXML, "text/xml");  
		//make sure to remove all nodes from the document
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);            
		//add the nodes from the new document
		for (var i=0; i < objDoc.childNodes.length; i++) {            
			//import the node
			var objImportedNode = this.importNode(objDoc.childNodes[i], true);            
			//append the child to the current document
			this.appendChild(objImportedNode);
		} //End: for
	} //End: function
	
	
	/**
	* add the xml attribute to the node class
	* Everytime the .xml attribute is called it will be transformed to string
	*/
	Node.prototype.__defineGetter__("xml", function () {
		var oSerializer = new XMLSerializer();
		return oSerializer.serializeToString(this, "text/xml");
	} );
}
function GetXmlHttpObject()
{
	var curXmlObj;
	if ( msIE_version >= 7 ) {
		curXmlObj = new XMLHttpRequest();
	}
	else {
		curXmlObj = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return curXmlObj;
}

//Use this to send soap request 
function loadXMLRequest(url, methodName)
{
	// branch for native XMLHttpRequest object
	if (!isIE) 
	{
		isIE = false;
		xmlhttp = new XMLHttpRequest();
	} 
	// branch for IE/Windows ActiveX version
	else if (isIE) 
	{
		isIE = true;
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	// Build the SOAP envelop which is requested by the service
	var strEnvelope = BuildSOAPEnvelope(methodName);
	
	xmlhttp.onreadystatechange = processHttpChange;
	xmlhttp.open("POST", url, true);
	
	if ( methodName != "GetListOfDegrees" ||
		 methodName != "GetJobListByCountryID" ||
		 methodName != "GetJobListByCityID" ||
		 methodName != "GetJobListByCityIDAndJobCategoryID" )
	{
		xmlhttp.setRequestHeader("SOAPAction", "http://" + webServiceNS + "/" + methodName);
		xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8" );
	}
	
	if (isIE)
	{
		xmlhttp.send(strEnvelope);
	}
	else
	{
		xmlhttp.send(strEnvelope, null);
	}
}

// Event handler of the loadXMLRequest function
function processHttpChange() 
{
	// only if req shows "loaded"
	if (xmlhttp.readyState == 4) 
	{
		// only if "OK"
		if (xmlhttp.status == 200) 
		{
			processXML();
		}
		else 
		{
			alert("There was a problem retrieving the XML data:\n" +xmlhttp.statusText);
		}
	}
}

// function is called by the processHttpChange event handler when 
// the xml has been loaded (readyState = 4) and in correct format (status = 200)
function processXML()
{	
	// checks if processXslt is true then transform the xml loaded to xslt, else just load the xml.
	//processXslt ? transformXMLforIE() : LoadXMLforIE();
	processXslt ? loadXSLTRequest(xsltUrl) : ( isIE ? LoadXMLforIE() : LoadXMLforNonIE() );
}

function processXsltChange() 
{
	// only if req shows "loaded"
	if (xslthttp.readyState == 4) 
	{
		// only if "OK"
		if (xslthttp.status == 200) 
		{
			isIE ? transformXMLforIE() : transformXMLforNonIE();
		}
		else 
		{
			alert("There was a problem retrieving the XML data:\n" + xslthttp.statusText);
		}
	}
}

function loadXSLTRequest(url) 
{	
	// branch for native XMLHttpRequest object
	if (!isIE) 
	{
		xslthttp = new XMLHttpRequest();
		xslthttp.onreadystatechange = processXsltChange;
		xslthttp.open("GET", url, true);
		xslthttp.send(null);
	} 
	// branch for IE/Windows ActiveX version
	else if (isIE) 
	{
		isIE = true;
		xslthttp = new ActiveXObject("Microsoft.XMLHTTP");
		if (xslthttp) 
		{
			xslthttp.onreadystatechange = processXsltChange;
			xslthttp.open("POST", url, true);
			xslthttp.send();
		}
	}
}

// Load the SOAP/XML data returned by the web service using IE 
function LoadXMLforIE()
{
	// create an instance of ActiveXObject to load the SOAP message returned by the web service
	var xmlDocSOAP = new ActiveXObject("Microsoft.XMLDOM");
	xmlDocSOAP.async = false;
	xmlDocSOAP.loadXML( xmlhttp.responseText );
	
	// create an instance of ActiveXObject to load xml data within the SOAP message returned by the web service
	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.async = false;
	xmlDoc.loadXML( HtmlDecode(xmlDocSOAP.documentElement.getElementsByTagName( CallerID + "Result" )[0].childNodes[0].xml) );
	
	XmlResult(xmlDoc, "", xmlDoc); // returns the xml data to this function which should be found on the same page of the requestor
}

function LoadXMLforNonIE()
{
	var objSrcTreeSOAP = document.implementation.createDocument("", "", null); 
	objSrcTreeSOAP.async = false;
	try 
	{
		objSrcTreeSOAP.loadXML(xmlhttp.responseText);
		
		// create an instance of ActiveXObject to load xml data within the SOAP message returned by the web service
		var objSrcTree = document.implementation.createDocument("", "", null);
		objSrcTree.async = false;
		objSrcTree.loadXML( HtmlDecode(objSrcTreeSOAP.getElementsByTagName( CallerID + "Result" )[0].childNodes[0].xml) );
		
		XmlResult(objSrcTree, "", objSrcTree);
	}
	catch(Exception){
		alert(Exception);
	}
}

// Load the SOAP/XML data returned by the web service using IE and transform the data into xslt
function transformXMLforIE()
{
	// Loads the returned SOAP message
	var xmlDocSOAP = new ActiveXObject("Microsoft.XMLDOM");
	xmlDocSOAP.async = false;
	xmlDocSOAP.loadXML( xmlhttp.responseText );
	
	// Loads the xml within the SOAP message. 
	var xmlDocRaw = new ActiveXObject("Microsoft.XMLDOM");
	xmlDocRaw.async = false;
	if ( CallerID == "GetListOfDegrees" ||
		 CallerID == "GetJobListByCountryID" ||
		 CallerID == "GetJobListByCityID" ||
		 CallerID == "GetJobListByCityIDAndJobCategoryID" )
	{
		xmlDocRaw.loadXML(xmlDocSOAP.xml);
	}
	else
	{
		xmlDocRaw.loadXML( HtmlDecode(xmlDocSOAP.documentElement.getElementsByTagName( CallerID + "Result" )[0].childNodes[0].xml) );
	}
	
	// Loads the XSLT file set by the user on the method call
	var xsl = new ActiveXObject("Microsoft.XMLDOM");
	xsl.async = false;
	xsl.load( xsltUrl );
	
	// Transforms the loaded xml data into xsl format
	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.async = false;
	xmlDoc.loadXML( xmlDocRaw.transformNode(xsl) );
	
	XmlResult(xmlDoc, xsl, xmlDocRaw); // returns the xml data to this function which should be found on the same page of the requestor
}

function transformXMLforNonIE()
{
	var objSrcTreeSOAP = document.implementation.createDocument("", "", null); 
	var objSrcTree = document.implementation.createDocument("", "", null);
	var objXSLT = document.implementation.createDocument("", "", null);
	objSrcTreeSOAP.async = false;
	objSrcTree.async = false;
	try 
	{
		objSrcTreeSOAP.loadXML( xmlhttp.responseText );
		objXSLT.loadXML( xslthttp.responseText );
		if ( CallerID == "GetListOfDegrees" ||
			 CallerID == "GetJobListByCountryID" ||
			 CallerID == "GetJobListByCityID" ||
			 CallerID == "GetJobListByCityIDAndJobCategoryID" )
		{
			objSrcTree.loadXML(objSrcTreeSOAP.xml);
		}
		else
		{
			objSrcTree.loadXML( HtmlDecode(objSrcTreeSOAP.getElementsByTagName( CallerID + "Result" )[0].childNodes[0].xml) );
		}
	}
	catch(Exception){
		alert(Exception);
	}
	objXSLTProc = new XSLTProcessor();
	objXSLTProc.importStylesheet(objXSLT);
	
	try 
	{
		var resultDOM = objXSLTProc.transformToDocument(objSrcTree);
		XmlResult(resultDOM, objXSLT, objSrcTree);
	}
	catch(e)
	{
		alert(e);
	}
}

// Function accetps xml and xslt data. Returns xml data transformed with xslt
function ConvertXmlToXsl(xmlTagRaw, xslFile)
{	
	// Loads the xsl data from file
	var xsl = new ActiveXObject("Microsoft.XMLDOM");
	xsl.async = false;
	xsl.load(xslFile);
	
	// Loads the xml "raw" data to be converted and transformed using xslt. (This snippet also transforms xml into xsl)
	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.async = false;
	xmlDoc.loadXML(xmlTagRaw.transformNode(xsl));
	
	return xmlDoc;
}

// Bind the Xml data into the Combo Box (or select tag in HTML)
// accepts value and text of the option tag, ID of the select tag and the XML.
function BindXmlToComboBox(valueTag, textTag, cboName, xmlTag)
{		
	var xmlDoc = xmlTag;
	var cboId = cboName.getAttribute("id");
	if ( cboName.length != 2 )
	{
		cboName.length = 1;
	}
	
	if(xmlDoc.getElementsByTagName(valueTag)[0].firstChild.nodeValue != 0)
	{		
		for (var i=0;i < xmlDoc.getElementsByTagName(valueTag).length; i++)
		{
			var objCboItem = document.createElement("option");
			var txtNode = document.createTextNode( HtmlDecode(xmlDoc.getElementsByTagName(textTag)[i].firstChild.nodeValue) );
			objCboItem.setAttribute("value", xmlDoc.getElementsByTagName(valueTag)[i].firstChild.nodeValue);
			objCboItem.appendChild( txtNode );
			if (isIE)
			{
				cboName.appendChild( objCboItem );
			}
			else
			{
				cboName.appendChild( objCboItem, null );
			}
		}
	}
}

// Display the content of of the transformed xml file into a DIV tag
function DisplayPageContent(divResult, xmlTagRaw, xslFile)
{
	
	var xmlTag = ConvertXmlToXsl(xmlTagRaw, xslFile);
	
	document.getElementById(divResult).innerHTML = xmlTag.xml;
	document.getElementById(divResult).style.display = "block";
}

// Builds the SOAP envelope in requesting data from the web service.
// Format of the SOAP envelope can be found on the web service itself after you consume a method.
function BuildSOAPEnvelope(methodName)
{
	var strEnvelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		strEnvelope += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
		strEnvelope += " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"";
		strEnvelope += " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
		strEnvelope += "<soap:Body>";
		strEnvelope += "<" + methodName + " xmlns=\"http://" + webServiceNS + "/\">";
		if ( arrParams.length > 0 )
		{
			for (var i=0; i < arrParams[0].length; i++)
			{
				strEnvelope += "<" + arrParams[0][i] + ">" + arrParams[1][i] + "</" + arrParams[0][i] + ">";
			}
		}
		strEnvelope += "</" + methodName + ">";
		strEnvelope += "</soap:Body>";
		strEnvelope += "</soap:Envelope>";
		
	return strEnvelope;
}
