var xmlHttp;
var xmlDoc;


function GetXmlHttpObject()
 {
 var objXMLHttp=null
 if (window.XMLHttpRequest)
  {
  objXMLHttp=new XMLHttpRequest()
  }
 else if (window.ActiveXObject)
  {
  objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
  }
 return objXMLHttp
 }


function showcomarques(str) {

if (str=="AD") {

     document.getElementById('consellest').style.display = "none";
     document.getElementById('paisbloc').style.display = "block";

     document.forms[0].estranger.disabled = true;
     document.forms[0].estranger.style.display = "none";
     document.forms[0].comarca.disabled = true;
     document.forms[0].comarca.style.display = "none";
     document.getElementById('label_comarca').style.display = "none";
     document.getElementById('label_municipi').style.display = "block";
     document.getElementById('label_municipi').innerHTML= "Parròquia";
     document.forms[0].comarca.options[0].name = "Andorra";
     document.forms[0].comarca.options[0].value = "andorra";
     document.forms[0].municipi.disabled = false;
     document.forms[0].municipi.style.display = "block";
     showmunicipis('andorra');



}

else if (str=="AL") {

     document.getElementById('consellest').style.display = "none";
     document.getElementById('paisbloc').style.display = "block";

     document.forms[0].estranger.disabled = true;
     document.forms[0].estranger.style.display = "none";
     document.forms[0].comarca.disabled = true;
     document.forms[0].comarca.style.display = "none";
     document.forms[0].municipi.disabled = true;
     document.forms[0].municipi.style.display = "none";
     document.getElementById('label_comarca').style.display = "none";
     document.getElementById('label_municipi').style.display = "none";
     document.forms[0].comarca.options[0].name = "l'Alguer";
     document.forms[0].comarca.options[0].value = "lalguer";
     document.forms[0].municipi.options[0].name = "l'Alguer";
     document.forms[0].municipi.options[0].value = "lalguer";

     var munivalue = "lalguer";

     MainMap.getXmlSEM(munivalue, 'municipi');


}


else if (str=="CR") {

     document.getElementById('consellest').style.display = "none";
     document.getElementById('paisbloc').style.display = "block";

     document.forms[0].estranger.disabled = true;
     document.forms[0].estranger.style.display = "none";
     document.forms[0].comarca.disabled = true;
     document.forms[0].comarca.style.display = "none";
     document.getElementById('label_comarca').style.display = "none";
     document.getElementById('label_municipi').style.display = "block";
     document.getElementById('label_municipi').innerHTML= "Nucli";
     document.forms[0].comarca.options[0].name = "el Carxe";
     document.forms[0].comarca.options[0].value = "el_carxe";
     document.forms[0].municipi.disabled = false;
     document.forms[0].municipi.style.display = "block";

     var comarcavalue = "el_carxe";
     showmunicipis('el_carxe');
     MainMap.getXmlSEM(comarcavalue, 'comarca');

}

else if ((str=="CT") || (str=="CN") || (str=="PV") || (str=="FJ") || (str=="BA")) {

	 document.getElementById('consellest').style.display = "none";
     document.getElementById('paisbloc').style.display = "block";

     document.forms[0].estranger.disabled = true;
     document.forms[0].estranger.style.display = "none";
     document.getElementById('label_comarca').style.display = "block";

     if (str=="BA") {
     	document.getElementById('label_comarca').innerHTML= "Illa";
     }

     else {
     	document.getElementById('label_comarca').innerHTML= "Comarca";
     }

     document.getElementById('label_municipi').innerHTML= "Municipi";
     document.forms[0].comarca.disabled = false;
     document.forms[0].comarca.style.display = "block";
     document.getElementById('label_municipi').style.display = "block";
     document.forms[0].municipi.disabled = false;
     document.forms[0].municipi.style.display = "block";


 xmlHttp=GetXmlHttpObject()
 if (xmlHttp==null)
  {
  alert ("El navegador no funciona amb l'HTTP Request")
  return
  }
 var url="/getcomarca.php"
 url=url+"?territori="+str
 url=url+"&sid="+Math.random()
 xmlHttp.onreadystatechange=processaXML
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)

}



else if (str=="ET") {

	document.getElementById('consellest').style.display = "block";
	document.getElementById('paisbloc').style.display = "none";

    document.forms[0].estranger.disabled = false;
    document.forms[0].estranger.style.display = "block";
	document.forms[0].comarca.disabled = true;
	document.forms[0].comarca.style.display = "none";
	document.forms[0].municipi.disabled = true;
	document.forms[0].municipi.style.display = "none";

}



