/*****
*    Returns a new XMLHttpRequest object, or false if this browser doesn't support it
*    
*****/
function newXMLHttpRequest() {

  var xmlreq = false;

  if (window.XMLHttpRequest) {
    // Create XMLHttpRequest object in non-Microsoft browsers
    xmlreq = new XMLHttpRequest();

  } else if (window.ActiveXObject) {
    // Create XMLHttpRequest via MS ActiveX
    try {
      // Try to create XMLHttpRequest in later versions
      // of Internet Explorer
      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e1) {
      // Failed to create required ActiveXObject
      try {
        // Try version supported by older versions of Internet Explorer
        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
        // Unable to create an XMLHttpRequest with ActiveX
      }
    }
  }

  return xmlreq;
}


/*
 * Returns a function that waits for the specified XMLHttpRequest
 * to complete, then passes its XML response
 * to the given handler function.
 * req - The XMLHttpRequest whose state is changing
 * responseXmlHandler - Function to pass the XML response to
 */
function getReadyStateHandler(req, responseXmlHandler, clickX, clickY) {

  // Return an anonymous function that listens to the 
  // XMLHttpRequest instance
  return function () {

    // If the request's status is "complete"
    if (req.readyState == 4) {
      
      // Check that a successful server response was received
      if (req.status == 200) {

        // Pass the XML payload of the response to the 
        // handler function
        responseXmlHandler(req.responseXML,clickX,clickY);

      } else {

        // An HTTP problem has occurred
        alert("HTTP error: "+req.status);
      }
    }
  }
}


/* 
*    Creates and configures a XMLHttpRequest instance
*****/
function getRequestInstance(serverStaticUrl,responseFunction,clickX,clickY) {
	// Obtain an XMLHttpRequest instance
	var req = newXMLHttpRequest();

	// Set the handler function to receive callback notifications from the request object
	var handlerFunction = getReadyStateHandler(req, responseFunction, clickX, clickY);
	req.onreadystatechange = handlerFunction;

	// Open an HTTP POST connection. Third parameter specifies request is asynchronous.
	//req.open("POST", "servlet/ServletAjaxTest", true);
	req.open("POST", serverStaticUrl, true);

	// Specify that the body of the request contains form data
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	return req;
}


var poisRetencions = new Array();
var poisObres = new Array();
var poisCons = new Array();
var poisMeteorologia = new Array();
var layerRetencionsVisible = false;
var layerObresVisible = false;
var layerConsVisible = false;
var layerMeteorologiaVisible = false;
var poi;

function Poi () {
	this.id = "";
	this.category_id = "";
	this.name = "";
	this.info = "";
	this.text = "";
	this.timestamp = "";
	this.level = "";
	this.level_description = "";
	this.pk_end = "";
	this.pk_init = "";
	this.poblation = "";
	this.poblation_pk_init = "";
	this.road_code = "";
	this.type = "";
	this.subtype = "";
	this.coordx = "";
	this.coordy = "";
}


function crearPoisAjax () {
	var req = this.getRequestInstance("http://c1.cercalia.com/clients/mobilitatnou/mobxml?cmd=map&mindist=0&infoxml=1&ctn=barcelona&ctryc=ESP&scale=11&getpoicats=082A2&getpoicats=082A3&getpoicats=082A4&getpoicats=082A5",processResponse3,undefined,undefined);
	req.send(" ");
}

function processResponse3(responseXML,clickX,clickY) {
	//alert("processResponseXML:(nomes ho mostra l'IE) \n" + responseXML.xml );

	try {			
		var cercaliaN = responseXML.getElementsByTagName("cercalia")[0];
		var mapN = cercaliaN.getElementsByTagName("map")[0];
		var getpoicatsN = mapN.getElementsByTagName("getpoicats")[0];
		var poilistN = getpoicatsN.getElementsByTagName("poilist")[0];
		var poiN = "";
		var i = 0;
		//alert(poilistN.getElementsByTagName("poi").length);
		while(i < poilistN.getElementsByTagName("poi").length){
		
			poiN = poilistN.getElementsByTagName("poi")[i];
				nameN = poiN.getElementsByTagName("name")[0];
				infoN = poiN.getElementsByTagName("info")[0];
				infoXmlN = poiN.getElementsByTagName("infoxml")[0];
					affectationN = infoXmlN.getElementsByTagName("affectation")[0];
				coordN = poiN.getElementsByTagName("coord")[0];

			poi = new Poi();

			poi.id = poiN.getAttribute("id");
			poi.category_id = poiN.getAttribute("category_id");
			poi.name = nameN.firstChild.nodeValue;
			poi.info = infoN.firstChild.nodeValue;
			poi.text = affectationN.getAttribute("TEXT");
			poi.timestamp = affectationN.getAttribute("TIMESTAMP");
			poi.level = affectationN.getAttribute("level");
			poi.level_description = affectationN.getAttribute("level_description");
			poi.pk_end = affectationN.getAttribute("pk_end");
			poi.pk_init = affectationN.getAttribute("pk_init");
			poi.poblation = affectationN.getAttribute("poblation");
			poi.poblation_pk_init = affectationN.getAttribute("poblation_pk_init");
			poi.road_code = affectationN.getAttribute("road_code");
			poi.type = affectationN.getAttribute("type");
			poi.subtype = affectationN.getAttribute("subtype");
			poi.coordx = coordN.getAttribute("x");
			poi.coordy = coordN.getAttribute("y");
		
			if(poiN.getAttribute("category_id") == '082A2'){				
				poisRetencions.push(poi);
			}else if(poiN.getAttribute("category_id") == '082A3'){
				poisObres.push(poi);
			}else if(poiN.getAttribute("category_id") == '082A4'){
				poisCons.push(poi);
			}else if(poiN.getAttribute("category_id") == '082A5'){
				poisMeteorologia.push(poi);
			}
			i++;
		}

	} catch (e) {
		alert("Error parsing response.\n");
	}
}

