( function ( $ ) {

	HappyForms.parts = HappyForms.parts || {};

	HappyForms.parts.rank_order = {
		init: function () {
			this.$input = $( 'input, select', this.$el );
            this.$ranks = $( 'ul.happyforms-custom-select-dropdown', this.$el );
			var self = this;

			$( '.happyforms-custom-select', this.$el ).each( function() {
				var $part = $( this );
				var $input = $( 'input[data-serialize]', $part );
				var $visualInput = $( 'input[type=text]', $part );
				var $select = $( '.happyforms-custom-select-dropdown', $part );

				$visualInput.happyFormsSelect( {
					$input: $input,
					$select: $select,
					searchable: false
				} );

				$select.unbind( 'click' );
				$select.on( 'click', 'li', self.onItemSelect.bind( self ) );


			} );


			this.initTooltip();
		},

		onItemSelect: function ( e ) {
			e.stopPropagation();

			var $target = $( e.target );
			var $select = $target.parent();

			if( ! $target.hasClass( 'rank-choice-disable' ) ) {
				var $visualInput =  $select.siblings( 'input[type=text]' );
				var selectedValue = $target.data( 'value' );
				var previousValue = $visualInput.data( 'prev-value' );

				if( selectedValue != previousValue ) {
					$( 'li[data-value="' + selectedValue + '"]', this.$ranks ).not( '.happyforms-rank-clear-button' ).not( $target ).addClass( 'rank-choice-disable' );
					$( 'li[data-value="' + previousValue + '"]', this.$ranks ).not( '.happyforms-rank-clear-button' ).not( $target ).removeClass( 'rank-choice-disable' );
				}

				if( selectedValue == '' ) {
					$( '.happyforms-rank-clear-button', $select ).addClass( 'hide-clear-button' );
				} else {
					$( '.happyforms-rank-clear-button', $select ).removeClass( 'hide-clear-button' );
				}

				$select.siblings( '[data-serialize]' ).val( selectedValue );
				$visualInput.val( selectedValue );
				$visualInput.data( 'prev-value', selectedValue );
			}

			$select.hide();
		},
	};
} ) ( jQuery );