else {

     document.getElementById('consellest').style.display = "none";
     document.getElementById('paisbloc').style.display = "block";


     document.forms[0].comarca.name = "";
     document.forms[0].comarca.value = "";
     document.forms[0].estranger.disabled = true;
     document.forms[0].estranger.style.display = "none";
     document.getElementById('label_comarca').style.display = "block";
     document.forms[0].comarca.disabled = false;
     document.forms[0].comarca.style.display = "block";
     document.getElementById('label_municipi').style.display = "block";
     document.forms[0].municipi.disabled = false;
     document.forms[0].municipi.style.display = "block";


 xmlHttp=GetXmlHttpObject()
 if (xmlHttp==null)
  {
  alert ("El navegador no funciona amb l'HTTP Request")
  return
  }
 var url="/getcomarca.php"
 url=url+"?territori="+str
 url=url+"&sid="+Math.random()
 xmlHttp.onreadystatechange=processaXML
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)
 }

}


function showcomarques2(str) {


 xmlHttp=GetXmlHttpObject()
 if (xmlHttp==null)
  {
  alert ("El navegador no funciona amb l'HTTP Request")
  return
  }
 var url="/getcomarca.php"
 url=url+"?territori="+str
 url=url+"&sid="+Math.random()
 xmlHttp.onreadystatechange=processaXML
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)


}


function activamuni() {


	if (document.forms[0].noumuni.checked) {

		document.getElementById('consellest').style.display = "block";
		document.getElementById('selectbloc').style.display = "none";

        document.forms[0].estranger.disabled = false;
        document.forms[0].estranger.style.display = "block";
		document.forms[0].territori.disabled = true;
		document.forms[0].territori.style.display = "none";
		document.forms[0].comarca.disabled = true;
		document.forms[0].comarca.style.display = "none";
		document.forms[0].municipi.disabled = true;
		document.forms[0].municipi.style.display = "none";


	}

	else {

		document.getElementById('consellest').style.display = "none";
		document.getElementById('selectbloc').style.display = "none";

    	document.forms[0].estranger.disabled = true;
    	document.forms[0].estranger.style.display = "none";
    	document.forms[0].territori.disabled = false;
    	document.forms[0].territori.style.display = "block";
    	document.forms[0].comarca.disabled = false;
    	document.forms[0].comarca.style.display = "block";
    	document.forms[0].municipi.disabled = false;
    	document.forms[0].municipi.style.display = "block";


	}

}

function getDoc(XMLHttpRequestObject) {
	var doc;
	if (document.implementation && document.implementation.createDocument){
		doc = XMLHttpRequestObject.responseXML;
		//In case to be the internet explorer
	}
	else if (window.ActiveXObject){
		//Create a xml tag in run time
		var testandoAppend = document.createElement('xml');
		//Put the requester.responseText in the innerHTML of the xml tag
		testandoAppend.setAttribute('innerHTML',XMLHttpRequestObject.responseText);
		//Set the xml tag's id to _formjAjaxRetornoXML
		testandoAppend.setAttribute('id','_formjAjaxRetornoXML');
		//Add the created tag to the page context
		document.body.appendChild(testandoAppend);
		//Just for check put the xmlhttp.responseXML in the innerHTML of the tag
		document.getElementById('_formjAjaxRetornoXML').innerHTML = XMLHttpRequestObject.responseText;
		//Now we can get the xml tag and put it on a var
		doc = document.getElementById('_formjAjaxRetornoXML');
		//So we have a valid xml we can remove the xml tag
		document.body.removeChild(document.getElementById('_formjAjaxRetornoXML'));
	}
	return doc;
}

function processaXML(){

	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {


		xmlDoc=getDoc(xmlHttp);

		var terri = xmlDoc.getElementsByTagName('territori').length;

		document.forms[0].comarca.options.length = 0;
		document.forms[0].municipi.options.length = 0;



		var box3 = document.forms[0].municipi;
		box3.options[0]= new Option('Seleccioneu una comarca/illa...', '0');


		var ter = new Array();

		for(var i=0;i<terri;i++){

			ter.push(xmlDoc.getElementsByTagName('territori')[i].getAttribute('nom'));

			var terricom = xmlDoc.getElementsByTagName('territori')[i].getElementsByTagName('comarca').length;



			var box2 = document.forms[0].comarca;
			box2.options[0] = new Option('Seleccioneu-ne una...', '0');



			for (var y=1; y<terricom+1;y++) {

				var coma = xmlDoc.getElementsByTagName('territori')[i].getElementsByTagName('comarca')[y-1].getAttribute('nom');
				var valor = xmlDoc.getElementsByTagName('territori')[i].getElementsByTagName('comarca')[y-1].getAttribute('sem');
				var sem = xmlDoc.getElementsByTagName('territori')[i].getElementsByTagName('comarca')[y-1].getAttribute('sem');
				box2.options[y] = new Option(coma, valor);


			}

		}

	}

}


