/**
 * Theme Name: BlogCentral
 * Theme URI: http://4bzthemes.com/themes/blogcentral/
 * Author: 4bzthemes
 * Author URI: http://4bzthemes.com
 * File Description: javascript admin file included on the theme options, post edit, and user profile pages.
 *
 * @since BlogCentral 1.0.0
 *
 * @package BlogCentral
 * @subpackage admin.js
 ------------------------------------------------------------------------
	Table of Contents
	
	1. Utility Functions 
	2. Theme Options Page Functions
	3. Media Uploader Functions
	4. Event Handlers
-------------------------------------------------------------------------*/
 
/**
 * 1. Utility Functions
 *-----------------------------------------------------------------------*/

/**
 * Split an id by '-'
 *
 * @since 1.0.0
 * @param string id. Required. Id to be parsed.
 * @return Array. The id parsed into parts.
 */
function blogcentral_parse_id( id ) {
	return id.split( "-" );
}

/**
 * Get the index of an element by parsing its id.
 *
 * @since 1.0.0
 *
 * @param string id. Required. Id to be parsed.
 * @param int offset. Required. Array offset.
 * @return Int. The index.
 */
function blogcentral_get_index( id, offset ) {
	var split = blogcentral_parse_id( id );
	
	return parseInt( split[split.length-offset] );
}

/**
 * Get the prefix of an element's id.
 *
 * Used when there's a group of elements with the same base id, differing only in its prefix.
 *
 * @since 1.0.0
 *
 * @param string id. Id to be parsed.
 * @return string. The id's prefix.
 */
function blogcentral_get_name( id ) {
	var split = blogcentral_parse_id( id );
	
	return split[0];
}

