// Title: Timestamp picker
// Description: See the demo at url
// URL: http://us.geocities.com/tspicker/
// Script featured on: http://javascriptkit.com/script/script2/timestamp.shtml
// Version: 1.0
// Date: 12-05-2001 (mm-dd-yyyy)
// Author: Denis Gritcyuk <denis@softcomplex.com>; <tspicker@yahoo.com>
// Notes: Permission given to use this script in any kind of applications if
//    header lines are left unchanged. Feel free to contact the author
//    for feature requests and/or donations

 var ERR = new Array();
 ERR[1]="Camp obligatori";
 ERR[2]="Aquest camp ha de ser numèric";
 ERR[3]="No hi pot haver més d'un punt";
 ERR[4]="El camp pot tenir com a m?xim";
 ERR[5]=" decimals";
 ERR[6]="Hi ha caràcters no vàlids :";
 ERR[7]="  | # { } ( ) - + ~ ";
 ERR[8]="Camp incorrecte";
 ERR[9]="Dia incorrecte";
 ERR[10]="Mes incorrecte";
 ERR[11]="Camp incorrecte. Format AAAAMM o AAMM";
 ERR[12]="Camp incorrecte. Format AAAA o AA";
 ERR[13]="Camp incorrecte. Format HHMM";
 ERR[14]="Hora incorrecte";
 ERR[15]="Minut incorrecte";
 ERR[16]="Cal posar valor a ";
 ERR[17]="El valor no pot ser inferior a ";
 ERR[18]="El valor no pot ser superior a ";
 ERR[19]="Primer cal situar-se en el camp de la lupa";
 
// variable que cont? el valor del dia actual 
var avui = new Date();
avui= ""+(((avui.getDate()+"").length==1)?"0"+avui.getDate():avui.getDate())+((((avui.getMonth()+1)+"").length==1)?"0"+(avui.getMonth()+1):(avui.getMonth()+1))+avui.getFullYear();

// funci? que mostra un calendari per tal de poder seleccionar un dia
function calendari(control, data) {
	var mesos = ["Gener", "Febrer", "Mar&ccedil;", "Abril", "Maig", "Juny",
		"Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"];
	var dies = ["dl.", "dt.", "dm.", "dj.", "dv.", "ds.","dg."];
	var color;

	if (data==null || data=="" ||str2dt(data)  )
	{
		var laData = (data == null || data =="" ?  new Date() : str2dt(data));
		var mesAnterior = new Date(laData);
		mesAnterior.setMonth(laData.getMonth()-1);
		var mesSeguent = new Date(laData);
		mesSeguent.setMonth(laData.getMonth()+1);
		var primerDia = new Date(laData);
		primerDia.setDate(1);
		primerDia.setDate(2-primerDia.getDay());
		var ultimDia = new Date(mesSeguent);
		ultimDia.setDate(0);
		
	
		var str_buffer = new String (
			"<html>\n"+
			"<head>\n"+
			"<link rel='stylesheet' href='../css/estils.css' type='text/css'>\n"+
			"	<title>Calendari</title>\n"+
			"</head>\n"+
			"<body>\n"+
//			"<table cellspacing=\"3\" border=\"0\" width=\"100%\">\n"+
//			"<tr><td class=\"calendari\">\n"+
			"<table cellspacing=\"3\" border=\"0\" width=\"100%\" class=\"calendari\">\n"+
			"<tr>\n	<td class=\"dalt\"><a href=\"javascript:window.opener.calendari('"+
			control+"', '"+ dt2dtstr(mesAnterior)+"');\"><img border=\"0\" src=\"../images/fcalleft.gif\">"+
			"</a></td>\n"+
			"	<td  class=\"dalt\" colspan=\"5\">"+mesos[laData.getMonth()]+"&nbsp;"+laData.getFullYear()+"</td>\n"+
			"	<td  class=\"dalt\"><a  href=\"javascript:window.opener.calendari('"
			+control+"', '"+dt2dtstr(mesSeguent)+"');\"><img border=\"0\" src=\"../images/fcalright.gif\">"+
			"</a></td>\n</tr>\n"
		);
	
		var diaActual = new Date(primerDia);
	
		// print weekdays titles
		str_buffer += "<tr>\n";
		for (var n=0; n<7; n++)
			str_buffer += "	<td class=\"ds\">"+			
			dies[n]+
			"</td>\n";
		// print calendar table
		str_buffer += "</tr>\n";
		while (diaActual.getMonth() == laData.getMonth() ||
			diaActual.getMonth() == primerDia.getMonth()) {
			// print row heder
			str_buffer += "<tr>\n";
			for (var n_current_wday=0; n_current_wday<7; n_current_wday++) {
					if (diaActual.getDate() == laData.getDate() &&
						diaActual.getMonth() == laData.getMonth())
						// print current date
						str_buffer += "	<td class=\"avui\" align=\"right\">";
					else if (diaActual.getDay() == 0 || diaActual.getDay() == 6)
						// weekend days
						str_buffer += "	<td class=\"fa\" align=\"right\">";
					else
						// print working days of current month
						str_buffer += "	<td class=\"da\" align=\"right\">";
	
					if (diaActual.getMonth() == laData.getMonth())
					{
						if (diaActual.getDate() == laData.getDate())
							color = "avui";
					
							// print days of current month
						else if (diaActual.getDay() == 0 || diaActual.getDay() == 6)
						
								color="fa";							
						else						 
								color="da";
						str_buffer += "<a class=\""+color+"\" href=\"javascript:window.opener."+control+
						".value='"+dt2dtstr(diaActual)+"'; window.close();\">";
							//"<font color=\""+color+"\" "+
							//"face=\"tahoma, verdana\" size=\"2\""+
							//">";
					}	
					else 
					{
						// print days of other months
						if (diaActual.getDay() == 0 || diaActual.getDay() == 6)
						{
							str_buffer += "<a class=\"af\" href=\"javascript:window.opener."+control+
							".value='"+dt2dtstr(diaActual)+"'; window.close();\">";
						}
						else
						{
							str_buffer += "<a class=\"ad\" href=\"javascript:window.opener."+control+
							".value='"+dt2dtstr(diaActual)+"'; window.close();\">";
						}
					}
					str_buffer += diaActual.getDate()+
							"</a></td>\n";
					diaActual.setDate(diaActual.getDate()+1);
			}
			// print row footer
			str_buffer += "</tr>\n";
		}
		// print calendar footer
		str_buffer +=
			"</table>\n" +
//			"</tr>\n</td>\n</table>\n" +
			"</body>\n" +
			"</html>\n";
	
		var finestra = window.open("", "Calendar", 
			"width=190,height=160,status=no,resizable=yes,top=200,left=200");
		finestra.opener = self;
		var doc = finestra.document;
		doc.write (str_buffer);
		doc.close();

	}
}