function showLayer () {
	
	if(document.getElementById("layerRetencions").checked){ //Si el check está marcado
		if(layerRetencionsVisible == false){ //Si los pois no estan pintados
			for(var i = 0; i<poisRetencions.length; i++){
				cercalia.createMarker(  poisRetencions[i].id,
                                        poisRetencions[i].coordx,
                                        poisRetencions[i].coordy,
                                        "EPSG:54004",
                                        {icon:'img/pois/incidencia_'+poisRetencions[i].type+'.gif',
                                         width:22,
                                         height:21,
                                         visible:false,
                                         minimized:false,
                                         title:poisRetencions[i].text,
                                         cssTitle:"contTitolPopup",
                                         content:'<span style="color:#858585;padding:4px;">'+poisRetencions[i].name+'</span><br/>'+'<span class="linkMostrar" style="cursor:pointer;padding:4px;" onclick="javascript:obrirPopup(poisRetencions['+i+'])">Mostrar detalls</span>',
                                         noHideOthers:true,
										 panMapIfOutOfView:true});
			}
			
			layerRetencionsVisible = true;
		}
	}else{
		for(var j = 0; j<poisRetencions.length; j++){
			cercalia.deleteMarkers(poisRetencions[j].id);
		}
		
		layerRetencionsVisible = false;
	}

	if(document.getElementById("layerObres").checked){
		if(layerObresVisible == false){
			for(var i = 0; i<poisObres.length; i++){
				cercalia.createMarker(  poisObres[i].id,
                                        poisObres[i].coordx,
                                        poisObres[i].coordy,
                                        "EPSG:54004",
                                        {icon:'img/pois/incidencia_'+poisObres[i].type+'.gif',
                                         width:22,
                                         height:21,
                                         visible:false,
                                         minimized:false,
                                         title:poisObres[i].text,
                                         cssTitle:"contTitolPopup",
                                         content:'<span style="color:#858585;padding:4px;">'+poisObres[i].name+'</span><br/>'+'<span class="linkMostrar" style="cursor:pointer;padding:4px;" onclick="javascript:obrirPopup(poisObres['+i+'])">Mostrar detalls</span>',
                                         noHideOthers:true,
										 panMapIfOutOfView:true});
			}
			
			layerObresVisible = true;
		}
	}else{
		for(var j = 0; j<poisObres.length; j++){
			cercalia.deleteMarkers(poisObres[j].id);
		}
		
		layerObresVisible = false;
	}

	if(document.getElementById("layerCons").checked){
		if(layerConsVisible == false){
			for(var i = 0; i<poisCons.length; i++){
				cercalia.createMarker(  poisCons[i].id,
                                        poisCons[i].coordx,
                                        poisCons[i].coordy,
                                        "EPSG:54004",
                                        {icon:'img/pois/incidencia_'+poisCons[i].type+'.gif',
                                         width:22,
                                         height:21,
                                         visible:false,
                                         minimized:false,
                                         title:poisCons[i].text,
                                         cssTitle:"contTitolPopup",
                                         content:'<span style="color:#858585;padding:4px;">'+poisCons[i].name+'</span><br/>'+'<span class="linkMostrar" style="cursor:pointer;padding:4px;" onclick="javascript:obrirPopup(poisCons['+i+'])">Mostrar detalls</span>',
                                         noHideOthers:true,
										 panMapIfOutOfView:true});
			}
			
			layerConsVisible = true;
		}
	}else{
		for(var j = 0; j<poisCons.length; j++){
			cercalia.deleteMarkers(poisCons[j].id);
		}
		
		layerConsVisible = false;
	}

	if(document.getElementById("layerMeteorologia").checked){
		if(layerMeteorologiaVisible == false){
			for(var i = 0; i<poisMeteorologia.length; i++){
				cercalia.createMarker(  poisMeteorologia[i].id,
                                        poisMeteorologia[i].coordx,
                                        poisMeteorologia[i].coordy,
                                        "EPSG:54004",
                                        {icon:'img/pois/incidencia_'+poisMeteorologia[i].type+poisMeteorologia[i].subtype+'.gif',
                                         width:22,
                                         height:21,
                                         visible:false,
                                         minimized:false,
                                         title:poisMeteorologia[i].text,
                                         cssTitle:"contTitolPopup",
                                         content:'<span style="color:#858585;padding:4px;">'+poisMeteorologia[i].name+'</span><br/>'+'<span class="linkMostrar" style="cursor:pointer;padding:4px;" onclick="javascript:obrirPopup(poisMeteorologia['+i+'])">Mostrar detalls</span>',
                                         noHideOthers:true,
										 panMapIfOutOfView:true});
			}
			
			layerMeteorologiaVisible = true;
		}
	}else{
		for(var j = 0; j<poisMeteorologia.length; j++){
			cercalia.deleteMarkers(poisMeteorologia[j].id);
		}
		
		layerMeteorologiaVisible = false;
	}
}


