// JavaScript Document

function CarregaCombos() {
	var P1 = ObtenirP(1);
	if (P1 == "Funcio=10") {
		P1 = 2;
	}
	var P6 = ObtenirP(6);
	if ((P6 == "")||(P6 == "0")) {
		P6 = -1;
	}
	else {
		P6 = P6.substring(10);
	}
	CarregaCombos2(P1,P6)
	
}

function CarregaCombos2(iSeleccio,iEstanca) {
	document.getElementById("Seleccio").selectedIndex=iSeleccio;
	document.getElementById("Estances").value=iEstanca;	
}


function CanviSeleccioEstanca(idAplicacio) {
  var cbSeleccio=document.getElementById("Seleccio");
  var cbEstances=document.getElementById("Estances"); 
  var sFuncio;  
  var iIndex,iIndex2,iIndex3;
  var sUsuari='';
  var sURL;
  
  switch (idAplicacio) {
    case 4: // Cas online	
      sFuncio='410';		
      sUsuari='&usuari=';
      // Busquem l'usuari de la crida URL      
      sURL=window.location.href;      
      iIndex=sURL.indexOf(sUsuari);
      if (iIndex>-1) {
        iIndex2=sURL.indexOf('&',iIndex+1);        
        if (iIndex2==-1) {
          // Agafem la resta de la cadena
          iIndex3=sURL.Length; 
        }
        else {
          iIndex3=iIndex2;
        }
        sUsuari=sURL.substring(iIndex,iIndex3);  
      }
      break;    
    case 2:	
      sFuncio='210';		
      break;
    default:
      sFuncio='110';		
      break;
  }
  window.location='../servlet/BlopHome?'+cbSeleccio.selectedIndex+'&Funcio='+sFuncio+
     '&seleccio='+cbSeleccio.options[cbSeleccio.selectedIndex].value+
     '&idIdioma=ES&aplicacio='+idAplicacio+'&idEstanca='+cbEstances.options[cbEstances.selectedIndex].value+sUsuari;		
}

function cercaProjectesRocaIYo (idAutor, idClient) {
        var sCerca=document.getElementById("txtCerca").value;
	
	if (sCerca.length > 0) {
          window.location='../servlet/BlopHome?Funcio=610&seleccio=4&idIdioma=ES&aplicacio=0&idEstanca=-1&idClient='+idClient+'&idAutor='+idAutor+'&cerca='+StringAUtf8(sCerca.toLowerCase())+'&txtcerca='+sCerca+'&rnd='+Math.random()*11;	
	}
}

function cercaProjectes (idAplicacio) {
	var cbSeleccio=document.getElementById("Seleccio");
  	var cbEstances=document.getElementById("Estances"); 
	var sCerca=document.getElementById("txtCerca").value;
	
	if (sCerca.length > 0) {
          window.location='../servlet/BlopHome?'+cbSeleccio.selectedIndex+'&Funcio=510&seleccio='+cbSeleccio.options[cbSeleccio.selectedIndex].value+'&idIdioma=ES&aplicacio='+idAplicacio+'&idEstanca='+cbEstances.options[cbEstances.selectedIndex].value+'&cerca='+StringAUtf8(sCerca.toLowerCase())+'&txtcerca='+sCerca+'&rnd='+Math.random()*11;	
	}
}

function StringAUtf8(sTexte) {
      var iCodiASCII;

      var cadenaUtf="";

	for (var i=0;(i<sTexte.length);i++) {
    		iCodiASCII=sTexte.charCodeAt(i);
		// Si és una lletra sense accent o número no cal conversio
    		if (((iCodiASCII>=45)&&(iCodiASCII<=57))||
    		    ((iCodiASCII>=65)&&(iCodiASCII<=90))||
    		    ((iCodiASCII>=97)&&(iCodiASCII<=122))||
                    (iCodiASCII==32)||
                    (iCodiASCII==61)||(iCodiASCII==63)) {
    			cadenaUtf=cadenaUtf+sTexte.charAt(i);
    		} else if (iCodiASCII==38) {
                    cadenaUtf=cadenaUtf+"&amp;";
                }
    		else {
    			cadenaUtf=cadenaUtf+"%"+decimal_a_hexadecimal(iCodiASCII);
    		}
    	}

        return cadenaUtf;
      
    }
	
