<?php

class Intense_Field_Animation extends Intense_Field_Dropdown {
	private function set_default_options() {
		$intense_animations = Intense_Animated::get_animations();

		if ( empty( $this->args['options'] ) ) {
			$categories = intense_get_animation_categories();
			$animation_options = array( '' => '' );

			foreach ( $categories as $category ) {
				$category_animations = array();

				foreach ( $intense_animations as $animation => $attributes ) {
					$animation_source = $attributes[0];
					$animation_category = $attributes[1];
					$starthidden = $attributes[2];
					$endhidden = $attributes[3];

					if ( $category == $animation_category ) {
						$category_animations[] = $animation;
					}
				}

				$animation_options[ $category ] = array();

				natsort( $category_animations );

				foreach ( $category_animations as $animation ) {
					$animation_options[ $category ][] = $animation;
				}
			}

			$this->args['options'] = $animation_options;
		}
	}

	public function render_field() {
		$this->class .= ' selectize animation';
		return parent::render_field();
	}

	public function render_init_script() {
		return "$('.selectize.animation select').not('.repeater-item-model .selectize.animation select').selectize();";
	}

	protected function render() {
		if ( empty( $this->args['class'] ) ) $this->args['class'] = '';
		if ( empty( $this->args['style'] ) ) $this->args['style'] = '';

		$this->args['class'] .= ' selectize';
		$this->args['style'] .= ' width:206px;';

		$this->set_default_options();

		return parent::render();
	}

	public function map_visual_composer() {
		$intense_animations = Intense_Animated::get_animations();

		$this->set_default_options();

		$animations = array();

		foreach ($this->args['options'] as $group_key => $optiongroup) {
			if ( is_array( $optiongroup ) ) {
				foreach ($optiongroup as $key => $value) {
					$animations[ $value ] = $value;
				}
			}
		}

		$this->args['options'] = $animations;

		return parent::map_visual_composer();
	}
}
