var globalDebug = 0;
/****************************************************
				Idioma
****************************************************/

function changeIdioma(lang) {
	document.location = changeWindowLanguaje(document.location.href, lang);
}

function changeWindowLanguaje(url, idioma) {
	str = url;
	
	re = /\?idioma=(CA|ES|EN)\&/g; 
	str = str.replace(re,"?");

	re = /(\?i|\&i)dioma=(CA|ES|EN)/g;
	str = str.replace(re, "");

	var aname = "";
	if (str.indexOf('#')>0)
	{
		aname = str.substring(str.indexOf('#'));
		str = str.substring(0,str.indexOf('#'));
	}

	if (str.indexOf('?')>0) 
		str = str + "&idioma=" + idioma;
	else
		str = str + "?idioma=" + idioma;

	str += aname;

	return str;
}

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


function regenerateCaptcha(objName) 
{
	var time= new Date();
	var obj = dojo.byId(objName);
	obj.src = obj.src + "&r="+time.getSeconds();	
}

function validate(obj, type) 
{
	if (type == "E") // email validation
	{
	} else {

		if (obj.value == "") {
			obj.style.borderColor = "red";
			return true;
		} else {
			obj.style.borderColor = "";
		}
	}
	return false;
}




/****************************************************
				Send by Mail
****************************************************/
function showSendByMail(id) {
	var obj = dojo.byId("sendByMailPlacer_"+id);
	obj.style.display = "block";
}


function sendByMail(id) {
	var i = 1000;

	lastSentByMail = id;
	var obj = dojo.byId("sendByMailPlacer_"+id);
	var objW4C = dojo.byId("sendByMailWaiter_"+id);
	var nm = dojo.byId("sndByName_"+id);
	var em = dojo.byId("sndByEmail_"+id);
	var tnm = dojo.byId("sndToName_"+id);
	var tem = dojo.byId("sndToEmail_"+id);
	var com = dojo.byId("sndComment_"+id);
	var kp = dojo.byId("sndCaptcha_"+id);
	var rm = dojo.byId("sndchkRemember_"+id);

	var error = false;

	error = error || validate(nm, "T");
	error = error || validate(tnm, "T");
	error = error || validate(kp, "T");

	if (!emailCheck(em.value)) {
		em.style.borderColor = "red";
		error = true;
	} else {
		em.style.borderColor = "";
	}	

	if (!emailCheck(tem.value)) {
		tem.style.borderColor = "red";
		error = true;
	} else {
		tem.style.borderColor = "";
	}	

	if (!error) {
		obj.style.display = "none";
		objW4C.style.display = "block";


		dojo.io.bind({
		   url: 'sendByMail.php',
		   handler: setByMailCallback,
		   method: 'GET',
		   content: {
		   		ida: id,
		   		rnombre: nm.value,
		   		remail: em.value,
		   		dnombre: tnm.value,
		   		demail: tem.value,
				comment: com.value,
		   		rem: (rm.checked?1:0),
		   		captcha: kp.value
		   }
		});					
	}


}


function setByMailCallback(type, encoded_data, evt) 
{
	var id = lastSentByMail;
	var obj = dojo.byId("sendByMailPlacer_"+id);
	var objW4C = dojo.byId("sendByMailWaiter_"+id);
	var res = dojo.byId("sendByMailResult_"+id);
	
	var nm = dojo.byId("sndByName_"+id);
	var em = dojo.byId("sndByEmail_"+id);
	var tnm = dojo.byId("sndToName_"+id);
	var tem = dojo.byId("sndToEmail_"+id);
	var com = dojo.byId("sndComment_"+id);
	var kp = dojo.byId("sndCaptcha_"+id);
	var rm = dojo.byId("sndchkRemember_"+id);

	
	if (type == 'error')
		res.innerHTML = ' setPubBcstCallback::Error when retrieving data from the server!' +  encoded_data.message;		  
	else {		 
		eval("var decoded_data = "+encoded_data);
		
		res.innerHTML = decoded_data["desc"];

		if (decoded_data["stat"] == "ok") {	
			tnm.value = "";
			tem.value = "";
			com.value = "";
			kp.value = "";
			regenerateCaptcha('bmImgCaptcha'+id);
			
			if (decoded_data["remm"] != "1") {
				nm.value = "";
				em.value = "";
			}
		}
	}
	res.style.display = "inline";
	obj.style.display = "inline";
	objW4C.style.display = "none";
}