function decimal_a_hexadecimal(dec)
{
	var Char_hexadecimales = "0123456789ABCDEF";
	var low = dec % 16;
	var high = (dec - low)/16;
	hex = "" + Char_hexadecimales.charAt(high) + Char_hexadecimales.charAt(low);
	return hex;
}


function CarregaPagina (P1) {
    switch(parseInt(P1)) {
		case 0: 
		    // Entrar				
			canviPestanya (parseInt(P1));
			mostraTitol('Enter');
			mostraHTML('centre','entrar.html', '#000000');
		break;
		case 1: 
			// Projectes
			canviPestanya (parseInt(P1));
            mostraTitol('User proyects');
			mostraHTML('centre','projecte.html', '#FFFFFF');
			CarregaListProjecte (2); //mostraHTML('zona_projectes','servlet/BlopHome?Funcio=10&seleccio=2&idIdioma=ES&rnd='+Math.random()*11, '#FFFFFF');
		break;							
		case 2: 
			// Serveis			
            canviPestanya (parseInt(P1));
			mostraTitol('Add your drawings');
			mostraHTML('centre','dibuixos.html', '#000000');
		break;
		case 3: 
			// Foro
			canviPestanya (parseInt(P1));
            mostraTitol('Forum');
			//mostraHTML('centre','foro_prova.html');	
			mostraHTML('centre','./servlet/Foro?Funcio='+ObtenirP(2)+'&idTemaPare='+ObtenirP(4)+'&idIdioma='+ObtenirP(3)+'&idPregunta='+ObtenirP(5)+'&rnd='+Math.random()*11, '#FFFFFF');
		break;									
		case 4: 
			// Contactar			
			canviPestanya (parseInt(P1));
            mostraTitol('Contact');
			mostraHTML ('centre', 'contactar.html', '#FFFFFF');
			mostraHTML('zona_contactar','contactar_par.html');
		break;							
		case 5: 
			// Preguntas			
			canviPestanya (parseInt(P1));
            mostraTitol('Interest Links');
			mostraHTML('centre','enlaces.html', '#000000');
		break;
		case 10:
			canviPestanya (parseInt(P1));
			mostraTitol('BlopHome Registro');
			mostraHTML('centre','register.html', '#FFFFFF');
			ObtenirPregunta(false);
		break;
		case 20:
			mostraTitol('Envia tus dibujos a BlopHome');
			mostraHTML('centre','form-envia-tus-dibujos.html', '#FFFFFF');
			ObtenirPregunta(false);
		break;
	}
}

function CarregaListProjecteAdm (idPag) {
	mostraHTML('zona_projectes','./servlet/BlopHome?Funcio=100&idPag='+idPag+'&rnd='+Math.random()*11, '#FFFFFF');
}

function CarregaLlistaProjectes() {
	var P1 = ObtenirParamDef(1,'1'); // Per defecte els més votats
	var P2 = ObtenirParamDef(2,'2'); // Per defecte els més votats 
	var P3 = ObtenirParamDef(3,'-1'); // Per defecte totes
  	var sURL = './servlet/BlopHome?'+P1+'&Funcio=110&seleccio='+P2+'&idIdioma=ES&aplicacio=3&idEstanca='+P3+'&rnd='+Math.random()*11;
	mostraHTML('llistat_projectes',sURL, '#000000');
	CarregaCombos2(P1,P3);
}

function EliminarProjecte (idProject) {
	var User = document.getElementById("userName").value;
	var Pass = hex_md5(document.getElementById("passUser").value);
	//alert ('servlet/BlopHome?Funcio=13&idProject='+idProject+'&user='+User+'&pass='+Pass+'&rnd='+Math.random()*11);
	alert (getFile('./servlet/BlopHome?Funcio=13&idProject='+idProject+'&user='+User+'&pass='+Pass+'&rnd='+Math.random()*11));
	CarregaListProjecteAdm (0);
}

