<?php
include_once("c_esmo_magnit_instruction_lession.php");
class c_page_cab_esmo_magnit_instruction_lession_sign extends c_page_cab_esmo_magnit_instruction_lession
{
  public $h1='Занятие по инструктажу - подпись участников' ;
  public $rec_event=array() ;
  public $rec_lession=array() ;

  function block_main()
  { $this->h1.=' - Подпись участников занятия' ;
	?><!--[if lt IE 9]><script type="text/javascript" src="/AddOns/jSignature/flashcanvas.js"></script><![endif]-->
	  <!--<script src="/AddOns/jSignature/jSignature.min.noconflict.js"></script>-->
      <link rel="stylesheet" href="/<?echo _CLASS_?>/ext/interface/signature-pad-master/assets/jquery.signaturepad.css">
      <script src="/<?echo _CLASS_?>/ext/interface/signature-pad-master/jquery.signaturepad.js"></script>
      <script src="/<?echo _CLASS_?>/ext/interface/signature-pad-master/assets/json2.min.js"></script>
      <style>
    	canvas {
    		outline: 1px solid #aaa;
    		background: #fff;
    	}
      </style>
    <?

	$this->page_title() ;
    $this->panel_lession_info() ;
    $this->panel_lession_themes() ;
    if ($this->rec_lession['status']<5)
    { $this->panel_select_personal() ;
      $this->panel_person_sign() ;
    }
    $this->panel_person_sign_info() ;
  }

  function panel_select_personal($options=array())
   {   if (!is_array($options['disabled_filter'])) $options['disabled_filter']=array() ;
       ?><div id="panel_filter">
               <form id="sky-form" class="sky-form">
                   <fieldset>
                      <div class="row">
                          <section class="col col-3">
                                 <label class="label">Пропуск</label>
                                 <label class="input"><input type="text" id=propusk  name="propusk" value=""></label>
                          </section>
                          <section class="col col-3">
                                 <label class="label">&nbsp;</label>
                                 <button class="button v2" event_id="<?echo $this->rec_event['pkey']?>" lession_id="<?echo $this->rec_lession['pkey']?>" cmd="esmo_magnit_instruction/seach_personal_to_sign" style="margin:0;float:none;">Поиск</button>
                          </section>
                          <section class="col col-3">
                                  <label class="label">&nbsp;</label>
                                 <?$all_is_sign=$this->panel_sign_stats() ; ?>
                          </section>
                          <section class="col col-3">
                              <label class="label">&nbsp;</label>
                              <input type="hidden" name="url_page_doc_view" value="/window/esmo_magnit_instruction/lession/<?echo $this->rec_lession['pkey']?>/report/">
                              <input type="hidden" name="filter[lession_id]" value="<?echo $this->rec_lession['pkey']?>">
                              <input type="hidden" name="obj_reffer" value="<?echo $this->rec_lession['_reffer']?>">
                              <input type="hidden" name="lession_id" value="<?echo $this->rec_lession['pkey']?>">
                              <input type="hidden" name="report_seria" value="<?echo htmlspecialchars(MEMBER()->cur_group_name)?>">
                              <input type="hidden" name="report_code" value="lession_personal_status">
                              <?if ($all_is_sign){?><button class="button v2" cmd="docs/doc_create">Сформировать ведомость</button><?}
                                else {?><button class="button v2" cmd="esmo_magnit_instruction/check_lession_sign_before_report_create" lession_id="<?echo $this->rec_lession['pkey']?>">Сформировать ведомость</button><?}?>
                          </section>
                      </div>
                  </fieldset>
                </form>
         </div><br>
	     <script type="text/javascript">
	            $j(document).ready(function()
	              {   $j('#propusk').focus() ;
	                  $j('#propusk').on('keyup',function()
	                                        {   console.log($j(this).val().length) ;
	                                            if ($j(this).val().length==14) send_ajax_request({cmd:"esmo_magnit_instruction/seach_personal_to_sign",
	                                                                                             event_id:<?echo $this->rec_event['pkey']?>,
	                                                                                             lession_id:<?echo $this->rec_lession['pkey']?>,
	                                                                                             propusk:$j(this).val()
	                                                                                            }) ;

	                                                                                             $j('#propusk').focus() ;

	                                        }) ;
	               });
	            </script>
       <?
   }

