/***************************************************************************/
/*  AUTHOR: Eduardo Elgueta                                                */
/*  PURPOSE: Client side javascript utility functions                      */
/*  COPYRIGHT: (c) 1999-2004 Eduardo Elgueta - SRD e-business integration  */
/*                           Navix S.A.                                    */
/*  SOURCE; E:\iSCP\iSCP_Prj\csjutil.js                                    */
/*  RESTRICTIONS: JavaScript 1.3                                           */
/***************************************************************************/

/***************************************************************************/
/* String functions                                                        */
/***************************************************************************/

/***************************************************************************/
// Returns a string of t times the c character
/***************************************************************************/
function replicate (c, t) {
  var tmps = "";
  for (var i = 0; i < t; i++)
    tmps = tmps + c;
  return tmps;
}

/***************************************************************************/
// Returns a string of "times" spaces
/***************************************************************************/
function space (times) {
  return replicate(" ", times);
}

/***************************************************************************/
// Returns a string of "times" html nombreaking spaces
/***************************************************************************/
function nbSpace (times) {
  return replicate("&nbsp", times);
}

/***************************************************************************/
// Removes leading spaces
/***************************************************************************/
function ltrim (str) {

  var i = 0;
  var s = true;
  
  while ( s & (str.length > 0) ) {
    if ( str.charAt(0) == " ") {
      str = str.substring(1)
    } else {
      s = false
    }
  }
  return str
}

/***************************************************************************/
// Removes trailing spaces
/***************************************************************************/
function rtrim (str) {

  var i = 0;
  var s = true;

  while ( s & (str.length > 0) ) {
    if ( str.charAt(str.length - 1) == " ") {
      str = str.substring(0, str.length - 2)
    } else {
      s = false
    }
  }
  return str
}

/***************************************************************************/
// Removes trailing spaces (NS 4 version)
/***************************************************************************/
function crtrim (str) {

  var i = 0;
  var s = true;

  while ( s & (str.length > 0) ) {
    if ( str.charAt(str.length - 1) == " ") {
      str = str.substring(0, str.length - 1)
    } else {
      s = false
    }
  }
  return str
}

/***************************************************************************/
// Removes leading and trailing spaces
/***************************************************************************/
function alltrim (str) {
  return rtrim(ltrim(str))
}

/***************************************************************************/
/* Ajusts "s" string length to "l". If string length is shorter, it adds   */
/* char "c" to the left, if r is "L", or to the right if r is "R"          */
/***************************************************************************/
function pad (s, l, r, c) {

  if (s == null)
    s = "";
  if (!isNaN(s))
    s = s.toString();
  s = alltrim(s);
  
  if (r == null)
    r = "R";
  if (r == 'r')
    r = "R";
  if (c == null)
    c = " ";
    
  if (s.length > l)
    return s.substr(0, l);
  if (s.length < l) {
    if (r == "R")
      return s + replicate(c, l - s.length);
    else
      return replicate(c, l - s.length) + s;
  }
  return s
}

/***************************************************************************/
/* Pads string s to the given length l with html non-breaking spaces. See  */
/* pad function                                                            */
/***************************************************************************/
function nbspPad (s, l, r) {
  return pad(s, l, r, "&nbsp");
}



/***************************************************************************/
/* Date & time functions                                                   */
/***************************************************************************/

var SECOND = 1000; // the number of milliseconds in a second
var MINUTE = SECOND * 60; // the number of milliseconds in a minute
var HOUR = MINUTE * 60; // the number of milliseconds in an hour
var DAY = HOUR * 24; // the number of milliseconds in a day
var WEEK = DAY * 7; // the number of milliseconds in a week

/***************************************************************************/
/* Returns d2 - d1 in minutes                                              */
/***************************************************************************/
function minDif (d1, d2) {
  var t1 = d1.getTime();
  var t2 = d2.getTime();
  var dif = t1 - t2;
  return Math.round(dif / MINUTE);
}

