ShortcodesUltimateMakerEditor.CustomCss = ( function( $ ) {

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

	/**
	 * Define component elements.
	 */
	self.el = {
		field: $( '#sum-custom-css' ),
		value: $( '#sum-custom-css-value' ),
		container: $( '#sum-custom-css-editor' ),
		editor: null
	};

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

		/**
		 * Initialize the editor.
		 */
		self.el.container.removeClass( 'hidden' );
		self.el.editor = ace.edit( 'sum-custom-css-editor' );
		self.el.editor.$blockScrolling = Infinity;
		self.el.editor.getSession().setValue( self.el.value.val() );
		self.el.editor.getSession().setUseWrapMode( true );
		self.el.editor.getSession().setWrapLimitRange( null, null );
		self.el.editor.getSession().setUseSoftTabs( null );
		self.el.editor.getSession().setUseWorker( false );
		self.el.editor.getSession().setMode( 'ace/mode/css' );
		self.el.editor.setTheme( 'ace/theme/sqlserver' );
		self.el.editor.renderer.setShowPrintMargin( null );

		self.el.value.addClass( 'hidden' );

		self.updateHeight();
		self.bindEvents();

	};

	/**
	 * Setup event listeners.
	 */
	self.bindEvents = function() {

		self.el.editor.getSession().on( 'change', self.updateValue );
		self.el.editor.getSession().on( 'change', self.updateHeight );

	};

	/**
	 * Update hidden textrea value.
	 */
	self.updateValue = function() {
		self.el.value.val( self.el.editor.getSession().getValue() );
	};

	/**
	 * Update editor height.
	 */
	self.updateHeight = function() {

		var newHeight = self.el.editor.getSession().getScreenLength() * self.el.editor.renderer.lineHeight + self.el.editor.renderer.scrollBar.getWidth() + self.el.editor.renderer.lineHeight * 3,
			maxHeight = $( window ).height() - 100;

		if ( newHeight > maxHeight ) {
			newHeight = maxHeight;
		}

		self.el.container.height( newHeight.toString() + 'px' );

		self.el.editor.resize();

	};

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

} )( jQuery );