/**
 * Ensenya una capa o l'amaga (errors)
 **/
function toggle(id) {
    var element = document.getElementById(id);
    with (element.style) {
        if ( display == "none" ){
            display = ""
        } else{
            display = "none"
        }
    }
    var text = document.getElementById(id + "-switch").firstChild;
    if (text.nodeValue == "[show]") {
        text.nodeValue = "[hide]";
    } else {
        text.nodeValue = "[show]";
    }
}



/** Funcions per fer el swap d'imatges */

var articles = "";
var and = "";

function MM_preloadImages() { //v3.0
  var d = document; 
  if (d.images) { 
  	
  	if (!d.MM_p) d.MM_p=new Array();
    
    var i, j=d.MM_p.length, a = MM_preloadImages.arguments; 
    for(i=0; i<a.length; i++)
    	if (a[i].indexOf("#")!=0) { 
    		d.MM_p[j] = new Image; 
    		d.MM_p[j++].src = a[i];
    	}
  }
}

function MM_swapImgRestore() { //v3.0
  var i,x,a = document.MM_sr; 
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) 
  x.src = x.oSrc;
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function submitFitxa() {
	document.atribs.method = "post";
	document.atribs.action = "carret.form";
	document.atribs.submit();
}

function submitPetInformacioDisp() {
	document.atribs.method = "post";
	document.atribs.action = "petInformacioDisp.form";
	document.atribs.submit();
}

function openPopup(url, width, height) {
	window.open(url, "popup", "status=no,directories=no,toolbars=no,scrollbars=yes,width="+width+", height="+height+", menuBar=no");
}

function openPopup(url, nom, width, height) {
	window.open(url, nom, "status=no,directories=no,toolbars=no,scrollbars=yes,width="+width+", height="+height+", menuBar=no");
}
function openContingut(url, width, height) {
	window.open(url, "contingut", "status=no,directories=no,toolbars=no,scrollbars=yes,width="+width+", height="+height+", menuBar=no");
}

function openComparativa(article, url, width, height) {
	if(article == "0"){
		window.opener.articles = "";
		window.opener.and = "";
	}else if(article == ""){
	        url = url + "?entitat=";
	}
	else {
		//document.comparativa.articles.value = document.comparativa.articles.value + and + article;
		//articles = articles + and + article;
		//and = "$";
		url = url + "&entitat=" + article;
	}
	window.open(url, "comparativa", "status=yes,directories=no,toolbars=yes,scrollbars=yes,width="+width+", height="+height+", menuBar=no");
}
function delComparativa(article, url, width, height) {
	window.open(url, "comparativa", "status=yes,directories=no,toolbars=yes,scrollbars=yes,width="+width+", height="+height+", menuBar=no");
		
}

function categoria(categoria, nom) {
  opener.wizard.categid.value=categoria;
  opener.wizard.categoria.value=nom;
  self.close();
}

// Canvia l'valor d'una url i fa el salt
function canviToken(token, valor, url) {
	// Variables
	var urlfinal = new String();

	// Separem la part de parýtres de la url principal
	var index = url.indexOf('?');
	
	if (index==-1) {
		// No te parýtres, construàla url final
		urlfinal = url + "?" + token + "=" + valor;

	} else {
		// Si que te variables a la url
		// Mirem si te la variable valor
		if (url.substr(0,index).length==url.length+1) {
			// Nom`t¿, construàla url final
			urlfinal = url + token + "=" + valor;
		} else {
			// Hi ha coses despr`de l'interrogant
			var trobat = false;
			// .dex dintre de stranýsi
			var subindex = 0;
			// La url a la qual ens anirem, li posem l'interrogant
			urlfinal = url.substr(0, index) + "?";
			// url que anem a analitzar (parýtres)
			var stranalisi = url.substr(index+1, url.length);
			// Trossets que anirem agafant (diferents parýtres)
			var strtmp = new String();

			while ((subindex!=-1)&&(stranalisi.length!=0)) {
				subindex = stranalisi.indexOf('&');
				if (subindex!=-1) {
					// Hi han m`variables
					strtmp = stranalisi.substr(0, subindex);

					// Escur- l'anýsi
					if (stranalisi.substr(0,subindex).length==stranalisi.length+1) {stranalisi = "";}
					else {stranalisi = stranalisi.substr(subindex+1, stranalisi.length);}

					// Veiem si el que hem agafat `la variable valor
					if (strtmp.substr(0, strtmp.indexOf('=')) == token) {
						// L'hem trobada per>o l'afegim
						trobat=true;
					} else {
						urlfinal+=strtmp;
					}

				} else {
					// Mirem si estý la ýa part, nom`te una variable?
					if (stranalisi.substr(0, stranalisi.indexOf('=')) == token) {
						// L'hem trobada per>o l'afegim
						trobat = true;
					} else {
						urlfinal+=stranalisi;
					}
				}
				
				if (!trobat) urlfinal+="&";
				else trobat = false;
			}
		}
		urlfinal+=token+"="+valor;
	}
	
	return urlfinal;
}


