// JavaScript Document

function LoadProvincia() {
        document.frmSearch.id_provincia.value=document.frmBusc.Provincia.value;
        document.frmSearch.id_sector.value=document.frmBusc.Sector.value;
        document.frmSearch.id_poblacion.value="";
        document.frmSearch.NumPage.value="1";
		document.frmSearch.searchStr.value="";
        document.frmSearch.submit();
}

function LoadSector() {
        document.frmSearch.id_provincia.value="";
        document.frmSearch.id_sector.value=document.frmBusc.Sector.value;
        document.frmSearch.id_poblacion.value="";
        document.frmSearch.NumPage.value="1";
		document.frmSearch.searchStr.value="";
        document.frmSearch.submit();
}      
function LoadPoblacion() {
        document.frmSearch.id_provincia.value=document.frmBusc.Provincia.value;
        document.frmSearch.id_sector.value=document.frmBusc.Sector.value;
        document.frmSearch.id_poblacion.value=document.frmBusc.Poblacion.value;
        document.frmSearch.NumPage.value="1";
		document.frmSearch.searchStr.value="";
        document.frmSearch.submit();
}

// Cargar -- No Cargar mapas

function cargaMapas() {
        document.frmSearch.id_provincia.value=document.frmBusc.Provincia.value;
        document.frmSearch.id_sector.value=document.frmBusc.Sector.value;
        document.frmSearch.id_poblacion.value=document.frmBusc.Poblacion.value;
        document.frmSearch.NumPage.value="1";
		document.frmSearch.tipo_busqueda.value="1";
        document.frmSearch.submit();
}

function nocargaMapas() {
        document.frmSearch.id_provincia.value=document.frmBusc.Provincia.value;
        document.frmSearch.id_sector.value=document.frmBusc.Sector.value;
        document.frmSearch.id_poblacion.value=document.frmBusc.Poblacion.value;
        document.frmSearch.NumPage.value="1";
		document.frmSearch.tipo_busqueda.value="0";
        document.frmSearch.submit();
}

function creaXML()
{
	var xmlhttp=false;
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
	{
		try
		{
			xmlhttp = new XMLHttpRequest();
		}
		catch (e) 
		{
			xmlhttp=false;
		}
	}
	if (!xmlhttp && window.createRequest) 
	{
		try 
		{
			xmlhttp = window.createRequest();
		} 
		catch (e) 
		{
			xmlhttp=false;
		}
	}
	return xmlhttp;
}

function LoadPoblacionEdit(id_empresa,id_user)
{
	var prov=document.frmEdit.Provincia.value;
	var pob=document.frmEdit.Poblacion.value;
	
	var url="/admin/admin_emp-ficha.php?id_empresa="+id_empresa+"&id_provincia="+prov+"&id_poblacion="+pob;
	
	window.location = url;
	
}

function LoadPoblacionEditProd(id_empresa,id_user)
{
	var prov=document.frmEdit.Provincia.value;
	var pob=document.frmEdit.Poblacion.value;
	
	var url="/menu-edit.php?id_empresa="+id_empresa+"&id_provincia="+prov+"&id_poblacion="+pob;
	
	window.location = url;
	
}


// Google Maps Functions

function load(idsector, poblacion, provincia, txtsearch, numpage) {
  if (GBrowserIsCompatible()) {
	var map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(40.420088, -3.688810), 6);

	var bounds = new GLatLngBounds();

	GDownloadUrl("/gen-createMapXML.php?idsector="+idsector+"&idpoblacion="+poblacion+"&idprovincia="+provincia+"&searchstr="+txtsearch+"&NumPage="+numpage, function(data) {
	  var xml = GXml.parse(data);
	  var markers = xml.documentElement.getElementsByTagName("marker");
	  
	  for (var i = 0; i < markers.length; i++) {
		var name = markers[i].getAttribute("name");
		var address = markers[i].getAttribute("address");
		var type = markers[i].getAttribute("type");
		var desc =  markers[i].getAttribute("line2");
		var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
								 parseFloat(markers[i].getAttribute("lng")));
		var marker = createMarker(point, name, address, type, desc);
		map.addOverlay(marker);
		bounds.extend(point);
	  }
	  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	});
  }
}

