/*
 * jQuery resize event - v1.1 - 3/14/2010
 * http://benalman.com/projects/jquery-resize-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
;(function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this);

jQuery.noConflict();

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};
/********************************
*
*   Selects
*
********************************/
function getSelectValue($trg){
    $trg.find('select').each(function(){
		jQuery(this).unbind('change');
		jQuery(this).bind('change',function(){
			var tx = jQuery('option:selected',this).text();
			if ( !jQuery(this).parents('span').eq(0).find('.appended').length ) {
				jQuery(this).parents('span').eq(0).prepend('<span class="appended" />');
			}
			var elm = jQuery(this).siblings('.appended');
			jQuery(elm).text(tx);
		}).triggerHandler('change');
	});
}

/********************************
*
*   Ajax loaders
*
********************************/
function ajaxLoaders($start){
	if ( $start===true ) {
		var spinclone = jQuery('#spinner2').clone();
		jQuery('.ui-dialog-content:visible > *').animate({ opacity : 0.25}, 250).parents('.ui-dialog-content').eq(0).append(spinclone.animate({opacity:1}, 250));
	} else {
		jQuery('.ui-dialog-content #spinner2').animate({opacity:0}, 250, function(){
			jQuery(this).remove();
		});
		jQuery('.ui-dialog-content > *').animate({ opacity : 1}, 250);
	}
}

/********************************
*
*   Load the shortcode manager
*
********************************/
function scManagerLoader(){
	jQuery(document).off('change', '.shortcodelic_shortcode_manager_loader');
	jQuery(document).on('change', '.shortcodelic_shortcode_manager_loader', function(){
		ajaxLoaders(true);
		var t = jQuery(this),
			postVar = jQuery('option:selected', t).data('link') + '&postid=' + pix_post_id,
			id = jQuery('option:selected', t).data('type'),
			url = jQuery('#shortcodelic_'+id+'_wrap').data('url');

		if ( typeof tinyMCE!=='undefined' ) {
			tinyMCE.execCommand('mceRemoveEditor',false,'shortcodelicTMCE');
		}
		jQuery.ajax({
            url: url,
            type: "GET",
            data: postVar,
            cache: false,
            success: function(loadeddata) {
				var html = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).find('#shortcodelic_'+id+'_generator .shortcodelic_opts_part').html(),
					html2 = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).find('#shortcodelic_'+id+'_generator .shortcodelic_opts_list').html(),
					html3 = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).find('#shortcodelic_'+id+'_generator .shortcodelic_opts_list_2').html();
				jQuery('#shortcodelic_'+id+'_generator .shortcodelic_opts_part').html(html);
				jQuery('#shortcodelic_'+id+'_generator .shortcodelic_opts_list').html(html2);
				jQuery('#shortcodelic_'+id+'_generator .shortcodelic_opts_list_2').html(html3);
				uploadSlidesForSlideshow();
				sortSlides();
				cloneSlides();
				editSlides(t.parents('.shortcodelic-dialog').eq(0));
				editCols(t.parents('.shortcodelic-dialog').eq(0));
				deleteSlides();
				getSelectValue(jQuery('#shortcodelic_'+id+'_generator').find('.shortcodelic_opts_part, .shortcodelic_opts_list, .shortcodelic_opts_list_2'));
				scelic_init_sliders();
				scelic_init_farbtastic();
				ajaxLoaders();
				editElements(t.parents('.shortcodelic-dialog').eq(0));
				deleteElements();
				sortElements();
				cloneElements();
				cloneSet();
				deleteSet();
				var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);
				jQuery(window).bind('resize', function(){
					var colWrap = jQuery('.table-column-list:visible'),
						topColWrap = parseFloat(colWrap.parents('.shortcodelic_el_list').eq(0).height()),
						hDiv = parseFloat(colWrap.parents('.shortcodelic_meta').eq(0).height()) - topColWrap;
					jQuery('.table-column-list').css({height:(hDiv*0.75)});
				})/*.triggerHandler('resize')*/;
            }
		});
	});
}

/********************************
*
*   Get thumbnail from the server
*
********************************/
function getThumbnailUrl($id, $field, $altbg){
	var data = {
		action: 'shortcodelic_get_thumb',
		security: shortcodelic_slideshows_nonce,
		content: $id
	};
	jQuery.post(ajaxurl, data)
		.success(function(html){
			$field.css({backgroundImage: $altbg + 'url('+html+')'});
		});
}

/********************************
*
*   Open the shortcode select
*
********************************/
function openShortcodeSelector($id){
	var div = jQuery('#shortcodelic_selection'),
		h = jQuery(window).height(),
		dialog;
	div.dialog({
		height: 150,
		width: 300,
		modal: false,
		dialogClass: 'wp-dialog shortcodelic-dialog',
		position: { my: "center", at: "center", of: window },
		title: div.data('title'),
		zIndex: 10000,
		open: function(){
			jQuery(this).closest('.ui-dialog').find('.ui-button').eq(0).addClass('ui-dialog-titlebar-edit');
			if ( !jQuery('#shortcodelic-modal-overlay').length ) {
				jQuery('body').addClass('overflow_hidden').append('<div id="shortcodelic-modal-overlay" />');
			}
			pluginDialogWindows($id);
			var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);
		},
		close: function(){
			jQuery('body').removeClass('overflow_hidden');
			jQuery('#shortcodelic-modal-overlay').remove();
			jQuery('select option[value=""]',div).prop('selected', true);
			jQuery('select',div).trigger('change');
		}
	});
	jQuery(window).bind('resize',function() {
		h = jQuery(window).height();
		jQuery(div).dialog('option',{'position':{ my: "center", at: "center", of: window }});
	})/*.triggerHandler('resize')*/;
}

/********************************
*
*   Update the post meta
*
********************************/
function updatePostMeta($data, $key, $reload, $id){

	ajaxLoaders(true);

	var data = {
		action: 'shortcodelic_update_meta',
		meta_key: $key,
		type: $id,
		post_id: pix_post_id,
		security: eval('shortcodelic_'+$id+'_nonce'),
		content: $data
	}, url = jQuery('#shortcodelic_'+$id+'_wrap').data('url');
	jQuery.post(ajaxurl, data)
		.success(function(html){
			if ( $reload === true ) {
				jQuery.ajax({
					url: url,
					type: "GET",
					data: jQuery('#shortcodelic_'+$id+'_manager_loader option:selected').data('link') + '&postid=' + pix_post_id,
					cache: false,
					success: function(loadeddata){
						var html = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).find('#shortcodelic_'+$id+'_generator').html();
						jQuery('#shortcodelic_'+$id+'_generator').html(html);
						ajaxLoaders();
					}
				});
			} else {
				ajaxLoaders();
			}


		});

	return false;
}
/********************************
*
*   Plugin dialog windows
*
********************************/
function pluginDialogWindows($id){
    jQuery(document).off('change', '#shortcodelic_selection select');
    jQuery(document).on('change', '#shortcodelic_selection select', function(){
		var t = jQuery(this),
			h = jQuery(window).height(),
			sel = jQuery('option:selected',this),
			cols = sel.data('cols'),
			val = sel.val(),
			div = jQuery('#shortcodelic_'+val+'_generator');
		jQuery('.shortcodelic-dialog .ui-dialog-content').dialog('close');
		div.dialog({
			height: (h*0.8),
			width: '92%',
			modal: false,
			dialogClass: 'wp-dialog shortcodelic-dialog shortcodelic-'+cols+'-cols-dialog',
			position: { my: "center", at: "center", of: window },
			title: div.data('title'),
			zIndex: 100,
			open: function(){
				jQuery(window).trigger('shortcodelic_dialog_open');
				div.find('.shortcodelic_shortcode_manager_loader').trigger('change');
				var tdial = jQuery(this);
				tdial.scrollTop(0);
				tdial.closest('.ui-dialog').find('.ui-button').eq(0).addClass('ui-dialog-titlebar-edit');
				if ( !tdial.closest('.ui-dialog').find('.ui-dialog-titlebar').eq(0).find('.shortcodelic-dialog-back').length ) {
					tdial.closest('.ui-dialog').find('.ui-dialog-titlebar').eq(0).append('<button class="shortcodelic-dialog-back re-open" />');
				}
				if ( !jQuery('#shortcodelic-modal-overlay').length ) {
					jQuery('body').addClass('overflow_hidden').append('<div id="shortcodelic-modal-overlay" />');
				}
				jQuery(document).off('click','.shortcodelic-dialog-back.re-open');
				jQuery(document).on('click','.shortcodelic-dialog-back.re-open', function(){
					tdial.dialog( "close" );
					openShortcodeSelector($id);
				});
				uploadSlidesForSlideshow();
				getSelectValue(tdial);
				scelic_init_sliders();
				scelic_init_farbtastic();
				var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);
			},
			buttons: {
				'0': function() {
					var ser = jQuery(this).find('input[name], textarea[name], select[name]').serialize();
					updatePostMeta(ser, 'shortcodelic_'+val, false, val);
				},
				'1': function() {
					var ser = jQuery(this).find('input[name], textarea[name], select[name]').serialize();
					updatePostMeta(ser, 'shortcodelic_'+val, true, val);
					var valInput = jQuery('input#shortcodelic_get_sc', div).val(),
						tinyCont = tinyMCE.get($id).getContent();
					valInput = valInput.replace(/postid=[\'|"](.*?)[\'|"]/,'');
					valInput = valInput.replace(/  /g,' ');
					if ( ser!=='' ) {
						tinyMCE.execCommand('mceFocus',true,$id);
						//if ( tinyMCE.get($id).selection.getContent()!=='' ) {
							tinyMCE.get($id).selection.setContent( valInput );
						/*} else {
							tinyMCE.get($id).setContent( tinyCont + valInput );
						}*/
					}
					jQuery(this).dialog( "close" );
				}
			},
			close: function(){
				jQuery('.el-list .element-tab', div).not('.clone').remove();
				var html = div.html();
				jQuery('body').removeClass('overflow_hidden');
				jQuery('#shortcodelic-modal-overlay').remove();
				/*jQuery('select option[value=""]',div).prop('selected', true);
				jQuery('select',div).trigger('change');*/
			}
		});
		jQuery(window).bind('resize',function() {
			h = jQuery(window).height();
			jQuery(div).dialog('option',{'height':(h*0.8),'position':{ my: "center", at: "center", of: window }});
		})/*.triggerHandler('resize')*/;
	});
}

/********************************
*
*   Sort the slides
*
********************************/
function sortSlides(){
	jQuery('.slides-list').sortable({
		items: '.slide-el:not(".clone")',
		placeholder: 'slide-el slide-el-highlighted',
		tolerance: 'pointer',
		start: function( event, ui ) {
			/*jQuery('.slides-list .slide-el').not('.clone').each(function(){
				var ind = jQuery(this).index();
				jQuery(this).find('.no-slide').text(ind);
			});*/
		},
		stop: function( event, ui ) {
			jQuery('.slide-el', this).not('.clone').each(function(){
				var ind = jQuery(this).index('.slide-el:not(".clone")');
				jQuery(this).find('[name]').each(function(){
					var name = jQuery(this).attr('name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+(ind+1)+'][$4]');
					jQuery(this).attr('name',name);
				});
				jQuery(this).find('.no-slide').text(ind+1);
			});
		}
	});
}

/********************************
*
*   Clone slideshows
*
********************************/
function cloneSet(){
	jQuery(document).off('click','.clone-set');
	jQuery(document).on('click','.clone-set', function(e){

		ajaxLoaders(true);

		var t = jQuery(this),
			$data = t.parents('.ui-dialog-content').eq(0).find('input[name], textarea[name], select[name]').serialize(),
			$data_from = t.parents('.ui-dialog-content').eq(0).find('input[data-name="clone_from"]'),
			$meta_size = t.parents('.ui-dialog-content').eq(0).find('input[data-name="meta_size"]').val(),
			type = t.data('type'),
			datalink = t.data('link'),
			actual = t.data(type),
			old = t.data('old'+type),
			url = jQuery('#shortcodelic_'+type+'_wrap').data('url'),
			data;

		if ( $data_from.length && $data_from.val() !== '' ) {
			data = {
				action: 'shortcodelic_update_meta',
				meta_key: 'shortcodelic_'+type,
				meta_size: $meta_size,
				type: type,
				from: $data_from.val(),
				post_id: pix_post_id,
				security: eval('shortcodelic_'+type+'_nonce'),
				content: $data
			};
		} else if ( $data_from.length && $data_from.val() === '' ) {
			return false;
		} else {
			old = new RegExp(old, 'g');
			$data = $data.replace(old, actual);
			data = {
				action: 'shortcodelic_update_meta',
				meta_key: 'shortcodelic_'+type,
				type: type,
				post_id: pix_post_id,
				security: eval('shortcodelic_'+type+'_nonce'),
				content: $data
			};
		}

		switch(type) {
			case 'slideshows':
				data.slideshow = t.attr('data-slideshows');
			break;
			case 'tabs':
				data.tabs = t.attr('data-tabs');
			break;
			case 'tables':
				data.tables = t.attr('data-tables');
			break;
			case 'maps':
				data.maps = t.attr('data-maps');
			break;
			case 'carousels':
				data.carousels = t.attr('data-carousels');
			break;
			case 'postcarousels':
				data.postcarousels = t.attr('data-postcarousels');
			break;
			case 'woocarousels':
				data.woocarousels = t.attr('data-woocarousels');
			break;
		}
		jQuery.post(ajaxurl, data)
			.success(function(html){
				jQuery.ajax({
					url: url,
					type: "GET",
					data: datalink + '&postid=' + pix_post_id,
					cache: false,
					success: function(loadeddata) {
						var selhtml = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).find('#shortcodelic_'+type+'_manager_loader').html(),
							html = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).find('#shortcodelic_'+type+'_generator .shortcodelic_opts_part').html(),
							html2 = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).find('#shortcodelic_'+type+'_generator .shortcodelic_opts_list').html(),
							html3 = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).find('#shortcodelic_'+type+'_generator .shortcodelic_opts_list_2').html();
						jQuery('#shortcodelic_'+type+'_manager_loader').html(selhtml);
						jQuery('#shortcodelic_'+type+'_generator .shortcodelic_opts_part').html(html);
						jQuery('#shortcodelic_'+type+'_generator .shortcodelic_opts_list').html(html2);
						jQuery('#shortcodelic_'+type+'_generator .shortcodelic_opts_list_2').html(html3);
						uploadSlidesForSlideshow();
						sortSlides();
						cloneSlides();
						editSlides(t.parents('.shortcodelic-dialog').eq(0));
						deleteSlides();
						getSelectValue(jQuery('#shortcodelic_'+type+'_generator').find('.shortcodelic_opts_part, .shortcodelic_opts_list, .shortcodelic_opts_list_2'));
						jQuery('#shortcodelic_'+type+'_manager_loader').find('option[data-link="'+datalink+'"]').prop('selected', true).end().trigger('change');
						scelic_init_sliders();
						scelic_init_farbtastic();
						ajaxLoaders();
					}
				});
			});

		return false;
	});
}

