// as_jsfunclib.js: useful javascript function set,
// written / assembled by Alexander Selifonov <alex [at] selifan.ru>
// V 1.010.122  last change: 01.07.2008
var noajax = 'No XmlHttpRequest in Your browser !';
var postcont = 'application/x-www-form-urlencoded; charset=UTF-8';
var HttpRequestExist = true;

function NewXMLHttpRequest() {
  if(!HttpRequestExist) return false;
  var xmlhttplocal;
  try {
    xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")
  } catch (e)
  {
    try {
      xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")
    }
    catch (E) {
        xmlhttplocal=false;
    }
  }

  if (!xmlhttplocal && typeof XMLHttpRequest!='undefined') {
    try { var xmlhttplocal = new XMLHttpRequest(); }
    catch (e) { xmlhttplocal = HttpRequestExist = false; }
  }
  return(xmlhttplocal);
}

function SetFormValue(felem,newval,fireonchange) {
  var itmp;
//  var dobj;
  if(typeof(felem)=="string") felem=eval(felem);
//  else dobj=felem;
  if(typeof(felem)!="object") { return; }
  switch(felem.type) {
  case 'select-one':
    for(itmp=0;itmp<felem.options.length;itmp++) {
      if(felem.options[itmp].value==newval) {felem.selectedIndex=itmp; break; }
    }
    break;
  case 'checkbox':
    felem.checked = (newval>0);
    break;
  default:
    felem.value = newval;
    break;
  }
  if(!!fireonchange) {
    if(felem.onchange) { felem.onchange(); }
    if(felem.onclick) felem.onclick();
  }
}

function GetFormValue(felem) {
  ret = '';
  var itmp;
  if(typeof(felem)=="string") felem=eval(felem);
  if(typeof(felem)!="object") return ret;
  switch(felem.type) {
  case 'select-one':
    itmp=felem.selectedIndex;
    if(itmp>=0) ret = felem.options[itmp].value;
    break;
  case 'checkbox':
    ret = felem.checked?1:0;
    break;
  default:
    ret = felem.value;
    break;
  }
  return ret;
}
function ComputeParamString(frmname, skipempty, fldlist)
{ // compute param string with all "frmname" form values
    var theForm;
    if(isNaN(skipempty)) skipempty=false;
    if(typeof(frmname)=='object') theForm=frmname;
    else theForm=eval("window.document."+frmname);
    var els = theForm.elements;
    var retval = "";
    for(i=0; i<els.length; i++)
    { //<2>
        vname = els[i].name;
        if(vname=='') continue;
        if(typeof(fldlist)=='object' && !IsInArray(fldlist,vname)) continue;
        oneval = "";
        t = els[i].type;
        switch(t)
        { //<3>
           case "select-one" :
               var selobj =els[i];
               var nIndex = selobj.selectedIndex;
               if (nIndex >=0) oneval = selobj.options[nIndex].value;
               break;
           case "text": case "button": case "textarea": case 'password': case "hidden": case 'submit':
               if(els[i].value != "")
                 oneval = els[i].value;
               break;
           case "checkbox":
/*               if(vname =='dago_limit') {
               alert(vname+ ' type: '+ typeof(els[i]) );
               alert('value: '+els[i].value + ' length: '+ els[i].length);
               }
*/
               oneval = (els[i].checked ? "1":"0");
               break;
           case "radio":
               if(els[i].value != "" && els[i].checked)
                 oneval = els[i].value;
               break;
           default:
//              alert(vname+': not supported control: '+els[i].type);
               oneval = els[i].value;
              break;
        } //<3>
        if((oneval!='' && oneval!=0) || (!skipempty)) {
           if (retval != "") retval = retval + "&";
           retval = retval+vname+'='+encodeURIComponent(oneval);
        }
    } //<2>
    return retval;
} // ComputeParamString()

