<?php
/**
 * WordPress Options Administration API.
 *
 * @package WordPress
 * @subpackage Administration
 * @since 4.4.0
 */

/**
 * Output JavaScript to toggle display of additional settings if avatars are disabled.
 *
 * @since 4.2.0
 */
function options_discussion_add_js() {
	?>
	<script>
	(function($){
		var parent = $( '#show_avatars' ),
			children = $( '.avatar-settings' );
		parent.change(function(){
			children.toggleClass( 'hide-if-js', ! this.checked );
		});
	})(jQuery);
	</script>
	<?php
}

/**
 * Display JavaScript on the page.
 *
 * @since 3.5.0
 */
function options_general_add_js() {
	//Enqueue media.
    wp_enqueue_media();
	
	?>
<script type="text/javascript">
	jQuery(document).ready(function($){
		var $siteName = $( '#site-admin-bar-site-name' ).children( 'a' ).first(),
			homeURL = ( <?php echo wp_json_encode( get_home_url() ); ?> || '' ).replace( /^(https?:\/\/)?(www\.)?/, '' );

		$( '#blogname' ).on( 'input', function() {
			var title = $.trim( $( this ).val() ) || homeURL;

			// Truncate to 40 characters.
			if ( 40 < title.length ) {
				title = title.substring( 0, 40 ) + '\u2026';
			}

			$siteName.text( title );
		});

		$("input[name='date_format']").click(function(){
			if ( "date_format_custom_radio" != $(this).attr("id") )
				$( 'input[name="date_format_custom"]' ).val( $( this ).val() ).closest( 'fieldset' ).find( '.example' ).text( $( this ).parent( 'label' ).children( '.format-i18n' ).text() );
		});
		$( 'input[name="date_format_custom"]' ).on( 'click input', function() {
			$( '#date_format_custom_radio' ).prop( 'checked', true );
		});

		$("input[name='time_format']").click(function(){
			if ( "time_format_custom_radio" != $(this).attr("id") )
				$( 'input[name="time_format_custom"]' ).val( $( this ).val() ).closest( 'fieldset' ).find( '.example' ).text( $( this ).parent( 'label' ).children( '.format-i18n' ).text() );
		});
		$( 'input[name="time_format_custom"]' ).on( 'click input', function() {
			$( '#time_format_custom_radio' ).prop( 'checked', true );
		});
		$("input[name='date_format_custom'], input[name='time_format_custom']").change( function() {
			var format = $( this ),
				fieldset = format.closest( 'fieldset' ),
				example = fieldset.find( '.example' ),
				spinner = fieldset.find( '.spinner' );

			spinner.addClass( 'is-active' );

			$.post( ajaxurl, {
					action: 'date_format_custom' == format.attr( 'name' ) ? 'date_format' : 'time_format',
					date : format.val()
				}, function( d ) { spinner.removeClass( 'is-active' ); example.text( d ); } );
		});

		var languageSelect = $( '#WPLANG' );
		$( 'form' ).submit( function() {
			// Don't show a spinner for English and installed languages,
			// as there is nothing to download.
			if ( ! languageSelect.find( 'option:selected' ).data( 'installed' ) ) {
				$( '#submit', this ).after( '<span class="spinner language-install-spinner is-active" />' );
			}
		});
		
		// Add Favicon Handler
		$('.sitepad-site-icon-media').on('click', function(){
			sitepad_site_icon_controller($(this));
		});
		
		// Remove Favicon Handler
		$('.sitepad-site-icon-remove').on('click', function(){
			var wrapper = $(this).closest('.sitepad-site-icon-wrapper');
			var preview = wrapper.find('.sitepad-site-icon-preview');
			
			wrapper.find('.sitepad-site-icon-select').show();
			preview.hide();
			wrapper.find('input[name="site_icon"]').val('');
			preview.find('img').attr('src', '');
		});
		
	});

function sitepad_site_icon_controller(jEle){
	/**
	 * Create a media modal select frame, and store it so the instance can be reused when needed.
	*/
	
	params = {
		'width' : 512,
		'height' : 512,
		'flex_height' : 0,
		'flex_width' : 0,
	};
	
	var setImageFromAttachment = function(image){
		image = image || {};
		
		var wrapper = jEle.closest('.sitepad-site-icon-wrapper');
		var preview = wrapper.find('.sitepad-site-icon-preview');
		
		wrapper.find('.sitepad-site-icon-select').hide();
		preview.show();
		wrapper.find('input[name="site_icon"]').val(image.id);
		preview.find('img').attr('src', image.url);
	};
	
	var calculateImageSelectOptions = function( attachment, controller ) {

		var control    = controller.get( 'control' ),
			flexWidth  = !! parseInt( 512, 10 ),
			flexHeight = !! parseInt( 512, 10 ),
			realWidth  = attachment.get( 'width' ),
			realHeight = attachment.get( 'height' ),
			xInit = parseInt( 512, 10 ),
			yInit = parseInt( 512, 10 ),
			ratio = xInit / yInit,
			xImg  = xInit,
			yImg  = yInit,
			x1, y1, imgSelectOptions;

		//controller.set( 'canSkipCrop', ! mustBeCropped( flexWidth, flexHeight, xInit, yInit, realWidth, realHeight ) );

		if ( realWidth / realHeight > ratio ) {
			yInit = realHeight;
			xInit = yInit * ratio;
		} else {
			xInit = realWidth;
			yInit = xInit / ratio;
		}

		x1 = ( realWidth - xInit ) / 2;
		y1 = ( realHeight - yInit ) / 2;

		imgSelectOptions = {
			handles: true,
			keys: true,
			instance: true,
			persistent: true,
			imageWidth: realWidth,
			imageHeight: realHeight,
			minWidth: xImg > xInit ? xInit : xImg,
			minHeight: yImg > yInit ? yInit : yImg,
			x1: x1,
			y1: y1,
			x2: xInit + x1,
			y2: yInit + y1
		};

		if ( flexHeight === false && flexWidth === false ) {
			imgSelectOptions.aspectRatio = xInit + ':' + yInit;
		}

		if ( true === flexHeight ) {
			delete imgSelectOptions.minHeight;
			imgSelectOptions.maxWidth = realWidth;
		}

		if ( true === flexWidth ) {
			delete imgSelectOptions.minWidth;
			imgSelectOptions.maxHeight = realHeight;
		}

		return imgSelectOptions;
	};
	
	var frame = wp.media({
		button: {
			text: 'Select',
			close: false
		},
		states: [
			new wp.media.controller.Library({
				title: "<?php echo  __('Site Icon'); ?>",
				library: wp.media.query({ type: 'image' }),
				multiple: false,
				date: false,
				priority: 20,
				suggestedWidth: 512,
				suggestedHeight: 512
			}),
			new wp.media.controller.SiteIconCropper({
				imgSelectOptions: calculateImageSelectOptions,
				control: this
			})
		]
	});

	frame.on( 'select', function(){
		var attachment = frame.state().get( 'selection' ).first().toJSON();

		if ( params.width === attachment.width && params.height === attachment.height && ! params.flex_width && ! params.flex_height ) {

			wp.ajax.post( 'crop-image', {
				nonce: attachment.nonces.edit,
				id: attachment.id,
				context: 'site-icon',
				cropDetails: {
					x1: 0,
					y1: 0,
					width: params.width,
					height: params.height,
					dst_width: params.width,
					dst_height: params.height
				}
			} ).done( function( croppedImage ) {
				
				setImageFromAttachment( croppedImage );
				frame.close();
			} ).fail( function() {
				frame.trigger('content:error:crop');
			} );
		} else {
			frame.setState( 'cropper' );
		}
	});
	
	frame.on( 'cropped', function( croppedImage ) {
		setImageFromAttachment( croppedImage );
	});
		
	// Open Library
	frame.setState( 'library' ).open();
}
</script>
	<?php
}

/**
 * Display JavaScript on the page.
 *
 * @since 3.5.0
 */
function options_reading_add_js() {
	?>
<script type="text/javascript">
	jQuery(document).ready(function($){
		var section = $('#front-static-pages'),
			staticPage = section.find('input:radio[value="page"]'),
			selects = section.find('select'),
			check_disabled = function(){
				selects.prop( 'disabled', ! staticPage.prop('checked') );
			};
		check_disabled();
		 section.find('input:radio').change(check_disabled);
	});
</script>
	<?php
}

/**
 * Render the site charset setting.
 *
 * @since 3.5.0
 */
function options_reading_blog_charset() {
	echo '<input name="blog_charset" type="text" id="blog_charset" value="' . esc_attr( get_option( 'blog_charset' ) ) . '" class="regular-text" />';
	echo '<p class="description">' . __( 'The <a href="https://sitepad.com/docs/Glossary#Character_set">character encoding</a> of your site (UTF-8 is recommended)' ) . '</p>';
}