function obrirPopup (arrayPoi) {
	

	var finestra = window.open("","Incidčncies","height=170,width=450,status=no,toolbar=no,menubar=no,location=no");

	finestra.document.write( '	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">');
	finestra.document.write( '<HTML>');
	finestra.document.write( '	<HEAD>');
	finestra.document.write( '		<TITLE></TITLE>');
	finestra.document.write( '		<LINK REL="stylesheet" HREF="mobilitat.css" TYPE="text/css"/>');
	finestra.document.write( '	</HEAD>');
	finestra.document.write( '	<BODY BGCOLOR="#EFEFE7" style="margin: 0px">');
	finestra.document.write( '	<CENTER>');
	finestra.document.write( '	<IMG SRC="img/empty.gif" border="0" width="1" height="10"/>');

	finestra.document.write('<TABLE id="miniincidencies_id" WIDTH="95%" CELLSPACING="0" CELLPADDING="0">');
	finestra.document.write('<TR>');
	finestra.document.write('	<TD WIDTH="100%" BGCOLOR="000000">');
	finestra.document.write('		<TABLE WIDTH="100%" CELLSPACING="1" CELLPADDING="1">');
	finestra.document.write('			<TR>');
	finestra.document.write('				<TD BGCOLOR="#AC2115" align="center">');

	/*if (level_description != "") stringTitol=level_description
	else stringTitol=affectation;*/

	finestra.document.write( '					<IMG SRC="img/empty.gif" border="0" width="1" height="3"/>');
	finestra.document.write('					<FONT class="text10blanc"><B>' + arrayPoi.level_description + '</B>&#160;&#160;</FONT><FONT class="text8blanc">' + arrayPoi.timestamp + '</FONT>' );
	finestra.document.write('				</TD>');
	finestra.document.write('			</TR>');
	finestra.document.write('		</TABLE>');
	
	finestra.document.write('		<TABLE WIDTH="100%" CELLSPACING="0" CELLPADDING="0" style="border:1px solid #000000">');

	finestra.document.write('			<TR>');
	finestra.document.write('				<TD BGCOLOR="white" align="center" valign="top" style="border-right:0px solid #FFFFFF;">');
	finestra.document.write( '					<IMG SRC="img/empty.gif" border="0" width="1" height="3"/>');
	finestra.document.write('					<IMG SRC="img/pois/incidencia_' + arrayPoi.type + '.gif">');
	finestra.document.write('				</TD>');

	finestra.document.write('				<TD WIDTH="100%" BGCOLOR="FFFFFF" colspan="2" style="border-left:0px solid #FFFFFF;">');
	finestra.document.write('					<FONT face="Arial,Helvetica" size="1">');
	finestra.document.write('					<TABLE class="text8" border="0" WIDTH="100%">');
	
	finestra.document.write('<TR><TD width="80">&#160;&#160;<B>Carretera:</B>&#160;</TD><TD>' + arrayPoi.road_code +'</TD><TD align="right"></TD></TR>');
	finestra.document.write('<TR><TD>&#160;&#160;<B>Punt inici:</B>&#160;</TD><TD>km.&#160;' + arrayPoi.pk_init +'&#160;('+ arrayPoi.poblation +')</TD><TD align="right"></TD></TR>');
//	finestra.document.write('<TR><TD>&#160;&#160;<B>' + string_poblation + ':</B>&#160;</TD><TD>' + poblation +'</TD><TD align="right"></TD></TR>');
	finestra.document.write('<TR><TD>&#160;&#160;<B>Punt fi:</B>&#160;</TD><TD>km.&#160;' + arrayPoi.pk_end +'</TD><TD align="right"></TD></TR>');
	finestra.document.write('<TR><TD>&#160;&#160;<B>Causa:</B>&#160;</TD><TD>' + arrayPoi.text +'</TD><TD align="right"></TD></TR>');
	if (arrayPoi.info != "") {
		finestra.document.write('<TR><TD>&#160;&#160;<B>Cap a:</B>&#160;</TD><TD>' + arrayPoi.info +'</TD><TD align="right"></TD></TR>');
	}

	finestra.document.write('					</TABLE>');
	finestra.document.write('				</TD>');
	finestra.document.write('			</TR>');
	finestra.document.write('		</TABLE>');
	finestra.document.write('	</TD>');
	finestra.document.write('</TR>');
	finestra.document.write('</TABLE>');

	finestra.document.write( '	</CENTER>');
	finestra.document.write( '	</BODY>');
	finestra.document.write( '	</HTML>');

	
	finestra.focus();
}