function preuArticle(idioma, preu, pvp, pvpo, tpcrebaixa, tpcdescompte, comp) {
	
	//alert("idioma: #"+idioma+"#");
	//alert("preu: #"+preu+"#");
	//alert("pvp: #"+pvp+"#");
	//alert("pvpo: #"+pvpo+"#");
	//alert("tpcrebaixa: #"+tpcrebaixa+"#");
	//alert("tpcdescompte: #"+tpcdescompte+"#");
	//alert("comprable: #"+comp+"#");
	
	// Internacionalització per diferents idiomes
	var spvp = new Array();
	var soferta = new Array();
	var srebaixa = new Array();
	var sdescompte = new Array();
	var saconsultar = new Array();
	
	spvp[1] = "PVP";
	spvp[2] = "PVP";
	spvp[3] = "PVP";
	spvp[4] = "PVP";
	spvp[5] = "PVP";
	
	soferta[1] = "OFERTA";
	soferta[2] = "OFERTA";
	soferta[3] = "ON OFFER";
	soferta[4] = "ON OFFER";
	soferta[5] = "ON OFFER";

	srebaixa[1] = "rebaja";
	srebaixa[2] = "rebaixa";
	srebaixa[3] = "discount";
	srebaixa[4] = "discount";
	srebaixa[5] = "discount";

	sdescompte[1] = "dto. cliente";
	sdescompte[2] = "dte. client";
	sdescompte[3] = "client discount";
	sdescompte[4] = "client discount";
	sdescompte[5] = "client discount";

	saconsultar[1] = "A consultar";
	saconsultar[2] = "A consultar";
	saconsultar[3] = "To ask";
	saconsultar[4] = "To ask";
	saconsultar[5] = "To ask";

	// String per mostrar per pantalla
	var strFinal = "";
	
	if (comp==1) {
		// Construïm l'string
		if (pvpo!='0,00') {
			// Hi ha oferta
			strFinal = '<span class="contingutFinestra">'+spvp[idioma]+': <s>'+pvp+' &euro;</s><br/>';
			strFinal+= '<font color="CC3333"><b>'+soferta[idioma]+": "+pvpo+" &euro;</b></font></span>";
		} else {
			if (tpcrebaixa!='0,00') {
				// Hi ha % rebaixa
				strFinal = '<span class="contingutFinestra">'+spvp[idioma]+': <s>'+pvp+' &euro;</s><br/>';
				strFinal+= '<font color="CC3333"><b>-'+tpcrebaixa+"% "+srebaixa[idioma]+" = "+preu+" &euro;</b></font></span>";
			} else {
				if (tpcdescompte!='0,00') {
					// Hi ha descompte de client
					strFinal = '<span class="contingutFinestra">'+spvp[idioma]+': <s>'+pvp+' &euro;</s><br/>';
					strFinal+= '<font color="CC3333"><b>-'+tpcdescompte+"% "+sdescompte[idioma]+" = "+preu+" &euro;</b></font></span>";
				} else {
					// És preu normal
					strFinal = '<span class="contingutFinestra">'+spvp[idioma]+': '+pvp+' &euro;</span><br/>';
				}
				
			}
		}
	} else {
		// Posem que no es pot comprar
		strFinal = '<span class="contingutFinestra"><i>'+spvp[idioma]+': '+saconsultar[idioma]+'</i></span>';
	}
	
	return strFinal;
}

