// -------------------------------------------------------------------------
// Javascript utility functions
// -------------------------------------------------------------------------
//
// Global variables needed for this module
//

// Global variable defaultEmptyOK defines default return value 
// for many functions when they are passed the empty string. 
// By default, they will return defaultEmptyOK.
//
// defaultEmptyOK is false, which means that by default, 
// these functions will do "strict" validation.  Function
// isInteger, for example, will only return true if it is
// passed a string containing an integer; if it is passed
// the empty string, it will return false.
//
// You can change this default behavior globally (for all 
// functions which use defaultEmptyOK) by changing the value
// of defaultEmptyOK.
//
// Most of these functions have an optional argument emptyOK
// which allows you to override the default behavior for 
// the duration of a function call.
//
// This functionality is useful because it is possible to
// say "if the user puts anything in this field, it must
// be an integer (or a phone number, or a string, etc.), 
// but it's OK to leave the field empty too."
// This is the case for fields which are optional but which
// must have a certain kind of content if filled in.

var defaultEmptyOK = false;
// whitespace characters
var whitespace = " \t\n\r";

// -------------------------------------------------------------------------
// Functions for the form validation icons
// -------------------------------------------------------------------------

// test the browser to make sure it's ok
var browserName = navigator.appName;
var browserVer = parseInt(navigator.appVersion);
var browserOK = (((browserName == "Netscape") && (browserVer >= 3)) || 
				 ((browserName == "Microsoft Internet Explorer") && (browserVer >= 4)));

// the prefix to use for the status image names
var image_prefix = "img_";
var image_prefix_opt = "opt_";

// set up the images
var imgPath

// for pages that are not in 4 level dirs (../../../../)
// declare the variable dirLevel and
// put dir in this variable always with end slash
if (typeof(dirLevel) == "undefined") {
   imgPath = "../../../../";
}
else {
   imgPath = dirLevel;   
}

if (browserOK) {
	emptyImg = new Image();
	emptyImg.src = imgPath + "images/punto.gif";
	warnImg = new Image();
	warnImg.src = imgPath + "images/warn.gif";
	reqImg = new Image();
	reqImg.src = imgPath + "images/req.gif";
}

// walk through the images on a page and update each one based 
// on its associated form item
function initImgForm(formname) {
	var i;

	if (browserOK) {
		for (i = 0; i < document.images.length; i++) {
			var cur_image = document.images[i].name;
			var cur_image_prefix = cur_image.substring(0, image_prefix.length);
			if ((cur_image_prefix) && (cur_image_prefix == image_prefix)) {
				var this_ctrl_name = cur_image.substring(image_prefix.length);
				var this_ctrl = eval("document.forms." + formname + "." + this_ctrl_name);
				
				reqfieldImg(this_ctrl);
			}
		}
	}
}

// set the image associated with a form item
function reqfieldImg(ctrl) {	
	if (browserOK) {
		var img = image_prefix + ctrl.name;
		
		if (ctrl.value != "") {
			document.images[img].src = emptyImg.src;
		} else {
			// the field is empty so display the required image
			document.images[img].src = reqImg.src;
		}
	}
}

function resetAnyImg(ctrl, prefix)
{
	var sImgName;
	
	sImgName = prefix + ctrl.name;	
    document.images[sImgName].src = emptyImg.src;
}


function resetOptImg(ctrl)
{
	var sImgName;
	
	sImgName = image_prefix_opt + ctrl.name;	
    document.images[sImgName].src = emptyImg.src;
}

function resetImg(ctrl)
{
	var sImgName;
	
	sImgName = image_prefix + ctrl.name;	
    document.images[sImgName].src = emptyImg.src;
}

function swapOptImg(ctrl)
{
	var bError = false;
	var sImgName;
	
	sImgName = image_prefix_opt + ctrl.name;
	
	if (ctrl.value != "") {
	    document.images[sImgName].src = emptyImg.src;
	}	  
	else {
	    document.images[sImgName].src = reqImg.src;
	    bError = true;
	}
	
	return bError;
}

function setWarnImg(prefix, ctrl)
{
	var sImgName;
	
	sImgName = prefix + ctrl.name;
    document.images[sImgName].src = warnImg.src;
}

// isInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating 
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// There is an optional second argument called emptyOK.
// emptyOK is used to override for a single function call
//      the default behavior which is specified globally by
//      defaultEmptyOK.
// If emptyOK is false (or any value other than true), 
//      the function will return false if s is empty.
// If emptyOK is true, the function will return true if s is empty.
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true 
// isInteger ("")             defaultEmptyOK
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true

function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}


// isSignedInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters are numbers; 
// first character is allowed to be + or - as well.
//
// Does not accept floating point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// EXAMPLE FUNCTION CALL:          RESULT:
// isSignedInteger ("5")           true 
// isSignedInteger ("")            defaultEmptyOK
// isSignedInteger ("-5")          true
// isSignedInteger ("+5")          true
// isSignedInteger ("", false)     false
// isSignedInteger ("", true)      true

function isSignedInteger (s)

{
	if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];		
        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;            
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}

// isNonnegativeInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer >= 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number >= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s,10) >= 0) ) );
}


//
//
//
function IsFilled(sBuffer, sMessage)
{
   if (sBuffer == "") {
		if (sMessage != "") {
      		alert(sMessage);
		}
      return false;
   }
   return true;
}

//
//  check if a field contains only numeric digits
//
function IsNumeric(aVar, sMessage)
{
	var aVarlen;
	var digitos = "0123456789";
	
	aVarlen = aVar.length;
	
	for(var i = 0; i < aVarlen; i++) {
		var subcadena = aVar.substring(i, i + 1);

		if (digitos.indexOf(subcadena) < 0) {
         if (sMessage != "") 
   			alert(sMessage);
			return false;
		}
	} /* end for */
	
	return true;
}

function IsNumericInRange(aVar, sMessage, aVarMin, aVarMax)
{
	if (!IsFilled(aVar, sMessage))
		return false;
	if (!IsNumeric(aVar, sMessage))
		return false;
	//alert(aVar + "|" + aVarMin + "|" + aVarMax);
	if (aVar < aVarMin || aVar > aVarMax ){
			if (sMessage != "")
			{
				alert(sMessage);
			}
			return false;
		}
	return true;
}

//
// Check whether string s is empty.
//
function isEmpty(s)
{
   return ((s == null) || (s.length == 0))
}

// Returns true if string s is empty or 
// whitespace characters only.
function isWhitespace (s)
{
    var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function isEmail (s)
{   
    if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    // is s whitespace?
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

// isAlphabetic (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) only.
//
function isAlphabetic (s)

{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphabetic character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }

    // All characters are letters.
    return true;
}

// Returns true if character c is an English letter 
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.
function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}



// Returns true if character c is a digit 
// (0 .. 9).
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}



// Returns true if character c is a letter or digit.
function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

// FOR DATA CHECK ------------------------------

// Attempting to make this library run on Navigator 2.0,
// so I'm supplying this array creation routine as per
// JavaScript 1.0 documentation.  If you're using 
// Navigator 3.0 or later, you don't need to do this;
// you can use the Array constructor instead.

function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

// isYear (STRING s [, BOOLEAN emptyOK])
// 
// isYear returns true if string s is a valid 
// Year number.  Must be 2 or 4 digits only.
// 
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
//
// And yes, this function is not Year 10000 compliant, but 
// because I am giving you 8003 years of advance notice,
// I don't feel very guilty about this ...
//
// For B.C. compliance, write your own function. ;->
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isYear (s)
{   
	if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}



// isIntegerInRange (STRING s, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
// 
// isIntegerInRange returns true if string s is an integer 
// within the range of integer arguments a and b, inclusive.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.


function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s,10);
    return ((num >= a) && (num <= b));
}



// isMonth (STRING s [, BOOLEAN emptyOK])
// 
// isMonth returns true if string s is a valid 
// month number between 1 and 12.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isMonth (s)
{   if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 01, 12);
}



// isDay (STRING s [, BOOLEAN emptyOK])
// 
// isDay returns true if string s is a valid 
// day number between 1 and 31.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 01, 31);
}



// daysInFebruary (INTEGER year)
// 
// Given integer argument year,
// returns number of days in February of that year.

function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}



// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day 
// form a valid date.
// 

function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
	
    var intYear = parseInt(year,10);
    var intMonth = parseInt(month,10);
    var intDay = parseInt(day,10);

    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 
    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