function load_empresa(idempresa) {
  if (GBrowserIsCompatible()) {
	var map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(40.520088, -3.688810), 15);

	var bounds = new GLatLngBounds();

	GDownloadUrl("/gen-createMapXMLEmpresa.php?idempresa="+idempresa, function(data) {
	  var xml = GXml.parse(data);
	  var markers = xml.documentElement.getElementsByTagName("marker");
	  
	  for (var i = 0; i < markers.length; i++) 
	  {
		var name = markers[i].getAttribute("name");
		var address = markers[i].getAttribute("address");
		var type = markers[i].getAttribute("type");
		var desc =  markers[i].getAttribute("line2");

		var point = new GLatLng(parseFloat(markers[i].getAttribute("lat") ),
								 parseFloat(markers[i].getAttribute("lng") ));
		var marker = createMarker(point, name, address, type, desc);
		map.addOverlay(marker);
		bounds.extend(point);
	  }
	  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)-2);
	});
  }
}

function load_empresa_admin(idempresa) {
  if (GBrowserIsCompatible()) {
	var map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(40.520088, -3.688810), 15);

	var bounds = new GLatLngBounds();

	GDownloadUrl("/admin/gen-createMapXMLEmpresa_admin.php?idempresa="+idempresa, function(data) {
	  var xml = GXml.parse(data);
	  var markers = xml.documentElement.getElementsByTagName("marker");
	  
	  for (var i = 0; i < markers.length; i++) 
	  {
		var name = markers[i].getAttribute("name");
		var address = markers[i].getAttribute("address");
		var type = markers[i].getAttribute("type");
		var desc =  markers[i].getAttribute("line2");

		var point = new GLatLng(parseFloat(markers[i].getAttribute("lat") ),
								 parseFloat(markers[i].getAttribute("lng") ));
		var marker = createMarker(point, name, address, type, desc);
		map.addOverlay(marker);
		bounds.extend(point);
	  }
	  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)-2);
	});
  }
}

function createMarker(point, name, address, type, desc) {
  var marker = new GMarker(point);
  var html = "<b>" + name + "</b><br/>" + address + "<br/>";
  GEvent.addListener(marker, 'click', function() {
	marker.openInfoWindowHtml(html);
  });
  return marker;
}

// funciones varias 

function validar()
{
	ingreso = new String();
	ingreso2 = new String();

	ingreso = document.frmEdit.empresa.value;
	if (ingreso.length == 0)
	{ 
		alert("The company name is needed");
		return false;
	}

	ingreso = document.frmEdit.login.value;
	if (ingreso.length == 0)
	{ 
		alert("The field login is needed");
		return false;
	}
	ingreso = document.frmEdit.password.value;
	if (ingreso.length == 0)
	{ 
		alert("The field password is needed");
		return false;
	}

        if (document.frmEdit.password.value!=document.frmEdit.repassword.value) {
            alert("The field password must match with its validation");
            return false;
        }

	ingreso = document.frmEdit.direccion.value;
	if (ingreso.length == 0)
	{ 
		alert("The company direction is needed");
		return false;
	}
	
	zipcode=document.frmEdit.cp.value;
	if (zipcode.length<5 || zipcode.length>10) 
	{ 
		alert("You must Introduce a valid zip code"); 
		document.frmEdit.cp.focus(); 
		return false; 
	} 
	else 
	{ 
		var c_cpl=true; 
	} 


	if ( isNaN(document.frmEdit.telefono.value))
	{  
		alert("The phone number must be a numeric value, without spaces");
		document.frmEdit.telefono.focus();   
		return false;  
	} 

	if (document.frmEdit.telefono.value.length<9 || document.frmEdit.telefono.value.length>13) 
	{ 
		alert("The field phone number must be introduced."); 
		document.frmEdit.telefono.focus(); 
		return false; 
	} 
	else 
	{ 
		var c_telefono=true; 
	} 

	//ingreso = document.frmEdit.mail.value;
	//if (!ingreso.match("@"))
	//{
	//	alert("You must introduce a valid email address.");
	//	return false;
	//}

	if (document.frmEdit.Provincia.value == -1)
	{ 
		alert("You must select a province/state");
		return false;
	}

	if (document.frmEdit.Poblacion.value == -1)
	{ 
		alert("You must select a City");
		return false;
	}
	
	var theone=-1;
	for (i=0;i<document.frmEdit.id_sector.length;i++)
	{
		if (document.frmEdit.id_sector[i].checked==true)
		{
			theone=i;
			break; //exist for loop, as target acquired.
		}
	}
	
	if(theone == -1) 
	{
		alert("You must select a category");
		return false;
	}
        return true;
}