function submitBuscar(strIdioma) {
	
	var strMiss1Buscador = new Array;
	var strMiss2Buscador = new Array;
	var items = new Array;
	var idioma = 1;
	if (strIdioma == 'es') {
		idioma = 1;
	} else if (strIdioma == 'ca') {
		idioma = 2;
	} else if (strIdioma == 'en') {
		idioma = 3;
	}
	
	strMiss1Buscador[0] = "Debe de haber algún string de búsqueda y un ámbito de búsqueda obligatorio.";
	strMiss1Buscador[1] = "Ha d'haber algún string de cerca i un àmbit de cerca obligatori.";
	strMiss1Buscador[2] = "not defined";
	strMiss1Buscador[3] = "not defined";
	strMiss1Buscador[4] = "not defined";
	
	strMiss2Buscador[0] = "Los elementos de búsqueda han de tener más de 3 letras.";
	strMiss2Buscador[1] = "Els elements de cerca han de tenir més de 3 lletres.";
	strMiss2Buscador[2] = "not defined";
	strMiss2Buscador[3] = "not defined";
	strMiss2Buscador[4] = "not defined";

	// Troceamos la cadena de búsqueda para elementos mayores a 3 letras
	var index = 0;
	var subcadena = document.seccio.strCerca.value+" ", elem = "";
	do {
		index = subcadena.indexOf(" ");
		elem = (index!=-1)? subcadena.substr(0, index): "";
		subcadena = (index!=-1)? subcadena.substr(index+1, subcadena.length): "";
		
		if (elem.length>3) items[items.length] = elem;
		
	} while (index!=-1);
	
	
	// Hacemos la evaluación
	if ((document.seccio.strCerca.value=="")||((document.seccio.isNomBuscador.checked==false)&&(document.seccio.isDescripcioBuscador.checked==false)&&(document.seccio.isNomMarcaBuscador.checked==false)&&(document.seccio.isNomCategoriaBuscador.checked==false))) {
		alert(strMiss1Buscador[idioma-1]);
	} else {
		if (items.length!=0) {
			document.seccio.action="gamabuscar-page.html";
			document.seccio.submit();
		} else {
			alert(strMiss2Buscador[idioma-1]);
		}
	}
}

function submitEinaBuscar(strIdioma) {
	var strMiss1Buscador = new Array;
	var strMiss2Buscador = new Array;
	var items = new Array;
	var saux = "gamabuscar-page.html";
	
	var idioma = 1;
	if (strIdioma == 'es') {
		idioma = 1;
	} else if (strIdioma == 'ca') {
		idioma = 2;
	} else if (strIdioma == 'en') {
		idioma = 3;
	}
	
	strMiss1Buscador[0] = "Debe de haber algún string de búsqueda.";
	strMiss1Buscador[1] = "Ha d'haber algún string de cerca.";
	strMiss1Buscador[2] = "not defined";
	strMiss1Buscador[3] = "not defined";
	strMiss1Buscador[4] = "not defined";
	
	strMiss2Buscador[0] = "Los elementos de búsqueda han de tener más de 3 letras.";
	strMiss2Buscador[1] = "Els elements de cerca han de tenir més de 3 lletres.";
	strMiss2Buscador[2] = "not defined";
	strMiss2Buscador[3] = "not defined";
	strMiss2Buscador[4] = "not defined";

	// Troceamos la cadena de búsqueda para elementos mayores a 3 letras
	var index = 0;
	var subcadena = document.eina.search.value+" ", elem = "";
	do {
		index = subcadena.indexOf(" ");
		elem = (index!=-1)? subcadena.substr(0, index): "";
		subcadena = (index!=-1)? subcadena.substr(index+1, subcadena.length): "";
		
		if (elem.length>3) items[items.length] = elem;
		
	} while (index!=-1);
	
	// Hacemos la evaluación
	if (document.eina.search.value=="") {
		alert(strMiss1Buscador[idioma-1]);
	} else {
		if (items.length!=0) {
			saux = canviToken("strCerca", document.eina.search.value, saux);
			saux = canviToken("isNomBuscador", "1", saux);
			saux = canviToken("isDescripcioBuscador", "1", saux);
			saux = canviToken("isNomCategoriaBuscador", "1", saux);
			saux = canviToken("isNomMarcaBuscador", "1", saux);
			saux = canviToken("esportBuscador", "-1", saux);
			saux = canviToken("marcaBuscador", "-1", saux);
			
			parent.location.href=saux;
		} else {
			alert(strMiss2Buscador[idioma-1]);
		}
	}
}