( function( $ ) {
	"use strict";
	
	/**
	 * 2. Theme Options Page Functions
	 *-----------------------------------------------------------------------*/
	
	
	/**
	 * Handle selection to hide and show a container
	 * The target and the container to hide and show must be siblings.
	 *
	 * Works for select and checkboxes.
	 *
	 * @since 1.0.0
	 *
	 * @param object event. Object passed to handler by jquery.
	 */
	function blogcentral_hide_show( event ) {
		var parent = $( event.target ).parent(), 
			display = $( '.hideshow', parent ).css( 'display' );
		
		if ( $( event.target ).attr( 'checked' ) ) {
			display = 'table-row';
		} else {
			display = 'none';
		}
		
		$( '> .hideshow', parent ).css( 'display', display );
	}
	
	/**
	 * Handle click of the x button to close a box
	 *
	 * @since 1.0.0
	 *
	 * @param object event. Object passed to handler by jquery.
	 */
	function blogcentral_close_box( event ) {
		var target = $( event.target ), 
			parent = target.parent();
		
		parent.remove();
	}
	
	/**
	 * Handle font selection.
	 *
	 * @since 1.0.0
	 *
	 * @param object event. Object passed to handler by jquery.
	 */
	function blogcentral_font_options( event ) {
		var target = $( event.target ), 
			val = target.val(), 
			id = target.attr( 'id' ), 
			i = blogcentral_get_name( id ),
			parent = target.parent(), 
			font_class = target.find( ":selected" ).attr( 'class' ), 
			type = '',
			paramsJson = '', 
			url = target.data( 'blogcentral-font-url' );
		
		if ( 'no_font' === val ) {
			$( '#' + i + '-font-variant-cont' ).text( '' );
			$( '#' + i + '-font-subsets-cont' ).text( '' );
			return;
		}
		
		if ( 'system_fonts' === font_class ) {
			type = 'system';
		} else {
			if ( 'google_fonts' === font_class )  {
				type = 'google';
			}
		}
		
		$( 'input[type=hidden]', parent ).val( type );
		
		$( '#' + i + '-font-variant-cont' ).text( '' );
		$( '#' + i + '-font-subsets-cont' ).text( '' );
		
		paramsJson = {
			'font': val, 
			'name': i, 
			'type': font_class
			};
	
		// Make the ajax call to retrieve the font options for the font selected.
		$.ajax( { 
			url: url,
			type: "POST",
			timeout: 5000,
			dataType: "json",
			error: function( xhr ) {
					alert( 'error in ajax '+ xhr.status + ' ' + xhr.statusText );
				   },
			data: paramsJson,
			beforeSend: function() {
							$( '.loader', parent ).show();
						},
			complete: function(){
						$( '.loader', parent ).hide();
					  },
			success: function( data ) {
						/*
						 * data should hold the variants and subsets fragment that should be appended to 
						 * the fonts container.	
						 */
						$( '#' + i + '-font-variant-cont' ).append( data.variants );
						$( '#' + i + '-font-subsets-cont' ).append( data.subsets );
					 }
					
			} ); // End of ajax call.
	}
	
	/**
	 * Show component layout specific options.
	 *
	 * @since 1.0.0
	 * @param object event. Object passed to handler by jquery.
	 */
	function blogcentral_show_sub_options( event ) {
		var target = $( event.target ), 
			val = target.val(), 
			name = target.data( 'blogcentral-name' ), 
			html = '',
			img_file = '';
		
		$( '.' + name + '-layout-sub-layout' ).css( 'display', 'none' );
		$( '.' + name + '-layout-sub-' + val, $( this ).closest( 'td' ) ).css( 'display', 'block' );
		
	}
	
	/**
	 * Handle border selection
	 *
	 * @since 1.0.0
	 * @param object event. Object passed to handler by jquery.
	 */
	function blogcentral_show_border( event ) {
		var target = $( event.target ), 
			parent = target.parent(), 
			val = target.val(), 
			border = $( '.border-ex', parent );
		
		border
			.text( '' )
			.removeClass( 'div1 div2 div3' );
		
		if ( 'default' !== val && '0' !== val ) {
			border
				.text( val )
				.addClass( val );
		}
	}
	
	/**
	 * Handle slide template selection.
	 *
	 * @since 1.0.0
	 * @param object event. Object passed to handler by jquery.
	 */
	function blogcentral_get_template( event ) {
		var target = $( event.target ), 
			val = target.val(), 
			parent = target.parent(), 
			url = blogcentral_object.admin_template_ajax, 
			paramsJson = '';
		
		// Send the selected template.
		paramsJson = { 'template': val };
		
		// Make the ajax call to retrieve the template code for the template selected.
		$.ajax( { 
			url: url,
			type: "POST",
			timeout: 5000,
			dataType: "json",
			error: function( xhr ) {
				alert( 'error in ajax '+ xhr.status + ' ' + xhr.statusText );
			},
			data: paramsJson,
			beforeSend: function() {
				$( '.loader', parent ).show();
			},
			complete: function(){
				$( '.loader', parent ).hide();
			},
			success: function( data ) {
				// Insert the template code into the textarea.
				$( '.slide-html', parent ).val( data.template );
			}			
		} );
	}
	
	/**
	 * Handle click to show the font awesome icons box to choose an icon.
	 *
	 * @since 1.0.0
	 *
	 * @param object event. Object passed to handler by jquery.
	 */
	function blogcentral_display_icons_box( event ) {
		var i, item, 
			html = '<div class="blogcentral-icon-chooser"><div class="closer">' + blogcentral_object.close + ' X</div>',
			target = $( event.target ), 
			parent = target.parent(), 
			fa = blogcentral_object.fa_items;
		
		for ( i = 0; i < fa.length; ++i ) {
			item = fa[i];
			html += '<i value="' + item + '" class="fa ' + item + '"></i>';
		}
		
		html += '</div>';
		
		$( '.blogcentral-icon-chooser', parent ).remove();
		
		parent.append( html );
		
		$( '.blogcentral-icon-chooser .fa' ).on( 'click', blogcentral_add_icon_field );
	}
	
	/**
	 * Handle selection of a font awesome icon. 
	 * Inserts the icon into the corresponding text field.
	 *
	 * @since 1.0.0
	 *
	 * @param object event. Object passed to handler by jquery.
	 */
	function blogcentral_add_icon_field( event ) {
		var target = $( event.target ), 
			parent = target.parent().parent(), 
			val = target.attr( 'value' );
	
		$( '.blogcentral-icon-field', parent ).val( val );
	}
	
	/**
	 * 3. Media Uploader Functions
	 *-----------------------------------------------------------------------*/
	
	// Global variables used in the media uploader functions.
	var custom_uploader, blogcentral_index;
	
	/**
	 * Handle media file(s) selection in the media uploader, specifically images
	 *
	 * @since 1.0.0
	 *
	 * @param object event. Object passed to handler by jquery.
	 */
	function blogcentral_update_file_url( event ) {
		var image = '',
			width = '',
			height = '',
			alt = '',
			imgs_html = '',
			selection = custom_uploader.state().get( 'selection' );
		
		// Map image(s) selections.
		selection.map( function( attachment ) {
			attachment = attachment.toJSON();
			
			var id = attachment.id,
				i;
		
			if ( 'image' === attachment.type ) {
				image = attachment.url;
				width = attachment.width;
				height = attachment.height;
				alt	= attachment.alt;
				return;
			}
		});
		
		$( '#' + blogcentral_index + '-width' ).val( width );
		$( '#' + blogcentral_index + '-height' ).val( height );
		$( '#' + blogcentral_index + '-alt' ).val( alt );
		$( '#' + blogcentral_index ).val( image );
	}
	
	/**
	 * Handle the display of the WP Media Uploader
	 *
	 * Add handler for selection of files in the uploader.
	 *
	 * @since 1.0.0
	 *
	 * @param object event. Object passed to handler by jquery.
	 */
	function blogcentral_display_media_uploader( event ) {
		var id = $( event.target ).data( 'blogcentral-textbox' );
		
		blogcentral_index = id;
		
		event.preventDefault();
		
		// If the uploader object has already been created, reopen the dialog.
		if ( custom_uploader ) {
			custom_uploader.open();
			return;
		}
		
		// Extend the wp.media object.
		custom_uploader = wp.media.frames.file_frame = wp.media({
			title: blogcentral_object.choose_image,
			button: {
				text: blogcentral_object.choose_image
			},
			multiple: true
		});
		
		// Handle the file selection.
		custom_uploader.on( 'select', blogcentral_update_file_url );

		// Open the uploader dialog.
		custom_uploader.open();
	}
	
	/**
	 * 4. Event Handlers
	 *-----------------------------------------------------------------------*/
	$( document ).on( 'ready', function() {	
		// Sortable
		$( '.sortable' ).sortable();
		
		// Tabs	
		$( '.tabs-layout1' ).tabs( { show: { effect: "fadeIn", duration:100 }} );
		$( '.tabs-layout2' ).tabs( { show: { effect: "fadeIn", duration:100 }} );
		
		/**
		 * WP Color Picker
		 *-----------------------------------------------------------------------*/
		
		// For theme options page and shortcode builder.
		$( '.theme-options .blogcentral-color-field' ).wpColorPicker();
		
		/**
		 * General Theme Options
		 *-----------------------------------------------------------------------*/
		$( 'body' ).on( 'click', '.layout-show', blogcentral_show_sub_options );
		$( 'body' ).on( 'change', '.header-border-select', blogcentral_show_border );
		$( 'body' ).on( 'change', '.template-select', blogcentral_get_template );
		$( '.font-select' ).change( blogcentral_font_options );
		$( 'body' ).on( 'click', '.displaymaster', blogcentral_hide_show );
		$( 'body' ).on( 'focus', '.blogcentral-icon-field', blogcentral_display_icons_box );
		$( 'body' ).on( 'click', '.closer', blogcentral_close_box );
		$( 'body' ).on( 'click', '.icon-image-btn', blogcentral_display_media_uploader );
	});
})( jQuery );