var appDecSeparator = ',';
var appGrpSeparator = '.';
var defAppNumDecFactor = 100.0;

/* --- Array functions --- */

Array.prototype.indexOf = function(s) {
	for (var x=0;x<this.length;x++) if(this[x] == s) return x;
	return -1;
}

/* --- Window functions --- */

  function windowSize() {
  
    //Leave values injs vars: myWidth, myHeight
  
    if( typeof( window.innerWidth ) == 'number' ) {
      //Non-IE
      myWidth = window.innerWidth;
      myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
      //IE 6+ in 'standards compliant mode'
      myWidth = document.documentElement.clientWidth;
      myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
      //IE 4 compatible
      myWidth = document.body.clientWidth;
      myHeight = document.body.clientHeight;
    } 
	
  }
  
  function showProc() {
    document.getElementById("bkProc").style.visibility = 'visible';
  }

  function hideProc() {
    document.getElementById("bkProc").style.visibility = 'hidden';
  }
  
  function showAuxLayer() {
    inAuxLayer = true;
    document.getElementById("auxLayer").style.visibility = 'visible';
	document.getElementById("auxLayer").focus();
  }
  
  function hideAuxLayer() {
    document.getElementById("auxLayer").style.visibility = 'hidden';
	inAuxLayer = false;
  }

/* --- Date functions --- */

function validValue(value, type, field) {
  if (type == "DATE") {
    if (!isValidDate(value)) {
	  alert("Formato de fecha incorrecto (dd/mm/aaaa) [" + field + "]");
	  return false;
	}
  } else {
    if (type.length >= 5 && type.substr(0,5) == "EMAIL") {
	  if (!isValidEmail(value)) {
	    alert("Email incorrecto [" + field + "]");
		return false;
	  }
	}
  }
  
  return true;
}

function isValidEmail(str) {
  var filter=/^[A-Za-z_.][A-Za-z0-9_.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
  if (str.length == 0) 
    return true;
  if (filter.test(str))
    return true;
  else
    return false;
}

function formatDate(inputDate) {
  if (inputDate == null) {
    return "";
  } else {
    var year=inputDate.getYear();
    if (year < 1000)
      year+=1900;
    var day=inputDate.getDay();
    var month=inputDate.getMonth()+1;
    if (month<10)
      month="0"+month;
    var daym=inputDate.getDate();
    if (daym<10)
      daym="0"+daym;
    return daym+"/"+month+"/"+year;
  }
}

function formatHour(inputDate) {
  if (inputDate == null) {
    return "";
  } else {
    var hh=inputDate.getHours();
	var mm=inputDate.getMinutes();
	if (hh<10)
      hh="0"+hh;
	if (mm<10)
      mm="0"+mm;
    return hh + ":" + mm;
  }
}

function strToDate(inputDate) {
  if (inputDate == null || inputDate == '') {
    return '';
  } else {
    var aa = new String(inputDate.substring(inputDate.lastIndexOf("/")+1,inputDate.length));
    var mm = new String(inputDate.substring(inputDate.indexOf("/")+1,inputDate.lastIndexOf("/")));
    var dd = new String(inputDate.substring(0,inputDate.indexOf("/")));
	
	return aa + mm + dd;
  }
}

function getDateFromStr(inputDate) {
  //Esta funci&oacute;n habr&aacute; que adaptarla para formatos de fechas diferentes, de momento s&oacute;lo funciona para dd/mm/aaaa
  
  if (inputDate == null || inputDate == '') {
    return null;
  } else {
    var aa = new String(inputDate.substring(inputDate.lastIndexOf("/")+1,inputDate.length));
    var mm = new String(inputDate.substring(inputDate.indexOf("/")+1,inputDate.lastIndexOf("/")));
    var dd = new String(inputDate.substring(0,inputDate.indexOf("/")));
	
	return new Date(parseInt(aa),parseInt(mm-1),parseInt(dd));
  }
  
}

function isValidDate(inputDate){
	inputDate = trim(inputDate);
	
	if (inputDate == '')
	  return true;
	
	var nDate = getDateFromStr(inputDate);
	
	if (nDate == null)
	  return false;
	  
	var Ano = nDate.getYear();
	if (Ano < 1900) { Ano+=1900; }
	var Mes = nDate.getMonth()+1;
	var Dia = nDate.getDate();
	
	// Valido el a&ntilde;o
	if (isNaN(Ano) || Ano.length<4 || parseFloat(Ano)<1900){
		return false;
	}
	// Valido el Mes
	if (isNaN(Mes) || parseFloat(Mes)<1 || parseFloat(Mes)>12){
		return false;
	}
	// Valido el Dia
	if (isNaN(Dia) || parseInt(Dia)<1 || parseInt(Dia)>31){
		return false;
	}
	
	if((Ano%4 != 0) && (Mes == 2) && (Dia > 28))	   
	  return false;
    else	
	  {
	    if ((((Mes == 4) || (Mes == 6) || (Mes == 9) || (Mes==11)) && (Dia>30)) || ((Mes==2) && (Dia>29)))
		  return false;
	  }
	
  return true;
}

/* --- String functions --- */

String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'') }

