<?php
/* SVN FILE: $Id$ */
/**
 * Pluginクラス
 *
 * PHP versions 5
 *
 *      hitSuji : Social Network Service <http://rakuto.net/rktSNS/>
 *      Copyright (c) 2007 Yujiro Takahashi
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @category        hitSuji
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision$
 * @modifiedby      $LastChangedBy$
 * @lastmodified    $Date$
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * Pluginクラス
 *
 * @category        hitSuji
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision$
 * @modifiedby      $LastChangedBy$
 * @lastmodified    $Date$
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */
class hitsuji_insertPoll extends RKT_plugin
{
    /**
     * 可視範囲
     * @var integer
     */
    protected $visible = null;

    /**
     * チャート数
     * @var integer
     */
    private $_count = 1;

    /**
     * アンケート情報
     * @var array
     */
    private $_poll = null;

    /**
     * 選択肢
     * @var array
     */
    private $_answers = null;

    /**
     * 結果
     * @var array
     */
    private $_results = null;

    /**
     * コンストラクタ
     *
     * @access public
     * @return void
     */
    public function __construct()
    {
        $status = RKT_account::exec()->getStatus();

        $this->visible = VISIBILITY_PUBLIC;      // ネット上に公開
        /* 会員判定 */
        if ($status != STATUS_GUEST){
            $this->visible |= VISIBILITY_PROTECTED;
        }
    }

    /**
     * リッチエディターボタン追加用JavaScript
     *
     * @access public
     * @return string
     */
    public function editorAddButtonJs()
    {
?>
		var imgConfig = {
			type: 'push', label: '<?php _e('Insert Poll'); ?>', value: 'insertPoll',
			menu: function() {
				var menu = new YAHOO.widget.Overlay('insertPoll', {
					width: '188px',
					height: '194px',
					visible: false
				});
				var str = '<iframe src="<?php e(HTTP_ACTION); ?>public/plugin/view/hitsuji/poll/module/" width="188" height="200" frameborder="0"></iframe>';
				menu.setBody('<div>' + str + '</div>');
				menu.beforeShowEvent.subscribe(function() {
					menu.cfg.setProperty('context', [
						myEditor.toolbar.getButtonByValue('insertPoll').get('element'),
						'tl', 'bl'
					]);
				});
				menu.render(document.body);
				menu.element.style.visibility = 'hidden';
				return menu;
			}()
		};
		if (editorType == 'large'){
			myEditor.toolbar.addButtonToGroup(imgConfig, 'insertitem');
		}
<?php
    }