/****************************************************
				Comments
****************************************************/
function sendComment() 
{
	var nombre = dojo.byId("commName");	
	var mail = dojo.byId("commEmail");	
	var cntry = dojo.byId("commCntr");	
	var comm = dojo.byId("commComentario");	
	var ida = dojo.byId("commArticleId");
	var www = dojo.byId("commWww");	
	var cptch = dojo.byId("commCaptcha");	
	var remb = dojo.byId("commRemember");	
	var res = dojo.byId("commentresult");

	res.style.display = "none";


	var error = false;
	
	error = error || validate(comm, "T");
	error = error || validate(nombre, "T");
	error = error || validate(mail, "T");
	error = error || validate(cptch, "T");		
	
	if (!error) {
		dojo.byId('frmCommentLayer').style.display = "none";
		dojo.byId('waitForComment').style.display = "block";

		dojo.io.bind({
		   url: 'commentPropose.php',
		   handler: setCommentCallback,
		   method: 'GET',
		   content: {
		   		_name: nombre.value,
		   		_email: mail.value,
		   		cntry: cntry.value,
		   		text: comm.value,
		   		idarticulo: ida.value,
		   		www: www.value,
		   		rem: (remb.checked?1:0),
		   		captcha: cptch.value
		   }
		});					
	}
	
}

function setCommentCallback(type, encoded_data, evt) 
{
	var w4comm = dojo.byId("waitForComment");
	var f = dojo.byId("frmCommentLayer");
	var res = dojo.byId("commentresult");
	
	var nombre = dojo.byId("commName");	
	var mail = dojo.byId("commEmail");	
	var cntry = dojo.byId("commCntr");	
	var comm = dojo.byId("commComentario");	
	var www = dojo.byId("commWww");	
	var cptch = dojo.byId("commCaptcha");	

	
	if (type == 'error')
		res.innerHTML = ' setPubBcstCallback::Error when retrieving data from the server!' +  encoded_data.message;		  
	else {		 
		eval("var decoded_data = "+encoded_data);
		
		res.innerHTML = decoded_data["desc"];

		if (decoded_data["stat"] == "ok") {	
			comm.value = "";
			cptch.value = "";
			regenerateCaptcha('commImgCaptcha');

			window.location.reload();
			
			if (decoded_data["remm"] != "1") {
				nombre.value = "";
				mail.value = "";
				cntry.selectedIndex = 0;	
				www.value = "";				
			}
		}
	}
	res.style.display = "inline";
	f.style.display = "inline";
	w4comm.style.display = "none";
}


/****************************************************
				Newsletter
****************************************************/
function subscribe(acc) 
{
	var e = dojo.byId("nwsEmail");
	var w4em = dojo.byId("waitForNews");
	var f = dojo.byId("frmNewsletter");
	var i = dojo.byId("nwsIdiomaES");
	var res = dojo.byId("newsresult");

	var error = false;
	
	if (!emailCheck(e.value)) {
		e.style.backgroundColor = "red";		
		error = true;
	} else {
		e.style.backgroundColor = "transparent";
	}	
	if (!error) {
		f.style.display = "none";
		w4em.style.display = "block";
		dojo.io.bind({
		   url: 'newsletter-handle.php',
		   handler: subscribeCallback,
		   method: 'GET',
		   content: {
		   		acc: acc,
		   		_email: e.value,
			    idioma: ((i.checked)?'ES':'EN')
		   }
		});					

	}
}


function subscribeCallback(type, encoded_data, evt) {		
	var w4em = dojo.byId("waitForNews");
	var f = dojo.byId("frmNewsletter");
	var res = dojo.byId("newsresult");
	
	if (type == 'error')
		res.innerHTML = ' setNewsletterCallback::Error when retrieving data from the server!' +  encoded_data.message;		  
	else {		
		eval("var decoded_data = "+encoded_data);
		
		res.innerHTML = decoded_data["descripcion"];				
	}
	res.style.display = "inline";
	f.style.display = "inline";
	w4em.style.display = "none";
}