function trim(cadena)
{
  if (cadena != null && cadena.length> 0) {
	for(i=0; i<cadena.length; )
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}

	for(i=cadena.length-1; i>=0; i=cadena.length-1)
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}
	
  }
  
  return cadena;
}

function formatInputValue(value, type) {

  if (value == null || value == '')
    return '';

  var res = value;
  
  if (type == 'DATE' && value.length > 7) {
    res = value.substr(6,2) + '/' + value.substr(4,2) + '/' + value.substr(0,4);
  }
  
  if (type == 'DOUBLE' || type == 'CURRENCY' || type == 'CURRENCY_YEAR' || type == 'CURRENCY_AREA' || type == 'CURRENCY_MONTH' || type == 'AREA') {
    res = formatDouble(value);
  }
  
  if (type == 'PERCENTAGE') {
    res = formatNumberDec(value, false, 1000.0);
  }

  if (type == 'INTEGER') {
    res = formatInteger(value);
  }
  
  return res;
}

  /* --- Number functions --- */
  
  function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
    return Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
  }
  
  function isNumeric(val) {
        var validChars = '0123456789.';

        for(var i = 0; i < val.length; i++) {
            if(validChars.indexOf(val.charAt(i)) == -1)
                return false;
        }

        return true;
  }
  
  function isValidInteger(s) {

    var valid = false;
    if (s != null && s != "" && !isNaN(s)) {
        valid = parseInt(s, 10) == s;
    }
    return valid;
  }
  
  function clearInteger(val) {
     var res = '';
	 for (ii=0; ii<val.length; ii++) {
	   if (val.substring(ii, ii+1) == '-') {
	     if (ii==0)
	       res += val.substring(ii, ii+1);
	   } else {
	     if (val.substring(ii, ii+1) != '.' && val.substring(ii, ii+1) != ',')
	        res += val.substring(ii, ii+1);
	   }
	 }
	 return res;
  }
  
  function clearInputInteger(item) {
     item.value = clearInteger(item.value);
	 //item.focus();
  }
  
  function clearDouble(val) {
     var res = '';
	 var aux = '';
	 var sep = '';
	 
	 //Find decimal separator
	 for (ii=val.length-1; ii>=0; ii--) {
	   if (val.substring(ii, ii+1) == '-') {
	     if (ii==0)
	       aux += val.substring(ii, ii+1);
	   } else {
	     if ((val.substring(ii, ii+1) == '.' || val.substring(ii, ii+1) == ',') && sep == '') {
  	        sep = val.substring(ii, ii+1);
		    aux += '.';  
	     } else {
	        if (val.substring(ii, ii+1) != '.' && val.substring(ii, ii+1) != ',')
  	           aux += val.substring(ii, ii+1);
	     }
	   }
	 }
	 
	 for (ii=aux.length-1; ii>=0; ii--) {
        res += aux.substring(ii, ii+1);
	 }
	 
	 return res;
  }
  
  function clearInputDouble(item) {
     item.value = clearDouble(item.value);
	 //item.focus();
  }

  function formatNumberDec(num, isInteger, numDecFactor) {   
    var auxFactor = numDecFactor;
    if (isInteger)
	  auxFactor = 1;
    num = num.toString().replace(/$|,/g,''); 
      if(isNaN(num)) 
        num = "0"; 
      sign = (num == (num = Math.abs(num))); 
      num = Math.floor(num*auxFactor+0.50000000001); 
      cents = num%auxFactor; 
      num = Math.floor(num/auxFactor).toString(); 
      if(cents<10) 
        cents = "0" + cents; 
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) 
          num = num.substring(0,num.length-(4*i+3))+appGrpSeparator+ 
          num.substring(num.length-(4*i+3)); 
	 
      if (isInteger)
        return (((sign)?'':'-') + num);
	  else
	    return (((sign)?'':'-') + num + appDecSeparator + cents);
  }
  
  function formatNumber(num, isInteger) { 
    return formatNumberDec(num, isInteger, defAppNumDecFactor);
  }
  
  function formatDouble(num) {
    return formatNumber(num, false);
  }
  
  function formatInteger(num) {
    return formatNumber(num, true);
  }
  
  function formatInputDouble(item) {
    item.value = formatDouble(clearDouble(item.value));
  }

  function formatInputInteger(item) {
    item.value = formatInteger(clearDouble(item.value));
  }

  function formatCurrency(num, currency) {
    return formatDouble(num) + ' ' + currency;
  }
  
  function formatEuro(num) {
    return formatCurrency(num, '&euro;');
  }

