<?php
/**
* EChosen class file.
* 
* @author Andrius Marcinkevicius <andrew.web@ifdattic.com>
* @copyright Copyright &copy; 2011 Andrius Marcinkevicius
* @license Licensed under MIT license. http://ifdattic.com/MIT-license.txt
* @version 1.5.1
*/

/**
* EChosen makes select boxes much more user-friendly.
* 
* @author Andrius Marcinkevicius <andrew.web@ifdattic.com>
*/
class EChosen extends CWidget
{
  /**
  * @var string apply chosen plugin to these elements.
  */
  public $target = '.chzn-select';

  /**
  * @var boolean use jQuery plugin, otherwise use Prototype plugin.
  */
  public $useJQuery = true;

  /**
  * @var boolean use ajax chosen plugin.
  * works only with useJquery = true
  */
  public $useAjax = false;

  /**
  * @var boolean include un-minified plugin then debuging.
  */
  public $debug = false;

  /**
  * @var array native Chosen plugin options.
  */
  public $options = array();

  /**
  * @var int script registration position.
  */
  public $scriptPosition = CClientScript::POS_BEGIN;

  /**
  * Apply Chosen plugin to select boxes.
  */
  public function run()
  {
    $this->debug = YII_DEBUG;

    $assets = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.EChosen') . '/assets');
    $cs = Yii::app()->getClientScript();

    $ext = ($this->debug) ? '.css' : '.min.css';
    $cs->registerCssFile($assets . '/chosen.css');

    $ext = ($this->debug) ? '.js' : '.min.js';

    if($this->useJQuery) {
      $options = array(
        'no_results_text' => "Nada encontrado",
        'placeholder_text_single' => "Selecione",
        'placeholder_text_multiple' => "Selecione"
      );
      $this->options += $options;
      $options = CJavaScript::encode($this->options);

      $cs->registerScriptFile($assets . '/chosen.jquery' . $ext, $this->scriptPosition);
      /*if($this->useAjax) {
        $cs->registerScriptFile($assets . '/ajax-chosen' . $ext, $this->scriptPosition);

        $cs->registerScript('chosen', "$('{$this->target}').ajaxChosen({
            type: 'GET',
            dataType: 'json'
          }, function (data) {
            var terms = {};
            $.each(data, function (key, value) {
              terms[value.id] = value.text;
            });
            return terms;
          });", CClientScript::POS_READY);
        $cs->registerCss('chosen', ".chzn-container .chzn-results .group-result {display: list-item;}");
      } else {*/
        $cs->registerScript('chosen', "$('{$this->target}').chosen({$options});", CClientScript::POS_READY);
      /*}*/
    } else {
      $cs->registerScriptFile($assets . '/chosen.proto' . $ext, $this->scriptPosition);
    }
  }
}