function str2dt (data) {
	var re_date = /^(\d{1,2})\/(\d{1,2})\/(\d{4})\s*$/;
	if (!re_date.exec(data))
		return alert("Format de data inv?lid: "+ data);
	return (new Date (RegExp.$3, RegExp.$2-1, RegExp.$1, RegExp.$4, RegExp.$5, RegExp.$6));
}

function dt2dtstr (valor) {
	
	var pref = 20;    
	var cadena;
	var any;
	
	any = valor.getFullYear(); 
	cadena = 
	(((valor.getDate()+"").length==1)?"0"+valor.getDate():valor.getDate())+"/"+((((valor.getMonth()+1)+"").length==1)?"0"+(valor.getMonth()+1):(valor.getMonth()+1));
    if ((any+"").length==2)
    {
    	if(any>50) pref=19;
    	any=pref+""+any;
    }
	return (cadena+"/"+any);
}

// funci? que comprova si la data ?s correcta
function comprovacioData(control)
{
	var error;
	valorData(control);
	preData(control);
	error = valData(control.value);
	postData(control);

	if (error)
	{
		alert(error);
		return true;
	}
	return false;
}

function piece(str,sep,pos) 
{
	 var n;
	 var subStr;
	 var pf;
	 var pi=0;

	 if(str=='undefined') return '';
	 if(str==undefined) return '';
	 
	 for(n=0;n<pos;n++) 
	 {
	 	pf=str.indexOf(sep,pi);
	  	if(pf==-1) pf=str.length;
	  	subStr=str.substring(pi,pf);
	  	pi=pf+sep.length;
	 }
	 return subStr;
}

// Converteix la data en format dia/mes/any
function postData(control) 
{
	var valor = control.value;

  	if(valor.length==8) 
  	{
    	valor=valor.substring(0,2)+'/'+valor.substring(2,4)+'/'+valor.substring(4,8);
	}
	control.value= valor;
}