function setInputValue(inputName, value) {
  if (document.getElementById(inputName)) 
    document.getElementById(inputName).value = value;
}  

function setInputValueIfNullValue(inputName, value) {
  if (document.getElementById(inputName) && document.getElementById(inputName).value == "") 
    document.getElementById(inputName).value = value;
}  

function getInputValue(inputName) {
  var value = "";
  if (document.getElementById(inputName)) 
    value = document.getElementById(inputName).value;
  return value;
}  


function getDataValue(str, node) {
  var res = "";
  var from = "[" + node + "]";
  var to = "[/" + node + "";
  
  if (str.indexOf(from) != -1 && str.indexOf(to) != -1) {
    res = str.substring(str.indexOf(from) + from.length, str.indexOf(to));
  }
  
  return res;
}

function buildAddress(tAddress, address, number, stair, floor, letter, addressadd, zip, province, locality, country) {
  var strAddress = "";
  
  if (tAddress != null && tAddress != '')
    strAddress = strAddress + tAddress + " ";
	
  if (address != null && address != '')
    strAddress = strAddress + address;
  
  if (number != null && number != '')
    strAddress = strAddress + " " + number;
	
  if (stair != null && stair != '')
    strAddress = strAddress + ", Esc. " + stair;
	
  if (floor != null && floor != '')
    strAddress = strAddress + ", " + floor;
	
  if (letter != null && letter != '')
    strAddress = strAddress + " " + letter;
	
  if (addressadd != null && addressadd != '')
    strAddress = strAddress + "\n" + addressadd;
	
  var strLocality = '';
  var strProvince = '';
  if (province != null && province != '' && locality != null && locality != '' && province.toUpperCase() != locality.toUpperCase()) {
    strLocality = locality;
	strProvince = province;
  } else {
    if (locality != null && locality != '') {
	  strLocality = locality;
	} else {
	  if (province != null && province != '')
	    strLocality = province;
	}
  }
  
  if (zip != null || zip != '' || strLocality != '' || strProvince != '') {
    strAddress = strAddress + "\n";

	if (zip != null && zip != '')
	  strAddress = strAddress + zip;
	  
	if (strLocality != '')
	  strAddress = strAddress + " - " + strLocality;
	  
	if (strProvince != '')
	  strAddress = strAddress + "\n" + strProvince;
  }
  
  if (country != null && country != '') {
	if (strProvince != '')
	  strAddress = strAddress + "\n" + country;
  }
  
  return strAddress.toUpperCase();
}

/* --- Cookies --- */

  function setCookie(cookieName,cookieValue) { 
    setCookieProc(cookieName,cookieValue,caduca(365));
  }
  
  function setCookieProc(cookieName,cookieValue,expires,path,domain,secure) { 
    document.cookie=escape(cookieName)+'='+escape(cookieValue) 
                  +(expires?'; EXPIRES='+expires:'') 
                  +(path?'; PATH='+path:'') 
                  +(domain?'; DOMAIN='+domain:'') 
                  +(secure?'; SECURE':''); 
  }
  
  function getCookie(cookieName) { 
    var cookieValue=null; 
    var posName=document.cookie.indexOf(escape(cookieName)+'='); 
    if (posName!=-1) { 
      var posValue=posName+(escape(cookieName)+'=').length; 
      var endPos=document.cookie.indexOf(';',posValue); 
      if (endPos!=-1) cookieValue=unescape(document.cookie.substring(posValue,endPos)); 
      else cookieValue=unescape(document.cookie.substring(posValue)); 
    } 
    return cookieValue; 
  }
  
  function caduca(dias) {  
    var hoy = new Date()                                        //coge la fecha actual  
    var msEnXDias = eval(dias) * 24 * 60 * 60 * 1000    //pasa los dias a mseg.  
  
    hoy.setTime(hoy.getTime() + msEnXDias)          //fecha de caducidad: actual + caducidad  
    return (hoy.toGMTString())  
  }  
  
/* --- Images --- */

