/**
 * Admin page javascript
 */
(function( $ ) {
	'use strict';

	var $window = $( window ),
	    $document = $( document ),
	    $body = $( 'body' );
		
	var file_frame;
	
	$(function() {
	
		// Upload control
		$( document.body ).on(
			'click',
			'.custom_media_upload',
			function ( event ) {
				var $el                 = $( this );
				var file_target_input   = $el.parent().find( '.custom_media_input' );
				var file_target_preview = $el.parent().find( '.custom_media_preview' );

				event.preventDefault();

				// Create the media frame.
				file_frame = wp.media.frames.media_file = wp.media(
					{
						// Set the title of the modal.
						title  : $el.data( 'choose' ),
						button : {
							text : $el.data( 'update' )
						},
						states : [
							new wp.media.controller.Library(
								{
									title   : $el.data( 'choose' ),
									library : wp.media.query( { type : 'image' } )
								}
							)
						]
					}
				);

				// When an image is selected, run a callback.
				file_frame.on(
					'select',
					function () {
						// Get the attachment from the modal frame.
						var attachment = file_frame.state().get( 'selection' ).first().toJSON();

						// Initialize input and preview change.
						file_target_input.val( attachment.url ).change();
						file_target_preview.css( { display : 'none' } ).find( 'img' ).remove();
						file_target_preview.css( { display : 'block' } ).append( '<img src="' + attachment.url + '" style="max-width:100%">' );
					}
				);

				// Finally, open the modal.
				file_frame.open();
			}
		);

		// Media Uploader Preview.
		$( 'input.custom_media_input' ).each(
			function () {
				var preview_image  = $( this ).val(),
				    preview_target = $( this ).siblings( '.custom_media_preview' );

				// Initialize image previews.
				if ( preview_image !== '' ) {
					preview_target.find( 'img.custom_media_preview_default' ).remove();
					preview_target.css( { display : 'block' } ).append( '<img src="' + preview_image + '" style="max-width:100%">' );
				}
			}
		);
		
		if ( $.fn.select2 ) {
			$( '.nevo-admin-multiselect-control' ).select2();
		}

		// Color control
		if ( $.fn.wpColorPicker ) {
			$( '.nevo-admin-color-control' ).find( 'input' ).wpColorPicker();
		}

		// Dependency fields
		$body.on( 'change', '.nevo-admin-dependent-field', function() {
			var $field = $( this ),
			    $settings = $( '[data-dependency="' + $field.attr( 'name' ) + '"]' ),
			    value = this.value;

			$settings.hide();
			$settings.each(function() {
				var $setting = $( this ),
				    requirements = $setting.attr( 'data-value' ).split( ',' ),
				    found;

				found = -1 < requirements.indexOf( value ) ? true : false;

				switch ( $setting.attr( 'data-operator' ) ) {
					case '!=':
						if ( ! found ) $setting.show();
						break;

					default:
						if ( found ) $setting.show();
						break;
				}
			});
		});
		$( '.nevo-admin-dependent-field' ).trigger( 'change' );

		// Tabs
		$( '.nevo-admin-page-settings' ).each(function() {
			var $metabox = $( this ),
			    $navigation = $metabox.find( '.nevo-admin-nav' ),
			    $panels = $metabox.find( '.nevo-admin-panels' );

			$navigation.on( 'click', '.nevo-admin-nav-item a', function( e ) {
				e.preventDefault();

				var $link = $( this ),
				    $target = $panels.children( $link.attr( 'href' ) );

				if ( $target && ! $target.hasClass( 'active' ) ) {
					$navigation.children( '.nevo-admin-nav-item.active' ).removeClass( 'active' );
					$link.parent( '.nevo-admin-nav-item' ).addClass( 'active' );

					$panels.children( '.nevo-admin-panel.active' ).removeClass( 'active' );
					$target.addClass( 'active' );
				}
			});

			$metabox.trigger( 'nevo-admin-metabox.ready', this );
		});

		/**
		 * Rating notice close button
		 */

		$( '.nevo-rating-notice' ).on( 'click', '.nevo-rating-notice-close', function( e ) {
			var $link = $( this ),
			    $notice = $link.closest( '.nevo-rating-notice' ),
			    repeat = $link.attr( 'data-nevo-rating-notice-repeat' );
				
			 var nonce = nevo_ajax_object.ajax_nonce;
			 
			// Run AJAX to set data after closing the notice.
			$.ajax({
				method: 'POST',
				dataType: 'JSON',
				url: ajaxurl,
				data: {
					action: 'nevo_rating_notice_close',
					repeat_after: repeat,
					_ajax_nonce: nonce,
				},
			});

			// Always remove the notice on current page.
			$notice.fadeTo( 100, 0, function() {
				$notice.slideUp( 100, function() {
					$notice.remove();
				});
			});
		});

		/**
		 * "Nevo Sites Import" plugin installation from theme's dashboard page.
		 */

		$( '.nevo-admin-install-sites-import-plugin-button' ).on( 'click', function( e ) {
			var $button = $( this );

			$button.prop( 'disabled', 'disabled' );
			$button.addClass( 'disabled' );
			$button.html( NevoAdminData.strings.installing );

			return $.ajax({
				method: 'POST',
				dataType: 'JSON',
				url: ajaxurl + '?do=nevo_install_sites_import_plugin',
				cache: false,
				data: {
					action: 'nevo_install_sites_import_plugin',
					plugin_slug: 'nevo-sites-import',
					_ajax_nonce: NevoAdminData.ajax_nonce,
				},
			})
			.done(function( response, status, XHR ) {
				if ( response.success ) {
					$button.html( NevoAdminData.strings.redirecting_to_demo_list );

					window.location = NevoAdminData.sitesImportPageURL;
				} else {
					alert( NevoAdminData.strings.error_installing_plugin );
				}
			});
		});
		/* $('#nevo_page_settings__excerpt_type').on('change', function() {
			if ($(this).val() !== 'custom' && $(this).val() !== '') {
				$('.custom-excerpt_length').hide();
			} else {
				$('.custom-excerpt_length').show();
			}
		});

		if ($('#nevo_page_settings__excerpt_type').val() !== 'custom' && $('#nevo_page_settings__excerpt_type').val() !== '') {
			$('.custom-excerpt_length').hide();
		} else {
			$('.custom-excerpt_length').show();
		} */
		
		
		
		/* $('#nevo_page_settings__excerpt_type').on('change', function() {
			if ($(this).val() !== 'custom') {
				$('.custom-excerpt_length').hide();
			} else {
				$('.custom-excerpt_length').show();
			}
		});
		if ($('#nevo_page_settings__excerpt_type').val() !== 'custom') {
			$('.custom-excerpt_length').hide();
		}
		$('input[name="nevo_page_settings[layout]"]').on('change', function() {
			if ($(this).val() === '') {
				$('.custom-per-page').hide();
			} else {
				$('.custom-per-page').show();
			}
		});
		if ($('input[name="nevo_page_settings[layout]"]').val() === '') {
			$('.custom-per-page').hide();
		}
		$('input[name="nevo_page_settings[layout]"]').on('change', function() {
			var selectedValue = $(this).val();
			if (selectedValue === '') { // 'Customizer' option is selected
				$('input[name="nevo_page_settings[posts_per_page]"]').val('');
			}
		});
		$('select[name="nevo_page_settings[excerpt_type]"]').on('change', function() {
			var selectedValue = $(this).val();
			if (selectedValue === '') { // 'Customizer' option is selected
				$('input[name="nevo_page_settings[excerpt_length]"]').val('');
			}
		}); */
		// Excerpt Type and Layout Handling
        function toggleCustomExcerptLength() {
            if ($('#nevo_page_settings__excerpt_type').val() !== 'custom') {
                $('.custom-excerpt_length').hide();
            } else {
                $('.custom-excerpt_length').show();
            }
        }

        function toggleCustomPerPage() {
			var layoutValue = $('input[name="nevo_page_settings[layout]"]:checked').val();
            if (layoutValue === '') {
                $('.custom-per-page').hide();
                $('input[name="nevo_page_settings[posts_per_page]"]').val('');
            } else {
                $('.custom-per-page').show();
            }
        }

        function resetExcerptLength() {
            var excerptTypeValue = $('select[name="nevo_page_settings[excerpt_type]"]').val();
            if (excerptTypeValue === '') {
                $('input[name="nevo_page_settings[excerpt_length]"]').val('');
            }
        }

        // Initialize on load
        toggleCustomExcerptLength();
        toggleCustomPerPage();
        resetExcerptLength();

        // Bind events
        $('#nevo_page_settings__excerpt_type').on('change', toggleCustomExcerptLength);
        $('input[name="nevo_page_settings[layout]"]').on('change', toggleCustomPerPage);
        $('select[name="nevo_page_settings[excerpt_type]"]').on('change', resetExcerptLength);
	});
	
})( jQuery );