// Converteix l'hora en format hh:mm
function postHora(control) 
{
	var valor = control.value;
  	if (valor.length==4) 
  	{
  		valor=valor.substring(0,2)+':'+valor.substring(2,4);
  	}
  	control.value = valor;
//  return Valor
}

// Treu els car?cters "/" de la data
function preData(control) 
{
	var valor = control.value;
	var val;
  	if(valor!='') 
  	{	
    	val=piece(valor,'/',2) ;

    	if(val!='') 
    	{
    		valor=valor.substring(0,2)+valor.substring(3,5)+valor.substring(6,10);
    	}
  	}

  	control.value = valor;
//  return Valor
}

// Treu els car?cters ":" de l'hora
function prevHora(control) 
{
	var valor = control.value;
  	if(valor!='')
  	{
  		valor=valor.substring(0,2)+valor.substring(3,5);
  	}
  	control.value = valor;
//  return Valor
}

// Valida que la data sigui correcta
function valData(valor) 
{
	var error;

	if(valor=='') return false;
	caractersValids='0123456789';
	for(i=0;i<valor.length;i++)
	{
		caracter=valor.charAt(i);
	    if(caractersValids.indexOf(caracter,0)==-1)
	    {
	      error=ERR[8];
	      return error
	    }
	}
  	if(valor.length==3||valor.length==5) 
  	{
    	Error=ERR[9];
      	return Error
  	}
  	dia=valor.substring(0,2);
  	mes=valor.substring(2,4);
  	any=valor.substring(4,8);
  	if(any.length==1||any.length==3) 
  	{
    	error=ERR[9];
      	return error
  	}
  	if(dia>31||dia<1)
  	{
    	error=ERR[9];
    	return error
  	}
	if(mes>12||mes<1)
	{
    	error=ERR[10];
    	return error
  	}
  	if(dia>30)
  	{
    	if(mes==4||mes==6||mes==9||mes==11)
    	{
      		error=ERR[9];
      		return error
    	}
  	}
  	if(mes==2)
  	{
    	diasFeb=28;
    	bisiesto=any%4;
    	if(bisiesto==0) diasFeb=29;
    	if(dia>diasFeb)
    	{
	    	error=ERR[9];
      		return error
    	}
  	}
  	return false
}

function valPeriode(valor) 
{
  if(valor=='') return false;
  caractersValids='0123456789';
  for(i=0;i<valor.length;i++)
  {
    caracter=valor.charAt(i);
    if(caractersValids.indexOf(caracter,0)==-1)
    {
      error=ERR[11];
      return error
    }
  }
  mes=valor.substring(4,6);
  if(mes>12||mes<1)
  {
    error=ERR[10];
    return error
  }
  return false
}

function valAny(valor) 
{
  if(valor=='') return false;
  if(valor.length!=2 && valor.length!=4)
  {	error = ERR[12];
  	return error;
  }
  caractersValids='0123456789';
  for(i=0;i<valor.length;i++){
    caracter = valor.charAt(i);
    if(caractersValids.indexOf(caracter,0)==-1){
      error=ERR[12];
      return error
    }
  }
  return false
}

function valHora(valor) 
{
  if(valor=='') return false;
  caractersValids='0123456789:';
  if(valor.length>5) return ERR[13];
  for(i=0;i<valor.length;i++){
    caracter = valor.charAt(i);
    if(caractersValids.indexOf(caracter,0)==-1)
    {
      error=ERR[13];
      return error
    }
  }
  hora=valor.substring(0,2);
  minut=valor.substring(3,5);
  if(hora>23) {
    error=ERR[14];
    return error
  }
  if(minut>59) {
    error=ERR[15];
    return error
  }
  return false
}
function valorData(control) 
{
	var pref;
	var valor= control.value;
	if(valor.length==1) valor='0'+valor+avui.substring(2,8);
  	if(valor.length==2||valor.length==4) valor=valor+avui.substring(valor.length,8);
  	if(valor.length==6) 
  	{
    	pref=20;
    	if(valor.substring(4,6)>50) pref=19;
    	valor=valor.substring(0,4)+pref+valor.substring(4,6);
  	}
  	if(valor.length==10) valor=valor.substring(0,2)+valor.substring(3,5)+valor.substring(6,10);
  	control.value = valor;
  //return Valor
}
function valorPeriode(valor) 
{
	var pref;
  	if(valor.length==2) valor=avui.substring(4,8)+valor;
  	if(valor.length==4) 
  	{
    	pref=20;
    	if(valor.substring(0,2)>50) pref=19;
    	valor=pref+valor;
  	}
  	return valor
}

