function getDomain() {
	return document.domain;
}

function test()
{
	alert('test');
}


// declare a global  XMLHTTP Request object
var XmlHttpObj;

// create an instance of XMLHTTPRequest Object, varies with browser type, try for IE first then Mozilla
function CreateXmlHttpObj()
{
	// try creating for IE (note: we don't know the user's browser type here, just attempting IE first.)
	try
	{
		XmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			XmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlHttpObj = null;
		}
	}
	// if unable to create using IE specific code then try creating for Mozilla (FireFox) 
	if(!XmlHttpObj && typeof XmlHttpObj != "undefined") 
	{
		XmlHttpObj = new XMLHttpRequest();
	}
}

function ShowDealers()
{
	// state ==4 indicates receiving response data from server is completed
	if(XmlHttpObj.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttpObj.status == 200)
		{		
			generateDealerListWindow();
		}
		else
		{
			alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
		}
	}
	
}

var dealerWindow;

function generateDealerListWindow()
{
	setTimeout("showXML()",10);
	//dealerWindow = window.open("","subwindow","height=200,width=200");	
	//setTimeout("finishDealerList()", 100);
}

function showXML()
{
	var ans = ParseResponseXML(XmlHttpObj.responseText);
	var dealerRows = '';
	var elements = ans.getElementsByTagName('RESULTS')[0].getElementsByTagName('OUTPUT')[0].getElementsByTagName('ELEMENTS');
		if ((elements)&&(elements.length > 0)) {
			elements = elements[0];
			do {				
				var requested_attribute = elements.getElementsByTagName('REQUESTED_ATTRIBUTE');
				var anagraphicCode,companyName,address, cap, town;
				if ((requested_attribute)&&(requested_attribute.length > 0)) {
					requested_attribute = requested_attribute[0];
					do {
						var label = requested_attribute.getAttribute('label');
						if (label == 'anagraphicCode') anagraphicCode = GetInnerText(requested_attribute);
						if (label == 'companyName') companyName = GetInnerText(requested_attribute);
						if (label == 'address') address = GetInnerText(requested_attribute);
						if (label == 'zipCode') cap = GetInnerText(requested_attribute);
						if (label == 'city') town = GetInnerText(requested_attribute);
					} while (requested_attribute = requested_attribute.nextSibling)
				}
				
				//dealerRows += "<p><a onclick='window.opener.document.getElementById(\"DealerData\").innerHTML=\"<p>" + anagraphicCode + "<br>" + companyName + "<br>" + address + "<br></p>\";window.close();' href='#'>select</a> " + " " + companyName + " " + address + "</p>";
				//dealerRows += "<p><a onclick='window.opener.document.getElementById(\"DealerCode\").value=\"4\";window.opener.document.getElementById(\"DealerData\").innerHTML=\"<p>" + companyName + "<br>" + address + "<br></p>\";window.close();' href='#'>select</a> " + " " + companyName + " " + address + "</p>";
				dealerRows += "<tr><td width=\"70%\">" + companyName + "<br />" + address + ", "+ cap + " - " + town +"</td><td width=\"30%\" align=\"right\"><a onclick='window.opener.document.getElementById(\"DealerData\").innerHTML=\"<p>" + 
								companyName + "<br/>" + address +", <br/>"+ cap + " - " + town +"<br/></p>\";window.opener.document.getElementById(\"DealerCode\").value=\"" + 
								anagraphicCode + "\";window.close();' href='#'><img src=\"img/select.jpg\" border=\"0\" /></a></td></tr>";
					
			} while (elements = elements.nextSibling);
			dealerWindow = window.open("","subwindow","height=600,width=400");
			var output = "";
			output += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"it\" lang=\"it\"><head><title>Alfaromeo</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><link href=\"css/style.css\" rel=\"stylesheet\" type=\"text/css\"><link rel=\"stylesheet\" href=\"css/base.css\" type=\"text/css\" media=\"screen\"><link href=\"css/screen.css\" rel=\"stylesheet\" rev=\"stylesheet\"><link href=\"css/def.css\" rel=\"stylesheet\" rev=\"stylesheet\" /></head><body><div id=\"bg-TopRed\" style=\"width:100%;\"><div style=\"float: left\"><img src=\"img/tit-LogoAlfaRed.jpg\" alt=\"\" width=\"57\" height=\"47\"></div><div style=\"float: left\" id=\"DIV1\"><h1>H&auml;ndler</h1></div></div><div style=\"margin:10px;\"><h3>Bitte w&auml;hlen Sie hier einen H&auml;ndler f&uuml;r Ihre Probefahrt aus.</h3><table border=\"0\" width=\"100%\">";
			output += dealerRows;
			output += "</table></div></body></html>";
			dealerWindow.document.write(output);
			dealerWindow.document.close();
		} else 
			return;
}