function SelectBoxSet(frm,objname, val){
  var obj;
  elems = '';
  if(typeof frm=='string') eval("obj=document."+frm+"."+objname);
  else eval('obj=frm.'+objname);
  if(!isNaN(obj.selectedIndex)) //alert('SelectBoxSet error: '+frm+'.'+objname+" - not a selectbox !");
  {
    for(kk=0; kk<obj.options.length; kk++) {
      if (obj.options[kk].value==val) { obj.selectedIndex = kk; return; }
    }
  }
}
function FindInSelectBox(frm,objname,val){
  var obj;
  if(typeof frm=='string') eval("obj=document."+frm+"."+objname);
  else eval('obj=frm.'+objname);
  if(isNaN(obj.selectedIndex)) return -1;
  var kk; var vlow = val.toLowerCase();
  for(kk=0; kk<obj.options.length; kk++) {
    if (obj.options[kk].text.toLowerCase()==vlow) return kk;
  }
  return -1;
}
function DateRepair(sparam,fmt, delim)
{ // make input date well formatted: dd.mm.yyyy (if fmt='dmy')
  if(!fmt) fmt='dmy'; // default format - dd.mm.yyyy
  if(!delim) delim='.'; // default delimiter
  var sdate = (typeof(sparam)=='string' ? sparam : sparam.value);
  if(sdate.length<1) return '';
  var spltd = sdate.split(/[\\\/.-]/);
  var posm = fmt.indexOf("m"); var posd=fmt.indexOf("d"); var posy=fmt.indexOf("y");
  var now = new Date();

  if(posm<0 || posd<0 || posy<0) { alert('DateRepair: wrong fmt - '+fmt);return ''}
  if(spltd.length>1) {
    if(spltd[0]=='') spltd[0]=0;
    if(spltd[1]=='') spltd[1]=0;
    if(!spltd[2] || spltd[2]=='') spltd[2]=0;
  }

  else if(sdate.length<=2) { //only first 2 chars entered
    spltd[0]=sdate;
    if(fmt=='dmy') { spltd[1]=1+now.getMonth(); spltd[2]=now.getFullYear(); }
    else if(fmt=='mdy') { spltd[1]=now.getDay(); spltd[2]=now.getFullYear(); }
    else if(fmt=='ymd')  { spltd[1]=1+now.getMonth(); spltd[2]=now.getDay(); }
    else if(fmt=='ydm')  { spltd[1]=now.getDay(); spltd[2]=1+now.getMonth(); }
  }
  else if(sdate.length<=4) { // case of ddmm or mmdd
    spltd[0]=sdate.substring(0,2);
    spltd[1]=sdate.substring(2);
    if(fmt=='dmy' || fmt=='mdy') { spltd[2]=now.getFullYear(); }
  }
  else if(sdate.length<=6) { //ddmmyy, mmddyy, yymmdd ... - case of 2-digit year, no delimiters
    spltd[0]=sdate.substring(0,2);
    spltd[1]=sdate.substring(2,4);
    spltd[2]=sdate.substring(4);
  }
  spltd[0]=parseInt(spltd[0]-0); spltd[1]=parseInt(spltd[1]-0);spltd[2]=parseInt(spltd[2]-0);
  if(isNaN(spltd[0])) spltd[0]=0;
  if(isNaN(spltd[1])) spltd[1]=0;
  if(isNaN(spltd[2])) spltd[2]=0;
  if(spltd[posd]<1) {
    if(typeof(sparam)=='object') { sparam.value = ""; return false; }
    return "";
  }
  if(spltd[posm]<1) spltd[posm]=1+now.getMonth(); else if (spltd[posm]>12) spltd[posm]=12;
  if(spltd[posy]<1) spltd[posy]=now.getYear();
  else if (spltd[posy]<=15) spltd[posy]=spltd[posy]+2000; //'.15' =>'2015'
  else if (spltd[posy]<=99) spltd[posy]=spltd[posy]+1900; //'.96' =>'1996'
  delete now;
  // auto-correcting wrong month and day :
  if(spltd[posm]>12) spltd[posm]=12; else if(spltd[posm]<1) spltd[posm]=1;
  maxday = 31;
  if(spltd[posm]==4 || spltd[posm]==6 || spltd[posm]==9 || spltd[posm]==11) maxday=30;
  if(spltd[posm]==2) maxday = (spltd[posy]%4)? 28:29;
  if(spltd[posd]>maxday) spltd[posd]=maxday; else if(spltd[posd]<1) spltd[posd]=1;
  if(spltd[posd]<10) spltd[posd] = "0"+spltd[posd];
  if(spltd[posm]<10) spltd[posm] = "0"+spltd[posm];
  spltd['d']=spltd[posd]; spltd['m']=spltd[posm]; spltd['y']=spltd[posy];
  var ret = "";
  for(kfmt=0;kfmt<3;kfmt++) { ret += (ret==""?"":delim)+spltd[fmt.substring(kfmt,kfmt+1)]; }
  if(typeof(sparam)=='object') { sparam.value = ret; return false; }
  return ret;
}
// DayDiff from A1ien51, http://www.pascarello.com
function DaysDiff(dy1,mo1,yr1, dy2, mo2, yr2){
//  var _targetDate = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0);
  var Date1 = Date.UTC(yr1, mo1 - 1, dy1);
  var Date2 = Date.UTC(yr2,mo2 - 1, dy2);
  DateDiff = Math.round((Date2 - Date1)/(24*60*60*1000));
  return(DateDiff);
}
function DaysDiffDMY(dmobj1,dmobj2) {
  var dmy1 = (typeof(dmobj1)=='object')? dmobj1.value : dmobj1;
  var dmy2 = (typeof(dmobj2)=='object')? dmobj2.value : dmobj2;
  var da1 = dmy1.split(/[\\\/.-]/);
  var da2 = dmy2.split(/[\\\/.-]/);
  if(da1.length<3 || da2.length<3) return false;
  return DaysDiff(da1[0],da1[1],da1[2],da2[0],da2[1],da2[2]);
}
function NumberRepair(sparam) {
  var sdata = (typeof(sparam)=='string' ? sparam : sparam.value);
  var ret = sdata.replace(',','.');
  ret = parseFloat(ret);
  if(isNaN(ret) || ret=='') ret = '';
  if(typeof(sparam)=='object') { sparam.value = ret; return; }
  return ret;
}
function AddToDate(sdate, years, months, days)
{ // sdate must be in 'dd.mm.yyyy' format !!!
   var mlen = [0,31,28,31,30,31,30,31,31,30,31,30,31];
   var delem = sdate.split(/[\\\/.-]/);
   if(delem.length<3) return '';
   var nday = (delem[0]-0);
   var nmon = (delem[1]-0);
   var nyear = (delem[2]-0);
   if(months>12 || months<-12) {
      years += Math.floor(months/12);
      months = months % 12;
   }
   if(years!=0) nyear +=years;
   if(months>0) {
       nmon += months;
       while(nmon >12) {
         nyear++;
         nmon -= 12;
       }
   }
   else if(months<0) {
       nmon += months;
       while(nmon <-12) {
         nyear--;
         nmon += 12;
       }
   }
   var nmlen = ((nyear % 4==0) && nmon==2) ? 29 : mlen[nmon];
   if(days!=0) {
          nday+=days;
          if(nday > nmlen) {
            nday -= nmlen;
            nmon++;
            if(nmon>12) { nmon=1; nyear++;};
          }
          else if(nday<=0) {
            nmon--;
            if(nmon<=0) { nmon=12; nyear--; }
          }
          nmlen = ((nyear % 4==0) && nmon==2) ? 29 : mlen[nmon];
          if(nday<=0) nday += nmlen;
   }
   if(nday>nmlen) nday = nmlen;

   if(nday<10) nday = '0'+nday;
   if(nmon<10) nmon = '0'+nmon;
   return (nday+'.'+nmon+'.'+nyear);
}
// returns "rounded" years diff between two "dd.mm.yyyy" dates
function RoundedYearsDiff(dt1,dt2,bordermon) {
 da1 = dt1.split(/[\\\/.-]/);
 da2 = dt2.split(/[\\\/.-]/);
 var years = parseInt(parseFloat(da2[2]))-parseInt(parseFloat(da1[2]));
 var months = parseInt(parseFloat(da2[1]))-parseInt(parseFloat(da1[1]));
 var days = parseInt(parseFloat(da2[0]))-parseInt(parseFloat(da1[0]));
 if(months<0) { years--; months +=12; }
 if(days<0) {
   months--;
   if(months<0) { years--; months +=12; }
 }
 if(months>=(bordermon-0)) years++;
 return years;
}
// compares two 'dd.mm.yyyy' strings as dates
function CompareDates(dt1,dt2) {
  var da1 = dt1.split(/[\\\/.-]/);
  var da2 = dt2.split(/[\\\/.-]/);
  if(da1.length<3 || da2.length<3) return false;
  var nd1=da1[2]*10000+da1[1]*100+da1[0];
  var nd2=da2[2]*10000+da2[1]*100+da2[0];
  if(nd1>nd2) ret= 1;
  else if(nd1<nd2) ret=-1;
  else ret=0;
//  alert("CompareDates debug: "+dt1+" ^ "+dt2+" = "+ret); //debug
  return ret;
}

