// Copyright 2004 and onwards  Zucchetti Spa.

var decSep
var milSep

SetNumberSettings()

function FormatNumber(number, len, dec, picture) {
  if (isNaN(number)) number=0;
  if (picture==null) { picture='' }
  if (len==null) { len=0 }
  if (dec==null) { dec=0 }

  var decimals = dec, integers
  var i, stringLen = picture.length, j
  var stringNumber = Str(number), integerValue, aux, decimalValue = ''
  var bNeg = false;
  if (number < 0) {
      bNeg = true
      stringNumber = Str(Math.abs(number))
  }

  if (stringLen > 0) {
    for(i = 0; i < stringLen; i++)
      if ((picture.charAt(i) == ".")) break;
    if (i == stringLen)
      decimals = 0;
    else
      decimals = stringLen-i-1;
  }

  stringNumber = FormatDecimals(Math.abs(number), decimals)
  j = stringNumber.length-decimals
  if (decimals > 0) {
    decimalValue = decSep + Substr(stringNumber,stringNumber.length-decimals+1);
    j--
  }
  aux = integerValue = Left(stringNumber,j)
  if (aux=='') {
   integerValue=aux="0"
  }

  if (At(",", picture) > 0) {
    if (decimals > 0)
      picture = Left(picture, stringLen - decimals - 1);

    // aggiunta del separatore delle migliaia
    aux = ''
    stringLen = integerValue.length
    for(i = 0; i < stringLen; i++) {
      aux = integerValue.charAt(stringLen-i-1) + aux
      if ((i+1) % 3 == 0 && i != (stringLen - 1)) aux = milSep + aux
    }
  }
  if (bNeg) {
    return ('-'+aux+decimalValue)
  }
  else {
    return (aux+decimalValue)
  }
}

function FormatDecimals(number, dec) {
  if (dec == 0)
    return(Math.round(number).toString())
  if (number == 0)
    return "."+"0000000000000".substr(0,dec)
  var mult = 1
  for (i = 0; i < dec; i++) {
    mult = mult * 10
  }
  var r = (Math.round(number * mult)).toString()
  r = ZeroPad(r,dec)
  var l = r.length
  var decimals = r.substr(l-dec,dec)
  if (decimals != '')
    return r.substr(0,l-dec)+"."+r.substr(l-dec,dec)
  else
    return r.substr(0,l-dec)
}

function SetNumberSettings() {
  try {
    var s = (1.2).toLocaleString()
    decSep = s.substr(1,1)
    milSep = decSep == ',' ? '.' : ','
  } catch(except) {
    decSep = '.'
    milSep = ','
  }
}

function Replicate(str,n){
  if (str==null) return ""
  if (!IsA(str,'C')) return ""
  if (n==null) n=1
  if (!IsA(n,'N')) n=1
  var r=""
  for(var i=0;i<n;i++) {
    r=r+str
  }
  return r
}

function Space(n){
  return Replicate(" ",n)
}

function Trim(str,chr){
  if (str==null) return ""
  var i=1, l=str.length
  chr=!IsA(chr,'U')?""+chr:' '
  while (i<=l && str.charAt(l-i)==chr)
    i++
  return str.substring(0,l-i+1)
}

function RTrim(str,chr){
  return Trim(str,chr)
}

function LTrim(str,chr){
  var i=0, l=str.length
  chr=!IsA(chr,'U')?""+chr:' '
  while (i<l && str.charAt(i)==chr)
    i++
  return str.substring(i)
}

function LRTrim(str,chr){
  return LTrim(Trim(str,chr),chr)
}

function Left(str,len) {
  if (IsA(str,'C') && IsA(len,'N')) {
    return(str.substr(0,len))
  } else {
    return ''
  }
}

function Right(str,len) {
  if (IsA(str,'C')) {
    return(str.substr(str.length-len))
  } else {
    return ''
  }
}

function Strtran(src,find,repl){
 var sb=new Array("");
 var b = 0;
 var e = find.length>0? src.indexOf(find): -1;
 while (e > -1) {
  if (b!=e) sb.push(src.substring(b, e));
  if (typeof(repl)!='string' || repl.length>0) sb.push(repl);
  b = e + find.length;
  e = src.indexOf(find, b);
 }
 sb.push(src.substring(b));
 return sb.join("");
}

function Substr(str,pos,cnt) {
  if (!IsA(str,'C')) return ''
  if (IsA(pos,'N')) {
    pos-=1
    if (pos<0) return ""
    if (IsA(cnt,'N')){
      if (cnt<1) return ""
      return str.substr(pos,cnt)
    } else {
      return str.substr(pos)
    }
  } else if (pos==null) {
    return str.substr()
  } else {
    return ''
  }
}

function Upper(str) {
  if (IsA(str,'C')) return str.toUpperCase(); else return ''
}

function Lower(str) {
  if (IsA(str,'C')) return str.toLowerCase(); else return ''
}

function Val(str) {
  if (IsA(str,'C')) {
    var n=parseFloat(str);
    if (isNaN(n)) {
      return(0);
    }
    else {
      return(n);
    }
  } else {
    return(0)
  }
}

function Str(p_n,len,dec) {
  if (p_n==null) {p_n=0}
  if (!IsA(p_n,'N')) {p_n=0}
  if (len==null) {len=10}
  if (!IsA(len,'N')) {len=10}
  if (dec==null) {dec=0}
  if (!IsA(dec,'N')) {dec=0}
  var res=p_n.toString()
  var point=At(".",res)
  if (point==0) res=res+".0"
  res+=Replicate("0",dec-Len(res)+At(".",res));
  point=At(".",res)
  if (point<=len+1) {
    res=Substr(res,1,dec>0 ? point+dec: point-1);
    if (res.length> len) {
      res=Substr(res,1,len)
      if (res.charAt(len-1)=='.')
        res=Substr(res,1,len-1);
    }
    len=len-res.length
    for(;len>0;len--) {
      res=" "+res
    }
  } else {
    res="";
    for(;len>0;len--)
      res+="*"
  }
  return res
}

function At(p_cStrFind,p_cStr,cnt) {
  // Resituisce la posizione di una stringa in un'altra.
  // Il param opz. "cnt" indica quale occorrenza e' richiesta
  if (cnt<=0 || !IsA(cnt,'N')) {cnt=1}
  if (p_cStrFind==null || p_cStrFind=="") {return 0}
  var l=0
  var pos=-1;
  while (l<cnt) {
    pos=p_cStr.indexOf(p_cStrFind, pos+1) ;
    l++;
  }
  return pos+1;
}

function RAt(strFind,str,cnt) {
  // Resituisce la posizione di una stringa in un'altra iniziando la ricerca da destra.
  // Il param opz. "cnt" indica quale occorrenza e' richiesta
  var pattern,result,pos=new Array()
  var index=0, strTest
  if (!IsA(strFind,'C') || !IsA(str,'C')) return 0
  if (cnt<=0 || !IsA(cnt,'N')) cnt=1
  if (navigator.appName=='Netscape') {
    pattern = new RegExp(strFind,"g")
    while ((result=pattern.exec(str))!=null) {
      pos[pos.length]=result.index+1
    }
  } else {
    // In Internet Explorer si deve usare una tecnica diversa
    // in quanto l'oggetto RegExp ha un baco !!!
    pattern = new RegExp(strFind)
    strTest=str
    while ((result=strTest.search(pattern))>=0) {
      index=index+result+strFind.length
      strTest=str.substr(index)
      pos[pos.length]=index-strFind.length+1
    }
  }
  pos.reverse()
  if (cnt<=pos.length) {
    return(pos[cnt-1])
  } else {
    return 0
  }
}

function ZeroPad(str,size) {
  if (!IsA(str,'C')) return ''
  while (str.length<size) {
   str='0'+str
  }
  return str
}

function Len(obj) {
  //Resituisce la lunghezza di una stringa o array
  return obj.length
}

function Asc(str) {
  if (str==null || str.length==0) return -1
  return str.charCodeAt(0)
}

function Chr(num){
  return String.fromCharCode(num)
}

function Max(a,b) {
  return ((Gt(a,b))?a:b)
}

function Min(a,b) {
  return ((Gt(a,b))?b:a)
}

function Mod(a,b) {
  return a % b
}

function Floor(a,b) {
  return Math.floor(a,b)
}

