jQuery( document ).ready( function( $ ) {
	"use strict";
	var $body = $( 'body' );

	roxima_alpha_colorpicker_init();
	roxima_repeating_colorpicker_init();
	roxima_repeating_sortable_init();
	roxima_collapsible_init();

    function on_customizer_widget_form_update( e, widget_el ) {
		roxima_alpha_colorpicker_init( widget_el );
		roxima_repeating_colorpicker_init( widget_el );
		roxima_repeating_sortable_init( widget_el );
		roxima_collapsible_init( widget_el );
    }
	// Widget init doesn't occur for some reason, when added through the customizer. Therefore the event handler below is needed.
	// https://make.wordpress.org/core/2014/04/17/live-widget-previews-widget-management-in-the-customizer-in-wordpress-3-9/
	// 'widget-added' is complemented by 'widget-updated'. However, alpha-color-picker shows multiple alpha channel
	// pickers if called on 'widget-updated'
	//$( document ).on( 'widget-updated', on_customizer_widget_form_update );
	$( document ).on( 'widget-added', on_customizer_widget_form_update );



	//Widget Actions on Save
	$( document ).ajaxSuccess( function( e, xhr, options ) {
		if ( options.data.search( 'action=save-widget' ) != -1 ) {
			var widget_id;

			if ( ( widget_id = options.data.match( /widget-id=(ci-.*?-\d+)\b/ ) ) !== null ) {
				var widget = $( "input[name='widget-id'][value='" + widget_id[1] + "']" ).parent();
				roxima_alpha_colorpicker_init( widget );
				roxima_repeating_colorpicker_init();
				roxima_repeating_sortable_init( widget );
				roxima_collapsible_init( widget );
			}

		}
	} );


	$( 'body' ).on( 'click', '.ci-collapsible legend', function() {
		var arrow = $( this ).find( 'i' );
		if ( arrow.hasClass( 'dashicons-arrow-down' ) ) {
			arrow.removeClass( 'dashicons-arrow-down' ).addClass( 'dashicons-arrow-right' );
			$( this ).siblings( '.elements' ).slideUp();
		} else {
			arrow.removeClass( 'dashicons-arrow-right' ).addClass( 'dashicons-arrow-down' );
			$( this ).siblings( '.elements' ).slideDown();
		}
	} );


});

var roxima_collapsible_init = function( selector ) {
	if ( selector === undefined ) {
		jQuery( '.ci-collapsible .elements' ).hide();
		jQuery( '.ci-collapsible legend i' ).removeClass( 'dashicons-arrow-down' ).addClass( 'dashicons-arrow-right' );
	} else {
		jQuery( '.ci-collapsible .elements', selector ).hide();
		jQuery( '.ci-collapsible legend i', selector ).removeClass( 'dashicons-arrow-down' ).addClass( 'dashicons-arrow-right' );
	}
};

var roxima_alpha_colorpicker_init = function( selector ) {
	if ( selector === undefined ) {
		var roxima_AlphaColorPicker = jQuery( '#widgets-right .alpha-color-picker, #wp_inactive_widgets .alpha-color-picker' ).filter( function() {
			return !jQuery( this ).parents( '.field-prototype' ).length;
		} );

		roxima_AlphaColorPicker.alphaColorPicker();
	} else {
		jQuery( '.alpha-color-picker', selector ).alphaColorPicker();
	}
};