function IsInArray(arr, val){
  for(lp=0; lp<arr.length;lp++){ if(arr[lp]==val) return true; }
  return false;
}

function FormatInteger( integer )
{ // author:
  var result = '';
  var pattern = '###,###,###,###';
  if(typeof(integer)!='string') integer = integer+'';
  integerIndex = integer.length - 1;
  patternIndex = pattern.length - 1;
  while ( (integerIndex >= 0) && (patternIndex >= 0) )
  {
    var digit = integer.charAt( integerIndex );
    integerIndex--;
    // Skip non-digits from the source integer (eradicate current formatting).
    if ( (digit < '0') || (digit > '9') )  continue;

    // Got a digit from the integer, now plug it into the pattern.
    while ( patternIndex >= 0 )
    {
      var patternChar = pattern.charAt( patternIndex );
      patternIndex--;
      // Substitute digits for '#' chars, treat other chars literally.
      if ( patternChar == '#' )
      {
        result = digit + result;
        break;
      }
      else { result = patternChar + result; }
    }
  }
  return result;
}

/* useful functions from Dustin Diaz, http://www.dustindiaz.com/top-ten-javascript/
*/

/* grab Elements from the DOM by className */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}
/* get, set, and delete cookies */
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function asGetObj(name){
 if (document.getElementById) {
   return document.getElementById(name);
 }
 else if (document.all) {
   return document.all[name];
 }
 else if (document.layers)
 {
   if (document.layers[name]) {
     return document.layers[name];
     this.style = document.layers[name];
   }
   else { return document.layers.testP.layers[name]; }
 }
 return null;
}
function round_2dec(num) { // rounds to 2 decimal digits
  var rrr = 0.01*Math.round(0.01*Math.round(num*10000)) + '';
  if (rrr.indexOf(".") != -1) rrr = rrr.substring(0,rrr.indexOf(".")+4);
  rrr -= 0;
  return rrr;
}

function getObjPos(oElement) {
  var ret = [0,0];
  while( oElement != null ) {
    ret[0] +=oElement.offsetLeft;
    ret[1] +=oElement.offsetTop;
    oElement = oElement.offsetParent;
  }
  return ret;
}

