var undef=null;
var af={};
var htroot=document.location.href.match(/(.+\/)/);
htroot=htroot[1].replace(/\/cgi-bin/, '');

function AttachEvent(o, e, fn, cap)
{
  if(o.addEventListener)
    o.addEventListener(e, fn, cap ? true : false);
  else
    o.attachEvent('on'+e, fn);
}

function Dumper(o)
{
  if (o==null)
    return "undef";
  if(typeof(o)=="number")
    return o.toString();
  if(typeof(o)=="boolean")
    return o ? "1" : "0";
  if(typeof(o)=="string")
    return "'"+o.replace(/([\\'])/g, "\\$1")+"'";

  if(typeof(o)=="object")
  {
if(o.nodeType)
  return "node";
    if(typeof(o.length)=="number")
    {
      var a=new Array();
      for(var i=0; i<o.length; i++)
        a.push(Dumper(o[i]));
      return "["+a.join(',')+"]";
    }
    else
    {
      var a=new Array();
      for(var k in o)
        a.push(Dumper(k)+"=>"+Dumper(o[k]));
      return "{"+a.join(',')+"}";
    }
  }
  return "unknown"
}

function Change3state(element,eid)
{
  var e=document.getElementById(eid);
  var state=parseInt(e.value);  //element.getAttribute('c3state')
  state=state>1 ? 0 : state+1;
  element.src=element.src.replace(/\d\.gif$/, (state+1)+".gif");
  e.value=state;
}

function GetElements(e)
{
  var uenum=e.udata.data;
  var ulinks=e.udata.links;
  for(var j=0; j<ulinks.length; ++j)
  {
    var l=ulinks[j];
/*
    var ind=l.selectedIndex;
    var s=l.options[ind];
    s=s.value;
*/
    var s=l.value;
    var ue=uenum[s];
    if(!ue)
      ue=[];

    if(l.udata.type=='tree')
    {
      var el=l.udata.map[s];
      var p=el.parent;
      while(p)
      {
        var d=p.data;
        p=p.parent;
        if(!d)
          continue;
        var s=d[1];
        var u=uenum[s];
        if(!u)
          u=[];
        ue=u.concat(ue);
      }

      if(0)
      {
        var p=el.childs;

        function GetChilds(p, uenum)
        {
          if(!p.childs)
            return [];

          var ue=[];
          for(var i=0; i<p.childs.length; ++i)
          {
            var e=p.childs[i];
            var u=uenum[e.data[1]];
            if(!u)
              u=[];
            ue=ue.concat(u);
            u=GetChilds(e, uenum);
            ue=ue.concat(u);
          }
          return ue;
        }
        var u=GetChilds(el, uenum);
        ue=ue.concat(u);
      }
    }
    uenum=ue;
  }
  return uenum;
}

function InitCombo(e)
{
  var uenum=GetElements(e);

  if(e.udata.imp)
    uenum.unshift([0,e.udata.imp]);

  if(window.opera)    // Opera fix
  {
    var o="";
    for(var j=0; j<uenum.length; ++j)
    {
      var it=uenum[j];
      var s="";
      var name=it.length<2 ? it[0] : it[1];
      if(it[0]==e.udata.def || (j==0 && !e.udata.def))
        s="selected";
      o+="<option value='"+it[0]+"' "+s+">"+name+"</option>";
    }
    e.innerHTML=o;
  }
  else
  {
    var col=e.options;
    while(col.length>0)
      e.remove(0);

    for(var j=0; j<uenum.length; ++j)
    {
      var it=uenum[j];
      var opt=document.createElement('OPTION');
      opt.value=it[0];
      opt.text=it.length<2 ? it[0] : it[1];
      if(it[0]==e.udata.def || (j==0 && !e.udata.def))
        opt.selected=true;
      col.add(opt);
    }
  }
}
function ReadUnion(e)
{
  e=document.getElementById(e);
  var il=e.udata.inp.getElementsByTagName('INPUT');
  var a=[];
  for(var i=0; i<il.length; ++i)
  {
    var vl=il[i].id.split('_');
    var v=vl.pop();
    if(il[i].checked)
      a.push(v);
    if(e.udata.type=='union3')
    {
      var f=parseInt(il[i].value);
      if(f!=2)
        a.push(f ? v : "!"+v);
    }
  }
  a=a.join(',');
  e.value=a;
}
function InitUnion(e)
{
  var uenum=GetElements(e);

  var def=e.udata.def.split(',');
  var d={};
  for(var i=0; i<def.length; ++i)
  {
    var k=def[i];
    var v=1;
    var r=k.match(/^!(\d+)$/);
    if(r)
    {
      k=r[1];
      v=0;
    }
    d[k]=v;
  }

  var html="";
  for(var j=0; j<uenum.length; ++j)
  {
    var it=uenum[j];

    var id=e.id+"_"+it[0];
    if(e.udata.type=='union')
    {
      var c=d[it[0]] ? "checked" : "";
      html+="<nobr><input id='"+id+"' type='checkbox' onchange='ReadUnion(\""+e.id+"\")' "+c+"><label for='"+id+"'>&nbsp;"+it[1]+"</label></nobr><br>";
    }
    else
    {
      var c=d[it[0]];
      if(typeof(c)=="undefined")
        c=2;
      html+="<input id='"+id+"' type='hidden' value='"+c+"'><img onclick='Change3state(this,\""+id+"\");ReadUnion(\""+e.id+"\")' src='"+htroot+"check"+(c+1)+".gif'><span>&nbsp;"+it[1]+"</span><br>";
    }
  }
  e.udata.inp.innerHTML=html;
}
function InitTree(e)
{
  function Set(id)
  {
    var el=e.udata.map[id];

    if(!el)
      el=e.udata.data.childs[0];
    id=el.data[1];

    e.value=id;
    if(e.onchange)
      e.onchange();

    var old=e.udata.sel;
    if(old)
    {
      var cn=old.node.className.split(' ');
      old.node.className=cn[0];
    }
    el.node.className+=" atselected";
    e.udata.sel=el;

    var stat=[];
    while(el)
    {
      if(el.data)
        stat.unshift(el.data[0]);
      el=el.parent;
      if(el && el.childsNode)
        el.childsNode.style.display="block";
    }
    e.udata.stat.value=stat.join(' / ');
  }
  function PrintTree(t, parent)
  {
    var childs="";
    var n2=t.data ? document.createElement('DIV') : "";
    t.parent=parent;
    t.node=n2;

    if(t.childs)
    {
      childs=document.createElement('DIV');
      for(var i=0; i<t.childs.length; ++i)
      {
        var el=PrintTree(t.childs[i], t);
        childs.appendChild(el);
      }
    }
    if(!t.data)
      return childs;

    t.childsNode=childs;

    e.udata.map[t.data[1]]=t;
    n2.innerHTML=t.data[0];

    var n=document.createElement('DIV');
    n.appendChild(n2);

    n2.onclick=function()
    {
      if(childs)
      {
        if(childs.style.display=="block")
          childs.style.display="none";
        else
          childs.style.display="block";
      }
      Set(t.data[1]);
    }
    if(childs)
    {
      n2.className="atnode";
      childs.style.paddingLeft="10px";
      childs.style.display="none";
      n.appendChild(childs);
    }
    else
      n2.className="atleaf";

    return n;
  }

  var n=document.createElement('INPUT');
  n.type='text';
  n.readOnly=true;
  n.style.width="100%";

  e.udata.stat=n;
  e.udata.map={};

  if(e.udata.imp)
    e.udata.data.childs.unshift({'data':[e.udata.imp, 0]});

  var n2=PrintTree(e.udata.data);
  n2.style.display="none";

  n.onclick=function()
  {
    var s=n2.style;
    if(s.display=="block")
      s.display="none";
    else
      s.display="block";
  }
  e.udata.inp.appendChild(n);


  Set(e.udata.def);

  e.udata.inp.appendChild(n2);
}

var hvalidate={'mandatory':'.', 'int':'^\\d+$', 'float':'^\\d+([.,])?(\\d+)?$', 'email':'^[\\w-.]+@[\\w-]+\\.[\\w-.]+$', 'date':'^(\\d\\d?)\\.(\\d\\d?)\\.(\\d\\d\\d\\d)$'};
function ValidateForm(form)
{
  for(var i=0; i<form.elements.length; ++i)
  {
    var e=form.elements[i];
    var validate=e.getAttribute('uitype');
    if(!validate)
      continue;

    var uiname=e.getAttribute('uiname');
    var vl=validate.split(',');
    for(var j=0; j<vl.length; ++j)
    {
      var v=hvalidate[vl[j]];
      if(!v)
        continue;
      var re=new RegExp(v, "i");

      var msg="";
      if(vl[j]=='mandatory')
      {
        if(e.value=="")
          msg="Не заполнено поле '";
      }
      else if(e.value!="" && !re.test(e.value))
        msg="Неправильно заполнено поле '";
      if(msg!="")
      {
        alert(msg+uiname+"'");
        e.focus();
        return false;
      }
    }
  }
  return true;
}

function findPosX(obj){
  var curleft = 0;
  if (obj.offsetParent){
    while (obj.offsetParent){
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  }
  return curleft;
}

function findPosY(obj){
  var curtop = 0;
  if (obj.offsetParent){
    while (obj.offsetParent){
      curtop += obj.offsetTop
      obj = obj.offsetParent;
    }
  }
  return curtop;
}

function ChangeInpType(id)
{
  var type="text";
  if(id.type==type)
    type="file";

  if(id.outerHTML)
  {
    var re1=/type=["']?[^"' ]+["']?/i;
    var re2=/<INPUT /i;
    var s=id.outerHTML.replace(re1,"");
    s=s.replace(re2,'<INPUT type="'+type+'" ');
    id.outerHTML=s;
  }
  else
    id.type=type;
}

function cGetValue(s, Name)
{
  if(!s)
    return null;
  var re=new RegExp(Name+' *= *([^;]+);? *');
  var m=s.match(re);
  return m ? unescape(m[1]) : null;
}
function cDelValue(s, Name)
{
  if(!s)
    return null;
  var re=new RegExp(Name+' *= *[^;]+;? *');
  return s.replace(re,'');
}
function cSetValue(s, Name, Val)
{
  s=cDelValue(s, Name);
  return Name+"="+escape(Val)+";"+s;
}

function GetCookie(Name1, Name2)
{
  return cGetValue(cGetValue(document.cookie, Name1), Name2);
}
function SetCookie(Name1, Name2, Val)
{
  var s=cSetValue(cGetValue(document.cookie, Name1), Name2, Val)

  var expir=new Date();
  expir.setTime(expir.getTime() + (1000*24*60*60*1000));

  document.cookie=Name1+"="+escape(s)+"; expires="+expir.toGMTString();
}

document.onclick=function(e)
{
  var elem;
  if(!e)
  {
    e=window.event;
    elem=e.srcElement;
  }
  else
  {
    elem=e.target;
  }
  if(!e.shiftKey || elem.tagName!="INPUT" || elem.type!="checkbox")
    return;
  var state=elem.checked;

  var cell=elem.offsetParent;
  if(cell.tagName!="TD")
    return;
  var table=cell.offsetParent;
  while(table.tagName!="TABLE")
    table=table.offsetParent;

  if(table.id!="rtable")
    return;

  var cindex=0;
  while(cell.previousSibling)
  {
    ++cindex;
    cell=cell.previousSibling;
  }

  var rl=table.rows;

  for(var i=0; i<rl.length; ++i)
  {
    var c=rl[i].childNodes[cindex];
    var il=c.childNodes;
    for(var j=0; j<il.length; ++j)
    {
      if(il[j].tagName=="INPUT" && il[j].type=="checkbox")
      {
        il[j].checked=state;
      }
    }
  }
}

AttachEvent(window, 'load', function()
{
  for(var fid in af)
  {
    for(var field in af[fid])
    {
      var f=af[fid][field];
      var e=document.getElementById("id_"+fid+"_"+field);
      var links=[];
      for(var i=0; i<f.links.length; ++i)
      {
        var l=document.getElementById("id_"+fid+"_"+f.links[i]);
        links.push(l);
        l.udata.rlinks.push(e);
      }
      f.links=links;
      e.udata=f;

      if(f.type=='combo' || f.type=='union' || f.type=='union3' || f.type=='tree')
      {
        if(f.type=='combo')
          f.Init=InitCombo;
        else
        {
          f.Init=f.type=='tree' ? InitTree : InitUnion;

          var inp=document.createElement('DIV');
          inp.style.textAlign='left';
          f.inp=inp;
          e.parentNode.insertBefore(inp, e);
        }

        e.onchange=function()
        {
          for(var f=0; f<this.udata.rlinks.length; ++f)
          {
            var r=this.udata.rlinks[f];
            r.udata.Init(r);
          }
        }
      }
      f.Init(e);
    }
  }
});


function AddElement(type, fid, field, data, links, def, imp)
{
  if(!af[fid])
    af[fid]={};
  if(!links)
    links=[];
  if(!def)
    def="";

  af[fid][field]={'type':type, 'data':data, 'links':links, 'rlinks':[], 'def':def, 'imp':imp};
  if(type=='combo')
    document.write('<select name="'+field+'" id="id_'+fid+'_'+field+'" style="width:100%"></select>');
  if(type=='union' || type=='union3' || type=='tree')
    document.write('<input type="hidden" name="'+field+'" id="id_'+fid+'_'+field+'">');
}

function InsertFlash(swf, width, height, transparent)
{
  var t1=transparent ? '<param name="wmode" value="transparent"/>' : "";
  var t2=transparent ? 'wmode="transparent"' : "";
document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="'+width+'" height="'+height+'">\
  <param name="movie" value="'+swf+'">\
  <param name="quality" value="high">\
  <param name="play" value="true">\
  '+t1+'\
  <PARAM name="wmode" value="transparent"/>\
 <embed src="'+swf+'" '+t2+' width="'+width+'" height="'+height+'" quality="high" play="true" loop="true"></embed>\
</object>\
');
}
