ShortcodesUltimateMakerEditor.TagName = ( function( $ ) {

	/**
	 * Define main object.
	 */
	var self = {};

	/**
	 * Define component elements.
	 */
	self.el = {
		tagName: $( '#sum-tag-name' ),
		title: $( '#sum-title' )
	};

	/**
	 * Initialize the component.
	 */
	self.init = function() {
		self.bindEvents();
	};

	/**
	 * Setup event listeners.
	 */
	self.bindEvents = function() {
		self.el.tagName.on( 'keyup', self.validateTagName );
		self.el.title.on( 'blur', self.generateTagName );
	};

	/**
	 * Generate shortcode tag name when 'shortcode title' field losts focus.
	 */
	self.generateTagName = function() {

		var title = self.el.title.val(),
			tagName = self.el.tagName.val(),
			newTagName = '';

		if ( tagName !== '' ) {
			return;
		}

		newTagName = title
			.toLowerCase()
			.replace( / /g, '_' )
			.replace( /[^a-z0-9_]/g, '' );

		self.el.tagName.val( newTagName );

	};

	/**
	 * Validate shortcode tag name.
	 */
	self.validateTagName = function( event ) {

		var value = self.el.tagName.val(),
			isValid = /^([a-z0-9_]*)$/.test( value ),
			isEmpty = value === '';

		if ( isValid ) {
			self.el.tagName.parent( 'td' ).removeClass( 'sum-validation-failed' );
		} else {
			self.el.tagName.parent( 'td' ).addClass( 'sum-validation-failed' );
		}

		if ( isEmpty ) {
			self.el.tagName.parent( 'td' ).addClass( 'sum-validation-required' );
		} else {
			self.el.tagName.parent( 'td' ).removeClass( 'sum-validation-required' );
		}

	};

	/**
	 * Provide public API.
	 */
	return {
		init: self.init
	};

} )( jQuery );