<?php
/**
 * Interchange form
 *
 * @author Moises Heberle [moises@solis.coop.br]
 *
 * @version $Id$
 *
 * \b Maintainers \n
 * Eduardo Bonfandini [eduardo@solis.coop.br]
 * Jamiel Spezia [jamiel@solis.coop.br]
 * Luiz Gregory Filho [luiz@solis.coop.br]
 * Moises Heberle [moises@solis.coop.br]
 * Sandro Roberto Weisheimer [sandrow@solis.coop.br]
 *
 * @since
 * Class created on 20/02/2009
 *
 * \b Organization: \n
 * SOLIS - Cooperativa de Solucoes Livres \n
 * The Gnuteca3 Development Team
 *
 * \b CopyLeft: \n
 * CopyLeft (L) 2009 SOLIS - Cooperativa de Solucoes Livres \n
 *
 * \b License: \n
 * Licensed under GPL (for further details read the COPYING file or http://www.gnu.org/copyleft/gpl.html )
 *
 * \b History: \n
 * See history in SVN repository: http://gnuteca.solis.coop.br
 */
class FrmInterchange extends GnutecaForm
{
    public $MIOLO;
    public $module;
    public $busInterchangeType;
    public $busInterchangeStatus;
    public $busSupplierTypeAndLocation;
    public $busMaterial;

    public $_interchangeItem;
    public $_interchangeObservation;