function CarregaListProjecte (bPintaImage) {
	var P1 = ObtenirP(1);
	if (P1 == "Funcio=10") {
		P1 = 2;
	}
	if (bPintaImage == 1) {
  	  switch(parseInt(P1)) {
		case 0: 
			// Mas Vistos				
			/*document.getElementById("titulLlistaPro").innerHTML="Más Vistos";*/
			document.getElementById("titulLlistaPro").src= "../images/vistosW.jpg";
			//mostraHTML('zona_projectes','./servlet/BlopHome?Funcio=10&seleccio=1&idIdioma=ES&rnd='+Math.random()*11, '#FFFFFF');
		break;
		case 1: 
			// Mas Valorados				
			/*document.getElementById("titulLlistaPro").innerHTML="Más Valorados";*/
			document.getElementById("titulLlistaPro").src= "../images/votadosW.jpg";
			//mostraHTML('zona_projectes','./servlet/BlopHome?Funcio=10&seleccio=2&idIdioma=ES&rnd='+Math.random()*11, '#FFFFFF');
		break;
		case 2: 
			// Mas Recientes				
			/*document.getElementById("titulLlistaPro").innerHTML="Más Recientes";*/
			document.getElementById("titulLlistaPro").src= "../images/recientesW.jpg";
			//mostraHTML('zona_projectes','./servlet/BlopHome?Funcio=10&seleccio=3&idIdioma=ES&rnd='+Math.random()*11, '#FFFFFF');
		break;
	  }
	}
}

function CarregaContactar (P1) {
	switch(parseInt(P1)) {
		case 0: 
			// Particulars				
			mostraHTML('zona_contactar','contactar_par.html');
			ObtenirPregunta(false);
		break;
		case 1: 
			// Empreses
			mostraHTML('zona_contactar','contactar_emp.html');
			ObtenirPregunta(false);
		break;
	}
}

function CarregaPaginaForo (sHtml) {
    // Foro
	mostraHTML('centre', sHtml+'&rnd='+Math.random()*11);
};


function ObtenirParamDef(nParametre,sDef) 
{ 
	//Capturem la URL 
	var callingURL = document.location.href; 

	//Separem els paràmetres 
	var cgiString = callingURL.substring(callingURL.indexOf('?')+1,callingURL.length); 
	
    // En realitat comencem per zero
	nParametre -=1; 

	// Dividim els paràmetres
	var col_array=cgiString.split("&"); 
	var part_num=0; 
	
	if (cgiString.length<callingURL.length) {
			
		// Ara recorrem els paràmetres
		while (part_num < col_array.length) 
		{ 
			if ( part_num == nParametre ) 
				return col_array[part_num]; 
			else part_num+=1; 
		}
	} 

	// valor per defecte (no trobat)
	return sDef; 
};

function ObtenirP(nParametre) 
{ 
	return ObtenirParamDef(nParametre,'0');
};


function mostraTitol(texte){
  document.title=texte.concat(" - BlopHome decora, dibuja o diseña cualquier habitación de tu casa u oficina.");  
};

function mostraTexte(element,texte){
  document.getElementById(element).innerHTML=texte;
};

function mostraFoto(foto){
  document.getElementById('banner').style.backgroundImage="url(./imatges/".concat(foto).concat(".jpg)");
};

function mostraHTML(IdDIV,filename, sColor){
	document.getElementById(IdDIV).innerHTML=getFile(filename);
	document.getElementById(IdDIV).style.backgroundColor=sColor;
};

function getFile(filename)
  { 
    oxmlhttp = null;
    try
      { oxmlhttp = new XMLHttpRequest();
        oxmlhttp.overrideMimeType("text/xml");
      }
    catch(e)
      { try
          { oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
          }
        catch(e)
          { return null;
          }
      }
    if(!oxmlhttp) return null;
    try
      { oxmlhttp.open("GET",filename,false);
        oxmlhttp.send(null);
      }
    catch(e)
      { 
	  	return null;
      }
	return oxmlhttp.responseText;
  }