function isDayMonth (month, day)
{   // catch  invalid months and days.
    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intMonth = parseInt(month,10);
    var intDay = parseInt(day,10);

    if (! (isMonth(month, false) && isDay(day, false))) return false;

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 
    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

// isHour (STRING s [, BOOLEAN emptyOK])
// 
// isHour returns true if string s is a valid 
// hour number between 0 and 23.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isHour (s)
{   if (isEmpty(s)) 
       if (isHour.arguments.length == 1) return defaultEmptyOK;
       else return (isHour.arguments[1] == true);   
    return isIntegerInRange (s, 00, 23);
}

// isHour (STRING s [, BOOLEAN emptyOK])
// 
// isHour returns true if string s is a valid 
// hour number between 0 and 23.
// 
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isMinute (s)
{   if (isEmpty(s)) 
       if (isMinute.arguments.length == 1) return defaultEmptyOK;
       else return (isMinute.arguments[1] == true);   
    return isIntegerInRange (s, 00, 59);
}

function Trim ( inputStringTrim ) {
	var sTemp;
	inputStringTrim =  new String(inputStringTrim );
	fixedTrim = "";
	lastCh = " ";
	for (x=0; x < inputStringTrim.length; x++) {
	ch = inputStringTrim.charAt(x);
	if ((ch != " ") || (lastCh != " ")) { fixedTrim += ch; }
	lastCh = ch;
	}
	if (fixedTrim.charAt(fixedTrim.length - 1) == " ") {
	fixedTrim = fixedTrim.substring(0, fixedTrim.length - 1); }
	return fixedTrim
}

function IsDate(sDate) {
			var iDay, iMonth, iYear;
			if (sDate.length != 10)	return false;
			
			iDay= sDate.substring(0,2);
			if (isNaN(iDay)) return false;
			
			iMonth= sDate.substring(3,5);
			if (isNaN(iMonth)) return false;
			
			iYear= 	sDate.substring(6,10);	
			if (isNaN(iYear)) return false;
			
			if (Number(iDay) > 31) return false;
			if (Number(iMonth) > 12) return false;
			
			return true;
}		

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_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
    obj.visibility=v; }
}
function MM_findObj(n, d) { //v3.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); 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 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;
}
//Preload images (DynDuo)
function preload(imgObj,imgSrc) {
                eval(imgObj+' = new Image()')
                eval(imgObj+'.src = "'+imgSrc+'"')
}

// comprova si el camp passat com a paràmetre te un format de data vàlid (dd/mm/aaaa)
function checkDate(dateField)
{
 if (isWhitespace(dateField.value))
    return true;
    
 var pieces = dateField.value.split("/");
 var date = new Date(Date.parse(pieces[1]+"/"+pieces[0]+"/"+pieces[2]));
 if (isNaN(date))
 {
   	 alert("El formato de la fecha no es válido.\n\nDebe ser dd/mm/aaaa.");
	 dateField.focus();
     dateField.value = "";
  return false;
 }
 
 var d = date.getDate();
 if (d < 10) d = new String("0" + d);
 
 var m = date.getMonth()+1;
 if (m < 10) m = new String("0" + m);
 
 if (date.getFullYear() > 1980) {
     var y = new String(date.getFullYear());
    } 
 else {
 	var yr;
	Today = new Date();
	yr = Today.getFullYear();
 	//var y = new String(date.getFullYear() + 100);
	var y = new String(yr);
    }
 dateField.value = d + "/" + m + "/" + y;
 return true;
}


//chdeckdate2:No hace focus
function checkDate2(dateField)
{
  var sMsg4b = "Compruebe que la fecha tiene el formato (dd/mm/aaaa), y sea válida";
   
	var dateFieldOld = new Date(dateField);
	
	if (isWhitespace(dateField.value) || dateField.value=='dd/mm/aaaa')
	{
		dateField.value = '';
		dateField.focus();
		return true;	
   }
	
	var pieces = dateField.value.split("/");
	var date = new Date(Date.parse(pieces[1]+"/"+pieces[0]+"/"+pieces[2]));
	if (isNaN(date))
	{
     	alert("El formato de la fecha no es válido.\n\nDebe ser dd/mm/aaaa.");
	 	//dateField.value = '';
   		dateField.focus();
   		return false;
	}
	
	var d = date.getDate();
	if (d < 10) d = new String("0" + d);
	
	var m = date.getMonth()+1;
	if (m < 10) m = new String("0" + m);
	
	if (date.getFullYear() > 2070)
	{ 
		var y = '2070';
    }
	else
	{
		if (date.getFullYear() < 1900)
		{ 
			var y = '1900';
    	}
		else
		{
			var y = new String(date.getFullYear());
		}
	}
	dateFieldOld.value = d + "/" + m + "/" + y;

	var pField = dateField.value.split("/");
	var pFieldOld = dateFieldOld.value.split("/");
	//alert (dateField.value);
	//alert(dateFieldOld.value);
	var d = pField[0];
	var m = pField[1];
	if (d.length<2)
	{
		d = '0'+d;
	}
	if (m.length<2)
	{
		m = '0'+m;
	}
	if (d==pFieldOld[0] && m==pFieldOld[1] && pField[2]==pFieldOld[2] )
	{
		dateField.value = dateFieldOld.value;
		return true;
	}	
	else
	{
		alert (dateField.value+" "+sMsg4b);//a
		//dateField.value = ""
		dateField.focus();
		return false;	
	}	
}