    public function __construct()
    {
        $this->MIOLO  = MIOLO::getInstance();
        $this->module = MIOLO::getCurrentModule();
        $this->busInterchangeType         = $this->MIOLO->getBusiness($this->module, 'BusInterchangeType');
        $this->busInterchangeStatus       = $this->MIOLO->getBusiness($this->module, 'BusInterchangeStatus');
        $this->busSupplierTypeAndLocation = $this->MIOLO->getBusiness($this->module, 'BusSupplierTypeAndLocation');
        $this->busMaterial                = $this->MIOLO->getBusiness($this->module, 'BusMaterial');
        $this->setAllFunctions('Interchange', 'supplierId', 'interchangeId', array('interchangeId'));
        parent::__construct();
        $this->page->addJsCode("
        changeStatus = function()
        {
            miolo.doAjax('changeStatus', '', 'frm__mainForm');
        }
        ");
        if  ( $this->primeiroAcessoAoForm() && ($this->function != 'update') )
        {
            GnutecaRepetitiveField::clearData('_interchangeItem');
            GnutecaRepetitiveField::clearData('_interchangeObservation');
            $this->setFocus('type');
        }
    }


    public function createFields()
    {
        $defaultTypeId = INTERCHANGE_TYPE_SEND;

        if ($this->function == 'update')
        {
            $interchangeId = new MTextField('interchangeId', NULL, _M('Code', $this->module), FIELD_ID_SIZE);
            $interchangeId->setReadOnly(TRUE);
            $fields[] = $interchangeId;
        }
        $validators[] = new MIntegerValidator('interchangeId');
        $defaultType = 'p'; //Permuta
        $type = new GnutecaSelection('type', $defaultType, _M('Type', $this->module), $this->business->listTypes(), null, null, null, TRUE);
        $type->addAttribute('onchange', "miolo.doAjax('changeType', '', 'frm__mainForm')");
        $validators[] = new MRequiredValidator('supplierId');
        $fields[] = $type;
        $fields[] = new MDiv('divSupplier', $this->getSupplierField($defaultType));
        $fields[] = new MCalendarField('date', GnutecaDate::now(GnutecaDate::getDbMask('DATE')), _M('Date', $this->module), FIELD_DATE_SIZE);
        $validators[] = new MDATEDMYValidator('date', null, 'required');
        $interchangeTypeId = new GnutecaSelection('interchangeTypeId', $defaultTypeId, _M('Interchange type', $this->module), $this->busInterchangeType->listInterchangeType(), null, null, null, TRUE);
        $interchangeTypeId->addAttribute('onchange', "changeStatus()");
        $interchangeTypeId->addAttribute('onkeydown', "changeStatus()");
        $fields[] = $interchangeTypeId;
        $fields[] = new MHContainer('status', array($this->getInterchangeStatusField($defaultTypeId)));
        $operator = new MTextField('operator', GnutecaOperator::getOperatorId(), _M('Operator', $this->module));
        $operator->setReadOnly(TRUE);
        $fields[] = $operator;

        //Interchange item
        $columns    = null;
        $flds       = null;
        $valids     = null;

        $itemNumber = new MTextField('_number', null, _M('Number', $this->module), FIELD_ID_SIZE);
        $flds[] = $itemNumber;
        
        $options    = array(
            array(_M('Control number', $module), 'controlNumber'),
            array(_M('Item number', $module), 'itemNumber'),
        );
        $types = new MRadioButtonGroup('numberType', null, $options, 'controlNumber', null, 'vertical');
        $flds[] = $types;
        if (!GnutecaForm::getEvent() || (GnutecaForm::getEvent() == 'tbBtnNew:click')) //selecionar por default controlNumber (nao funciona no repetitiveField) 
        {
            $this->page->onload("dojo.byId('numberType_1').checked = 'checked'");
        }

        //$flds[] = new MTextField('_content', null, _M('Content', $this->module), FIELD_DESCRIPTION_SIZE);
        $flds[] = new MHiddenField('interchangeItemId');
        $columns[] = new MGridColumn(_M('Control number', $this->module), MGrid::ALIGN_LEFT, true, true, true,  'controlNumber');
        $columns[] = new MGridColumn(_M('Title', $this->module),          MGrid::ALIGN_LEFT, true, true, true,  'contentTitle');
        $columns[] = new MGridColumn(null,                                MGrid::ALIGN_LEFT, true, true, false, 'interchangeItemId');
        $valids[] = new MIntegerValidator('controlNumber', null, 'required');
        $opts = array('remove', 'noUpdateButton');
        $interchangeItem = new GnutecaRepetitiveField('_interchangeItem', _M('Items', $this->module), $columns, $flds, $opts);
        //$interchangeItem->setUpdateButton(TRUE);
        $interchangeItem->setValidators($valids);
        $fields[] = $interchangeItem;

        //Interchange observation
        $columns    = null;
        $flds       = null;
        $valids     = null;

        $now = GnutecaDate::now(GnutecaDate::getDbMask('DATE'));
        $date = new MCalendarField('obs_date', $now, _M('Date', $this->module), FIELD_DATE_SIZE);
        $date->addAttribute('onChange', "document.getElementById('obs_date2').value = this");
        $flds[] = $date;
        $flds[] = new MHiddenField('obs_date2', $now);
        $flds[] = new MSeparator();
        $flds[] = new MMultiLineField('observation', null, _M('Observation', $this->module), NULL, FIELD_MULTILINE_ROWS_SIZE, FIELD_MULTILINE_COLS_SIZE);
        $flds[] = new MSeparator();
        $operator = new MTextField('operator', GnutecaOperator::getOperatorId(), _M('Operator', $this->module));
        $operator->setReadOnly(TRUE);
        $flds[] = $operator;
        $flds[] = new MHiddenField('interchangeObservationId');
        $columns[] = new MGridColumn(_M('Date', $this->module),        MGrid::ALIGN_LEFT, true, true, true,  'obs_date');
        $columns[] = new MGridColumn(_M('Date', $this->module),        MGrid::ALIGN_LEFT, true, true, false, 'obs_date2');
        $columns[] = new MGridColumn(_M('Observation', $this->module), MGrid::ALIGN_LEFT, true, true, true,  'observation');
        $columns[] = new MGridColumn(_M('Operator', $this->module),    MGrid::ALIGN_LEFT, true, true, true,  'operator');
        $columns[] = new MGridColumn(null,                             MGrid::ALIGN_LEFT, true, true, false, 'interchangeObservationId');
        $interchangeObservation = new GnutecaRepetitiveField('_interchangeObservation', _M('Observation', $this->module), $columns, $flds);
        $interchangeObservation->setUpdateButton(TRUE);
        $fields[] = $interchangeObservation;

        $this->setFields($fields);
        $this->setValidators($validators);
	}


    public function changeStatus($sender)
    {
        $this->setResponse($this->getInterchangeStatusField($sender->interchangeTypeId), 'm_status');
    }


    public function getInterchangeStatusField($interchangeTypeId)
    {
        $lblES = new MLabel( _M('Status', $this->module) . ':' );
        $lblES->setWidth(FIELD_LABEL_SIZE);
        $interchangeStatusId = new GnutecaSelection('interchangeStatusId', null, null, $this->busInterchangeStatus->listInterchangeStatus($interchangeTypeId), null, null, null, TRUE);
        $hct = new MHContainer('hctInterchangeStatus', array($lblES, $interchangeStatusId));
        $hct->addBoxStyle('width', '100%');
        return $hct;
    }


    public function changeType($sender)
    {
    	$fields[] = $this->getSupplierField($sender->type);
        $this->setResponse($fields, 'divSupplier');
    }


    public function getSupplierField($type = NULL)
    {
        $lbl = new MLabel (_M('Supplier:',$this->module));
        $lbl->width = FIELD_LABEL_SIZE;
        $supplierId = new MLookupTextField ('supplierId','','',FIELD_LOOKUPFIELD_SIZE);
        $supplierId->setContext($this->module, $this->module, 'supplierType', 'filler', 'supplierId,supplierIdDescription');
        $supplierId->baseModule = 'gnuteca3';
        $supplierIdDescription = new MTextField ('supplierIdDescription','',null, FIELD_DESCRIPTION_LOOKUP_SIZE);
        $supplierIdDescription->setReadOnly(true);
        $supplierIdContainer = new MHcontainer('supplierIdContainer', array ($lbl, $supplierId, $supplierIdDescription,));
        return $supplierIdContainer;
    }


    public function loadFields()
    {
    	$this->business->getInterchange( MIOLO::_REQUEST('interchangeId') );
    	$this->business->date = GnutecaDate::explodeDate($this->business->date);
    	$this->business->date = $this->business->date[0];
    	$this->setData($this->business);

    	//InterchangeItem
        if ($this->business->interchangeItem)
        {
            foreach ($this->business->interchangeItem as $i => $v)
            {
                $this->business->interchangeItem[$i]->contentTitle = $v->content;
            }
        }
    	$this->_interchangeItem->setData($this->business->interchangeItem);

    	//InterchangeObservation
        if ($this->business->interchangeObservation)
        {
        	foreach ($this->business->interchangeObservation as $i => $v)
        	{
        		$this->business->interchangeObservation[$i]->obs_date  = GnutecaDate::toUser($v->date, 'DATE');
        		$this->business->interchangeObservation[$i]->obs_date2 = GnutecaDate::toDb($v->obs_date, 'DATE');
        	}
        }

    	$this->_interchangeObservation->setData($this->business->interchangeObservation);

        if (MIOLO::_REQUEST('function') == 'update')
        {
            $this->getControlById('interchangeStatusId')->options = $this->busInterchangeStatus->listInterchangeStatus($this->business->interchangeTypeId);
        }
    }


    public function tbBtnSave_click($sender)
    {
    	$this->addValidator(new MRequiredValidator('supplierId'));
        $data = $this->getData();
        if ($this->function == 'insert')
        {
            $data->interchangeId = $this->business->getNextId();
            $session = new MSession();
            $session->set('interchangeId', $data->interchangeId);
        }

        $data->interchangeItem = $this->_interchangeItem->getData();
        if ($data->interchangeItem)
        {
            foreach ($data->interchangeItem as $i => $v)
            {
            	$data->interchangeItem[$i]->content = $v->contentTitle;
            }
        }

        $data->interchangeObservation = $this->_interchangeObservation->getData();
        if ($data->interchangeObservation)
        {
        	foreach ($data->interchangeObservation as $i => $v)
        	{
                $data->interchangeObservation[$i]->date = GnutecaDate::toDB($v->obs_date2, 'DATE');
        	}
        }
    	parent::tbBtnSave_click($sender, $data);
    }


    public function forceAddToTable($args)
    {
    	$this->addToTable($args, TRUE);
    }


    public function addToTable($args, $forceMode = FALSE)
    {
        $errors = array();
    	if ($args->GnutecaRepetitiveField == '_interchangeObservation')
    	{
    		$args->obs_date = GnutecaDate::toUser($args->obs_date2, 'DATE');
    	}
    	else if ($args->GnutecaRepetitiveField == '_interchangeItem')
    	{
            if ($args->numberType == 'controlNumber')
            {
                $args->controlNumber = $args->_number;
                $args->contentTitle = $this->busMaterial->getContentTag($args->_number, MARC_TITLE_TAG);
                if (!$args->contentTitle)
                {
                    $errors[] = _M('Control number not found', $this->module);
                }
            }
            else //itemNumber
            {
                $args->controlNumber = $this->busMaterial->getContentByItemNumber($args->_number, MARC_CONTROL_NUMBER_TAG);
                $args->contentTitle  = $this->busMaterial->getContentByItemNumber($args->_number, MARC_TITLE_TAG);
                if (!$args->controlNumber || !$args->contentTitle)
                {
                    $errors[] = _M('Item number not found', $this->module);
                }
            }
    	}

        ($forceMode) ? parent::forceAddToTable($args, null, $errors) : parent::addToTable($args, null, $errors);

        if ($args->GnutecaRepetitiveField == '_interchangeObservation')
        {
            $date   = GnutecaDate::now(GnutecaDate::getUserMask('DATE'));
            $dateDb = GnutecaDate::now(GnutecaDate::getDbMask('DATE'));
            $this->page->onLoad("document.getElementById('obs_date').value = '{$date}'");
            $this->page->onLoad("document.getElementById('obs_date2').value = '{$dateDb}'");
        }
    }
}
?>
