/////// VALIDACION DE FORMULARIOS \\\\\\\\

/* Codifica Parametro Para Valores */
function URLEncodeValue(obj)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = obj;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	return encoded;
}


/* FUNCIONES VALIDACIÓN FORMULARIOS */

var whitespace = " \t\n\r";
var reWhitespace = /^\s+$/

/** Verifica que no este vacio **/
function isEmpty(s){
	return ((s == null) || (s.length == 0)) 
}
 
/*** Verifica que no sean espacios en blanco o vacio ***/
function isWhitespace (s){
    return (isEmpty(s) || reWhitespace.test(s));
}
 
/*** corta espacios en blanco al principio y al final de una variable ***/
function trimAll(sString) 
{
    while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	};
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

/*** Valida un email mediante expresiones regulares ***/
function validarEmail(valor) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(valor)){
                return false;
        } else {
                return true;
        }
}
function isEmail(s){
	return (isWhitespace(s) || validarEmail(s));
}


/* ONMOUSEOVER Y ONMOUSEOUT DE OPCIONES DE MENU */
function setOpcionOver(obj,color){
	obj.style.backgroundImage="url(/images/comm/bg_header_hover.png)";
	obj.style.color="#000000";
	return null;
}
function setOpcionOut(obj){
	obj.style.backgroundImage="";
	obj.style.color="";
	return null;
}

/* ONMOUSEOVER Y ONMOUSEOUT DE LISTADO PANEL */
function setListOver(obj,color){
	obj.style.backgroundImage="none";
	obj.style.backgroundColor=color;
	obj.style.color="#000000";
	return null;
}
function setListOut(obj){
	obj.style.backgroundImage="";
	obj.style.backgroundColor="";
	obj.style.color="";
	return null;
}

// Parseador de textos normarles a url
function parseToURL(str){
	str=str.replace(/á/ig,'a');
	str=str.replace(/à/ig,'a');
	str=str.replace(/â/ig,'a');
	str=str.replace(/é/ig,'e');
	str=str.replace(/è/ig,'e');
	str=str.replace(/ê/ig,'e');
	str=str.replace(/ë/ig,'e');
	str=str.replace(/ç/ig,'c');
	str=str.replace(/í/ig,'i');
	str=str.replace(/ì/ig,'i');
	str=str.replace(/î/ig,'i');
	str=str.replace(/ï/ig,'i');
	str=str.replace(/ó/ig,'o');
	str=str.replace(/ò/ig,'o');
	str=str.replace(/ö/ig,'o');
	str=str.replace(/ô/ig,'o');
	str=str.replace(/ú/ig,'u');
	str=str.replace(/ù/ig,'u');
	str=str.replace(/ü/ig,'u');
	str=str.replace(/û/ig,'u');
	str=str.replace(/&/ig,'and');
	str=str.replace(/ñ/ig,'n');
	str=str.replace(/ /ig,'-');
	str=str.replace(/·/ig,'-');
	var noChar = new Array('\'','/','?','¿','!','¡',':','"','(',')','[',']','=','%','$','#','@','|','{','}','¬','~','*',';',',','.',',','[',']','^','´','`','¨','+',';','<','>','~','\\','ª','º');
	for(i=0;i<noChar.length;i++){
		for (j=0;j<str.length;j++)
		{
			str=str.replace(noChar[i],'');
		}
	}
	str=str.replace(/--/ig,'-');
	str=str.toLowerCase();
	return str;
}

// Inserta el titulo parseado para URL en el input URL
function setBlogURL(eleorg,eledest){
	eledest.value=parseToURL(eleorg.value);
}