/****************************************************
				Public Broadcast
****************************************************/
function showProposeALink(id) {
	document.location = "#postALink";
	new Effect.Highlight(dojo.byId('pubbcst'));
	/*
	var obj = dojo.byId("proposeALinkPlacer_"+id);
	obj.style.display = "none";
	
	obj = dojo.byId("proposeALinkPlacer_"+id);
	obj.style.display = "block";*/
}

function sendPbBcst() 
{
	var db=0;
	var w4pb = dojo.byId("waitForPB");
	var f = dojo.byId("pubbcstForm");
	var n = dojo.byId("pbName");
	var e = dojo.byId("pbEmail");
	var c = dojo.byId("pbCntr");
	var t = dojo.byId("pbText");
	var l = dojo.byId("pbLink");
	var s = dojo.byId("pbSecc");
	var w = dojo.byId("pbWww");
	var cptch = dojo.byId("pbCaptcha");
	var res = dojo.byId("pubbcstresult");
	
	if (globalDebug == 1)
	{
		alert(n.value);
	}

	res.style.display = "none";
	
	var error = false;
	
	
	error = error || validate(n, "T");
	error = error || validate(t, "T");
	error = error || validate(cptch, "T");		
	error = error || validate(l, "T");		
	
	if (e.value != "" && !emailCheck(e.value)) {
		e.style.backgroundColor = "red";		
		error = true;
	} else {
		e.style.backgroundColor = "transparent";
	}

	if (!error) {
		f.style.display = "none";
		w4pb.style.display = "block";
		dojo.io.bind({
		   url: 'publicbroadcastPropose.php',
		   handler: setPubBcstCallback,
		   content: {
		   		_name: n.value,
		   		_email: e.value,
		   		cntry: c.value,
		   		text: t.value,
		   		link: l.value,
		   		seccion: s.value,
		   		www: w.value,
				idd: -1,
				captcha: cptch.value,
		   		rem: (dojo.byId("chkRemember").checked?1:0)
		   }
		});					
	}
}

function setPubBcstCallback(type, encoded_data, evt) {		
	var w4pb = dojo.byId("waitForPB");
	var f = dojo.byId("pubbcstForm");
	var res = dojo.byId("pubbcstresult");
	var cptch = dojo.byId("pbCaptcha");
	
	if (type == 'error')
		res.innerHTML = ' setPubBcstCallback::Error when retrieving data from the server!' +  encoded_data.message;		  
	else {		 
		eval("var decoded_data = "+encoded_data);

		res.innerHTML = decoded_data["desc"];
		regenerateCaptcha('pbImgCaptcha');
		cptch.value = "";
	}
	res.style.display = "inline";
	f.style.display = "inline";
	w4pb.style.display = "none";
	
}


function publicbroadcast2Callback(type, encoded_data, evt) {		
	var w4pb = dojo.byId("waitForPB");
	
	if (type == 'error')
		alert(' setPubBcstCallback::Error when retrieving data from the server!' +  encoded_data.message);
	else {		 
		eval("var decoded_data = "+encoded_data);

		var id=decoded_data["id"];
		
		var obj = dojo.byId("proposeALinkPlacer_"+id);
		var objW4C = dojo.byId("proposeALinkWaiter_"+id);
		var sec = dojo.byId("pbSecc_"+id);
		var tex = dojo.byId("pbText_"+id);
		var link = dojo.byId("pbLink_"+id);
		var nm = dojo.byId("pbName_"+id);
		var em = dojo.byId("pbEmail_"+id);
		var cn = dojo.byId("pbCntr_"+id);
		var ww = dojo.byId("pbWww_"+id);
		var kp = dojo.byId("pbCaptcha_"+id);
		var rm = dojo.byId("pbchkRemember_"+id);

		var res = dojo.byId("proposeALinkResult_"+id);
		var cptch = dojo.byId("pbCaptcha");

		res.innerHTML = decoded_data["desc"];

		regenerateCaptcha('pbImgCaptcha'+id);
		kp.value = "";
	}
	res.style.display = "inline";
	w4pb.style.display = "none";
	
}
/*****************************************************************************/
/*****************************************************************************/
/*****************************************************************************/
/*****************************************************************************/

function linkValidator(url) {
	var j = new RegExp();
    j.compile("^[A-Za-z]+://[A-Za-z0-9-]+\.[A-Za-z0-9]+");
    if (!j.test(url)) {
        alert("You must supply a valid URL.");
        return false;
    } 	
    return true;
}