function valorAny(valor) 
{
	var pref;
  	if(valor.length==2) 
  	{
    	pref=20;
    	if(valor>50) pref=19;
    	valor=pref+valor;
  }
  return valor
}

function valorHora(valor) 
{
  if(valor.length==1) valor='0'+valor+'00';
  if(valor.length==2) valor=valor+'00';
  if(valor.length==3) valor=valor.substring(0,2)+'0'+valor.substring(2,3);
  return valor
}

function ferOnLoad(formulari, accio)
{
	activarBotons();
	if (accio!=null && accio!="")
	{
		eval(accio+"()");
	}		
}


function campObligatori(control, nomCamp)
{
	if (control==null || control.value=="")
	{
		alert("El camp "+nomCamp+" no pot estar buit");
		control.focus();
	}
}

function finestraLupa(url)
{
	var finestra = window.open(url, "Buscar", 
			"width=800,height=500,status=no,resizable=yes,top=150,left=200");
	finestra.focus();			
}

function sortirLupa()
{
	alert('Sortir')
}

function ValDec(Valor,Dec) {
  if (Valor.indexOf('.',0)!=-1) {
    NDec=Valor.length-(Valor.indexOf('.',0)+1);
    NDec=Number(NDec);
    Dec=Number(Dec);
    if (NDec>Dec){
      Error=ERR[4]+' '+Dec+ERR[5];
      return Error
    }
    return false
  }
  return false
}

function ValNum(Valor) {
  CaractersValids='0123456789.-';
  for (i=0;i<Valor.length;i++){
    Caracter=Valor.charAt(i);
    if (CaractersValids.indexOf(Caracter,0)==-1){
      Error=ERR[2];
      return Error
    }
  }
  if (Valor.indexOf('.',0)!=Valor.lastIndexOf('.')){
    Error=ERR[3];
    return Error
  }
  return false
}


function comprovarNumeric(valor)
{
	var error;
	
	error = ValNum(valor);
	if (error)
	{
		alert(error)
	}
	return false;
}

function esNumeric(valor)
{
	var error;
	
	error = ValNum(valor);
	if (error)
	{
		alert(error)
		return false;
	}
	
	return true;
}

function validarEnter(valor){
	for ( i = 0; i < valor.length; i++ ) {
		valorInt = parseInt(valor.charAt(i));
		if (isNaN(valorInt)) {
			return false
		}
	}
	return true	
}

function validarCaracter(valor){
	for ( i = 0; i < valor.length; i++ ) {
		valorInt = parseInt(valor.charAt(i));
		if (!isNaN(valorInt)) {
			return false
		}
	}
	return true	
}

function Trim(TRIM_VALUE){
if(TRIM_VALUE.length < 1){
return"";
}
TRIM_VALUE = RTrim(TRIM_VALUE);
TRIM_VALUE = LTrim(TRIM_VALUE);
if(TRIM_VALUE==""){
return "";
}
else{
return TRIM_VALUE;
}
} //End Function

function RTrim(VALUE){
var w_space = String.fromCharCode(32);
var v_length = VALUE.length;
var strTemp = "";
if(v_length < 0){
return"";
}
var iTemp = v_length -1;

while(iTemp > -1){
if(VALUE.charAt(iTemp) == w_space){
}
else{
strTemp = VALUE.substring(0,iTemp +1);
break;
}
iTemp = iTemp-1;

} //End While
return strTemp;

} //End Function

function LTrim(VALUE){
var w_space = String.fromCharCode(32);
if(v_length < 1){
return"";
}
var v_length = VALUE.length;
var strTemp = "";

var iTemp = 0;

while(iTemp < v_length){
if(VALUE.charAt(iTemp) == w_space){
}
else{
strTemp = VALUE.substring(iTemp,v_length);
break;
}
iTemp = iTemp + 1;
} //End While
return strTemp;
} //End Function


/**
* Removes the options in a SELECT element
* @param object sel A node reference to a SELECT element
* @return void
*/
function removeOptions(sel) {
for (var i=sel.options.length-1; i > -1; i--) {
sel.options[i] = null;
}
}

function validarAny(valor) {
  
  if(valor=='') return false;
  if(valor.length!=2 && valor.length!=4)
  {	return false;
  }
  caractersValids='0123456789';
  for(i=0;i<valor.length;i++){
    caracter = valor.charAt(i);
    if(caractersValids.indexOf(caracter,0)==-1){
      return false;
    }
  }
  return true;
} 