function IsNumber(kCode) {
  //44-->Comma ascii code , 45-->Minus ascii code, 46-->Point ascii code
  if (!(IsDigit(kCode) || kCode==44 || kCode==45 || kCode==46)) {
  //if (!(kCode >47 && kCode <58)) {
    return(false);
  } else {
    return(true);
  }
}

function IsDigit(kCode) {
if (!(kCode >47 && kCode <58)) {
    return(false);
  } else {
    return(true);
  }
}

function IsAlpha(kCode) {
  return(((kCode>64 && kCode<91) || (kCode>96 && kCode<123))?true:false)
}

function BoolToChar(b) {
  if (IsA(b,'L')) {
    return b ? "t" : "f"
  }
  return "f"
}

function CharToBool(s) {
  s = Trim(Lower(s))
  if (s=='true')
    return true
  else
    return false
}

function NullDate() {
  return new Date(100,0,1,0,0,0,0)
}

function NullDateTime() {
  return NullDate()
}

function DateToChar(obj) {
  if (IsA(obj,'D')) {
    return zeroFill(''+obj.getFullYear(),4)+zeroFill(''+(obj.getMonth()+1),2)+zeroFill(''+obj.getDate(),2)
  }
  return ''
}

function DateTimeToChar(obj) {
  if (IsA(obj,'D')) {
    return zeroFill(''+obj.getFullYear(),4)+zeroFill(''+(obj.getMonth()+1),2)+zeroFill(''+obj.getDate(),2)+zeroFill(''+obj.getHours(),2)+zeroFill(''+obj.getMinutes(),2)+zeroFill(''+obj.getSeconds(),2)
  }
  return ''
}

function CharToDate(obj) {
  if (Empty(obj)) return ''
  if (IsA(obj,'C')) {
    var year,month,day
    var fstSlash = obj.indexOf("/")
    var lstSlash = obj.lastIndexOf("/")
    if ((obj.indexOf("/", fstSlash + 1) == lstSlash) && (lstSlash == Len(obj) - 5)) {
      day = Val(Left(obj, fstSlash))
      month = Val(Substr(obj, fstSlash + 2, lstSlash - fstSlash))
      year = Val(Right(obj, 4))
      return new Date(year,month-1,day,0,0,0,0)
    }
    else{
      return new Date(Val(Substr(obj,1,4)),Val(Substr(obj,5,2))-1,Val(Substr(obj,7,2)),0,0,0,0)
    }
  }
  return new Date(100,0,1,0,0,0,0)
}

function CharToDateTime(obj) {
  if (Empty(obj)) return ''
  if (IsA(obj,'C')) {
    return new Date(Val(Substr(obj,1,4)),Val(Substr(obj,5,2))-1,Val(Substr(obj,7,2)),
                    Val(Substr(obj,9,2)),Val(Substr(obj,11,2)),Val(Substr(obj,13,2)),0)
  }

  return new Date(100,0,1,0,0,0,0)
}

function DayOfWeek(obj) {
  if (Eq(obj,NullDate())) return 0
  if (IsA(obj,'D')) {
    return obj.getDay()+1
  }
  return 0
}

function Sec(obj) {
  if (Eq(obj,NullDateTime())) return 0
  if (IsA(obj,'D')) {
    return obj.getSeconds()
  }
  return 0
}

function Minute(obj) {
  if (Eq(obj,NullDateTime())) return 0
  if (IsA(obj,'D')) {
    return obj.getMinutes()
  }
  return 0
}

function Hour(obj) {
  if (Eq(obj,NullDateTime())) return 0
  if (IsA(obj,'D')) {
    return obj.getHours()
  }
  return 0
}

function Day(obj) {
  if (Eq(obj,NullDate())) return 0
  if (IsA(obj,'D')) {
    return obj.getDate()
  }
  return 0
}

function Month(obj) {
  if (Eq(obj,NullDate())) return 0
  if (IsA(obj,'D')) {
    return obj.getMonth()+1
  }
  return 0
}

function Year(obj) {
  if (Eq(obj,NullDate())) return 0
  if (IsA(obj,'D')) {
    return obj.getFullYear()
  }
  return 0
}

function Week(obj) {
  if (Eq(obj,NullDate())) return 0
  if (IsA(obj,'D')) {
    var dayOfWeek=DayOfWeek(obj)
    var MinimalDaysInFirstWeek=4
    var rem = [0]
    var EPOCH_JULIAN_DAY = 2440588
    var ONE_DAY=1000*60*60*24
    var JAN_1_1_JULIAN_DAY = 1721426
    var gregorianEpochDay=EPOCH_JULIAN_DAY + floorDivide(obj.getTime(), ONE_DAY)- JAN_1_1_JULIAN_DAY
    var n400 = floorDivide(gregorianEpochDay, 146097, rem); // 400-year cycle length
    var n100 = floorDivide(rem[0], 36524, rem); // 100-year cycle length
    var n4 = floorDivide(rem[0], 1461, rem); // 4-year cycle length
    var n1 = floorDivide(rem[0], 365, rem);
    //var rawYear = 400*n400 + 100*n100 + 4*n4 + n1;
    var dayOfYear = rem[0]; // zero-based day of year
    if (n100 == 4 || n1 == 4) {
      dayOfYear = 365; // Dec 31 at end of 4- or 400-yr cycle
    } else {
      //++rawYear;
    }
    var firstDayOfWeek=1
    var relDow = (dayOfWeek + 7 - firstDayOfWeek) % 7; // 0..6
    var relDowJan1 = (dayOfWeek - dayOfYear + 701 - firstDayOfWeek) % 7; // 0..6
    var woy = Math.floor((dayOfYear - 1 + relDowJan1) / 7); // 0..53
    if ((7 - relDowJan1) >= MinimalDaysInFirstWeek)
      ++woy;

    // XXX: The calculation of dayOfYear does not take into account
    // Gregorian cut over date. The next if statement depends on that
    // assumption.
    if (dayOfYear > 359) { // Fast check which eliminates most cases
      // Check to see if we are in the last week; if so, we need
      // to handle the case in which we are the first week of the
      // next year.
      var lastDoy = DaysOfYear(Year(obj));
      var lastRelDow = (relDow + lastDoy - dayOfYear) % 7;
      if (lastRelDow < 0)
        lastRelDow += 7;
      if (((6 - lastRelDow) >= MinimalDaysInFirstWeek) &&
          ((dayOfYear + 7 - relDow) > lastDoy))
        woy = 1;

    } else if (woy == 0) {
      // We are the last week of the previous year.
      var prevDoy = dayOfYear + DaysOfYear(rawYear - 1);
      woy = weekNumber(prevDoy, dayOfWeek);
    }
    return woy
  }
  return 0
}

function floorDivide( numerator, denominator,  remainder) {
  if (remainder==null) remainder=[0]
  if (numerator >= 0) {
    remainder[0] = numerator % denominator
    return Math.floor(numerator / denominator)
  }
  var quotient = Math.floor((numerator + 1) / denominator) - 1;
  remainder[0] = numerator - (quotient * denominator);
  return quotient
}

var day_of_year_offset= [0,31,59,90,120,151,181,212,243,273,304,334];

function IsLeapYear(year){
return (year%4==0 && year%100!=0) || (year%400==0);
}

function DaysOfMonth(month,year){
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
  return 31;
case 4:
case 6:
case 9:
case 11:
  return 30;
case 2:
  return IsLeapYear(year)? 29: 28;
default:
  return 0;
}
}

function DaysOfYear(year){
if(year>0)
return IsLeapYear(year)? 366: 365;
else
return -1;
}

function DayOfYear(day,month,year){
if((day>0)&&(month>0)&&(year>0))
return day + day_of_year_offset[month-1] + (month>2 && IsLeapYear(year)? 1: 0);
else
return -1;
}

function AddDays(a,days) {
  if (Empty(a)) return NullDate();
  if (days==0) return a;
  var day=Day(a);
  var month=Month(a);
  var year=Year(a);

  if (days>0) {
    var days_of_month=DaysOfMonth(month,year);
    for(;days>0;days--) {
      if (++day>days_of_month) {
        if (++month>12) {
          year++;
          month=1;
        }
        day=1;
        days_of_month=DaysOfMonth(month,year);
      }
    }
  }
  else {
    for (;days<0;days++) {
      if (--day<1) {
        if (--month<1) {
          year--;
          month=12;
        }
        day=DaysOfMonth(month,year);
      }
    }
  }
  return new Date(year,month-1,day,Hour(a),Minute(a),Sec(a),0);
}