    /**
     * リッチエディター用CSS
     *
     * @access public
     * @return string
     */
    public function editorCss()
    {
?>
.yui-skin-sam .yui-toolbar-container .yui-toolbar-insertPoll span.yui-toolbar-icon {
	background-image: url( <?php e(BASE_URL); ?>resource/img/icons/chart_pie.gif );
	background-position: 1px 0px;
	left: 5px;
}
#insertPoll {
	border:1px solid #808080;
	padding:5px;
	background-color: #F2F2F2;
}
#insertPoll a {
	display: block;
	float: left;
	border: 1px solid #F2F2F2;
}
#insertPoll a:hover {
	border: 1px solid #808080;
}
<?php
    }

    /**
     * リッチエディター用JavaScript
     *
     * @access public
     * @return string
     */
    public function editorJavaScript()
    {
    }

    /**
     * HTML BODY出力用エフェクト
     *
     * @access public
     * @parmas string $value
     * @return string
     */
    public function outputEditorBody($string)
    {
        return $string;
    }

    /**
     * HTML BODY出力用エフェクト
     *
     * @access public
     * @return void
     */
    public function outputEditorLoadJs()
    {
        RKT_View::getInstance()->addJavas('yui/datasource/datasource-beta-min.js');
        RKT_View::getInstance()->addJavas('yui/element/element-beta-min.js');
        RKT_View::getInstance()->addJavas('yui/charts/charts-experimental-min.js');
    }

    /**
     * HTML BODY出力用エフェクト
     *
     * @access public
     * @parmas string $value
     * @return string
     */
    public function outputHtmlBody($string)
    {
        $name2method = array(
            'NonMobile'=>'_pollHtml',
            'DoCoMo'=>   '_pollMobileHtml',
            'EZweb'=>    '_pollMobileHtml',
            'SoftBank'=> '_pollMobileHtml',
            'WILLCOM'=>  '_pollMobileHtml',
        );
        $name = Net_UserAgent_Mobile::singleton()->getCarrierLongName();
        $method = $name2method[$name];

        $callback = array(&$this, $method);
        $result   = preg_replace_callback('/\[poll\:([0-9a-f]+)\]/', $callback, $string);
        return $result;
    }

    /**
     * HTML BODY入力用エフェクト
     *
     * @access public
     * @parmas string $value
     * @return string
     */
    public function requestHtmlBody($string)
    {
        $src = preg_quote(BASE_URL.'resource/img/common/blankpoll.gif','/');

        $pattern = '<img id="(\d+)" src="'.$src.'">';
        $string  = preg_replace('/'.$pattern.'/', '[poll:\1]', $string);
        return $string;
    }

    /**
     * HTML BODY入力用エフェクト
     *
     * @access private
     * @parmas string $value
     * @return string
     */
    private function _pollHtml($matches)
    {
        $this->_setPoll($matches[1]);

        $html = 
            '<table align="center" cellpadding="0" cellspacing="0">'.
            '<tbody><tr><td colspan="2">'.$this->_poll['comment'].'</td></tr><tr>'.
            $this->_pollChart().'</tr><tr><td>'.
            $this->_pollForm().'</td></tr></tbody></table>';
        return $html;
    }

    /**
     * HTML BODY入力用エフェクト
     *
     * @access private
     * @parmas string $value
     * @return string
     */
    private function _pollMobileHtml($matches)
    {
        $this->_setPoll($matches[1]);

        $html  = '<br>'.$this->_poll['comment'].'<br>'."\r\n";
        foreach ($this->_results as $result){
            $html .= $result['response'].'('.$result['count'].')<br>'."\r\n";
        }
        $html .= $this->_pollForm();
    
        return $html;
    }

    /**
     * チャート用HTML
     *
     * @access private
     * @return string
     */
    private function _pollChart()
    {
        $sort = array();
        foreach ($this->_results as $id=>$row){
            $sort[$id] = $row['count'];
        }    
        arsort($sort);
    
        $options = array();
        $row = 0;
        $other = 0;

        $html  = 
            '<td rowspan="2" style="width:200px;">'.
            '<div id="chart'.$this->_count.'">'.
            '<a href="http://www.adobe.com/go/getflashplayer">'.
            'Adobe Flash Player Download</a></div>'.
            '</td><td style="width:280px; text-align:left;"><ul id="legend">';

        foreach ($sort as $id=> $count){
            if ($row < 5){
                $options[] = '{ response: "'.$this->_results[$id]['response'].
                                '", count: '.$this->_results[$id]['count'].' }';
                $html .= '<li class="chart0'.$row.'"><span class="categoryName">';
            } else {
                $other += $count;
                $html .= '<li class="chart05"><span class="categoryName">';
            }
            $row++;

            $html .= 
                $this->_results[$id]['response'].
                '&nbsp;('.$this->_results[$id]['count'].')'.
                '</span></li>';
        }
        if ($other != 0){
            $options[] = '{ response: "'._('Other').'", count: '.$other.' }';
        }
        $html .= 
            '</ul>'."\r\n".'<script type="text/javascript">'."\r\n".
            'YAHOO.util.Event.onContentReady("chart'.$this->_count.'", function () {'."\r\n".
            'YAHOO.widget.Chart.SWFURL = "'.BASE_URL.'resource/yui/charts/assets/charts.swf";'."\r\n".
            'YAHOO.example.publicOpinion = ['. implode(',', $options) .']'."\r\n".
            'var opinionData = new YAHOO.util.DataSource( YAHOO.example.publicOpinion );'."\r\n".
            'opinionData.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;'."\r\n".
            'opinionData.responseSchema = { fields: [ "response", "count" ] };'."\r\n".
            'var mychart = new YAHOO.widget.PieChart( "chart'.$this->_count.'", opinionData, {'."\r\n".
            'dataField: "count", categoryField: "response", series: [{}],'."\r\n".
            'expressInstall: "'.BASE_URL.'resource/yui/charts/assets/expressinstall.swf"});'."\r\n".
            '});</script>'."\r\n".'</td>'."\r\n";
        
        $this->_count++;

        return $html;
    }


    /**
     * チャートフォームHTML
     *
     * @access private
     * @return string
     */
    private function _pollForm()
    {
        $nonce = RKT_Crypt::getNonce('manipNonce');

        $html  = 
            '<form method="post" action="'.HTTP_ACTION.
            'member/poll/answer/'.$this->_poll['id'].'/confirm/">'."\r\n".
            '<input name="_mpnnc" type="hidden" value="'.$nonce.'" />'."\r\n".
            '<select name="answer">'."\r\n";

        foreach ($this->_answers as $id=>$label){
            $html .= 
                '<option label="'.$label.'" value="'.$id.'">'.
                $label.'</option>'."\r\n";
        }
        $html .= 
            '</select>'."\r\n".
            '<input name="confirm" type="submit" value="'._('Answer').
            '" style="width:120px;" />'."\r\n".'</form>'."\r\n";
        return $html;
    }

    /**
     * アンケート用情報の設定
     *
     * @access private
     * @parmas string $code
     * @return string
     */
    private function _setPoll($code)
    {
        $condition = array(
            'code'=>       $code,
            'visibility'=> array('&', $this->visible),
        );
        $this->_poll = RKT_DB::getRow('sum_poll', $condition);
        if (empty($this->_poll)){
            return '';
        }
        $this->_answers = explode("\r\n", $this->_poll['answers']);
        $this->_results = array();
        foreach ($this->_answers as $id=>$answer){
            $condition = array(
                'ref_poll'=> $this->_poll['id'],
                'answer'=>   $id,
            );
            $count = RKT_DB::getRow('sum_answer', $condition, 'count(*) as ct');
            $this->_results[$id] = array(
                'response'=> $answer,
                'count'=>    $count['ct'],
            );
        }
    }
} // RKT_plugin
?>
