var windowAgentDetail;
var boolNetscapeBrowser;
var browserName = navigator.appName;
var browserVersion = parseInt(navigator.appVersion)
if (browserName == "Netscape")
	boolNetscapeBrowser = true;
else
	boolNetscapeBrowser = false;

var objXmlDom;
var sLocationChar = '';
var url = 'SplashAgentLocator.asp';
var xmlHttp;
var matchLocationKey = '';
var httpRequestType;
var REQUESTLIST = 'q';
var AGENTTLIST = 'a';
var AGENTDETAILS = 'g';

//	onLoaded()
function onLoaded()
{
	document.getElementsByName('txtTownCounty').item(0).focus();
	document.onkeyescape = dropdownHide;
}

//	createDOMDocument()
function createDOMDocument(xml)
{
	var aVersions = [ "MSXML2.DOMDocument.5.0",
			"MSXML2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0",
			"MSXML2.DOMDocument", "Microsoft.XmlDom" ];
	var oXmlDom;
    if (boolNetscapeBrowser) {
		var oParser = new DOMParser();
		oXmlDom = oParser.parseFromString(xml, "text/xml");	
		return oXmlDom;
	} else {
	    for (var i = 0; i < aVersions.length; i++) {
		    try {
			    if (!boolNetscapeBrowser)
					oXmlDom = new ActiveXObject(aVersions[i]);
                oXmlDom.loadXML(xml);
			    return oXmlDom;
		    } 
		    catch (oError) {
			    // Do nothing
		    }
		}
	    throw new Error("MSXML is not installed.");
    }
}

//	createXMLHTTP()
function createXMLHTTP()
{
	var _xmlHttp;
	if (window.XMLHttpRequest)
		_xmlHttp = new XMLHttpRequest();
	// code for IE
	else if (window.ActiveXObject)
		_xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    
	//xmlHttp = GetXmlHttpObject()
	if (_xmlHttp == null)
		throw new Error("Browser does not support HTTP Request");

	return _xmlHttp;
}

//	function dropdownShow
function dropdownShow(text)
{
//	if (text && text != '')
		document.getElementById('dropdown').innerHTML = text;
		
	if (document.getElementById('dropdown').innerHTML != '')				
		document.getElementById('dropdown').style.visibility = "visible";
	else
		document.getElementById('dropdown').style.visibility = "hidden";
    return;
}

//	function locationSelected
function locationSelected(selectedValue) {
	if (selectedValue == '') {
		return;
	}
	dropdownShow('<p style="font-weight:bold; color:red; font-size:1em;">Please wait while querying for Western Union agents...</p>');
	httpRequest('a', 'Key=' + selectedValue);
    return;
}

//	function dropdownHide
function dropdownHide()
{
	if (document.getElementById('dropdown').style.visibility == "visible")
		document.getElementById('dropdown').style.visibility = "hidden";
}

//	function agentsListOn
function agentsListOn(text)
{
	document.getElementById('agentsList').innerHTML = text; 
	document.getElementById('agentsList').style.visibility = "visible";
    dropdownHide();
    return;
}

//	function httpRequest
function httpRequest(type, parameters)
{
	xmlHttp = null;
	xmlHttp = createXMLHTTP();
	httpRequestType = type;
	if ((parameters) && (parameters.charAt(0) != '&'))
		parameters = '&' + parameters;
	try
	{
		xmlHttp.open('GET', url + '?R=' + type + parameters, true);
		xmlHttp.onreadystatechange = httpResponse;
		xmlHttp.send(null);
	}
	catch (err)
	{
		alert (err);
		return false;
	}
}