/********************************
*
*   Delete slideshows
*
********************************/
function deleteSet(){
	jQuery(document).off('click','.delete-set');
	jQuery(document).on('click','.delete-set',function(e){

		ajaxLoaders(true);

		e.preventDefault();

		var t = jQuery(this),
			par = t.parents('.ui-dialog-content').eq(0).find('.shortcodelic_el_list').eq(0),
			type = t.data('type'),
			url = jQuery('#shortcodelic_'+type+'_wrap').data('url');


		jQuery('.slide-el', par).not('.clone').fadeOut(250,function(){ jQuery(this).remove(); });

		var data = {
			action: 'shortcodelic_update_meta',
			meta_key: 'shortcodelic_'+type,
			type: type,
			post_id: pix_post_id,
			security: eval('shortcodelic_'+type+'_nonce'),
			content: ''
		};
		switch(type) {
			case 'slideshows':
				data.slideshow = t.attr('data-slideshows');
			break;
			case 'tabs':
				data.tabs = t.attr('data-tabs');
			break;
			case 'tables':
				data.tables = t.attr('data-tables');
			break;
			case 'maps':
				data.maps = t.attr('data-maps');
			break;
			case 'carousels':
				data.carousels = t.attr('data-carousels');
			break;
			case 'postcarousels':
				data.postcarousels = t.attr('data-postcarousels');
			break;
			case 'woocarousels':
				data.woocarousels = t.attr('data-woocarousels');
			break;
		}
		jQuery.post(ajaxurl, data)
			.success(function(html){
				t.parents('.ui-dialog-content').eq(0).fadeOut(250,function(){ jQuery(this).dialog('close'); });
				jQuery.ajax({
					url: url,
					type: "GET",
					data: jQuery('#shortcodelic_'+type+'_generator option:selected').data('link') + '&postid=' + pix_post_id,
					cache: false,
					success: function(loadeddata){
						var html = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).find('#shortcodelic_'+type+'_generator').html();
						jQuery('#shortcodelic_'+type+'_generator').html(html);
						ajaxLoaders();
					}
				});
			});
	});
}

/********************************
*
*   Delete slides
*
********************************/
function deleteSlides(){
	jQuery('.slides-list .slide-el-ui.delete-slide').off('click');
	jQuery('.slides-list .slide-el-ui.delete-slide').on('click', function(){
		var el = jQuery(this).parents('.slide-el').eq(0),
			slides = el.parents('.slides-list').eq(0);
		el.remove();
		jQuery('.slide-el', slides).not('.clone').each(function(){
			var ind = jQuery(this).index('.slide-el:not(".clone")');
			jQuery(this).find('[name]').each(function(){
				var name = jQuery(this).attr('name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+(ind+1)+'][$4]');
				jQuery(this).attr('name',name);
			});
			jQuery(this).find('.no-slide').text(ind+1);
		});

		return false;
	});
}

/********************************
*
*   Replace img slide
*
********************************/
function replaceSlide(){

	var pix_media_frame,
		formlabel = 0;

	jQuery('.shortcodelic_meta').not('.shortcodelicadd_meta').off('click','.pix_upload .img_preview, .pix_upload .pix_button');
	jQuery('.shortcodelic_meta').not('.shortcodelicadd_meta').on('click','.pix_upload .img_preview, .pix_upload .pix_button', function( e ){
		e.preventDefault();
		var button = jQuery(this),
			wrap = button.parents('.pix_upload').eq(0);

		if ( pix_media_frame ) {
			pix_media_frame.open();
			return;
		}

		pix_media_frame = wp.media.frames.pix_media_frame = wp.media({

			className: 'media-frame pix-media-frame',
			frame: 'post',
			multiple: false,
			library: {
				type: 'image'
			}
		});

		pix_media_frame.on('insert', function(){
			var media_attachments = pix_media_frame.state().get('selection').toJSON(),
				thumbSize = jQuery('.attachment-display-settings select.size option:selected').val(),
				thumbUrl;

/******************************** Fill the input ********************************/
			jQuery.each(media_attachments, function(index, el) {
				var url = this.url,
					id = this.id,
					size = typeof thumbSize!=='undefined' ? thumbSize : '',
					field = wrap.find('.img_preview').addClass('filled');
				if ( typeof thumbSize!=='undefined' ) {
					url = this.sizes[thumbSize]['url'];
				}
				wrap.find('input[name="slide_bg"], input[name="el_bg"]').val(url);
				getThumbnailUrl(id, field, '');
				wrap
					.find('input[name="slide_id"], input[name="el_id"]').val(id).end()
					.find('input[name="slide_size"], input[name="el_size"]').val(size);

			});
/******************************** Fill the input ********************************/
		});

		pix_media_frame.open();
	});

}

