<?php
/* 
 * プロフィール表示用Helper
 * i18n対応
 */
class ProfiledispHelper extends Helper {
	var $helpers = array(
		'Html',
		'Text',
		'Form',
		'Select',
	);

	var $i18n_profile_types = array();

	var $profile_type = array();

	var $public_flags= array();

	var $character_has_profile_num = 0;
	var $character_has_profile_cols = 0;

	var $form_id = 0;

	function __construct()
	{
		parent::__construct();

		$this->Character = CorePlus::set_model('Character');
		$this->public_flags = $this->Character->public_flag;
	}


	/**
	 * profile_typeの設定をview表示形式に変換
	 */
	function get_i18n_profile_type($profile_type, $profile_types)
	{
		if (empty($profile_type)) {
			return null;
		}

		if (empty($this->i18n_profile_types)) {
			$this->i18n_profile_types = $this->set_profile_type($profile_types);
		}

		return $this->i18n_profile_types[$profile_type];
	}
	/**
	 * profile_typeの選択プルダウン出力
	 * i18n対応
	 */
	function create_profile_type_select($profile_types = array(), $fieldName = 'profile_type', $options = array('type' => 'select'))
	{
		if (!isset($options['type'])) {
			$options['type'] = 'select';
		}
		if (!isset($options['options'])) {
			$options['options'] = array();
		}
		$options['options'] = $this->set_profile_type($profile_types, $options['options']);

		return $this->Form->input($fieldName, $options);
	}
	/* profile_typeの設定を、key->value(多言語化対応)に変換 */
	function set_profile_type($profile_types = array(), $options = array())
	{
		if (!empty($options)) {
			$this->i18n_profile_types = $options;
		}

		if (empty($profile_types)) {
			$profile_types = CorePlus::get_profile_types();
		}

		foreach ($profile_types as $k => $v) {
			if ($k == 'input') {
				$this->i18n_profile_types[$v] = __('input', true);
			} elseif($k == 'textarea') {
				$this->i18n_profile_types[$v] = __('textarea', true);
			} elseif($k == 'select') {
				$this->i18n_profile_types[$v] = __('select', true);
			} elseif($k == 'radio') {
				$this->i18n_profile_types[$v] = __('radio', true);
			} elseif($k == 'checkbox') {
				$this->i18n_profile_types[$v] = __('checkbox', true);
			} elseif($k == 'm-input') {
				$this->i18n_profile_types[$v] = __('multi input', true);
			} elseif($k == 'table') {
				$this->i18n_profile_types[$v] = __('table', true);
			} elseif($k == 's-table') {
				$this->i18n_profile_types[$v] = __('static table', true);
			} else {
				$this->i18n_profile_types[$v] = $v;
			}
		}

		return $this->i18n_profile_types;
	}

	/* profileの設定をフォームで出力 */
	function disp_form4profile($profile, $form_num = 2, $disp_add_link = false, $disp_public = false, $options = array())
	{
		if (CorePlus::get_profile_type($profile['profile_type']) == 'textarea') {
			$options['type'] = 'textarea';
		} else {
			$options['type'] = 'text';
		}

		$character_id = null;
		if (isset($options['character_id'])) {
			$character_id = $options['character_id'];
		}

		$isMulti = false;
		if ($options['type'] == 'textarea') {
			$isMulti = true;
		}

		if (!CorePlus::is_valid($profile, 'CharactersHasProfile.0.value')) {
			$profile['CharactersHasProfile'][0]['value'] = null;
		}

		$result = '';

		foreach ($profile['CharactersHasProfile'] as $k => $v) {
			$disp_profile = $this->_get_profile_tag($profile['id'], $v['value'], false, $options);

			if ($disp_public) {
				$result .= $this->Html->tag('li', $this->dispPublicFlag4Profile($disp_profile, $this->character_has_profile_num, $v, false))."\n";
			} else {
				$result .= $this->Html->tag('li', $disp_profile. $this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.public_flag', array(
					'type' => 'hidden',
					'value' => 1,
				)));
			}

