jQuery.noConflict();

function getDataAttributes(node) {
    var d = {}, 
        re_dataAttr = /^data\-(.+)$/;

    $.each(node.get(0).attributes, function(index, attr) {
        if (re_dataAttr.test(attr.nodeName)) {
            var key = attr.nodeName.match(re_dataAttr)[1];
            d[key] = attr.nodeValue;
        }
    });

    return d;
}

function pixgridder_hex2rgb( hex ) {
	hex = (hex.substr(0,1)=="#") ? hex.substr(1) : hex;
	if (hex.length < 6) {
		hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
	}
	if (!isNaN(hex)) {
		return [parseInt(hex.substr(0,2), 16), parseInt(hex.substr(2,2), 16), parseInt(hex.substr(4,2), 16)];
	} else {
		return [255,255,255];
	}
}

function pixgridder_checkDarkness( hex ) {
	var rgb = pixgridder_hex2rgb( hex );
    var min, max, delta, h, s, l;
    var r = rgb[0], g = rgb[1], b = rgb[2];
    min = Math.min(r, Math.min(g, b));
    max = Math.max(r, Math.max(g, b));
    delta = max - min;
    l = (min + max) / 2;
    s = 0;
    if (l > 0 && l < 1) {
      s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
    }
    h = 0;
    if (delta > 0) {
      if (max == r && max != g) h += (g - b) / delta;
      if (max == g && max != b) h += (2 + (b - r) / delta);
      if (max == b && max != r) h += (4 + (r - g) / delta);
      h /= 6;
    }
    return l > (255/2);
  }
/********************************
*
*   Select
*
********************************/
function getSelValue(){
    jQuery('#pix_builder_canvas select, #pix_builder_row_fields select, #pix_builder_column_fields select').off('change');
    jQuery('#pix_builder_canvas select, #pix_builder_row_fields select, #pix_builder_column_fields select').on('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');

	jQuery('.pix_section_builder').each(function(){
		var dataCols = jQuery(this).attr('data-cols');
		jQuery('.pix_section_template option[value="'+dataCols+'"]',this).prop('selected',true);
		jQuery('.pix_section_template',this).change();
	});

	jQuery('#pix_builder_canvas .pix_section_template').off('change');
	jQuery('#pix_builder_canvas .pix_section_template').on('change',function(){ //if I change the number of columns
		var section = jQuery(this).parents('.pix_section_builder').eq(0),
			dataCol = parseFloat(jQuery('option:selected',this).val()),
			lengAct = 0,
			lengCol = 0,
			t = jQuery(this);
		jQuery('.pix_builder_column',section).not('.pix_clone_column').each(function(){
			lengCol = lengCol + parseFloat(jQuery(this).attr('data-col'));
		});
		jQuery('.pix_builder_column.pix_column_active',section).not('.pix_clone_column').each(function(){
			lengAct = parseFloat(jQuery(this).attr('data-col')) > lengAct ? parseFloat(jQuery(this).attr('data-col')) : lengAct;
		});
		if(dataCol < lengAct) { //in this case you are trying to remove columns from the layout, but you can't because the script can't know how to manage the extra content
			jQuery('option[value="'+lengAct+'"]',this).prop('selected',true);
			var tx = jQuery('option:selected',this).text(),
				elm = jQuery(this).siblings('.appended');
			jQuery(elm).text(tx);
			section.find('.pix_section_error').fadeIn(400,function(){jQuery(this).delay(1500).fadeOut();});
		} else { //in this case you can change the layout
			section.attr('data-cols',dataCol);
			/*if ( dataCol > lengCol ) {
				var i = lengCol;
				while (i<dataCol) {
					section.find('.pix_builder_column').not('.pix_clone_column').last().after('<div class="pix_builder_column" data-col="1" />');
					i++;
				}
				jQuery('.pix_builder_column',section).not('.pix_clone_column').each(function(){ //I calculate again lengCol to avoid that the 'while' loop replicates the action and add too many columns
					lengCol = lengCol + parseFloat(jQuery(this).attr('data-col'));
				});
				checkEmptyColumns();	
			} else {
				var i = (dataCol+1);
				while (i<lengCol) {
					jQuery('.pix_builder_column',section).not('.pix_clone_column').not('.pix_column_active').not(':has(.pix_add_column)').last().attr('data-col','0');
					i++;
					jQuery('.pix_builder_column[data-col=0]',section).remove(); //repeated, because of the getSelValue is init on DOM too
					checkEmptyColumns();
				}
			//}
			jQuery('.pix_builder_column[data-col=0]',section).remove(); //repeated, because of the getSelValue is init on DOM too*/
			setVisualContent();
			columnWidth();
		}
		getSelValue();
	});
}


/********************************
*
*   iFrame scroll and fade
*
********************************/
function pix_loaded_iframe(){
	var myIframe = document.getElementById('pix-builder-iframe');
	iframeDoc = myIframe.contentWindow.document;
	if ( jQuery(iframeDoc).find('#main').length ) {
		var content = jQuery(iframeDoc).find('#main').offset().top;
	} else {
		var content = 0;
	}
	myIframe.contentWindow.scrollTo(0,content);
	jQuery('#pix-builder-iframe').css('visibility','visible');
	jQuery('#pix_loader_iframe').fadeOut();
}