/********************************
*
*   Edit elements
*
********************************/
function editElements($comeFrom){
	jQuery('.el-list .edit-el').not('.column-el').off('click');
	jQuery('.el-list .edit-el').not('.column-el').on('click', function(){
		var panel = jQuery(this).data('panel'),
			editor = jQuery('#wp-shortcodelicTMCE-wrap'),
			div = jQuery('#'+panel),
			el = jQuery(this).parents('.element-sort').eq(0),
			h = jQuery(window).height(),
			textA,
			htmlThis,
			inputArr = {},
			dialog;
		if ( typeof tinyMCE!=='undefined' ) {
			tinyMCE.execCommand('mceRemoveEditor',false,'shortcodelicTMCE');
		}
		div.find('.shortcodelic_tinymce_area').append(editor);
		jQuery('input[type="hidden"], input[type="text"], textarea[readonly]',el).each(function(){
			var name = jQuery(this).attr('name');
			if ( name.match( /\[caption\]+$/ ) ) {
				textA = jQuery(this);
				htmlThis = textA.val();
			} else {
				var match = jQuery(this).attr('name').match(/(\[(.*?)\])+$/);
				match = match[2];
				inputArr[match] = jQuery(this).val();
			}
		});
		jQuery(div).dialog({
			height: (h*0.8),
			width: '92%',
			modal: false,
			dialogClass: 'wp-dialog shortcodelic-dialog shortcodelic-three-cols-dialog',
			position: { my: "center", at: "center", of: window },
			title: div.data('title'),
			zIndex: 10000,
			open: function(){
				jQuery(window).trigger('shortcodelic_dialog_open');
				pixWpPointer();
				$comeFrom.hide();
				replaceSlide();
				jQuery(this).closest('.ui-dialog').find('.ui-button').eq(0).addClass('shortcodelic-dialog-back');
				if ( typeof tinyMCE!=='undefined' ) {
					htmlThis = htmlThis.replace(/\"\{(.*?)\}\"/g,"'{$1}'");
					tinyMCE.execCommand('mceAddEditor',false,'shortcodelicTMCE');
					tinyMCE.execCommand('mceFocus',false,'shortcodelicTMCE');
					tinyMCE.get('shortcodelicTMCE').setContent(htmlThis);
					jQuery('#wp-shortcodelicTMCE-wrap').removeClass('html-active').addClass('tmce-active');
				} else {
					htmlThis = htmlThis.replace(/\\r\\n/g,'');
					jQuery('textarea#shortcodelicTMCE', div).val(htmlThis);
				}
				jQuery('input[type="checkbox"], textarea[readonly]', div).prop('checked', false);
				jQuery.each(inputArr, function(i, val) {
					jQuery('input[type="text"][name="el_'+i+'"]', div).val(val).triggerHandler('keyup');
					jQuery('input[type="hidden"][name="el_'+i+'"]', div).val(val);
					if ( val.indexOf('{') == -1 ) {
						jQuery('input[type="checkbox"][name="el_'+i+'"][value="'+val+'"]', div).prop('checked', true);
						jQuery('select[name="el_'+i+'"] option[value="'+val+'"]', div).prop('selected', true).trigger('change');
						jQuery('input[type="radio"]', div).prop('checked', false);
						jQuery('input[type="radio"][name="el_'+i+'"][value="'+val+'"]', div).prop('checked', true);
					}
					if ( i == 'id' ) {
                        getThumbnailUrl(val, jQuery('.img_preview.slide_bg', div).addClass('filled'), '');
                    }
				});

				jQuery('.shortcodelic_icon_button', div).off('click');
				jQuery('.shortcodelic_icon_button', div).on('click', function(e){
					e.preventDefault();
					openFontSelector('',jQuery('[name="el_icon"]', div));
				});

				jQuery('.shortcodelic_icon_button_2', div).off('click');
				jQuery('.shortcodelic_icon_button_2', div).on('click', function(e){
					e.preventDefault();
					openFontSelector('',jQuery('[name="el_icon_2"]', div));
				});

				/*jQuery(window).bind('resize',function() {
					if ( typeof tinyMCE === 'undefined' ) {
						var txtH = parseFloat(jQuery('#wp-shortcodelicTMCE-editor-container').height()),
							qtH = parseFloat(jQuery('#qt_shortcodelicTMCE_toolbar').outerHeight()),
							toolH = parseFloat(jQuery('#wp-shortcodelicTMCE-editor-tools').outerHeight());
						jQuery('#shortcodelicTMCE').height(txtH-(qtH+toolH+40));
					}
				});*/
				if ( !jQuery('#shortcodelic-modal-overlay').length ) {
					jQuery('body').addClass('overflow_hidden').append('<div id="shortcodelic-modal-overlay" />');
				}
				var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);

			},
			buttons: {
				'': function() {
					var cont;
					if ( typeof tinyMCE!=='undefined' ) {
						if ( jQuery('#wp-shortcodelicTMCE-wrap').hasClass('html-active') && tinyMCE.activeEditor.getParam('wpautop', true) ) {
							cont = switchEditors.wpautop(jQuery('textarea#shortcodelicTMCE').val());
						} else {
							cont = tinyMCE.get('shortcodelicTMCE').getContent();
						}
					} else {
						cont = jQuery('textarea#shortcodelicTMCE').val();
					}
					cont = cont.replace(/(\r\n|\n|\r)/gm,"");
					if ( typeof textA != 'undefined' ) {
						textA.val(cont);
					}
					jQuery('input[type="hidden"], input[type="text"]',el).each(function(){
						var name = jQuery(this).attr('name');
						if ( !name.match( /\[caption\]+$/ ) ) {
							var match = jQuery(this).attr('name').match(/(\[(.*?)\])+$/);
							match = match[2];
							if ( jQuery('[name="el_'+match+'"]').is('input:radio') ) {
								jQuery(this).val(jQuery('input[name="el_'+match+'"]:checked', div).val());
							} else if ( jQuery('[name="el_'+match+'"]').is('input:checkbox') ) {
								jQuery(this).val(jQuery('input[name="el_'+match+'"]:checked', div).val());
							} else if ( jQuery('[name="el_'+match+'"]').is('select') ) {
								jQuery(this).val(jQuery('select[name="el_'+match+'"] option:selected', div).val());
							} else {
								jQuery(this).val(jQuery('input[name="el_'+match+'"]', div).val());
							}
						}
					});
					jQuery( this ).dialog( "close" );
				}
			},
			close: function(){
				$comeFrom.show();
				if ( typeof tinyMCE!=='undefined' ) {
					tinyMCE.execCommand('mceRemoveEditor',false,'shortcodelicTMCE');
				}
				jQuery('#shortcodelic_tinymce').append(editor);
			}
		});
		jQuery(window).bind('resize',function() {
			h = jQuery(window).height();
			jQuery(div).dialog('option',{'height':(h*0.8),'position':{ my: "center", at: "center", of: window }});
		})/*.triggerHandler('resize')*/;
	});
}

/********************************
*
*   Clone slides
*
********************************/
function cloneSlides(){
	jQuery('.slides-list .slide-el-ui.clone-slide').off('click');
	jQuery('.slides-list .slide-el-ui.clone-slide').on('click', function(){
		var wrap = jQuery(this).parents('.slides-list').eq(0),
			el = jQuery(this).parents('.slide-el').eq(0),
			clone = el.clone();
		el.after(clone);
		jQuery('.slide-el', wrap).not('.clone').each(function(){
			var ind = jQuery(this).index();
			jQuery(this).find('[name]').each(function(){
				var name = jQuery(this).attr('name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+(ind)+'][$4]');
				jQuery(this).attr('name',name);
			});
			jQuery(this).find('.no-slide').text(ind);
		});
		cloneSlides();
		sortSlides();
		editSlides(wrap.parents('.shortcodelic-dialog').eq(0));
		deleteSlides();
	});
}