function ObtenirImatge (id, bRocaiYo) {
	var sSufix = "";	
	if (bRocaiYo) {
		sSufix = "iyo";
	} 

    	EliminarImatges (bRocaiYo);
	navRoot2 = document.getElementById(id);
	navRoot2.className = "divProjecteSelec";
	
	fills = navRoot2.getElementsByTagName("img");
	for (j=0; j<fills.length; j++) {
		node = fills[j];
		if (node.className == "imBotonObrir") {
			node.setAttribute ("src", "../../images/openprj.jpg");
		}	    
 	}
	/*fills = navRoot2.getElementsByTagName ("table");
	for (j=0; j<fills.length; j++) {
		fills[j].className = "tableProjSelec";
	}*/
	fills = navRoot2.getElementsByTagName ("input");
	for (j=0; j<fills.length; j++) {
		fills[j].className = "titulProjecteSelec"+sSufix;
	}
	fills = navRoot2.getElementsByTagName ("div");
	for (j=0; j<fills.length; j++) {
		if (fills[j].className == "nomProp"+sSufix) {
			fills[j].className = "nomPropSelec"+sSufix;
		} else if (fills[j].className == "descProp"+sSufix) {
			fills[j].className = "descPropSelec"+sSufix;
		} else if (fills[j].className == "div_click_foto"+sSufix) {
			fills[j].className = "div_click_foto_selec"+sSufix;
		} else if (fills[j].className == "div_texte_boto_proj") {
			ancles = fills[j].getElementsByTagName ("a");
			for (i=0; i<ancles.length; i++) {
				if (ancles[i].className == "ancla_obrir_projecte"+sSufix) {
					ancles[i].className = "ancla_obrir_projecte_selec"+sSufix;	
				}
			}
		}
	}
}

function EliminarImatges (bRocaiYo) {
	var sSufix = "";	
	if (bRocaiYo) {
		sSufix = "iyo";
	}
	node = document.getElementById ("zona_projectes");
	navRoot2 = node.getElementsByTagName ("div");
	for (j=0; j<navRoot2.length; j++) {
		node = navRoot2[j];
		if ((node.className == "divProjecteSelec") || (node.className == "divProjecte")) {
			node.className = "divProjecte";
			navRoot3 = node.getElementsByTagName ("img");
			for (i=0; i<navRoot3.length; i++) {
				node2 = navRoot3[i];
				if (node2.className == "imBotonObrir") {
					node2.setAttribute ("src", "../../images/blank"+sSufix+".jpg");
				}
			}
			navRoot3 = node.getElementsByTagName ("input");
			for (i=0; i<navRoot3.length; i++) {
				node2 = navRoot3[i];
				node2.className = "titulProjecte"+sSufix;
			}

			navRoot3 = node.getElementsByTagName ("div");
			for (i=0; i<navRoot3.length; i++) {
				node2 = navRoot3[i];
				if (node2.className == "nomPropSelec"+sSufix) {
					node2.className = "nomProp"+sSufix;
				} else if (node2.className == "descPropSelec"+sSufix) {
					node2.className = "descProp"+sSufix;
				} else if (node2.className == "div_click_foto_selec"+sSufix) {
					node2.className = "div_click_foto"+sSufix;
				} else if (node2.className == "div_texte_boto_proj") {
					ancles = node2.getElementsByTagName ("a");
					for (k=0; k<ancles.length; k++) {
						if (ancles[k].className == "ancla_obrir_projecte_selec"+sSufix) {
							ancles[k].className = "ancla_obrir_projecte"+sSufix;	
						}
					}
				}
			}
		}
	}
}

function canviPestanya (id) {
	if (id < 10) {
		for (i=0; i<6; i++) {
	    	navRoot2 = document.getElementById("pes"+i);
			if (i == id) {
				navRoot2.className = "pest_activa";
			} else {
				navRoot2.className = "pest_desactiva";
			}
		}
	}
}

// Enviar Dibuixos
OBJ_LLISTA = "listFile";
OBJ_SELECCIO_FILE = "file";
	
function seleccionaFitxer () {
	document.fAddPicture.file.click ();
}
	