function TernsCmp(xa,ya,za,xb,yb,zb){
if(za>zb)
return 1;
if(za<zb)
return -1;
if(ya>yb)
return 1;
if(ya<yb)
return -1;
if(xa>xb)
return 1;
if(xa<xb)
return -1;
return 0;
}

function DaysBetw(dayL,monthL,yearL,dayH,monthH,yearH){
var neg=false;
if(TernsCmp(dayL,monthL,yearL,dayH,monthH,yearH)==0)
return 0;
if(TernsCmp(dayL,monthL,yearL,dayH,monthH,yearH)>0){
var back;
back=yearL;
yearL=yearH;
yearH=back;
back=monthL;
monthL=monthH;
monthH=back;
back=dayL;
dayL=dayH;
dayH=back;
neg=true;
}
var days = -DayOfYear(dayL,monthL,yearL);
var y;
for (y=yearL; y<yearH; y++) days += DaysOfYear(y);
days += DayOfYear(dayH,monthH,yearH);
if(neg)
return -days;
return days;
}

function DaysBetween(low,high) {
if(Empty(low)&&Empty(high))
return 0;
else
if (Empty(low)||Empty(high))
return Number.NaN;
return DaysBetw(Day(low),Month(low),Year(low),Day(high),Month(high),Year(high));
}

function DateDiff(low,high) {
var days=DaysBetween(low,high);
var DayLow,DayHigh;
DayLow= (Sec(low) + Minute(low)*60 + Hour(low)*3600)/86400;
DayHigh= (Sec(high) + Minute(high)*60 + Hour(high)*3600)/86400;
return days = days+(DayHigh-DayLow);
}

function iif(expr,trueExpr,falseExpr) {
  return ((expr)?trueExpr:falseExpr)
}

function zeroFill(varValue,len) {
  if ("0123456789".indexOf(varValue.charAt(0)) > -1) {
    while (varValue.length < len)
      varValue = '0' + varValue;
  }
  return varValue
}

function Round(varValue,len) {
  var res
  var l=Math.pow(10,Math.abs(len))
  if (len>0) {
    res=Math.round(varValue*l)/l
  } else if (len<0) {
    res=Math.round(varValue/l)*l
  } else
    res=Math.round(varValue)
  return(res)
}

function Int(varValue) {
  if(varValue>0)
   return Math.floor(varValue,0)
  else
   return -1*Math.floor(varValue*-1,0)
}

function SystemDate(d){
if(d==null)d=new Date()
return new Date(d.getFullYear(),d.getMonth(),d.getDate(),0,0,0,0)
}

SystemDate.parse=function(strdate) {
if (Eq("1-1-100",strdate)){
return NullDate()
}
return Date.parse(strdate)
}

function DateTime(d){
if(d==null){d=new Date();d.setMilliseconds(0)}
return d
}

function EmptyString(str){
  if (str==null) return true;
  if (typeof(str.match)=='undefined') return false;
  return str.match(/\S/)==null;
}
function EmptyNumber(num) {
  return Eq(num,0)
}
function EmptyDate(date) {
  if (date==null) {
    return true
  }
  if (date.getFullYear()==100) {
    if (date.getMonth()==0) {
      if (date.getDate() == 1) {
        return true
      }
    }
  }
  return false
}

function EmptyDateTime(date) {
  return EmptyDate(date)
}

function EmptyBoolean(yesno) {
  return yesno==false
}

function EmptyArray(arr) {
  return arr==null||arr.length==0;
}

function Empty(any) {
  switch(typeof any) {
    case 'number':
      return Eq(any,0)
    case 'boolean':
      return EmptyBoolean(any)
    case 'string':
      return EmptyString(any)
    case 'object':
      if (any==null) return true
      if(IsA(any,'D'))
        return EmptyDate(any)
      else if(IsA(any,'A'))
        return EmptyArray(any)
      break;
    case 'undefined':
      return true
  }
  return false
}

function IsNull(any) {
  return Empty(any);
}
function Eq(a,b){
if(a!=null && b!=null){
if(IsA(a,'D'))return a.getTime()==b.getTime()
if(IsA(a,'C')&&IsA(b,'D'))return a==FormatDate(b)
if(IsA(a,'N')&&IsA(b,'N'))return Ge(a,b)&&Le(a,b)
}
return a==b
}
function Eqr(a,b) {
if (IsA(a,'C') && IsA(b,'C'))
return RTrim(a)==RTrim(b)
else
return Eq(a,b)
}
function Ne(a,b){return !Eq(a,b)}
function Lt(a,b){
if(IsA(a,'D'))return a.getTime()<b.getTime()
if(IsA(a,'N')&&IsA(b,'N'))return 1e-10<b-a
return a<b
}
function Le(a,b){
if(IsA(a,'D'))return a.getTime()<=b.getTime()
if(IsA(a,'N')&&IsA(b,'N'))return a-b<=1e-10
return a<=b
}
function Ge(a,b){
if(IsA(a,'D'))return a.getTime()>=b.getTime()
if(IsA(a,'N')&&IsA(b,'N'))return 1e-10>=b-a
return a>=b
}
function Gt(a,b){
if(IsA(a,'D'))return a.getTime()>b.getTime()
if(IsA(a,'N')&&IsA(b,'N'))return a-b>1e-10
return a>b
}

function DateFromApplet(date) {
  return new Date(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0,0)
}

function DateTimeFromApplet(date) {
  return new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),
                  date.getMinutes(),date.getSeconds(),0)
}

function Format(any, len, dec, picture) {
  if (picture==null && IsA(len,'C')) {
    picture=len
    len=0
  }
  switch (typeof(any)) {
    case 'string':
      return FormatChar(any, len, picture)
      break
    case 'number':
      return FormatNumber(any, len, dec, picture)
      break
    case 'boolean':
      return FormatBoolean(any, picture)
      break
    case 'object':
      if (IsA(any,'D')) {
        if (any.getHours() > 0 || any.getMinutes() > 0 || any.getSeconds() > 0)
          return FormatDateTime(any, picture)
        else
          return FormatDate(any, picture)
        //return ApplyPictureToDate(any, picture)
      }
      break
    default:
      return any
      break;
  }
}
function FormatDate(date,pict){
if(Empty(date))pict=''
else{
if(pict=='D'||pict==''||pict==null)pict='DD-MM-YYYY'
else if(pict=='N')pict='DDMMYYYY'
pict=_PictDS(ZeroPad(date.getDate().toString(),2),ZeroPad((date.getMonth()+1).toString(),2),ZeroPad(date.getFullYear().toString(),4),pict)
}
return pict
}
function FormatDateTime(time,pict){
if(Empty(time))pict=''
else{
if(pict=='D'||pict==''||pict==null)pict='DD-MM-YYYY hh:mm:ss'
else if(pict=='N')pict='DDMMYYYYhhmmss'
pict=_PictTS(ZeroPad(time.getDate().toString(),2),ZeroPad((time.getMonth()+1).toString(),2),ZeroPad(time.getFullYear().toString(),4),ZeroPad(time.getHours().toString(),2),ZeroPad(time.getMinutes().toString(),2),ZeroPad(time.getSeconds().toString(),2),pict)
}
return pict
}
function _PictDS(day,month,year,pict){
pict=Strtran(pict,"DD",day)
pict=Strtran(pict,"D",Left(day,1)=="0"?Right(day,1):day)
pict=Strtran(pict,"MM",month)
pict=Strtran(pict,"M",Left(month,1)=="0"?Right(month,1):month)
pict=Strtran(pict,"YYYY",year)
pict=Strtran(pict,"YY",Right(year,2))
if(At('h',pict)>0)pict=LRTrim(Substr(pict,1,At('h',pict)-1))
return pict
}
function _PictTS(day,month,year,hour,minute,second,pict){
pict=Strtran(pict,"hh",hour)
pict=Strtran(pict,"h",Left(hour,1)=="0"?Right(hour,1):hour)
pict=Strtran(pict,"mm",minute)
pict=Strtran(pict,"m",Left(minute,1)=="0"?Right(minute,1):minute)
pict=Strtran(pict,"ss",second)
pict=Strtran(pict,"s",Left(second,1)=="0"?Right(second,1):second)
return _PictDS(day,month,year,pict)
}
function CountChar(chr, str) {
  num=0;
  for(i=0; i<str.length; i++ ) {
    if(str.charAt(i)==chr) num++;
  }
  return num;
}