function validar_factura()
{
	ingreso = new String();
	ingreso2 = new String();

	ingreso = document.frmEdit.nombre.value;
	if (ingreso.length == 0)
	{ 
		alert("You must introduce a name");
		return false;
	}
	ingreso = document.frmEdit.direccion.value;
	if (ingreso.length == 0)
	{ 
		alert("You must introduce a direction");
		return false;
	}

	if (document.frmEdit.cp.value.length<5 || document.frmEdit.cp.value.length>10) 
	{ 
		alert("You must introduce a Zip Code"); 
		document.frmEdit.cp.focus(); 
		return false; 
	} 
	else 
	{ 
		var c_cpl=true; 
	} 
	ingreso = document.frmEdit.poblacion.value;
	if (ingreso.length == 0)
	{ 
		alert("You must introduce a city");
		return false;
	}
	ingreso = document.frmEdit.provincia.value;
	if (ingreso.length == 0)
	{ 
		alert("You must introduce a province/State");
		return false;
	}
	ingreso = document.frmEdit.cif_nif.value;
	if (ingreso.length != 9)
	{ 
		alert("You must introduce a CIF/NIF. (Ej.A12345678 o 12345678A)");
		return false;
	}
	ingreso = document.frmEdit.email.value;
	if (!ingreso.match("@"))
	{ 
		alert("You must introduce a valid email address.");
		return false;
	}
	if ( isNaN(document.frmEdit.telefono.value))
	{  
		alert("The phone number must be numeric and without spaces");
		document.frmEdit.telefono.focus();   
		return false;  
	} 

	if (document.frmEdit.telefono.value.length<9 || document.frmEdit.telefono.value.length>13) 
	{ 
		alert("You must introduce the phone number."); 
		document.frmEdit.telefono.focus(); 
		return false; 
	} 
	else 
	{ 
		var c_telefono=true; 
	} 
	
}

function clearField(fieldId)
{
	var field = document.getElementById(fieldId);
	field.value = "";
}
function setField(fieldId, originalValue)
{
	var field = document.getElementById(fieldId);
	if(field.value == "")
	{
		field.value = originalValue;
	}
}
						
function toggle_ap(elemento) 
{
  if(elemento.value == "false")
  {
  	document.getElementById("ap").style.display = "none";
  } 
  else 
  {
  	document.getElementById("ap").style.display = "block";
  }
}

var bustcachevar=1; //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects="";
var rootdomain="http://"+window.location.hostname;
var bustcacheparameter="";

function ajaxpage(url, containerid){
	var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest();
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	} else return false

	page_request.onreadystatechange=function(){loadpage(page_request, containerid)}

	if (bustcachevar) //if bust caching of external page
	bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	page_request.open('GET', url+bustcacheparameter, true);
	page_request.send(null);
}

function loadpage(page_request, containerid){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
	document.getElementById(containerid).innerHTML=page_request.responseText;
}

function loadobjs(){
	if (!document.getElementById)
		return
	for (i=0; i<arguments.length; i++){
		var file=arguments[i]
		var fileref=""
		if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
		if (file.indexOf(".js")!=-1){ //If object is a js file
		fileref=document.createElement('script')
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", file);
	} else if (file.indexOf(".css")!=-1){ //If object is a css file
		fileref=document.createElement("link")
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", file);
		}
	}
		if (fileref!=""){
		document.getElementsByTagName("head").item(0).appendChild(fileref)
		loadedobjects+=file+" " //Remember this object as being already added to page
		}
	}
}

// funciones ajax txt
function combopobs(id_poblacion)
{
	if(document.frmEdit.Provincia.value != -1)
	{
		ajaxpage("/gen-combogetpob.php?id_poblacion="+id_poblacion+"&id_provincia="+document.frmEdit.Provincia.value,'cpobs');
		document.getElementById("cpobs_li").style.visibility = "visible";
		
	}
	else
	{
		document.getElementById("cpobs_li").style.visibility = "hidden";
	}
}

function loadcombolistados(id_sector, id_provincia, id_poblacion)
{
		ajaxpage("/gen-combolistados.php?id_sector="+id_sector+"&id_poblacion="+id_poblacion+"&id_provincia="+id_provincia,'combolistados');
}

function loadcombolistadossphinx(id_sector, id_provincia, id_poblacion, query)
{
		ajaxpage("/gen-combolistadossphinx.php?id_sector="+id_sector+"&id_poblacion="+id_poblacion+"&id_provincia="+id_provincia+"&query="+query,'combolistados');
}


function validar_opiniones()
{
	ingreso = new String();

	ingreso = document.frmOpinar.nombre.value;
	if (ingreso.length == 0)
	{
		alert("The field name must be informed");
		return false;
	}
	ingreso = document.frmOpinar.titulo.value;
	if (ingreso.length == 0)
	{ 
		alert("The title must be informed");
		return false;
	}
	ingreso = document.frmOpinar.opinion.value;
	if (ingreso.length == 0)
	{ 
		alert("The opinion must be validated");
		return false;
	}
        return true;

}