function afegirDibuixLlista () {
	if (document.getElementById (OBJ_SELECCIO_FILE).value.length > 0) {
		var nodo = document.createElement("option");
		nodo.value = document.getElementById (OBJ_LLISTA).length;
		nodo.innerHTML = document.getElementById (OBJ_SELECCIO_FILE).value;
		document.getElementById (OBJ_LLISTA).appendChild (nodo);
	}
	
	var Node = document.getElementById (OBJ_SELECCIO_FILE).parentNode.cloneNode (true);
	document.getElementById (OBJ_SELECCIO_FILE).id = "file_ok"+document.getElementById ("num_files").value;
	document.getElementById (OBJ_SELECCIO_FILE).name = "file_ok"+document.getElementById ("num_files").value;
	document.getElementById ("num_files").value++;
	var NodePare = document.getElementById (OBJ_SELECCIO_FILE).parentNode.parentNode;
	document.getElementById (OBJ_SELECCIO_FILE).parentNode.style.visibility = "hidden";
	NodePare.insertBefore (Node, document.getElementById (OBJ_SELECCIO_FILE).parentNode);
}

function eliminarDibuixLlista () {
	var nodeSelFiles = document.getElementById (OBJ_SELECCIO_FILE).parentNode.parentNode;
	var nodeLlista = document.getElementById (OBJ_LLISTA);
	var j = 0;
	var bTrobat = false;
	
 	for (var i=nodeLlista.length-1; i>=0; i--) {
		nodeop = nodeLlista[i];
		
		if (nodeop.selected) {
			j=0;
			bTrobat = false;
			while ((j < nodeSelFiles.childNodes.length) && (!bTrobat)) {
				if (nodeSelFiles.childNodes[j].firstChild.value == nodeop.innerHTML) {
					nodeSelFiles.removeChild(nodeSelFiles.childNodes[j]);
					bTrobat = true;
				}
				j++;
			}
			nodeLlista.removeChild(nodeop);
		}
	}
}

//************************************************************
// Enviament de Dibuixos
//************************************************************
function AddPicture() {
	var nom = document.getElementById('fpic_nom').value;
	var cognom = document.getElementById('fpic_cnom').value;
	var email = document.getElementById('fpic_mail').value;
	var comentaris = document.getElementById('fpic_notes').value;
	var bAcepto = document.getElementById('fcon_acepto').checked;
	var texto = 'Error al validar formulario. Corrija el/los siguiente/s error/es:\n';
	ret=true;
	if ((nom == null || nom.length == 0 || /^\s+$/.test(nom))){
		texto = texto + '\t* Nombre en blanco.\n';
		ret=false;
	} 
	if ((cognom == null || cognom.length == 0 || /^\s+$/.test(cognom))){
		texto = texto + '\t* Apellidos en blanco.\n';
		ret=false;
	}
	if ((email == null || email.length == 0 || /^\s+$/.test(email))){
		texto = texto + '\t* Email en blanco.\n';
		ret=false;
	}
	if (document.getElementById('listFile').length == 0) {
		texto = texto + "\t* No ha añadido ninguna imagen o fichero.\n";
		ret=false;
	}
	if (!bAcepto){
		texto = texto + '\t* Debe aceptar las condiciones.\n';
		ret=false;
	}
	
	if(ret==true){
		if (ComprovarQuestion (document.getElementById('idSeguretat').value, document.getElementById('resposta').value, false) == 1) {
			document.fAddPicture.submit ();
			return true;
		} else {
			alert("Respuesta del código de seguridad incorrecto.");
			ObtenirPregunta();
			return false;
		}	
		return true;
	} else {
		alert(texto);
		return false;
	}
}

function ResetearFormDibuix () {
	var nodeSelFiles = document.getElementById (OBJ_SELECCIO_FILE).parentNode.parentNode;
	var nodeLlista = document.getElementById (OBJ_LLISTA);
	var j = 0;
	var bTrobat = false;
	
 	for (var i=nodeLlista.length-1; i>=0; i--) {
		nodeop = nodeLlista[i];
		
		j=0;
		bTrobat = false;
		while ((j < nodeSelFiles.childNodes.length) && (!bTrobat)) {
			if (nodeSelFiles.childNodes[j].firstChild.value == nodeop.innerHTML) {
				nodeSelFiles.removeChild(nodeSelFiles.childNodes[j]);
				bTrobat = true;
			}
			j++;
		}
		nodeLlista.removeChild(nodeop);
	}
	
	document.getElementById ("fpic_nom").value = "";
	document.getElementById ("fpic_cnom").value = "";
	document.getElementById ("fpic_mail").value = "";
	document.getElementById ("fpic_notes").value = "";
	document.getElementById ("num_files").value = "0";
	
	ObtenirQuestion (document.getElementById('idSeguretat'), document.getElementById('pregunta'), false);
}