function showmunicipis(str)
 {
 xmlHttp=GetXmlHttpObject()
 if (xmlHttp==null)
  {
  alert ("El navegador no funciona amb l'HTTP Request")
  return
  }

 var url="/getmunicipi.php"
 url=url+"?comarca="+str
 url=url+"&sid="+Math.random()
 xmlHttp.onreadystatechange=processaXML2
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)
 }

function processaXML2(){


if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {


	xmlDoc=getDoc(xmlHttp);

	var comarca = xmlDoc.getElementsByTagName('comarca').length;


	document.forms[0].municipi.options.length = 0;

	var comar = new Array();

	var box2 = document.forms[0].municipi;
	box2.options[0] = new Option('Seleccioneu-ne un...', '0');


	for(var i=0;i<comarca;i++){

		comar.push(xmlDoc.getElementsByTagName('comarca')[i].getAttribute('nom'));

		var communi = xmlDoc.getElementsByTagName('comarca')[i].getElementsByTagName('municipi').length;


			for (var y=1; y<communi+1;y++) {

				var muni = xmlDoc.getElementsByTagName('comarca')[i].getElementsByTagName('municipi')[y-1].getAttribute('nom');
				var valor = xmlDoc.getElementsByTagName('comarca')[i].getElementsByTagName('municipi')[y-1].getAttribute('sem');
				var sem = xmlDoc.getElementsByTagName('comarca')[i].getElementsByTagName('municipi')[y-1].getAttribute('sem');
				box2.options[y] = new Option(muni, valor);


			}


		}


	}

}



var W3CDOM = (document.getElementsByTagName && document.createElement);

window.onload = function () {

	document.forms[0].onsubmit = function () {
		return validate()
	}
}

// Validate form
function validate() {
	validForm = true;
	firstError = null;
	errorstring = '';


	var dades = document.forms[0];
	var x = document.forms[0].elements;
	var box = document.forms[0].territori;
	var box2 = document.forms[0].comarca;
	var box3 = document.forms[0].municipi;

	var IDbox = document.forms[0].IDtipus;

	var number = box.options[box.selectedIndex].value;
	var number2 = box2.options[box2.selectedIndex].value;
	var number3 = box3.options[box3.selectedIndex].value;

	var IDtipus = IDbox.options[IDbox.selectedIndex].value;

	var blanc = /^[\s+]*$/;

	if (!x['nom'].value || blanc.test(x['nom'].value)) {
		writeError(x['nom'],'Cal que ompliu aquest camp');
	}
	if (!x['cognoms'].value || blanc.test(x['cognoms'].value)) {
		writeError(x['cognoms'],'Cal que ompliu aquest camp');
	}
	if (!x['ID'].value || blanc.test(x['ID'].value)) {
		writeError(x['ID'],'Cal que ompliu aquest camp');
	}
	if (!x['email'].value || blanc.test(x['email'].value)) {
		writeError(x['email'],'Cal que ompliu aquest camp');
	}
	if (number=="ET" && !x['estranger'].value) {
		writeError(x['estranger'],'Cal que ompliu aquest camp');
	}

	if (number == "0" ) {

		validForm = false;
	//	writeError(x['territori'],'Cal que seleccioneu una opció');

	}


	if (number2 == "0" && number!= "ET" ) {

		validForm = false;
	//	writeError(x['comarca'],'Cal que seleccioneu una opció');

	}

	if (number3 == "0" && number!= "ET" ) {

		validForm = false;
	//		writeError(x['municipi'],'Cal que seleccioneu una opció');

	}


	if (IDtipus=="NIF" && nif(x['ID'].value) == false ) {
		writeError(x['ID'],'El NIF no és vàlid');
	}

	if (IDtipus=="CNC" && cnc(x['ID'].value) == false ) {
		writeError(x['ID'],'El CNC no és vàlid');
	}

	if (IDtipus=="CdI" && cdi(x['ID'].value) == false ) {
		writeError(x['ID'],'El CdI no és vàlid');
	}

	if (emailCheck(x['email'].value) == false) {
		writeError(x['email'],'L`adreça electrònica no és vàlida');
	}
	if (!W3CDOM) {
		alert(errorstring);
	}
	if (firstError) {
		firstError.focus();
	}
	if (validForm) {
		dades.submit();
	}
	return false;
}