// Original:  Mike Welagen (welagenm@hotmail.com)
// This script and many more are available free online at
// The JavaScript Source!! http://javascript.internet.com
// Indent and language modified by Eduardo Elgueta/Navis S.A.
// format and language switch added by Eduardo Elgueta/Navis S.A.
// lang: SP, EN
// strDateStyle: EU, US
function chkDate(objName, lang, strDatestyle) {
  if (lang == null) {
    lang = "SP"
  }
  if (strDatestyle == null) {
    strDatestyle = "EU";
  }
  var strDate;
  var strDateArray;
  var strDay;
  var strMonth;
  var strYear;
  var intday;
  var intMonth;
  var intYear;
  var booFound = false;
  var datefield = objName;
  var strSeparatorArray = new Array("-"," ","/",".");
  var intElementNr;
  var err = 0;
  var strMonthArray = new Array(12);
  if (lang == "EN") {
    strMonthArray[0] = "Jan";
    strMonthArray[1] = "Feb";
    strMonthArray[2] = "Mar";
    strMonthArray[3] = "Apr";
    strMonthArray[4] = "May";
    strMonthArray[5] = "Jun";
    strMonthArray[6] = "Jul";
    strMonthArray[7] = "Aug";
    strMonthArray[8] = "Sep";
    strMonthArray[9] = "Oct";
    strMonthArray[10] = "Nov";
    strMonthArray[11] = "Dec";
  } else {
    strMonthArray[0] = "Ene";
    strMonthArray[1] = "Feb";
    strMonthArray[2] = "Mar";
    strMonthArray[3] = "Abr";
    strMonthArray[4] = "May";
    strMonthArray[5] = "Jun";
    strMonthArray[6] = "Jul";
    strMonthArray[7] = "Ago";
    strMonthArray[8] = "Sep";
    strMonthArray[9] = "Oct";
    strMonthArray[10] = "Nov";
    strMonthArray[11] = "Dic";
  }
  strDate = new String(datefield.value);
  if (strDate.length < 1) {
    return true;
  }
  for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
    if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
      strDateArray = strDate.split(strSeparatorArray[intElementNr]);
      if (strDateArray == null) {
        err = 1;
        return false;
      }
      if (strDateArray.length != 3) {
        err = 1;
        return false;
      } else {
        strDay = strDateArray[0];
        strMonth = strDateArray[1];
        strYear = strDateArray[2];
      }
      booFound = true;
    }
  }
  if (booFound == false) {
    if (strDate.length > 5) {
      strDay = strDate.substr(0, 2);
      strMonth = strDate.substr(2, 2);
      strYear = strDate.substr(4);
    } else {
      err = 1;
      return false;
    }
  }
  if (strYear.length == 2) {
    strYear = '20' + strYear;
  }
  // US style
  if (strDatestyle == "US") {
    strTemp = strDay;
    strDay = strMonth;
    strMonth = strTemp;
  }
  intday = parseInt(strDay, 10);
  if (isNaN(intday)) {
    err = 2;
    return false;
  }
  intMonth = parseInt(strMonth, 10);
  if (isNaN(intMonth)) {
    for (i = 0; i < 12; i++) {
      if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
        intMonth = i+1;
        strMonth = strMonthArray[i];
        i = 12;
      }
    }
    if (isNaN(intMonth)) {
      err = 3;
      return false;
    }
  }
  intYear = parseInt(strYear, 10);
  if (isNaN(intYear)) {
    err = 4;
    return false;
  }
  if (intMonth>12 || intMonth<1) {
    err = 5;
    return false;
  }
  if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
    err = 6;
    return false;
  }
  if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
    err = 7;
    return false;
  }
  if (intMonth == 2) {
    if (intday < 1) {
      err = 8;
      return false;
    }
    if (LeapYear(intYear) == true) {
      if (intday > 29) {
        err = 9;
        return false;
      }
    } else {
      if (intday > 28) {
        err = 10;
        return false;
      }
    }
  }
  if (strDatestyle == "US") {
    datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
  } else {
    datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
  }
  return true;
}

function LeapYear(intYear) {
  if (intYear % 100 == 0) {
    if (intYear % 400 == 0) { 
      return true;
    }
  } else {
    if ((intYear % 4) == 0) {
      return true;
    }
  }
  return false;
}

function checkDate (dObj, label) {
  var save = dObj.value;
  var retVal = chkDate(dObj);
  dObj.value = save;
  if (!retVal) {
    alert(label + " is not a valid date!");
    dObj.focus();
  }
  return retVal;
}


/***************************************************************************/
/* Converts a date from american format (mm/dd/yyyy) to spanish format (dd/mm/yyy)
/***************************************************************************/
function spDateEng (aDate) {
  var auxStr = new String(aDate);
  var newStr = "";
  var slPos = auxStr.indexOf("/");
  if (slPos > -1) {
    var slPos2 = auxStr.lastIndexOf("/");
    newStr = auxStr.substring(slPos + 1, slPos2) + "/" + auxStr.substring(0, slPos);
    newStr += "/" + auxStr.substring(slPos2 + 1, auxStr.length);
  }
  return newStr;
}


/***************************************************************************/
/* Form functions                                                          */
/***************************************************************************/

/***************************************************************************/
/* Removes all leading and trailling spaces in all the given form fields
/***************************************************************************/
function trimAllFields (aForm) {
  var i = 0;

  for (i = 0; i < aForm.elements.length; i++) {
    field = aForm.elements[i];
    var valor = field["value"]
    if (valor != "undefined") {
      field.value = alltrim(valor);
    }
  }
}

