<?php
/**
 * @version    $Id$
 * @package    IT_Theme_Framework
 * @author     InnoThemes Team <support@innothemes.com>
 * @copyright  Copyright (C) 2012 InnoThemes.com. All Rights Reserved.
 * @license    GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Websites: http://www.innothemes.com
 */

// Prepare attributes
$this->attributes['name'] = $this->multiple ? "{$this->name}[]" : $this->name;

if ( $this->multiple ) {
	$this->attributes['multiple'] = 'multiple';
} elseif ( isset( $this->attributes['multiple'] ) ) {
	unset( $this->attributes['multiple'] );
}
?>
<div class="it-form-field-select">
	<select <?php $this->html_attributes( array('placeholder', 'value' ) ); ?>>
<?php if ( $this->placeholder ) : $num_option = 1; ?>
		<option value=""><?php esc_html_e( $this->placeholder, IT_THEME_TEXTDOMAIN ); ?></option>
<?php
endif;

// Backup original attributes
$original_attrs = $this->attributes;

// Count number of option
$num_option = isset( $num_option ) ? $num_option + count( $this->choices ) : count( $this->choices );

foreach ( $this->choices as $value => $label ) :

// Update attributes
$this->attributes['value'] = $value;

if ( 1 == $num_option || $this->value == $value ) {
	$this->attributes['selected'] = 'selected';
}

// Prepare additional attributes
if ( is_array( $label ) ) {
	foreach ( $label as $k => $v ) {
		if ( 'label' != $k ) {
			$this->attributes[ $k ] = $v;
		}
	}

	$label = $label['label'];
}
?>
		<option <?php $this->html_attributes( array( 'autocomplete', 'class', 'id', 'name', 'placeholder', 'data-customize-setting-link' ) ); ?>>
			<?php esc_html_e( $label, IT_THEME_TEXTDOMAIN ); ?>
		</option>
<?php
// Trigger click event if option is selected
IT_Init_Assets::load( array( 'it-chosen-js', 'it-chosen-css' ) );

$script = '
		$("div.it-form-field-select select.chosen-box" ).each(function(i, e) {
			!$(e).hasClass("hide") || $(e).removeClass("hide").addClass("unhidden");

			$(e).chosen( {
				disable_search: $(e).hasClass("it-form-field-typography-font-google") ? false : true,
				inherit_select_classes: true
			} );

			!$(e).hasClass("unhidden") || $(e).removeClass("unhidden").addClass("hide").next().addClass("hide");
		});';

IT_Init_Assets::inline( 'js', $script, true );

// Restore original attributes
$this->attributes = $original_attrs;

endforeach;
?>
	</select>
</div>