/********************************
*
*   Field creation
*
********************************/
function setVisualContent() {

	var content = '';

	jQuery('#pix_builder_canvas .pix_section_builder_movable').not('.pix_clone_section').each(function(){

		var t = jQuery(this),
			dataCols = parseFloat(t.attr('data-cols')),
			dataId = (typeof jQuery(this).attr('data-id')!='undefined' && jQuery(this).attr('data-id')!=='') ? ' data-id['+jQuery(this).attr('data-id')+']' : '',
			dataClass = (typeof jQuery(this).attr('data-class')!='undefined' && jQuery(this).attr('data-class')!=='') ? ' data-class['+jQuery(this).attr('data-class')+']' : '';
			dataExtra = (typeof jQuery(this).attr('data-extra')!='undefined' && jQuery(this).attr('data-extra')!=='') ? ' data-extra['+jQuery(this).attr('data-extra')+']' : '';
			dataRatio = (typeof jQuery(this).attr('data-stellar-background-ratio')!='undefined' && jQuery(this).attr('data-stellar-background-ratio')!=='') ? ' data-stellar-background-ratio['+jQuery(this).attr('data-stellar-background-ratio')+']' : '';
			dataStyle = (typeof jQuery(this).attr('data-style')!='undefined' && jQuery(this).attr('data-style')!=='') ? ' data-style['+jQuery(this).attr('data-style')+']' : '';

		dataStyle = dataStyle.replace(/\"/g,"'");

		content = content + '<!--pixgridder:row[cols='+dataCols+']' + dataId + dataClass + dataExtra + dataStyle + dataRatio + '-->' + jQuery('textarea.pix_section_txt',this).val();

		jQuery('.pix_builder_column.pix_column_active',t).not('.pix_clone_column').each(function(){
			var dataCol = parseFloat(jQuery(this).attr('data-col')),
				dataId = (typeof jQuery(this).attr('data-id')!='undefined' && jQuery(this).attr('data-id')!=='') ? ' data-id['+jQuery(this).attr('data-id')+']' : '',
				dataClass = (typeof jQuery(this).attr('data-class')!='undefined' && jQuery(this).attr('data-class')!=='') ? ' data-class['+jQuery(this).attr('data-class')+']' : '',
				dataSmall = (typeof jQuery(this).attr('data-small')!='undefined' && jQuery(this).attr('data-small')!=='') ? ' data-small['+jQuery(this).attr('data-small')+']' : '',
				dataMedium = (typeof jQuery(this).attr('data-medium')!='undefined' && jQuery(this).attr('data-medium')!=='') ? ' data-medium['+jQuery(this).attr('data-medium')+']' : '',
				dataStyle = (typeof jQuery(this).attr('data-style')!='undefined' && jQuery(this).attr('data-style')!=='') ? ' data-style['+jQuery(this).attr('data-style')+']' : '',
				colCont = jQuery('textarea',this).val();
			dataStyle = dataStyle.replace(/\"/g,"'");
			content = content + '<!--pixgridder:column[col='+dataCol+']' + dataId + dataClass + dataSmall + dataMedium + dataStyle + '-->';
			content = content + colCont;
			content = content + '<!--/pixgridder:column[col='+dataCol+']-->';
		});

		content = content + '<!--/pixgridder:row[cols='+dataCols+']-->';

	});

	content = content.replace(/<p><\/p>/g,'');
	/*content = content.replace(/<span(.+?)font-size: 1rem(.+?)>(.+?)<\/span>/g,'$3');
	content = content.replace(/<(.+?) (.+?)font-size: 1rem(.+?)>(.+?)<\//g,'<$1>$4</');
	content = content.replace(/<(.+?) font-size: 1rem(.+?)>(.+?)<\//g,'<$1>$3</');*/
	content = content.replace(/<iframe(.+?)data-utoplay(.+?)>/g,'<iframe$1autoplay$2>');

	if ( typeof tinymce!=='undefined' && typeof tinymce.get('content')!=='undefined' ) {
		tinymce.get('content').setContent(content);
	}

	jQuery('textarea#content').val(content);

}


function pageBuilder(){

	if ( pixgridder_disable_preview != 'true' ) {
		jQuery('#wp-content-editor-tools').prepend(
			'<a id="pix-content-preview" class="hide-if-no-js wp-switch-editor switch-preview" onclick="switchEditors.switchto(this);">'+pixgridder_preview_text+'</a>'
		).prepend(
			'<a id="pix-content-builder" class="hide-if-no-js wp-switch-editor switch-builder" onclick="switchEditors.switchto(this);">'+pixgridder_builder_text+'</a>'
		);
	}

	var after = jQuery('#pix-builder-editor-container');
	jQuery('#wp-content-editor-container').after(after);


	var pix_editor_tab = localStorage.getItem("pix_editor_tab"),
		page_template,
		max_columns,
		class_wrap;

	function switchBuilder(){
		jQuery('#pix_builder_preview').hide();
		jQuery('#pix_builder_canvas').show();
		var wrap = jQuery('#wp-content-wrap');
		wrap.removeClass('preview-active').addClass('builder-active');
		localStorage.setItem('pix_editor_tab', 'pix_builder');
	}

	function switchPreview(){
		jQuery('#pix_loader_iframe').show();
		jQuery('#pix-builder-iframe').css('visibility','hidden');
		jQuery('#pix_builder_canvas').hide();
		jQuery('#pix_builder_preview').show();
		var wrap = jQuery('#wp-content-wrap');
		wrap.removeClass('builder-active').addClass('preview-active');
		localStorage.setItem('pix_editor_tab', 'pix_preview');
		if ( jQuery('#auto_draft').val() == '1'/* && notSaved*/ ) {
			//autosaveDelayPreview = true;
			autosave();
			return false;
		}
		doPixPreview();
		return false;
	}

	function doPixPreview(){
		jQuery('input#wp-preview').val('dopreview');
		jQuery('form#post').attr('target', 'iframe-preview').submit().attr('target', '');

		var ua = navigator.userAgent.toLowerCase();
		if ( ua.indexOf('safari') != -1 && ua.indexOf('chrome') == -1 ) {
			jQuery('form#post').attr('action', function(index, value) {
				return value + '?t=' + new Date().getTime();
			});
		}

		jQuery('input#wp-preview').val('');
	}

	jQuery(document).off('click','#pix-content-builder');
	jQuery(document).on('click','#pix-content-builder',function(){
		switchBuilder();
	});

	jQuery(document).off('click','#pix-content-preview');
	jQuery(document).on('click','#pix-content-preview',function(){
		switchPreview();
	});

	if ( pix_editor_tab == 'pix_builder' || pixgridder_disable_preview == 'true' ) {
		switchBuilder();
	} else {
		switchPreview();
	}

	jQuery(document).off('click',"#pix_builder_canvas .pix_column_edit");
	jQuery(document).on('click',"#pix_builder_canvas .pix_column_edit",function(){
		if ( typeof tinymce!=='undefined' ) {
			tinymce.execCommand('mceRemoveEditor',false,'textArea');
		}
		var t = jQuery(this).parents('.pix_builder_column').eq(0),
			textA = jQuery('textarea',t),
			textCont = jQuery('.pix_builder_content',t),
			htmlThis = textA.val(),
			h = jQuery(window).height(),
			div = jQuery('#textarea_builder'),
			dataCol = t.attr('data-col'),
			dataCols = t.parents('.pix_section_builder').eq(0).attr('data-cols'),
			title = typeof div.attr('data-title')!='undefined' ? div.attr('data-title') : 'Add some values';

		htmlThis = htmlThis.replace(/<p><\/p>/g,'');
		htmlThis = htmlThis.replace(/<p><\!--\/pixgridder(.+?)-->(?!<\!--)/g, '<!--/pixgridder$1--><p>');
		htmlThis = htmlThis.replace(/<p><\!--pixgridder(.+?)--><\/p>/g, '<!--pixgridder$1-->');
		htmlThis = htmlThis.replace(/<p><\!--\/pixgridder(.+?)--><\/p>/g, '<!--/pixgridder$1-->');
		htmlThis = htmlThis.replace(/<iframe(.+?)data-utoplay(.+?)>/g,'<iframe$1autoplay$2>');
		jQuery(div).dialog({
			height: (h*0.8),
			width: '80%',
			modal: false,
			dialogClass: 'wp-dialog pix-dialog pix-page-builder',
			position: 'center',
			title: title,
			zIndex: 10000,
			open: function(){
				jQuery(window).trigger('pix_builder_modal');
				if ( typeof tinymce!=='undefined' ) {
					pixgridderTinyMCEinit();
				}
				jQuery(this).closest('.ui-dialog').find('.ui-button').eq(0).addClass('ui-dialog-titlebar-edit');
				jQuery('body').addClass('overflow_hidden').append('<div id="pix-modal-overlay" />');
				jQuery('#pix-modal-overlay').css({
					background: '#000000',
					bottom: 0,
					height: '100%',
					left: 0,
					opacity: 0.6,
					position: 'fixed',
					right: 0,
					top: 0,
					width: '100%',
					zIndex: 9999
				});
				if ( typeof tinymce!=='undefined' ) {
					tinymce.execCommand('mceAddEditor',false,'textArea');
					tinymce.execCommand('mceFocus',false,'textArea');
					tinymce.get('textArea').setContent(htmlThis);
					var bodyTMCE = tinymce.get('textArea').dom.select('body');
					jQuery(bodyTMCE).css({width:(pixgridder_content_width*(dataCol/dataCols))}); //to display a particular width of the editor according with the width of the column you're editing
					jQuery('#wp-textArea-wrap').removeClass('html-active').addClass('tmce-active');
				} else {
					jQuery('textarea#textArea').val(htmlThis);
				}
				jQuery(window).bind('resize',function() {
					if ( typeof tinymce === 'undefined' ) {
						var txtH = parseFloat(jQuery('#textarea_builder').height()),
							qtH = parseFloat(jQuery('#qt_textArea_toolbar').outerHeight()),
							toolH = parseFloat(jQuery('#wp-textArea-editor-tools').outerHeight());
						jQuery('#textArea').height(txtH-(qtH+toolH+40));
					}
				});
				var set = setTimeout(function(){ jQuery(window).triggerHandler('resize'); },100);
			},
			buttons: {
				'': function() {
					var cont;
					if ( typeof tinymce!=='undefined' ) {
						if ( jQuery('#wp-textArea-wrap').hasClass('html-active') && tinymce.get('textArea').getParam('wpautop', true) ) {
							cont = switchEditors.wpautop(jQuery('textarea#textArea').val());
						} else {
							cont = tinymce.get('textArea').getContent();
						}
					} else {
						cont = jQuery('textarea#textArea').val();
					}
					/*cont = cont.replace(/<span(.+?)font-size: 1rem(.+?)>(.+?)<\/span>/g,'$3');
					cont = cont.replace(/<(.+?) (.+?)font-size: 1rem(.+?)>(.+?)<\//g,'<$1>$4</');
					cont = cont.replace(/<(.+?) font-size: 1rem(.+?)>(.+?)<\//g,'<$1>$3</');*/
					cont = cont.replace(/<iframe(.+?)autoplay(.+?)>/g,'<iframe$1data-utoplay$2>');

					textA.val(cont);
					textCont.html(cont);

					var set;
					clearTimeout(set);
					set = setTimeout(function(){ setVisualContent(); },200);

					jQuery( this ).dialog( "close" );
				}
			},
			close: function(){
				jQuery('body').removeClass('overflow_hidden');
				jQuery('#pix-modal-overlay').remove();
				jQuery(window).unbind('resize');
			}
		});
		jQuery(window).bind('resize',function() {
			h = jQuery(window).height(),
			jQuery(div).dialog('option',{'height':(h*0.8),'position':'center'});
		}).triggerHandler('resize');
	});


	jQuery(document).off('click',"#pix_builder_canvas .pix_column_id");
	jQuery(document).on('click',"#pix_builder_canvas .pix_column_id",function(){
		var t = jQuery(this).parents('.pix_builder_column').eq(0),
			section = t.parents('.pix_section_builder').eq(0),
			dataCols = parseFloat(section.attr('data-cols')),
			textA = jQuery('textarea',t),
			h = jQuery(window).height(),
			div = jQuery('#pix_builder_column_fields'),
			idT = typeof t.attr('data-id')!='undefined' ? t.attr('data-id') : '',
			classT = typeof t.attr('data-class')!='undefined' ? t.attr('data-class').replace(/\s+/g, ' ') : '',
			classArr = classT.split(' '),
			cfxArr = [],
			styleArr,
			newClassT,
			dataSmall = typeof t.attr('data-small')!='undefined' ? t.attr('data-small') : '',
			dataMedium = typeof t.attr('data-medium')!='undefined' ? t.attr('data-medium') : '',
			height = typeof div.attr('data-height')!='undefined' ? div.attr('data-height') : 450,
			title = typeof div.attr('data-title')!='undefined' ? div.attr('data-title') : 'Add some values',
			styleT = typeof t.attr('data-style')!='undefined' ? t.attr('data-style') : '';

		height = height < (h * 0.8) ? height : (h * 0.8);

		if ( styleT!=='' ) {
			styleT = styleT.replace(/'/g, '"');
			styleArr = jQuery.parseJSON( styleT );
		}

		if ( styleArr === null || typeof styleArr == 'undefined' ) {
			styleArr = {};
		}

		jQuery.each(styleArr, function(i, val) {
			jQuery('[data-style="'+i+'"]',div).each(function(){
				if ( typeof jQuery(this).attr('data-unit') != 'undefined' && jQuery(this).attr('data-unit') !== '' ) {
					var re = new RegExp(jQuery(this).attr('data-unit'),"g");
					val = val.replace(re,'');
				}
				if ( typeof jQuery(this).attr('data-parenth') != 'undefined' && jQuery(this).attr('data-parenth') !== '' ) {
					val = val.replace(/(.+?)\((.+?)\)/g,'$2');
				}
				jQuery(this).val(val);
			});
		});

		jQuery('input[data-use="id"]',div).val(idT);
		jQuery('input[data-use="class"]',div).val(classT);
		jQuery('select[data-use="fx"] option',div).each(function(){
			if ( jQuery(this).val()!=='' ) {
				cfxArr.push(jQuery(this).val());
			}
		});
		jQuery.each( classArr, function( key, value ) {
			jQuery('select[data-use="fx"] option[value="'+value+'"]',div).prop('selected',true);
		});

		jQuery(div).find('.for_select').show().end().dialog({
			height: height,
			width: 780,
			modal: false,
			dialogClass: 'wp-dialog pix-dialog pix-page-builder-id',
			position: 'center',
			title: title,
			zIndex: 9999,
			open: function(){
				getSelValue();
				gridder_farbtastic();
				gridder_sliders();
				pixGridderAutoComplete(jQuery('[data-style="background-color"]',div), pixgridder_featuredColors, false, true);

				jQuery('select', div).trigger('change');

				jQuery('select[data-use="fx"]', div).bind('change',function(){
					newClassT = jQuery('input[data-use="class"]',div).val();
					jQuery.each( cfxArr, function( key, value ) {
						value = new RegExp(value,"g");
						newClassT = newClassT.replace(value, '');
					});
					if ( /*newClassT !== '' && */jQuery('option:selected', this).val() !== '' ) {
						newClassT = newClassT + ' ' + jQuery('option:selected', this).val();
					}
					if ( newClassT.replace(/\s+/g, '')!=='' ) {
						jQuery('input[data-use="class"]',div).val( newClassT.replace(/\s+/g, ' ') );
					} else {
						jQuery('input[data-use="class"]',div).val('');
					}
					jQuery('input[data-use="class"]',div).val( newClassT.replace(/\s+/g, ' ') );
				});

				jQuery('select[data-break] option[value!=""]', div).remove();
				jQuery('select[data-break]', div).each(function(){
					var i = 1;
					while ( i<=dataCols ) {
						jQuery(this).append('<option value="'+i+'">'+i+'</option>');
						i++;
					}
				});

				jQuery('select[data-break="small"] option[value="'+dataSmall+'"]',div).prop('selected',true);
				jQuery('select[data-break="medium"] option[value="'+dataMedium+'"]',div).prop('selected',true);
				jQuery('select', div).trigger('change');

				jQuery(this).closest('.ui-dialog').find('.ui-button').eq(0).addClass('ui-dialog-titlebar-edit');
				jQuery('body').addClass('overflow_hidden').append('<div id="pix-modal-overlay" />');
				pixGridderAutoComplete(jQuery('[data-use="class"]',div), pixgridder_colClassArr, true);
				jQuery('#pix-modal-overlay').css({
					background: '#000000',
					bottom: 0,
					height: '100%',
					left: 0,
					opacity: 0.6,
					position: 'fixed',
					right: 0,
					top: 0,
					width: '100%',
					zIndex: 9999
				});
			},
			buttons: {
				'': function() {
					t.attr('data-id', jQuery('[data-use="id"]',div).val());
					t.attr('data-class', jQuery('[data-use="class"]',div).val());
					t.attr('data-small', jQuery('[data-break="small"]',div).val());
					t.attr('data-medium', jQuery('[data-break="medium"]',div).val());

					var styleArr2 = {};
					jQuery('[data-style]',div).each(function(){
						var keyStyle = jQuery(this).attr('data-style'),
							valueStyle = jQuery(this).val();
						if ( valueStyle!=='' ) {
							var unit = typeof jQuery(this).data('unit') != 'undefined' ? jQuery(this).data('unit') : '';
							valueStyle = valueStyle+unit;
							valueStyle = typeof jQuery(this).data('parenth') != 'undefined' ? jQuery(this).data('parenth')+'('+ valueStyle +')' : valueStyle;
							styleArr2[keyStyle] = valueStyle;
						}
					});

					if (!jQuery.isEmptyObject(styleArr2)) {
						styleArr2 = JSON.stringify(styleArr2);
						t.attr('data-style', styleArr2);
					} else {
						t.removeAttr('data-style');
					}

					jQuery( this ).dialog( "close" );
					var set = setTimeout(function(){ setVisualContent(); },200);

				}
			},
			close: function(){
				jQuery('body').removeClass('overflow_hidden');
				jQuery('#pix-modal-overlay').remove();
				div.find('input').val('');
				jQuery(window).unbind('resize');
			}
		});
		jQuery(window).bind('resize',function() {
			height = height < (jQuery(window).height() * 0.8) ? height : (jQuery(window).height() * 0.8);
			jQuery(div).dialog('option',{'height':height,'position':'center'});
		}).triggerHandler('resize');
	});




	jQuery(document).off('click',"#pix_builder_canvas .pix_column_clone");
	jQuery(document).on('click',"#pix_builder_canvas .pix_column_clone",function(){
		var t = jQuery(this),
			column = t.parents('.pix_column_active').eq(0),
			dataCol = parseFloat(column.attr('data-col')),
			section = column.parents('.pix_section_builder').eq(0),
			dataCols = parseFloat(section.attr('data-cols')),
			clone = column.clone(),
			textA = column.find('textarea').val(),
			lengCol = 0;
		jQuery('.pix_builder_column.pix_column_active',section).not('.pix_clone_column').each(function(){
			lengCol = lengCol + parseFloat(jQuery(this).attr('data-col'));
		});
		//if ( dataCol <= (dataCols-lengCol) ) {
			clone.attr('data-col','0').css({display:'none'});
			column.after(clone);
			/*var i = 0;
			while (i<dataCol) {
				jQuery('.pix_builder_column:not(.pix_clone_column):last',section).remove();
				i++;
			}*/
			var set = setTimeout(function(){
				clone.fadeIn();
				clone.attr('data-col',dataCol);
				clone.find('textarea').val(textA);
				sortColumns();
				checkEmptyColumns();
				expandColumns();
				removeColumns();
				setVisualContent();
				columnWidth();
				getSelValue();
			},100);
		/*} else {
			t.parents('.pix_section_builder').eq(0).find('.pix_section_error').fadeIn(400,function(){jQuery(this).delay(1500).fadeOut();});
		}*/
	});




	jQuery(document).off('click',"#pix_builder_canvas .pix_section_clone");
	jQuery(document).on('click',"#pix_builder_canvas .pix_section_clone",function(){
		var t = jQuery(this),
			section = t.parents('.pix_section_builder').eq(0),
			clone = section.clone().hide(),
			textASection = jQuery('textarea.pix_section_txt',section).val();
		jQuery('.pix_builder_column.pix_column_active:not(".pix_clone_column")', section).each(function(){
			var textA =  jQuery('textarea',this).val(),
				ind = jQuery(this).index();
			jQuery('.pix_builder_column.pix_column_active textarea',clone).eq(ind).val(textA);
		});
		jQuery('textarea.pix_section_txt',clone).val(textASection);
		section.after(clone);
		clone.slideDown();
		sortColumns();
		expandColumns();
		addColumns();
		removeColumns();
		removeSections();
		setVisualContent();
		getSelValue();
	});




	jQuery(document).off('click',"#pix_builder_canvas .pix_section_id");
	jQuery(document).on('click',"#pix_builder_canvas .pix_section_id",function(){
		var t = jQuery(this).parents('.pix_section_builder').eq(0),
			textA = jQuery('textarea.pix_section_txt',t),
			h = jQuery(window).height(),
			div = jQuery('#pix_builder_row_fields'),
			idT = typeof t.attr('data-id')!='undefined' ? t.attr('data-id') : '',
			classT = typeof t.attr('data-class')!='undefined' ? t.attr('data-class') : '',
			extraT = typeof t.attr('data-extra')!='undefined' ? t.attr('data-extra') : '',
			ratioT = typeof t.attr('data-stellar-background-ratio')!='undefined' ? t.attr('data-stellar-background-ratio') : '',
			styleT = typeof t.attr('data-style')!='undefined' ? t.attr('data-style') : '',
			classArr = classT.split(' '),
			cfxArr = [],
			styleArr,
			newClassT,
			height = typeof div.attr('data-height')!='undefined' ? div.attr('data-height') : 300,
			title = typeof div.attr('data-title')!='undefined' ? div.attr('data-title') : 'Add some values';

		height = height < (jQuery(window).height() * 0.8) ? height : (jQuery(window).height() * 0.8);

		if ( styleT!=='' ) {
			styleT = styleT.replace(/'/g, '"');
			styleArr = jQuery.parseJSON( styleT );
		}

		jQuery('input[data-use="id"]',div).val(idT);
		jQuery('input[data-use="class"]',div).val(classT);
		jQuery('input[data-use="stellar-background-ratio"]',div).val(ratioT);

		if ( styleArr === null || typeof styleArr == 'undefined' ) {
			styleArr = {};
		}

		jQuery.each(styleArr, function(i, val) {
			jQuery('[data-style="'+i+'"]',div).each(function(){
				if ( typeof jQuery(this).attr('data-unit') != 'undefined' && jQuery(this).attr('data-unit') !== '' ) {
					var re = new RegExp(jQuery(this).attr('data-unit'),"g");
					val = val.replace(re,'');
				}
				if ( typeof jQuery(this).attr('data-parenth') != 'undefined' && jQuery(this).attr('data-parenth') !== '' ) {
					val = val.replace(/(.+?)\((.+?)\)/g,'$2');
				}
				jQuery(this).val(val);
			});
		});

		jQuery('select[data-extra] option[value="'+extraT+'"]',div).prop('selected',true);
		jQuery('input[data-extra]',div).val(extraT);

		jQuery(div).find('.for_select').show().end().dialog({
			height: height,
			width: 780,
			modal: false,
			dialogClass: 'wp-dialog pix-dialog pix-page-builder-id',
			position: 'center',
			title: title,
			zIndex: 1000,
			open: function(){
				getSelValue();
				gridder_farbtastic();
				gridder_sliders();
				gridderUploadImages();
				jQuery('select', div).trigger('change');
				jQuery(this).closest('.ui-dialog').find('.ui-button').eq(0).addClass('ui-dialog-titlebar-edit');
				jQuery('body').addClass('overflow_hidden').append('<div id="pix-modal-overlay" />');
				pixGridderAutoComplete(jQuery('[data-use="class"]',div), pixgridder_rowClassArr, true);
				pixGridderAutoComplete(jQuery('[data-style="background-color"],[data-style="border-bottom-color"],[data-style="border-top-color"]',div), pixgridder_featuredColors, false, true);
				jQuery('#pix-modal-overlay').css({
					background: '#000000',
					bottom: 0,
					height: '100%',
					left: 0,
					opacity: 0.6,
					position: 'fixed',
					right: 0,
					top: 0,
					width: '100%',
					zIndex: 9999
				});
				jQuery(window).trigger('pixgridder_section_id_open');
			},
			buttons: {
				'': function() {
					if ( jQuery('[data-use="id"]',div).val()!=='' ) {
						t.attr('data-id', jQuery('[data-use="id"]',div).val());
					} else {
						t.removeAttr('data-id');
					}
					if ( jQuery('[data-use="class"]',div).val()!=='' ) {
						t.attr('data-class', jQuery('[data-use="class"]',div).val());
					} else {
						t.removeAttr('data-class');
					}
					if ( jQuery('[data-use="extra"]',div).val()!=='' ) {
						t.attr('data-extra', jQuery('[data-extra] option:selected',div).val());
					} else {
						t.removeAttr('data-extra');
					}
					if ( jQuery('[data-use="stellar-background-ratio"]',div).val()!=='' ) {
						t.attr('data-stellar-background-ratio', jQuery('[data-use="stellar-background-ratio"]',div).val());
					} else {
						t.removeAttr('data-stellar-background-ratio');
					}

					var styleArr2 = {};
					jQuery('[data-style]',div).each(function(){
						var keyStyle = jQuery(this).attr('data-style'),
							valueStyle = jQuery(this).val();
						if ( valueStyle!=='' ) {
							var unit = typeof jQuery(this).data('unit') != 'undefined' ? jQuery(this).data('unit') : '';
							valueStyle = valueStyle+unit;
							valueStyle = typeof jQuery(this).data('parenth') != 'undefined' ? jQuery(this).data('parenth')+'('+ valueStyle +')' : valueStyle;
							styleArr2[keyStyle] = valueStyle;
						}
					});
					if (!jQuery.isEmptyObject(styleArr2)) {
						styleArr2 = JSON.stringify(styleArr2);
						t.attr('data-style', styleArr2);
					} else {
						t.removeAttr('data-style');
					}

					jQuery( this ).dialog( "close" );
					var set = setTimeout(function(){ setVisualContent(); },200);
				}
			},
			close: function(){
				jQuery('body').removeClass('overflow_hidden');
				jQuery('.pix_color_picker i',this).click();
				jQuery('#pix-modal-overlay').remove();
				div.find('input').val('');
				jQuery(window).unbind('resize');
			}
		});
		jQuery(window).bind('resize',function() {
			height = height < (jQuery(window).height() * 0.8) ? height : (jQuery(window).height() * 0.8);
			jQuery(div).dialog('option',{'height':height,'position':'center'});
		}).triggerHandler('resize');
	});
}

function setBuilderContent() {

	var theDom,
		theBody,
		set, set2;


	/*if ( typeof tinymce !== "undefined" && typeof tinymce.get('content') !== "undefined" ) {
		theDom = tinymce.get('content').dom.select('body');
		theBody = jQuery(theDom).html();
	} else {*/
	theBody = jQuery('textarea#content').text();
	//}

	console.log(jQuery('textarea#content').text());

	theBody = theBody.replace(/<p><\!--pixgridder(.+?)-->(?!<\!--)/g, '<!--pixgridder$1--><p>');
	theBody = theBody.replace(/<p><\!--\/pixgridder(.+?)-->(?!<\!--)/g, '<!--/pixgridder$1--><p>');
	theBody = theBody.replace(/<p><\!--pixgridder(.+?)--><\/p>/g, '<!--pixgridder$1-->');
	theBody = theBody.replace(/<p><\!--\/pixgridder(.+?)--><\/p>/g, '<!--/pixgridder$1-->');
	theBody = theBody.replace(/<p><\!--\/pixgridder(.+?)--><\/p>/g, '<!--/pixgridder$1-->');
	theBody = theBody.replace(/<\!--\/pixgridder(.+?)--><p><\/p>/g, '<!--/pixgridder$1-->');
	theBody = theBody.replace(/<!--pixgridder:row([^<])+<!--\/pixgridder:row([^<])+-->/g, '');
	theBody = theBody.replace(/<!--pixgridder:column([^<])+<!--\/pixgridder:column([^<])+-->/g, '');
	theBody = theBody.replace(/<!--pixgridder:row\[cols=([0-9]+)\] data(.+?)-->/g, '<div class="pix_builder_row" data-cols="$1" data$2>');
	theBody = theBody.replace(/<!--pixgridder:row\[cols=([0-9]+)\]-->/g, '<div class="pix_builder_row" data-cols="$1">');
	theBody = theBody.replace(/<!--\/pixgridder:row\[cols=([0-9]+)\]-->/g, '</div>');
	theBody = theBody.replace(/<!--pixgridder:column\[col=([0-9]+)\] data(.+?)-->/g, '<div class="pix_builder_column" data-col="$1" data$2>');
	theBody = theBody.replace(/<!--pixgridder:column\[col=([0-9]+)\]-->/g, '<div class="pix_builder_column" data-col="$1">');
	theBody = theBody.replace(/<!--\/pixgridder:column\[col=([0-9]+)\]-->/g, '</div>');
	theBody = theBody.replace(/data-id\[(.+?)\]/g, 'data-id="$1"');
	theBody = theBody.replace(/data-class\[(.+?)\]/g, 'data-class="$1"');
	theBody = theBody.replace(/data-extra\[(.+?)\]/g, 'data-extra="$1"');
	theBody = theBody.replace(/data-stellar-background-ratio\[(.+?)\]/g, 'data-stellar-background-ratio="$1"');
	theBody = theBody.replace(/data-style\[(.+?)\]/g, 'data-style="$1"');
	theBody = theBody.replace(/data-small\[(.+?)\]/g, 'data-small="$1"');
	theBody = theBody.replace(/data-medium\[(.+?)\]/g, 'data-medium="$1"');
	theBody = theBody.replace(/<iframe(.+?)autoplay(.+?)>/g,'<iframe$1data-utoplay$2>');

	jQuery('#pix_builder_yard').append(theBody);

	if (!jQuery('#pix_builder_yard .pix_builder_row').length || !jQuery('#pix_builder_yard .pix_builder_column').length) {
		clearTimeout(set);
		clearTimeout(set2);
		set = setTimeout(function(){
			jQuery('#pix_builder_canvas .pix_add_section').click();
			jQuery('.pix_section_builder').not('.pix_clone_section').find('.pix_add_column').click();
			if ( theBody != '' ) {
				var dataCols = jQuery('.pix_builder_column').eq(0).parents('.pix_section_builder').attr('data-cols');
				jQuery('.pix_builder_column').eq(0).attr('data-col',dataCols).find('textarea').val(theBody);
				jQuery('.pix_builder_content').eq(0).html(theBody);
				checkEmptyColumns();
				columnWidth();
			}
			jQuery('body').addClass('pixgridder_generated');
		},500);
		set2 = setTimeout(function(){
			setVisualContent();
		},600);
	} else {

		jQuery('#pix_builder_canvas').hide();

		jQuery('#pix_builder_yard .pix_builder_row').each(function(){

			var count = 0;

			var t = jQuery(this),
				dataCols = parseFloat(t.attr('data-cols')),
				dataId = t.attr('data-id'),
				dataClass = t.attr('data-class'),
				dataId = typeof t.attr('data-id')!='undefined' ? t.attr('data-id') : '',
				dataClass = typeof t.attr('data-class')!='undefined' ? t.attr('data-class') : '',
				dataExtra = typeof t.attr('data-extra')!='undefined' ? t.attr('data-extra') : '',
				dataRatio = typeof t.attr('data-stellar-background-ratio')!='undefined' ? t.attr('data-stellar-background-ratio') : '',
				dataStyle = typeof t.attr('data-style')!='undefined' ? t.attr('data-style') : '',
				cloneOriginal = jQuery('.pix_section_builder.pix_clone_section'),
				clone = cloneOriginal.clone(),
				idClass = t.clone().children().remove().end().html();

			if ( jQuery('.pix_builder_column',t).length ) {
				clone.hide().removeClass('pix_clone_section');
				if ( dataCols!=='' ) { clone.attr('data-cols',dataCols); } else { clone.removeAttr('data-cols'); }
				if ( dataId!=='' ) { clone.attr('data-id',dataId); } else { clone.removeAttr('data-id'); }
				if ( dataClass!=='' ) { clone.attr('data-class',dataClass); } else { clone.removeAttr('data-class'); }
				if ( dataExtra!=='' ) { clone.attr('data-extra',dataExtra); } else { clone.removeAttr('data-extra'); }
				if ( dataRatio!=='' ) { clone.attr('data-stellar-background-ratio',dataRatio); } else { clone.removeAttr('data-stellar-background-ratio'); }
				if ( dataStyle!=='' ) { clone.attr('data-style',dataStyle); } else { clone.removeAttr('data-style'); }
				cloneOriginal.before(clone);
				clone.show();
			}

			jQuery('.pix_builder_column',t).each(function(){
				var cloneCol = jQuery('.pix_builder_column.pix_clone_column', clone).clone(),
					html = jQuery(this).html(),
					dataCol = parseFloat(jQuery(this).attr('data-col')),
					dataId = typeof jQuery(this).attr('data-id')!='undefined' ? jQuery(this).attr('data-id') : '',
					dataClass = typeof jQuery(this).attr('data-class')!='undefined' ? jQuery(this).attr('data-class') : '',
					dataSmall = typeof jQuery(this).attr('data-small')!='undefined' ? jQuery(this).attr('data-small') : '',
					dataMedium = typeof jQuery(this).attr('data-medium')!='undefined' ? jQuery(this).attr('data-medium') : '',
					dataStyle = typeof jQuery(this).attr('data-style')!='undefined' ? jQuery(this).attr('data-style') : '';
				cloneCol.hide().removeClass('pix_clone_column');
				if ( dataCol!=='' ) { cloneCol.attr('data-col',dataCol); } else { cloneCol.removeAttr('data-col'); }
				if ( dataId!=='' ) { cloneCol.attr('data-id',dataId); } else { cloneCol.removeAttr('data-id'); }
				if ( dataClass!=='' ) { cloneCol.attr('data-class',dataClass); } else { cloneCol.removeAttr('data-class'); }
				if ( dataSmall!=='' ) { cloneCol.attr('data-small',dataSmall); } else { cloneCol.removeAttr('data-small'); }
				if ( dataMedium!=='' ) { cloneCol.attr('data-medium',dataMedium); } else { cloneCol.removeAttr('data-medium'); }
				if ( dataStyle!=='' ) { cloneCol.attr('data-style',dataStyle); } else { cloneCol.removeAttr('data-style'); }
				jQuery('textarea',cloneCol).val(html);
				jQuery('.pix_builder_content',cloneCol).html(html);

				cloneCol.attr('data-col',dataCol).attr('data-id',dataId).attr('data-class',dataClass).show();
				jQuery('.pix_builder_column',clone).not('.pix_column_active').eq(0).before(cloneCol);
			});

			clone.find('textarea.pix_section_txt').val(idClass);

		});


		set = setTimeout( function(){
			jQuery('.pix_section_template').change();
		},10);
		sortColumns();
		checkEmptyColumns();
		expandColumns();
		removeColumns();
		getSelValue();
		addColumns();
		clearTimeout(set);
		jQuery('body').addClass('pixgridder_generated');

		var pix_editor_tab = localStorage.getItem("pix_editor_tab");
		if ( pix_editor_tab == 'pix_builder' ) {
			jQuery('#pix_builder_canvas').show();
		}

	}

}

/********************************
*
*   Sort sections
*
********************************/
function sortSections(){
	jQuery('#pix-builder-editor-container').sortable({
		handle: '.pix_section_mover',
		items: '.pix_section_builder_movable',
		placeholder: 'pix_section_builder_highlight',
		tolerance: 'pointer',
		stop: function( event, ui ) {
			setVisualContent();
		}
	});
}


/********************************
*
*   Sort columns
*
********************************/
function sortColumns(){
	jQuery('#pix_builder_canvas').sortable({
		handle: '.pix_column_mover',
		items: '.pix_builder_column',
		placeholder: 'pix_builder_column pix_column_builder_highlight',
		tolerance: 'pointer',
		connectWith: '.pix_section_body_wrap',
		start: function( event, ui ) {
			//jQuery('.pix_column_builder_highlight',this).width( ui.item.width() );
			//jQuery('#pix_builder_canvas, .pix_section_body').css({overflow:'visible'});
			setVisualContent();
		},
		sort: function( event, ui ) {
			var cols = ui.placeholder.parents('.pix_section_builder').eq(0).attr( 'data-cols' ),
				col = ui.item.attr( 'data-col' );
			if ( col > cols ) {
				col = cols;
			}
			ui.placeholder.attr( 'data-col', col );
			columnWidth();
		},
		stop: function( event, ui ) {
			setVisualContent();
			var panel = ui.item.parents('.pix_section_body_wrap').eq(0),
				clone = jQuery('.pix_clone_column',panel),
				add = jQuery('.pix_builder_column:has(.pix_add_column)',panel),
				cols = ui.item.parents('.pix_section_builder').eq(0).attr( 'data-cols' ),
				col = ui.item.attr( 'data-col' );
			if ( col > cols ) {
				ui.item.attr( 'data-col', cols );
			}
			columnWidth();
			clone.before(add);
		}
	});
}


/********************************
*
*   Check empty columns
*
********************************/
function checkEmptyColumns(){
	jQuery('.pix_section_body_wrap').each(function(){
		if(!jQuery('.pix_builder_column .pix_add_column.pix-ui',this).length){
			jQuery('.pix_builder_column',this).not('.pix_column_active').eq(0).append('<div class="pix_add_column pix-ui" style="display:none"><i class="pixgridder-icon-plus-1"></i></div>');
			jQuery('.pix_builder_column .pix_add_column',this).fadeIn(150);
		} else {
			jQuery('.pix_builder_column .pix_add_column',this).css({opacity:1});
		}
	});
}


/********************************
*
*   Add sections
*
********************************/
function addSections(){
	var clone;
	jQuery('#pix_builder_canvas').off('click','.pix_add_section');
	jQuery('#pix_builder_canvas').on('click','.pix_add_section',function(){
		cloneOriginal = jQuery('.pix_section_builder.pix_clone_section');
		clone = cloneOriginal.clone();
		clone.hide().removeClass('pix_clone_section');
		cloneOriginal.before(clone);
		clone.slideDown(400);
		addColumns();
		removeSections();
		setVisualContent();
		getSelValue();
	});
}


/********************************
*
*   Remove sections
*
********************************/
function removeSections(){
	jQuery(document).off('click','.pix_section_builder .pix_section_delete');
	jQuery(document).on('click','.pix_section_builder .pix_section_delete',function(){
		var t = jQuery(this).parents('.pix_section_builder').eq(0);
		t.slideUp(400,function(){
			t.remove();
			setVisualContent();
		});
	});
}


/********************************
*
*   Add columns
*
********************************/
function addColumns(){
	jQuery('.pix_section_body_wrap').each(function(){
		var t = jQuery(this),
			clone;
		t.off('click','.pix_add_column');
		t.on('click','.pix_add_column',function(){
			clone = jQuery('.pix_builder_column.pix_clone_column', t).clone();
			clone.hide().removeClass('pix_clone_column');
			clone.fadeIn();
			jQuery(this).parents('.pix_builder_column').before(clone)/*.remove()*/;
			sortColumns();
			checkEmptyColumns();
			expandColumns();
			removeColumns();
			setVisualContent();
		});
	});
}


/********************************
*
*   Add columns
*
********************************/
function removeColumns(){
	jQuery('.pix_builder_column').each(function(){
		var t = jQuery(this),
			parent = t.parents('.pix_section_body_wrap').eq(0),
			cols,
			i,
			setCol;
		t.off('click','.pix_column_delete');
		t.on('click','.pix_column_delete',function(){
			cols = parseFloat(t.attr('data-col')),
			i = 0;
			t.attr('data-col',0).fadeOut(400, function() {
				jQuery(this).remove();
				setVisualContent();
			});
		});
	});
}


/********************************
*
*   Expand columns
*
********************************/
function expandColumns(){
	jQuery('.pix_builder_column').each(function(){
		var t = jQuery(this),
			parent = t.parents('.pix_section_body_wrap').eq(0),
			clone,
			col,
			totCols,
			maxCols,
			setCol;
		t.off('click','.pix_column_increase');
		t.on('click','.pix_column_increase',function(){
			totCols = t.attr('data-col');
			maxCols = parseFloat(t.parents('.pix_section_builder').eq(0).attr('data-cols'));
			/*jQuery('.pix_builder_column.pix_column_active', parent).not('.pix_clone_column').each(function(){
				totCols = totCols + parseFloat(jQuery(this).attr('data-col'));
			});*/
			col = parseFloat(t.attr('data-col'));
			if ( totCols < maxCols ) {
				t.attr('data-col',(col+1));
				columnWidth();
				setVisualContent();
			} else {
				t.parents('.pix_section_builder').eq(0).find('.pix_section_error').fadeIn(400,function(){jQuery(this).delay(1500).fadeOut();});
			}
		});

		t.off('click','.pix_column_reduce');
		t.on('click','.pix_column_reduce',function(){
			col = parseFloat(t.attr('data-col'));
			if ( col > 1 ) {
				t.attr('data-col',(col-1));
			} else {
				t.parents('.pix_section_builder').eq(0).find('.pix_section_error').fadeIn(400,function(){jQuery(this).delay(1500).fadeOut();});
			}
			columnWidth();
			setVisualContent();
		});
	});
}


/********************************
*
*   Columns width
*
********************************/
function columnWidth(){
	jQuery('.pix_builder_column[data-col]').each(function(){
		var divid = parseFloat(jQuery(this).attr('data-col')),
			per = parseFloat(jQuery(this).parents('.pix_section_builder[data-cols]').eq(0).attr('data-cols'));
		jQuery(this).css({width:100*(divid/per)+'%'});
	});
}


/********************************
*
*   Color pickers
*
********************************/
function gridder_farbtastic(){
	if(jQuery.isFunction(jQuery.fn.farbtastic)) {
		jQuery(document).on('click','.pix-page-builder-id .pix_color_picker .pix_button',function(){
			var t = jQuery(this);
			t.siblings('.colorpicker, i').fadeIn(150);
			t.parents('.ui-dialog-content').eq(0).css({overflow:'visible'});

			t.siblings('i').on('click',function() {
				t.siblings('.colorpicker, i').fadeOut(150,function(){
					t.parents('.ui-dialog-content').eq(0).css({overflow:'auto'});
				});
			});
	
			return false;
		});

		jQuery('.pix-page-builder-id .pix_color_picker').each(function() {
			var divPicker = jQuery(this).find('.colorpicker'),
				inputPicker = jQuery(this).find('input[type=text]'),
				colorVal = inputPicker.val();
			var txtColor = pixgridder_checkDarkness(inputPicker.val()) ? '#000' : '#fff';
			inputPicker.css({backgroundColor:inputPicker.val(), color: txtColor});

			jQuery.farbtastic(divPicker, function(color){
				var txtColor = pixgridder_checkDarkness(color) ? '#000' : '#fff';
				inputPicker.val(color).css({backgroundColor:color, color: txtColor});
			}).setColor(colorVal);
			inputPicker.on('keyup',function(){
				colorVal = inputPicker.val();
				jQuery.farbtastic(divPicker).setColor(colorVal);
				inputPicker.css({backgroundColor:colorVal});
			});
		});
	}
}


/********************************
*
*   Sliders
*
********************************/
function gridder_sliders() {
	if(jQuery.isFunction(jQuery.fn.slider)) {
		jQuery('.pix-page-builder-id .slider_div').each(function(){
			var t = jQuery(this);
			var value = jQuery('input',t).val();
			if(t.hasClass('grid')){
				var mi = 0;
				var m = 300;
				var s = 1;
			} else if(t.hasClass('degrees')){
				var mi = -5;
				var m = 5;
				var s = .1;
			} else if(t.hasClass('opacity')){
				var mi = 0;
				var m = 1;
				var s = 0.05;
			} else {
				var mi = 1;
				var m = 20;
				var s = 1;
			}
			jQuery('.slider_cursor',t).slider({
				range: 'min',
				value: value,
				min: mi,
				max: m,
				step: s,
				slide: function( event, ui ) {
					var value = ui.value
					if ( value=='0' ) value = '';
					jQuery('input',t).val( value );
				}
			});
			jQuery('a',t).mousedown(function(event){
				t.addClass('active');
			});
			jQuery(document).mouseup(function(){
				t.removeClass('active');
			});
			jQuery('input',t).keyup(function(){
				var v = jQuery('input',t).val();
				jQuery('.slider_cursor',t).slider({
					range: 'min',
					value: v,
					min: 0,
					max: m,
					step: s,
					slide: function( event, ui ) {
						jQuery('input',t).val( ui.value );
					}
				});
			});
			jQuery('.slider_cursor',t).each(function(){
				if ( jQuery('.ui-slider-range-min',this).length > 1 ) {
					jQuery('.ui-slider-range-min',this).not(':last').remove();
				}
			});
		});
	}
}

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

	jQuery('.wp-dialog.pix-dialog .pix_upload.upload_image a, .wp-dialog.pix-dialog .pix_upload.upload_image span.img_preview').off('click');
	jQuery('.wp-dialog.pix-dialog .pix_upload.upload_image a, .wp-dialog.pix-dialog .pix_upload.upload_image span.img_preview').on('click', function( e ){
		e.preventDefault();
		var button = jQuery(this);

		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;

			jQuery.each(media_attachments, function(index, el) {
				//console.log(JSON.stringify(media_attachments));
				var url = this.url,
					id = this.id,
					size = typeof thumbSize!=='undefined' ? thumbSize : '';

				if ( size !== '' ) {
					size = this.sizes[size];
					url = size.url;
				}

				if ( typeof this.sizes != 'undefined' && typeof this.sizes.thumbnail != 'undefined' ) {
					previewUrl = this.sizes.thumbnail.url;
				} else {
					previewUrl = url;
				}
				button.parents('.pix_upload').eq(0).find('input').val(url);
				button.parents('.pix_upload').eq(0).find('.img_preview').addClass('filled').css({
					backgroundImage: 'url('+previewUrl+')'
				});
			});
		});

		pix_media_frame.open();
		jQuery('.media-menu a').eq(1).hide();
		jQuery('.attachment-display-settings .setting').remove();
		jQuery('.media-toolbar-secondary').hide();
	});

	jQuery('.wp-dialog.pix-dialog .img_preview').each(function(){
		var field = jQuery(this).siblings('input').val();
		if ( field!='' ) {
			jQuery(this).addClass('filled').css({
				backgroundImage: 'url('+field+')'
			});
		} else {
			jQuery(this).removeClass('filled').css({
				backgroundImage: ''
			});
		}
	});
}

/********************************
*
*   Autocomplete filter
*
********************************/
function pixGridderAutoComplete($field, availableTags, multiple, color){

	if ( availableTags.length ) {
		$field.attr('placeholder','Focus or \u2193 key for presets');
	}

	function split( val ) {
		return val.split( / \s*/ );
	}
	function extractLast( term ) {
		return split( term ).pop();
	}
	/*function array_diff( arr, bar ) {
		arr.forEach(function(key) {
			if (-1 === bar.indexOf(key)) {
				baz.push(key);
			}
		}, this);
		return bar;
	}*/

	$field
		.bind( "keydown", function( event ) {
			if ( event.keyCode === jQuery.ui.keyCode.TAB &&
					jQuery( this ).data( "ui-autocomplete" ).menu.active ) {
				event.preventDefault();
			}
		})
		.bind( "focus", function(){
			jQuery(this).trigger("keydown");
		})
		.autocomplete({
			minLength: 0,
			source: function( request, response ) {
				// delegate back to autocomplete, but extract the last term
				response( jQuery.ui.autocomplete.filter(
					availableTags, extractLast( request.term ) ) );
			},
			focus: function() {
				// prevent value inserted on focus
				if ( typeof multiple != 'undefined' && multiple === true )
					return false;
			},
			select: function( event, ui ) {
				if ( typeof multiple != 'undefined' && multiple === true ) {
					var terms = split( this.value );
					// remove the current input
					terms.pop();
					// add the selected item
					terms.push( ui.item.value );
					// add placeholder to get the comma-and-space at the end
					terms.push( "" );
					this.value = terms.join( " " );
					setTimeout( function(){
						$field.autocomplete( "search", "" ); }, 100);
					return false;
				}
			},
			open: function( event, ui ) {
				if ( typeof color != 'undefined' && color === true ) {
					var widget = jQuery(this).autocomplete('widget'),
						item = widget.find('a');
					item.each(function(){
						var hex = jQuery(this).text(),
							span = jQuery('<span />').css({background:hex,width:'16px',height:'16px',display:'block',float:'left',marginRight:'4px',verticalAlign:'text-bottom'});
						jQuery(this).prepend(span);
					});
				}
			}
		});
}


var pixGridderBuilderInit = function(){
	getSelValue();
	var set = setTimeout( function(){ jQuery('.pix_section_template').change(); },10);

	if ( pixgridder_display === true ) {
		pageBuilder();
		sortSections();
		sortColumns();
		checkEmptyColumns();
		addSections();
		removeSections();
		addColumns();
		setBuilderContent();
		columnWidth();
	}

	jQuery('#pix_builder_preview').resizable({ 
		handles: 'se',
		create: function( event, ui ) {
			var h = jQuery(this).height();
			jQuery('iframe',this).height(h);
		},
		stop: function( event, ui ) {
			var h = jQuery(this).height();
			jQuery('iframe',this).height(h);
			var data = {
				action: 'pixgridder_height_preview',
				height: h
			};
			jQuery.post(ajaxurl, data);
		}
	});
};