function writeError(obj,message) {
	validForm = false;
	if (obj.hasError) return;
	if (W3CDOM) {
		obj.className += ' error_form';
		obj.onchange = removeError;
		var sp = document.createElement('span');
		sp.className = 'error_form';
		sp.appendChild(document.createTextNode(message));
		obj.parentNode.appendChild(sp);
		obj.hasError = sp;
	}
	else {
		errorstring += obj.name + ': ' + message + '\n';
		obj.hasError = true;
	}
	if (!firstError)
		firstError = obj;
}

function removeError()
{
	this.className = this.className.substring(0,this.className.lastIndexOf(' '));
	this.parentNode.removeChild(this.hasError);
	this.hasError = null;
	this.onchange = null;
}


//Check email
function emailCheck (emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|cat)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address.
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
return false;
   }
}

// See if "user" is valid

if (user.match(userPat)==null) {

// user is not valid

return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.

var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 &&
domArr[domArr.length-1].search(knownDomsPat)==-1) {
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
return false;
}

// If we've gotten this far, everything's valid!
return true;
}


function nif(nifvalue)
{

dni=nifvalue.substring(0,nifvalue.length-1)
let=nifvalue.charAt(nifvalue.length-1)
if (!isNaN(let))
 {
  return false
 }
else
 {
  cadena="TRWAGMYFPDXBNJZSQVHLCKET"
  posicion = dni % 23
  letra = cadena.substring(posicion,posicion+1)
  if (letra!=let.toUpperCase())
   {
    return false
   }
 }
}

function cnc(cncvalue)
{

var cncpat = /^\d{6}$/;
var match_cnc=cncvalue.match(cncpat);

if (match_cnc==null)
 {
  return false;
 }
else {return true;}
}

function cdi(cdivalue)
{

var cdipat = /^\w{2}\d{7}$/;
var match_cdi=cdivalue.match(cdipat);

if (match_cdi==null)
 {
  return false;
 }
else {return true;}
}


// calls the geonames JSON webservice with the search term
function geosearch() {
  request = 'http://ws.geonames.org/searchJSON?q=' +  encodeURIComponent(document.forms[0].estranger.value)  + '&maxRows=10&lang=ca&callback=getLocation';

  // Create a new script object
  // (implementation of this class is in /export/jsr_class.js)
  aObj = new JSONscriptRequest(request);
  // Build the script tag
  aObj.buildScriptTag();
  // Execute (add) the script tag
  aObj.addScriptTag();
}

// this function will be called by our JSON callback
// the parameter jData will contain an array with geonames objects
function getLocation(jData) {
  if (jData == null) {
    // There was a problem parsing search results
    return;
  }

document.getElementById('resultDiv').style.display = "block";
  var html = '';
  var geonames = jData.geonames;
  for (i=0;i< geonames.length;i++) {
     var name = geonames[i];
     // we create a simple html list with the geonames objects
     // the link will call the center() javascript method with lat/lng as parameter
     html = html + '<a href="javascript:addname('+name.lat +',' + name.lng + ',\''+ name.name + '\',\''+name.countryName +'\');clean_results_geo();">' + name.name +' ('+ name.countryName +')' + '</a><br />';
  }
  document.getElementById('resultDiv').innerHTML = html;
}

function addname (lat, lng, name, country) {


    document.forms[0].lat_estranger.value = lat;
    document.forms[0].lng_estranger.value = lng;
    document.forms[0].nom_estranger.value = name;
    document.forms[0].sta_estranger.value = country;

}

function clean_results_geo() {

	document.getElementById('resultDiv').style.display = "none";
}

//Show documents ID
function show_documents() {

	document.getElementById('tipusDocument').style.display = "block";

}

function hide_documents() {

	document.getElementById('tipusDocument').style.display = "none";

}


function go_there(element, type) {


	var sem_nom = element.value;

	//MainMap.getXmlID2(code, type);
	MainMap.getXmlSEM(sem_nom, type);

}