// Valida que la data sigui correcta
function validacioData(valor) 
{
	if(valor=='') return false;
	caractersValids='0123456789';
	for(i=0;i<valor.length;i++)
	{
		caracter=valor.charAt(i);
	    if(caractersValids.indexOf(caracter,0)==-1)
	    {
	      return false;
	    }
	}
  	if(valor.length==3||valor.length==5) 
  	{
    	return false;
  	}
  	dia=valor.substring(0,2);
  	mes=valor.substring(2,4);
  	any=valor.substring(4,8);
  	if(any.length==1||any.length==3) 
  	{
    	return false;
  	}
  	if(dia>31||dia<1)
  	{
    	return false;
  	}
	if(mes>12||mes<1)
	{
    	return false;
  	}
  	if(dia>30)
  	{
    	if(mes==4||mes==6||mes==9||mes==11)
    	{
      		return false;
    	}
  	}
  	if(mes==2)
  	{
    	diasFeb=28;
    	bisiesto=any%4;
    	if(bisiesto==0) diasFeb=29;
    	if(dia>diasFeb)
    	{
	    	return false;
    	}
  	}
  	return true;
}

/******************************************************************************
 * method: ValidateTime
 *
 * author: Jason Geissler
 *
 * date: March 19, 2002
 *
 * parameters: time, formatType (1 - Standard format, 2- Military format)
 *
 * purpose: To validate a time in HH:MM format
 *****************************************************************************/
function ValidateTime(time, formatType) {
  var segments;      // Break up of the time into hours and minutes
  var hour;          // The value of the entered hour
  var minute;        // The value of the entered minute
    
  time = time.replace(".", ":");
    
  if (formatType == 1) {                                          /* Validating standard time */
    segments = time.split(":");
    
    if (segments.length == 2) {
      segments[1] = segments[1].substring(0,2);
      hour = segments[0];                                          // Test the hour
      if ((hour > 12) || (hour < 1))  
        return false;
            
      minute = segments[1];                                        // Test the minute
      if (( minute <= 59) && (minute >= 0)) 
        return true;
    }
      
  }
  else {                                                          /* Validating military time */
    segments = time.split(":");
    
    if (segments.length == 2) {
      hour = segments[0];                                          // Test the hour
      if ((hour > 23) || (hour <= -1)) 
        return false;
        
      minute = segments[1];                                        // Test the minute
      if (( minute <= 59) && (minute >= 0)) 
        return true;
    }
  }
  return false;
}  


/******************************************************************************
 * method: ValidateAdvancedTime
 *
 * author: Jason Geissler
 *
 * date: March 20, 2002
 *
 * parameters: time, formattype(1- Standard, 2- military)
 *
 * purpose: Calls the ValidateTime for hours and minutes but this also 
 *          calculates seconds. Time must be in XX:XX:XX style.
 *****************************************************************************/
function ValidateAdvancedTime(time, formatType){
  time = time.replace(".", ":");
  var newTime = time.substring(0, (time.indexOf(":") + 3)); // Strip out the seconds
  var status = ValidateTime(newTime, formatType);
  
  if(status == false) 
    return false;
    
  var seconds = time.substring(time.indexOf(":") + 4, time.length);
  if(seconds.length > 2) 
    seconds = seconds.substring(0, 2);                      // Remove any AM/PM afterwards
    
  if(!isNaN(seconds)) {                                      // Make sure its a number and it's between 0 and 59
    if((seconds <= 59) && (seconds >= 0)) 
      return true;
  }
  return false;  
}

/********************
* Format de strings
*********************/
function ltrim(s) 
{   return s.replace(/^\s+/, "");
}
function rtrim(s) 
{   return s.replace(/\s+$/, "");
}
function trim(s) 
{   return ltrim(rtrim(ltrim(s)));
}

/**************************
* Autofocus de textfields *
***************************/
function autofocus(actual, siguiente, longitud, evt) {
	evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : 
        ((evt.which) ? evt.which : 0));
	
	if(charCode > 31 && (actual.value.length) == longitud)
    {	siguiente.focus();
    }
}

function omplirZeros(txt,longitud)
{	if(txt.value!='' && txt.value.length < longitud)
	{
		nZeros = longitud - txt.value.length;
		valorFinal = txt.value;
		i=0;
		while(i<nZeros)
		{	valorFinal = "0"+valorFinal;
			i=i+1;
		}
		txt.value = valorFinal;
	}
}