function URLenc(s){
var e=Lower(document.charset)
return Strtran(Strtran(escape(s),"+","%2B"),"%u20AC",e=='utf-8'?"%E2%82%AC":(e=='iso-8859-15'?"%A4":"%80"))
}

function BuildPicture(type,len,dec){
  var i;
  var p;
  var result="";
  if (type=="N" && len>0){
    p="";
    if(dec==0){
      for(i=0;i<len;i++){
        p+="9";
      }
    }
    else{
      for(i=0;i<len-dec-1;i++){
        p+="9";
      }
      p+=".";
      for(i=0;i<dec;i++){
        p+="9";
      }
    }
    result=p;
  }
  if (type=="D"){
    return "DD-MM-YYYY"
  }
  if (type=="T"){
    return "DD-MM-YYYY hh:mm:ss"
  }
  return result;
}

var m_Ctx={
GetSql:function(){return null},
GetServer:function(){return ''},
GetPhName:function(n){return n},
IsSharedTemp:function(){return false}
}
var CPMessageSink={
ConsoleSink:{SendMessage:function(msg){alert(msg)},log:function(msg){alert(msg)}}
}
var Forward={
Unforwarded:null
}
function CPResultSet(s,id,v){
this.resultset={metadata:{},data:[],errormessage:'no results'}
try{
if(typeof PlatformPathStart=='function')s=PlatformPathStart(s);
var u=['../servlet/'+s,'?m_cBrowseName='+id]
for(var p in v){
if(IsA(v[p],'C')){
v[p]="'"+v[p]+"'"
}else if(IsA(v[p],'D')){
v[p]='{'+Day(v[p])+'-'+Month(v[p])+'-'+Year(v[p])+" "+Hour(v[p])+':'+Minute(v[p])+':'+Sec(v[p])+'}'
}else{
v[p]=''+v[p]
}
u[u.length]='&'+p+'='+URLenc(v[p])
}
eval('this.resultset='+new JSURL(u.join(''),true).__response())
for(var p in this.resultset.readdata)v[p]=this.resultset.readdata[p]
}catch(e){
this.resultset.errormessage=e.message
}
this.currow=0
this.Close=function(){}
this.Next=function(){this.currow++}
this.Eof=function(){return this.currow>=this.resultset.data.length}
this.ErrorMessage=function(){return this.resultset.errormessage}
this.Datum=function(cname){
try{
return this.resultset.data[this.currow][this.resultset.metadata[cname][0]]
}catch(e){return null}
}
this.GetDate=function(cname){
var d=this.Datum(cname)
return d==null?NullDate():this.coerce(d,'D')
}
this.GetDateTime=function(cname){
var d=this.Datum(cname)
return d==null?NullDateTime():this.coerce(d,'T')
}
this.GetString=function(cname){
var d=this.Datum(cname)
return d==null?'':this.coerce(d,'C')
}
this.GetDouble=function(cname){
var d=this.Datum(cname)
return d==null?0:this.coerce(d,'N')
}
this.GetBoolean=function(cname){
var d=this.Datum(cname)
return d==null?false:this.coerce(d,'L')
}
this.coerce=function(value,p_desired) {
var original
switch(typeof value) {
case 'string':
original='C';break
case 'number':
original='N';break
case 'boolean':
original='L';break
}
if (original==p_desired)
return value
else {
if(original=='C') {
switch(p_desired) {
case'N':return Val(value)
case'D':return CharToDate(value)
case'T':return CharToDateTime(value)
case'L':return !Empty(value)
}
} else if(original=='N') {
switch(p_desired){
case'C':return ''+value
case'L':return !Empty(value)
}
}
}
return value
}
}
function Caller(c,prefix){
if(prefix==null)prefix=""
var sget=function(e,n,d){
try{
if(e==n && c.eval('typeof '+prefix+n)=='undefined'){
return d
}else{
return Left(e,prefix.length)==prefix?c.eval(e):c.eval(prefix+e)
}
}catch(ex){
return d
}
}
this.GetNumber=function(n){return sget(n,n,0)}
this.GetString=function(n){return sget(n,n,'')}
this.GetDate=function(n){return sget(n,NullDate())}
this.GetDateTime=function(n){return sget(n,n,NullDateTime())}
this.GetLogic=function(n){return sget(n,n,false)}
this.SetNumber=function(n,t,l,d,v){sget(n+'='+v)}
this.SetString=function(n,t,l,d,v){sget(n+'='+LibJavascript.ToJSValue(v),n)}
this.SetDate=function(n,t,l,d,v){sget(n+'=CharToDate("'+DateToChar(v)+'")',n)}
this.SetDateTime=function(n,t,l,d,v){sget(n+'=CharToDateTime("'+DateTimeToChar(v)+'")',n)}
this.SetLogic=function(n,t,l,d,v){sget(n+'='+v)}
this.CalledBatchEnd=function(){if(c.CalledBatchEnd)c.CalledBatchEnd()}
}
function ReadGlobals(srvlt,glbls,sttr,snk){
var r,v
if(typeof PlatformPathStart=='function')srvlt=PlatformPathStart(srvlt);
try{
eval("r="+new JSURL('../servlet/'+srvlt+'?m_cGlobalsToRead=1',true).__response())
}catch(e){
snk.SendMessage(''+e)
}
for(var g in glbls){
try{
if(r==null || IsA(r[glbls[g][1]],'U')){
switch(glbls[g][0]) {
case'D':v=NullDate();break;
case'T':v=NullDateTime();break;
case'N':v=0;break;
case'L':v=false;break;
default:v=''
}
}else{
v=r[glbls[g][1]]
switch(glbls[g][0]) {
case'D':
v=CharToDate(v)
break
case'T':
v=CharToDateTime(v)
}
}
sttr(glbls[g][1],v)
}catch(e){
snk.SendMessage(''+e)
}
}
}
CPLib={
ToSQL:function(value,cpt,l,d){
switch(cpt){
case 'C':case'M':return value
default:alert('TBD')
}
},
ToCPStr:function(cs){
var res
if(IsA(cs,"C"))return Trim(cs)
if(IsA(cs,"N")){
res=Strtran(Trim(Strtran(Str(cs,16,16),"0"," "))," ","0")
res=Strtran(res,",",".")
if(Eq(Right(res,1),"."))res=Left(res,Len(res)-1)
if(Empty(res))res="0"
return res
}
if(IsA(cs,"D")){
res=DateToChar(cs)
if(Empty(res))
res="{}"
else
res="{^"+Left(res,4)+"-"+Substr(res,5,2)+"-"+Right(res,2)+"}"
return res
}
if(IsA(cs,"L"))return cs?".T.":".F."
if(IsA(cs,"T")){
if(Empty(cs))res="{}"
else{
res=DateTimeToChar(cs)
res="{^"+Left(res,4)+"-"+Substr(res,4,2)+"-"+Substr(res,5,2)+" "+Substr(res,6,2)+":"+Substr(res,7,2)+":"+Right(res,2)+"}"
}
return res
}
}
}
function IsAny(o){return o!=null && !IsA(o,'U')}
function __tof(o){return typeof o};
function _tof(o,t){return t==typeof o};
function _oof(o,o2){return _iof(o,o2.constructor)};
function _iof(o,f){return (o) instanceof f};
function _isd(o){return o && (o instanceof Date || (o.getFullYear && o.getMonth && o.getDate && o.getHours && o.getMinutes && o.getSeconds && o.getMilliseconds))};
function _hasc(o,c){return IsAny(o) && o.constructor==c}
_tpOfs={U:function(o){return _tof(o,'undefined');},C:function(o){return _hasc(o,String)},N:function(o){return _hasc(o,Number)},L:function(o){return _hasc(o,Boolean)},O:function(o){return _tof(o,'object')},F:function(o){return _tof(o,'function')},D:function(o){return _isd(o);},A:function(o){return _iof(o,Array);},T:function(o){return this.D(o);}};
_cis={"object":_oof,"function":_iof,"string":_tpOfs.C,"number":_tpOfs.N,"boolean":_tpOfs.L};
function IsA(o,c){
if(_tpOfs[c]) return _tpOfs[c](o);
switch (c){
case String: return _tpOfs.C(o);
case Number: return _tpOfs.N(o);
case Boolean: return _tpOfs.L(o);
case Function: return _iof(o,c);
case Object: return _oof(o,c);
default: return _cis[__tof(c)](o,c);
}}