function resetfContacte () {
	document.getElementById ("fcon_nom").value = "";
	document.getElementById ("fcon_cnom").value = "";
	document.getElementById ("fcon_mail").value = "";
	document.getElementById ("fcon_notes").value = "";
	ObtenirPregunta (false);
}

function SendContacte(bEmpresa) {
	var nom = document.getElementById('fcon_nom').value;
	if (!bEmpresa) {
		var cognom = document.getElementById('fcon_cnom').value;
	}
	var email = document.getElementById('fcon_mail').value;
	var comentaris = document.getElementById('fcon_notes').value;
	var bAcepto = document.getElementById('fcon_acepto').checked;
	var texto = 'Error al validar formulario. Corrija el/los siguiente/s error/es:\n';
	ret=true;
	if ((nom == null || nom.length == 0 || /^\s+$/.test(nom))){
		texto = texto + '\t* Nombre en blanco.\n';
		ret=false;
	} 
	if (!bEmpresa) {
		if ((cognom == null || cognom.length == 0 || /^\s+$/.test(cognom))){
			texto = texto + '\t* Apellidos en blanco.\n';
			ret=false;
		}
	}
	if ((email == null || email.length == 0 || /^\s+$/.test(email))){
		texto = texto + '\t* Email en blanco.\n';
		ret=false;
	}
	if ((comentaris == null || comentaris.length == 0 || /^\s+$/.test(comentaris))){
		texto = texto + '\t* Comentarios en blanco.\n';
		ret=false;
	}
	if (!bAcepto){
		texto = texto + '\t* Debe aceptar las condiciones.\n';
		ret=false;
	}
	
	if(ret==true){
		if (ComprovarQuestion (document.getElementById('idSeguretat').value, document.getElementById('resposta').value, false) == 1) {
			mostraRespostaFormContactar(document.fContacte.action, bEmpresa);
			return true;
		} else {
			alert("Respuesta del código de seguridad incorrecto.");
			ObtenirPregunta(false);
			return false;
		}	
	} else {
		alert(texto);
		return false;
	}
}

function mostraRespostaFormContactar(filename, bEmpresa){
  	alert (getFilePostContactar(filename, bEmpresa));
}

function getFilePostContactar(filename, bEmpresa) { 
    var oxmlhttp = null;
    try { 
		oxmlhttp = new XMLHttpRequest();
        oxmlhttp.overrideMimeType("text/xml");
    } catch(e) { 
		try { 
			oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) { 
			try {
				// Internet Explorer 5.0+
				oxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (ex) {
				return null;
          	}
      	}
	}
    
	if (!oxmlhttp && typeof XMLHttpRequest != 'undefined') {
		// Mozilla 1.0+ y Safari 1.2+
		oxmlhttp = new XMLHttpRequest();
	} 

	
	if(!oxmlhttp) return 'Se ha producido un error inesperado';
    try {
		var BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$';
    	var CRLF = '\r\n';
		
		// nom
		var L = '--' + BOUNDARY + CRLF;
		L = L + 'Content-Disposition: form-data; name="fcon_nom"' + CRLF; 
        L = L + CRLF;
		L = L + document.fContacte.elements['fcon_nom'].value+ CRLF;
		if (!bEmpresa) {
			//cognoms
			L = L + '--' + BOUNDARY + CRLF;
        	L = L + 'Content-Disposition: form-data; name="fcon_cnom"'+ CRLF;
        	L = L + CRLF;
			L = L + document.fContacte.elements['fcon_cnom'].value+ CRLF;
		}
		//mail
		L = L + '--' + BOUNDARY+ CRLF;
		L = L + 'Content-Disposition: form-data; name="fcon_mail"'+ CRLF;
		L = L + CRLF;
		L = L + document.fContacte.elements['fcon_mail'].value+ CRLF;
		//notes
		L = L + '--' + BOUNDARY+ CRLF;
        L = L + 'Content-Disposition: form-data; name="fcon_notes"'+ CRLF;
        L = L + CRLF;
		L = L + document.fContacte.elements['fcon_notes'].value+ CRLF;
                L = L + '--' + BOUNDARY + CRLF;
 		L = L + 'Content-Disposition: form-data; name="idIdioma"'+ CRLF;
		L = L + CRLF;
		L = L + 'EN'+ CRLF;
		L = L + '--' + BOUNDARY;
    	//L = L + CRLF;
		
		oxmlhttp.open("POST",filename,false);
		
		oxmlhttp.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + BOUNDARY);
		
		oxmlhttp.send(L);
	} catch(e) { 
	    return 'Se ha producido un error: '+e.message;
    }
	return oxmlhttp.responseText;
}