   function panel_sign_stats()
   {
       $stats=execSQL_row('select status,count(pkey) from obj_site_lession_persons where parent='.$this->rec_lession['pkey'].' group by status') ;
       $cnt_sign=($stats[4])? $stats[4]:0 ;
       echo '<div id="sign_stats">Расписалось <strong>'.$cnt_sign.'</strong> сотрудников из <strong>'.array_sum($stats).'</strong></div>' ;
       $result=($cnt_sign>=array_sum($stats))? 1:0 ;
       return($result) ;

   }

   function panel_person_sign()
   {   ?><div id="panel_person_sign"></div>
         <style type="text/css">
			#table_person_sign{width:auto;table-layout:auto;}
	        #table_person_sign td{text-align:left;vertical-align:top;padding-right:20px;}
	        #table_person_sign td.item img{border:1px solid #aaaaaa;float:left;}
	        #table_person_sign td.item .name{font-size:16px;font-weight:bold;}
	        #table_person_sign td.item div.org_name{font-size:13px;}
	        #table_person_sign td.item div.otdel_name{font-size:11px;}
	        #table_person_sign td.item div.working_name{font-size:11px;margin-bottom:12px;}
	        #table_person_sign div#alert{color:red;font-size:20px;text-align:right;}
	        #table_person_sign div#signature{width:800px;height:200px;margin-top:20px;background:url("<?echo _PATH_TO_EXT?>/esmo_magnit_instruction/img/kletka.png") repeat;}
            div#sign_stats{font-size:14px;}
            div#sign_stats strong{font-size:18px;}
         </style>
         <script type="text/javascript">
             $j(document).ready(function()
            {var api ;
             $j('body').everyTime(1000,'set_focus',function(){$j('#propusk').focus();})

	         $j('body').on('click','button#apply_sign',function()
	         {  //var sigdiv = $j("#signature")
                //var data = sigdiv.jSignature("getData", "native")  ;
                api =$j('form#dd2').signaturePad() ;
                var data = api.getSignature();

                if (data.length>50/*check_handsign(data)*/)
               { //var datapair = sigdiv.jSignature("getData", "image")  ;
                 var datapair = api.getSignatureImage() ;
		        send_ajax_request({cmd:'esmo_magnit_instruction/lession_person_sign',
                                   event_id:<?echo $this->rec_event['pkey']?>,
                                   lession_id:<?echo $this->rec_lession['pkey']?>,
                                   personal_id:$j(this).attr('personal_id'),
                                   image:datapair
		                          }) ;
               }
               else
               { $j('#alert').html('<div class=failed>Подпись некорректна</div>') ;
                 $j('#alert').show() ;
                 $j('body').oneTime(3000,'check_handsign_clear',function(){$j('#alert').hide() ;})
               }


	         }) ;

             $j('body').on('click','button#clear_sign',function()
             {  //var sigdiv = $j("#signature")
                //sigdiv.jSignature("reset") // clears the canvas and rerenders the decor on it.
                api =$j('form#dd2').signaturePad() ;
                api.clearCanvas() ;
	         }) ;

             function check_handsign(datapair)
               {   var cnt_line=datapair.length ;
                   var cnt_pix=0 ;
                   $j.each(datapair,function(id,value){if (value.x.length>cnt_pix) cnt_pix=value.x.length;}) ;
                   var min_line=<?echo $GLOBALS['LS_handsign_line_min']?> ;
                   var min_pix=<?echo $GLOBALS['LS_handsign_pix_min']?> ;
                   if (cnt_line>=min_line && cnt_pix>=min_pix) return(1) ;
                   else                                        return(0) ;

               }

                                }) ;
         </script>
	   <?
   }

   function panel_person_sign_new()
   {
    ?><style>
    	canvas {
    		outline: 5px solid #aaa;
    		background: #fff;
    	}
      </style>
      <link rel="stylesheet" href="/<?echo _CLASS_?>/ext/interface/signature-pad-master/assets/jquery.signaturepad.css">
    	<form method="POST" action="">
    		<canvas class="pad"></canvas>
    		<fieldset>
    			<input type="reset" value="clear" />
    		</fieldset>
    	</form>

      <script src="/<?echo _CLASS_?>/ext/interface/signature-pad-master/jquery.signaturepad.js"></script>
      <button id="test_sign">test</button>
      <script>
      var api ;
      (function(window) {
        var $canvas,
            onResize = function(event) {
              $canvas.attr({
                height: 400,
                width: 700
              });
            };

        $j(document).ready(function() {
          $canvas = $j('canvas');
          window.addEventListener('orientationchange', onResize, false);
          window.addEventListener('resize', onResize, false);
          onResize();

          api =$j('form').signaturePad({
            drawOnly: true,
            defaultAction: 'drawIt',
            validateFields: false,
            lineWidth: 0,
            output: null,
            sigNav: null,
            name: null,
            typed: null,
            clear: 'input[type=reset]',
            typeIt: null,
            drawIt: null,
            typeItDesc: null,
            drawItDesc: null
          });
        });
      }(this));

      $j('body').on('click','button#test_sign',test_sign) ;

      function test_sign()
      {

          var sig = api.getSignatureImage();
          console.log(sig) ;
      }
      </script>
      <script src="/<?echo _CLASS_LOCAL_?>/ext/demo_sign/signature-pad-master/assets/json2.min.js"></script>
       <?
   }