if(typeof LibJavascript=='undefined') var LibJavascript={};
LibJavascript.AlfaKeyGen=function(keyLen){
	var res="";
  for(var i=0; i++<keyLen; res+=String.fromCharCode(Math.floor(Math.random()*26+97)));
	return res;
}
LibJavascript.String={
  stripTags:function(s){
    return s.replace(/<([^>]+)>/g,'');
  },
  Chainer: function(){
    var b;
    if(navigator.userAgent.indexOf('MSIE')!=-1){
      b=[];
      return {
        concat: function(s){
          b.push(s);
          return this;
        },
        flush: function(){
          var res=this.toString();
          b=[];
          return res;
        },
        debug: function(){
          debugger;
        },
        toString: function(){
          //debugger
          return b.join('');
        }
      }
    }else{
      b='';
      return {
        concat: function(s){
          b+=s;
          return this;
        },
        flush: function(){
          var res=this.toString();
          b='';
          return res;
        },
        debug: function(){
          debugger;
        },
        toString: function(){
          return b;
        }
      };
    }
  }
};
LibJavascript.JSONUtils={
  validate: function(obj, schema){
    throw new Error("Validate function not yet implemented")
  },
  adjust: function(obj, schema){
    /*
      Verifica che tutte le proprieta' del diz schema siano presenti in obj.
      Quelle che mancano vengono valorizzate da schema[p].
      - Se schema[p] non e' una funzione il valore viene condiviso
          !!! ATTENZIONE A NON CAMBIARE I VALORI IN SCHEMA !!!
      - Se schema[p] e' una funzione viene invocata e assegnato il risultato a obj[p]

      Viene ritornato l'obj "aggiustato".

      Se obj e' un array viene "aggiustato" ogni elemento dell'array.
        Se un elemento e' null viene creato e inserito un nuovo oggetto "aggiustato".

      Pensata per far "unmarshalling" di serializzazioni vecchie su versioni nuove
    */
    var objs = IsA(obj, 'A') ? obj : [obj];

    for(var p in schema){
      for(var i=0, o, l=objs.length; i<l; i++){
        o=objs[i];
        if(!IsAny(o)){
          o=objs[i]={};
        }
        if(!(p in o)){
          var defVal = schema[p];
          o[p]= ('function' == typeof(defVal) ? defVal(o) : defVal);
        }
      }
    }
    return IsA(obj, 'A') ? objs : objs[0];
  },
  purge: function(obj, props){
    /*
      Ritorna un oggetto con solo le proprieta' di obj elencate in props.
      props e' un array di stringhe che contiene i nomi delle proprieta' da assegnare.
      Restituisce un oggetto nuovo.

      Se obj e' un array applica la "pulizia" ad ogni elemento dell'array
        ritornando un array nuovo.

      Pensato per serializzare tramite JSON e minimizzare il cosi' traffico.
    */
    function purge(obj){//pulisce il singolo obj
      var res={};
      for(var i=0, p; p=props[i++]; ){
        res[p]=obj[p];
      }
      return res;
    }

    var res = [],
        objs = IsA(obj, 'A') ? obj : [obj];

    for(var i=0, o, l=objs.length; i<l; i++){
      if(o=objs[i]){
        res.push(purge(objs[i]));
      }
    }
    return IsA(obj, 'A') ? res : res[0];
  }
};
LibJavascript.Array={
  indexOf: function(m_aArr,m_oElem,m_fCmpFnc){
    if(IsA(m_aArr,'U'))return -1;
    if(IsA(m_fCmpFnc,'U')){
      m_fCmpFnc=function(el){
        return m_oElem==el&&IsA(el,m_oElem);
      }
    }
    if(IsA(m_oElem,'U'))return -1;
    for(var i=0;i<m_aArr.length;i++)
    if(m_fCmpFnc(m_aArr[i],m_oElem))return i;
    return -1;
  },
  moveAfter: function(a, f, t){//array, from, to
    if(f==t || f==t+1)return;
    a.splice(t+1,0,a[f]);
    a.splice(f+(t<f ? 1 : 0),1);
  },
  moveBefore: function(a, f, t){//array, from, to
    if(f==t || f==t-1)return;
    a.splice(t,0,a[f]);
    a.splice(f+(t<f ? 1 : 0),1);
  },
  remove: function(a, i){//array, idx
    if(!(i in a))return;
    return a.splice(i,1)[0];
  },
  insert: function(a, i, e){//array, idx, any
    var l=a.length;
    a.splice(i, 0, e);
    return i>=0 ? (a[i]==e ? i : (a[l]==e ? l : Libjavascript.Array.indexOf(a,e))) : Math.max(0, l+i);
  },
  copy: function(a){
    return a.slice();
  }/*,
  http://developer.mozilla.org/en/docs/New_in_JavaScript_1.6#Array_extras
  forEach:function(){},
  filter:function(){},
  every:function(){},
  map:function(){},
  */
}
LibJavascript.CssClassNameUtils=function(){
  var _this;
  return {
  init:function(){
    _this=LibJavascript.CssClassNameUtils;
  },
	hasClass:function(obj,cName){
    if(!obj) return;
		return new RegExp('\\b'+cName+'\\b').test(obj.className);
	},
	hasClasses:function(obj,classes){
    if(!obj) return;
		for(var i=0,l=classes.length;i<l;i++)
      if(!_this.hasClass(obj,classes[i]))
				return false;
		return true;
	},
  _addClass:function(obj,cName){
    if(!obj) return;
    if(!_this.hasClass(obj,cName))
			obj.className+=EmptyString(obj.className)?cName:' '+cName;
  },
  addClass:function(obj,cName,lazy){
    if(lazy){
      window.setTimeout(function(){
        _this._addClass(obj,cName);
      }, 0);
    }else{
      _this._addClass(obj,cName);
    }
	},
  _removeClass:function(obj,cName){
    if(!obj) return;
    if(!_this.hasClass(obj,cName))
			return;
		var rep=obj.className.match(' '+cName)?' '+cName:cName;
		obj.className=obj.className.replace(rep,'');
  },
  removeClass:function(obj,cName,lazy){
    if(lazy){
      window.setTimeout(function(){
        _this._removeClass(obj,cName);
      }, 0);
    }else{
      _this._removeClass(obj,cName);
    }
	},
  toggleClass:function(obj,cName){
    _this[ _this.hasClass(obj,cName) ? '_removeClass' : '_addClass'](obj,cName);
  },
	swapClasses:function(obj,class1,class2){
    if(_this.hasClass(obj,class1)){
      _this._removeClass(obj,class1);
      _this._addClass(obj,class2);
			return;
		}
    if(_this.hasClass(obj,class2)){
      _this._removeClass(obj,class2);
      _this._addClass(obj,class1);
			return;
		}
	},
	replaceClass:function(obj,find,_with){
    if(_this.hasClass(obj,find))
      _this._removeClass(obj,find);
    _this._addClass(obj,_with);
		return true;
	},
  getElementsByClassName:function(className,container/*default to document*/,tag/*default to'*' */){
    if(IsAny(container)){
      container=LibJavascript.DOM.Ctrl(container);
      if(!container) return;
    }else{
      container=document;
    }
		tag=tag||'*';
		var all=container.all||container.getElementsByTagName(tag);//listing container descendants
		var found=[];
    for(var f=0,el; el=all[f++]; ){
      if(_this.hasClass(el,className)){
				found.push(el);
		  }
    }
		return found;
	}
  };
}();
LibJavascript.CssClassNameUtils.init();
if(!LibJavascript.Events){
LibJavascript.Events = {
  _evts: {},
	addEvent: function(obj, type, fn) {
    obj=LibJavascript.DOM.Ctrl(obj);
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
      var e_id='e'+ type + fn;
      obj.detachEvent('on'+ type, obj[e_id] || new Function);
      obj.attachEvent('on'+ type, obj[e_id] = fn);
      if('unload'==type) return;
      LibJavascript.Events._evts[e_id]={obj: obj, type: type, fn: fn};
		}
	},
	removeEvent: function(obj, type, fn) {
		if (obj.removeEventListener)
			obj.removeEventListener(type, fn, false);
		else if (obj.detachEvent) {
      var e_id='e'+ type + fn;
      obj.detachEvent('on'+ type, obj[e_id]);
      obj[e_id] = null;
      try{
        delete obj[e_id];
      }catch(e){
          if(e_id in obj) {
            try  {
              obj.removeAttribute(e_id);
            } catch(e){
            }
          }
      }finally{
        delete LibJavascript.Events._evts[e_id];
      }
		}
  },
  _cleanUp: function(){
    var libE=LibJavascript.Events,evts=libE._evts,o;
    for(var e_id in evts){
      o=evts[e_id];
      libE.removeEvent(o.obj, o.type, o.fn);
    }
    libE._evts=null;
  }
}}
LibJavascript.DOM=function(){
  var _this,
  res={
  init: function(){
    _this=this;
  },
  _CtrlById: function(id){
    return document.getElementById(id);
  },
  Ctrl: function(el){//id o rif
    return IsA(el,'C') ? _this._CtrlById(el) : el;
  },
  addNode: function(parent,el){
    parent=_this.Ctrl(parent);
    el=_this.Ctrl(el);
    if(!parent || !el) return;
    _this.removeNode(el);
    parent.appendChild(el);
    return [parent,el];
  },
  insertNode: function(parent, position, el){
    parent=_this.Ctrl(parent);
    el=_this.Ctrl(el);
    if(!parent || !el || !IsA(position,'N') || position<0 ) return;
    var children=parent.childNodes;
    if(position>=children.length){
      return _this.addNode(parent,el) ? children.length-1 : null ;
    }else{
      parent.insertBefore(el,children[position]);
      return el==children[position] ? position : null ;
    }
  },
  removeNode: function(el){
    el=_this.Ctrl(el);
    if(!el){
      return;
    }
    if(!el.parentNode){
      return el;
    }
    return el.parentNode.removeChild(el);
  }
  }
  res.init();
  return res;
}();
LibJavascript.StackTrace=function(){
var p=arguments.callee,s='',i
while((p=p.caller)!=null){
s+=Substr(''+p,1,At('(',''+p))
for(i=0;i<p.arguments.length;i++)s+=(i==0?'':',')+p.arguments[i];
s+=')\n'
}
return s
}
LibJavascript.xap=function(pass,inp){
var plen=pass.length,i,n=0,p=-1,seed,rval,ibuf=[],obuf=[]
for(i=0;i<inp.length;i+=4){
ibuf[i/4]=parseInt(Substr(inp,i+1,4),16)
}
seed=pass.charCodeAt(0)
for(i=1;i<plen;i++)seed=(seed^(pass.charCodeAt(i)))
p=(seed%plen)
for(i=0;i<ibuf.length;i++){
p++
if(p>=plen)p=0
rval=pass.charCodeAt(p)
if(p==(seed%plen))seed=(pass.charCodeAt(p)^seed)
rval=(pass.charCodeAt(p)^seed)
obuf[n++]=String.fromCharCode(ibuf[i]^rval)
}
return obuf.join('')
}

