<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Float field
 *
 * @author Igor Ratsun
 */
class rtgc_float implements rtgc_callback
{

    protected $options = array(
        'class'          => 'span2',
        'prepend_symbol' => '',
        'default' => null,
    );

    public function __construct($options = array())
    {
        $this->options = array_merge($this->options, $options);
    }

    public function column($value = '')
    {
        return $this->prepare($value);
    }

    public function field($name = '', $value = '')
    {
        if ($value == '' && !is_null($this->options['default'])) {
            $value = $this->options['default'];
        }
        
        $js = '$(function(){
                    $(\'.float\').keypress(function (e) {
                        if (e.which != 46 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                            return false;
                        }
                    });
                });';
        get_instance()->js_css->add_js_string($js);
        if (!empty($this->options['prepend_symbol'])) {
            $html = '<div class="input-prepend"><span class="add-on">' . $this->options['prepend_symbol'] . '</span>%s</div>';
        } else {
            $html = '%s';
        }
        $input = '<input class="' . $this->options['class'] . ' float" name="' . $name . '" type="text" placeholder="99.99" value="' . $this->column($value) . '">';

        return sprintf($html, $input);
    }

    protected function prepare($value = 0)
    {
        return number_format(floatval($value), 2, '.', '');
    }

}