//	function onchangeLocation
function onchangeLocation(str)
{
	if (str.length == 0) 
	{ 
		dropdownHide();
		return;
	}
	if (!isAlphanumeric(str))
		dropdownShow('<p style="font-weight:bold; color:red; font-size:1em;">Invalid character entered.</p>');
	else 
	{
		str = str.toLowerCase();
		if (!isAlpha(str.charAt(0))) {
			dropdownShow('<p style="font-weight:bold; color:red; font-size:1em;">Invalid character entered.</p>');
			return;
		}
		if (sLocationChar == str.charAt(0))
		{
			var dropdownList;
			dropdownList = buildCountiesTownsList(str);
			if (matchLocationKey != '')
				locationSelected(matchLocationKey);
			else
				dropdownShow(dropdownList);
		}
		else {
			dropdownShow('<p style="font-weight:bold; color:red; font-size:1em;">Please wait while querying for locations...</p>');
			sLocationChar = str.charAt(0);
			httpRequest(REQUESTLIST, 's=' + sLocationChar);
		}
	}
}

//	function buildCountiesTownsList
function buildCountiesTownsList(str)
{
	var txtSelectOption = '';
    var nodeCounties;
	var county;
	var nCounties = 0;
    var nodeTowns;
	var nTowns = 0;
	var town;
	var request;
	var size = str.length;
	var firstTime = true;
	var nodeRoot = objXmlDom.documentElement;
	for (var i = 0; i < nodeRoot.childNodes.length; i++) {
		if (nodeRoot.childNodes[i].nodeType != 1) continue;
	    if (nodeRoot.childNodes[i].nodeName == 'Counties') {
	        nodeCounties = nodeRoot.childNodes[i];
	        for (var j = 0; j < nodeCounties.childNodes.length; j++) {
				if (nodeCounties.childNodes[j].nodeType != 1) continue;
	            var tmpCounty = nodeCounties.childNodes[j].getAttribute('Name').substr(0, size);
	            if (tmpCounty > str)
	                break;
	            else if (tmpCounty == str) {
					if (firstTime) {
						firstTime = false;
						txtSelectOption = '<option value=\"\" style=\"font-weight:bold; text-decoration: underline; color: blue;\">Counties</option>';
					}
		            county = nodeCounties.childNodes[j].getAttribute('Name');
		            // c indicates a county key
		            request = 'CKey=' + nodeCounties.childNodes[j].getAttribute('CKey');
		            txtSelectOption += '<option value=\"' + request;
		            txtSelectOption += '\">&nbsp;&nbsp;&nbsp;' + county + '</option>';
	                nCounties += 1;
                }
	        }
        }
	    else if (nodeRoot.childNodes[i].nodeName == 'Towns') {
			firstTime = true
	    	nodeTowns = nodeRoot.childNodes[i];
	        for (var j = 0; j < nodeTowns.childNodes.length; j++) {
				if (nodeTowns.childNodes[j].nodeType != 1) continue;
	            var tmpTown = nodeTowns.childNodes[j].getAttribute('Name').substr(0, size);
	            if (tmpTown > str)
	                break;
	            else if (tmpTown == str) {
		            town = nodeTowns.childNodes[j].getAttribute('Name');
		            county = nodeTowns.childNodes[j].getAttribute('County');   
					if (firstTime) {
						firstTime = false;
			            txtSelectOption += '<option value=\"\" style=\"font-weight:bold; text-decoration:underline; color: blue;\">Towns</option>'
					}
					request = 'TKey=' + nodeTowns.childNodes[j].getAttribute('TKey'); 
					txtSelectOption += '<option value=\"' + request
					txtSelectOption +=  '\">&nbsp;&nbsp;&nbsp;' + town;
					if (county.length > 0) 
						txtSelectOption += ' - ' + county;
					txtSelectOption += '</option>';
		            nTowns += 1;
                }
	        }
        }
	}
	matchLocationKey = '';
	size = nCounties + nTowns;
	switch (size) {
		case 0:
			text = '<p style="font-weight:bold; color:#C0071B">\"' + str;
			text += '\" does not ';
			text += 'point to a Western Union agent location or is not a valid location in Ireland.</p>';
			return text;	
		case 1:
			size += 1;
			if (((nCounties == 1) && (county == str)) || ((nTowns == 1) && (town == str)))
				matchLocationKey = request;
			break;
			
		default:
			if ((nCounties == 0) || (nTowns == 0))
				size += 1;
			else 
				size += 2;
				
			if (size > 15)
			    size = 15;
	}
	var text = '<select style=\"width:245px;\" name=\"selLocations\" id=\"selLocations\" size=\"' + size + '\" '
	text += 'onchange=\"locationSelected(document.getElementById(\'selLocations\').options[document.getElementById(\'selLocations\').selectedIndex].value);\">';
	text += txtSelectOption;
	text += '</select>';
	return text;	
}

