// JavaScript Document
function ir(pPagina)
{
	document.location = pPagina;
}

function borrarListBox(lista)
{
	for (i = lista.options.length;i > 0;i--)
		 lista.options[0] = null;
}

function anadirOpt(lista, nombre, valor, estado)
{
	var optionName = new Option(nombre,valor,estado,estado)
  var length = lista.options.length;
  lista.options[length] = optionName;
}

function quitarOpt(lista, id)
{
	lista.options[id] = null;
}

function mover(pCampo,pDireccion)
{
	var campo = eval(pCampo);
	var pos=campo.selectedIndex;
	if(pos<0) return false;
	if ((pos==0) && (pDireccion==-1)) return false;
	if ((pos==campo.options.length-1) && (pDireccion==1)) return false;
	var valor = campo.options[pos].value;
	var texto = campo.options[pos].text;
	campo.options[pos].value = campo.options[pos+pDireccion].value;
	campo.options[pos].text = campo.options[pos+pDireccion].text;
	campo.options[pos+pDireccion].value = valor;
	campo.options[pos+pDireccion].text = texto;
	campo.selectedIndex = pos+pDireccion;
}	

function anadirItem(pCampoOrigen,pLista)
{
	var campo = eval(pCampoOrigen);
	var lista = eval(pLista);
	var pos = campo.selectedIndex;
	if(pos < 0) pos = 0;
	var valor = campo.options[pos].value;
	var nombre = campo.options[pos].text;
	
	//miramos si el valor ya esta en la lista
	var encontrado = false;
	var i;
	for(i=0;((!encontrado) && (i<lista.options.length));i++)
	{
		encontrado = (lista.options[i].value == valor)
	}
	if(!encontrado)
		anadirOpt(lista, nombre, valor, false)
}

function eliminarItem(pLista)
{
	var lista = eval(pLista);
	var pos = lista.selectedIndex;
	if(pos<0) return;
	quitarOpt(lista,pos)
}

function obtenerItems(pLista,pSeparador)
{
	var res = "";
	var lista = eval(pLista);
	var i;
	for(i=0;i<lista.options.length;i++)
	{
		if(res!="") res += pSeparador;
		res += lista.options[i].value;
	}
	return res;
}

//nombreForm: nom del formulari
//nombreCampo: nom del camp
//txtCampo: text del camp (el text que es mostra en cas d'error)
//tipo: T:text, D:fecha, CK: checkboxs; F:Fichero imagen; 
//opciones: R:Obligatori
//return: true:form ok; false: form ko
function validarForm() 
{ 
	var resultat;
	var args = validarForm.arguments;
	var obligatori=false
	if (((args.length-1) % 4)!=0) resultat = false;
	else
	{
		var i=1;
		var error = "";
		var val;
		var obj = "";
		while(i<args.length)
		{
			var obligatori = (args[i+3].indexOf('R')!=-1);			

			if ((args[i+2] != "S")&&(args[i+2] != "D")&&(args[i+2] != "CB"))
				val = eval('document.' + args[0] + '.' + args[i] + '.value');
			res = 0;
			if ((args[i+2] == "T") && obligatori) error += comprovarText(val,args[i+1]);
			if ((args[i+2] == "AR") && obligatori) error += comprovarArticulo(val,args[i+1]);
			if (args[i+2] == "CK") error += comprovarCheck(args[0],args[i], txtCheck);
			if (args[i+2] == "F") error += comprovarExtension(args[0],args[i],args[i],args[i+1],obligatori);
			if (args[i+2] == "N") error += comprovarNumero(val,args[i+1],obligatori);
			if (args[i+2] == "E") error += comprovarEmail(val,args[i+1],obligatori);
			if (args[i+2] == "D") error += comprovarFecha(args[0],args[i],args[i+1],args[i+3]);
			if (args[i+2] == "S") error += comprovarSelect(args[0],args[i],args[i+1],args[i+3]);
			if (args[i+2] == "CB") error += comprovarCheckBox(args[0], args[i],args[i+1]);
			
			i=i+4;
		}
		if(error!="")
		{
		 alert(textoInicioFrase
			+ error
			+ textoFinalFrase);
		}
		resultat = (error=="");
	}
	return resultat;
}

function comprovarNumero(pNumero,ptextoCampo, pObligatori)
{
	var error="";
	if ((pNumero == "") && pObligatori) return(textoObligatorio.replace("#nombre#", ptextoCampo));
	if (pNumero != "")
	{
		if (isNaN(pNumero)) return(textoIncorrecto.replace("#nombre#", ptextoCampo));	
	}
	return error;
}

function comprovarText(pText, ptextoCampo)
{
	if (pText == "")  return(textoObligatorio.replace("#nombre#", ptextoCampo));
	else	return "";
}
function comprovarArticulo(pText, ptextoCampo)
{
	if (pText == "")  return(txtArticulo);
	else	return "";
}

