/********************************************************************************************************************
*********************************************************************************************************************

	GEOGRAPHICA STUDIO S.L.
	Tomás Sánchez Falcón

**********************************************************************************************************************
**********************************************************************************************************************

	Here are all the functions needed for the data tab.

**********************************************************************************************************************
**********************************************************************************************************************/




/*********************************************************************************************************************
* Fuction that goes to the data index. it will be called by the second data tree section
**********************************************************************************************************************/

function goToTheDataIndex()
{
	

	Ext.get('datosTabContent').update("");

	var connection = new Ext.data.Connection();
	var ajaxUrl = 'html/dataIndex.php';

	connection.request (
		{
			url: ajaxUrl,
			method: 'POST',
    		params: {},
    					
			success: function (responseObject) 
			{
        			showGoToTheDataIndex(responseObject.responseText);
    			},
     			failure: function () 
			{
         			Ext.Msg.alert ('estado', 'timeout');
     			}
		}
	);
}

function showGoToTheDataIndex(t)
{
	Ext.get('datosTabContent').update("<div id='panelId' style='overflow:auto; width:100%; height:"+altura +"px; background:#FFFFFF;'></div>");
	Ext.get('panelId').update(t);
	adjustDataIndex();// @#
}

/*********************************************************************************************************************
* Expand the whole data tree for a selected town
**********************************************************************************************************************/
function expandAll(ine)
{
	expandANodeTree(ine,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);
}