function finishDealerList()
{
	var output = "";
	output += "<html><body><h1>A Sub-window</h1>";
	output += "<form><input type='button' value='Close Main Window'";
	output += "onclick='window.opener.close()'></form></body></html>";
	dealerWindow.document.write(output);
	dealerWindow.document.close();
}

function DepartmentOnload()
{

	// url of page that will send xml data back to client browser
	var requestUrl;
	//***************TODO**************
	requestUrl = 'http://'+getDomain()+'/cgi-bin/pbrand.dll/NEWALFA_DE/dealerlocator/dealerlocator.jsp';
	//requestUrl = 'http://auth.alfaromeo.com/cgi-bin/pbrand.dll/NEWALFA_DE/dealerlocator/dealerlocator.jsp';
	//requestUrl = 'TestDepartment.xml';
	//requestUrl = '../../webform1.aspx';
	//*********************************
	

	CreateXmlHttpObj();
	var zipcode = document.getElementById('OBS-Cap').value;
	
	/*
	if (zipcode == null) {
		zipcode = "44145";
	}
	else {
		zipcode = document.getElementById('OBS-Cap').value;
	}
	*/

	// verify XmlHttpObj variable was successfully initialized   44145
	if(XmlHttpObj)
	{
		// assign the StateChangeHandler function ( defined below in this file)
		// to be called when the state of the XmlHttpObj changes
		// receiving data back from the server is one such change
		
		var params = "xmlForm=" + escape("<FORM NAME=\"DealerLocator\"><ACTION>1</ACTION><FIELDS><FIELD NAME=\"region\"><VALUE>0</VALUE></FIELD><FIELD NAME=\"province\"><VALUE>0</VALUE></FIELD><FIELD NAME=\"cities\"><VALUE/></FIELD><FIELD NAME=\"DL_zipCode\"><VALUE>"+zipcode+"</VALUE></FIELD></FIELDS></FORM>");
		//var url = requestUrl + "?" + params;
		
		XmlHttpObj.onreadystatechange = ShowDealers;
		//XmlHttpObj.open("GET", url, true);		
		XmlHttpObj.open("POST", requestUrl, true);
		//XmlHttpObj.send("xmlForm=<FORM NAME=\"DealerLocator\"><ACTION>1</ACTION><FIELDS><FIELD NAME=\"region\"><VALUE>0</VALUE></FIELD><FIELD NAME=\"province\"><VALUE>0</VALUE></FIELD><FIELD NAME=\"cities\"><VALUE /></FIELD><FIELD NAME=\"DL_zipCode\"><VALUE>"+zipcode+"</VALUE></FIELD></FIELDS></FORM>");
		// send request to server, null arg  when using "GET"
		//XmlHttpObj.send(null);
		
		// define the iteraction with the server -- true for as asynchronous.
		//XmlHttpObj.open("POST", requestUrl, true);
		XmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		XmlHttpObj.setRequestHeader("Content-length", params.length);
		XmlHttpObj.setRequestHeader("Connection", "close");
		
		// send request to server, null arg  when using "GET"
		XmlHttpObj.send(params);
		
		
	}

}

function CittaOnchange()
{
	resetComboBox(document.getElementById("dealer"));
	
	// url of page that will send xml data back to client browser
	var requestUrl;
	//***************TODO**************
	requestUrl = 'http://www.alfaromeo.de/cgi-bin/pbrand.dll/NEWALFA_DE/dealerlocator/dealerlocator.jsp';
	//requestUrl = 'http://auth.alfaromeo.com/cgi-bin/pbrand.dll/NEWALFA_DE/dealerlocator/dealerlocator_zip.jsp';
	//requestUrl = '../../webform1.aspx';
	//*********************************

	CreateXmlHttpObj();
	
	// verify XmlHttpObj variable was successfully initialized
	if(XmlHttpObj)
	{
		// assign the StateChangeHandler function ( defined below in this file)
		// to be called when the state of the XmlHttpObj changes
		// receiving data back from the server is one such change
		XmlHttpObj.onreadystatechange = DealerStateHandler;
		
		// define the iteraction with the server -- true for as asynchronous.
		var params = 'xmlForm=' + GetPostData();
		XmlHttpObj.open("GET", requestUrl + "?" + params, true);
		
		//PostData();
		
		// send request to server, null arg  when using "GET"
		//XmlHttpObj.send(null);
		/*
		XmlHttpObj.open("post", requestUrl, true);
		var params = 'xmlForm=' + GetPostData();
		XmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		XmlHttpObj.setRequestHeader("Content-length", params.length);
		XmlHttpObj.setRequestHeader("Connection", "close");
		*/
		
		// send request to server, null arg  when using "GET"
		XmlHttpObj.send(null);
		
	}
}