if(typeof window!='undefined'){LibJavascript.Events.addEvent(window, 'unload', LibJavascript.Events._cleanUp)}
LibJavascript.ToJSValue=function(s){
return "'"+Strtran(Strtran(Strtran(Strtran(s,"\\","\\\\"),"\n","\\n"),"\r","\\r"),"'","\\'")+"'"
}
LibJavascript.IncludeFunction=function(depend,wanted,async,redef){
if(redef||!window[wanted]){
var fetchFrom='../'+wanted+'.js',s,i
if(!(s=document.scripts))s=document.getElementsByTagName('script')
for(i=0;i<s.length;i++)if(Right(s[i].src,Len(depend+'.js'))==depend+'.js')fetchFrom=Left(s[i].src,Len(s[i].src)-Len(depend+'.js'))+wanted+'.js';
function include(j){
var h=j.http,e,m
try{
eval(j.Response())
if(h.status==200)window[wanted]=eval(wanted)
}catch(ex){e=ex}
if(!window[wanted]){
if(h.status==200)m='Errore applicazione dovuto all\'eccezione\n'+e.name+' '+e.message
else m='Problema di connessione all\'URL '+j.Server()+',\nil server ha risposto con il codice '+h.status+'.'+(fetchFrom!=j.Server()?'\n(URL originale '+fetchFrom+')':'')
setTimeout("alert('Il batch "+wanted+" incluso da "+depend+" non puo\\' essere caricato.'+"+LibJavascript.ToJSValue("\n"+m)+")",1)
// if(h.status==200)throw e
}
}
async?new JSURL(fetchFrom,false,include):include(new JSURL(fetchFrom,false))
}
}
LibJavascript.Split=function(p_cS){
var i,t=p_cS.split('\n')
for(i=0;i<t.length;i++)if(Right(t[i],1)=='\r')t[i]=Left(t[i],Len(t[i])-1);
return t
}
LibJavascript.SplitNoConst=function(p_cS,val){ //split in cui non vengono valutate le stringhe costanti (comprese tra ' o ")
if (EmptyString(p_cS)) return [];
var start=p_cS.indexOf("'");
var single=true;
if (p_cS.indexOf('"')>-1 && p_cS.indexOf('"')<start){
start=p_cS.indexOf('"');
single=false;
}
var end=-1;
if (single) end=p_cS.indexOf("'",start+1);
else end=p_cS.indexOf('"',start+1);
var res=p_cS.substring(0,(start!=-1?start:p_cS.length)).split(val)
if (start!=end) {
if (EmptyString(val))
res=res.concat(p_cS.substring(start,end+1));
else
res[res.length-1]=res[res.length-1].concat(p_cS.substring(start,end+1));
var rimanente=p_cS.substring(end+1);
if (!EmptyString(rimanente)){
res2=LibJavascript.SplitNoConst(rimanente,val);
if (Eq(Left(rimanente,Len(val)),val)) {
if (EmptyString(res2[0])) delete res2[0];
}else{
res[res.length-1]=res[res.length-1].concat(res2[0]);
delete res2[0];
}
res=res.concat(res2);
}
}
return res;
}
if(typeof window!='undefined'&&At('SPRegionalSettingsGatherer',''+document.location)==0){
LibJavascript.Events.addEvent(window,'load',function(){
try{
var d=(1.2).toLocaleString().substr(1,1),m=d == ',' ? '.' : ',',i=document.createElement('iframe')
i.frameBorder='no'
i.style.cssText='visibility:hidden;height:0;width:0'
i.setAttribute('toResize','no');
i.src='../servlet/SPRegionalSettingsGatherer/?decsep='+URLenc(d)+'&milsep='+URLenc(m)+'&datef='+URLenc("dd/mm/aaaa")+'&tzo='+URLenc(new Date().getTimezoneOffset())
document.body.appendChild(i)
}catch(e){}
}
)}
function JavaHttpRequest() {
this.open=function(method,url,synch) {
var u=java.net.URL(url)
this.cn=u.openConnection()
this.cn.setDoOutput(true)
this.cn.setUseCaches(false)
this.cn.setAllowUserInteraction(false)
}
this.setRequestHeader=function(header, value ){
this.cn.setRequestProperty(header,value)
}
this.send=function(data) {
var out=java.io.PrintWriter(this.cn.getOutputStream())
if (data!=null){
out.print(data)
}
out.close()
var is=this.cn.getInputStream()
var r=0,i=0
var read=is.read,fromCharCode=String.fromCharCode
this.responseText=[]
while((r=read())!=-1) {
this.responseText[i]=fromCharCode(r)
i++
}//while
this.responseText=this.responseText.join('')
is.close()
}//send
}
function JSURL(srv,p_bNoCache,callback) {
var msg
if(p_bNoCache==null)p_bNoCache=false
this.http=null
//Microsoft KB 208427
if(!p_bNoCache && srv.length>1500 && (IsIE() || IsIE_Mac()))p_bNoCache=true
try{
this.http=new XMLHttpRequest()
}catch(e){
try{
this.http=new ActiveXObject('Msxml2.XMLHTTP')
}catch(f){
try{
this.http=new ActiveXObject('Microsoft.XMLHTTP')
}catch(g){
try{
this.http=new JavaHttpRequest()
}catch(h){
this.http=false
}
}
}
}
if(p_bNoCache){
var p=srv.indexOf('?')
if(p!=-1){
this.prm=srv.substr(p+1)
srv=Left(srv,p)
}else
this.prm=""
this.http.open('POST', srv, callback!=null)
this.http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
}else{
this.http.open('GET', srv, callback!=null)
this.prm=""
}
this.http.setRequestHeader("User-Agent", navigator.userAgent )
if(typeof document != 'undefined' && typeof document.location !='undefined'){
this.http.setRequestHeader("Referer", ''+document.location+'')
}
if(callback){var j=this,h=j.http
h.onreadystatechange=function(){
if(h.readyState==4){h.onreadystatechange=_avoidleak;callback(j)}
}
j.Response=function(){return this.http.responseText}
h.send(j.prm)
}else{this.Response=function(){
try{
return this.__response()
}catch(e){
return ''
}}
}
this.Server=function(){
return srv
}
this.__response=function(){
this.msg=''
this.http.send(this.prm)
try{
this.msg=this.http.getResponseHeader("JSURL-Message")
}catch(e){
}
return this.http.responseText
}
this.ResponseXML=function(){
this.Response()
return this.http.responseXML
}
this.FailedLogin=function(){
return Left(this.msg,8)=='cp_login' ? eval(Substr(this.msg,9)) : ''
}
this.FailedAccess=function(){
return Left(this.msg,9)=='SPServlet' ? eval(Substr(this.msg,10)) : ''
}
}
function _avoidleak(){}
function TrsJavascript(SetValueNameFirst) {
this.p = {}
this.m_bUpdatedFlag = false
this.m_bLoadedFlag = false
this.m_bSetValueNameFirst=SetValueNameFirst==null?false:SetValueNameFirst
this.asString = function() {
var strrep=new Array(),val,vo=this.p,key
if (this.m_bUpdatedFlag) strrep[strrep.length]='#\\m_bUpdated\n';
if (this.m_bLoadedFlag) strrep[strrep.length]='#\\m_bLoaded\n';
for (key in vo) {
val = vo[key]
if (!IsA(val,'C')) val=val.join('\n')
key = this.saveConvert(key, true)
val = this.saveConvert(val, false)
strrep[strrep.length]= key + '=' + val + '\n'
}
return strrep.join('')
}

this.currRow=null

this.setRow = function(i) {
this.SetRow(i)
}
this.SetRow = function(i) {
this.currRow=i+''
this.p["Rows"]=this.currRow
}

this.setValue = function(id,value) {
var sr
if (id=='m_bUpdated' && value=='true') this.m_bUpdatedFlag=true;
if (id=='m_bLoaded' && value=='true') this.m_bLoadedFlag=true;
if(this.m_bSetValueNameFirst){
sr=this.p[id]
if(sr==null) {sr=[];this.p[id]=sr}
sr[sr.length]=this.currRow+"#="+this.saveConvert(value,false)
}else
this.p[this.currRow+"#"+id]=value;
}

this.setDeleted = function(x) {
this.p[x+"#m_nRowStatus"]="3"
}

this.getValue = function(id) {
var v=this.p[this.currRow+"#"+id]
if (Empty(v)) v=""
return v
}

this.reset = function() {
this.p={}
}

this.getRows = function() {
var v=this.p["Rows"]
if (v==null) v=this.p["0#Rows"]
try {
return v - 0
} catch (e) {
return 0
}
}

this.Append = function(s) {
var name="";
var l_prop=new TrsJavascript();
try {
l_prop.BuildProperties(s)
for(var name in l_prop.p) {
if (!IsA(l_prop.p[name],'F'))
this.p[name]=l_prop.p[name]
}
} catch (e) {
}
}


this.BuildProperties = function(s) {
this.reset()
var text=LibJavascript.Split(s),line,i,value,firstChar,nextLine,loppedLine,startIndex,len,keyStart,separatorIndex,currentChar,valueIndex
for(i=0;i<text.length;i++) {
  line=text[i]
  if (line.length > 0) {
    firstChar=line.charAt(0)
    if ((firstChar != '#') && (firstChar != '!')) {
      while (this.continueLine(line)) {
        i++
        nextLine = text[i]
        loppedLine = line.substring(0, line.length-1);
        for(startIndex=0; startIndex<nextLine.length; startIndex++)
          if (this.whiteSpaceChars.indexOf(nextLine.charAt(startIndex)) == -1)
            break;
        nextLine = nextLine.substring(startIndex,nextLine.length);
        line = loppedLine+nextLine
      }
      len=line.length
      for(keyStart=0; keyStart<len; keyStart++) {
        if(this.whiteSpaceChars.indexOf(line.charAt(keyStart)) == -1)
          break;
      }
      if (keyStart == len)
        continue;
      for(separatorIndex=keyStart; separatorIndex<len; separatorIndex++) {
        currentChar=line.charAt(separatorIndex)
        if (currentChar == '\\')
          separatorIndex++
        else if(this.keyValueSeparators.indexOf(currentChar) != -1)
          break
      }
      for (valueIndex=separatorIndex; valueIndex<len; valueIndex++)
        if (this.whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
          break;
      if (valueIndex < len)
        if (this.strictKeyValueSeparators.indexOf(line.charAt(valueIndex)) != -1)
          valueIndex++
      while (valueIndex < len) {
        if (this.whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
          break
        valueIndex++
      }
      key = eval("'"+line.substring(keyStart, separatorIndex).replace(/'/g,"\\'")+"'")
      value = (separatorIndex < len) ? line.substring(valueIndex, len) : ""
      value = eval("'"+value.replace(/'/g,"\\'")+"'")
      this.p[key]=value
    }
  }
}
}

this.continueLine = function (line) {
var slashCount = 0
var index = line.length - 1
while((index >= 0) && (line.charAt(index--) == '\\'))
  slashCount++
return (slashCount % 2 == 1)
}

this.whiteSpaceChars = " \t\r\n\f"
this.keyValueSeparators = "=: \t\r\n\f"
this.strictKeyValueSeparators = "=:"
this.hexDigit = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
this.SP=' '.charCodeAt(0)
this.BSL = '\\'.charCodeAt(0)
this.LF = '\n'.charCodeAt(0)
this.CR = '\r'.charCodeAt(0)
this.TAB = '\t'.charCodeAt(0)
this.FF = '\f'.charCodeAt(0)
this.specialSaveChars=new Array()
this.specialSaveChars['='.charCodeAt(0)]=true
this.specialSaveChars[':'.charCodeAt(0)]=true
this.specialSaveChars['#'.charCodeAt(0)]=true
this.specialSaveChars['!'.charCodeAt(0)]=true

this.saveConvert = function(theString,escapeSpace) {
var len = theString.length,asciiChar,toHex=this.hexDigit,specialSaveChars=this.specialSaveChars,x=0
var theChars=theString.split('')
var SP=this.SP,BSL=this.BSL,TAB=this.TAB,LF=this.LF,CR=this.CR,FF=this.FF
while(x<len) {
asciiChar = theChars[x].charCodeAt(0)
switch(asciiChar) {
case SP:
if (x == 0 || escapeSpace) {
theChars[x]='\\ '
} else {
theChars[x]=' '
}
break;
case BSL:
theChars[x]='\\\\'
break;
case TAB:
theChars[x]='\\t'
break;
case LF:
theChars[x]='\\n'
break;
case CR:
theChars[x]='\\r'
break;
case FF:
theChars[x]='\\f'
break;
default:
if ((asciiChar < 0x0020) || (asciiChar > 0x007e)) {
theChars[x]='\\u'+toHex[(asciiChar >> 12) & 0xF]+toHex[(asciiChar >>  8) & 0xF]+toHex[(asciiChar >>  4) & 0xF]+toHex[ asciiChar & 0xF]
} else {
if (specialSaveChars[asciiChar]) {
theChars[x]='\\'+String.fromCharCode(asciiChar)
}
}
}//switch
x++
}//while
return theChars.join('')
}
}
function BatchJavascript(p_documentloc){
this.rdvar
this.retval
this.errmsg
this.params=new Array()
if(typeof BatchJavascript.documentloc=='undefined' || p_documentloc!=null){
BatchJavascript.documentloc=(p_documentloc==null?location.toString():p_documentloc)
var file2=BatchJavascript.documentloc
if(file2.lastIndexOf('?')!=-1)file2=file2.substring(0,file2.lastIndexOf('?'))
BatchJavascript.m_cExtension=Right(file2,5)==".aspx"?".aspx":""
BatchJavascript.documentloc=file2;
}

this.SetParameterString = function(name,value) {
if (name==null) return;
if (value==null) value="";
this.params[name]=value
}

this.SetParameterNumber=function(name,value) {
if (name==null) return;
this.params[name]=value+''
}
this.SetCallerStringVar=function(name,value) {
if (name==null) return;
if (value==null) value="";
this.params[name]=value
}
this.SetCallerNumberVar=function(name,value) {
if (name==null) return;
this.params[name]=value+''
}
this.GetDoubleVar=function(name) {
if (name==null) return 0;
var r=this.rdvar[name]
if (r==null) return 0;
try {
return r-0
} catch (e) {
return 0;
}
}
this.GetCallerStringVar=function(name) {
if (name==null) return "";
var r=this.rdvar[name]
if (r==null) return "";
return r;
}
this.GetCallerDoubleVar=function(name) {
if (name==null) return 0;
return this.ToDouble(this.rdvar[name])
}
this.GetCallerDateVar=function(name) {
if (name==null) return null;
return LibJavascript.ToDate(this.rdvar[name]);
}
this.GetCallerDateTimeVar=function(name) {
if (name==null) return null;
return LibJavascript.ToDateTime(this.rdvar[name]);
}
this.GetCallerBooleanVar=function(name) {
if (name==null) return false;
return this.ToBoolean(this.rdvar[name]);
}
this.GetString=function() {
return this.retval;
}
this.GetDouble=function() {
return this.ToDouble(this.retval);
}
this.ToDouble=function(p_cNumber) {
if (p_cNumber==null) return 0;
try {
return p_cNumber-0
} catch (e) {
return 0;
}
}
this.GetDate=function() {
return LibJavascript.ToDate(this.retval);
}
this.GetDateTime=function() {
return LibJavascript.ToDateTime(this.retval);
}
this.GetBoolean=function() {
return this.ToBoolean(this.retval);
}
this.ToBoolean=function(p_cBoolean) {
if (p_cBoolean==null) return false;
return "true"==(p_cBoolean.toLowerCase());
}


this.GetFromResponse=function(s) {
var l,stop=false,i=0,p,end,text,line
this.rdvar=new Array()
this.retval=""
this.errmsg=""
text=LibJavascript.Split(s)
for(line=0;line<text.length && !stop;line++) {
l=text[line]
i++
stop=(l=="-->")
end = Right(l,1)==";" ? l.length-1 : l.length
if (Left(l,22)=="Function return value:") {
this.retval=l.substring(22,end)
while(line<text.length && !stop) {
line++
l=text[line]
stop=(LRTrim(l)=='-->')
if (!stop) {
this.retval+='\n'+l
}
}
} else if(Left(l,14)=="Error message:") {
if(this.errmsg!="")this.errmsg+='\n'
this.errmsg+=Substr(l,15,Len(l)-14)
} else if(Left(l,6)=="Fault:") {
this._fault=eval(Substr(l,7,Len(l)-6))
if(!confirm(this._fault[0]))alert(this._fault[1])
}else if(Left(l,3)=="js:"){
p=l.indexOf('=')
this.rdvar[Trim(l.substring(3,p))]=eval(l.substring(p+1,end))
}else if(Left(l,4)=="djs:"){
p=l.indexOf('=')
s=Trim(l.substring(4,p))
this.rdvar[s]=l.substring(p+1,end)
while(line<text.length) {
line++
l=text[line]
this.rdvar[s]+=l+"\n"
if(l=="}")break;
}
} else {
p=l.indexOf('=')
if (p!=-1) {
this.rdvar[Trim(l.substring(0,p))]=Trim(l.substring(p+1,end))
}
}
}
}
this.CallServlet=function(p_cSrvltName) {
try{this.params['m_cID']=m_IDS[p_cSrvltName]}catch(e){}
p_cSrvltName+=BatchJavascript.m_cExtension
try {
var URL=BatchJavascript.documentloc,r,m
URL=URL.substring(0,URL.substring(0,URL.lastIndexOf('/')).lastIndexOf('/'))+"/servlet/"+p_cSrvltName+"?"
for(var name in this.params) {
if(!IsA(this.params[name],'F'))URL=URL+name+"="+URLenc(this.params[name])+"&"
}
this.params=new Array()
j=new JSURL(URL,true)
r=j.__response()
m=j.FailedLogin()
if(Empty(m))m=j.FailedAccess()
if(Empty(m))this.GetFromResponse(r);else alert('Errore dell\'applicazione:la routine '+p_cSrvltName+' ha restituito il messaggio\n'+m)
}catch(e){
return -1
}
return 0
}
}
function WtA(workvar,type){
switch(type){
case 'D':
return FormatDate(workvar,'D')
break
case 'T':
return FormatDateTime(workvar,'D')
break
default:
return workvar.toString()
}
}
function _rargs(a,o){
var r=[],i,h
o.eval('if(!m_Caller){m_Caller=new Caller(window,"w_");m_Caller.__first=true}')
if(a.length>0 && a[0] instanceof Array){
a=a[0]
h=new Caller(o)
for(i=0;i<a.length;i++){
switch(typeof a[i][1]){
case 'string':h.SetString(a[i][0],"C",0,0,a[i][1]);break;
case 'number':h.SetNumber(a[i][0],"N",0,0,a[i][1]);break;
case 'boolean':h.SetLogic(a[i][0],"L",0,0,a[i][1]);break;
case 'object':if(typeof a[i][1].GetContext!='undefined'){
h.SetString(a[i][0],"C",0,0,a[i][1].GetContext())
}else{h.SetDateTime(a[i][0],"T",0,0,a[i][1])};break;}
}
}else for(i=0;i<a.length;i++){
h=a[i]
if(typeof h=='object' && h.cllr)o.eval('m_Caller=new Caller(arguments['+i+'].cllr)');
else try{
h=new Date(h.getFullYear(),h.getMonth(),h.getDate(),h.getHours(),h.getMinutes(),h.getSeconds(),h.getMilliseconds())
}catch(nodate){}
r[r.length]=h
}
return r
}
function Alert(m){return confirm(m)?1:0}

debug={
  log: function(ss,pos){
    var s=document.createElement('div')
    s.innerHTML=(ss+'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    s.style.borderBottom='1px dashed red';
    var l=this._getlogwnd();
    l.appendChild(s);
  },
  clear: function(){
    this._getlogwnd().innerHTML='';
  },
  _getlogwnd: function(pos){//[nesw]
    var d=document.getElementById('wndlog');
    if(!d){
      d=document.createElement('div')
      d.id='wndlog'
      var ds=d.style;
      ds.zIndex='1000';
      ds.position='absolute';
      ds.border='1px solid blue';
      var v= pos && pos.indexOf('n')>-1 ? 'top' : 'bottom';
      var h= pos && pos.indexOf('w')>-1 ? 'left' : 'right';
      ds[v]='0px';
      ds[h]='0px';
      document.body.appendChild(d);
    }
    return d;
  }
}
function SetLocationHref(l,url,fn) {
var p=At('?',url),s=Left(Substr(url,At('/',url)+1),p-1)
if(url.match(/(\?|&)m_cID=/g)==null&&typeof m_IDS!='undefined'&&typeof m_IDS[s]!='undefined')url+=(p>0?'&':'?')+'m_cID='+m_IDS[s]
try {
if(l==null){
if(frames[fn]==null){
if(opener){
 if(opener.SetLocationHref)
  opener.SetLocationHref(null,url,fn)
}
else if(parent.SetLocationHref)
parent.SetLocationHref(null,url,fn)
else
l=parent.frames[fn].location
}else l=frames[fn].location}
if(l)l.href=CompleteWithRegionalSettings(url)
}catch(e){}
}