function ObtenirPregunta (bEstemSvlt) {
	ObtenirQuestion (document.getElementById('idSeguretat'), document.getElementById('pregunta'), bEstemSvlt);
}

function ObtenirPreguntaUs () {
	ObtenirQuestionUs (document.getElementById('idSeguretat'), document.getElementById('pregunta'));
}

function resetfRegister () {
	document.fRegister.reset ();
	ObtenirPregunta (false);
}

function Registrarse() {
	name = document.fRegister.elements['name'].value;
	mail = document.fRegister.elements['email'].value;
	user = document.fRegister.elements['user'].value;
	twitter = document.fRegister.elements['twitter'].value;
	pass = document.fRegister.elements['pass'].value;
	pass2 = document.fRegister.elements['pass2'].value;
	texto = 'Error al validar formulario. Corrija el/los siguiente/s error/es:\n';
	ret=true;
	if ((mail == null || mail.length == 0 || /^\s+$/.test(mail))){
		texto = texto + '\t* Introduzca un e-mail correcto.\n';
		ret=false;
	}
	if ((user == null || user.length == 0 || /^\s+$/.test(user))){
		texto = texto + '\t* Introduzca un Usuario correcto.\n';
		ret=false;
	}
	if ((pass == null || pass.length == 0 || /^\s+$/.test(pass))){
		texto = texto + '\t* Introduzca una Password correcta.\n';
		ret=false;
	} else if (pass != pass2) {
			texto = texto + '\t* Introduzca una contraseña correcta.\n';
			ret=false;
	}
	/*if (!document.fRegister.elements['bcontract'].checked) {
		texto = texto + '\t* Tiene que aceptar las condiciones de contrato.\n';
		ret=false;
	}*/
	
	if(ret==true){
		if (ComprovarQuestion (document.fRegister.elements['idSeguretat'].value, document.fRegister.elements['resposta'].value, false) == 1) {
			mostraRespostaFormRegister (document.fRegister.action);
			return true;
		} else {
			alert("Respuesta del código de seguridad incorrecta.");
			ObtenirPregunta(false);
			return false;
		}
	} else {
		alert(texto);
		return false;
	}
}

function mostraRespostaFormRegister(filename){
  	alert (getFilePostRegister(filename));
}

function getFilePostRegister(filename) { 
    var oxmlhttp = null;
    try { 
		oxmlhttp = new XMLHttpRequest();
        oxmlhttp.overrideMimeType("text/xml");
    } catch(e) { 
		try { 
			oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) { 
			try {
				// Internet Explorer 5.0+
				oxmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (ex) {
				return null;
          	}
      	}
	}
    
	if (!oxmlhttp && typeof XMLHttpRequest != 'undefined') {
		// Mozilla 1.0+ y Safari 1.2+
		oxmlhttp = new XMLHttpRequest();
	} 

	
	if(!oxmlhttp) return 'Se ha producido un error inesperado';
    try {
		var BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$';
    	var CRLF = '\r\n';
		
		// nom
		var L = '--' + BOUNDARY + CRLF;
		L = L + 'Content-Disposition: form-data; name="name"' + CRLF; 
        L = L + CRLF;
		L = L + document.fRegister.elements['name'].value+ CRLF;
		//cognoms
		L = L + '--' + BOUNDARY + CRLF;
        L = L + 'Content-Disposition: form-data; name="email"'+ CRLF;
        L = L + CRLF;
		L = L + document.fRegister.elements['email'].value+ CRLF;
	//twitter
		L = L + '--' + BOUNDARY+ CRLF;
		L = L + 'Content-Disposition: form-data; name="twitter"'+ CRLF;
		L = L + CRLF;
		L = L + document.fRegister.elements['twitter'].value+ CRLF;
		//mail
		L = L + '--' + BOUNDARY+ CRLF;
		L = L + 'Content-Disposition: form-data; name="user"'+ CRLF;
		L = L + CRLF;
		L = L + document.fRegister.elements['user'].value+ CRLF;
		//notes
		L = L + '--' + BOUNDARY+ CRLF;
        L = L + 'Content-Disposition: form-data; name="pass"'+ CRLF;
        L = L + CRLF;
		L = L + document.fRegister.elements['pass'].value+ CRLF;
                L = L + '--' + BOUNDARY + CRLF;
 	L = L + 'Content-Disposition: form-data; name="idIdioma"'+ CRLF;
	L = L + CRLF;
	L = L + 'ES'+ CRLF;
		L = L + '--' + BOUNDARY;
    	//L = L + CRLF;
		
		oxmlhttp.open("POST",filename,false);
		
		oxmlhttp.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + BOUNDARY);
		
		oxmlhttp.send(L);
	} catch(e) { 
	    return 'Se ha producido un error: '+e.message;
    }
	return oxmlhttp.responseText;
}