/* valida los campos del formulario blog */
function valBlogData(frm, mode){
	var ok=true;
	var msg=txt['0'];
	if(isWhitespace(frm.titulo.value)==true){
		ok=false;
		msg+=txt['1'];
	}
	if(isWhitespace(frm.url.value)==true){
		ok=false;
		msg+=txt['2'];
	}
	if(mode=='crear'){
		if(isWhitespace(frm.img_code.value)==true){
			ok=false;
			msg+=txt['5'];
		}
	}
	if(isWhitespace(frm.categoria.value)==true){
		ok=false;
		msg+=txt['3'];
	}
	if(isWhitespace(frm.plantilla.value)==true){
		ok=false; 
		msg+=txt['4'];
	}

	if(ok==false){
		alert(msg);
		return null;
	}else{
		//comprobamos que la url esté libre
		if(frm.valurl.value!='true'){
			alert(msg_txt['4']);
			frm.url.focus();
			frm.url.style.backgroundColor="#DAB8B8";
			return null;
		}else{
			frm.submit();
		}
	}
}

/* ELIMINAR BLOG */
function delBlog(iduser,idblog){
	if(confirm(msg_txt['5'])==true){
		location.assign("/blogs/edicion/configuracion/eliminar/");
	}
}

/* valida los campos del formulario blog */
function valUsuData(frm, mode){
	var ok=true;
	var msg=txt['0'];
	if(mode=='crear'){
		if(isWhitespace(frm.usuario.value)==true){
			ok=false;
			msg+=txt['6']; //CAMBIAR TEXTO
		}
		if(isWhitespace(frm.img_code.value)==true){
			ok=false;
			msg+=txt['5'];
		}
		//comprobamos que el usuario esté libre
		if(frm.valurl.value!='true'){
			alert(msg_txt['4']);
			frm.usuario.focus();
			frm.usuario.style.backgroundColor="#DAB8B8";
			return null;
		}
	}
	if(isWhitespace(frm.nombre.value)==true){
		ok=false;
		msg+=txt['7'];
	}
	if(isWhitespace(frm.apellidos.value)==true){
		ok=false;
		msg+=txt['8'];
	}
	if(isEmail(frm.mail.value)==true){
		ok=false;
		msg+=txt['9'];
	}

	if(ok==false){
		alert(msg);
		return null;
	}else{
		frm.submit();
	}
}

/* Añade la categoría seleccionada */
function setIdCat(cat,idcat,frm,iduser,idblog,idart){
	frm.catgr.value+=cat+", ";
	frm.idcatgr.value+=idcat+"-";
	getAddCatTable(frm,iduser,idblog,idart);
	return null;
}

/* Elimina la categoría seleccionada */
function delIdCat(frm,cat,idcat){
	if((cat==", ")||(idcat=="-")){
		frm.catgr.value="";;
		frm.idcatgr.value="";
	}else{
		frm.catgr.value=cat;
		frm.idcatgr.value=idcat;
	}
	getDelCatTable(frm);
	return null;
}

/* inserción de tag */
function setTag(tag,frm,idart){
	var input = frm.taglist.value;
	if (input.charAt(input.length-1)==' '){
		input=input.substr(0,input.length-1);
	}
	if (input.charAt(input.length-1)==','){
		input=input.substr(0,input.length-1);
	}
	if(input!=''){
		var tagArr = input.split(", ");
		if(tagArr.length<=1){
			 tagArr = input.split(", ");
		}
		var exist=false;
		for (var i=0; i<tagArr.length; i++)	{
			if(tagArr[i]==tag){
				exist=true;
			}
		}
		if(!exist){
			tagArr[tagArr.length]=tag+", ";
		}
		input=tagArr.join(", ");
	}else{
		input=tag+", ";
	}

	frm.taglist.value = input;
	return null;
}

/* VALIDACION DE DATOS DEL ARTICULO */
function valArticuloData(frm,mode,estado){
	var ok=true;
	var msg=txt['0'];

	if(isWhitespace(frm.titulo.value)==true){
		ok=false;
		msg+=txt['1'];
	}
	var cuerpo=tinyMCE.getContent('texteditor');
	if(isWhitespace(cuerpo)==true){
		ok=false;
		msg+=txt['10'];
	}else{
		frm.cuerpo.value=cuerpo;
	}

	if(ok==false){
		alert(msg);
		return null;
	}else{
		frm.saving.value=true;
		frm.accion.value=mode;
		frm.estado.value=estado;
		frm.submit();
	}
}

