<?php

/**
 * JMultiSelect class file.
 *
 * PHP Version 5.1
 *
 * @package  Widget
 * @author   Segoddnja <segoddnja@i.ua>
 * @license  http://www.opensource.org/licenses/mit-license.php MIT
 * @since    1.0
 */

Yii::import('zii.widgets.jui.CJuiInputWidget');

class JMultiSelect extends CJuiInputWidget {

    /**
     * @var array data for generating the list options (value=>display)
     */
    public $data  = array();

    /**
     * @var array selected data for list
     */
    public $selected  = array();

    /**
     * @var array additional options for multiselect script
     */
    public $options = array();

    /**
     * Run this widget.
     * This method registers necessary javascript and renders the needed HTML code.
     */
    function run() {
        list($name, $id) = $this->resolveNameID();
        if (isset($this->htmlOptions['id']))
            $id = $this->htmlOptions['id'];
        else
            $this->htmlOptions['id'] = $id;
        if (isset($this->htmlOptions['name']))
            $name = $this->htmlOptions['name'];
        else
            $this->htmlOptions['name'] = $name;
        if ($this->hasModel())
            //echo CHtml::activeDropDownList($this->model, 'citysFilter', $this->data, $this->htmlOptions);
			echo CHtml::activeDropDownList($this->model, $this->attribute, $this->data, $this->htmlOptions);
        else
            echo CHtml::dropDownList($name, $this->selected, $this->data, $this->htmlOptions);
        $options = CJavaScript::encode($this->options);
        $js = "jQuery('#{$id}').multiselect($options);";
        Yii::app()->getClientScript()->registerScript(__CLASS__.'#'.$id, $js);
    }

    /**
     * Initializes the widget.
     */
    public function init() {
        parent::init();
        $this->registerScripts();
        $this->htmlOptions['multiple'] = 'multiple';
        $this->options = array_merge(array(
            'height' => 300,
            'selectAll' => true,
			'header' => true,
            'selectedList' => 200,
            'noneSelectedText' => 'Todos',
            'oneOrMoreSelected' => '% selecionado(s)',
        ), $this->options);
    }

    /**
     * Registers the JS and CSS Files
     */
    protected function registerScripts() {
        parent::registerCoreScripts();
        $assets = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.multiselect') . '/assets');
        $cs = Yii::app()->getClientScript();
        $cs->registerCssFile($assets . '/jquery.multiselect.css');

        $cs->registerScriptFile($assets . '/jquery.multiselect.min.js', CClientScript::POS_BEGIN);
        $cs->registerScriptFile($assets . '/jquery.multiselect.filter.min.js', CClientScript::POS_BEGIN);
        $cs->registerScriptFile($assets . '/jquery.multiselect.br.js', CClientScript::POS_BEGIN);
        $cs->registerCss('multiselectIndex','.ui-multiselect-menu {z-index: 999999!important;}');

    }
}