function comprovarExtension(pForm, pCampo, pCampoFichero, ptextoCampo, pObligatori)
{
	var error="";
	fichero = eval("document."+pForm+"."+pCampo+".value");
	ficheroOld = eval("document."+pForm+"."+pCampo+"_old.value");
	if ((fichero == "") && (ficheroOld == "") && pObligatori) 
		return(textoObligatorio.replace("#nombre#",ptextoCampo));

	if (fichero != "")
	{
		var fAux = fichero.toLowerCase();
		var pos= fAux.lastIndexOf (".jpg");
		if(pos!=fAux.length-4)
		{
			var pos= fAux.lastIndexOf (".jpeg");
			if(pos!=fAux.length-5)
				return(txtFichero);	
		}
	}
	return error;
}

function comprovarSelect(pNomForm,pNomCamp,ptextoCampo,pValorDef)
{
 	var campo = eval('document.' + pNomForm + '.' + pNomCamp);
 	var pos = campo.selectedIndex;
 	if(pos<0) 
 	{
 		return (textoObligatorio.replace("#nombre#", ptextoCampo));
 	}
 	if(campo.options[pos].value==pValorDef)
 	{
 		return (textoObligatorio.replace("#nombre#", ptextoCampo));
 	}
	else
	 return "";
}

function comprovarEmail(pEmail, ptextoCampo, pObligatori)
{
	var error = "";
	if ((pEmail =="") && (pObligatori))
		return(textoObligatorio.replace("#nombre#", ptextoCampo));
	if (pEmail !="")
	{ 
  var arroba = pEmail.indexOf('@');
  var punt = pEmail.indexOf('.',arroba);
  if ((arroba<1) || (punt<1) || (arroba==(pEmail.length-1)) || (punt==(pEmail.length-1)) || (punt<arroba))
		return(textoIncorrecto.replace("#nombre#", ptextoCampo));	
	}	
	return error;
}

function comprovarFecha(pNomForm, pCampo, ptextoCampo, pObligatorio)
{
	var campo = eval('document.' + pNomForm + '.' + pCampo);

	if((pObligatorio.indexOf('R')!=-1)&& (campo.value==""))
		return (textoObligatorio.replace("#nombre#", ptextoCampo));

	if(campo.value!="")
	{
		var arrayFecha = campo.value.split("/");
		var textocampos = ptextoCampo;
	
		if(((pObligatorio.indexOf('R')!=-1)&&arrayFecha.length!=3))
			return (textoIncorrecto.replace("#nombre#", ptextoCampo));
		if(arrayFecha.length!=3)
			return (textoIncorrecto.replace("#nombre#", ptextoCampo));
		var campoDia = arrayFecha[0];
		var campoMes = arrayFecha[1];
		var campoAnyo = arrayFecha[2];

		if(campoDia.length!=2) return (textoIncorrecto.replace("#nombre#", ptextoCampo));
		if(campoMes.length!=2) return (textoIncorrecto.replace("#nombre#", ptextoCampo));
		if(campoAnyo.length!=4) return (textoIncorrecto.replace("#nombre#", ptextoCampo));
		var dia = -1;
		if(campoDia.charAt(0)=="0") campoDia = campoDia.charAt(1);
		if(isNaN(campoDia)) return (textoIncorrecto.replace("#nombre#", ptextoCampo));
		else dia = parseInt(campoDia);

		if(campoMes.charAt(0)=="0") campoMes = campoMes.charAt(1);
		if(isNaN(campoMes)) return (textoIncorrecto.replace("#nombre#", ptextoCampo));
		else mes = parseInt(campoMes)-1;

		if(isNaN(campoAnyo)) return (textoIncorrecto.replace("#nombre#", ptextoCampo));
		else anyo = parseInt(campoAnyo);
		
		var numDias = diasMes(mes, anyo)
		if(dia>numDias)
		 return (textoIncorrecto.replace("#nombre#", ptextoCampo));
	}
	return "";
}

function esBisiesto(pAnyo) { 
return (((pAnyo % 4 == 0) && (pAnyo % 100 != 0)) || (pAnyo % 400 == 0)) ? 1 : 0;
}

function diasMes(pMes, pAnyo)
{
	if (pMes==1)
	{
	 if (!esBisiesto(pAnyo)) return 28;
	 else return 29;
	}
	else
	{
		if ((pMes==0) || (pMes==2) || (pMes==4) || (pMes==6) || (pMes==7) || (pMes==9) || (pMes==11)) return 31
		else return 30;
	}
}


function comprovarCheckBox(pNomForm, pNomCamp, ptextoCampo)
{
	var campo = eval('document.' + pNomForm + '.' + pNomCamp);
	if(campo.checked==false)
 	 return (textoObligatorio.replace("#nombre#", ptextoCampo))
	else
	 return "";
}

// Funcions per Panell

function ordenar(campoOrden, orden, tipo, tipusProd, Url)
{
	/*
	campoOrden: És el camp per el quan volem fer la ordenació.
	orden: Tipus d'ordenació (ASC o DESC).
	tipo: Tipus de llistat en el que estem.
	tipusProd: Tipus de producte.
	Url: Url del llistat que volem ordenar.
	*/
	document.fLlistat.tipo.value=tipo;
	document.fLlistat.tipusProd.value=tipusProd;
	document.fLlistat.orden.value=orden;
	document.fLlistat.campoOrden.value=campoOrden;
	document.fLlistat.action="" + Url + "";
	document.fLlistat.submit();
//	window.location.href="" + Url + "?tipo=" + tipo + "&tipusProd=" + tipusProd + "&orden=" + orden + "&campoOrden=" + campoOrden + ""
}