// RESET DEL FORMULARIO
function resetRollForm(frm){
	frm.enlace.value="";
	frm.url.value="";
	frm.idroll.value="";
}

/* MUESTRA EL COMENTARIO SELECCIONADO */
function setComment(id){
	tr=document.getElementById('tr_'+id);
	img=document.getElementById('img_'+id);
	if(tr.style.display==""){
		tr.style.display="none";
		img.src="/images/comm/ico_listin.gif";
	}else{
		tr.style.display="";
		img.src="/images/comm/ico_listout.gif";
	}
}

/* VALIDACIÓN FORMULARIO ADJUNTOS */
function addAdjunto(frm){
	var nombre = URLEncodeValue(frm.nombre.value);
	var inputfile = frm.inputfile.value;
	var ok=true;
	var msg=txt['0'];
	if(isWhitespace(inputfile)==true){
		ok=false;
		msg+="- Archivo a subir\n";
	}
	if(isWhitespace(nombre)==true){
		ok=false;
		msg+="- Nombre\n";
	}
	if(ok==false){
		alert(msg);
		return null;
	}else{
		frm.submit();
	}
}

//Capturamos el enlace del upload
function setUploadLink(href,frm){
	frm.link_insert.value=href;
}

//Capturamos la url del upload
function setUploadSrc(src,frm){
	frm.src_insert.value=src;
}

// La siguinte función esta calificada como "OBRA MAESTRA"
// ÚSALA, RESPÉTALAA, Y TRÁTALA COMO TAL

// Inserta adjuntos dentro del tinyMCE
function setUpload(frm){
	src=frm.src_insert.value;
	if(!src){
		alert("Introduce un tamaño para la imagen");
		return null;
	}
	href=frm.link_insert.value;
	if(href=='false'){
		html='<img src="'+src+'" />';
	}else{
		html='<a href="'+href+'" target="_blank"><img src="'+src+'" /></a>';
	}
	window.parent.tinyMCE.execCommand('mceInsertContent',false,html);
	return false;
}

// Validación del formulario de password
function valPassData(frm){
	var ok=true;
	var msg=txt['0'];

	if(isWhitespace(frm.confoldpass.value)==true){
		ok=false;
		msg+=txt['14'];
	}
	if(isWhitespace(frm.newpass.value)==true){
		ok=false;
		msg+=txt['15'];
	}
	if(isWhitespace(frm.confnewpass.value)==true){
		ok=false;
		msg+=txt['16'];
	}

	if(ok==false){
		alert(msg);
		return null;
	}else{
		frm.submit();
	}
}

// Mostrar el formulario de añadir comentario
function addCommentario(){
	x=document.getElementById('com_table_cont');
	if(x.style.display=='inline'){
		x.style.display='none';
	}else{
		x.style.display='inline';
	}
}

// Mostrar el formulario de añadir comentario
function addComment(){
	x=document.getElementById('com_table_cont');
	y=document.getElementById('add_comentario_form');
	if(x.style.display=='inline'){
		x.style.display='none';
		y.style.backgroundColor='';
	}else{
		x.style.display='inline';
		y.style.backgroundColor='#e9eaeb';
		document.getElementById('send_table_cont').style.display='none';
		document.getElementById('amic_form').style.backgroundColor='';;
		document.getElementById('msg_cont').style.display='none';
	}
}

// Validar comentario sin usuario
function valPublicCom(frm,idusu,idblog,idart, ids){
	var ok=true;
	var msg=txt['0'];

	if(isWhitespace(frm.com_name.value)==true){
		ok=false;
		msg+=txt['2'];
	}
	if(isWhitespace(frm.com_title_2.value)==true){
		ok=false;
		msg+=txt['25'];
	}else{
		if (validarEmail(frm.com_title_2.value))
		{
			ok=false;
			msg+=txt['25'];
		}
	}
	if(isWhitespace(frm.com_poblacion.value)==true){
		ok=false;
		msg+=txt['24'];
	}
	if(isWhitespace(frm.com_text.value)==true){
		ok=false;
		msg+=txt['17'];
	}

	if(isWhitespace(frm.codconf.value)==true){
		ok=false;
		msg+="- Codi de segguretat";
	}
    
	if(ok==false){
		alert(msg);
		return null;
	}else{
		addPublicCom(frm,idusu,idblog,idart, ids);
	}
}