function preloadImages() { //v3.0
    var d=document; if(d.images){ if(!d.TT_p) d.TT_p=new Array();
      var i,j=d.TT_p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
      if (a[i].indexOf("#")!=0){ d.TT_p[j]=new Image; d.TT_p[j++].src=a[i];}}
}

function preloadWorkImages() {
    preloadImages("rs_images/bk_button_.gif",
  				  "rs_images/bk_button.gif",
				  "rs_images/access.gif",
				  "rs_images/news.gif",
				  "rs_images/webuser.gif",
				  "rs_images/contentpub.gif",
				  "rs_images/contents.gif",
				  "rs_images/new.gif",
				  "rs_images/exit.gif",
				  "rs_images/save.gif",
				  "rs_images/delete.gif");
}

/* --- Files --- */

function writeFile(folder,filename,data,mode){ //fwrite_x v1.0 byScriptman
  //modes: 0:si no existe, regresa false ;1: sobreescribe; 2:append.

  var fso = new ActiveXObject("Scripting.FileSystemObject");
  
  filename=folder+filename;
  if(fso.FileExists(filename) == false&&mode==0)
  return false;
  if(fso.FileExists(filename) != false&&mode==2) {
    tf = fso.OpenTextFile(filename,1);
    var dataold = tf.readall(); tf.close(); 
  } else dataold="";
  var tf = fso.CreateTextFile(filename,2);
  tf.write(dataold+data);
  tf.close();
  return true;
}

/* --- Input validation --- */

function onlytext(box){
  regexp = /\W/g;
  if(box.value.search(regexp) >= 0){
    box.value = box.value.replace(regexp, '');
  }
}

/* --- Find select entity --- */

function findSelect(idEntity, title, funSelect) {
  showProc();
  
  document.getElementById("auxLayerSelect").innerHTML = 
           "<div style='width:800px;height:16px;text-align:right;margin:0 0 5px 0;color:#000000;'><a class='upload' href='javascript:closeAuxLayerSelect()'>[Cerrar]</a></div>" + 
		   "<div style='width:800px;height:460px;'><iframe width='100%' height='100%' frameborder='0' src='rs_select.php?ENTITY=" + escape(idEntity) + "&TITLE=" + escape(title) + "&FUNSELECT=" + escape(funSelect) + "&WIDTH=780'></iframe></div>";
  
  showAuxLayerSelect();
} 

function findSelectFilter(idEntity, title, funSelect, filterProp, filterPropValue, filterProp2, filterPropValue2) {
  showProc();
  
  if (filterProp == null)
    filterProp = "";
  if (filterPropValue == null)
    filterPropValue = "";

  if (filterProp2 == null)
    filterProp2 = "";
  if (filterPropValue2 == null)
    filterPropValue2 = "";
  
  document.getElementById("auxLayerSelect").innerHTML = 
           "<div style='width:800px;height:16px;text-align:right;margin:0 0 5px 0;color:#000000;'><a class='upload' href='javascript:closeAuxLayerSelect()'>[Cerrar]</a></div>" + 
		   "<div style='width:800px;height:460px;'><iframe width='100%' height='100%' frameborder='0' src='rs_select.php?ENTITY=" + escape(idEntity) + "&TITLE=" + escape(title) + "&FUNSELECT=" + escape(funSelect) + "&FILTERPROP=" + escape(filterProp) + "&FILTERPROPVALUE=" + escape(filterPropValue) + "&FILTERPROP2=" + escape(filterProp2) + "&FILTERPROPVALUE2=" + escape(filterPropValue2) + "&WIDTH=780'></iframe></div>";
  
  showAuxLayerSelect();
} 

function closeAuxLayerSelect() {
  hideAuxLayerSelect();
  hideProc();
}

function showAuxLayerSelect() {
  inAuxLayerSelect = true;
  document.getElementById("auxLayerSelect").style.width = '800px';
  document.getElementById("auxLayerSelect").style.height = '500px';
  document.getElementById("auxLayerSelect").style.left = '50%';
  document.getElementById("auxLayerSelect").style.top = '50%';
  document.getElementById("auxLayerSelect").style.margin = '-250px 0 0 -400px';
  document.getElementById("auxLayerSelect").style.visibility = 'visible';
  document.getElementById("auxLayerSelect").focus();
}
  
function hideAuxLayerSelect() {
  document.getElementById("auxLayerSelect").style.width = '0px';
  document.getElementById("auxLayerSelect").style.height = '0px';
  document.getElementById("auxLayerSelect").style.visibility = 'hidden';
  inAuxLayerSelect = false;
}

/* ----- Print function ----- */

function printEntity(idEntity, id, target) {
}