function ordenar_Imatges(campoOrden_Imatges, orden_Imatges, tipo, tipusProd, Url)
{
	/*
	campoOrden: És el camp per el quan volem fer la ordenació.
	orden: Tipus d'ordenació (ASC o DESC).
	tipo: Tipus de llistat en el que estem.
	tipusProd: Tipus de producte.
	Url: Url del llistat que volem ordenar.
	*/
	document.fLlistat.tipo.value=tipo;
	document.fLlistat.tipusProd.value=tipusProd;
	document.fLlistat.orden_Imatges.value=orden_Imatges;
	document.fLlistat.campoOrden_Imatges.value=campoOrden_Imatges;
	document.fLlistat.action="" + Url + "";
	document.fLlistat.submit();
//	window.location.href="" + Url + "?tipo=" + tipo + "&tipusProd=" + tipusProd + "&orden=" + orden + "&campoOrden=" + campoOrden + ""
}

function ordenar_Arxius(campoOrden_Arxius, orden_Arxius, tipo, tipusProd, Url)
{
	/*
	campoOrden: És el camp per el quan volem fer la ordenació.
	orden: Tipus d'ordenació (ASC o DESC).
	tipo: Tipus de llistat en el que estem.
	tipusProd: Tipus de producte.
	Url: Url del llistat que volem ordenar.
	*/
	document.fLlistat.tipo.value=tipo;
	document.fLlistat.tipusProd.value=tipusProd;
	document.fLlistat.orden_Arxius.value=orden_Arxius;
	document.fLlistat.campoOrden_Arxius.value=campoOrden_Arxius;
	document.fLlistat.action="" + Url + "";
	document.fLlistat.submit();
//	window.location.href="" + Url + "?tipo=" + tipo + "&tipusProd=" + tipusProd + "&orden=" + orden + "&campoOrden=" + campoOrden + ""
}

//function modificar(pId, pTipo)
function modificar(pId)
{
	document.fLlistat.id.value=pId;
	document.fLlistat.submit();
}

function eliminar_Imatge(pId, Url)
{
	if(confirm("Esta segur que desitja esborrar el registre seleccionat?"))
	{
		document.fLlistat.id_ImatgeEsborrar.value=pId;
		document.fLlistat.action="" + Url + "";
		document.fLlistat.submit();
	}
}

function eliminar_Arxiu(pId, Url)
{
	if(confirm("Esta segur que desitja esborrar el registre seleccionat?"))
	{
		document.fLlistat.id_ArxiuEsborrar.value=pId;
		document.fLlistat.action="" + Url + "";
		document.fLlistat.submit();
	}
}

function eliminar(pId, Url)
{
	if(confirm("Esta segur que desitja esborrar el registre seleccionat?"))
	{
		document.fLlistat.id.value=pId;
		document.fLlistat.action="" + Url + "";
		document.fLlistat.submit();
	}
}

function arxius(pId, Tipo, Url)
{
	document.fLlistat.id.value=pId;
	document.fLlistat.tipo.value=Tipo;
	document.fLlistat.action="" + Url + "";
	document.fLlistat.submit();
}

function tornar(Url, Tipo)
{
	if( Tipo == "Llistat"){
		document.fLlistat.id.value="-1";
		document.fLlistat.action="" + Url + "";
		document.fLlistat.submit();
	}
	if( Tipo == "Editar"){
		document.fEditar.id.value="-1";
		document.fEditar.action="" + Url + "";
		document.fEditar.submit();
	}
}

function obrirFinestra(url,param){
   window.open(url,"windows",param)
}

function seleccioTipusProd(tipusProd,tipo,Url)
{
	window.location.href="" + Url + "?tipusProd=" + tipusProd + "&tipo=" + tipo + "";
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}

function nuevoAjax() 
{ 
        var xmlhttp=false; 
        try 
        { 
                // Creacion del objeto AJAX para navegadores no IE 
                xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
        } 
        catch(e) 
        { 
                try 
                { 
                        // Creacion del objet AJAX para IE 
                        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
                } 
                catch(E) 
                { 
                        if (!xmlhttp && typeof XMLHttpRequest!="undefined") xmlhttp=new XMLHttpRequest(); 
                } 
        } 
        return xmlhttp; 
} 

function destacar(id)
{ 
		ajax=nuevoAjax();

		ajax.open("GET", "prod_destacar.php?id=" + id + "", true);
        ajax.onreadystatechange=function() 
        { 
                if (ajax.readyState==4) 
                { 
                        //alert("Datos guardados");
                } 
        } 
        ajax.send(null);

}

function ventanaSecundaria(URL,PARAM3){
   window.open(URL,"PopUp",PARAM3)
}

function volver()
{
	history.back();
}