(function($){

	function hideAllWidgets() {
		$('#widget-list .widget').hide();
		// $('.widget[id*="losatom_widget_testimonial"]').show();
		// $('.widget[id*="losatom_widget_table"]').show();
		$('.widget[id*="losatom_widget_features"]').show();
		$('#widgets-right .widgets-holder-wrap').hide();
		$('#widgets-right .widgets-holder-wrap:nth-child(3)').show();
		$('#widgets-right .widgets-holder-wrap').first().show();
	}

	function onFormUpdate( event, widget ) {
		
		$( '#widgets-right .widget[id*="losatom_widget_"]' ).each( function() {
			mosWidgetFunctions( $( this ) );
		});		

		$( '#widgets-right .widget[id*="losatom_widget_features"]' ).each( function() {
			initFontPicker( $( this ) );
		});				
	}

	function initFontPicker( widget ) {
		$( '.accordion:not(.hidden) .fpicker', widget ).fontIconPicker({
    		emptyIcon: false,
		});
 	}	
 
	function mosWidgetFunctions( widget ) {

		var $id = '#' + widget.find( '.widget-inside' ).parent().attr( 'id' );

		$( '#widgets-right ' + $id + ' .add-new-button' ).unbind( 'click' ).bind( 'click', function( evt ) {

			evt.preventDefault();
			// Split id (i.e. #widget-1_losatom_widget_checklist-161), grab number from the end -> 161.
			var $x = $id.split( /-/ ); 
			$x = $x[2];

			if ( $( this ).hasClass( 'add-social' ) ) {
				var $y       = $( $id + ' .losatom-social:not(.hidden)' ).length,				
					$object  = $( '.losatom-social.for-cloning', widget ).clone(),
					$element = mosCloneElement( $object, $x, $y, false );
			} else {
				var $y       = $( $id + ' .accordion:not(.hidden)' ).length,				
					$object  = $( '.accordion.for-cloning', widget ).clone(),
					$element = mosCloneElement( $object, $x, $y, true );
					$element.find( '.accordion-title span' ).text( $y+1 );
			}

			$element.insertBefore( $( this ) ).slideDown( 100 ).removeClass( 'hidden for-cloning' );

			/* Init font picker if it exists in cloned element. */
			if ( $element.find( '.fpicker' ) ) {
				$( '.fpicker', $element ).fontIconPicker({
		    		emptyIcon: false,
				});
			}
		});	
 	}

	function mosAttributeReplace( $object, $x, $y ) {

		if ( $object.attr( 'for' ) ) {
			var $for_attr = $object.attr( 'for' ).replace( '__x__', $x ).replace( '__y__', $y );
				$object   = $object.attr( 'for', $for_attr );
		} else {
			var $id   = $object.attr( 'id' ).replace( '__x__', $x ).replace( '__y__', $y ),
				$name = $object.attr( 'name' ).replace( '__x__', $x ).replace( '__y__', $y );

			$object = $object.attr( 'id', $id );
			$object = $object.attr( 'name', $name );
		}

		return $object;
	}	

	function mosCloneElement( $object, $x, $y, $accordion ) {

		var $allowedTags = ['label', 'input', 'textarea', 'select'];
		var $element     = ( true === $accordion ) ? '.accordion-content *' : '*';

		$( $element, $object ).each( function() {
			var $tag = $( this ).prop( 'tagName' ).toLowerCase();
			if ( $.inArray( $tag, $allowedTags ) != -1 ) {
				mosAttributeReplace( $( this ), $x, $y );
			} 

		});

		return $object; 
	}
 

	$( '#widgets-right' ).on( 'click', '.mos-remove-element', mosRemove );

	function mosRemove() {

		$( this ).parent().slideUp( 250, function() {			
			$( this ).remove();
		});		

		var $id = $( this ).parents( '.widget' ).attr( 'id' );
		mosResetFields( $id );

		if ( wp.customize ) {
			$( '.chk-title' ).trigger( 'change' );
		}		

	}

	function mosResetFields( $id ) {

		$( '#' + $id + ' .losatom-social' ).each( function( i ) {
		
			var $inp_id   = $( 'input', this ).attr( 'id' ).replace( /item_\d+/, 'item_'+i );
			var $inp_name = $( 'input', this ).attr( 'name' ).replace( /item_\d+/, 'item_'+i );
			
			$( 'input', this ).attr( 'id', $inp_id );
			$( 'input', this ).attr( 'name', $inp_name );
			$( 'label', this ).attr( 'for', $inp_id );

		});
	}

	$( '#widgets-right' ).on( 'click', '.delete-accordion', mosRemoveAccordion );

	function mosRemoveAccordion() {

		var $id = '#' + $( this ).parents( '.widget' ).attr( 'id' );

		$( this ).hide().parent().slideUp( 250, function() {			
			$( this ).remove();
			mosUpdateAccNumbers( $id );
		});		

		mosResetAccordions( $id );

		if ( wp.customize ) {
			$( '.widget-heading' ).trigger( 'change' );
		}
	}	

	function mosUpdateAccNumbers( $id ) {
		$( $id + ' .accordion:not(.hidden)' ).each(function( i ){
			$( '.accordion-title span', this ).text( i+1 );
		});
	}

	function mosResetAccordions( $id ) {

		var $allowedTags = ['label', 'input', 'textarea', 'select'];		

		$( $id + ' .accordion:not(.hidden)' ).each( function( i ) {

			$( '.accordion-content *', this ).each( function() {

				var $tag = $( this ).prop( 'tagName' ).toLowerCase();

				if ( $.inArray( $tag, $allowedTags ) != -1 ) {

					var $id = $( this ).attr( 'id' );

					if ( 'label' == $tag ) {
						$id = $( this ).attr( 'for' );
					} else {
						var $name = $( this ).attr( 'name' );								
						// widget-losatom_widget_testimonial[37][content_0]
						var $y = $name.split( /_/ );
						$y[$y.length-1] = i-1+']';
						var $new_name = $y.join('_');
					}

					var $x = $id.split( /_/ ); 					
					$x[$x.length-1] = i-1;

					var $new_id = $x.join( '_' );

					if ( 'label' == $tag ) {
						$( this ).attr( 'for', $new_id );
					} else {
						$( this ).attr( 'id', $new_id );							
						$( this ).attr( 'name', $new_name );							
					}
 					
				}
			});

		});

	}

	function mosSlideToggle() {
		$( '#widgets-right' ).on( 'click', '.accordion-title', function() {
			$( this ).next().slideToggle( 100 );	
		});
	}

	function mosUploadFields() {

		var _custom_media = true,
		_orig_send_attachment = wp.media.editor.send.attachment;
		 
		$( document ).on( 'click', '.losatom-upload', function(e) {

			var send_attachment_bkp = wp.media.editor.send.attachment;
			var button = $( this );
			var id = $( this ).prev().attr('id');
 			_custom_media = true;

			wp.media.editor.send.attachment = function( props, attachment ) {
				if ( _custom_media ) {
					$( "#"+id ).val( attachment.url );
				} else {
					return _orig_send_attachment.apply( this, [props, attachment] );
				};
			}

			wp.media.editor.open( button );
			return false;
		});
		 
		$( document ).on( 'click', '.add_media', function() {
			_custom_media = false;
		}); 		
	}	
 
	$( document ).on( 'widget-added widget-updated', onFormUpdate );

	// hideAllWidgets();
	mosSlideToggle();
	mosUploadFields(); 
	onFormUpdate();

})(jQuery);

