<?php 

class PutFormValidate {
  private $scope;
  private $position;
  private $label;
  private $idProp;
  private $confirmModal;

  public function __construct ($entry) {
    if (isset($entry)) {
      $this->scope    = $entry->scope;
      $this->headText = $entry->headText;
      $this->bodyText = $entry->bodyText;
      $this->disabled = $entry->disabled;
      $this->iterator = $entry->iterator;
      $this->idProp   = $entry->idProp;
      $this->label    = $entry->label;
      $this->defLab   = explode ("_", $entry->label)[0];

      $this->mandatory = "{";
      if (isset($entry->mandatory)) {
        $mandatories = explode(",", $entry->mandatory);
      
        for ($i=0; $i<count($mandatories); $i++) {
          if ($i == 0)    
            $this->mandatory .= $mandatories[$i] . ":0";
          else
            $this->mandatory .= "," . $mandatories[$i] . ":0";
        }
      }    
      $this->mandatory .= "}";

      if (isset($entry->position) && $entry->position == "left")
        $this->position = "left";
      else
        $this->position = "right";
    
      if (isset($entry->confirmModal)) 
        $this->confirmModal = $entry->confirmModal;
      else
        $this->confirmModal = 0;

    }
  }
  
  public function outputLayout() {
  
    $html = "
<button id='$this->idProp' class='btn btn-inverse' value='$this->label'
  onclick='valid$this->scope();' style='float:$this->position;'>
  $this->defLab
</button>

    ";
  	return $html;
  }
  
  public function outputScript() {
		
    $script = " 	 

var mandatory = $this->mandatory;    
var reply = [];
reply.update = false;
reply.reset = false;

function valid$this->scope () {
  reply.valid = true;
  reply.invalidMsg = ''; 
  for (var key in mandatory) {
//alert (key + '  ' +  mandatory[key]); 
    if (mandatory[key] == 0) {
      reply.valid = false;
      reply.invalidMsg += ' Missing ' + key;  
    }
  }

  if (reply.valid && reply.update && $this->confirmModal)
    $('#cnfModal$this->iterator').modal('show'); 
  else if (reply.valid) {
    reply.update = true;          
    passed$this->iterator (true);
  } 
  else
    passed$this->iterator (true);
}


function passed$this->iterator (ok) {
  if (!ok) {
    reply.update = false;
    reply.reset = true;
  }
alert (reply.update);
alert (reply.valid);
  putaction$this->iterator(reply); 

  reply.update = false;
  reply.reset = false;
}

function listener$this->scope (message) {
  var key = Object.keys(message); 
alert (key + ': ' + mandatory[key] + '  ' + message[key]);
  if (mandatory[key] != 0 && mandatory[key] != message[key])
    reply.update = true;
alert (reply.update);
  mandatory[key] = message[key];

}

    ";
    return $script;
  }
}

?>