/********************************
*
*   Edit slides
*
********************************/
function editSlides($comeFrom){
	jQuery('.slides-list .slide-el-ui.edit-slide').off('click');
	jQuery('.slides-list .slide-el-ui.edit-slide').on('click', function(e){
		e.preventDefault();
		var dest = jQuery(this).data('dest'),
			editor = jQuery('#wp-shortcodelicTMCE-wrap'),
			cols = jQuery(this).data('cols'),
			div = jQuery(dest),
			el = jQuery(this).parents('.slide-el').eq(0),
			h = jQuery(window).height(),
			textA,
			htmlThis,
			inputArr = {},
			wrap = jQuery(this).parents('.shortcodelic-dialog').eq(0),
			wVal = jQuery('[name$="[width]"]', wrap).val(),
			hVal =  jQuery('[name$="[height]"]', wrap).val();
		if ( typeof tinyMCE!=='undefined' ) {
			tinyMCE.execCommand('mceRemoveEditor',false,'shortcodelicTMCE');
		}
		div.find('.shortcodelic_tinymce_area').append(editor);
		jQuery('input[type="hidden"]',el).each(function(){
			var name = jQuery(this).attr('name');
			if ( name.match( /\[caption\]+$/ ) ) {
				textA = jQuery(this);
				htmlThis = textA.val();
			} else {
				var match = jQuery(this).attr('name').match(/(\[(.*?)\])+$/);
				match = match[2];
				inputArr[match] = jQuery(this).val().replace(/\\;quot\;\{/g, '[{').replace(/\}\\;quot\;/g, '}]');
			}
		});
		jQuery(div).dialog({
			height: (h*0.8),
			width: '92%',
			modal: false,
			dialogClass: 'wp-dialog shortcodelic-dialog shortcodelic-'+cols+'-cols-dialog',
			position: { my: "center", at: "center", of: window },
			title: div.data('title'),
			zIndex: 10000,
			open: function(){
				jQuery(window).trigger('shortcodelic_dialog_open');
				htmlThis = typeof htmlThis=='undefined' ? '' : htmlThis;
				htmlThis = htmlThis.replace(/\"\{(.*?)\}\"/g,"'{$1}'");
				if ( typeof tinyMCE!=='undefined' ) {
					tinyMCE.execCommand('mceAddEditor',false,'shortcodelicTMCE');
					tinyMCE.execCommand('mceFocus',false,'shortcodelicTMCE');
					tinyMCE.get('shortcodelicTMCE').setContent(htmlThis);
					jQuery('#wp-shortcodelicTMCE-wrap').removeClass('html-active').addClass('tmce-active');
				} else {
					jQuery('textarea#shortcodelicTMCE', div).val(htmlThis);
				}
				/*jQuery(window).bind('resize',function() {
					if ( typeof tinyMCE === 'undefined' ) {
						var txtH = parseFloat(jQuery('#wp-shortcodelicTMCE-editor-container').height()),
							qtH = parseFloat(jQuery('#qt_shortcodelicTMCE_toolbar').outerHeight()),
							toolH = parseFloat(jQuery('#wp-shortcodelicTMCE-editor-tools').outerHeight());
						jQuery('#shortcodelicTMCE').height(txtH-(qtH+toolH+40));
					}
				});*/

				replaceSlide();
				pixWpPointer();
				var slideElArr = {},
					slideElOb = {};
				$comeFrom.hide();
				jQuery(this).closest('.ui-dialog').find('.ui-button').eq(0).addClass('shortcodelic-dialog-back');
				jQuery('input[type="checkbox"]', div).prop('checked', false);
				jQuery.each(inputArr, function(i, val) {
					if ( i=='elements') {
						elems = jQuery.parseJSON( val );
						if ( elems === null ) {
							elems = {};
						}

						jQuery('.el-list .element-slide', div).not('.clone').remove();

						jQuery.each(elems, function(i, val) {
							var key;
							jQuery.each(val, function(i2, val2) {
								if ( i2 == 'name' ) {
									key = val2;
								} else {
									slideElArr[key] = val2;
								}
							});
						});
						var key = 0;
						jQuery.each(slideElArr, function(i, val) {
							if ( i.match( /\[caption\]+$/ ) ) {
								key = key + 1;
								slideElOb[key] = {}
							}
							slideElOb[key][i] = val.replace(/\;quot\;/g, '"');
						});

						var wrap = jQuery('.el-list', div),
							el = jQuery('.element-slide.clone', wrap);

						jQuery.each(slideElOb, function(i, val) {
							var clone = el.clone();
							wrap.append(clone.removeClass('clone'));
							clone.find('[data-name]').each(function(){
								var name = jQuery(this).attr('data-name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+i+'][$4]');
								jQuery(this).attr('name',name).removeAttr('data-name');
							});
							clone.find('.no-el').text(i);

							jQuery.each(val, function(i2, val2) {
								if ( typeof val2 == 'object' ) {
									val2 = JSON.stringify(val2);
									val2 = val2.replace(/[\[\]']+/g,'');
								}
								clone.find('[name="' + i2 + '"]').val(val2);
							});

							cloneElements();
							deleteElements();
							sortElements();
						});
					} else {
						jQuery('input[type="text"][name="slide_'+i+'"]', div).val(val);
						jQuery('input[type="hidden"][name="slide_'+i+'"]', div).val(val);
						jQuery('input[type="checkbox"][name="slide_'+i+'"][value="'+val+'"]', div).prop('checked', true);
						jQuery('select[name="slide_'+i+'"]').not('[multiple]').find('option[value="'+val+'"]', div).prop('selected', true);
						jQuery('select[name="slide_'+i+'"][multiple]', div).val(val.split(','));
						jQuery('input[type="radio"][name="slide_'+i+'"][value="'+val+'"]', div).prop('checked', true);
						if ( i == 'id' ) {
                            getThumbnailUrl(val, jQuery('.img_preview.slide_bg', div).addClass('filled'), '');
                        }
					}
				});
				editElements(jQuery(this).parents('.shortcodelic-dialog').eq(0));
				previewSlide(jQuery(this).parents('.shortcodelic-dialog').eq(0), wVal, hVal);

				getSelectValue(jQuery('body .shortcodelic_meta'));
				scelic_init_sliders();
				scelic_init_farbtastic();

				if ( !jQuery('#shortcodelic-modal-overlay').length ) {
					jQuery('body').addClass('overflow_hidden').append('<div id="shortcodelic-modal-overlay" />');
				}
				var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);

			},
			buttons: {
				'': function() {
					var cont;
					if ( typeof tinyMCE!=='undefined' ) {
						if ( jQuery('#wp-shortcodelicTMCE-wrap').hasClass('html-active') && tinyMCE.activeEditor.getParam('wpautop', true) ) {
							cont = switchEditors.wpautop(jQuery('textarea#shortcodelicTMCE').val());
						} else {
							cont = tinyMCE.activeEditor.getContent();
						}
					} else {
						cont = jQuery('textarea#shortcodelicTMCE').val();
					}
					cont = cont.replace(/(\r\n|\n|\r)/gm,"");
					if ( typeof textA != 'undefined' ) {
						textA.val(cont);
					}
					jQuery('input[type="hidden"]',el).each(function(){
						var name = jQuery(this).attr('name');
						if ( !name.match( /\[caption\]+$/ ) ) {
							if ( !name.match( /\[elements\]+$/ ) ) {
								var match = jQuery(this).attr('name').match(/(\[(.*?)\])+$/);
								match = match[2];
								if ( jQuery('[name="slide_'+match+'"]', div).is('input:radio') ) {
									jQuery(this).val(jQuery('input[name="slide_'+match+'"]:checked', div).val());
								} else if ( jQuery('[name="slide_'+match+'"]').is('input:checkbox') ) {
									jQuery(this).val(jQuery('input[name="slide_'+match+'"]:checked', div).val());
								} else if ( jQuery('[name="slide_'+match+'"]').is('select') ) {
									if (jQuery('[name="slide_'+match+'"][multiple]').length) {
										jQuery(this).val(jQuery('[name="slide_'+match+'"]', div).val());
									} else {
										jQuery(this).val(jQuery('select[name="slide_'+match+'"]').not('[multiple]').find('option:selected', div).val());
									}
								} else {
									jQuery(this).val(jQuery('input[name="slide_'+match+'"]', div).val());
								}
							} else {
								var elemArr = jQuery('[name*="slide_elements"]', div).serializeArray();
								elemArr = JSON.stringify(elemArr);
								elemArr = elemArr.replace(/\\\"/g, ';quot;');
								jQuery(this).val(elemArr);
							}
						}
					});
					var altbg = '';
					if ( jQuery('input[name="slide_video"]', div).val()!=='' && typeof jQuery('input[name="slide_video"]', div).val()!=='undefined' ) {
						altbg = 'url('+shortcodelic_video_icon+'), ';
					}
					getThumbnailUrl(jQuery('input[name="slide_id"]', div).val(), el, altbg);

					jQuery( this ).dialog( "close" );
				}
			},
			close: function(){
				jQuery('.el-list .element-slide', div).not('.clone').remove();
				$comeFrom.show();
			}
		});
		jQuery(window).bind('resize',function() {
			h = jQuery(window).height();
			jQuery(div).dialog('option',{'height':(h*0.8),'position':{ my: "center", at: "center", of: window }});
		})/*.triggerHandler('resize')*/;
	});
}

/********************************
*
*   Edit table columns
*
********************************/
function editCols($comeFrom){
	jQuery('.column-el').off('click');
	jQuery('.column-el').on('click', function(e){
		e.preventDefault();
		var div = jQuery('#shortcodelic_editcolumn_panel'),
			el = jQuery(this).parents('.element-table').eq(0),
			h = jQuery(window).height(),
			htmlThis,
			inputArr = {},
			wrap = jQuery(this).parents('.shortcodelic-dialog').eq(0);
		jQuery('input[type="hidden"], input[type="text"], textarea[readonly]',el).each(function(){
			var name = jQuery(this).attr('name');
			var match = jQuery(this).attr('name').match(/(\[(.*?)\])+$/);
			match = match[2];
			inputArr[match] = jQuery(this).val();
		});
		jQuery(div).dialog({
			height: (h*0.8),
			width: '500',
			modal: false,
			dialogClass: 'wp-dialog shortcodelic-dialog shortcodelic-one-col-dialog',
			position: { my: "center", at: "center", of: window },
			title: div.data('title'),
			zIndex: 10000,
			open: function(){
				jQuery(window).trigger('shortcodelic_dialog_open');
				pixWpPointer();
				var slideElArr = {},
					slideElOb = {};
				$comeFrom.hide();
				jQuery(this).closest('.ui-dialog').find('.ui-button').eq(0).addClass('shortcodelic-dialog-back');
				jQuery.each(inputArr, function(i, val) {
					if ( i=='elements') {
						elems = jQuery.parseJSON( val );
						if ( elems === null ) {
							elems = {};
						}

						jQuery('.el-list .element-slide', div).not('.clone').remove();

						jQuery.each(elems, function(i, val) {
							var key;
							jQuery.each(val, function(i2, val2) {
								if ( i2 == 'name' ) {
									key = val2;
								} else {
									slideElArr[key] = val2;
								}
							});
						});
						var key = 0;
						jQuery.each(slideElArr, function(i, val) {
							if ( i.match( /\[caption\]+$/ ) ) {
								key = key + 1;
								slideElOb[key] = {};
							}
							slideElOb[key][i] = val.replace(/\;quot\;/g, '"');
						});

						var wrap = jQuery('.el-list', div),
							el = jQuery('.element-slide.clone', wrap);

						jQuery.each(slideElOb, function(i, val) {
							var clone = el.clone();
							wrap.append(clone.removeClass('clone'));
							clone.find('[data-name]').each(function(){
								var name = jQuery(this).attr('data-name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+i+'][$4]');
								jQuery(this).attr('name',name).removeAttr('data-name');
							});
							clone.find('.no-el').text(i);

							jQuery.each(val, function(i2, val2) {
								if ( typeof val2 == 'object' ) {
									val2 = JSON.stringify(val2);
									val2 = val2.replace(/[\[\]']+/g,'');
								}
								clone.find('[name="' + i2 + '"]').val(val2);
							});

							cloneElements();
							deleteElements();
							sortElements();
						});
					} else {
						jQuery('input[type="text"][name="slide_'+i+'"]', div).val(val);
						jQuery('input[type="hidden"][name="slide_'+i+'"]', div).val(val);
						jQuery('input[type="checkbox"][name="slide_'+i+'"][value="'+val+'"]', div).prop('checked', true);
						jQuery('select[name="slide_'+i+'"]').not('[multiple]').find('option[value="'+val+'"]', div).prop('selected', true);
						jQuery('select[name="slide_'+i+'"][multiple]', div).val(val.split(','));
						jQuery('input[type="radio"][name="slide_'+i+'"][value="'+val+'"]', div).prop('checked', true);
						if ( i == 'id' ) {
                            getThumbnailUrl(val, jQuery('.img_preview.slide_bg', div).addClass('filled'), '');
                        }
					}
				});
				editElements(jQuery(this).parents('.shortcodelic-dialog').eq(0));
				getSelectValue(jQuery('body .shortcodelic_meta'));
				scelic_init_sliders();
				scelic_init_farbtastic();

				if ( !jQuery('#shortcodelic-modal-overlay').length ) {
					jQuery('body').addClass('overflow_hidden').append('<div id="shortcodelic-modal-overlay" />');
				}
				var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);

			},
			buttons: {
				'': function() {
					var cont, slideElArr = {};
					jQuery('input[type="hidden"]',el).each(function(){
						var name = jQuery(this).attr('name');
						if ( !name.match( /\[active\]+$/ ) ) {
							if ( !name.match( /\[elements\]+$/ ) ) {
								var match = jQuery(this).attr('name').match(/(\[(.*?)\])+$/);
								match = match[2];
								if ( jQuery('[name="slide_'+match+'"]', div).is('input:radio') ) {
									jQuery(this).val(jQuery('input[name="slide_'+match+'"]:checked', div).val());
								} else if ( jQuery('[name="slide_'+match+'"]').is('input:checkbox') ) {
									jQuery(this).val(jQuery('input[name="slide_'+match+'"]:checked', div).val());
								} else if ( jQuery('[name="slide_'+match+'"]').is('select') ) {
									if (jQuery('[name="slide_'+match+'"][multiple]').length) {
										jQuery(this).val(jQuery('[name="slide_'+match+'"]', div).val());
									} else {
										jQuery(this).val(jQuery('select[name="slide_'+match+'"]').not('[multiple]').find('option:selected', div).val());
									}
								} else {
									jQuery(this).val(jQuery('input[name="slide_'+match+'"]', div).val());
								}

							} else {
								var elemArr = jQuery('[name*="slide_elements"]', div).serializeArray();
								elemArr = JSON.stringify(elemArr);
								elemArr = elemArr.replace(/\\\"/g, ';quot;');
								jQuery(this).val(elemArr);

								elems = jQuery.parseJSON( elemArr );
								if ( elems === null ) {
									elems = {};
								}

								jQuery('.table-el-block', el).remove();

								jQuery.each(elems, function(i, val) {
									var key;
									jQuery.each(val, function(i2, val2) {
										if ( i2 == 'name' ) {
											key = val2;
										} else {
											slideElArr[key] = val2;
										}
									});
								});
								var key = 0;
								jQuery.each(slideElArr, function(i, val) {
									if ( i.match( /\[caption\]+$/ ) ) {
										key = key + 1;
										el.append('<span class="table-el-block">'+val+'</span>');
									}
								});
							}
						}
					});
					jQuery( this ).dialog( "close" );
				}
			},
			close: function(){
				jQuery('.el-list .element-slide', div).not('.clone').remove();
				$comeFrom.show();
				editCols($comeFrom);
			}
		});
		jQuery(window).bind('resize',function() {
			h = jQuery(window).height();
			jQuery(div).dialog('option',{'height':(h*0.8),'position':{ my: "center", at: "center", of: window }});
		})/*.triggerHandler('resize')*/;
	});
}

/********************************
*
*   Delete elements
*
********************************/
function deleteElements(){
	jQuery('.el-list .delete-el').off('click');
	jQuery('.el-list .delete-el').on('click', function(e){
		e.preventDefault();
		var wrap = jQuery(this).parents('.el-list').eq(0),
			el = jQuery(this).parents('.element-sort').eq(0),
			list = el.parents('.shortcodelic_el_list').eq(0),
			ticked = false;
		if ( jQuery('.tick-el:visible', el).length ) {
			ticked = true;
		}
		if ( jQuery(this).hasClass('delete-col') ) {
			el.animate({opacity:0},150).animate({width:0},150,function(){
				jQuery(this).remove();
				if (ticked===true) {
					wrap.find('.element-sort').not('.clone').eq(0).find('.tick-el').show();
					wrap.find('.element-sort').not('.clone').eq(0).find('.untick-el').hide();
					list.find('input[name*="active"]').val('1');
				}
				jQuery('.element-sort', wrap).not('.clone').each(function(){
					var ind = jQuery(this).index();
					jQuery(this).find('[name]').each(function(){
						var name = jQuery(this).attr('name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+(ind)+'][$4]');
						jQuery(this).attr('name',name);
					});
					jQuery(this).find('.no-el').text(ind);
				});
			});
		} else {
			el.fadeOut({duration: 250, queue: false}).slideUp(250,function(){
				jQuery(this).remove();
				if (ticked===true) {
					wrap.find('.element-sort').not('.clone').eq(0).find('.tick-el').show();
					wrap.find('.element-sort').not('.clone').eq(0).find('.untick-el').hide();
					list.find('input[name*="active"]').val('1');
				}
				jQuery('.element-sort', wrap).not('.clone').each(function(){
					var ind = jQuery(this).index();
					jQuery(this).find('[name]').each(function(){
						var name = jQuery(this).attr('name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+(ind)+'][$4]');
						jQuery(this).attr('name',name);
					});
					jQuery(this).find('.no-el').text(ind);
				});
			});
		}
	});
}

/********************************
*
*   Clone Elements
*
********************************/
function cloneElements(){
	jQuery('.el-list .clone-el').off('click');
	jQuery('.el-list .clone-el').on('click', function(e){
		e.preventDefault();
		var wrap = jQuery(this).parents('.el-list').eq(0),
			el = jQuery(this).parents('.element-sort').eq(0),
			clone;
		jQuery('textarea', el).each(function(){
			jQuery(this).text( jQuery(this).val() );
		});
		clone = el.clone();
		el.after(clone.hide().fadeIn(250));
		if ( jQuery('.tick-el:visible', clone).length ) {
			jQuery('.tick-el', clone).hide();
			jQuery('.untick-el', clone).show();
		}
		jQuery('.element-sort', wrap).not('.clone').each(function(){
			var ind = jQuery(this).index();
			jQuery(this).find('[name]').each(function(){
				var name = jQuery(this).attr('name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+(ind)+'][$4]');
				jQuery(this).attr('name',name);
			});
			jQuery(this).find('.no-el').text(ind);
		});
		cloneElements();
		sortElements();
		deleteElements();
		editElements(wrap.parents('.shortcodelic-dialog').eq(0));
		editCols(wrap.parents('.shortcodelic-dialog').eq(0));
	});
}

/********************************
*
*   Sort elements
*
********************************/
function sortElements(){
	jQuery('.el-list').sortable({
		items: '.element-sort:not(".clone")',
		placeholder: 'element-sort element-highlighted',
		tolerance: 'pointer',
		start: function( event, ui ) {
			/*jQuery('.slides-list .slide-el').not('.clone').each(function(){
				var ind = jQuery(this).index();
				jQuery(this).find('.no-slide').text(ind);
			});*/
		},
		stop: function( event, ui ) {
			var t = jQuery(this),
				list = t.parents('.shortcodelic_el_list').eq(0);
			jQuery('.element-sort', list).not('.clone').each(function(){
				var not = jQuery('.element-sort', list).not('.clone'),
					ind = not.index(jQuery(this));
				jQuery(this).find('[name]').each(function(){
					var name = jQuery(this).attr('name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+(ind+1)+'][$4]');
					jQuery(this).attr('name',name);
				});
				jQuery(this).find('.no-el').text(ind+1);
				if ( jQuery('.tick-el:visible', this).length ) {
					list.find('input[name*="active"]').val(ind+1);
				}
			});
		}
	});
}

/********************************
*
*   Hide/show - activate/deactivate elements
*
********************************/
function hideShowElems(){
	jQuery(document).off('click','.show-el, .hide-el');
	jQuery(document).on('click','.show-el, .hide-el', function( e ){
		e.preventDefault();
		var button = jQuery(this),
			wrap = button.parents('.element-slide').eq(0);

		if ( button.hasClass('show-el') ) {
			button.hide().siblings('span.hide-el').show();
			wrap.removeClass('hidden_view');
		} else {
			button.hide().siblings('span.show-el').show();
			wrap.addClass('hidden_view');
		}
	});

	jQuery(document).off('click','.untick-el, .tick-el');
	jQuery(document).on('click','.untick-el, .tick-el', function( e ){
		e.preventDefault();
		var button = jQuery(this),
			el = button.parents('.element-sort').eq(0),
			list = button.parents('.shortcodelic_el_list').eq(0),
			ind = el.index();

		if ( button.hasClass('untick-el') ) {
			list
				.find('span.tick-el').hide().end()
				.find('span.untick-el').show().end()
				.find('input[name*="active"]').val(ind);
			button.hide().siblings('span.tick-el').show();
		} else {
			list.find('input[name*="active"]').val('false');
			button.hide().siblings('span.untick-el').show();
		}
	});

	jQuery(document).off('click','.deactive-el, .active-el');
	jQuery(document).on('click','.deactive-el, .active-el', function( e ){
		e.preventDefault();
		var button = jQuery(this),
			el = button.parents('.element-sort').eq(0),
			list = button.parents('.shortcodelic_el_list').eq(0),
			ind = el.index();

		if ( button.hasClass('deactive-el') ) {
			el.find('input[name*="active"]').val('true');
			button.hide().siblings('span.active-el').show();
		} else {
			el.find('input[name*="active"]').val('');
			button.hide().siblings('span.deactive-el').show();
		}
	});
}


/********************************
*
*   HEX to RGB
*
********************************/
function hexToRgb(hex) {
	var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
	return result ? {
		r: parseInt(result[1], 16),
		g: parseInt(result[2], 16),
		b: parseInt(result[3], 16)
	} : null;
}

/********************************
*
*   Slide preview
*
********************************/
function previewSlide($comeFrom, $wVal, $hVal){
	jQuery(document).off('click','.slide-preview');
	jQuery(document).on('click','.slide-preview', function( e ){
		e.preventDefault();
		var div = jQuery('#shortcodelic_slide_preview'),
			clone = div.find('iframe').clone(),
			h = jQuery(window).height(),
			dialog,
			bg = jQuery(this).parents('.shortcodelic-dialog').eq(0).find('[name=slide_bg]').val(),
			pos = jQuery(this).parents('.shortcodelic-dialog').eq(0).find('[name=slide_bg_pos]:checked').val(),
			spinclone = jQuery('#spinner2').clone();
		div.append(spinclone).append(clone.attr('name','shortcodelic_preview_iframe')).dialog({
            iframe: true,
			dialogClass: 'wp-dialog shortcodelic-dialog',
			position: { my: "center", at: "center", of: window },
			title: div.data('title'),
			width: $wVal,
			zIndex: 10000,
			open: function(){
				jQuery(window).trigger('shortcodelic_dialog_open');
				jQuery(this).closest('.ui-dialog').find('.ui-button').eq(0).addClass('shortcodelic-dialog-back');
				jQuery('#shortcodelic_send_url').submit();
				var t = jQuery(this).find('[name="shortcodelic_preview_iframe"]').load(function(){
					var iframe = t.contents();

					iframe.find('body').css({
						backgroundImage: 'url('+bg+')',
						backgroundRepeat: 'no-repeat',
						backgroundSize: 'cover',
						backgroundPosition: pos+'',
						height: $hVal+'',
						overflow: 'hidden'
					});
					jQuery(this).show();
					spinclone.remove();

					$comeFrom.find('.element-slide').not('.clone').not('.hidden_view').each(function(){
						var clone = jQuery('<div />'),
							t = jQuery(this).addClass('element-slide-preview'),
							html = jQuery('textarea', t).val(),
							position = jQuery.parseJSON( t.find('input[name$="[position]"]').val() );
							if ( position === null ) {
								position = {};
							}
							ind = t.index('.element-slide-preview');
						iframe
							.find('html')
								.css({ overflow : 'hidden' })
							.find('body')
								.append(clone.addClass('slideshine_caption')
									.html(html)
									.css({zIndex:ind,position:'absolute',left:0,top:0})
								);

						jQuery('iframe',iframe).each(function(){
							var replace = jQuery('<div />');
							jQuery(this).after(replace);
							replace.width(jQuery(this).width()).height(jQuery(this).height()).css({background:'#000000'});
							jQuery(this).remove();
						});

						var cloneW = clone.width();
						clone.css({width:cloneW}).css(position);

						jQuery('*', clone).filter(function (index) {
							return jQuery(this).css("display") === "block";
						}).each(function(){
							jQuery(this).wrapInner('<span class="pixlightfx" />');
						}).filter(function (index) {
							return !jQuery('.notpixlight',this).length;

						}).find('.pixlightfx').wrapInner('<span class="pixlight" />');

						var bgClone = jQuery('input[name$="[bg]"]', t).val(),
							rgbaClone = hexToRgb(bgClone),
							opacityClone = jQuery('input[name$="[opacity]"]', t).val();
						opacityClone = opacityClone === '' ? '0' : opacityClone;

						if ( Modernizr.rgba && rgbaClone !== 'null' ) {
							jQuery('.pixlight', clone).css({
								backgroundColor: 'rgba('+rgbaClone.r+','+rgbaClone.g+','+rgbaClone.b+','+opacityClone+')'
							});
						} else {
							jQuery('.pixlight', clone).css({
								backgroundColor: bgClone
							});
						}

						clone.addClass('sc_draggable').attr('data-index',ind);

					});

					jQuery('body').trigger('sc_slideshine_preview_started');
				});

				$comeFrom.hide();
				div.css({
					height: $hVal,
					overflow: 'hidden',
					position: 'relative'
				});

				var set = setTimeout(function(){ jQuery(window).triggerHandler('open_preview'); },10);
			},
			buttons: {
				'': function() {
					$comeFrom.find('[data-position]').not('.hidden_view').each(function(){
						var dataPos = jQuery(this).attr('data-position');
						jQuery(this).find('input[name$="[position]"]').val(dataPos);
					});
					jQuery( this ).dialog( "close" );
				}
			},
			close: function(){
				$comeFrom.show().find('[data-position]').removeAttr('data-position');
				jQuery(this).find('[name="shortcodelic_preview_iframe"]').remove();
				jQuery('body').unbind('sc_slideshine_preview_started');
			}
		});
		jQuery(window).bind('resize open_preview',function() {
			var winW = jQuery(window).width()*0.9,
				winH = jQuery(window).height()*0.9,
				slideR = $wVal/$hVal;
			if ( $wVal > winW && (winW*slideR) <= winH ) {
				jQuery(div).dialog('option',{'width':winW, 'height':winW*slideR});
			} else if ( $hVal > winH  && (winH/slideR) <= winW ) {
				jQuery(div).dialog('option',{'height':winH, 'width':winH*slideR});
			}
			jQuery(div).dialog('option',{'position':{ my: "center", at: "center", of: window }});
		});
	});
}

/********************************
*
*   Add columns and rows
*
********************************/
function addRowCols(){
	jQuery(document).off('click','.add-column, .add-row');
	jQuery(document).on('click','.add-column, .add-row', function( e ){
		e.preventDefault();
		var button = jQuery(this),
			wrap = button.siblings('div.el-list'),
			clone = wrap.find('.clone').clone().removeClass('clone'),
			ind;

		if (button.hasClass('add-column')) {
			wrap.append(clone.hide().fadeIn(250));
			ind = clone.index();
			clone.find('.no-el').text(ind);
			clone.find('[data-name]').each(function(){
					name = jQuery(this).attr('data-name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+ind+'][$4]');
					jQuery(this).removeAttr('data-name').attr('name',name);
				});

			editElements(wrap.parents('.shortcodelic-dialog').eq(0));
		} /*else {
			alert('row');
		}*/
	});
}
/********************************
*
*   Add elements
*
********************************/
function addElems(){
	jQuery(document).off('click','.add-element');
	jQuery(document).on('click','.add-element', function( e ){
		e.preventDefault();
		var button = jQuery(this),
			wrap = button.siblings('div.el-list'),
			clone = wrap.find('.clone').clone().removeClass('clone'),
			ind;

		wrap.append(clone.hide().fadeIn(250));
		ind = clone.index();
		clone.find('.no-el').text(ind);
		clone.find('[data-name]').each(function(){
				name = jQuery(this).attr('data-name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+ind+'][$4]');
				jQuery(this).removeAttr('data-name').attr('name',name);
			});

		editElements(wrap.parents('.shortcodelic-dialog').eq(0));
		sortElements();
		cloneElements();
		deleteElements();
		editCols(button.parents('.shortcodelic-dialog').eq(0));
	});
}

/********************************
*
*   Upload media
*
********************************/
function uploadSlidesForSlideshow(){
	var pix_media_frame,
		formlabel = 0;

	jQuery(document).off('click','.add-slide');
	jQuery(document).on('click','.add-slide', function( e ){
		e.preventDefault();
		var button = jQuery(this),
			wrap = button.siblings('div.slides-list');

		if ( pix_media_frame ) {
			pix_media_frame.open();
			return;
		}

		pix_media_frame = wp.media.frames.pix_media_frame = wp.media({

			className: 'media-frame pix-media-frame',
			frame: 'post',
			multiple: true,
			library: {
				type: 'image'
			}
		});

		pix_media_frame.on('insert', function(){
			var media_attachments = pix_media_frame.state().get('selection').toJSON(),
				thumbSize = jQuery('.attachment-display-settings select.size option:selected').val(),
				thumbUrl,
				length = jQuery('.slide-el', wrap).length;

/******************************** Create the slide inputs ********************************/
			jQuery.each(media_attachments, function(index, el) {
				var clone = wrap.find('.clone').clone().removeClass('clone'),
					url = this.url,
					id = this.id,
					size = typeof thumbSize!=='undefined' ? thumbSize : '';
				if ( typeof thumbSize!=='undefined' ) {
					url = this.sizes[thumbSize]['url'];
				}
				clone
					.find('input[name$="[bg]"]').each(function(){
						jQuery(this).val(url);
					});
				getThumbnailUrl(id, clone, '');

				clone.find('input[data-name]').each(function(){
						name = jQuery(this).attr('data-name').replace(/(.+?)\[(.+?)\]\[(.+?)\]\[(.+?)\]/g, '$1[$2]['+(length+index)+'][$4]');
						jQuery(this).removeAttr('data-name').attr('name',name);
					}).end()
					.find('input[name$="[bg]"]').val(url).end()
					.find('input[name$="[id]"]').val(id).end()
					.find('input[name$="[size]"]').val(size);
				wrap.append(clone);
				ind = clone.index();
				clone.find('.no-slide').text(ind);
			});
			sortSlides();
			cloneSlides();
			editSlides(button.parents('.shortcodelic-dialog').eq(0));
			deleteSlides();
/******************************** Create the slide inputs ********************************/
		});

		pix_media_frame.open();
		jQuery('.media-menu a').eq(1).hide();
		jQuery('.media-toolbar-secondary').hide();
	});

}

/********************************
*
*   WP pointer tooltips
*
********************************/
function pixWpPointer(){
	jQuery(document).off('click','.shortcodelic-wp-pointer');
	jQuery(document).on('click','.shortcodelic-wp-pointer', function(){
		var trig = jQuery(this),
			zIndex = jQuery('.wp-pointer').css('z-index');

		options = {
			content : trig.attr('data-content'),
			position : {
				edge : 'left',
				align : 'center'
			},
			show : function( event, t ) {
				t.pointer.css({ zIndex : 200000 });
				t.pointer.show();
				t.opened();
			},
			hide : function( event, t ) {
				t.pointer.css({ zIndex : zIndex });
				t.pointer.hide();
				t.closed();
			}
		};
		if ( ! options )
			return;
		options = jQuery.extend( options, {
			close: function() {
			//to do
			}
		});
		jQuery(this).pointer( options ).pointer( 'open' );
	});
}

/********************************
*
*   Sliders
*
********************************/
function scelic_init_sliders() {
	if(jQuery.isFunction(jQuery.fn.slider)) {
		jQuery('.slider_div').each(function(){
			var t = jQuery(this),
				value = jQuery('input',t).val(),
				mi, m, s;
			if( t.hasClass('milliseconds') ){
				mi = 0;
				m = 25000;
				s = 100;
			} else if( t.hasClass('opacity') ){
				mi = 0;
				m = 1;
				s = 0.01;
			} else if( t.hasClass('percent') || t.hasClass('percentage') ){
				mi = 0;
				m = 100;
				s = 1;
			} else if( t.hasClass('grid') ){
				mi = 1;
				m = 50;
				s = 1;
			} else if( t.hasClass('stroke') ){
				mi = 1;
				m = 20;
				s = 1;
			} else if( t.hasClass('zoom') ){
				mi = 1;
				m = 18;
				s = 1;
			} else if( t.hasClass('columns') ){
				mi = 1;
				m = 8;
				s = 1;
			} else if( t.hasClass('heading') ){
				mi = 0;
				m = 360;
				s = 1;
			} else if( t.hasClass('pitch') ){
				mi = -90;
				m = 90;
				s = 1;
			} else {
				mi = 0;
				m = 2000;
				s = 1;
			}
			jQuery('.slider_cursor',t).slider({
				range: 'min',
				value: value,
				min: mi,
				max: m,
				step: s,
				slide: function( event, ui ) {
					jQuery('input',t).val( ui.value );
				}
			});
			jQuery('a',t).mousedown(function(event){
				t.addClass('active');
			});
			jQuery(document).mouseup(function(){
				t.removeClass('active');
			});
			jQuery('input',t).bind('keyup blur',function(){
				var v = jQuery('input',t).val();
				jQuery('.slider_cursor',t).slider({ value: v });
			});
			jQuery('.slider_cursor',t).each(function(){
				if ( jQuery('.ui-slider-range-min',this).length > 1 ) {
					jQuery('.ui-slider-range-min',this).not(':last').remove();
				}
			});
		});
	}
}

/********************************
*
*   Color pickers
*
********************************/
function scelic_init_farbtastic(){
	if(jQuery.isFunction(jQuery.fn.farbtastic)) {
		/*jQuery('.colorpicker').each(function(){
			jQuery(this).after('<div class="picker_close" />');
		})*/
		jQuery('.shortcodelic-dialog .pix_color_picker .pix_button').click(function(){
			var t = jQuery(this);
			t.siblings('.colorpicker, i').fadeIn(150);

			t.siblings('i').click(function() {
				t.siblings('.colorpicker, i').fadeOut(150);
			});
	
			return false;
		});

		jQuery('.shortcodelic-dialog .pix_color_picker').each(function() {
			var divPicker = jQuery(this).find('.colorpicker');
			var inputPicker = jQuery(this).find('input[type=text]');
			divPicker.farbtastic(inputPicker);
			jQuery.farbtastic(divPicker).setColor(jQuery(this).find('input[type=text]').val());
		});
	}
}

/******************************************************
*
*	Insert icons as shortcodes
*
******************************************************/
function insertSCicons($tdial,$id,$textarea){
	jQuery('#shortcodelic_fonticons_generator .the-icons').off('click');
	jQuery('#shortcodelic_fonticons_generator .the-icons').on('click', function(){
		var valIcon = jQuery('i',this).attr('class'),
			size = jQuery('#shortcodelic_fonticons_generator [data-name="size"]').val(),
			color = jQuery('#shortcodelic_fonticons_generator [data-name="color"]').val(),
			bg = jQuery('#shortcodelic_fonticons_generator [data-name="bg"]').val(),
			style = jQuery('#shortcodelic_fonticons_generator [data-name="style"] option:selected').val(),
			datastyle = style !== '' ? ' data-style="'+style+'"' : '',
			json = jQuery('#shortcodelic_fonticons_generator [data-name="json"]').is(':checked') ? true : false,
			opts = {};

		if( size!=='' ) opts.size = size;
		if( color!=='' ) opts.color = color;
		if( bg!=='' ) opts.bg = bg;
		if( style!=='' ) opts.style = style;

		if ( style=='circle' ) {
			style = 'border-color:'+bg;
        } else if ( style=='disc' ) {
			style = 'background-color:'+bg;
        } else {
			style = '';
        }

		if ( json === true ) {
			$icon = '<i class="' + valIcon + '" data-icopts=\''+JSON.stringify(opts)+'\'>do not remove this text</i>';
		} else {
			size = size === '' ? '' : 'font-size:'+size+'px;';
			$icon = '<i class="' + valIcon + '" style="'+size+'color:'+color+'; '+style+'"'+datastyle+'>#</i>';
		}

		if ( valIcon!=='' ) {
			if ( $textarea!=='' && typeof $textarea != 'undefined' ) {
				$textarea.val($icon+$textarea.val());
			} else {
				tinyMCE.execCommand('mceAddEditor',false,$id);
				tinyMCE.execCommand('mceFocus',false,$id);
				tinyMCE.get($id).selection.setContent( $icon );
			}
		}
		$tdial.dialog( "close" );
	});
}

/******************************************************
*
*	Find icon on the list
*
******************************************************/
function hideByTyping(){
	jQuery('.shortcodelic_font_list_wrap input').off('keyup');
	jQuery('.shortcodelic_font_list_wrap input').on('keyup',function(){
		var val = jQuery(this).val(),
			par = jQuery(this).parents('.shortcodelic_font_list_wrap').eq(0);
		if ( val !== '' ) {
			jQuery('.the-icons',par).not('[data-search*="'+val+'"]').hide();
			jQuery('.the-icons[data-search*="'+val+'"]', par).show();
		} else {
			jQuery('.the-icons', par).show();
		}
	});
}

/******************************************************
*
*	Select font set
*
******************************************************/
function selectFontSet($tdial,$id,$textarea){
	jQuery('#shortcodelic_fonticons_generator .select_font_set').change(function(){
		var val = jQuery('option:selected',this).val();
		ajaxLoaders(true);
		jQuery.ajax({
            url: shortcodelic_url + '/font/scicon-' + val + '.php',
            cache: false,
            success: function(loadeddata) {
				jQuery('#shortcodelic_fonticons_generator .shortcodelic_font_list_wrap input').val('');
				var html = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).html();
				jQuery('#shortcodelic_fonticons_generator .shortcodelic_font_list').html(html);
				hideByTyping();
				insertSCicons($tdial,$id,$textarea);
				ajaxLoaders();
            }
		});
	});
}

/********************************
*
*   Open the font selector
*
********************************/
function openFontSelector($id,$textarea){
	var div = jQuery('#shortcodelic_fonticons_generator'),
		h = jQuery(window).height(),
		dialog,
		overlay = false;
	if ( jQuery('#shortcodelic-modal-overlay').length ) {
		overlay = true;
	}
	div.dialog({
		height: (h*0.8),
		width: '92%',
		modal: false,
		dialogClass: 'wp-dialog shortcodelic-dialog shortcodelic-three-cols-dialog',
		position: { my: "center", at: "center", of: window },
		title: div.data('title'),
		zIndex: 10000,
		open: function(){
			jQuery(window).trigger('shortcodelic_dialog_open');
			if ( overlay === false ) {
				jQuery('body').addClass('overflow_hidden').append('<div id="shortcodelic-modal-overlay" />');
			}
			var tdial = jQuery(this);
			tdial.scrollTop(0);
			tdial.closest('.ui-dialog').find('.ui-button').eq(0).addClass('ui-dialog-titlebar-edit');
			selectFontSet(tdial,$id,$textarea);
			hideByTyping();
			getSelectValue(tdial);
			scelic_init_sliders();
			scelic_init_farbtastic();
			insertSCicons(tdial,$id,$textarea);
			var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);
		},
		close: function(){
			if ( overlay === false ) {
				jQuery('body').removeClass('overflow_hidden');
				jQuery('#shortcodelic-modal-overlay').remove();
			}
		}
	});
	jQuery(window).bind('resize',function() {
		h = jQuery(window).height();
		jQuery(div).dialog('option',{'height':(h*0.8),'position':{ my: "center", at: "center", of: window }});
	})/*.triggerHandler('resize')*/;
}

/********************************
*
*   Open the tooltip generator
*
********************************/
function openTooltipGen($id){
	var div = jQuery('#shortcodelic_tooltips_generator'),
		h = jQuery(window).height(),
		editor = jQuery('#wp-tooltipTMCE-wrap'),
		dialog,
		overlay = false;
	if ( typeof tinyMCE!=='undefined' ) {
		tinyMCE.execCommand('mceRemoveEditor',false,'tooltipTMCE');
	}
	div.find('.shortcodelic_tinymce_area').append(editor);
	if ( jQuery('#shortcodelic-modal-overlay').length ) {
		overlay = true;
	}
	div.dialog({
		height: (h*0.8),
		width: '92%',
		modal: false,
		dialogClass: 'wp-dialog shortcodelic-dialog shortcodelic-three-cols-dialog',
		position: { my: "center", at: "center", of: window },
		title: div.data('title'),
		zIndex: 10000,
		open: function(){
			jQuery(window).trigger('shortcodelic_dialog_open');
			var node = tinyMCE.get($id).selection.getNode(),
				opts = {},
				htmlThis = '';
			if ( jQuery(node).attr('data-tooltip')!=='' && typeof jQuery(node).attr('data-tooltip')!='undefined' ) {
				htmlThis = jQuery(node).attr('data-tooltip');
				opts = jQuery.extend({}, jQuery(node).data('ttopts'), opts);
				jQuery('[data-name="position"] option[value="'+opts.position+'"]', div).prop('selected',true);
				jQuery('[data-name="animation"] option[value="'+opts.animation+'"]', div).prop('selected',true);
				jQuery('[data-name="maxwidth"]', div).val(opts.maxwidth);
				if ( opts.interactive != 'false' ) {
					jQuery('[data-name="interactive"]', div).prop('checked', true);
				} else {
					jQuery('[data-name="interactive"]', div).prop('checked', false);
				}
			}
			htmlThis = htmlThis.replace(/\"\{(.*?)\}\"/g,"'{$1}'");
			if ( typeof tinyMCE!=='undefined' ) {
				tinyMCE.execCommand('mceAddEditor',false,'tooltipTMCE');
				tinyMCE.execCommand('mceFocus',false,'tooltipTMCE');
				jQuery('#wp-tooltipTMCE-wrap').removeClass('html-active').addClass('tmce-active');
				tinyMCE.get('tooltipTMCE').setContent(htmlThis);
			}
			jQuery('textarea#tooltipTMCE', div).val(htmlThis);

			if ( overlay === false ) {
				jQuery('body').addClass('overflow_hidden').append('<div id="shortcodelic-modal-overlay" />');
			}
			var tdial = jQuery(this);
			tdial.scrollTop(0);
			tdial.closest('.ui-dialog').find('.ui-button').eq(0).addClass('ui-dialog-titlebar-edit');
			getSelectValue(tdial);
			scelic_init_sliders();
			var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);
		},
		buttons: {
			'': function() {
				var cont;
				if ( typeof tinyMCE!=='undefined' ) {
					if ( jQuery('#wp-tooltipTMCE-wrap').hasClass('html-active') && tinyMCE.activeEditor.getParam('wpautop', true) ) {
						cont = switchEditors.wpautop(jQuery('textarea#tooltipTMCE').val());
					} else {
						if ( $id == 'shortcodelicTMCE' )
							cont = jQuery('textarea#tooltipTMCE').val();
						else
							cont = tinyMCE.activeEditor.getContent();
					}
				} else {
					cont = jQuery('textarea#tooltipTMCE').val();
				}
				tinyMCE.execCommand('mceFocus',true,$id);
				var node = tinyMCE.get($id).selection.getNode(),
					opts = {};
				opts.position = jQuery('[data-name="position"] option:selected', div).val();
				opts.animation = jQuery('[data-name="animation"] option:selected', div).val();
				opts.maxwidth = jQuery('[data-name="maxwidth"]', div).val();
				if ( jQuery('[data-name="interactive"]',div).is(':checked') ) {
					opts.interactive = 'true';
				} else {
					opts.interactive = 'false';
				}
				if ( node.tagName == 'A' || node.tagName == 'SPAN' ) {
					jQuery(node).attr('data-tooltip', cont).attr('data-ttopts', JSON.stringify(opts));
				} else {
					var selection = tinyMCE.get($id).selection.getContent();
					tinyMCE.get($id).selection.setContent( "<span data-tooltip='"+cont+"' data-ttopts='"+JSON.stringify(opts)+"'>"+selection+"</span>" );
				}
				jQuery(this).dialog( "close" );
			}
		},
		close: function(){
			if ( typeof tinyMCE!=='undefined' ) {
				tinyMCE.execCommand('mceRemoveEditor',false,'tooltipTMCE');
			}
			if ( overlay === false ) {
				jQuery('body').removeClass('overflow_hidden');
				jQuery('#shortcodelic-modal-overlay').remove();
			}
		}
	});
	jQuery(window).bind('resize',function() {
		h = jQuery(window).height();
		jQuery(div).dialog('option',{'height':(h*0.8),'position':{ my: "center", at: "center", of: window }});
	})/*.triggerHandler('resize')*/;
}

/********************************
*
*   Remova the tooltips
*
********************************/
function removeTooltip($id){
	var node = tinyMCE.get($id).selection.getNode(),
		opts = {};
	if ( (node.tagName == 'A' || node.tagName == 'SPAN') && typeof jQuery(node).data('tooltip')!='undefined' ) {
		jQuery(node).removeAttr('data-tooltip').removeAttr('data-ttopts');
		if (node.attributes.length === 0) {
			var html = jQuery(node).html();
			jQuery(node).after(html).remove();
		}
	}
}

/********************************
*
*   Open the progress bars generator
*
********************************/
function openProgressGen($id){
	var div = jQuery('#shortcodelic_progress_generator'),
		h = jQuery(window).height(),
		dialog,
		overlay = false,
		htmlThis = '';
	if ( jQuery('#shortcodelic-modal-overlay').length ) {
		overlay = true;
	}
	div.dialog({
		height: (h*0.8),
		width: '92%',
		modal: false,
		dialogClass: 'wp-dialog shortcodelic-dialog shortcodelic-two-cols-dialog',
		position: { my: "center", at: "center", of: window },
		title: div.data('title'),
		zIndex: 10000,
		open: function(){
			jQuery(window).trigger('shortcodelic_dialog_open');
			if ( overlay === false ) {
				jQuery('body').addClass('overflow_hidden').append('<div id="shortcodelic-modal-overlay" />');
			}
			var selection = tinyMCE.get($id).selection.getContent(),
				tdial = jQuery(this);
			jQuery('[data-name="label"]',div).val(selection);
			tdial.scrollTop(0);
			tdial.closest('.ui-dialog').find('.ui-button').eq(0).addClass('ui-dialog-titlebar-edit');
			getSelectValue(tdial);
			scelic_init_sliders();
			scelic_init_farbtastic();
			var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);
		},
		buttons: {
			'': function() {
				var opts = {},
					label = jQuery('[data-name="label"]', div).val();
				opts.label2 = jQuery('[data-name="label2"]', div).val();
				opts.unit = jQuery('[data-name="unit"]', div).val();
				opts.value = jQuery('[data-name="value"]', div).val();
				opts.maximum = jQuery('[data-name="maximum"]', div).val();
				opts.barcolor = jQuery('[data-name="barcolor"]', div).val();
				opts.trackcolor = jQuery('[data-name="trackcolor"]', div).val();
				opts.style = jQuery('[data-name="style"] option:selected', div).val();
				opts.linecap = jQuery('[data-name="linecap"] option:selected', div).val();
				opts.linewidth = jQuery('[data-name="linewidth"]', div).val();
				opts.size = jQuery('[data-name="size"]', div).val();
				opts.zoom = jQuery('[data-name="zoom"]', div).val();
				opts.class = jQuery('[data-name="class"]', div).val();
				opts.id = jQuery('[data-name="id"]', div).val();
				opts.animate = jQuery('[data-name="animate"]', div).val();
				var shortcode = '[shortcodelic-progress';
				jQuery.each(opts, function(key, val) {
					if ( val !== '' ) {
						shortcode = shortcode + ' ' + key + '="' + val + '"';
					}
				});
				var selection = tinyMCE.get($id).selection.getContent();
				tinyMCE.get($id).selection.setContent( shortcode + "]" + label + "[/shortcodelic-progress]" );
				jQuery(this).dialog( "close" );
			}
		},
		close: function(){
			if ( overlay === false ) {
				jQuery('body').removeClass('overflow_hidden');
				jQuery('#shortcodelic-modal-overlay').remove();
			}
		}
	});
	jQuery(window).bind('resize',function() {
		h = jQuery(window).height();
		jQuery(div).dialog('option',{'height':(h*0.8),'position':{ my: "center", at: "center", of: window }});
	})/*.triggerHandler('resize')*/;
}

/********************************
*
*   Remove the buttons
*
********************************/
function removeButtons($id){
	var node = tinyMCE.get($id).selection.getNode();
	if ( (node.tagName == 'A' || node.tagName == 'SPAN') && jQuery(node).hasClass('buttonelic') ) {
		jQuery(node).removeClass('buttonelic').removeAttr('data-btopts');
		if ( node.tagName == 'SPAN' ) {
			var html = jQuery(node).html();
			jQuery(node).after(html).remove();
		}
	}
}

/********************************
*
*   Remove the spans
*
********************************/
function removeSpans($id){
	var node = tinyMCE.get($id).selection.getNode();
		if (
			node.tagName == 'SPAN' &&
			typeof jQuery(node).attr('class') == 'undefined' &&
			typeof jQuery(node).attr('id') == 'undefined' &&
			typeof jQuery(node).attr('style') != 'undefined'
		) {
		var html = jQuery(node).html();
		jQuery(node).after(html).remove();
	}
}

/********************************
*
*   Open the buttons generator
*
********************************/
function openButtonsGen($id){
	var div = jQuery('#shortcodelic_buttons_generator'),
		h = jQuery(window).height(),
		dialog,
		overlay = false;
	if ( jQuery('#shortcodelic-modal-overlay').length ) {
		overlay = true;
	}
	/*if ( typeof tinyMCE!=='undefined' ) {
		tinyMCE.execCommand('mceRemoveEditor',false,'shortcodelicTMCE');
	}*/
	div.dialog({
		height: (h*0.8),
		width: '92%',
		modal: false,
		dialogClass: 'wp-dialog shortcodelic-dialog shortcodelic-two-cols-dialog',
		position: { my: "center", at: "center", of: window },
		title: div.data('title'),
		zIndex: 10000,
		open: function(){
			jQuery(window).trigger('shortcodelic_dialog_open');
			var node = tinyMCE.get($id).selection.getNode(),
				opts = {},
				htmlThis = '',
				classLink = '',
				id = typeof jQuery(node).attr('id') != 'undefined' ? jQuery(node).attr('id') : '',
				fontsize = typeof jQuery(node).attr('style') != 'undefined' && jQuery(node).attr('style').indexOf('font-size') != -1 ? parseFloat(jQuery(node).css('font-size')) : '';
			fontsize = typeof jQuery(node).attr('class') != 'undefined' && jQuery(node).attr('class').indexOf('buttonelic') != -1 ? fontsize : '14';
			if ( (node.tagName == 'A' || node.tagName == 'SPAN') ) {
				htmlThis = jQuery(node).html();
				htmlThis = htmlThis.replace(/"\{(.*?)\}"/g,'\'{$1}\'');
				htmlThis = htmlThis.replace(/&quot;/g,'"');
				jQuery('[data-name="link"]', div).val(jQuery(node).attr('href'));
				if ( typeof jQuery(node).attr('class') !== 'undefined' ) {
					classLink = ' '+jQuery(node).attr('class')+' ';
					classLink = classLink.replace(/buttonelic/g,'').replace(/  /g,' ');
					jQuery('[data-name="style"] option', div).each(function(){
						var optVal = jQuery(this).val(),
							re;
						if ( optVal!=='' ) {
							if ( classLink.indexOf(' '+optVal+' ') !== -1 ) {
								jQuery(this).prop('selected',true);
								re = new RegExp(optVal+' ',"g");
								classLink = classLink.replace(re,'');
							}
							if ( classLink == optVal ) {
								jQuery(this).prop('selected',true);
								classLink = '';
							}
						}
					});
				}
			} else {
				htmlThis = tinyMCE.get($id).selection.getContent();
			}
			jQuery('[data-name="class"]', div).val(classLink);
			jQuery('[data-name="id"]', div).val(id);
			jQuery('[data-name="fontsize"]', div).val(fontsize);
			if ( jQuery(node).attr('target') == '_blank' ) {
				jQuery('[data-name="target"]', div).prop('checked', true);
			} else {
				jQuery('[data-name="target"]', div).prop('checked', false);
			}
			jQuery('textarea', div).val(htmlThis);
			if ( overlay === false ) {
				jQuery('body').addClass('overflow_hidden').append('<div id="shortcodelic-modal-overlay" />');
			}
			var tdial = jQuery(this);
			tdial.scrollTop(0);
			tdial.closest('.ui-dialog').find('.ui-button').eq(0).addClass('ui-dialog-titlebar-edit');
			getSelectValue(tdial);
			scelic_init_sliders();
			var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);
			jQuery('.shortcodelic_icon_button', div).off('click');
			jQuery('.shortcodelic_icon_button', div).on('click', function(e){
				e.preventDefault();
				openFontSelector('',jQuery('textarea', div));
			});
		},
		buttons: {
			'': function() {
				tinyMCE.execCommand('mceFocus',true,$id);
				var node = tinyMCE.get($id).selection.getNode(),
					fontSize,
					classLink = 'buttonelic ' + jQuery('[data-name="class"]', div).val(),
					id =  jQuery('[data-name="id"]', div).val(),
					target,
					cont = jQuery('textarea', div).val();
				classLink = classLink !== '' ? ' '+classLink : '';
				classLink = classLink + ' ' + jQuery('[data-name="style"] option:selected', div).val();
				fontSize = jQuery('[data-name="fontsize"]', div).val();
				if ( jQuery('[data-name="target"]',div).is(':checked') ) {
					target = ' target="_blank"';
				}
				if ( target!=='' && node.tagName == 'A' ) {
					jQuery(node).attr('target','_blank');
				}
				if ( node.tagName == 'A' ) {
					jQuery(node).addClass(classLink).attr('id',id).attr('href', jQuery('[data-name="link"]', div).val()).css({fontSize:fontSize}).text('').append(cont);
					tinyMCE.get($id).dom.setStyle(node, 'font-size', fontSize+'px');
					var style = jQuery(node).attr('style');
					jQuery(node).attr('data-mce-style',style);
				} else if ( node.tagName == 'SPAN' ) {
					jQuery(node).addClass(classLink).attr('id',id).text('').css({fontSize:fontSize}).append(cont);
					tinyMCE.get($id).dom.setStyle(node, 'font-size', fontSize+'px');
					var style = jQuery(node).attr('style');
					jQuery(node).attr('data-mce-style',style);
				} else {
					var selection = tinyMCE.get($id).selection.getContent();
					id =  id !== '' ? ' id="'+id+'"' : '';
					fontSize = fontSize !== '' ? ' style="font-size:'+fontSize+'px"' : '';
					if ( jQuery('[data-name="link"]', div).val() !== '' ) {
						tinyMCE.get($id).selection.setContent( '<a href="'+jQuery('[data-name="link"]', div).val()+'" class="'+classLink+'"'+id+target+fontSize+'>'+cont+'</a>' );
					} else {
						tinyMCE.get($id).selection.setContent( '<span class="'+classLink+'"'+id+fontSize+'>'+cont+'</span>' );
					}
				}
				jQuery(this).dialog( "close" );
			}
		},
		close: function(){
			if ( overlay === false ) {
				jQuery('body').removeClass('overflow_hidden');
				jQuery('#shortcodelic-modal-overlay').remove();
			}
		}
	});
	jQuery(window).bind('resize',function() {
		h = jQuery(window).height();
		jQuery(div).dialog('option',{'height':(h*0.8),'position':{ my: "center", at: "center", of: window }});
	})/*.triggerHandler('resize')*/;
}

/********************************
*
*   Open the box generator
*
********************************/
function openBoxGen($id){
	var div = jQuery('#shortcodelic_box_generator'),
		h = jQuery(window).height(),
		editor = jQuery('#wp-boxTMCE-wrap'),
		comeFrom = editor.parent(),
		dialog,
		overlay = false;
	if ( typeof tinyMCE!=='undefined' ) {
		tinyMCE.execCommand('mceRemoveEditor',false,'boxTMCE');
	}
	div.find('.shortcodelic_tinymce_area').append(editor);
	if ( jQuery('#shortcodelic-modal-overlay').length ) {
		overlay = true;
	}
	div.dialog({
		height: (h*0.8),
		width: '92%',
		modal: false,
		dialogClass: 'wp-dialog shortcodelic-dialog shortcodelic-three-cols-dialog',
		position: { my: "center", at: "center", of: window },
		title: div.data('title'),
		zIndex: 10000,
		open: function(){
			jQuery(window).trigger('shortcodelic_dialog_open');
			var htmlThis = '';
			if ( typeof tinyMCE.get($id) !== 'undefined' ) {
				htmlThis = tinyMCE.get($id).selection.getContent();
			}
			htmlThis = htmlThis.replace(/\"\{(.*?)\}\"/g,"'{$1}'");
			if ( typeof tinyMCE!=='undefined' ) {
				tinyMCE.execCommand('mceAddEditor',false,'boxTMCE');
				tinyMCE.execCommand('mceFocus',false,'boxTMCE');
				jQuery('#wp-boxTMCE-wrap').removeClass('html-active').addClass('tmce-active');
				tinyMCE.get('boxTMCE').setContent(htmlThis);
			} else {
				jQuery('textarea#boxTMCE', div).val(htmlThis);
			}
			if ( overlay === false ) {
				jQuery('body').addClass('overflow_hidden').append('<div id="shortcodelic-modal-overlay" />');
			}
			var tdial = jQuery(this);
			tdial.scrollTop(0);
			tdial.closest('.ui-dialog').find('.ui-button').eq(0).addClass('ui-dialog-titlebar-edit');
			getSelectValue(tdial);
			scelic_init_sliders();
			jQuery('.shortcodelic_icon_button', div).off('click');
			jQuery('.shortcodelic_icon_button', div).on('click', function(e){
				e.preventDefault();
				openFontSelector('',jQuery('[data-name="icon"]', div));
			});
			var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);
		},
		buttons: {
			'': function() {
				var cont;
				if ( typeof tinyMCE!=='undefined' ) {
					if ( jQuery('#wp-boxTMCE-wrap').hasClass('html-active') && tinyMCE.activeEditor.getParam('wpautop', true) ) {
						cont = switchEditors.wpautop(jQuery('textarea#boxTMCE').val());
					} else {
						cont = tinyMCE.activeEditor.getContent();
					}
				} else {
					cont = jQuery('textarea#boxTMCE').val();
				}
				//tinyMCE.execCommand('mceRemoveEditor',false,$id);
				tinyMCE.execCommand('mceAddEditor',false,$id);
				tinyMCE.execCommand('mceFocus',true,$id);
				var icon = jQuery('[data-name="icon"]', div).val(),
					position = jQuery('[data-name="position"] option:selected', div).val(),
					custom = jQuery('[data-name="custom"] option:selected', div).val(),
					dismiss_box = '';
				if ( jQuery('[data-name="dismiss_box"]',div).is(':checked') ) {
					dismiss_box = jQuery('[data-name="dismiss_box"]',div).val();
				}
				tinyMCE.get($id).selection.setContent( "[shortcodelic-box position=\""+position+"\" custom=\""+custom+"\" dismiss=\""+dismiss_box+"\"]"+icon+cont+"[/shortcodelic-box]" );
				jQuery(this).dialog( "close" );
			}
		},
		close: function(){
			if ( typeof tinyMCE!=='undefined' ) {
				tinyMCE.execCommand('mceRemoveEditor',false,'boxTMCE');
			}
			comeFrom.append(editor);
			if ( overlay === false ) {
				jQuery('body').removeClass('overflow_hidden');
				jQuery('#shortcodelic-modal-overlay').remove();
			}
		}
	});
	jQuery(window).bind('resize',function() {
		h = jQuery(window).height();
		jQuery(div).dialog('option',{'height':(h*0.8),'position':{ my: "center", at: "center", of: window }});
	})/*.triggerHandler('resize')*/;
}

jQuery(document).ready(function(){
	uploadSlidesForSlideshow();
	addElems();
	hideShowElems();
	sortElements();
	cloneElements();
	getSelectValue(jQuery('body .shortcodelic_meta'));
	scManagerLoader();
	cloneSet();
	deleteSet();
	scelic_init_sliders();
	scelic_init_farbtastic();
	pixWpPointer();
	addRowCols();
});