			$this->character_has_profile_num++;
		}

		if ($this->profile_type['is_multi']) {
			for ($i=0;$i<$form_num;$i++) {
				$disp_profile =  $this->_get_profile_tag($profile['id'], null, false, $options);

				if ($disp_public) {
					$result .= $this->Html->tag('li', $this->dispPublicFlag4Profile($disp_profile, $this->character_has_profile_num, $profile, $isMulti))."\n";
				} else {
					$result .= $this->Html->tag('li', $disp_profile. $this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.public_flag', array(
					'type' => 'hidden',
					'value' => 1,
				)));
				}

				$this->character_has_profile_num++;
			}

			$result = $this->Html->tag('ul', $result, array(
				'id' => 'ProfileId'. $profile['id'],
			));

			if ($disp_add_link) {
				$result .= $this->Html->div('editLink', $this->Html->link(
					__('Add Column', true),
					array(
						'action' => 'add_multi_profiles',
						$options['character_id'].
						'/profile_id:'.$profile['id']
					),
					null,
					__('If some data have been changed, you should save before click it. OK?', true)
				));
			}
		}

		echo $result;
	}
	function _get_profile_tag($profile_id, $value = null, $label = false, $options = array())
	{
		if (empty($profile_id)) {
			return null;
		}

		$name1 = sprintf('CharactersHasProfile.%s.value', $this->character_has_profile_num);
		$name2 = sprintf('CharactersHasProfile.%s.profile_id', $this->character_has_profile_num);
		$options = array_merge(array(
			'label' => $label,
			'value' => $value,
			), $options
		);

		$profile_tag = 
			$this->Form->input($name1, $options).
			$this->Form->input($name2, array(
				'type' => 'hidden',
				'value' => $profile_id,
			));
		if ($options['type'] == 'textarea') {
			$name3 = sprintf('CharactersHasProfile.%s.is_textarea', $this->character_has_profile_num);
			$profile_tag .= $this->Form->input($name3, array(
				'type' => 'hidden',
				'value' => 1,
			));
		}

		return $profile_tag;
	}

	function dispPublicFlag4Profile($profile, $profile_num, $public_flag = null, $isMulti = false)
	{
		$profilePublicName = sprintf('CharactersHasProfile.%d.public_flag', $profile_num);

		if (is_array($profile) && isset($profile['CharactersHasProfile'][0]['public_flag'])) {
			$selected_public_flag = $profile['CharactersHasProfile'][0]['public_flag'];
		} elseif(is_array($public_flag) && isset($public_flag['public_flag'])) {
			$selected_public_flag = $public_flag['public_flag'];
		} elseif (is_string($public_flag)) {
			$selected_public_flag = $public_flag;
		} else {
			$selected_public_flag = null;
		}

		$publicSelect = array(
			'label' => false,
			'div' => 'profilePublic',
			'value' => $selected_public_flag, 
		);
		if ($isMulti === true) {
			$publicSelect['div'] = 'profilePublic profilePublicMulti';
		}

		if (!empty($profile)) {
			$publicSelect['before'] = $profile;
		}

		$public_select = $this->Select->create_publicflag_select($this->public_flags, $profilePublicName, $publicSelect);
		if (!empty($profile)) {
			$public_select .= '<WBR>';
		}

		return $public_select;
	}

	/* profile_selectsの設定を出力 */
	function disp4profile_selects($profile_selects, $disp_public = false, $option = array())
	{
		foreach ($profile_selects as $k => $v) {
			$options[stripcslashes($v['value'])] = stripcslashes($v['value']);
		}
		$options = array_merge(
			array(
			'type' => 'select',
			'options' => $options,
			),
			$option
		);

		$profile_select_tag = 
			 $this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.value', $options).
			 $this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.profile_id', array(
				'type' => 'hidden',
				'value' => $profile_selects[0]['profile_id'],
			)).
			 $this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.profile_select_id', array(
				'type' => 'hidden',
				'value' => $profile_selects[0]['id'],
			));
		$profile = $profile_select_tag;

		if ($disp_public) {
			echo $this->dispPublicFlag4Profile($profile, $this->character_has_profile_num, $options['public_flag']);
		} else {
			echo $profile. $this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.public_flag', array(
				'type' => 'hidden',
				'value' => 1,
			));
		}

		$this->character_has_profile_num++;
	}


	/* profile_selectsの設定をプルダウンで出力 */
	function disp_select4profile_selects($profile_selects, $characters_has_profile = array(), $options = array(), $label = false, $legend = false, $disp_public = false, $isProfileDefault = false)
	{
		if (empty($profile_selects)) {
			return null;
		}

		$selected = $this->set_form_value($profile_selects, $characters_has_profile, $isProfileDefault);

		$public_flag = null;
		if (isset($characters_has_profile[0]['public_flag'])) {
			$public_flag = $characters_has_profile[0]['public_flag'];
		}

		$options = array_merge(
			array(
				'type' => 'select',
				'label' => $label,
				'legend' => $legend,
				'selected' => $selected['value'],
				'public_flag' => $public_flag,
			),
			$options
		);

		$this->disp4profile_selects($profile_selects, $disp_public, $options);
	}

	/* profile_selectsの設定をラジオボタンで出力 */
	function disp_radio4profile_selects($profile_selects, $characters_has_profile = array(), $label = false, $legend = false, $disp_public = false)
	{
		if (empty($profile_selects)) {
			return null;
		}

		$selected = $this->set_form_value($profile_selects, $characters_has_profile);
		if ($selected['value']) {
			$selected_value = $selected['value'];
		} else {
			$first = reset($profile_selects);
			$selected_value = $first['value'];
		}

		$public_flag = null;
		if (isset($characters_has_profile[0]['public_flag'])) {
			$public_flag = $characters_has_profile[0]['public_flag'];
		}

		$options = array(
			'type' => 'radio',
			'value' => $selected_value,
			'label' => $label,
			'legend' => $legend,
			'public_flag' => $public_flag,
			'div' => array(
				'class' => 'input radio inline'
			),
		);

		return $this->disp4profile_selects($profile_selects, $disp_public, $options);

	}

	/* profile_selectsの設定をチェックボックスで出力 */
	function disp_checkbox4profile_selects($profile_selects, $characters_has_profile = array(), $label = false, $legend = false, $disp_public = false, $isProfileDefault = false)
	{
		if (empty($profile_selects)) {
			return null;
		}

		foreach($profile_selects as $k => $v) {
			if (empty($v)) {
				continue;
			}

			$profile_select[0] = $v;
			$has_profile[0] = $this->get_selected_profile($v, $characters_has_profile, $isProfileDefault);
			$this->disp_select4profile_selects(
				$profile_select, 
				$has_profile,
				array(
					'multiple' => 'checkbox',
					'label' => $label,
					'legend' => $legend,
					'div' => array(
						'class' => 'input checkbox inline'
					),
				), $label, $legend, $disp_public, $isProfileDefault
			);
		}
	}

	/* profile_tablesの設定からtableHeadersを出力 */
	function disp_th4profile_tables($profile_tables, $tableId = null, $disp_public = false, $tr_options = array(), $th_options = array(), $isAction = false)
	{
		if (empty($profile_tables)) {
			return null;
		}

		$values = array();
		$style_options = array();
		$i = 1;
		foreach ($profile_tables as $k => $v) {
			$values[$k] = $v['title'];

			if ($v['width']) {
				$key = '#'.$tableId.' td.column-' . $i;
				$style_options[$key] = array('width' => $v['width']."px");
				$key = '#'.$tableId.' td.column-' . $i. ' input';
				$style_options[$key] = array('width' => $v['width']."px");
			}
			$i++;
		}

		if ($disp_public === true) {
			$values[] = __('Public Flag', true);
		}

		if ($isAction === true) {
//			$values[] = "&nbsp;";
			$values[] = __('Actions', true);
		}

		if (!empty($style_options)) {
			echo '<style type="text/css"><!--'."\n";
			foreach($style_options as $k => $v) {
				echo $k. " {\n";
				echo $this->Html->style($v);
				echo "}\n";
			}
			echo '--></style>';
		}

		$table_header = $this->Html->tableHeaders(
			$values,
			$tr_options,
			$th_options
		);

		$table_header = '<thead>'.$table_header.'</thead>';

		echo $table_header;
	}

	/* characters_has_profilesの設定からtableCellsを出力 */
	function disp_td4characters_has_profiles($characters_has_profiles, $oddTrOptions = null, $evenTrOptions = null, $useCount = false, $continueOddEven = true)
	{
		if (empty($characters_has_profiles)) {
			return null;
		}

		if (isset($characters_has_profiles[0]['ProfileTableStatic'])) {
			$statics = $characters_has_profiles[0]['ProfileTableStatic'];
		}

		$values = array();
		foreach ($characters_has_profiles as $k => $v) {
			if (is_string($v)) {
				$values[$k] = $v;
			} else {
				$values[$k] = $v['value'];
			}
		}

		$table_cells = $this->Html->tableCells($values, $oddTrOptions, $evenTrOptions, $useCount, $continueOddEven);

		echo $table_cells;
	}

	/* characters_has_profileからtable td出力 */
	function disp_tds4characters_has_profiles($characters_has_profile, $type = 'view', $publicOnly = true, $profile_type = null, $oddTrOptions = null, $evenTrOptions = null, $useCount = false, $continueOddEven = true, $isProfileDefault = false, $isAction = false)
	{
		$i = 1;
		$profile_num = 0;
		$profiles[$i] = array();
		$profile_id = null;
		foreach($characters_has_profile as $k => $v) {
			if (is_null($profile_id) && CorePlus::is_valid($v, 'profile_id')) {
				$profile_id = $v['profile_id'];
			}
			if (!CorePlus::is_valid($v, 'profile_id')) {
				if (!is_null($profile_id) && !CorePlus::is_valid($v, 'profile_id')) {
					$v['profile_id'] = $profile_id;
				} else {
					continue;
				}
			}

			if (!CorePlus::is_valid($v, 'profile_table_id')) {
				$profile_table_ids = array_keys(Set::combine($characters_has_profile, '{n}.profile_table_id'));

				if (!empty($prof_table_ids)) {
					$v['profile_table_id'] = current(array_slice($prof_table_ids, $profile_num+1, 1));
					$v['value'] = null;
				} else {
					$v['profile_table_id'] = null;
					$v['value'] = null;
					continue;
				}
			}

			if (isset($v['id'])) {
				$v['pre_id'] = $v['id'];
			} else {
				$v['pre_id'] = null;
			}
			$v['id'] = $v['profile_table_id'];

			if (isset($profiles[$i][$v['profile_table_id']])) {
				$i++;
			}
			$profiles[$i][$v['profile_table_id']] = $v;

			$profile_num++;
		}
		$forms = array();

		foreach($profiles as $k => $v) {
			if ($type == 'form') {
				$tds = $this->disp_form4profile_tables($v, $publicOnly, $oddTrOptions, $evenTrOptions, true, true, $isProfileDefault, $isAction);
			} else {
				$tds = $this->disp_value4profile_tables($v, $publicOnly, $profile_type, null, null, true, $isProfileDefault);
			}
		}
		$this->character_has_profile_cols = 0;

		$this->disp_td4characters_has_profiles($tds, $oddTrOptions, $evenTrOptions, $useCount, $continueOddEven);
	}


	/* characters_has_profileからvalue出力 */
	function disp_value_td4characters_has_profiles($characters_has_profile, $publicOnly = true, $profile_type = null)
	{
		$this->disp_tds4characters_has_profiles($characters_has_profile, 'view', $publicOnly, $profile_type, null, null, true);
	}

	/* characters_has_profileからtdフォーム出力 */
	function disp_form_td4characters_has_profiles($characters_has_profile, $disp_public = false, $profile_type = null, $isProfileDefault = false, $isAction = false)
	{
		if ($disp_public === true) {
			$publicOnly = false;
		} else {
			$publicOnly = true;
		}
		$this->disp_tds4characters_has_profiles($characters_has_profile, 'form', $publicOnly, $profile_type, null, null, true, true, $isProfileDefault, $isAction);
	}

	/* profile_tablesの設定からView表示を出力 */
	function disp_value4profile_tables($profile_tables, $publicOnly = true, $profile_type = null, $oddTrOptions = null, $evenTrOptions = null, $useCount = false, $continueOddEven = true, $isProfileDefault = false)
	{
		if (empty($profile_tables)) {
			return null;
		}

		$tds = array();
		$i = 0;
		foreach ($profile_tables as $k => $v) {
			if (!Set::check($v, 'value')) {
				$v['value'] = "&nbsp";
			} elseif (!$this->isPublic($v, $publicOnly)) {
				$v['value'] = "&nbsp";
			}
			if(!$publicOnly && $v['public_flag'] != 1) {
				$v['value'] = $this->Html->tag('span', $v['value'], array('class' => 'publicFlagBg'));
			}
			if ($this->isPublic($v, $publicOnly)|| CorePlus::get_profile_type($profile_type) != 'table') {
				$tds[] = $v['value'];
			}
			$i++;
		}

		$this->disp_td4characters_has_profiles($tds, $oddTrOptions, $evenTrOptions, $useCount, $continueOddEven);
	}

	/* profile_tablesの設定から入力フォームを出力 */
	function disp_form4profile_tables($profile_tables, $publicOnly = true, $oddTrOptions = null, $evenTrOptions = null, $useCount = false, $continueOddEven = true, $isProfileDefault = false, $isAction = false)
	{
		if (empty($profile_tables)) {
			return null;
		}
		$first = reset($profile_tables);

		if (isset($first['ProfileTableStatic'])) {
			$statics = $first['ProfileTableStatic'];
		}

		$ids = array();
		$forms = array();
		$i = 0;
		$first_num = $this->character_has_profile_num;
		foreach ($profile_tables as $k => $v) {
			if (!Set::check($v, 'profile_id')) {
				continue;
			}

			if (!Set::check($v, 'profile_table_id')) {
				$v['profile_table_id'] = null;
			}


			if (isset($v['pre_id'])) {
				$ids[] = $v['pre_id'];
			} else {
				$ids[] = $v['id'];
			}
			if (!Set::check($v, 'id')) {
				if (Set::check($v, 'profile_table_id')) {
					$v['id'] = $v['profile_table_id'];
				} else {
					continue;
				}
			}

			if (!Set::check($v, 'value')) {
				$v['value'] = null;
			}

			if ($i == 0 && (isset($statics[$this->character_has_profile_cols]) || (isset($v['profile_table_static_id']) && !empty($v['profile_table_static_id'])))) {
				$value = isset($v['profile_table_static_id']) ? $v['value']: $statics[$this->character_has_profile_cols]['title']; 
				$form = '<span class="staticHead">'.$value.'</span>'.
					$this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.value', array(
						'type' => 'hidden',
						'value' => $value,
					));
			} else {
				$form = $this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.value', array(
					'type' => 'text',
					'label' => false,
					'class' => 'longInput',
					'value' => $v['value'],
				));
			}

			if (isset($v['profile_table_static_id'])) {
				$profile_table_static_id = $v['profile_table_static_id'];
			} elseif (isset($profile_tables[0]['ProfileTableStatic'][$this->character_has_profile_cols]['id'])) {
				$profile_table_static_id = $profile_tables[0]['ProfileTableStatic'][$this->character_has_profile_cols]['id'];
			} else {
				$profile_table_static_id = null;
			}

			$forms[] = 
				$form.
				$this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.profile_id', array(
					'type' => 'hidden',
					'value' => $v['profile_id'],
				)).
				$this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.profile_table_id', array(
					'type' => 'hidden',
					'value' => $v['id'],
				)).
				$this->Form->input('CharactersHasProfile.'.$this->character_has_profile_num.'.profile_table_static_id', array(
					'type' => 'hidden',
					'value' => $profile_table_static_id,
				));

			$this->character_has_profile_num++;
			$i++;
		}

		if ($publicOnly === false) {
			$last = end($profile_tables);
			if ($isProfileDefault && isset($last["public_flag"])) {
				$forms[] = $this->dispPublicFlag4Profile(null, $first_num, $last["public_flag"], false);
			} else {
				$forms[] = $this->dispPublicFlag4Profile(null, $first_num, $first, false);
			}
		}

		if ($publicOnly === false && $isProfileDefault === true) {
			if (!empty($ids) && $isAction === true) {
				$forms[] = $this->Html->link(__('Delete', true),
					array(
						'action' => 'delete_all',
						implode('_', $ids),
					),
					array(
						'class' => 'actions',
					)
				);
			} else {
//				$forms[] = "&nbsp;";
			}
		}

		$this->character_has_profile_cols++;

		$this->disp_td4characters_has_profiles($forms, $oddTrOptions, $evenTrOptions, $useCount, $continueOddEven);

		if ($publicOnly) {
			echo $this->Form->input('CharactersHasProfile.'.$first_num.'.public_flag', array(
				'type' => 'hidden',
				'value' => 1,
			));;
		}
	}

	/* profile_tablesの設定からブランクのtableCellsを出力 */
	function disp_blank_td4profile_tables($profile_tables, $num = 2, $oddTrOptions = null, $evenTrOptions = null, $useCount = false, $continueOddEven = true)
	{
		if (empty($profile_tables)) {
			return null;
		}

		$blank = array_fill(0, count($profile_tables), $this->Html->div('blank', "&nbsp;"));

		for ($i=0; $i<$num; $i++) {
			$this->disp_td4characters_has_profiles($blank, $oddTrOptions, $evenTrOptions, $useCount, $continueOddEven);
		}
	}

	/* Profile種類を判断 */
	function set_profile_type4view($profile)
	{
		$this->profile_type = array(
			'is_subsetting' => false,
			'is_select' => false,
			'is_radio' => false,
			'is_checkbox' => false,
			'is_table' => false,
			'is_multi' => false,
		);

		if (CorePlus::get_profile_type($profile['profile_type']) == 'select' || CorePlus::get_profile_type($profile['profile_type']) == 'radio' || CorePlus::get_profile_type($profile['profile_type']) == 'checkbox'  || CorePlus::get_profile_type($profile['profile_type']) == 'table' ) {
			$this->profile_type['is_subsetting'] = true;
		}
		if (CorePlus::get_profile_type($profile['profile_type']) == 'select') {
			$this->profile_type['is_select'] = true;
		}
		if (CorePlus::get_profile_type($profile['profile_type']) == 'radio') {
			$this->profile_type['is_radio'] = true;
		}
		if (CorePlus::get_profile_type($profile['profile_type']) == 'checkbox') {
			$this->profile_type['is_checkbox'] = true;
		}
		if (CorePlus::get_profile_type($profile['profile_type']) == 'table' || CorePlus::get_profile_type($profile['profile_type']) == 's-table') {
			$this->profile_type['is_table'] = true;
		}
		if (CorePlus::get_profile_type($profile['profile_type']) == 'm-input') {
			$this->profile_type['is_multi'] = true;
		}
	}

	/* profile_typeの設定に応じてフォーム表示
	 * set_profile_type4view($profile)チェック済み前提。
	 */
	function disp_forms4profile_type($profile, $form_num = 2, $table_blank = 2, $disp_add_link = false, $character_id = null, $disp_public = false, $options = array(), $isProfileDefault = false, $isAction = false)
	{
		if (!isset($profile['CharactersHasProfile']) || empty($profile['CharactersHasProfile'])) {
			if (isset($profile['DefaultProfile']) && !empty($profile['DefaultProfile'])) {
				$profile['CharactersHasProfile'] = $profile['DefaultProfile'];
			} else {
				$profile['CharactersHasProfile'] = array();
			}
		}

		if ($this->profile_type['is_select'] || $this->profile_type['is_radio'] || $this->profile_type['is_checkbox']) {
			if ($this->profile_type['is_select']) {
				$this->disp_select4profile_selects($profile['ProfileSelect'], $profile['CharactersHasProfile'], array('div' => array('class' => 'inline')), false, false, $disp_public);
			} elseif ($this->profile_type['is_radio']) {
				$this->disp_radio4profile_selects($profile['ProfileSelect'], $profile['CharactersHasProfile'], false, false, $disp_public);
			} elseif ($this->profile_type['is_checkbox']) {
				$this->disp_checkbox4profile_selects($profile['ProfileSelect'], $profile['CharactersHasProfile'],  false, false, $disp_public, $isProfileDefault);
			}
		} elseif ($this->profile_type['is_table']) {
			if ($disp_public == true) {
				$publicOnly = false;
			} else {
				$publicOnly = true;
			}

			if (isset($profile['id'])) {
				$tableId = 'TableProfileId'. $profile['id'];
			} else {
				$tableId = 'TableProfileId'. $profile['Profile']['id'];
			}
			echo '<table id="'.$tableId.'">';
			$this->disp_th4profile_tables($profile['ProfileTable'], $tableId, $disp_public, array(), array(), $isAction);
			echo '<tbody>';
			if (!empty($profile)) {
				$this->disp_form_td4characters_has_profiles($profile['CharactersHasProfile'], $disp_public, null, $isProfileDefault, $isAction);

			}
			if ((isset($profile['Profile']['profile_type']) && CorePlus::get_profile_type($profile['Profile']['profile_type']) != 's-table')
				|| (isset($profile['profile_type']) && CorePlus::get_profile_type($profile['profile_type']) != 's-table')
				|| (isset($profile['Profile'][0]['profile_type']) && CorePlus::get_profile_type($profile['Profile'][0]['profile_type']) != 's-table')
				|| empty($profile['CharactersHasProfile'])) {
				for ($i=0; $i<intval($form_num); $i++) {
					$this->disp_form4profile_tables($profile['ProfileTable'], $publicOnly, array(), array(), true, true, $isProfileDefault, false);
				}
				$this->character_has_profile_cols = 0;
			}
			if (intval($table_blank) > 0 && CorePlus::get_profile_type($profile['profile_type']) != 's-table') {
				$this->disp_blank_td4profile_tables($profile['ProfileTable'], intval($table_blank), null, null, true);
			}
			echo '</tbody>';
			echo '</table>';
			if ($disp_add_link) {
				$link = null;
				if (CorePlus::get_profile_type($profile['profile_type']) != 's-table') {
					$link = $this->Html->link(
						__('Add Column', true),
						array(
							'action' => 'add_multi_profiles',
							$character_id.
							'/profile_id:'.$profile['id']
						),
						null,
						__('If some data have been changed, you should save before click it. OK?', true)
					);
				}
				if (!empty($profile['CharactersHasProfile'][0]['character_id'])) {
					$link .= " ".$this->Html->link(
						__('Clear', true),
						array(
							'controller' => 'characters_has_profiles',
							'action' => 'delete',
							$profile['id'],
							'character_id:'.$profile['CharactersHasProfile'][0]['character_id'],
						),
						null,
						sprintf(__('Are you sure you want to clear the data of %s?', true), $profile['name'])
					);
				}

				echo $this->Html->div(
					'editLink text', 
					$link
				);
			}

		} else {
			$options = array_merge(array(
				'character_id' => $character_id,
				), $options
			);
			$this->disp_form4profile($profile, $form_num, $disp_add_link, $disp_public, $options);
		}

		if (isset($profile['required']) && $profile['required']) {
			echo $this->Html->tag(
				'div',
				__(' required', true),
				array(
					'class' => 'required'
				)
			);
		}
	}

	/* characters_has_profilesの設定に応じてView表示
	 * set_profile_type4view($profile)チェック済み前提。
	 * $profileのkeyはprofilesのkey_name
	 */
	function disp_values4characters_has_profiles($profile, $table_blank = 2, $disp_add_link = false, $character_id = null, $publicOnly = true)
	{
		if (!isset($profile['CharactersHasProfile']) && !$this->profile_type['is_table']) {
			$profile['CharactersHasProfile'] = array();
		}

		if (!$this->profile_type['is_table']) {
			$num = 0;
			foreach ($profile['CharactersHasProfile'] as $v) {
				if (!empty($v['value']) && $this->isPublic($v, $publicOnly)) {
					if ($num > 0) {
						echo "&nbsp;";
					}


					if (!$publicOnly && isset($v['public_flag']) && $v['public_flag'] != 1) {
						echo $this->Html->tag('span', 
							$this->autoLinkProf($v['value']),
							array(
								'class' => 'publicFlagBg',
							)
						);

						echo $this->Html->tag('span', 
							__('[Private]', true), 
							array(
								'class' => 'publicFlag publicFlagBg',
							)
						);
					} else {
						echo $this->Html->tag('span',
							$this->autoLinkProf($v['value'])
						);
					}

					$num++;
				}
			}

			if ($this->profile_type['is_multi'] && $disp_add_link && CorePlus::get_profile_type($profile['profile_type']) != 's-table') {
				echo $this->Html->div('editLink', $this->Html->link(
					__('Edit', true),
					array(
						'action' => 'add_multi_profiles',
						$character_id.
						'/profile_id:'.$profile['id']
					)
				));
			}

		} else {
			$tableId = 'TableProfileId'. $profile['id'];
			echo '<table id="'.$tableId.'">';
			if (isset($profile['ProfileTable'])) {
				$this->disp_th4profile_tables($profile['ProfileTable'], $tableId);
				echo '<tbody>';
				if (!empty($profile['CharactersHasProfile'])) {
					$this->disp_value_td4characters_has_profiles($profile['CharactersHasProfile'], $publicOnly, $profile['profile_type']);
				} else {
					if (intval($table_blank) > 0) {
						$this->disp_blank_td4profile_tables($profile['ProfileTable'], intval($table_blank));
					}
				}
				echo '</tbody>';
			}
			echo '</table>';
			if ($disp_add_link) {
				$link = $this->Html->link(
					__('Edit', true),
					array(
						'action' => 'add_multi_profiles',
						$character_id.
						'/profile_id:'.$profile['id']
					)
				);
				if (isset($profile['CharactersHasProfile'][0]) && !empty($profile['CharactersHasProfile'][0]['character_id'])) {
					$link .= " ".$this->Html->link(
						__('Clear', true),
						array(
							'controller' => 'characters_has_profiles',
							'action' => 'delete',
							$profile['id'],
							'character_id:'.$profile['CharactersHasProfile'][0]['character_id'],
						),
						null,
						sprintf(__('Are you sure you want to clear the data of %s?', true), $profile['name'])
					);
				}
				echo $this->Html->div(
					'editLink text', 
					$link
				);
			}
		}
	}

	/* フォームに値入力 */
	function set_form_value($profile_selects, $characters_has_profile, $isProfileDefault = false)
	{
		$this->form_id++;

		if ($this->profile_type['is_select'] || $this->profile_type['is_radio'] || $this->profile_type['is_checkbox']) {
			return $this->set_form_value_select($profile_selects, $characters_has_profile, $isProfileDefault);
		} elseif ($this->profile_type['is_table']) {
			return $this->set_form_value_table($characters_has_profile);
		} else {
//			return $profile_selects;
			return $this->set_form_value_profile($profile_selects, $characters_has_profile);
		}

	}

	/* profile_select */
	/* profile_select_id->profile_idで抽出 */
	function set_form_value_select($profile_selects, $characters_has_profile, $isProfileDefault = false)
	{
		if (isset($characters_has_profile[0]['value'])) {
			$selected = array(
				'value' => $characters_has_profile[0]['value'],
			);
			if (isset($characters_has_profile[0]['public_flag'])) {
				$selected['public_flag'] = $characters_has_profile[0]['public_flag'];
			}
			if (isset($characters_has_profile[0]['link_value'])) {
				$selected['link_value'] = $characters_has_profile[0]['link_value'];
			}
		} else {
			$selected = array(
				'value' => '',
				'public_flag' => '',
				'link_value' => '',
			);
		}

		return $selected;
	}
	/* profile_table */
	function set_form_value_table($profile_selects, $characters_has_profile)
	{
	}

	/* postからprofile_select_id->profile_idで抽出 */
	function get_selected_profile($profile_select, $characters_has_profile, $isProfileDefault = false)
	{
		$profile = array(
			'profile_select_id' => $profile_select['id'],
			'profile_id' => $profile_select['profile_id'],
		);

		if (!empty($isProfileDefault)) {
		} else {
			$profile['value'] = $profile_select['value'];
		}

		foreach ($characters_has_profile as $v) {
			if (Set::contains($v, $profile)) {
				return $v;
			}
		}

		return array();

	}

	function isPublic($profile, $publicOnly = true) 
	{
		if ($publicOnly && !CorePlus::check_public_flag($profile)) {
			return false;
		}

		return true;
	}

	function autoLinkProf($value)
	{
		if (!$value) {
			return null;
		}

		// URL espaceの解除
		$patterns = array("/\&amp;/", "/\&#37;/", "/\&#43;/", "/\&#45;/");
		$replacements = array("&", "%", "+", "-");
		$value = preg_replace($patterns, $replacements, $value);

		return $this->Text->autoLinkUrls(
			$value,
			array(
				'target' => '_blank',
				'escape' => false,
			)
		);
;
	}

	/* ProfileTableを横並びに表示(行単位) */
	function dispTableBySideways($profile, $key_name = 'title', $option = array())
	{
		$option = array_merge(array(
			'header' => null,
			'type' => 'text',
			'tabindex' => array(
				'start' => 0,
				'gap' => 0,
			),
			'add_column' => array(),
			'form_options' => array(),
			'tr_options' => array(),
			'td_options' => array(),
		), $option);

		if (!isset($profile['ProfileTable']) || empty($profile['ProfileTable'])) {
			if (isset($option['add_column']) && empty($option['add_column'])) {
				return null;
			}
		}

		if (!empty($option['add_column'])) {
			$add_profile = array(
				'id' => 0,
				'profile_id' => $profile['Profile']['id'],
				'title' => '',
				'tablekey_name' => '',
				'width' => '',
				'sort_order' => '',
				'ProfileTableStatic' => array(),
			);
			if (isset($option['add_column']['data']) && isset($add_profile[$key_name])) {
				$add_profile[$key_name] = $option['add_column']['data'];
			}
			if (isset($option['add_column']['place']) && $option['add_column']['place'] == 'top') {
				array_unshift($profile['ProfileTable'], $add_profile);
			} else {
				array_push($profile['ProfileTable'], $add_profile);
			}
		}

		$rows = count($profile['ProfileTable']);
		if (!empty($option['header'])) {
			$tds = $this->Html->tag('th', $option['header'], array('style' => 'width:65px;'));
		} else {
			$tds = null;
		}

		for ($i=0; $i<$rows;$i++) {
			if (!isset($profile['ProfileTable'][$i][$key_name])) {
				$profile['ProfileTable'][$i][$key_name] = null;
			}

			if ($option['type'] == 'form') {
				$tabindex = $option['tabindex']['start'] + $option['tabindex']['gap'] * $i;
				$form_options = array_merge(
					array(
						'type' => 'text',
						'value' => $profile['ProfileTable'][$i][$key_name],
						'label' => false,
						'tabindex' => $tabindex,
					),
					$option['form_options']
				);

				$content = $this->Form->input(
					'ProfileTable.'.$profile['ProfileTable'][$i]['id'].'.'.$key_name,
					$form_options
				);
				$option['td_options'] = array_merge($option['td_options'], array('escape' => false));
			} else {
				if (isset($option['add_column']['place']) &&
					(($option['add_column']['place'] == 'top' && $i == 0) || 
					($option['add_column']['place'] != 'top' && $i == $rows - 1))) {
					$content = __('Add', true);
				} else {
					$content = $profile['ProfileTable'][$i][$key_name];
				}
			}

			$tds .= $this->Html->tag('td', $content, $option['td_options']);
		}

		return $this->Html->tag('tr', $tds, $option['tr_options']);
	}


	/* 一定の文字数で複数行に折り返すtruncate
	 * マルチバイト対応
	 * URLやタグはスキップしない
	 * @param array $options is for truncate()
	 */
	function multi_truncate($text, $length = 20, $rows = 3, $options = array())
	{
		if (empty($text)) {
			return $text;
		}

		$rows = (int)$rows;
		if (!($rows > 0)) {
			$rows = 1;
		}

		// 置換
		$replace_pairs = array(
			// 改行
			'<br>' => "\n",
			'<br />' => "\n",
			// スペースの連続
			"\s\s" => "\s",
			'　' => '',
		);
		$text = strtr($text, $replace_pairs);

		// Sanitize戻し
		$Sanitize = CorePlus::set_behavoir('SanitizePlus');
		$text = $Sanitize->restore_html($this->model(), $text);

		$text = trim($text);

		if (mb_strlen($text) < $length) {
			return $text;
		}

		// 複数行対応
		$result = array();
		$last_row = '';
		for ($i = 1; $i <= $rows; $i++) {
			if ($i > 1) {
				if (!$text) {
					break;
				}

				// 前行の分を切り取り
				if (!empty($last_row)) {
					$text = substr_replace($text, '', 0, strlen($last_row));
				}
			}
			if ($i == $rows) {
				$text_len = mb_strlen($text);

				if ($text_len < $length) {
					$result[$i] = $text;
				} else {
					$result[$i] = $this->Text->truncate($text, mb_strlen(mb_substr($text, 0, $length)), $options);
				}

				break;
			} else {
				$result[$i] = mb_substr($text, 0, $length);
			}

			$last_row = $result[$i];
			$result[$i] = strip_tags($result[$i]);


			// タグをエスケープ
			$result[$i] = $Sanitize->escapeTags($this->model(), $result[$i]);
		}

		$text = implode("<br />\n", $result);

		return $text;
	}


}