//	function handleQResponse
function handleQResponse(_objXmlDom) 
{
	var text
	if (typeof(_objXmlDom) == 'undefined')
		text = '<p style="font-weight:bold; color:#C0071B">No such Western Union agent location or is not a valid location in Ireland.</p>';
	else {
	    objXmlDom = _objXmlDom;
		text = buildCountiesTownsList(sLocationChar);
	}
	dropdownShow(text);
}

//	function isAlphanumeric
function isAlphanumeric(alphane)
{
	var numaric = alphane;
	for(var j = 0; j < numaric.length; j++) {
		var alphaa = numaric.charAt(j);
		var hh = alphaa.charCodeAt(0);
		if (!(hh == 32 || (hh > 47 && hh < 59) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123)))
			return false;
	}
	return true;
}

//	function isAlpha
function isAlpha(alphane)
{
	var numaric = alphane;
	for(var j = 0; j < numaric.length; j++) {
		var alphaa = numaric.charAt(j);
		var hh = alphaa.charCodeAt(0);
		if(!(hh == 32 || (hh > 64 && hh < 91) || (hh > 96 && hh < 123)))
			return false;
	}
	return true;
}

//	function handleAResponse
function handleAResponse(_objXmlDom) 
{
	var text;
	var selectedTown;
	var selectedCounty;
	dropdownShow('');
	if (typeof(_objXmlDom) == 'undefined')
		throw new Error("Invalid server response.............");

	var nodeRoot = _objXmlDom.documentElement;
	var nodeLocation;
	var nodeAgentsDetail;
	for (var i = 0; i < nodeRoot.childNodes.length; i++) {
		if (nodeRoot.childNodes[i].nodeType != 1) continue;
		if (nodeRoot.childNodes[i].nodeName == 'Location') {
			nodeLocation = nodeRoot.childNodes[i];
		} else if (nodeRoot.childNodes[i].nodeName == 'AgentsDetail') {
			nodeAgentsDetail = nodeRoot.childNodes[i];
		}
	}
	selectedTown = nodeLocation.getAttribute('Town');
	if (!(selectedTown))
		selectedTown = '';
	selectedCounty = nodeLocation.getAttribute('County');
	if (!(selectedCounty))
		selectedCounty = '';
	if  (nodeAgentsDetail.childNodes.length == 0) {
		document.getElementById('agentsList').innerHTML = ''; 
		text = '<p style="font-weight:bold; color:blue;">No agents were found in ' + selectedTown + ' county ' + selectedCounty + '.</p>';
		dropdownShow(text);
		return;
	}
	text = '<table colspan="3">';
	text += '<tr><td colspan="3" class="tabletitle">agent list';
	if (selectedTown.length > 0)
		text += ' for ' + selectedTown.toUpperCase();
	if (selectedCounty.length > 0) {
		text += ' in ';
		if (selectedCounty.indexOf(" city") == -1) {
			text += ' county ';
		}
		text += selectedCounty.toUpperCase();
	}
	text += '</td ></tr>';
	text += '<tr>';
	text += '<td class="tableheader" >Agent Name</td>';
	text += '<td width="225px" class="tableheader">Address</td>';
	text += '<td width="100px" class="tableheader">Town</td>'
	//text += '<td width="80px">County</td></tr>';
	text += '<tr><td colspan="3" class="infomessage">'
	text += 'For further information on opening hours and services, please click on agency name'
	text += '</td></tr>';
	
	for (var i = 0; i < nodeAgentsDetail.childNodes.length; i++) {
		if (nodeAgentsDetail.childNodes[i].nodeType != 1) continue;
		var nodeAgent = nodeAgentsDetail.childNodes[i];
		text += '<tr>';
		text += '<td class="greycell">';
		text +=		'<a style="color:blue; text-decoration:underline;" title="Click upon agent name for further detail."';
		text +=			' onclick="javascript:agentSelected(\'' + nodeAgent.getAttribute('ID') + '\');"';
		text += 		' href="javascript:void(0);">';
		text +=			nodeAgent.getAttribute('N') + '</a>';
		text += '</td>';
		text += '<td class="greycell">' + nodeAgent.getAttribute('A') + '</td>';
		var town = nodeAgent.getAttribute('T');
		if ((town) && town.length > 0) 
			text += '<td class="greycell">' + town + '</td>';
		else
			text += '<td class="greycell">' + selectedCounty.toUpperCase() + '</td>';
		text += '</tr>';
	}
	text += '</table>';
	agentsListOn(text);
}