function submitLogin() {
	document.seccio.action = "/miviladomat/default.xml";
	document.seccio.method = "post";
	document.seccio.submit();
}
function emailCheck (emailStr) {
/* 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("Dirección Email incorrecta (chequear @ y .)")
 return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid
if (user.match(userPat)==null) {
    // user is not valid
    //alert("Usuario no valido.")
    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("Dirección IP destino no valida!")
  return false
     }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
 alert("Nombre de dominio no valido.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   //alert("La dirección debe acabar en dos (país) o tres letras.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="Esta dirección de correo electrónico no es valida !"
   //alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}



function formatnumbers(pnumber,decimals) 
{
  var strNumber = new String(pnumber);
  var arrParts = strNumber.split('.');
  var intWholePart = parseInt(arrParts[0],10);
  var strResult = '';
  if (isNaN(intWholePart))
    intWholePart = '0';
  if(arrParts.length > 1)
  {
    var decDecimalPart = new String(arrParts[1]);
    var i = 0;
    var intZeroCount = 0;
     while ( i < String(arrParts[1]).length )
     {
       if( parseInt(String(arrParts[1]).charAt(i),10) == 0 )
       {
         intZeroCount += 1;
         i += 1;
       }
       else
         break;
    }
    decDecimalPart = parseInt(decDecimalPart,10)/Math.pow(10,parseInt(decDecimalPart.length-decimals-1)); 
    Math.round(decDecimalPart); 
    decDecimalPart = parseInt(decDecimalPart)/10; 
    decDecimalPart = Math.round(decDecimalPart); 

    //If the number was rounded up from 9 to 10, and it was for 1 'decimal' 
    //then we need to add 1 to the 'intWholePart' and set the decDecimalPart to 0. 

    if(decDecimalPart==Math.pow(10, parseInt(decimals)))
    { 
      intWholePart+=1; 
      decDecimalPart="0"; 
    } 
    var stringOfZeros = new String('');
    i=0;
    if( decDecimalPart > 0 )
    {
      while( i < intZeroCount)
      {
        stringOfZeros += '0';
        i += 1;
      }
    }
    decDecimalPart = String(intWholePart) + "." + stringOfZeros + String(decDecimalPart); 
    var dot = decDecimalPart.indexOf('.');
    if(dot == -1)
    {
      decDecimalPart += '.'; 
      dot = decDecimalPart.indexOf('.'); 
    } 
    var l=parseInt(dot)+parseInt(decimals); 
    while(decDecimalPart.length <= l) 
    {
      decDecimalPart += '0'; 
    }
    strResult = decDecimalPart;
  }
  else
  {
    var dot; 
    var decDecimalPart = new String(intWholePart); 

    decDecimalPart += '.'; 
    dot = decDecimalPart.indexOf('.'); 
    var l=parseInt(dot)+parseInt(decimals); 
    while(decDecimalPart.length <= l) 
    {
      decDecimalPart += '0'; 
    }
    strResult = decDecimalPart;
  }
  return strResult;
}

function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function anyadirCero(codi) {
  if (codi.length<6)
  {
     while(codi.length<6) {
       codi = "0" + codi;
     }
  }

 return codi;
}