// Mostrar el formulario de enviar a un amigo
function sendAmic(){
	x=document.getElementById('send_table_cont');
	y=document.getElementById('amic_form');
	if(x.style.display=='inline'){
		x.style.display='none';
		y.style.backgroundColor='';
	}else{
		x.style.display='inline';
		y.style.backgroundColor='#e9eaeb';
		document.getElementById('com_table_cont').style.display='none';
		document.getElementById('add_comentario_form').style.backgroundColor='';
		document.getElementById('msg_cont').style.display='none';
	}
}

// Validar comentario sin usuario
function valSendAmic(frm,idusu,idblog,idart){
	var ok=true;
	var msg=txt['0'];

	/*if(isWhitespace(frm.nombre_orig.value)==true){
		ok=false;
		msg+=txt['19'];
	}
	if(isWhitespace(frm.email_orig.value)==true){
		ok=false;
		msg+=txt['20'];
	}
	if(isWhitespace(frm.nombre_dest.value)==true){
		ok=false;
		msg+=txt['21'];
	}*/
	if(isWhitespace(frm.email_dest.value)==true){
		ok=false;
		msg+=txt['22'];
	}
	if(isWhitespace(frm.zpamInput2.value)==true){
		ok=false;
		msg+=txt['23'];
	}

	if(ok==false){
		alert(msg);
		return false;
	}else{
		sendToAmic(frm,idusu,idblog,idart);
	}
}

// Validar comentario con usuario
function valRegisterCom(frm,idusu,idblog,idart){
	var ok=true;
	var msg=txt['0'];

	if(isWhitespace(frm.com_name.value)==true){
		ok=false;
		msg+=txt['2'];
	}
	if(isWhitespace(frm.com_pass.value)==true){
		ok=false;
		msg+=txt['18'];
	}
	if(isWhitespace(frm.com_text.value)==true){
		ok=false;
		msg+=txt['17'];
	}

	if(ok==false){
		alert(msg);
		return null;
	}else{
		addRegisterCom(frm,idusu,idblog,idart);
	}
}
// Muestra emails por pantalla
// pero algo más seguro
function showEmail(user,domain,extension){
	email=user + "@" + domain + "." + extension;
	document.write('<a href="mailto:'+email+'">'+email+'</a>');
}

// Cuenta y limita los caracteres de un comentario
function conCommChars(obj){
	var cont = document.getElementById('char_contador');
	var chars = obj.value.length;
	var resta = 255 - chars;
	if(resta<=0){
		obj.value=obj.value.substr(0,255)
		resta=0;
	}
	cont.innerHTML=resta;

	return true;
}

// Muestra o oculta el select de subcategoria
function showSubCatSelect(cat){
	if(cat=='10'){
		document.getElementById("sub_select").style.display='';
	}else{
		document.getElementById("sub_select").style.display='none';
	}
}
function enviar(opt, url_art){
	var url="";
	switch (opt)
	{
		case 'meneame':
			url = "http://meneame.net/login.php?return=/submit.php?url=http://" + url_art;
		break;
		case 'digg':
			url = "http://digg.com/submit?phase=2&url=http://" + url_art;
		break;
		case 'tafanera':
			url = "http://latafanera.cat/submit.php?url=http://" + url_art;
		break;
		case 'facebook':
			url = "http://www.facebook.com/sharer.php?u=http://" + url_art + "&title=blogs.ibdigital.net";
        break;
        case 'twitter':
			url = "http://twitter.com/home/?status=http://" + url_art + "&title=blogs.ibdigital.net";
        break;
	}
	var pop = window.open(url);
	popup.focus();
}
