<?php
/**
 * Horde_Form_Action_conditional_setvalue is a Horde_Form_Action that
 * sets the value of one Horde_Form variable based on the value of the
 * variable the action is attached to.
 *
 * $Horde: horde/lib/Form/Action/conditional_setvalue.php,v 1.6 2003/05/26 21:18:12 chuck Exp $
 *
 * Copyright 2002-2003 Chuck Hagenbuch <chuck@horde.org>
 *
 * See the enclosed file LICENSE for license information (BSD). If you
 * did not receive this file, see http://www.horde.org/licenses/bsdl.php.
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @version $Revision: 1.6 $
 * @package horde.form
 */
class Horde_Form_Action_conditional_setvalue extends Horde_Form_Action {

    var $_trigger = array('onchange', 'onload');

    function getActionScript(&$form, &$renderer, $index)
    {
        return 'map(\'' . $renderer->_genID($varname, $index, false) . "', '" . $renderer->_genID($this->getTarget(), $index, false) . '\');';
    }

    function setValues(&$vars, $sourceVal, $index = null, $arrayVal = false)
    {
        $map = $this->_params['map'];
        $target = $this->getTarget();

        if ($arrayVal && is_null($index)) {
            $i = 0;
            foreach ($sourceVal as $val) {
                if (!empty($map[$val])) {
                    $vars->setVar($target, $map[$val], $i);
                }
                $i++;
            }
        } else {
            if (!empty($map[$sourceVal])) {
                if (!is_null($index)) {
                    $vars->setVar($target, $map[$sourceVal], $index);
                } else {
                    $vars->setVar($target, $map[$sourceVal]);
                }
            }
        }
    }

    function printJavaScript()
    {
        $map = $this->_params['map'];
?>
_map = new Array(<?php
$i = 0;
foreach ($map as $val) {
    if ($i > 0) {
        echo ', ';
    }
    echo '"' . $val . '"';
    $i++;
}?>);

function map(sourceId, targetId)
{
    var newval;
    var source = document.getElementById(sourceId);
    var element = document.getElementById(targetId);
    if (element) {
        if (_map[source.selectedIndex]) {
            newval = _map[source.selectedIndex];
            replace = true;
        } else {
            newval = '';
            replace = false;
            for (i = 0; i < _map.length; i++) {
                if (element.value == _map[i]) {
                    replace = true;
                    break;
                }
            }
        }

        if (replace) {
            element.value = newval;
        }
    }
}<?php
    }

}