/***************************************************************************/
/* Returns true if field is not empty                                     */
/***************************************************************************/
function checkNotEmpty (tObj, label) {
  tObj.value = alltrim(tObj.value);
  if (tObj.value == "") {
    alert("Must enter " + label + "!");
    tObj.focus();
    return false;
  }
  return true;
}
/****************************************************************************/
/* Return False if mail is incorrect
/* Return True if mail OK.
/****************************************************************************/
function checkMail(tObj, label) {
	var mail = tObj.value;
	var i = 0;
	var sw = 0;
	var sw2 = 0;
	cnt = mail.length;
	for (i = 0; i < cnt ; i++) {
		valor = mail.substr(i, 1);
		if ( valor == "@") {
			sw = 1 ;
			for (j = i ; j < cnt ; j++){
				valor2 = mail.substr(j, 1);
				if (valor2 == ".") {
					sw2 = 1;
				}
			}
		}
	}
	if ( (sw == 1) && (sw2 == 1)){
		return true;
	} else {
		alert ( label + " is not a valid email address\n\n");
		return false;
	}
}
/***************************************************************************/
/* Returns true if given string contains digits only
/***************************************************************************/
function onlyDigits (str) {
  var digits = '0123456789';
  for (var i = 0; i < str.length; i++)  {
    c = str.substring(i, i + 1);
    if (digits.indexOf(c) < 0)
      return false;
  }
  return true;
}

/***************************************************************************/
/* Returns true is field contains only digits                              */
/***************************************************************************/
function checkDigitsOnly (tObj, label) {
  var digits = '0123456789';
  var val = tObj.value;
  if (!onlyDigits(tObj.value)) {
    alert(label + " accepts only dígits.");
    tObj.focus();
    return false;
  }
  return true;
}

/***************************************************************************/
/* Returns true if the value is between the given range                    */
/***************************************************************************/
function inRange (val, mn, mx) {
  if ((val < mn) || (val > mx))
    return false;
  return true;
}

/***************************************************************************/
/* Returns true is field contains valid time string (HH:mm)                */
/***************************************************************************/
function checkTime (tObj, label) {
  var tStr = tObj.value;
  var sepPos = tStr.indexOf(":");
  if (sepPos < 0) {
    sepPos = tStr.indexOf(".");
    if (sepPos < 0) {
      alert(label + " is not a valid time!\n\n(Use ':' o '.' as separator)");
      tObj.focus();
      return false;
    }
  }
  var hr = tStr.substring(0, sepPos);
  var mn = tStr.substring(sepPos + 1, tStr.length);
  if (hr =='') {
	  alert(label + " must specify hours...\n\n");
	  tObj.focus();
	  return false;
  }
  
  if (mn =='' ) {
	  alert(label + " must specify minutes...\n\n");
	  tObj.focus();
	  return false;
  }

  if (!onlyDigits(hr) || !onlyDigits(mn)) {
    alert(label + " is not a valid time!\n\n(Only numbers allowed)");
    tObj.focus();
    return false;
  }
  if (!inRange(parseInt(hr), 0, 23)) {
    alert(label + " Is not a valid time!\n\n(Invalid hour value)");
    tObj.focus();
    return false;
  }
  if (!inRange(parseInt(mn), 0, 59)) {
    alert(label + " is not a valid time!\n\n(Invalid minutes value)");
    tObj.focus();
    return false;
  }
	
	tObj.value = hr + ":" + mn;
  return true;
}

/**********************************************
/* Returns a DateTime object from a HH:MM
/* string, where HH is the hour (0 - 23) and
/* MM is the minutes (0 - 59). Remember to 
/* first check the string is a valid hour with
/* the function checkTime()
/*********************************************/
function DateTimeFromTimeStr (timeStr) {
	var tmp = timeStr.replace(/\./, ':');
	var ppos = tmp.indexOf(":");
	var h = tmp.substring(0, ppos);
	if (h.substring(0, 1) == "0")
		h = h.substring(1, h.length);
	var m = tmp.substring(ppos + 1, tmp.length);
	if (m.substring(0, 1) == "0")
		m = m.substring(1, m.length);
	return new Date(0, 0, 0, parseInt(h), parseInt(m), 0, 0);
}
/***************************************************************************/
/* Removes format chars from a RUT String. If empty, returns               */
/* an empty string. If no check digit, returns null                        */
/***************************************************************************/
function cleanInputRut (rutValue) {
  r = alltrim(rutValue);
  r = r.replace(/\./ig, "");
  if (r == "")
    return "";
  var gPos = r.indexOf("-");
  if (gPos < 0)
    return null;
  var dv = r.substring(gPos + 1, r.length);
  if (dv.length != 1)
    return null;
  var rp = r.substring(0, gPos);
  return rp;
}