//	function handleAResponse
function handleGResponse(xmlResponse) 
{
	if ((windowAgentDetail) && !windowAgentDetail.closed)
        windowAgentDetail.close();
	windowAgentDetail = window.open('', 'agentDetail', 'scrollbars=yes,resizable=no,dependent=yes,left=300,top=400,width=450,height=400');
	windowAgentDetail.document.write(xmlResponse);
	windowAgentDetail.focus();
}

//	function agentSelected
function agentSelected(agentID) 
{
	//throw new Error("Debug............");
	httpRequest(AGENTDETAILS, 'id=' + agentID);
	//windowAgentDetail.focus();
	return (true)
}

//	function httpResponse
function httpResponse() 
{
	if ((xmlHttp.readyState == 4) || (xmlHttp.readyState == "complete"))
	{
		var xmlResponse = xmlHttp.responseText;
		var _objXmlDom;
		if (xmlResponse != '') {
			if (xmlResponse.substr(0, 14) == '<?xml version=') {
				//xmlResponse = xmlResponse.substr(xmlResponse.search('xml version') - 2, xmlResponse.length);
				try {
					_objXmlDom = createDOMDocument(xmlResponse);
					if (handleErrorMessage(_objXmlDom))
						return;
				} 
				catch (oError) {
					throw new Error("An error has occured handling a response from the server.");
				}
			}
		}
		switch (httpRequestType) {
			case REQUESTLIST:
				handleQResponse(_objXmlDom);
				break;
			case AGENTTLIST:
				handleAResponse(_objXmlDom);
				break;
			case AGENTDETAILS:
				handleGResponse(xmlResponse);
				break;
			default:
				throw new Error("Don't know how to handle the response from the server.");
		}
	} 
}

//===========================================================================================
//	function: handleErrorMessage
//===========================================================================================
function handleErrorMessage(_objXmlDom) 
{
	if (typeof(_objXmlDom) == 'undefined')
		return '';
	var nodeErrorMessage = _objXmlDom.documentElement;
	if (nodeErrorMessage.nodeName == 'ErrorMessage') {
		var txtType = nodeErrorMessage.getAttribute('Type');
		if (!txtType || txtType == '') {
			txtType = '1';
		}
		switch (txtType) {
			case '1':
				var str
				if (boolNetscapeBrowser)
					str = nodeErrorMessage.textContent;
				else
					str = nodeErrorMessage.text;
				if ((windowAgentDetail) && !windowAgentDetail.closed)
					windowAgentDetail.close();
				windowAgentDetail = window.open('', 'AgentLocatorError', 'scrollbars=yes,resizable=no,dependent=yes,left=300,top=400,width=450,height=400');
				handleGResponse(str);
				return true;

			case '2':
				post_to_url('Error.asp');
				return true;
		}
	}
	return false;
}

//========================================================================================
//		function EnableSendAmount()
//========================================================================================
function post_to_url(path) {
    method = "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    document.body.appendChild(form);    // Not entirely sure if this is necessary
    form.submit();
}