<?php

// IBExpertWebForms
// copyright  ©  2006-2008 Holger Klemt hklemt@ibexpert.biz
// www.ibexpert.com


  class TComponent extends TObject
  {
    var $Template;
    var $Components;
    var $Owner;

    function __construct($owner=null)
    {
      parent::__construct($owner);

      $this->Owner=$owner;
      $this->Components=new TComponents($this);

      if($owner)
        if($owner->Components)
          $owner->Components->Add($this);


      $this->EventJS['mouse']=<<<END

        function {name}{event}(element)
        {
          if({isEvent})
          if(!document.getElementById('{NAME}').disabled)
          {
            var o=document.getElementById('o{NAME}');

            {name}MouseX=MouseX-GetLeft(o,0);
            {name}MouseY=MouseY-GetTop(o,0);

            var input='';
            {input}

            {server}.Request("object={name}&action={event}"+input);
          }
        }
END;

      $this->EventJS['key']=<<<END

        function {name}{event}(element)
        {
          if({isEvent})
          if(!document.getElementById('{NAME}').disabled)
          {
            var o=document.getElementById('o{NAME}');

            {name}MouseX=MouseX-GetLeft(o,0);
            {name}MouseY=MouseY-GetTop(o,0);

            var input='';
            {input}

            {server}.Request("object={name}&action={event}"+input);
          }
        }
END;

      $this->EventJS['component']=<<<END

        function {name}{event}(element)
        {
          if({isEvent})
          {
            //var o=document.getElementById('o{NAME}');

            {name}MouseX=MouseX;
            {name}MouseY=MouseY;
            var input='';
            {input}

            {server}.Request("object={name}&action={event}"+input);
          }
        }
END;


      $i=0;
      if($this->Class=="TTimer" || $this->Class=="TWFTimer")
      {
        $this->Events[$i]['js']=$this->EventJS['component'];
        $this->Events[$i++]['event']="OnTimer";
      }
      else if($this->Class=="TWFComboBox")
      {
        $this->Events[$i]['js']=$this->EventJS['component'];
        $this->Events[$i++]['event']="OnChange";

        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnClick";
        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnDblClick";
        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnMouseMove";
        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnExit";
        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnEnter";

        $this->Events[$i]['js']=$this->EventJS['key'];
        $this->Events[$i++]['event']="OnKeyDown";
        $this->Events[$i]['js']=$this->EventJS['key'];
        $this->Events[$i++]['event']="OnKeyPress";
        $this->Events[$i]['js']=$this->EventJS['key'];
        $this->Events[$i++]['event']="OnKeyUp";
      }
      else
      {
        //echo $this->Class."<br>";

        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnClick";
        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnDblClick";
        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnMouseMove";
        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnMouseUp";
        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnMouseDown";
        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnExit";
        $this->Events[$i]['js']=$this->EventJS['mouse'];
        $this->Events[$i++]['event']="OnEnter";

        $this->Events[$i]['js']=$this->EventJS['key'];
        $this->Events[$i++]['event']="OnChange";
        $this->Events[$i]['js']=$this->EventJS['key'];
        $this->Events[$i++]['event']="OnKeyDown";
        $this->Events[$i]['js']=$this->EventJS['key'];
        $this->Events[$i++]['event']="OnKeyPress";
        $this->Events[$i]['js']=$this->EventJS['key'];
        $this->Events[$i++]['event']="OnKeyUp";
      }

    }

    function Init()
    {
      parent::Init();

      if(!$this->db)
      {
        /*
        $database=$this->GetComponentByName("Main");
        if($database)
        {
          $database->Init();
          $this->db=$database->db;

          $main_db=$this->db;
        }
        else
          die("mindestends eine Datenbank-Komponente mit den Namen \"Main\" muss vorhanden sein");
        */
      }

      if($this->db)
      {
        //echo $this->Class."<br>";

        for($i=0;$i<count($this->Events);$i++)
        {
          $property=$this->Events[$i]['event'];

          eval('$v=$this->'.$property.';');

          $this->$property=$v;

          if($v)
          {
            $this->isEvents['isEvent'.$property]=1;
            //echo "1:".$property."<br>";

            eval('$this->is'.$this->Name.$property.'=1;');
            $sql="select p.* ".
                       "from rdb\$procedure_parameters p ".
                       "where p.rdb\$procedure_name='".strtoupper($v)."' ".
                       "  and p.rdb\$parameter_type=0 ".
                       "order by p.rdb\$parameter_number";

            $this->db->query($sql);
            while($row=$this->db->fetch())
            {
              //echo $row['RDB$PARAMETER_NAME']."<br>";
              eval('$this->'.$property.'Input[count($this->'.$property.'Input)]=$row[\'RDB$PARAMETER_NAME\'];');
            }
          }
        }
      }
    }

    function GetRoot()
    {
      $owner=$this->Owner;

      if($owner)
      {
        while($owner)
        {
          $bowner=$owner;
          $owner=$owner->Owner;
        }

        $owner=$bowner;
      }
      else
        $owner=$this;

      return $owner;
    }

    function GetChilds($class_name)
    {
      $owner=$this->GetRoot();

      return $this->ParseComponents($owner,"childs",strtoupper($class_name));
    }

    function GetComponentByName($name)
    {
      $owner=$this->GetRoot();

      return $this->ParseComponents($owner,"search",strtoupper($name));
    }

    function dout($f,$s)
    {
      /*
      $fh=fopen("debug/".$f.".txt","w");
      fwrite($fh,$s);
      fclose($fh);
      */
    }

    function ParseComponents($root,$type,$value="",$ret=null)
    {
      if(!$root)
        $root=$this->GetRoot();

      for($i=0;$i<$root->Components->Length;$i++)
      {
        if($type=="search" && strtoupper($root->Components->Components[$i]->Name)==$value)
          $ret=$root->Components->Components[$i];
        else if($type=="Call")
        {
          $arr=explode(";",$value);

          if(method_exists($root->Components->Components[$i],$arr[0]))
          {
            $arr[1]=str_replace("{name}",$root->Components->Components[$i]->Name,$arr[1]);
            $eval_str='$ret=$root->Components->Components[$i]->'.$arr[0].'('.$arr[1].');';
            eval($eval_str);
          }
        }
        else if($type=="childs" && strtoupper($root->Components->Components[$i]->Class)==$value)
        {
          if(!$ret)
            $ret=array();

          $ret[count($ret)]=$root->Components->Components[$i];
        }
        else if($type=="init")
        {
          if(method_exists($root->Components->Components[$i],"Init"))
            $ret=$root->Components->Components[$i]->Init();
        }
        else if($type=="FindByProperty")
        {
            //echo $value;
          $arr=explode(";",$value);

          //echo $arr[0]."/".$arr[1]."<br>";
          $eval_str='$v=$root->Components->Components[$i]->'.$arr[0].';';
          //echo $eval_str."<br>";

          //echo $root->Components->Components[$i]->DataSet."<hr>";

          eval($eval_str);
          if($v==$arr[1])
          {
            if(!$ret)
              $ret=array();

            $ret[count($ret)]=$root->Components->Components[$i];
          }
        }

        $ret=$this->ParseComponents($root->Components->Components[$i],$type,$value,$ret);
      }

      return $ret;
    }

    function _call_event_proc($proc,$vInput,$main=false)
    {
      $sql="select count(*) anz from rdb\$procedures where rdb\$procedure_name='".$proc."'";
      $this->db->queryandfetch($sql);

      if($this->db->Row['ANZ']==1)
      {
          $sql="select count(*) anz ".
               "from rdb\$procedure_parameters ".
               "where rdb\$procedure_name='".$proc."' ".
               "  and rdb\$parameter_type=1";

          $this->db->queryandfetch($sql);

          $isSelect=false;
          if($this->db->Row['ANZ']=="0")
            $sql="execute procedure ".$proc;
          else
          {
            $isSelect=true;
            $sql="select * from ".$proc;
          }

          $params="";

          if($main)
          {
            $this->db2=new PDB();
            $psql="select rdb\$parameter_name params ".
                  "from rdb\$procedure_parameters ".
                  "where rdb\$procedure_name='".$proc."' ".
                  "  and rdb\$parameter_type=0";
            $this->db2->query($psql);
            while($this->db2->fetch())
            {
              if(trim($this->db2->Row['PARAMS'])=="SESSION_ID")
              {
                if($params)
                  $params.=",";
                $params.="'".session_id()."'";
              }
              else if(trim($this->db2->Row['PARAMS'])=="REMOTE_ADDR")
              {
                if($params)
                  $params.=",";
                $params.="'".$_SERVER['REMOTE_ADDR']."'";
              }
              else if(trim($this->db2->Row['PARAMS'])=="SERVER_ADDR")
              {
                if($params)
                  $params.=",";
                $params.="'".$_SERVER['SERVER_ADDR']."'";
              }
              else if(trim($this->db2->Row['PARAMS'])=="LNG")
              {
                if($params)
                  $params.=",";
                global $lng;

                $params.="'".$lng."'";
              }
              else if(substr(trim($this->db2->Row['PARAMS']),0,7)=="COOKIE_")
              {
                if($params)
                  $params.=",";

                $cookie_var=substr(trim($this->db2->Row['PARAMS']),7);
                $params.="'".$_COOKIE[$cookie_var]."'";
                //setcookie("TEST","moinmoin2",time()+3600);
              }
            }
          }

          $anz=count($this->$vInput);

          for($j=0;$j<$anz;$j++)
          {
            if($params)
              $params.=",";

            eval('$hash=$this->'.$vInput.'[$j];');

            if($hash=="SESSION_ID")
              $v=session_id();
            else if($hash=="REMOTE_ADDR")
              $v=$_SERVER['REMOTE_ADDR'];
            else if($hash=="SERVER_ADDR")
              $v=$_SERVER['SERVER_ADDR'];
            else if($hash=="REMOTE_HOST")
              $v=$_SERVER['REMOTE_HOST'];
            else if($hash=="LNG")
            {
              global $lng;
              $v=$lng;
            }
            else if($hash=="SENDER_NAME")
              $v=$this->Name;
            else if($hash=="SENDER_CLASSNAME")
              $v=$this->Class;
            else
              $v=$_REQUEST[$hash];

            $v=urldecode($v);
            $v=str_replace("--add--","+",$v);
            if(substr($hash,strlen($hash)-4)=="_TOP" ||
               substr($hash,strlen($hash)-5)=="_LEFT")
              $v=str_replace("px","",$v);
            else if(substr($hash,strlen($hash)-8)=="_CHECKED")
            {
              $v=str_replace("true","True",$v);
              $v=str_replace("false","False",$v);
            }
            else if(substr($hash,strlen($hash)-4)=="_EOF")
            {
              $arr=explode("_",$hash);
              $cname=$arr[0];

              $ceof=$this->GetComponentByName($arr[0]);
              $v=$ceof->EOF;
              $v=str_replace("true","True",$v);
              $v=str_replace("false","False",$v);
            }

            $v=str_replace("'","''",$v);

            $params.="'".$v."'";
          }

          if($params)
            $params="(".$params.")";
          $sql.=$params;

          $fh=fopen("log/sql.sql","w");
          fwrite($fh,$sql);
          fclose($fh);

          $this->db->query($sql);

          $rows=array();

          if($isSelect)
          while($row=$this->db->fetch())
          {
            $rows[count($rows)]=$row;
          }

          $this->db->Commit();

          if($isSelect)
          for($irow=0;$irow<count($rows);$irow++)
          {
            $row=$rows[$irow];

            if(strtoupper(substr($row['PROPERTY'],0,11))=="SHOWMESSAGE")
            {
              $pos1=strpos($row['PROPERTY'],"(");
              $s=substr($row['PROPERTY'],$pos1+2,strlen($row['PROPERTY'])-$pos1-4);

              $this->ca->Alert($s);
            }
            else if(strtoupper(substr($row['PROPERTY'],0,12))=="BROWSER.OPEN")
            {
              $pos1=strpos($row['PROPERTY'],"(");
              $pos2=strlen($row['PROPERTY']);

              $s=substr($row['PROPERTY'],$pos1+1,strlen($row['PROPERTY'])-$pos1-2);
              $sarr=explode(",",$s);
              $sarr[0]=substr($sarr[0],1,strlen($sarr[0])-2);
              $sarr[1]=substr($sarr[1],1,strlen($sarr[1])-2);

              $js=<<<END

                window.open("{url}","{target}");

END;
              $js=str_replace("{url}",$sarr[0],$js);
              $js=str_replace("{target}",$sarr[1],$js);

              $this->ca->JS($js);
            }
            else if(strtoupper(substr($row['PROPERTY'],0,8))=="SENDMAIL")
            {
              $sendmail=new PSendMail();
              $sendmail->Start();
            }
            else if(strtoupper(substr($row['PROPERTY'],0,11))=="JAVASCRIPT:")
            {
              $this->ca->JS(substr($row['PROPERTY'],11));
            }
            else if(strtoupper(substr($row['PROPERTY'],0,7))=="COOKIE_")
            {
              $cookie_var=strtoupper(substr($row['PROPERTY'],7));
              setcookie($cookie_var,$row['VAL'],time()+3600);
            }
            else
            {
              $property=$row['PROPERTY'];
              $pos1=strpos($property,"(");
              if($pos1)
              {
                $parameters=substr($property,$pos1+1,strlen($property)-$pos1-2);
                $property=substr($property,0,$pos1)."()";
              }
              else
                $parameters="";

              //$this->ca->alert($parameters);
              $row['PROPERTY']=$property;

              $arr=explode(".",$row['PROPERTY']);

              $c_row=count($row);

              for($j=0;$j<$c_row;$j++)
              {
                $arr=explode("_",key($row));
                $c=$this->GetComponentByName($arr[0]);

                if(key($row)=="PROPERTY")
                {
                  $arr=explode(".",$row['PROPERTY']);

                  $ss=substr(current($row),strlen(current($row))-1);
                  if($ss==")")
                  {
                    $exec_c=$this->GetComponentByName($arr[0]);
                    $arr[1]=str_replace("()","(".$parameters.")",$arr[1]);
                    $eval_str='$exec_c->'.$arr[1].';';
                    eval($eval_str);
                  }

                  if(!$arr[2])
                  {
                    $c=$this->GetComponentByName($arr[0]);
                    if($c)
                      $c->Set(strtoupper($arr[1]),$row['VAL']);
                  }
                  else if($arr[2] && !$arr[3])
                  {
                    $c=$this->GetComponentByName($arr[0]);

                    if($c)
                      $c->Set(strtoupper($arr[1])."_".strtoupper($arr[2]),$row['VAL']);
                  }
                  else if($arr[2] && $arr[3])
                  {
                    $c=$this->GetComponentByName($arr[0]);

                    $c2=$c->$arr[1];

                    if($c2)
                    {
                      $c2->Set(strtoupper($arr[2])."_".strtoupper($arr[3]),$row['VAL']);
                    }
                  }
                }
                else
                {
                  if($c)
                  {
                    $property=$arr[1];
                    if($arr[2])
                      $property.="_".$arr[2];
                    if($arr[3])
                      $property.="_".$arr[3];

                    $c->Set($property,current($row));
                  }
                }

                next($row);
              }
            }
          }
      }
    }

    function Action($object,$action)
    {
      global $isMainProc,$id,$form;

      if($action=="init" && !$isMainProc)
      {
        $isMainProc=true;

        $main_proc=strtoupper($id);
        $main_proc=str_replace("-","_",$main_proc);

        $this->_call_event_proc($main_proc."MAIN","dummy",true);
        if($this->Parent->OnShow)
          $this->_call_event_proc(strtoupper($this->Parent->OnShow),"dummy",true);
      }

      for($i=0;$i<count($this->Events);$i++)
      {
        $v=$this->Events[$i]['event'];
        $vInput=$this->Events[$i]['event']."Input";

        $proc="";
        if($action==$this->Events[$i]['event'])
          $proc=strtoupper($this->$v);

        if($object==$this->Name && $proc)
        {
          $this->_call_event_proc($proc,$vInput);
        }
      }
    }

    function Get($propertys="")
    {
      parent::Get($propertys);

      $ControlTemplate=new PTemplate($this,"TComponent");
      //$ControlTemplate->debug=1;
      $control_events=$this->GetControlEvents();

      $ControlTemplate->SetFields($this->Anchors);

      $overflow="hidden";
      if($this->Parent->AutoSize=="True")
        $overflow="";

      $this->NoControl="<div style=\"border:1px solid black; ".CRLF.
                      "             overflow:".$overflow."; ".CRLF.
                      "             position:absolute; ".CRLF.
                      "             top:".$this->Top."px; ".CRLF.
                      "             left:".$this->Left."px; ".CRLF.
                      "             width:".$this->Width."px; ".CRLF.
                      "             height:".$this->Height."px; ".CRLF.
                      "             font-size:10px; ".CRLF.
                      "             font-family:Arial;".CRLF.
                      "\"><img width=\"".($this->Width-2)."\" height=\"".($this->Height-2)."\" alt=\"".$this->Name."\"/></div>".CRLF;

      if($this->Visible=="False")
        $this->Display="none";

      $this->Template=str_replace("{control_events}",$this->ControlEvents,$ControlTemplate->Get("TComponent"));


      $this->ControlEvents=$this->GetControlEvents();
      $this->ControlEvents=str_replace("{name}",$this->Name,$this->ControlEvents);
      $this->ControlEvents=str_replace("{NAME}",strtoupper($this->Name),$this->ControlEvents);

      $this->Template=str_replace("{control_events}",$this->ControlEvents,$ControlTemplate->Get("TComponent"));

      //die($this->ControlEvents);

      //echo $this->Name."(".strlen($this->Template).") - ";

    }

    function GetStyle()
    {
    }

    function GetControlEvents()
    {
      $ret=<<<END

      <script language="javascript">

        var {name}MouseX;
        var {name}MouseY;

END;

      for($i=0;$i<count($this->Events);$i++)
      {
        $v=$this->Events[$i]['event'];
        $vInput=$this->Events[$i]['event']."Input";

        $uret=$this->Events[$i]['js'];

        $global_left=$this->Left;
        $global_top=$this->Top+33;
        $parent=$this->Parent;
        while($parent)
        {
          $global_left+=$parent->Left;
          $global_top+=$parent->Top;
          $parent=$parent->Parent;
        }

        $uret=str_replace("{event}",$this->Events[$i]['event'],$uret);
        $uret=str_replace("{global_left}",$global_left,$uret);
        $uret=str_replace("{global_top}",$global_top,$uret);

        $input="";
        $anz=count($this->$vInput);

        for($j=0;$j<$anz;$j++)
        {
          eval('$inp=$this->'.$vInput.'[$j];');
          $arr=explode("_",$inp);
          $objectname=$arr[0];
          $c=$this->GetComponentByName($objectname);
          //echo $c->Class."<br>";

          $property=$arr[1];
          if($arr[2])
            $property.="_".$arr[2];

          if(($property=="TEXT" ||
              $property=="LINES_TEXT") && $c->Class=="TWFRichEdit")
          {
            $input.="v=str_replace('+','--add--',this['".$arr[0]."_rEdit'].document.body.innerHTML); input+='&".$inp."='+urlencode(v); ";
            //$input.="v=str_replace('+','--add--',document.getElementById('".$arr[0]."').innerHTML); input+='&".$inp."='+urlencode(v);";
          }
          else if($property=="CHECKED" && $c->Class=="TWFCheckbox")
          {
            $input.="input+='&".$inp."='+((document.getElementById('".$arr[0]."').checked) ? 'True' : 'False');";
          }
          else if($property=="CHECKED" && $c->Class=="TWFRadioButton")
          {
            $input.="input+='&".$inp."='+((document.getElementById('".$arr[0]."').checked) ? 'True' : 'False');";
          }
          else if($property=="TEXT" ||
             $property=="LINES_TEXT")
          {
            $input.="v=str_replace('+','--add--',document.getElementById('".$arr[0]."').value); input+='&".$inp."='+urlencode(v);";
          }
          else if($property=="CAPTION" && $c->Class=="TWFButton")
            $input.="input+='&".$inp."='+document.getElementById('".$arr[0]."').value;";
          else if($property=="CAPTION")
            $input.="input+='&".$inp."='+document.getElementById('".$arr[0]."').innerHTML;";
          else if($property=="VALUE")
            $input.="input+='&".$inp."='+document.getElementById('".$arr[0]."').value;";
          else if($arr[0]=="MOUSE")
          {
            if($property=="X")
              $input.="input+='&".$inp."='+".$this->Name."MouseX;";
            else if($property=="Y")
              $input.="input+='&".$inp."='+".$this->Name."MouseY;";
          }
          else if($property=="TOP")
          {
            $input.="input+='&".$inp."='+document.getElementById('o".$arr[0]."').style.top;";
          }
          else if($property=="LEFT")
          {
            $input.="input+='&".$inp."='+document.getElementById('o".$arr[0]."').style.left;";
          }
          else
          {
            //$input.="input+='&".$inp."='+document.getElementById('o".$arr[0]."').style.left;";
            //$input.="input+='&".$inp."='+".$this->GetEventParams()."";
            $c=$this->GetComponentByName($arr[0]);
            if($c)
            {
              //die($c->Class." (".$inp."/".$property.")");
              $input.="input+='&".$inp."='+".$c->GetEventParams($property)."";
            }
          }
        }

        //eval('$this->is'.$this->Name.$property.'=1;');

        eval('$isEvent=$this->is'.$this->Name.$this->Events[$i]['event'].';');
        if(!$isEvent)
          $isEvent=0;

        //echo '$isEvent=$this->is'.$this->Name.$this->Events[$i]['event'].'=<b>'.$isEvent."</b><br>";

        $uret=str_replace("{isEvent}",$isEvent,$uret);
        $uret=str_replace("{input}",$input,$uret);

        //if($input || 1==0)
        //echo "2:".$this->Events[$i]['event']."<br>";

        if($this->isEvents['isEvent'.$this->Events[$i]['event']] || 1==0)
        {
          //$this->isEvents['isEvent'.$this->Events[$i]['event']]=1;
          $ret.=$uret;
        }
        //else
        //  $this->isEvents['isEvent'.$this->Events[$i]['event']]=0;
      }

      $ret.=<<<END
      </script>

END;
      return $ret;
    }

    function GetEventParams($property)
    {
      // Prototype
    }

  }

?>