   function panel_sign()
   {
       ?><!-- you load jquery somewhere above here ... -->
	<style type="text/css">
	                  div#signature{width:600px;height:2000px;background:url("<?echo _PATH_TO_EXT?>/esmo_magnit_instruction/img/kletka.png") repeat;}
	              </style>
          	<div id="signature" style="width:600px;height:200px;"></div><div class="clear"></div><br><br>
          	<script>
          	    $j(document).ready(function() {
          	        //$j("#signature").jSignature()

                      var sigdiv = $j("#signature")
                      sigdiv.jSignature({color:"#00f",lineWidth:0}) // inits the jSignature widget.
                      // after some doodling...

                      sigdiv.jSignature("reset") // clears the canvas and rerenders the decor on it.
                      /*
                      // Getting signature as SVG and rendering the SVG within the browser.
                      // (!!! inline SVG rendering from IMG element does not work in all browsers !!!)
                      // this export plugin returns an array of [mimetype, base64-encoded string of SVG of the signature strokes]
                      var datapair = sigdiv.jSignature("getData", "svgbase64")
                      var i = new Image()
                      i.src = "data:" + datapair[0] + "," + datapair[1]
                      $j(i).appendTo($j("#someelement") // append the image (SVG) to DOM.

                      // Getting signature as "base30" data pair
                      // array of [mimetype, string of jSIgnature"s custom Base30-compressed format]
                      datapair = sigdiv.jSignature("getData","base30")
                      // reimporting the data into jSignature.
                      // import plugins understand data-url-formatted strings like "data:mime;encoding,data"
                      sigdiv.jSignature("setData", "data:" + datapair.join(","))
                      */

          	    })
          	</script>

          <?
   }

   function panel_person_sign_info()
   {  ?><div id="panel_person_sign_info"><?
	  ?><br><br><br><h2>Ведомость участия сотрудников в занятии</h2><?
	  $list_recs=execSQL('select * from view_lession_personals where lession_id='.$this->rec_lession['pkey']) ;
	  ?><table class="list_personal_table_img basic fz_small full auto">
		          <colgroup><col id="c1"><col id="c2"><col id="c3"></colgroup>
		          <tr><th>ФИО, дата рождения</th>
		              <th>Организация, подразделение</th>
		              <th>Должность</th>
		              <th>Подпись сотрудника</th>
		          </tr>
		          <?
		          if (_sizeof($list_recs)) foreach($list_recs as $rec) if ($rec['pkey'])
		          {   ?><tr class=item>
		                  <td class="left"><?echo $rec['obj_name']?>
		                      <?  if ($rec['uid']) echo '<br><span class="nowrap small">'.$rec['uid'].'</span>' ;
		                          if (!$rec['enabled'])echo '<br><br><span class="red bold">УВОЛЕН</span> ('.date('d.m.Y H:i',$rec['fired_data']).')' ;
		                          if ($rec['dr'])echo '<br>'.$rec['dr'] ;
		                          if ($rec['propusk'])echo '<br>'.$rec['propusk'] ;
		                      ?>
		                  </td>
		                  <td class="left"><?echo '<strong>'.$rec['_org_name'].'</strong><br><div class="small">'.$rec['_otdel_name'].'</div>'?></td>
		                  <td class="left"><?echo _IL('IL_works')->recs[$rec['working']]['obj_name'] ?></td>
		                  <td><?if ($rec['sign_fname']) echo '<img src="/public/instruktions_sign/'.$rec['sign_fname'].'" width=200>' ?></td>

		              </tr><?
		          }
	?></table></div><?
   }
}



?>