//
// captcha
//
function ObtenirQuestion (ObjIdPregunta, ObjPregunta, bEstemSvlt) {
	if (bEstemSvlt) {
		var result = getFile ('../servlet/BlopHome?Funcio=4&idIdioma=ES&rnd='+Math.random()*11);
	} else {
		var result = getFile ('./servlet/BlopHome?Funcio=4&idIdioma=ES&rnd='+Math.random()*11);
	}
	
	var idPregunta = result.substring (0, result.indexOf ("\n")-1);
	var sPregunta = result.substring (result.indexOf ("\n")+1, result.length);
	
	ObjPregunta.innerHTML = sPregunta;
	ObjIdPregunta.value = idPregunta;
}

function ObtenirQuestionUs (ObjIdPregunta, ObjPregunta) {
	var result = getFile ('http://www.blophome.com/servlet/BlopHome?Funcio=4&idIdioma=ES&rnd='+Math.random()*11);
	
	var idPregunta = result.substring (0, result.indexOf ("\n")-1);
	var sPregunta = result.substring (result.indexOf ("\n")+1, result.length);
	
	ObjPregunta.innerHTML = sPregunta;
	ObjIdPregunta.value = idPregunta;
}

function ComprovarQuestion (IdPregunta, Resposta, bEstemSvlt) {
	if (bEstemSvlt) {
		return getFile ('../servlet/BlopHome?Funcio=5&idIdioma=ES&id='+IdPregunta+'&r='+Resposta+'&rnd='+Math.random()*11);
	} else {
		return getFile ('./servlet/BlopHome?Funcio=5&idIdioma=ES&id='+IdPregunta+'&r='+Resposta+'&rnd='+Math.random()*11);
	}
}

// ==================
// md5
// ==================
/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */ 

function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}
function getDocHeight(doc)
{
  var docHt = 0, sh, oh;
  if (doc.height)
  {
    docHt = doc.height;
  }
  else if (doc.body)
  {
    if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
    if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
    if (sh && oh) docHt = Math.max(sh, oh);
  }
  return docHt;
}


function resizeIframe(){

	var iframeWin = window.frames['idFrameBlog'];
  	var iframeEl = window.document.getElementById? window.document.getElementById('idFrameBlog'): document.all? document.all['idFrameBlog']: null;
  	if ( iframeEl && iframeWin )
 	{
    		var docHt = getDocHeight(iframeWin.document);
		if (docHt > 10) {
	    		if (docHt != iframeEl.style.height) iframeEl.style.height = docHt + 'px';
		} else {
   			iframeEl.style.height = '5000px';
		}
  	}	
  	else
  	{ // FireFox
    		var docHt = window.document.getElementById('idFrameBlog').contentDocument.body.offsetHeight;
//    		var docHt = getDocHeight(iframeWin.document);
//alert (docHt);
		if (docHt > 10) {
   			window.document.getElementById('idFrameBlog').style.height = docHt + 'px';
		} else {
   			window.document.getElementById('idFrameBlog').style.height = '5000px';
		}
  	}

}