/***************************************************************************/
/* Calculates mod 11 check digit for given number                          */
/***************************************************************************/
function calc_dv (rut) {

  var cad = rut.toString(10);
  var suma = 0;
  var cont = 2;
  for (var i = cad.length; i > 0; i--) {
    var num = parseInt(cad.substr(i - 1, 1));
    suma += num * cont;
    cont++;
    if (cont == 8)
      cont = 2
  }
  var res = 11 - (suma % 11);
  if (res == 10)
    digito = 'K'
  else
    if (res == 11)
      digito = '0'
    else
      digito = res.toString(10);
  return digito
}

/***************************************************************************/
/* Checks the entered RUT is valid                                         */
/***************************************************************************/
function validInputRut (rutValue) {
  // Basic validation
  var rp = cleanInputRut(rutValue);
  if (rp == null) {
    alert("No se ha ingresado dígito verificador ingresado, o no es válido.");
    return false;
  }
  if (rp == "") {
    alert("Debe ingresar un RUT.");
    return false;
  }
  // check digit validation
  var gPos = rutValue.indexOf("-");
  var dv = alltrim(rutValue.substring(gPos + 1, rutValue.length));
  var cdv = calc_dv(Number(rp));
  if (cdv != dv) {
    alert("El rut o dígito verficador ingresados no son válidos.");
    return false;
  }
  return true;
}

/***************************************************************************/
/* Checks the text input is a valid RUT                                    */
/***************************************************************************/
function checkRut (tObj, label) {
  if (validInputRut(tObj.value)) {
    return true;
  } else {
    alert(label  + " no es un RUT válido!");
    tObj.focus();
    return false;
  }
}

/***************************************************************************/
/* Checks an option is selected in a HTML select.The flag indicates if the */
/* first line is a valid option (true)                                     */
/***************************************************************************/
function checkSelected (sObj, label, flagFLine) {
  if (flagFLine == null)
    flagFLine = false;
  if (sObj.selectedIndex >= (flagFLine ? 0 : 1)) {
    return true;
  } else {
    alert("Must select " + label  + "!");
    sObj.focus();
    return false;
  }
}


/***************************************************************************/
/* Sets a SELECT's selectedIndex property to the index that has the given  */
/* value parameter                                                         */
/***************************************************************************/
function setSelIdx (sel, value, defValue) {
  if (defValue == null) {
    defvalue = -1;
  }
  var notFound = true
  for (var i = 0; i < sel.options.length && notFound; i++) {
    var thisVal = sel.options[i].value;
    if (thisVal == value) {
      sel.selectedIndex = i;
      notFound = false;
    }
  }
  if (notFound) {
    sel.selectedIndex = defValue;
  }
}

/***************************************************************************/
/* Formats a RUT number                                                    */
/***************************************************************************/
function formatRut(rut, div) {
  if (rut == "" || div == "")
    fRut = "999.999.999-9"; 
  else {
    cad = rut.toString();
    len = cad.length;
    var cnt = 0;
    for (var i = len; i > 0; i--) {
      if (cnt == 3) {
        cad = cad.substr(0, i) + "." + cad.substr(i, 255);
        cnt = 0;
      }   
      cnt++;        
    }
    fRut = cad + "-" + div;  
  }  
  return fRut;
}


/***************************************************************************/
/* Formats a RUT number                                                    */
/***************************************************************************/
function setDisabled (id) {
  var obj = document.getElementById(id);
  obj.disabled = true;
}

/***************************************************************************/
/* if field value is blank, invoke func and jump to destField. If          */
/* destField is no specified, go back to field. If field is not blank, do  */
/* nothing                                                                 */
/***************************************************************************/
function loopIfBlank (field, func, destField) {
  if (destField == null) {
    destField = field;
  }
  field.value = alltrim(field.value);
  if (field.value != "") {
    func();
    destField.focus();
  }
}

/***************************************************************************/
/* Returns window parameters suitable to a dialog box                      */
/***************************************************************************/
function dialogWin (x, y, w, h) {
  var px = x == null ? 20 : x;
  var py = y == null ? 25 : y;
  var pw = w == null ? 200 : w;
  var ph = h == null ? 100 : h;
  var s = "top=" + py;
  s += ",left=" + px;
  s += ",height=" + ph;
  s += ",width=" + pw;
  s += ",hotkeys=0,menubar=0,personalbar=0,resizable=0,status=0,toolbar=0,scrollbars=0";
  return s;
}