function DepartmentOnchange()
{
	resetComboBox(document.getElementById("dealer"));
	resetComboBox(document.getElementById("province"));	
	
	// url of page that will send xml data back to client browser
	var requestUrl;
	//***************TODO**************
	//requestUrl = 'http://publish.fiat.com/cgi-bin/pbrand.dll/NEWALFA_DE/dealerlocator/dealerlocator_zip.jsp';	
	requestUrl = 'http://auth.alfaromeo.com/cgi-bin/pbrand.dll/NEWALFA_DE/dealerlocator/dealerlocator_zip.jsp';	
	//requestUrl = '../../webform1.aspx';
	//*********************************
	
	CreateXmlHttpObj();
	
	// verify XmlHttpObj variable was successfully initialized
	if(XmlHttpObj)
	{
		// assign the StateChangeHandler function ( defined below in this file)
		// to be called when the state of the XmlHttpObj changes
		// receiving data back from the server is one such change
		XmlHttpObj.onreadystatechange = CittaStateHandler;
		
		// define the iteraction with the server -- true for as asynchronous.
		var params = 'xmlForm=' + GetPostData();
		XmlHttpObj.open("GET", requestUrl + "?" + params, true);	
		// PostData();		
		// send request to server, null arg  when using "GET"
		//XmlHttpObj.send(null);		
		
		// define the iteraction with the server -- true for as asynchronous.
		/*
		XmlHttpObj.open("post", requestUrl, true);		
		XmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		XmlHttpObj.setRequestHeader("Content-length", params.length);
		XmlHttpObj.setRequestHeader("Connection", "close");
		*/
		
		
		
		// send request to server, null arg  when using "GET"
		XmlHttpObj.send(null);
		
	}

}

function resetComboBox(cbo)
{
	for (var count = cbo.options.length-1; count >-1; count--)
	{
		cbo.options[count] = null;
	}
	
	cbo.innerHTML = '';
	
	/*
	var eachGroup = cbo.firstChild;
	if (eachGroup!=null){
		do
		{
			lastGroup = eachGroup;
			eachGroup = lastGroup.nextSibling;
			debugger;
			if ('OPTGROUP' == eachGroup.tagName)
				cbo.removeChild(lastGroup)
		} while (eachGroup != null)
    }
    */
    
}

function DealerStateHandler()
{
	// state ==4 indicates receiving response data from server is completed
	if(XmlHttpObj.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttpObj.status == 200)
		{		
			FillDealer(ParseResponseXML(XmlHttpObj.responseText).documentElement);
		}
		else
		{
			alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
		}
	}
}

function CittaStateHandler()
{

	// state ==4 indicates receiving response data from server is completed
	if(XmlHttpObj.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttpObj.status == 200)
		{		
			FillCitta(ParseResponseXML(XmlHttpObj.responseText).documentElement);
		}
		else
		{
			alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
		}
	}
}

function DepartmentStateHandler()
{
	// state ==4 indicates receiving response data from server is completed
	if(XmlHttpObj.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttpObj.status == 200)
		{			
			FillDepartment(ParseResponseXML(XmlHttpObj.responseText).documentElement);
		}
		else
		{
			alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
		}
	}
}

function FillDealer(dealerNode)
{
	
	var concessionarioList = document.getElementById("dealer");
	// clear the department list
	for (var count = concessionarioList.options.length-1; count >-1; count--)
	{
		concessionarioList.options[count] = null;
	}
	
	var xmlData = dealerNode;
	
	if (!xmlData) return;

	var results = xmlData.getElementsByTagName('RESULTS');
	
	if ((results)&&(results.length > 0)) {
		results = results[0];
		var output = results.getElementsByTagName('OUTPUT');
		if ((output)&&(output.length > 0)) {
			output = output[0];
			var elements = output.getElementsByTagName('ELEMENTS');
			if ((elements)&&(elements.length > 0)) {
				elements = elements[0];
				do {				
					var requested_attribute = elements.getElementsByTagName('REQUESTED_ATTRIBUTE');
					var anagraphicCode,companyName,address;
					
					if ((requested_attribute)&&(requested_attribute.length > 0)) {
						requested_attribute = requested_attribute[0];
						do {
							var label = requested_attribute.getAttribute('label');
							if (label == 'anagraphicCode') anagraphicCode = GetInnerText(requested_attribute);
							if (label == 'companyName') companyName = GetInnerText(requested_attribute);
							if (label == 'address') address = GetInnerText(requested_attribute);							
						} while (requested_attribute = requested_attribute.nextSibling)
					}
					
					var oGroup = document.createElement('OPTGROUP');
					oGroup.label = companyName;
					var optionItem = document.createElement('OPTION');
					//new Option( companyName + ' - ' + address, anagraphicCode, false, false);
					optionItem.value = anagraphicCode;
					optionItem.innerHTML = address;
					oGroup.appendChild(optionItem);
					concessionarioList.appendChild(oGroup);
					//concessionarioList.options[concessionarioList.length] = optionItem;
					
					//var optionItem = new Option(companyName,'2',false,false);
					//concessionarioList.appendChild(optionItem);
				} while (elements = elements.nextSibling);			
			} else 
				return;	
		} else 
			return;	
	} else
		return;
}