/*********************************************************************************************************************
* Collapse the whole data tree for a selected town
**********************************************************************************************************************/
function collapseAll(ine)
{

	expandANodeTree(ine,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
		
}


/*********************************************************************************************************************
* Function that goes to a city data section. It recieves an ine code and calls
*an Ajax request to the php file php/dataTabTownSelected.php.
**********************************************************************************************************************/
function goToADataTown(ine)
{
	var width = screenWidthGlobal;
	var connection = new Ext.data.Connection();

	var urlAjax = "php/dataTabTownSelected.php?ine=" + ine+"&width="+width+"&height="+heightMunData+"&dataTabTargetObjectCode="+dataTabTargetObjectCode+"&treeForLocalization="+treeForLocalization;

	connection.request (
		{
			url: urlAjax,
			method: 'POST',
    		params: {'ine': ine, 'width':width,'height':heightMunData, 'dataTabTargetObjectCode':dataTabTargetObjectCode, 'suinfo':kvpSuinfo, 'treeForLocalization':treeForLocalization},
    					
			success: function (responseObject) 
			{
        		showAjaxResponseForDataTownSelected (responseObject.responseText,ine);
    		},
     			failure: function () 
			{
         	Ext.Msg.alert ('estado', 'Incapaz de mostrar el nombre de la ciudad para ese ine.');
     		}
		}
	);
}


/*********************************************************************************************************************
* handle procedure for the before function. See also it
**********************************************************************************************************************/
function showAjaxResponseForDataTownSelected(t,ine)
{
	Ext.get('datosTabContent').update("");

	p = new Ext.Panel({
			   renderTo: 'datosTabContent',
			   width:'100%',
				height:altura,
				hideBorders:true,
				autoScroll: false,
				html: t,
				border: false
	});

	// lets find out if a special table inside tree is to be shown for a specific object to be visible
	if(dataTabTargetObjectType!=null && dataTabTargetObjectCode!=null)
	{
		//----------------------------------------------------------------------------------------------------------------
		// node map
		// node 1:			Datos Generales
		// node 2:			Equipamientos
		// node 3:			Infraestructuras
		// node 4:			Población y vivienda
		// node 5:			Planeamiento urbanístico
		// node 6:			Instalaciones deportivas
		// node 7:			Centros culturales
		// node 8:			Espacios para la convivencia
		// node 9:			Mercados y recintos feriales
		// node 10:			Cementerios y tanatorios
		// node 11:			Mataderos
		// node 12:			Centros sanitarios
		// node 13:			Centros asistenciales
		// node 14:			Centros de enseñanza
		// node 15:			Bomberos y protección civil
		// node 16:			Ayuntamientos y otros centros municipales
		// node 17:			Edificios sin uso
		// node 18:			Comunicación y energía
		// node 19:			Carreteras
		// node 20:			Viario urbano
		// node 21:			Alumbrado
		// node 22:			Ciclo del agua
		// node 23:			Cementerios
		// node 24:			Tanatorios
		// node 25:			Energía
		// node 26:			Comunicaciones
		// node 27:			Captaciones																	07
		// node 28:			Depósitos
		// node 29:			Red de distribución interior
		// node 30:			Red de alcantarillado
		// node 31:			Depuradoras																	29

		//----------------------------------------------------------------------------------------------------------------
		// object map								code															node		table
		// type 0 = Servicios
		//												2010|LM|41|023|0001|01|001|11							9			42
		//												2010|PJ|41|023|0001|01|008|13							8			41
		//												2010|CU|41|023|0001|01|002|5							7			39
		//												2010|EN|41|023|0001|01|002|7							14			48
		//												2010|SA|41|023|0001|01|001|8							12			46
		//												2010|IP|41|023|0001|01|001|14							15			50
		//												2010|ID|41|023|0001|01|001|10							6			37
		// 											2010|CC|41|023|0001|01|002|3							16			51
		//												2010|MT|41|009|0001|01|001|12							11			43
		//												2010|AS|41|009|0001|01|002|6							13			47
		//												2010|SU|41|023|0001|01|001|9							17			53
		//												tanatorios													24			45
		//												cementerios													23			44
		//
		// type 2 = Carreteras
		//												-																19			4
		//
		// type 3 = Municipio
		//												41|023														1
		//			

		var nodeId = "";
		if(dataTabTargetObjectType==0)
		{
			// Servicios
			var subtype = dataTabTargetObjectCode.substring(5,7);
			if(subtype=="LM")
			{
				nodeId = "node9bid";
			}
			else
			if(subtype=="PJ")
			{
				nodeId = "node8bid";
			}
			else
			if(subtype=="CU")
			{
				nodeId = "node7bid";
			}
			else
			if(subtype=="EN")
			{
				nodeId = "node14bid";
			}
			else
			if(subtype=="SA")
			{
				nodeId = "node12bid";
			}
			else
			if(subtype=="IP")
			{
				nodeId = "node15bid";
			}
			else
			if(subtype=="ID")
			{
				nodeId = "node6bid";
			}
			else
			if(subtype=="CC")
			{
				nodeId = "node16bid";
			}
			else
			if(subtype=="MT")
			{
				nodeId = "node11bid";
			}
			else
			if(subtype=="AS")
			{
				nodeId = "node13bid";
			}
			else
			if(subtype=="SU")
			{
				nodeId = "node17bid";
			}
			else
			if(subtype=="TA")
			{
				nodeId = "node24bid";
			}
			else
			if(subtype=="CE")
			{
				nodeId = "node23bid";
			}
			else
			{
				alert("subtypo de servicio desconocido, subtype: "+subtype+", dataTabTargetObjectType: "+dataTabTargetObjectType+", dataTabTargetObjectCode: "+dataTabTargetObjectCode);
			}
		}
		else
		if(dataTabTargetObjectType==1)
		{
			// Edificios
			nodeId = "node2bid";
		}
		else
		if(dataTabTargetObjectType==2)
		{
			// Carretera
			nodeId = "node19bid";
		}
		else
		if(dataTabTargetObjectType==3)
		{
			// Núcleo de población
			nodeId = "node1bid";
		}
		else
		if(dataTabTargetObjectType==4)
		{
			// Municipio
			nodeId = "node1bid";
		}
		if(nodeId.length==0)
		{
			// unable to deduce appropiate node for this object
			alert("No se pudo encontrar el nodo de datos correspondiente al objeto, dataTabTargetObjectType: "+dataTabTargetObjectType+", dataTabTargetObjectCode: "+dataTabTargetObjectCode);
		}
		else
		{
			// lets set the scroll value
			var scrollLocation = getY(document.getElementById(nodeId));// an example value could be 'node10bid'
			//alert("nodeId: "+nodeId+", scrollLocation: "+scrollLocation);
			setDataScroll(scrollLocation);
		}

		// development tests
		/*var element;
		element = document.getElementById('panelIdOverflow2');
		if(element!=null)
		{
			//alert(element);
			//var scrollLocation = getY(document.getElementById('node19bid'));
			var scrollLocation = getY(document.getElementById('node10bid'));
			//alert("scrollLocation: "+scrollLocation);
			//element.scrollTop = scrollLocation;// this gives innexact results
			setDataScroll(scrollLocation);
		}*/

		// by now this javascript method must have been already defined by the same PHP that created the tables
		//var el = Ext.get("letsDefineTheElementToHighlight");//document.getElementById("abcd1");
		//alert(el);
		//var cadena = el.dom.title;
		//alert(cadena);
		//letsDefineTheElementToHighlight();
		//highlightedDataLineId = el.dom.title;
		//alert("highlightedDataLineId: "+highlightedDataLineId);
	}
	dataTabTargetObjectType = null;
	dataTabTargetObjectCode = null;

	adjustDataTownSelected();
}

function adjustDataTownSelected()
{
	// adjust left margin of 'townTable33' for ie7 @#
	var townTable33 = Ext.get('townTable33');
	//townTable33.applyStyles("background-color: #007000;");
	if(isIe7())
	{
		townTable33.applyStyles("margin-left:-27px;");
		townTable33.applyStyles("margin-top:20px;");
	}
	if(isIe8())
	{
		townTable33.applyStyles("margin-top:20px;");
	}
}


/*********************************************************************************************************************
* Function that shows the ajax response after calling the php file dataTabTownSelected.php 
* (it includes dataTree.php file)
**********************************************************************************************************************/
function expandANodeTree(ine,id1,id2,id3,id4,id5,id6,id7,id8,id9,id10,id11,id12,id13,id14,id15,id16,id17,id18,id19,id20,id21,id22,id23,id24,id25,id26,id27,id28,id29,id30,id31,h)
{
	var connection = new Ext.data.Connection();
	var width = screenWidthGlobal;
	var ajaxUrl = 'php/dataTabTownSelected.php?ine=' + ine +'&id1=' + id1 + '&id2=' + id2 + '&id3=' + id3 +  '&id4=' + id4 +  '&id5=' + id5 + '&id6=' + id6 + '&id7=' + id7 + '&id8=' + id8 + '&id9=' + id9 + '&id10=' + id10 + '&id11=' + id11 + '&id12=' + id12 + '&id13=' + id13 + '&id14=' + id14 + '&id15=' + id15 + '&id16=' + id16 + '&id17=' + id17 + '&id18=' + id18 + '&id19=' + id19 + '&id20=' + id20 + '&id21=' + id21 + '&id22=' + id22 + '&id23=' + id23 + '&id24=' + id24 + '&id25=' + id25 + '&id26=' + id26 + '&id27=' + id27 + '&id28=' + id28 + '&id29=' + id29 + '&id30=' + id30 + '&id31=' + id31+'&width='+width + '&height='+heightMunData;

	connection.request (
		{
			url: ajaxUrl,
			method: 'POST',
    			params: {'ine': ine, 'id1': id1, 'id2':id2, 'id3':id3, 'id4':id4, 'id5':id5, 'id6':id6, 'id7':id7, 'id8':id8, 'id9':id9, 'id10':id10, 'id11':id11, 'id12':id12, 'id13':id13, 'id14':id14, 'id15':id15, 'id16':id16, 'id17':id17, 'id18':id18, 'id19':id19, 'id20':id20, 'id21':id21, 'id22':id22, 'id23':id23, 'id24':id24, 'id25':id25, 'id26':id26, 'id27':id27, 'id28':id28, 'id29':id29, 'id30':id30, 'id31':id31,'width':width,'height':heightMunData},
    					
			success: function (responseObject) 
			{
        			showAjaxResponseForDataTree(responseObject.responseText,h);
    			},
     			failure: function () 
			{
         			Ext.Msg.alert ('estado', 'Incapaz de mostrar el nombre de la ciudad para ese ine.');
     			}
		}
	);
}


/*********************************************************************************************************************
* handle procedure for the before function. See also it
*
* @param h is the absolute height of the element. it's been calculated by a javascript function.
* t: is the complete data tab tree HTML, just downloaded with ajax
* h: is the height of t, is calculated outside this method
**********************************************************************************************************************/
function showAjaxResponseForDataTree(t,h)
{
	Ext.get('datosTabContent').update("<div id='panelId' style='width:100%;height:"+ altura+"px;'></div>");
	Ext.get('panelId').update(t);
	setDataScroll(h);
	adjustDataTownSelected();
}

function setDataScroll(h)
{
	divHeight=document.getElementById('panelIdOverflow2').offsetHeight;	
	currenttop = document.getElementById('panelIdOverflow2').scrollTop;
	scrollheight = document.getElementById('panelIdOverflow2').scrollHeight;
	document.getElementById('panelIdOverflow2').scrollTop= h - 225 +25;
}

/**
 * uses global variables 'currentScrollTop', 'currentScrollLeft', 'currentScrollIndexTownTop' and 'currentScrollIndexTownLeft'  to set the scroll position of the data tab tree
 */
function setCurrentScroll()
{
	var element;
	if (currentScrollTop!=null && currentScrollTop>0)
	{
		element = document.getElementById('panelIdOverflow2');
		if (element!=null)
		{
			element.scrollTop = currentScrollTop;
		}
	}
	if (currentScrollLeft!=null && currentScrollLeft>0)
	{
		element = document.getElementById('panelIdOverflow2');
		if (element!=null)
		{
			element.scrollLeft = currentScrollLeft;
		}
	}
	if (currentScrollIndexTownTop!=null && currentScrollIndexTownTop>0)
	{
		element = document.getElementById('panelId');
		if (element != null)
		{
			element.scrollTop = currentScrollIndexTownTop;
		}
	}
	if (currentScrollIndexTownLeft!=null && currentScrollIndexTownLeft>0)
	{
		element = document.getElementById('panelId');
		if (element != null)
		{
			element.scrollLeft = currentScrollIndexTownLeft;
		}
	}	
}

/**
 * DEPRECATED: this is currently used if the specified object key is equal to dataTabTargetObjectCode then the given table ndx and line ndx are captured at highlightedDataLineId, so later that line will be highlighted at the
 * data tab 
 */
/*function captureDataTabTableAndLineForHighlightedObject(objectKey,tableNdxStr,lineNdx)
{
	if(objectKey==dataTabTargetObjectCode)
	{
		// we found it
		highlightedDataLineId = "table"+tableNdxStr+"line"+lineNdx;
	}
}*/

function changeLineToGreen(id,fin)
{
	for(i=1;i<=fin;i++)
	{		
		var lineId = id+'col'+i;
		/*if(highlightedDataLineId==id)
		{
			// highlighted line
			window.document.getElementById(lineId).style.background = highlightedDataLineBackground;
		}
		else*/
		if(window.document.getElementById(lineId).className!="dataTabHigligthedLine")
		{
			window.document.getElementById(lineId).style.background="#CCFF99";		
		}
	}
}

function changeLineToNormal3(id,fin)
{
	for(i=1;i<=fin;i++)
	{		
		var lineId = id+'col'+i;
		/*if(highlightedDataLineId==id)
		{
			// highlighted line
			window.document.getElementById(lineId).style.background = highlightedDataLineBackground;
		}
		else*/
		if(window.document.getElementById(lineId).className!="dataTabHigligthedLine")
		{
			window.document.getElementById(lineId).style.background = "#F9F8F8";
		}
	}
}

function changeLineToNormal2(id,fin)
{
	for(i=1;i<=fin;i++)
	{		
		var lineId = id+'col'+i;
		/*if(highlightedDataLineId==id)
		{
			// highlighted line
			window.document.getElementById(lineId).style.background = highlightedDataLineBackground;
		}
		else*/
		if(window.document.getElementById(lineId).className!="dataTabHigligthedLine")
		{
			window.document.getElementById(lineId).style.background="#FFFFFF";		
		}
	}
}

function changeLineToLightGreen(id)
{
	if(window.document.getElementById(id).className!="dataTabHigligthedLine")
	{
		window.document.getElementById(id).style.background="#edf8fd";
		window.document.getElementById(id+'b').style.background="#edf8fd";
	}
}

function changeLineToNormalForTableHeader(id)
{
	window.document.getElementById(id).style.background="#ffffff";
	window.document.getElementById(id+'b').style.background="#ffffff";
}


/*********************************************************************************************************************
VGI procedures
**********************************************************************************************************************

procedencia de las vgi's


tipo: 0	Servicios					=> VGI EQUIPAMIENTO
		1	Edificios					=> VGI EQUIPAMIENTO							
		2	Carretera					=> VGI CARRETERA								
		3	Núcleo de población 		=> VGI MUNICIPIO								
		4	Municipio					=> VGI MUNICIPIO									
		5	Búsqueda						=> VGI BUSQUEDA
		6  Incidencia					=> VGI INCIDENCIA


**********************************************************************************************************************
**********************************************************************************************************************/
function showVGI(code,type)
{
//alert("code "+code+", type "+type);
	var w = screenWidthGlobal;
	var h = screenHeightGlobal;	

	switch(type)
	{
		case 0:
			showGeneralVGI(code,type);
			break;

		case 1:
			showGeneralVGI(code,type);
			break;
		case 2:
			showGeneralVGI(code,type);
			break;

		case 3:
			showGeneralVGI(code,type);
			break;

		case 4:
			showGeneralVGI(code,type);
			break;

		case 5:			
			showIssueVGI(code,type);
			vgiFlagIssue = true;
			break;

		case 6:
			
			showSearchVGI(code,type);
			vgiFlagSearch = true;
			break;

	}
	
	
}

function showGeneralVGI(code,type)
{
	var myFullScreen = false;
	try
	{
      myFullScreen = pulsarFullScreen;
   }
	catch(err)
	{
		// the variable is undefined
		myFullScreen = false;
	}

	w = screenWidthGlobal;
	h = screenHeightGlobal;
	var offsetRightVGI = 80;
	

	if(win==null)//no existe una VGI lanzada actualmente
	{
		switch(type)
		{
			case 0:
				win = new Ext.Window
				(
					{
						layout      : 'fit',
						width       : 290,
						height      : vgiHeight, 
						closeAction :'close',
						plain       : true,
						autoLoad    :
											{ 
		                           	url:'php/equipamiento.php', 
		                             	params:{'code':code, 'type':type, 'fullScreen':myFullScreen}
											},
						title			:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/i.png\" ></td><td valign=\"top\"><font class=\"roadTextTitle\" align=\"left\">Equipamiento</font></td></tr></table></div>",
						listeners: {close:handleCloseWindow},
						resizable	: false,
						x : w - 290 - offsetRightVGI,
						y : (h/2) - (vgiHeight *0.7),
						constrainHeader : true,
						shadow:false
					}
				);
				win.show();
				vgiFlag = true;
			break;

			case 1:
				win = new Ext.Window
				(
					{
						layout      : 'fit',
						width       : 490,
						height      : vgiHeight, 
						closeAction :'close',
						plain       : true,
						autoLoad    :
											{ 
		                           	url:'php/equipamiento.php', 
		                             	params:{'code':code, 'type':type, 'fullScreen':myFullScreen}
											},
						title			:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/i.png\" ></td><td valign=\"top\"><font class=\"roadTextTitle\" align=\"left\">Equipamiento</font></td></tr></table></div>",
						listeners: {close:handleCloseWindow},
						resizable	: false,
						x : w - 490 - offsetRightVGI,
						y : (h/2) - (vgiHeight *0.7),
						constrainHeader : true,
						shadow:false
					}
				);
				win.show();
				vgiFlag = true;
			break;

			case 2:
				win = new Ext.Window
				(
					{
					
						layout      : 'fit',
						width       : 290,
						height      : vgiHeight, 
						closeAction :'close',
						plain       : true,
						autoLoad    :
											{ 
		                           	url:'php/road.php', 
		                             	params:{'code':code, 'type':type}
											},
						title			:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/road.png\" ></td><td valign=\"top\"><font class=\"roadTextTitle\" align=\"left\" >Carretera</font></td></tr></table></div>",
						listeners: {close:handleCloseWindow},
						x : w - 290 - offsetRightVGI,
						y : (h/2) - (vgiHeight *0.7),
						resizable	: false,
						constrainHeader : true,
						shadow:false
					
					}
				);
				win.show();
				vgiFlag = true;
			break;

			case 3:
				//se trata de un VGI MUNICIPIO
				win = new Ext.Window
				(
					{
				
						layout      : 'fit',
						width       : 290,
						height      : vgiHeight, 
						closeAction :'close',
						plain       : true,
						autoLoad    :
											{ 
		                           	url:'php/town.php', 
		                             	params:{'code':code, 'type':type, 'fullScreen':myFullScreen}
		                             	//params:{'code':code, 'type':type, 'fullScreen':true}
											},
				
						title:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/icon-barra_info.png\"></td><td valign=\"middle\"><font class=\"roadTextTitle\" align=\"left\">Municipio</font></td></tr></table></div>",
						listeners: {close:handleCloseWindow},
						resizable	: false,
						x : w - 290 - offsetRightVGI,
						y : (h/2) - (vgiHeight *0.7),
						constrainHeader : true,
						shadow:false
				
					}
				);
				win.show();
				vgiFlag = true;
			break;

			case 4:
				win = new Ext.Window
				(
					{				
						layout      : 'fit',
						width       : 290,
						height      : vgiHeight, 
						closeAction :'close',
						plain       : true,
						autoLoad    :
											{ 
		                           	url:'php/town.php', 
		                             	params:{'code':code, 'type':type, 'fullScreen':myFullScreen}
											},
				
						title:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/icon-barra_info.png\"></td><td valign=\"middle\"><font class=\"roadTextTitle\" align=\"left\">Municipio</font></td></tr></table></div>",
						listeners: {close:handleCloseWindow},
						resizable	: false,
						x : w - 290 -offsetRightVGI,
						y : (h/2) - (vgiHeight *0.7),
						constrainHeader : true,
						shadow:false				
					}
				);
				win.show();
				vgiFlag = true;
			break;

			case 5:
				showIssueVGI(code,type);
				vgiFlagIssue = true;
				break;
			case 6:
				showSearchVGI(code,type/*,offsetRightVGI*/);
				vgiFlagSearch = true;
			break;
		
				
		}
	}
	else//existe una VGI lanzada actualmente
	{
		var posx = win.x;
		var posy = win.y;

		win.close();

		if(type==0 || type==1)//edificio
		{
			win = new Ext.Window
				(
					{
						layout      : 'fit',
						width       : 290,
						height      : vgiHeight, 
						closeAction :'close',
						plain       : true,
						autoLoad    :
											{ 
		                           	url:'php/equipamiento.php', 
		                             	params:{'code':code, 'type':type, 'fullScreen':myFullScreen}
											},
						title			:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/i.png\" ></td><td valign=\"top\"><font class=\"roadTextTitle\" align=\"left\">Equipamiento</font></td></tr></table></div>",
						listeners: {close:handleCloseWindow},
						resizable	: false,
						x : posx,
						y : posy,
						constrainHeader : true,
						shadow:false
					}
				);
				win.show();
				vgiFlag = true;
		}
		if(type==2)//carretera
		{
			win = new Ext.Window
				(
					{
					
						layout      : 'fit',
						width       : 290,
						height      : vgiHeight, 
						closeAction :'close',
						plain       : true,
						autoLoad    :
											{ 
		                           	url:'php/road.php', 
		                             	params:{'code':code, 'type':type}
											},
						title			:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/road.png\" ></td><td valign=\"top\"><font class=\"roadTextTitle\" align=\"left\" >Carretera</font></td></tr></table></div>",
						listeners: {close:handleCloseWindow},
						x : posx,
						y : posy,
						resizable	: false,
						constrainHeader : true,
						shadow:false
					
					}
				);
				win.show();
				vgiFlag = true;
		}
		if(type==3 || type==4)
		{
			win = new Ext.Window
			(
				{
				
					layout      : 'fit',
					width       : 290,
					height      : vgiHeight, 
					closeAction :'close',
					plain       : true,
					autoLoad    :
										{ 
                              	url:'php/town.php', 
                                	params:{'code':code, 'type':type, 'fullScreen':myFullScreen}
										},

				
					title:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/icon-barra_info.png\"></td><td valign=\"middle\"><font class=\"roadTextTitle\" align=\"left\">Municipio</font></td></tr></table></div>",
					listeners: {close:handleCloseWindow},
					resizable	: false,
					x : posx,
					y : posy,
					constrainHeader : true,
					shadow:false
				
				}
			);
			win.show();
			vgiFlag = true;
		}
	}	
}

function showIssueVGI(code,type)
{
	var w = screenWidthGlobal;
	var h = screenHeightGlobal;


	if(winIssue==null)//si no existe una VGI de incidencia nueva
	{
		winIssue = new Ext.Window
			(
				{
				
					layout      : 'fit',
					width       : 290,
					height      : vgiHeight, 
					closeAction :'close',
					plain       : true,
					autoLoad    :
										{ 
                              	url:'php/incidencia.php', 
                                	params:{'code':code, 'type':type}
										},
					title:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/iiii.png\"></td><td valign=\"top\"><font class=\"roadTextTitle\" align=\"left\">Enviar incidencia</font></td></tr></table></div>",
					listeners: {close:handleCloseWindowIssueVGI},
					x : (w/2)-130,
					y : (h/2) - (vgiHeight *0.7),
					resizable	: false,
					constrainHeader : true,
					shadow:false
					
				
				}
			);
		winIssue.show();
		vgiFlagIssue = true;
	}
	else//si existe una VGI de incidencia
	{
		var posx = winIssue.x;
		var posy = winIssue.y;

		winIssue.close();
		winIssue = null;
	
		winIssue = new Ext.Window
			(
				{
				
					layout      : 'fit',
					width       : 290,
					height      : vgiHeight, 
					closeAction :'close',
					plain       : true,
					autoLoad    :
										{ 
                              	url:'php/incidencia.php', 
                                	params:{'code':code, 'type':type}
										},
					title:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/iiii.png\"></td><td valign=\"top\"><font class=\"roadTextTitle\" align=\"left\">Enviar incidencia</font></td></tr></table></div>",
					listeners: {close:handleCloseWindowIssueVGI},
					x : posx,
					y : posy,
					resizable	: false,
					constrainHeader : true,
					shadow:false
					
				
				}
			);
		winIssue.show();
		vgiFlagIssue = true;

	}
	
}

function showSearchVGI(text,filter)
{
	var w = screenWidthGlobal;
	var h = screenHeightGlobal;
	
  	if(winSearch==null)//si no existe una VGI de búsqueda activa
	{
		winSearch = new Ext.Window
		(
			{
				
					layout      : 'fit',
					width       : 300,
					height      : vgiHeight, 
					closeAction :'close',
					plain       : true,
					autoScroll : true,
					autoLoad    :
										{ 
                              	url:'php/searchVGI.php?text='+text+'&filter='+filter, 
                                	params:{'text':text, 'filter':filter}
										},
					title:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"top\" height=\"14\" width=\"20\"><img src=\"img/icon-barra_busquedas.png\"></td><td valign=\"middle\"><font class=\"roadTextTitle\" align=\"left\">Resultado de b&uacute;squeda</font></td></tr></table></div>",
					listeners: {close:handleCloseWindowSearchVGI},
					x : 80,
					y : (h/2) - (vgiHeight *0.7),
					resizable	: false,
					constrainHeader : true,
					shadow:false				
			}
		);
		winSearch.show();
		vgiFlagSearch = true;
	}
	else//si existe una VGI activa
	{
		
		var posx = winSearch.x;
		var posy = winSearch.y;
		
		winSearch.close();
		winSearch = null;
//alert("showSearchVGI: text="+text+", filter="+filter);
		winSearch = new Ext.Window
		(
			{
				
					layout      : 'fit',
					width       : 290,
					height      : vgiHeight, 
					closeAction :'close',
					plain       : true,
					autoScroll : true,
					autoLoad    :
										{ 
                              	url:'php/searchVGI.php?text='+text+'&filter='+filter, 
                                	params:{'text':text, 'filter':filter}
										},
					title:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"top\" height=\"14\" width=\"20\"><img src=\"img/icon-barra_busquedas.png\"></td><td valign=\"middle\"><font class=\"roadTextTitle\" align=\"left\">Resultado de b&uacute;squeda</font></td></tr></table></div>",
					listeners: {close:handleCloseWindowSearchVGI},
					x : posx,
					y : posy,
					resizable	: false,
					constrainHeader : true,
					shadow:false				
			}
		);
		winSearch.show();
		vgiFlagSearch = true;
		
	}
	
}

function showEquipamiento3DVGI(cod_ine,cod_edi,base_url)
{
	var w = screenWidthGlobal;
	var h = screenHeightGlobal;
	var content = "<div id=\"container\">Loading the player ...</div>";
	var vgiHeight = 350;
	var vgiWidth = 380;

  	if(winEquipamiento3D==null)//si no existe una VGI de búsqueda activa
	{
		winEquipamiento3D = new Ext.Window
		(
			{

					layout      : 'fit',
					width       : vgiWidth,
					height      : vgiHeight,
					closeAction :'close',
					plain       : true,
					autoScroll  : true,
					html : content,
					title			:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/road.png\" ></td><td valign=\"top\"><font class=\"roadTextTitle\" align=\"left\" >Equipamiento 3D</font></td></tr></table></div>",
					listeners: {close:handleCloseWindowEquipamiento3DVGI},
					
					x : 80,
					y : (h/2) - (vgiHeight *0.7),
					resizable	: false,
					constrainHeader : true,
					shadow:false
			}
		);
		winEquipamiento3D.show();
	}
	else//si existe una VGI activa
	{

		var posx = winEquipamiento3D.x;
		var posy = winEquipamiento3D.y;

		winEquipamiento3D.close();
		winEquipamiento3D = null;

		winEquipamiento3D = new Ext.Window
		(
			{

					layout      : 'fit',
					width       : vgiWidth,
					height      : vgiHeight,
					closeAction :'close',
					plain       : true,
					autoScroll : true,
					html   : content,
					title			:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"middle\" height=\"14\" width=\"20\"><img src=\"img/road.png\" ></td><td valign=\"top\"><font class=\"roadTextTitle\" align=\"left\" >Equipamiento 3D</font></td></tr></table></div>",
					listeners: {close:handleCloseWindowEquipamiento3DVGI},
					x : posx,
					y : posy,
					resizable	: false,
					constrainHeader : true,
					shadow:false
			}
		);
		winEquipamiento3D.show();	

	}

	//launch player	
	jwplayer("container").setup({
		flashplayer: base_url + "jwplayer/player.swf",
		file:  base_url + "video/" + cod_ine + "/vgi_3d/" + cod_edi +".flv",
		image:  base_url + "video/" + cod_ine + "/vgi_3d/" + cod_edi +"_thumb.jpg",
		height: 280,
		width: 350,
		autostart: true

	});
	


}


function showVGIFromPHP(fullCode,type)
{

	switch (type)
	{
		case "0"://edificio 2010|PJ|41|017|0001|01|011|13
		showIssueVGI(fullCode,0);
		break;

		case "1"://servicio 2010|PJ|41|017|0001|01|011|13
		showIssueVGI(fullCode,1);
		break;


		case "2"://carretera 2010|N-IV|41
		codeSplit = fullCode.split("|");
		showIssueVGI(codeSplit[1],2);
		break;

		case "3"://municipio 41024
		//alert(fullCode);
		prov = fullCode.substring(0,2);
		mun = fullCode.substring(2);
		showIssueVGI(prov+'|'+mun,3);
		break;

		case "4"://nucleo de poblacion  41024000101
		//alert(fullCode);
		prov = fullCode.substring(0,2);
		mun = fullCode.substring(2);
		showIssueVGI(prov+'|'+mun,4);
		break;
	};

}

/*
*******************************************************************************************
******************************************************************************************/

/**
 * returns the height in pixels of the specified HTML element
 */
function getCurrentHeight(id)
{
	var height = document.getElementById(id).offsetHeight;
	return height;
}

function getY( oElement )
{
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	
	return iReturnValue;

}

function handleCloseWindowSearchVGI()
{
	vgiFlagSearch = false;
	winSearch = null;
}

function handleCloseWindow()
{
	vgiFlag = false;
	win = null;
}

function handleCloseWindowEquipamiento3DVGI()
{
	winEquipamiento3D = null;	
}

function handleCloseWindowIssueVGI()
{
	vgiFlagIssue = false;
	winIssue = null;
}

function callMapForZoom(x0,y0,x1,y1,x,y,type,pk)
{
	if(x0!='-1' && y0!='-1' && x1!='-1' && y1!='-1' && x!='-1' && y!='-1')
	{
	
		MiradorMashup.zoomToElement(x0,y0,x1,y1,x,y,type,pk);
		this.tabs2.setActiveTab("mapas");
	}	
}

function getPDFForATown(fullIne)
{
	try 
	{
		// this fails when in fullscreen mode
		this.tabs2.setActiveTab("datos");
		goToADataTown(fullIne);
	}
	catch(err) {}
	open('pdfs/'+fullIne+'.pdf');

}

function getPDFForATownFromSearchVGI(fullIne)
{
	this.tabs2.setActiveTab("datos");
	goToADataTown(fullIne);
	/*document.getElementById('datosTabContent').style.visibility='visible';
	document.getElementById('datosTabContent').style.display='inline';*/
	open('pdfs/'+fullIne+'.pdf');
}

/**
 * shows the data tab for the specified town,
 * new functionality: shows the data tree exactly opened at the specified object
 */
function getDataTabForATown(fullIne,objectType,objectCode)
{
	//alert("estoy en getDataTabForATown(), fullIne="+fullIne+", objectType="+objectType+", objectCode="+objectCode);
	dataTabTargetObjectType = objectType;
	dataTabTargetObjectCode = objectCode;
	this.tabs2.setActiveTab("datos");
	goToADataTown(fullIne);//
	/*document.getElementById('datosTabContent').style.visibility='visible';
	document.getElementById('datosTabContent').style.display='inline';*/
	//win.close();
}

/** shows data tab for a town, no secondary object selected for display */
/*function getDataTabForATown(fullIne)
{
alert("12");
	dataTabTargetObjectType = null;
	dataTabTargetObjectCode = null;
	this.tabs2.setActiveTab("datos");
	goToADataTown(fullIne);
	//win.close();
}*/

function getDataTabForATownFromSearchVGI(fullIne)
{
	
	this.tabs2.setActiveTab("datos");
	goToADataTown(fullIne);
	/*document.getElementById('datosTabContent').style.visibility='visible';
	document.getElementById('datosTabContent').style.display='inline';*/
	
}

function getFotosTabForATownFromSearchVGI(fullIne,townName)
{

	this.tabs2.setActiveTab("fotos");
	// all slideshow
   //goToTheTownPicsShow(fullIne,townName);
   goToTheTownPicsShow_shadowbox(fullIne,townName);
}

function getFotosTabForATown(fullIne,townName)
{
	this.tabs2.setActiveTab("fotos");
	// all slideshow
   //goToTheTownPicsShow(fullIne,townName);
   goToTheTownPicsShow_shadowbox(fullIne,townName);
}

function changeButton(id,newButton)
{
	document.getElementById(id).src=newButton;
}

function issueCancelButtonAction()
{
	
	winIssue.close();
}

function issueSendButtonAction(code,type,servicioEdificio,municipio,incidenciaText,email)
{

	var connection = new Ext.data.Connection();
	var urlF = 'php/procesaIncidencia.php?code=' + code + '&type='+ type + '&servicioEdificio=' + servicioEdificio + '&municipio='+ municipio + '&incidenciaText='+ incidenciaText+'&email='+email;


	connection.request (
		{
			url: urlF,
			method: 'POST',
    			params: {'code': code, 'type':type, 'servicioEdificio':servicioEdificio, 'municipio':municipio, 'incidenciaText':incidenciaText, 'email':email},
    					
			success: function (responseObject) 
			{
        			showIssueSendAction(responseObject.responseText);
    			},
     			failure: function () 
			{
         			Ext.Msg.alert ('estado','Incapaz de mostrar el nombre de la ciudad para ese ine.');
     			}
		}
	);
	winIssue.close();
}

function showIssueSendAction(t)
{

}

/** only for map tab search */
function validateKeyPressed(e) {
	if(currentlySelectedTabTitle!="Mapas")
	{
		return;
	}

	if (window.event)
	{ 
		e = window.event; 
	}
   if (e.keyCode == 13)
   {
		if(document.getElementById('searchText').value!="")
		{
			showSearchVGI(document.getElementById('searchText').value,document.getElementById('searchFilter').value);
		}
   }

}

/** only for data tab search */
function validateKeyPressed2(e) {
	if(currentlySelectedTabTitle!="Datos")
	{
		return;
	}
 
	if (window.event)
	{ 
		e = window.event; 
	}
   if (e.keyCode == 13)
   {
		if(document.getElementById('searchText2').value!="")
		{
			showSearchVGI(document.getElementById('searchText2').value,document.getElementById('searchFilter2').value);
		}
   }
}

/** only for photo tab search */
function validateKeyPressed3(e) {
	if(currentlySelectedTabTitle!="Fotos")
	{
		return;
	}
 
	if (window.event)
	{ 
		e = window.event; 
	}
   if (e.keyCode == 13)
   {
		if(document.getElementById('searchText3').value!="")
		{
			showSearchVGI(document.getElementById('searchText3').value,document.getElementById('searchFilter3').value);
		}
   }
}

function moveFocusToTheSearchTextField()
{
	//document.getElementById('searchText').focus();
}


/** only for map tab search */
function checkTextToFilter(searchText,searchFilter)
{
	if(currentlySelectedTabTitle!="Mapas")
	{
		return;
	}
	if(searchText!="")
	{
		showSearchVGI(searchText,searchFilter);
	}
}

/** only for data tab search */
function checkTextToFilter2(searchText,searchFilter)
{
	if(currentlySelectedTabTitle!="Datos")
	{
		return;
	}
	if(searchText!="")
	{
		showSearchVGI(searchText,searchFilter);
	}
}

/** only for data tab search */
function checkTextToFilter3(searchText,searchFilter)
{
	if(currentlySelectedTabTitle!="Fotos")
	{
		return;
	}
	if(searchText!="")
	{
		showSearchVGI(searchText,searchFilter);
	}
}

function showVgiFromPulsar(type,code)
{
//alert("showVgiFromPulsar("+type+","+code+")");
	switch(type)
	{
		case "0"://edificio 2010|PJ|41|017|0001|01|011|13
			var connection = new Ext.data.Connection();
			var urlF = 'php/geometriesCode2FieldsToSearchEielCode.php?id_edificio=' + code;
			var composeCode;
			connection.request (
				{
					url: urlF,
					method: 'GET',
		    		params: {'id_edificio': code},
		    		success: function (responseObject) 
					{		    		
						var responseText = responseObject.responseText.trim();

		    			composeCode =
		    				'2010|'+
							responseText.substring(0,2)+'|'+
							responseText.substring(2,4)+'|'+
							responseText.substring(4,7)+'|'+
							responseText.substring(7,11)+'|'+
							responseText.substring(11,13)+'|'+
							responseText.substring(13,16)+'|'+
							responseText.substring(16);
		    			showVGI(composeCode,parseInt(type));
		    		},
		     		failure: function () 
					{
		    			Ext.Msg.alert ('estado','Incapaz de mostrar la VGI para el poligono seleccionado');
					}
				}
			);
			break;
		case '2':
			showVGI('2010|'+code+'|41',parseInt(type));
			break;
		case '3':
			prov = code.substring(0,2);
			mun = code.substring(2);
			showVGI(prov+"|"+mun,parseInt(type));
			break;
	}
}
function checkRouteClickEnter (event)
{
	var lat = jQuery("#lat").val();
	var lng = jQuery("#lng").val();
	if (event.keyCode == 13)
	{
		MiradorMashup.calculateRoute(lat,lng);
	}
}
function showRouteVGI(lat,lng,destination)
{
	
	if (winRoute)
	{
		winRoute.close();
	}
  	
	var posx = win.x;
	var posy = win.y;

	winRoute = new Ext.Window
	(
		{

				layout      : 'fit',
				width       : 300,
				height      : vgiHeight,
				closeAction :'close',
				plain       : true,
				autoScroll : true,
				autoLoad    :
									{
										url:'php/route.php?lat='+lat+'&lng='+lng+'&destination='+destination,
										params:{'lat':lat, 'lng':lng,'destination' :destination},
										callback:function(){											
											if (jQuery.browser.mozilla)
											{
												jQuery("#origin").keypress (checkRouteClickEnter);
											}
											else
											{
												jQuery("#origin").keydown (checkRouteClickEnter);
											}
											jQuery("#modeTravel").change(function() {
												var lat = jQuery("#lat").val();
												var lng = jQuery("#lng").val();
												MiradorMashup.calculateRoute(lat,lng);
											});
										}
									},
				title:"<div class=\"x-window-header\"><table width=\"100%\" border=\"0\"><tr><td valign=\"top\" height=\"14\" width=\"20\"><img src=\"img/icon-barra_busquedas.png\"></td><td valign=\"middle\"><font class=\"roadTextTitle\" align=\"left\">C&aacute;lculo de rutas </font></td></tr></table></div>",
				x : posx,
				y : posy,				
				resizable	: false,
				constrainHeader : true,
				shadow:false
		}
	);
		
	winRoute.show();
	jQuery("#route_notifications").html('here');
	
}