/**** EMAIL Validator ****/


/* 1.1.4: Fixed a bug where upper ASCII characters (i.e. accented letters
international characters) were allowed.

1.1.3: Added the restriction to only accept addresses ending in two
letters (interpreted to be a country code) or one of the known
TLDs (com, net, org, edu, int, mil, gov, arpa), including the
new ones (biz, aero, name, coop, info, pro, museum).  One can
easily update the list (if ICANN adds even more TLDs in the
future) by updating the knownDomsPat variable near the
top of the function.  Also, I added a variable at the top
of the function that determines whether or not TLDs should be
checked at all.  This is good if you are using this function
internally (i.e. intranet site) where hostnames don't have to 
conform to W3C standards and thus internal organization e-mail
addresses don't have to either.
Changed some of the logic so that the function will work properly
with Netscape 6.

1.1.2: Fixed a bug where trailing . in e-mail address was passing
(the bug is actually in the weak regexp engine of the browser; I
simplified the regexps to make it work).

1.1.1: Removed restriction that countries must be preceded by a domain,
so abc@host.uk is now legal.  However, there's still the 
restriction that an address must end in a two or three letter
word.

1.1: Rewrote most of the function to conform more closely to RFC 822.

1.0: Original  */

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. */

			alert("Email address seems incorrect (check @ and .'s)");
			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) {
				alert("Ths username contains invalid characters.");
				return false;
   			}
		}
		for (i=0; i<domain.length; i++) {
			if (domain.charCodeAt(i)>127) {
				alert("Ths domain name contains invalid characters.");
				return false;
   			}
		}

// See if "user" is valid 

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

// user is not valid

			alert("The username doesn't seem to be 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) {
				alert("Destination IP address is invalid!");
				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) {
			alert("The domain name does not seem to be valid.");
			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) {
		alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}

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

	if (len<2) {
		alert("This address is missing a hostname!");
		return false;
	}

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


/**************************************/
/*		autocomplete pais			  */
/**************************************/

var req;

function loadXMLDoc(url,destfn) {
   // Internet Explorer
   try { req = new ActiveXObject("Msxml2.XMLHTTP"); }
   catch(e) {
      try { req = new ActiveXObject("Microsoft.XMLHTTP"); }
      catch(oc) { req = null; }
   }

   // Mozailla/Safari
   if (!req && typeof XMLHttpRequest != "undefined") { req = new XMLHttpRequest(); }

   // Call the processChange() function when the page has loaded
   if (req != null) {
      req.onreadystatechange = destfn;
      req.open("GET", url, true);
      req.send(null);
   }
}

function processChange1() {
   // The page has loaded and the HTTP status code is 200 OK
   if (req.readyState == 4 && req.status == 200) {
      // Write the contents of this URL to the searchResult layer
	  if (req != null) {
	      dojo.byId("searchResultPbCntry").innerHTML = req.responseText;
		  dojo.byId("searchResultPbCntry").style.visible = "visible";
	  }
   }
}

function processChange2() {
   // The page has loaded and the HTTP status code is 200 OK
   if (req.readyState == 4 && req.status == 200) {
      // Write the contents of this URL to the searchResult layer
	  if (req != null) {
	      //dojo.byId("searchResultCommCntry").innerHTML = req.responseText;
		  dojo.byId("searchResultCommCntry").style.visible = "visible";
	  }
   }
}


function setit(str, id){
	dojo.byId(id).value=str; 
}

function getCntry(v) 
{
	dojo.byId('searchResultCommCntry').style.visibility='visible';
	loadXMLDoc('includes/tools/cntry/cntryfind.php?fn=paises.txt&fl=default&d=default&sc=blue&usc=red&rfs=0&id=commCntr&cntr='+v,processChange2)
}

var lastSentByMail; 

/*****************************************
	PopUp Share
******************************************/

var  addthis_url   = '';
var  addthis_title = '';

function share_click(u, t){

 var gurl  = 'bookmark.php';
 gurl += '?url='+u;
 gurl += '&title='+t;

 window.open(gurl,'share','scrollbars=yes,menubar=no,width=530,height=440,resizable=yes,toolbar=no,location=no,status=no,screenX=200,screenY=100,left=200,top=100');


 return false;
}