function FillCitta(cittaNode)
{
	var cittaList = document.getElementById("province");
	// clear the department list
	for (var count = cittaList.options.length-1; count >-1; count--)
	{
		cittaList.options[count] = null;
	}
	
	FillCombo(cittaList,'province',cittaNode);
}

function FillDepartment(departmentNode)
{
	var departmentList = document.getElementById("region");
	// clear the department list
	for (var count = departmentList.options.length-1; count >-1; count--)
	{
		departmentList.options[count] = null;
	}
	
	FillCombo(departmentList,'region',departmentNode);
	
	
}

function FillCombo(cbo,filterName,xmlData)
{
	if (!xmlData) return;

	var departmentNodes = xmlData.getElementsByTagName('FIELDS');
	
	if ((departmentNodes)&&(departmentNodes.length > 0)) {
		var fieldNode = departmentNodes[0].firstChild;	
		do {
			if (fieldNode.getAttribute('NAME') == filterName)
			{
				var lovNodes = fieldNode.getElementsByTagName('ELEMENT');
				if ((lovNodes)&&(lovNodes.length > 0)) {
					var lovNode = lovNodes[0];
					do	{
						var idValue;
						var textValue; 
						var optionItem;
					
						textValue = GetInnerText(lovNode.getElementsByTagName('LABEL')[0]);
						idValue = GetInnerText(lovNode.getElementsByTagName('VALUE')[0]);		
						optionItem = new Option( textValue, idValue, false, false);				
						cbo.options[cbo.length] = optionItem;						
						
					} while (lovNode = lovNode.nextSibling);
					break;
				} else {
					return;
				}
			}		
		} while (fieldNode = fieldNode.nextSibling);
	
	} else {
		return;
	}
}


function GetPostData()
{
	var departmentList = document.getElementById("region");
	var cittaList = document.getElementById("province");
	
	//alert(departmentList[departmentList.selectedIndex].value);
		
	var form = document.createElement('FORM');
	var action = document.createElement('ACTION');
	var fields = document.createElement('FIELDS');
	var field;
	var value;

	form.setAttribute('NAME','DealerLocator');
	action.appendChild(document.createTextNode('1'));
	
	field = document.createElement('FIELD');
	field.setAttribute('NAME','region');
	value = document.createElement('VALUE');
	value.innerHTML = departmentList[departmentList.selectedIndex].value;
	field.appendChild(value);		
	fields.appendChild(field);
			
	field = document.createElement('FIELD');
	field.setAttribute('NAME','province');
	value = document.createElement('VALUE');
	if (cittaList.selectedIndex >= 0)
		value.innerHTML = cittaList[cittaList.selectedIndex].value;
	field.appendChild(value);		
	fields.appendChild(field);
	
	field = document.createElement('FIELD');
	field.setAttribute('NAME','cities');
	value = document.createElement('VALUE');
	field.appendChild(value);		
	fields.appendChild(field);
	
	field = document.createElement('FIELD');
	field.setAttribute('NAME','fleetOperator');
	value = document.createElement('VALUE');
	value.innerHTML = '0';
	field.appendChild(value);		
	fields.appendChild(field);		
	
	form.appendChild(action);
	form.appendChild(fields);
	
	//For FireFox support
	var aux = document.createElement('aux');
	aux.appendChild(form);
	
	return escape(aux.innerHTML);
	
}

// returns the node text value 
function GetInnerText (node)
{
	 return (node.textContent || node.innerText || node.text) ;
}

function ParseResponseXML(xmlText)
{
	var xmlObj;
	try
	{
		xmlObj = new ActiveXObject("Microsoft.XMLDOM");
		xmlObj.async="false";
		xmlObj.loadXML(xmlText);
	} 
	catch(e)
	{
		xmlObj = null;
	}
	
	if (!xmlObj && typeof xmlObj != "undefined")
	{
		var strXML = xmlText;
		
		// replace \n (new line) and \r (carriage return)
		strXML = strXML.replace(/\r|\n|\r\n/g,"");
		
		// replace two or more ocurrences of the \s (space character)
		strXML = strXML.replace(/\s{2,}/g,"");
				
		var oParser = new DOMParser();
		xmlObj = oParser.parseFromString(strXML,'application/xml');		
	}
	
	return xmlObj;	

}

function InitDealerAjax()
{
	DepartmentOnload();
	//document.getElementById("region").onchange = DepartmentOnchange;
	//document.getElementById("province").onchange = CittaOnchange;

}