function validar_denuncia ()
{
    ingreso = new String();

	ingreso = document.frmDenunciar.nombre.value;
	if (ingreso.length == 0)
	{
		alert("The field name must be informed");
		return false;
	}
	ingreso = document.frmDenunciar.Email.value;
	if (!ingreso.match("@"))
	{
		alert("The field email must be informed and must be a valid email address.");
		return false;
	}
	ingreso = document.frmDenunciar.motivo.value;
	if (ingreso.length == 0)
	{
		alert("Please, introduce a text");
		return false;
	}
        return true;
}


function validar_contactoficha()
{
	ingreso = new String();

	ingreso = document.contactoficha.Nombre.value;
	if (ingreso.length == 0)
	{
		alert("The field name must be informed");
		return false;
	}
	
	ingreso = document.contactoficha.Apellidos.value;
	if (ingreso.length == 0)
	{ 
		alert("The surname must be informed");
		return false;
	}
	
	ingreso = document.contactoficha.Provincia.value;
	if (ingreso.length == 0)
	{ 
		alert("The field state/province must be informed");
		return false;
	}
	
	ingreso = document.contactoficha.Localidad.value;
	if (ingreso.length == 0)
	{ 
		alert("You must select a city");
		return false;
	}
	
	ingreso = document.contactoficha.Email.value;
	if (!ingreso.match("@"))
	{ 
		alert("The field email must be informed and must be a valid email address.");
		return false;
	}

	ingreso = document.contactoficha.Mensaje.value;
	if (ingreso.length == 0)
	{ 
		alert("Please, introduce a text");
		return false;
	}
        return true;
}
function photoOverHandler(e)
{
	var smallId = Event.element(e).id;
	var largeId = smallId + '_large';

	movePhoto(largeId, Event.pointerX(e), Event.pointerY(e));

	$(smallId + '_large').show();

	Event.observe(Event.element(e).id, "mousemove", photoMoveHandler);
}

function photoOutHandler(e)
{
	var smallId = Event.element(e).id;

	$(smallId + '_large').hide();

	Event.stopObserving(Event.element(e).id, "mousemove", photoMoveHandler);
}

function photoMoveHandler(e)
{
	var smallId = Event.element(e).id;
	var largeId = smallId + '_large';

	movePhoto(largeId, Event.pointerX(e), Event.pointerY(e));
}

function movePhoto(id, x, y)
{
	var hPhoto = $(id).getHeight();
	var xPhoto = x + 20 - max(((getClientWidth()-1000) / 2), 0);
	var yPhoto = y - hPhoto;

	var yOffset = getScrollY();

	if(yPhoto < yOffset) yPhoto = yOffset;

	$(id).setStyle({top: String(yPhoto + 'px'), left: String(xPhoto + 'px')});
}

function max(x, y)
{
	if(x < y) result = y;
	else result = x;
	
	return result;
}

function getScrollY()
{
	var yOffset = 0;

	if(typeof( window.pageYOffset ) == 'number')
	{
    	//Netscape compliant
		yOffset = window.pageYOffset;
	}
	else if(document.body && document.body.scrollTop)
	{
		//DOM compliant
		yOffset = document.body.scrollTop;
	}
	else if(document.documentElement && document.documentElement.scrollTop)
	{
		//IE6 standards compliant mode
		yOffset = document.documentElement.scrollTop;
	}

	return yOffset;
}

function getClientHeight()
{
	var h = 0;

	if(typeof(window.innerHeight) == 'number')
	{
		//Non-IE
		h = window.innerHeight;
	}
	else if(document.documentElement && document.documentElement.clientHeight)
	{
		//IE 6+ in 'standards compliant mode'
		h = document.documentElement.clientHeight;
	}
	else if(document.body && document.body.clientHeight)
	{
		//IE 4 compatible
		h = document.body.clientHeight;
	}

	return h;
}

function getClientWidth()
{
	var h = 0;

	if(typeof(window.innerWidth) == 'number')
	{
		//Non-IE
		h = window.innerWidth;
	}
	else if(document.documentElement && document.documentElement.clientWidth)
	{
		//IE 6+ in 'standards compliant mode'
		h = document.documentElement.clientWidth;
	}
	else if(document.body && document.body.clientWidth)
	{
		//IE 4 compatible
		h = document.body.clientWidth;
	}

	return h;
}
