( ! ) Warning: file_get_contents(C:\wamp64\www\tico\wp-content\plugins\pagelayer\js/premium.js): failed to open stream: No such file or directory in C:\wamp64\www\tico\wp-content\plugins\pagelayer\js\givejs.php on line 99
( ! ) Warning: file_get_contents(C:\wamp64\www\tico\wp-content\plugins\pagelayer\js/trumbowyg.fontsize.min.js): failed to open stream: No such file or directory in C:\wamp64\www\tico\wp-content\plugins\pagelayer\js\givejs.php on line 99
( ! ) Warning: file_get_contents(C:\wamp64\www\tico\wp-content\plugins\pagelayer\js/premium-frontend.js): failed to open stream: No such file or directory in C:\wamp64\www\tico\wp-content\plugins\pagelayer\js\givejs.php on line 99
( ! ) Warning: Cannot modify header information - headers already sent by (output started at C:\wamp64\www\tico\wp-content\plugins\pagelayer\js\givejs.php:99) in C:\wamp64\www\tico\wp-content\plugins\pagelayer\js\givejs.php on line 117
( ! ) Warning: Cannot modify header information - headers already sent by (output started at C:\wamp64\www\tico\wp-content\plugins\pagelayer\js\givejs.php:99) in C:\wamp64\www\tico\wp-content\plugins\pagelayer\js\givejs.php on line 148
( ! ) Warning: Cannot modify header information - headers already sent by (output started at C:\wamp64\www\tico\wp-content\plugins\pagelayer\js\givejs.php:99) in C:\wamp64\www\tico\wp-content\plugins\pagelayer\js\givejs.php on line 161
/*
PAGELAYER
http://pagelayer.com/
(c) Pagelayer Team
*/
pagelayer = {
$: jQuery,
$$ : function(select){
return jQuery(select, window.parent.document);
},
gDocument : jQuery(window.parent.document).add(document),
p : this,
copy_selected: '',
mouse: {x: -1, y: -1},
history_action : true,
global_render : true,
history_lastTime : new Date(),
props_ref : {},
pro_txt : '',
loaded : 0,
post_status : '',
}
var pagelayer_history_obj = {}, pagelayer_revision_obj = {};
var pagelayer_add_section_data = {};
// Console error manager
window.onerror = function (msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "script error";
if(pagelayer.loaded > 0){
return;
}
if (string.indexOf(substring) > -1){
return;
}
if(url.indexOf('pagelayer')=== -1){
return;
}
var message = [
"Message: " + msg,
"\r\n URL: " + url,
"\r\n Line: " + lineNo,
"\r\n Column: "+ columnNo,
"\r\n Error object: " + error
].join('\n');
//alert("Script Error: See browser console for details");
pagelayer.$$('.pagelayer-errorBox-content').html(message);
pagelayer.$$('.pagelayer-errorBox-close').on('click', function(){
pagelayer.$$('.pagelayer-errorBox').fadeOut();
});
pagelayer.$$('.pagelayer-errorBox').fadeIn();
return false;
};
// Lets start
jQuery(document).ready(pagelayer_start);
// Function to load the codes
function pagelayer_start(){
pagelayer.loading = 1;
console.log('['+pagelayer_brand+'] Starting Pagelayer');
// Prevent the click Insite editor
pagelayer_prevent_click();
// Set the title of the parent window
try{ pagelayer.$$('head').append(pagelayer.$('title')[0].outerHTML); }catch(e){};
pagelayer.blank_img = pagelayer_url+'/images/default-image.png';
pagelayer_shortcodes['pl_inner_row'] = JSON.parse(JSON.stringify(pagelayer_shortcodes['pl_row']));
pagelayer_shortcodes['pl_inner_row']['name'] = 'Inner Row';
pagelayer_groups['grid'].push('pl_inner_row');
// Make the Topbar
pagelayer_bottombar();
// Make the Leftbar
pagelayer_leftbar();
// Add widget section
pagelayer_add_widget();
// Setup the ELPD
pagelayer_elpd_setup();
// Setup the properties of the elements
pagelayer_element_setup();
// An image to show for drag
jQuery('body').append('');
// Setup the grid drag
pagelayer_setup_drag();
// Set left bar draggable
pagelayer_make_leftbar_movable();
// Set to desktop
pagelayer_set_screen_mode('desktop');
// Create list of fonts
pagelayer_fonts = pagelayer_l('google_fonts_list');
// Set up right click
pagelayer_left_click();
pagelayer_right_click();
// Setup pagelayer history handle
pagelayer_history_obj['action_data'] = [];
pagelayer_history_setup(true);
// Make a quick access of the props
pagelayer_make_props_ref();
// Do any actions here
pagelayer_trigger_action('pagelayer_setup_history');
// Editor Tooltips
pagelayer_tooltip_setup();
// Load Fonts
for(var x in pagelayer_loaded_icons){
var item = pagelayer_loaded_icons[x];
jQuery.when(
pagelayer_get_stored_data(pagelayer_url+'/fonts/'+item+'.json', pagelayer_ver)
).then(function(){
pagelayer_icons[item] = JSON.parse(pagelayer_get_stored_data(pagelayer_url+'/fonts/'+item+'.json', pagelayer_ver));
});
};
// Set row-option top zero(0) of the first row
pagelayer_set_row_option_position();
// Just the txt
pagelayer.pro_txt = pagelayer_pro_txt;
// Hide the loader
pagelayer_loader_hide();
}
// Prevent the click Insite editor
function pagelayer_prevent_click(){
jQuery(document).on('submit', function(event){
var target = jQuery(event.target);
if (target.closest(pagelayer_editable).length < 1) {
event.preventDefault();
}
});
jQuery(document).on('click', function(event){
var target = jQuery(event.target);
if (target.closest('a').length > 0 && target.closest(pagelayer_editable).length < 1) {
event.preventDefault()
}
});
}
// Do pagelayer Dirty
function pagelayer_do_dirty(){
pagelayer_isDirty = true;
if (!window.onbeforeunload) {
window.onbeforeunload = function(){
return true;
};
}
}
function pagelayer_do_undirty(){
pagelayer_isDirty = false;
if (window.onbeforeunload) {
window.onbeforeunload = null;
}
}
// Executes when pagelayer is fully loaded
function pagelayer_loader_hide(){
var inner = pagelayer.$$('.pagelayer-percent');
inner.attr('loaded', 1);
var w = parseInt(inner.text());
var t = setInterval(function() {
w = w + 1;
inner.html(w +'%');
if (w >= 100){
clearInterval(t);
w = 0;
var loaderWrapper = pagelayer.$$('#pagelayer-loader-wrapper');
loaderWrapper.addClass('pagelayer-loaded');
loaderWrapper.animate({opacity:0}, function(){
loaderWrapper.remove();
});
}
}, 1);
pagelayer.loaded = 1;
}
// Set row-option top zero(0) of the first row
function pagelayer_set_row_option_position(){
try{
if(jQuery(pagelayer_editable).offset().top < 20){
jQuery(pagelayer_editable).addClass('pagelayer-row-option-zero');
}
}catch(e){
console.log(pagelayer_editable+" not found and hence Pagelayer wont work on this page !");
}
}
// The jQuery Object of the ELPD
var pagelayer_elpd;
// Store data values
function pagelayer_get_stored_data(url, version){
var name = 'pagelayer_'+url;
var data = {};
var force = false;
// Try to parse the data
try{
data = JSON.parse(localStorage.getItem(name));
if(data['version'] !== version){
force = true;
}
}catch(e){
force = true;
}
// Force download
if(force){
return jQuery.ajax({
url: url,
type: 'GET',
dataType: 'text',
success:function(newData){
var data = {};
data['version'] = version;
data['val'] = newData;
localStorage.setItem(name, JSON.stringify(data));
}
});
}
return data['val'];
}
function pagelayer_closest_corner(jEle){
var corners = [];
var w = jEle.outerWidth();
var h = jEle.outerHeight();
var topleft = jEle.offset();
// 0 - Top Left
corners.push(topleft);
// 1 - Top Right
corners.push({top: topleft.top, left: topleft.left+w});
// 2 - Bottom Right
corners.push({top: topleft.top+h, left: topleft.left+w});
// 3 - Bottom Left
corners.push({top: topleft.top+h, left: topleft.left});
//console.log(corners);
// Calculate the closest to the mouse
var distances = {};
for(var c in corners){
var dist = Math.hypot(pagelayer.mouse.x - corners[c].left, pagelayer.mouse.y - corners[c].top);
distances[c] = dist;
}
//console.log(distances);
var corner = Object.keys(distances).sort(function(a,b){return distances[a]-distances[b]})[0];
//console.log(corner);
return corner;
};
// Make left bar draggable
function pagelayer_make_leftbar_movable(){
var pl_iframe = pagelayer.$$('.pagelayer-iframe'),
pl_leftbar = pagelayer.$$('.pagelayer-leftbar-table');
// On mouse down in pagelayer-topbar-holder
pagelayer.$$('.pagelayer-topbar-mover').on('mousedown', function(e){
e = e || window.event;
e.preventDefault();
// Get leftbar position
var orig_eleX = pl_leftbar.offset().left;
var orig_eleY = pl_leftbar.offset().top;
// Get the mouse cursor position at startup:
var posX = e.clientX;
var posY = e.clientY;
// The variable needs to be empty.
var newMethod = '',
change = true;
var leftbar_mousemove = function(e){
e = e || window.event;
if(change){
// Add class to leftbar
pl_leftbar.addClass('pagelayer-leftbar-moving');
// Add left-right overlay
pl_iframe.before('');
pl_iframe.after('');
pagelayer.$$('body').addClass('pagelayer-overflow-hidden');
change = false;
}
// calculate the new cursor position and set the element left-top position
var top = orig_eleY + (e.clientY - posY);
var left = orig_eleX + (e.clientX - posX);
// set the element's new position:
pl_leftbar.css({'top': top +'px','left': left +'px'});
pagelayer.$$('.pagelayer-leftbar-toggle').hide();
// Make a copy of new method
var _newMethod = newMethod;
newMethod = '';
// Get near by corner
var offleft = pl_iframe.offset().left;
if(offleft + 100 > e.clientX){
newMethod = 'before';
}else if(offleft+pl_iframe.outerWidth()- 100 < e.clientX){
newMethod = 'after';
}
if(_newMethod != newMethod){
pagelayer.$$('.pagelayer-leftbar-move').css({'width' :'', 'opacity': '0.33'});
if(newMethod == 'after'){
pagelayer.$$('.pagelayer-moveto-right').animate({'width' :'60px', 'opacity': '0.66'}, 200);
pl_leftbar.addClass('pagelayer-rightbar');
}else if(newMethod == 'before'){
pagelayer.$$('.pagelayer-moveto-left').animate({'width' : '60px', 'opacity': '0.66'}, 200);
pl_leftbar.removeClass('pagelayer-rightbar');
}
}
};
var leftbar_mouseup = function(e){
// Remove events
pagelayer.gDocument.off('mousemove', leftbar_mousemove);
pagelayer.gDocument.off('mouseup', leftbar_mouseup);
// Remove class to leftbar
pagelayer.$$('.pagelayer-leftbar-move').remove();
var windowHeight = jQuery(window).height();
if(pl_leftbar.offset().top < 0){
pl_leftbar.css({'top': '10px'});
}else if( (windowHeight - e.clientY) < 10){
pl_leftbar.css({'top': ''+windowHeight - 40+'px'});
}
if( !pagelayer_empty(newMethod)){
pl_leftbar.removeClass('pagelayer-leftbar-moving');
pl_leftbar.removeAttr('style');
pagelayer.$$('.pagelayer-leftbar-toggle').show();
pagelayer.$$('body').removeClass('pagelayer-overflow-hidden');
pl_iframe[newMethod](pl_leftbar);
}
// make change true
change = true;
};
pagelayer.gDocument.on('mouseup', leftbar_mouseup);
pagelayer.gDocument.on('mousemove', leftbar_mousemove);
});
}
// Make rows and cols draggable
function pagelayer_setup_drag(){
// The object to show as drag
var shower = jQuery('.pagelayer-drag-show');
// Delete any prospect
var clear_prospect = function(){
jQuery('.pagelayer-drag-prospect').remove();
// Shows the wrap as active
jQuery('.pagelayer-drag-ele-hover').removeClass('pagelayer-drag-ele-hover');
}
// Reset the complete drag stuff
var reset_dragging = function(){
pagelayer.dragging = false;
pagelayer.drag_is_new = false;
pagelayer.drag_mouse = {x: 0, y: 0};
reset_on_drag();
}
// Reset the element on you were last
var reset_on_drag = function(){
pagelayer.drag_closest = false;
pagelayer.drag_closest_corner = null;
}
// Scroll by
var scrollPx = 7;
var scrollDist = 30;
// If we are too close too the window edge, then scroll
var handle_scroll = function(e){
var windowHeight = jQuery(window).height();
var windowWidth = jQuery(window).width();
// Are we to close to the top or bottom
if(e.clientY < scrollDist){
window.scrollBy(0, -scrollPx);
}else if((windowHeight - e.clientY) < scrollDist){
window.scrollBy(0, scrollPx);
}
// Are we to close to the top or bottom
if(e.clientX < scrollDist){
window.scrollBy(-scrollPx, 0);
}else if((windowWidth - e.clientX) < scrollDist){
window.scrollBy(scrollPx, 0);
}
}
// SET the values
reset_dragging();
var ondragover = function(e) {
//console.log(e);
pagelayer.mouse.x = parseInt(e.pageX);
pagelayer.mouse.y = parseInt(e.pageY);
//console.log(pagelayer.mouse);
// Are we dragging ?
if(pagelayer.dragging){
//console.log(e);
e.preventDefault();
//e.stopPropagation();
// The wrap of the element being dragged
var wrap = pagelayer.dragging;
// New addition
var is_new = pagelayer.drag_is_new;
var ele;
var tag = pagelayer_tag(wrap);
var id = pagelayer_id(wrap);
// If existing element then add we are dragging
if(!is_new){
// Start Dragging
if(!wrap.hasClass('pagelayer-is-dragging')){
wrap.addClass('pagelayer-is-dragging');
}
//shower.hide();
ele = document.elementFromPoint(e.clientX, e.clientY);
//console.log(ele);
// Drag the show object
//shower.show();
//var offset = {top: (e.pageY-10)+'px', left: (e.pageX-10)+'px'}
//shower.css(offset);
}else{
ele = document.elementFromPoint(e.clientX, e.clientY);
}
//console.log(e);
// Have we moved more than 5px;
var dist = Math.hypot(pagelayer.mouse.x - pagelayer.drag_mouse.x, pagelayer.mouse.y - pagelayer.drag_mouse.y);
//console.log(dist);
/*if(dist && dist < 5){
return false;
}*/
// Handle the scroll
handle_scroll(e);
// Find the closest wrap
var onWrap;
// If we are a column, we can be over another column or row
if(tag == 'pl_col'){
// Prevent column in inner-row and it's columns, if the draged column have inner-rows
if(wrap.find('.pagelayer-wrap-inner-row').length > 0){
onWrap = jQuery(ele).closest('.pagelayer-wrap-col,.pagelayer-wrap-row');
var innerRow = onWrap.closest(pagelayer_editable +' .pagelayer-wrap-inner-row');
if( onWrap.length < 1 || innerRow.length > 0){
onWrap = jQuery(innerRow).closest('.pagelayer-wrap-col,.pagelayer-wrap-row');
}
}else{
onWrap = jQuery(ele).closest('.pagelayer-wrap-col,.pagelayer-wrap-row,.pagelayer-wrap-inner-row');
}
//console.log(pagelayer_id(onWrap));
// If we are a row, we can be over another row or a column
}else if(tag == 'pl_row'){
onWrap = jQuery(ele).closest('.pagelayer-wrap-row');
//console.log(pagelayer_id(onWrap));
// For inner row we restrict to 1 level only
}else if(tag == 'pl_inner_row'){
var ele_wrap = jQuery(ele).parents('.pagelayer-wrap-col');
if(
(ele_wrap.length == 1 && !jQuery(ele).hasClass('pagelayer-wrap-col')) ||
(ele_wrap.length == 0 && jQuery(ele).hasClass('pagelayer-wrap-col'))
){
onWrap = jQuery(ele).closest('.pagelayer-wrap-ele,.pagelayer-wrap-col,.pagelayer-wrap-inner-row');
}else{
onWrap = jQuery(ele).closest('.pagelayer-wrap-inner-row');
}
// For every other element, we can be over a col or ele
}else{
onWrap = jQuery(ele).closest('.pagelayer-wrap-ele,.pagelayer-wrap-col,.pagelayer-wrap-inner-row');
// If we are inside the same widget tag
// We are allowing for now, hence the following is commented
/*var sameTag = onWrap.closest(pagelayer_editable +' [pagelayer-tag="'+tag+'"]');
if(sameTag.length > 0){
onWrap = sameTag.closest('.pagelayer-wrap-ele');
}*/
}
//console.log(onWrap);
// If we find nothing
if(pagelayer_empty(onWrap) || onWrap.length < 1){
clear_prospect();// Clear existing prospects
reset_on_drag();// Also reset the last on item
return false;
}
/*// If the columns more than 12 inside the row then return - As of now not enabled the below code
if(tag == 'pl_col'){
var _onTag = pagelayer_tag(onWrap);
var colEles;
// Is on col
if(_onTag == 'pl_col'){
colEles = onWrap.closest('.pagelayer-row-holder').children('.pagelayer-ele-wrap');
}else{
colEles = onWrap.find('.pagelayer-row-holder').first().children('.pagelayer-ele-wrap');
}
// If the columns more than 12
if(colEles.length >= 12){
return false;
}
}*/
// Get the ID
var onId = pagelayer_id(onWrap);
var onEle = pagelayer_ele_by_id(onId);
// Do we have a parent ?
var have_parent = function(Ele){
var pOnId = pagelayer_get_parent(Ele);
if(pagelayer_empty(pOnId) || tag == 'pl_col'){
return;
}
onId = pOnId;
onEle = pagelayer_ele_by_id(pOnId);
onWrap = pagelayer_wrap_by_id(pOnId);
have_parent(onEle);
}
// Do we have a parent ?
have_parent(onEle);
var changed = false;
// Was it the same ID like the one we were on before
if(pagelayer.drag_closest != onId){
pagelayer.drag_closest = onId;
changed = true;
}
//console.log(onId+' '+pagelayer.drag_closest)
var req_corners = {0: 'top', 1: 'top', 2: 'bottom', 3: 'bottom'};
// For columns we redefine the top and bottom
if(tag == 'pl_col'){
req_corners[1] = 'bottom';
req_corners[3] = 'top';
}
// Determine the previous and next
var next = wrap.next('.pagelayer-ele-wrap');
var prev = wrap.prev('.pagelayer-ele-wrap');
if(next.length == 1 && pagelayer_id(next) == onId){
req_corners = {0: 'bottom', 1: 'bottom', 2: 'bottom', 3: 'bottom'};
}
if(prev.length == 1 && pagelayer_id(prev) == onId){
req_corners = {0: 'top', 1: 'top', 2: 'top', 3: 'top'};
}
// Which corner are we closest to ?
var corner_num = pagelayer_closest_corner(onWrap);
var corner = req_corners[corner_num];
//console.log(corner+' != '+pagelayer.drag_closest_corner)
if(corner != pagelayer.drag_closest_corner){
pagelayer.drag_closest_corner = corner;
changed = true;
}
//console.log(changed);
// If we are on our self then clear return false
if(onId == id){
clear_prospect();// Clear existing prospects
reset_on_drag();// Also reset the last on item
return false;
}
// Then lets start showing
if(changed){
// Record the mouse points
pagelayer.drag_mouse.x = parseInt(e.pageX);
pagelayer.drag_mouse.y = parseInt(e.pageY);
// Clear any existing prospect
clear_prospect();
// Add new prospect
var prospect = '';
if(corner == 'bottom'){
onWrap.append(prospect);
}else if(corner == 'top'){
onWrap.prepend(prospect);
}
prospect = jQuery('.pagelayer-drag-prospect')
var animate_props = {height: '5px'};
// For column add a special class
if(tag == 'pl_col'){
prospect.addClass('pagelayer-drag-prospect-col');
animate_props['width'] = '5px';
// Adjust the left and right
var css = {};
css[(corner == 'bottom' ? 'right' : 'left')] = '0px';
prospect.css(css);
}
// Animate the prospect
prospect.animate(animate_props, 200);
// Highlight the wrap via overlay
onWrap.children('.pagelayer-ele-overlay').addClass('pagelayer-drag-ele-hover');
}
}
}
// When mouse is pressed down
var ondragstart = function(e){
//console.log(e);
// Target
var tEle = jQuery(e.target);
var wrap = tEle.closest('.pagelayer-ele-wrap');
//console.log(jEle[0]);
// Is it an existing element ?
if(wrap.length < 1){
return false;
}
// Do we have a parent ?
var id = pagelayer_id(wrap);
var jEle = pagelayer_ele_by_id(id);
var pId = pagelayer_get_parent(jEle);
if(pId){
wrap = pagelayer_wrap_by_id(pId);
}
//e.preventDefault();
var tag = pagelayer_tag(wrap);
e.originalEvent.dataTransfer.setData('Text', 1);
var img = document.createElement('img');
img.src = shower.attr('src');
e.originalEvent.dataTransfer.setDragImage(img, 32, 32);
pagelayer.dragging = wrap;
}
// When mouse is pressed down
var ondrop = function(e){
//console.log(e);
// Stop dragging ?
if(pagelayer.dragging){
e.preventDefault();
var wrap = pagelayer.dragging;
var tag = pagelayer_tag(wrap);
var gId = wrap.attr('pagelayer-global-id');
var fromEl = wrap.parent();
var id;
// Global ID is there for sure ?
if(pagelayer_empty(gId) || pagelayer_empty(pagelayer_global_widgets[gId])){
gId = 0;
}
wrap.removeClass('pagelayer-is-dragging');
// Find any prospect
var prospect = jQuery('.pagelayer-drag-prospect');
//console.log(prospect[0]);
// It should be exactly 1
if(prospect.length == 1){
var onWrap = prospect.parent();
var onId = pagelayer_id(onWrap);
var onTag = pagelayer_tag(onWrap);
var dropped;
var corner = prospect.attr('pagelayer-corner');
var method = (corner == 'top') ? 'before' : 'after';
var before_loc; // Location before the drop
// Create the element if it needs to be created
if(pagelayer.drag_is_new){
dropped = jQuery('');
// Is there a global ID
if(!pagelayer_empty(gId)){
dropped.attr('pagelayer-global-id', gId);
}
// Move the object
}else{
// Get near by element before move
before_loc = pagelayer_near_by_ele(pagelayer_id(wrap), tag);
dropped = wrap;
dropped.detach();
}
// If I am a column or row, then I go only before or after my same type !
if((onTag == 'pl_col' || onTag == 'pl_row') && onTag == tag){
// If I am a column and I am on a row
// OR I am a normal element and I am on column
}else if((tag == 'pl_col' && (onTag == 'pl_row' || onTag == 'pl_inner_row')) || onTag == 'pl_col'){
// We need to find the holder and add the prospect there
var holder = pagelayer_shortcodes[onTag]['holder'];
onWrap = onWrap.children('.pagelayer-ele').children(holder);
method = (corner == 'top') ? 'prepend' : 'append';
}
// Attach or shift the element
onWrap[method](dropped);
//console.log(dropped);
// Trigger the onadd
if(pagelayer.drag_is_new){
id = pagelayer_onadd(dropped);
// Create Column
if((tag == 'pl_row' || tag == 'pl_inner_row') && pagelayer_empty( dropped.attr('pagelayer-global-id') )){
var col = jQuery('');
jQuery('[pagelayer-id="'+id+'"]').find('.pagelayer-row-holder').append(col);
var col_id = pagelayer_onadd(col, false);
}
// Existing elements
}else{
id = pagelayer_id(wrap);
// Save in action history
pagelayer_history_action_push({
'title' : pagelayer_shortcodes[tag]['name'],
'action' : 'Moved',
'pl_id' : id,
'before_loc' : before_loc,
'after_loc' : {'method' : method, 'cEle' : onWrap}
});
pagelayer_do_dirty();
}
// Defining the variables as needed
var jEle = pagelayer_ele_by_id(id);
wrap = pagelayer_wrap_by_id(id);
var toEl = wrap.parent();
// Column number handle
if(tag == 'pl_col'){
var row_holder = jEle.parent().closest('.pagelayer-row-holder');
// Renumber the col where you are going
pagelayer_renumber_col(row_holder);
// Renumber the old columns as well
if(!pagelayer.drag_is_new){
var from_row = fromEl.closest('.pagelayer-row-holder');
pagelayer_renumber_col(from_row);
}
}
// Handle the empty col
if(tag != 'pl_col'){
pagelayer_empty_col(toEl.closest('.pagelayer-col-holder'));
if(!pagelayer.drag_is_new){
pagelayer_empty_col(fromEl.closest('.pagelayer-col-holder'));
}
}
}
// Clear prospect
clear_prospect();
}
reset_dragging();
}
// Add the events for inner content - as we are using the drag API
jQuery(document).on('dragstart', ondragstart);
jQuery(document).on('dragover', ondragover);
jQuery(document).on('drop', ondrop);
// For addition of new elements
pagelayer.$$('.pagelayer-leftbar').on('dragstart', function(e){
//console.log(e);
var tEle = jQuery(e.target);
var jEle = tEle.closest('.pagelayer-shortcode-drag');
var global_id = jEle.attr('pagelayer-global-id');
// Is it an existing element ?
if(jEle.length < 1){
return false;
}
e.originalEvent.dataTransfer.setData('tag', pagelayer_tag(jEle));
if(!pagelayer_empty(global_id)){
e.originalEvent.dataTransfer.setData( 'global_id', global_id );
}
pagelayer.dragging = jEle;
pagelayer.drag_is_new = true;
});
// Handle editable content by removing drag
var onmousedown = function(e){
var tEle = jQuery(e.originalEvent.explicitOriginalTarget);
if(tEle.closest('[pagelayer-editable]').length > 0){
//console.log('Is Editable MouseDown');
tEle.parents('[draggable]').attr('draggable', 'false');
}
}
// Handle editable content by adding drag that was removed
var onmouseup = function(e){
jQuery(document).find('[draggable=false]').attr('draggable', 'true');
}
// Handle editable contents by temprarily removing drag
jQuery(document).on('mousedown', onmousedown);
jQuery(document).on('mouseup', onmouseup);
};
// Handle empty col
// selector should be col holder
function pagelayer_empty_col(selector){
// Loop through
jQuery(selector).each(function(){
var jEle = jQuery(this);// jEle is the COL HOLDER
// Are we a col ?
if(!jEle.hasClass('pagelayer-col-holder')){
return;
}
// Column is becoming blank, so show add ele
if(jEle.children().length < 1){
//from.addClass('pagelayer-empty-col');
jEle.append('
Empty column please Drag Widgets
');
//var h = jEle.parent().parent().children('.pagelayer-ele-overlay').height();
//jEle.children('.pagelayer-add-ele').height(h);
jEle.find('>.pagelayer-add-ele .fa').unbind('click');
jEle.find('>.pagelayer-add-ele .fa').on('click', function(event){
event.stopPropagation();
pagelayer.$$('.pagelayer-elpd-close').click();
// Show left bar
pagelayer.$$('.pagelayer-leftbar-table').removeClass('pagelayer-leftbar-hidden pagelayer-leftbar-minimize');
});
// Any add ele sign with non-empty columns here ?
}else if(jEle.children('.pagelayer-add-ele').length > 0 && jEle.children().length > 1){
jEle.children('.pagelayer-add-ele').remove();
}
});
};
// Reset the column widths
// The selector should be a ROW HOLDER
function pagelayer_renumber_col(selector){
var pEle = jQuery(selector);
var children = pEle.children('.pagelayer-ele-wrap');
var cols = Math.floor(12 / (children.length));
var obj = {col: cols};
// Find out the number of cols of other cols
children.each(function(){
// This is the wrapper
var jEle = jQuery(this);
// The real element
var Ele = jEle.find('>.pagelayer-ele');
for(var x=1; x<=12; x++){
if(jEle.hasClass('pagelayer-col-'+x)){
jEle.removeClass('pagelayer-col-'+x);
Ele.removeClass('pagelayer-col-'+x);
break;
}
}
jEle.addClass('pagelayer-col-'+cols);
jEle.css({'width': ''});
// Set the att
pagelayer_set_atts(Ele, obj);
pagelayer_set_atts(Ele, 'col_width','');
pagelayer_sc_render(Ele)
});
}
// Make column resizable handler
function pagelayer_col_make_resizable(wrap){
// Resize handler element
var rHandler = jQuery('
');
var pResize = wrap.children('.pagelayer-ele-overlay').find('.pagelayer-resize-handler');
if(pResize.length > 0){
return;
}
// Append it
wrap.children('.pagelayer-ele-overlay').append(rHandler);
// Resize start
rHandler.on('mousedown', function(e) {
e.preventDefault();
var next_ele = wrap.next();
var rHolder_width = wrap.closest('.pagelayer-row-holder').width();
var new_width, nEle_new_width;
// Original width
var original_width = parseFloat(window.getComputedStyle(wrap[0]).getPropertyValue('width'));
var next_ele_width = parseFloat(window.getComputedStyle(next_ele[0]).getPropertyValue('width'));
var original_mouse_x = e.pageX;
var both_width = parseInt(original_width + next_ele_width);
// Add the element width and next element width
both_width = ((both_width / rHolder_width) *100);
if(both_width > 100){
return false;
}
jQuery('body').css({'cursor': 'ew-resize'});
rHandler.css({'display': 'block'});
var mousemoved = false;
var r_mousemove = function(e){
mousemoved = true;
var width = original_width + (e.pageX - original_mouse_x);
// Covert width in percentage
new_width = (width / rHolder_width *100).toFixed(2);
if(both_width > new_width && new_width > 0){
nEle_new_width = (both_width - new_width).toFixed(2);
wrap.css({'width': new_width+'%'});
next_ele.css({'width': nEle_new_width+'%'});
rHandler.attr({'pre-width': new_width+'%', 'next-width': nEle_new_width+'%'});
}
};
var r_mouseup = function(e){
jQuery(document).off('mousemove', r_mousemove);
jQuery(document).off('mouseup', r_mouseup);
jQuery('body').css({'cursor': ''});
rHandler.removeAttr('style pre-width next-width');
// IF mouseMoved
if(!mousemoved) return;
// find real element and next real element
var jEle = wrap.find('>.pagelayer-ele');
var nEle = next_ele.find('>.pagelayer-ele');
var mode = pagelayer_get_screen_mode();
var col_width = 'col_width';
// Do we have screen ?
if(mode != 'desktop'){
col_width = col_width +'_'+mode;
}
// Set the element attrs
pagelayer_set_atts(jEle, col_width, new_width);
pagelayer_set_atts(jEle, 'col', '');
pagelayer_set_atts(nEle, col_width, nEle_new_width);
pagelayer_set_atts(nEle, 'col', '');
};
// Resize start
jQuery(document).on('mousemove', r_mousemove);
jQuery(document).on('mouseup', r_mouseup);
});
}
// Handle addition of elements from the left
// NOTE : At this point the addition is FINALIZED
// The add element cannot be prevented !
function pagelayer_onadd(jEle, toClick){
toClick = arguments.length == 2 ? toClick : true;
//console.log(jEle);
var id = pagelayer_element_added(jEle);
var jEle = jQuery("[pagelayer-id="+id+"]");
if(toClick){
//console.log('here');
jEle.click();
}
return id;
};
// Add an element into the POST
function pagelayer_element_added(jEle){
var sc = jEle.attr('pagelayer-tag');
var id, par_id;
var gId = jEle.attr('pagelayer-global-id');
gId = gId && !pagelayer_empty(pagelayer_global_widgets[gId]) ? gId : 0;
// Set Pagelayer History FALSE to prevent saving attributes in action history
pagelayer.history_action = false;
pagelayer.global_render = false;
// Is this a global widget ?
if(!pagelayer_empty(gId)){
html = pagelayer_element_unsetup(pagelayer_global_widgets[gId].$);
html.attr('pagelayer-a-global_id', gId);
// Generate the HTML
}else{
html = pagelayer_create_sc(sc);
}
id = pagelayer_assign_id(html);
par_id = id;
// Insert the HTML
jEle[0].outerHTML = html[0].outerHTML;
// Setup the properties of the elements
pagelayer_element_setup("[pagelayer-id="+par_id+"], [pagelayer-id="+par_id+"] .pagelayer-ele", true);
// Any children to add ?
if(!('widget' in pagelayer_shortcodes[sc])){
// The element props
var props = pagelayer_shortcodes[sc];
// Do we have to create children ?
if('has_group' in props){
// Is this not a global widget ?
if(pagelayer_empty(gId)){
var has_group = props['has_group'];
var gProp = props[has_group['section']][has_group['prop']];
for(var i=0; i < gProp['count']; i++){
var cid = pagelayer_element_add_child(jQuery("[pagelayer-id="+id+"]"), gProp['sc']);
//pagelayer_element_setup('[pagelayer-id='+cid+']', true);
}
}else{
pagelayer_sc_render(jQuery('[pagelayer-id="'+par_id+'"]'));
}
}
}
// Save in action history
var cEle = pagelayer_near_by_ele(id, sc);
pagelayer_history_action_push({
'title' : pagelayer_shortcodes[sc]['name'],
'action' : 'Added',
'pl_id' : id,
'html' : jQuery("[pagelayer-id="+id+"]"),
'cEle' : cEle
});
// Set pagelayer history TRUE
pagelayer.history_action = true;
pagelayer.global_render = true;
return id;
};
// Add an element
function pagelayer_element_add_child(pEle, sc){
var child = pagelayer_create_sc(sc);
var cid = pagelayer_assign_id(child);
pagelayer_set_parent(child, pagelayer_assign_id(pEle));
// Does the parent have a holder ?
var tag = pagelayer_tag(pEle);
// There is a holder
if('holder' in pagelayer_shortcodes[tag]){
pEle.find(pagelayer_shortcodes[tag]['holder']).append(child);
// No holder, just append
}else{
pEle.append(child);
}
pagelayer_element_setup('[pagelayer-id='+cid+']', true);
// Certain element have editable areas which are inner rows. For UX we need to add columns for the users
if(sc == 'pl_inner_row'){
var col = jQuery('');
jQuery('[pagelayer-id="'+id+'"]').find('.pagelayer-row-holder').append(col);
cid = pagelayer_onadd(col, false);
}
// Do we have to create children ?
if('has_group' in pagelayer_shortcodes[sc]){
var has_group = pagelayer_shortcodes[sc]['has_group'];
var gProp = pagelayer_shortcodes[sc][has_group['section']][has_group['prop']];
for(var i=0; i < gProp['count']; i++){
var in_cid = pagelayer_element_add_child(jQuery("[pagelayer-id="+cid+"]"), gProp['sc']);
}
}
return cid;
};
// Return an element by ID
function pagelayer_ele_by_id(id){
return jQuery('[pagelayer-id='+id+']');
};
// Return the wrap by ID
function pagelayer_wrap_by_id(id){
return jQuery('[pagelayer-wrap-id='+id+']');
};
// Give the Pagelayer ID
function pagelayer_id(jEle){
var id = jEle.attr('pagelayer-wrap-id');
if(id){
return id;
}
id = jEle.attr('pagelayer-id');
return id;
}
// Assign the jQuery object an ID
function pagelayer_assign_id(jEle){
// Do you have the pagelayer id
var id = jEle.attr("pagelayer-id");
if(!id || id.length < 1){
id = pagelayer_randstr(16);
jEle.attr("pagelayer-id", id);
}
return id;
}
// Show the edit options
function pagelayer_element_clicked(selector, e){
var jEle = jQuery(selector);
e = e || false;
//console.log(e);
// You must be a element atleast
if(!jEle.hasClass('pagelayer-ele')){
return false;
}
// Get the parent
var pId = pagelayer_get_parent(jEle);
// If we found a parent
if(pId){
jEle = pagelayer_ele_by_id(pId);
}
// Make the editable fields active
//pagelayer_clear_editable();// First clear
jEle.find('[pagelayer-editable]').each(function (){
pagelayer_make_editable(jQuery(this), e);
});
// Show left bar
pagelayer.$$('.pagelayer-leftbar-table').removeClass('pagelayer-leftbar-hidden pagelayer-leftbar-minimize');
// Lets not rebuild everything to make it faster
if(pagelayer_is_active(jEle)){
return false;
}
// Set this as the active element
pagelayer_set_active(jEle);
// Show the properties
pagelayer_elpd_open(jEle);
}
// The edit option
function pagelayer_edit_element(selector){
pagelayer_element_clicked(selector);
}
// Setup the properties on a single click
function pagelayer_element_setup(selector, render){
var selector = selector || ".pagelayer-ele";
render = render || false;
// Loop through
jQuery(pagelayer_editable+' '+selector).each(function(){
var jEle = jQuery(this);
// Assign an ID if not there
var id = pagelayer_assign_id(jEle);
var pId = pagelayer_get_parent(jEle) || '';// Options to show on hover
var selector = '[pagelayer-id='+id+']';
if(render){
pagelayer_sc_render(jEle);
}
// Get the tag
var tag = pagelayer_tag(jEle);
// Lets check if we are the child of a parent i.e. element of a group
if(pagelayer_empty(pId)){
// Get the parent
var pEle = jEle.parent().closest('.pagelayer-ele');
// If we found a parent
if(pEle.length > 0){
var pTag = pagelayer_tag(pEle);
// Is the parent a group of this child ?
if(!pagelayer_empty(pagelayer_shortcodes[pTag]) && pagelayer_is_group(pTag)){
var has_group = pagelayer_shortcodes[pTag]['has_group'];
var child_type = pagelayer_shortcodes[pTag][has_group['section']][has_group['prop']]['sc'];
// If the type is the same as jEle
if(child_type == pagelayer_tag(jEle)){
pId = pagelayer_assign_id(pEle);
pagelayer_set_parent(jEle, pId);
}
}
}
}
// Make the wraps
jEle.wrap('');
var wrap = jEle.parent();
// For column we have to do some kidas !
if(tag == 'pl_col'){
var col;
for(var x=1; x<=12; x++){
if(jEle.hasClass('pagelayer-col-'+x)){
col = 'pagelayer-col-'+x;
break;
}
}
wrap.addClass('pagelayer-col '+col);
//jEle.removeClass('pagelayer-col '+col);
wrap.addClass('pagelayer-wrap-col');
}else if(tag == 'pl_row'){
wrap.addClass('pagelayer-wrap-row');
}else if(tag == 'pl_inner_row'){
wrap.addClass('pagelayer-wrap-inner-row');
}else{
wrap.addClass('pagelayer-wrap-ele');
}
// Create the overlay
wrap.prepend('');
var overlay = wrap.children('.pagelayer-ele-overlay');
var html;
if(tag == 'pl_row' || tag == 'pl_inner_row'){
overlay.addClass('pagelayer-row-hover');
if(jEle.hasClass('pagelayer-row-stretch-full')){
pagelayer_sc_render(jEle);
}
html = '
'+
''+
''+
''+
'
';
}else if(tag == 'pl_col'){
overlay.addClass('pagelayer-col-hover');
html = '
'+
''+
'
';
// Is it an empty col ?
pagelayer_empty_col(jEle.children('.pagelayer-col-holder'));
// Make col resizable
pagelayer_col_make_resizable(wrap);
}else{
html = '
'+
''+
''+
''+
'
';
}
// Append to the child
overlay.append(html);
jQuery('[pagelayer-option-id='+id+']').hide();
// Setup the HOVER events ABD create WRAPS IF we dont have a parent
if(pId.length > 0){
return;
}
// Make the wrap draggable, but only of independent or parent elements
wrap.attr('draggable', 'true');
wrap.hover(function(){
// Is there an element option shower ?
var opts = jQuery('[pagelayer-option-id='+id+']');
// Give the overlay the hover class
opts.parent().addClass('pagelayer-ele-hover');
// Show them
opts.show();
}, function(){
// Is there an element option shower ?
var opts = jQuery('[pagelayer-option-id='+id+']');
// Remove hover class
opts.parent().removeClass('pagelayer-ele-hover');
// Hide opts
opts.hide();
});
});
}
// Unsetup element for restup
function pagelayer_element_unsetup(selector, id){
id = id || false;
var src = jQuery(selector);
var html = src[0].outerHTML;
var jEle = jQuery(html);
jEle.removeAttr('pagelayer-id');
jEle.find('[pagelayer-id]').removeAttr('pagelayer-id');
jEle.find('[pagelayer-parent]').removeAttr('pagelayer-parent');// Remove the parent attribute as it will be reset during pagelayer_element_setup
jEle.find('style').remove();
jEle.find('.pagelayer-ele-overlay').remove();
// Unwrap the wraps
jEle.find('.pagelayer-ele').each(function (){
var ele = jQuery(this);
if(ele.parent().is('.pagelayer-ele-wrap')){
ele.unwrap();
}
});
// Assign id
if(id){
jEle.attr('pagelayer-id', id);
}
return jEle;
}
// Left Click
function pagelayer_left_click(){
jQuery(pagelayer_editable).on('click', function(e){
e.preventDefault();// Added by Jivan in Actions / Revisions version
// Hide the context menu
jQuery('.pagelayer-right-click-options').hide();
// Target
var tEle = jQuery(e.target);
// If its an edit option click
if(tEle.hasClass('pagelayer-eoi')){
return false;
}
pagelayer_element_clicked(tEle.closest('.pagelayer-ele'), e);
return false;
});
};
// Right Click Menu
function pagelayer_right_click(){
var html = '
';
jQuery('body').append(html);
var $contextMenu = jQuery('.pagelayer-right-click-options');
jQuery(pagelayer_editable).on('contextmenu', function(e){
var tEle = jQuery(e.target);
var jEle = tEle.closest('.pagelayer-ele-wrap').children('.pagelayer-ele');
// Get the parent
var pId = pagelayer_get_parent(jEle);
// If we found a parent
if(pId){
jEle = pagelayer_ele_by_id(pId);
}
// The basics
var id = pagelayer_assign_id(jEle);
var tag = pagelayer_tag(jEle);
$contextMenu.find('.pagelayer-right-edit').attr('onclick', 'pagelayer_edit_element("[pagelayer-id='+id+']")').html(' Edit '+pagelayer_shortcodes[tag]['name']);
$contextMenu.find('.pagelayer-right-duplicate').attr('onclick', 'pagelayer_copy_element("[pagelayer-id='+id+']")');
$contextMenu.find('.pagelayer-right-copy').attr('onclick', 'pagelayer_copy_select("[pagelayer-id='+id+']")');
$contextMenu.find('.pagelayer-right-paste').attr('onclick', 'pagelayer_paste_element("[pagelayer-id='+id+']")');
$contextMenu.find('.pagelayer-right-delete').attr('onclick', 'pagelayer_delete_element("[pagelayer-id='+id+']")');
// If is pagelayer pro
if(!pagelayer_empty(pagelayer_pro)){
$contextMenu.find('.pagelayer-right-save-global-widget').attr('onclick', 'pagelayer_save_sections("[pagelayer-id='+id+']", "global_widget")');
$contextMenu.find('.pagelayer-right-save-section').attr('onclick', 'pagelayer_save_sections("[pagelayer-id='+id+']", "section")');
$contextMenu.find('.pagelayer-right-save-global-section').attr('onclick', 'pagelayer_save_sections("[pagelayer-id='+id+']", "global_section")');
}else{
var pro = $contextMenu.find('[pro="1"]');
if(pro.find('.pagelayer-pro-req').length < 1){
pro.append('Pro');
}
pro.css({'color': '#a7a7a7'});
// To stopPropagation
pro.parent().on('click', function(e){
e.stopPropagation();
});
}
// If copy_selected is empty then copy data from localStorage
if(pagelayer_empty(pagelayer.copy_selected)){
pagelayer_copy_from_localStorage();
}
// Are we to hide the paste ?
if(!pagelayer_empty(pagelayer.copy_selected) && pagelayer_can_copy_to(jEle)){
//console.log(pagelayer_can_copy_to(jEle));
$contextMenu.find('.pagelayer-right-paste').parent().show();
}else{
$contextMenu.find('.pagelayer-right-paste').parent().hide();
}
var gId = jEle.attr("pagelayer-a-global_id");
// Are we to hide the global widget ?
if(!pagelayer_empty(gId) || tag == 'pl_row' || tag == 'pl_inner_row'|| tag == 'pl_col'){
$contextMenu.find('.pagelayer-right-save-global-widget').parent().hide();
}else{
$contextMenu.find('.pagelayer-right-save-global-widget').parent().show();
}
var sId = jEle.attr("pagelayer-a-global-section-id");
// Are we to hide the save as global section ?
if( tag == 'pl_row' && pagelayer_empty(sId)){
$contextMenu.find('.pagelayer-right-save-global-section').parent().show();
}else{
$contextMenu.find('.pagelayer-right-save-global-section').parent().hide();
}
// Are we to hide the save as section ?
if( tag == 'pl_row' ){
$contextMenu.find('.pagelayer-right-save-section').parent().show();
}else{
$contextMenu.find('.pagelayer-right-save-section').parent().hide();
}
$contextMenu.css({
display: "block",
left: e.pageX,
top: e.pageY
});
return false;
});
jQuery('html').on('click', function(e){
$contextMenu.hide();
});
}
// Set the parent for the group
function pagelayer_set_parent(jEle, id){
jEle.attr('pagelayer-parent', id);
};
// Set the parent for the group
function pagelayer_get_parent(jEle){
return jEle.attr('pagelayer-parent');
};
// Sets the screen mode
function pagelayer_set_screen_mode(mode){
var modes = ['desktop', 'tablet', 'mobile'];
var body = pagelayer.$$('.pagelayer-iframe-holder iframe');
var current = '';
for(var x in modes){
if(body.hasClass('pagelayer-screen-'+modes[x]) && modes[x] != mode){
current = modes[x];
body.removeClass('pagelayer-screen-'+modes[x]);
}
}
// Add the class
body.addClass('pagelayer-screen-'+mode);
// Add the class to the button
pagelayer.$$('.pagelayer-mode-button').removeClass('pli-'+current).addClass('pli-'+mode);
// Add the class to the button
pagelayer.$$('.pagelayer-prop-screen').removeClass('pli-'+current).addClass('pli-'+mode);
// Trigger screen change if any
pagelayer.$$('.pagelayer-elp-screen').trigger('pagelayer-screen-changed');
};
// Get the current screen mode
function pagelayer_get_screen_mode(){
var modes = ['desktop', 'tablet', 'mobile'];
var body = pagelayer.$$('.pagelayer-iframe-holder iframe');
for(var x in modes){
if(body.hasClass('pagelayer-screen-'+modes[x])){
return modes[x];
}
}
}
// Handle key press events
pagelayer.gDocument.keydown(function(event){
//alert(String.fromCharCode(event.which));
var tEle = jQuery(event.target);
// ctrl+s handle
if(event.keyCode == 83 && event.ctrlKey){
event.preventDefault();
pagelayer.$$('.pagelayer-bottombar-holder').find('.pagelayer-update-button').click();
}
// Is this in the editable area ?
if (tEle.is('input, textarea') || tEle.closest('[contenteditable]').length > 0) {
return;
}
// Delete
if(event.keyCode == 46){
pagelayer_delete_element('[pagelayer-active]');
}
// ctrl+z handle
if(event.keyCode == 90 && event.ctrlKey){
pagelayer_do_history('undo');
}
// ctrl+y handle
if(event.keyCode == 89 && event.ctrlKey){
pagelayer_do_history('redo');
}
// ctrl+d handle
if(event.keyCode == 68 && event.ctrlKey){
// If we have an active element
if( pagelayer_active.el && pagelayer_active.el.id ){
event.preventDefault();
pagelayer_copy_element('[pagelayer-id='+pagelayer_active.el.id+']');
}
}
});
// Handle Copy of content
jQuery(document).on('copy', function(copyEvent){
// Is Selected string?
var selectedText = "";
if (window.getSelection){ // all modern browsers and IE9+
selectedText = window.getSelection().toString();
}
if(selectedText.length > 0){
return;
}
if(pagelayer_active.el && pagelayer_active.el.id){
// Do empty clipbord data
(copyEvent.originalEvent || copyEvent).clipboardData.setData('text/plain', '');
copyEvent.preventDefault();
// Save the active element id
pagelayer_copy_select("[pagelayer-id='"+pagelayer_active.el.id+"']");
}
});
// Handle Paste in the editor
jQuery(document).on('paste', function(pasteEvent){
var pEle_target = jQuery((pasteEvent.originalEvent || pasteEvent).target);
var tag = pagelayer_tag(pEle_target.closest('[pagelayer-id]'));
var clipboardData = (pasteEvent.originalEvent || pasteEvent).clipboardData;
var items = clipboardData.items;
var pagelayer_ajax_func = {};
var contenteditable = false;
var pasteWidget = false;
if( !pagelayer_empty(tag) && tag == 'pl_text' && (pEle_target.closest('[contenteditable]').length > 0 || pEle_target.is('input, textarea')) ){
pEle_target = pEle_target.closest('[contenteditable]');
contenteditable = true;
}
if( items.length < 1 || (items.length == 1 && pagelayer_empty(clipboardData.getData(items[0].type))) ){
pasteWidget = true;
}
// This function for ajax before send call back
pagelayer_ajax_func['beforeSend'] = function(xhr){
// If target is not content editable
if( pagelayer_empty(contenteditable) ){
// If we dont have an active element then return false and stop ajax
if( !(pagelayer_active.el && pagelayer_active.el.id) ){
pagelayer_show_msg(pagelayer_l('active_ele_paste_msg'));
return false;
}
pagelayer.copy_selected = jQuery('');
// Is it to be pastable
if(!pagelayer_can_copy_to('[pagelayer-id="'+pagelayer_active.el.id+'"]')){
pagelayer.copy_selected = '';
return false;
}
}
pEle_target.css({'opacity': '0.33' , 'transition' : '0.1s'});
}
// This function for ajax success call back
pagelayer_ajax_func['success'] = function(obj){
// Successfully Uploaded
if(obj['success']){
// For content editable e.g. Rich Text
if( !pagelayer_empty(contenteditable) ){
document.execCommand('insertImage', false, obj['data']['url']);
// For our widgets
}else{
if(pagelayer_empty(pagelayer_active.el) || pagelayer_empty(pagelayer_active.el.id)){
pagelayer_show_msg('active_ele_paste_msg');
return;
}
var fTo = pagelayer_can_copy_to('[pagelayer-id="'+pagelayer_active.el.id+'"]');
// We need to empty pagelayer.copy_selected
pagelayer.copy_selected = '';
var pasteAfter = function(){
// Prevent to add action history
pagelayer.history_action = false;
// Create image html
var html = pagelayer_create_sc('pl_image');
pagelayer_set_atts(html, 'id', obj['data']['id']);
pagelayer_set_tmp_atts(html, 'id-url', obj['data']['url']);
// Allow to add action history
pagelayer.history_action = true;
// Copy the element
var id = pagelayer_copy_element(html, fTo);
jQuery('[pagelayer-id="'+id+'"]').click();
};
var replaceURL = function(){
// Finding widget image setting using id of jEle. Finding image editor setting from all of the other settings.
var row = pagelayer.$$('[pagelayer-element-id='+pagelayer_active.el.id+']').find('.pagelayer-elp-image').eq(0).parent().parent();
row.find('.pagelayer-elp-image').css('background-image', 'url(\''+obj['data']['url']+'\')');
// To remove past temp attr so that they are not involve in future temp values
_pagelayer_clear_tmp_atts(row);
for(var x in obj['data']['sizes']){
_pagelayer_set_tmp_atts(row, x+'-url', obj['data']['sizes'][x]['url']);
}
// Save and render
_pagelayer_set_tmp_atts(row, 'url', obj['data']['url']);
_pagelayer_set_atts(row, obj['data']['id']);
};
// Image paste confirmation.
if(!pagelayer_empty(pagelayer_active.el.tag) && pagelayer_active.el.tag == 'pl_image'){
pagelayer_confirmation_box(pagelayer_l('img_paste_conf'), replaceURL, pasteAfter, pagelayer_l('replace_img'), pagelayer_l('paste_after'));
}else{
pasteAfter();
}
}
// Some error occured
}else{
alert(obj['data']['message']);
}
}
// This function for ajax complete call back
pagelayer_ajax_func['complete'] = function(xhr){
//console.log(xhr);
pEle_target.css({'opacity': '1' , 'transition' : '0.1s'});
}
var findImg = pagelayer_editable_paste_handler(pasteEvent, pagelayer_ajax_func);
if(pagelayer_empty(findImg) && pagelayer_empty(contenteditable) || pasteWidget){
// Check the active element
if(pagelayer_active.el && pagelayer_active.el.id){
var jEle = jQuery("[pagelayer-id='"+pagelayer_active.el.id+"']");
// Check if the any element is copied
pagelayer_paste_element("[pagelayer-id='"+pagelayer_active.el.id+"']");
}else{
pagelayer_show_msg(pagelayer_l('no_active_ele_paste'));
}
}
});
// Delete an element as per the selector
function pagelayer_delete_element(selector){
var jEle = jQuery(selector);
// Anything found ?
if(jEle.length > 0){
var id = pagelayer_assign_id(jEle);
var sc = pagelayer_tag(jEle);
// Is there a wrap
var wrap = jQuery('[pagelayer-wrap-id="'+id+'"]');
var par = wrap.parent();
// Save this element in history action
if(pagelayer.history_action){
var cEle = pagelayer_near_by_ele(id, sc);
// To save in history, we need to save only element not the wraps as we call setup if we redo or undo
jEle.find('style').remove();
jEle.find('.pagelayer-ele-overlay').remove();
// Unwrap the wraps
jEle.find('.pagelayer-ele').each(function (){
var ele = jQuery(this);
if(ele.parent().is('.pagelayer-ele-wrap')){
ele.unwrap();
}
});
pagelayer_history_action_push({
'title' : pagelayer_shortcodes[sc]['name'],
'action' : 'Deleted',
'pl_id' : id,
'html' : jEle,
'cEle' : cEle
});
}
wrap.remove();
pagelayer_empty_col(par);
if( (pagelayer_active.el && pagelayer_active.el.id == id) ||
(pagelayer_active.el && pagelayer_active.el.id && jQuery('[pagelayer-id="'+pagelayer_active.el.id+'"]').length < 1)){
pagelayer.$$('.pagelayer-elpd-close').click();
}
}
pagelayer_do_dirty();
};
// Select an element
function pagelayer_copy_select(selector){
var eHtml = jQuery(selector)[0].outerHTML;
// Copy data on localStorage
localStorage.setItem("pagelayer_ele", eHtml);
pagelayer.copy_selected = selector;
pagelayer_show_msg( pagelayer_l('copied_msg'));
}
function pagelayer_can_copy_to(to){
var jEle = jQuery(pagelayer.copy_selected);
var tEle = jQuery(to);
var eTag = pagelayer_tag(jEle);
var tTag = pagelayer_tag(tEle);
//console.log(eTag+' - '+tTag);
// Final to
var fTo;
// Selected element is a Row, can go only after a row
if(eTag == 'pl_row'){
fTo = tEle.closest('.pagelayer-ele.pagelayer-row');
if(fTo.length != 1) return false;
return fTo;
}
// Selected element is a Column, can go only after a col
if(eTag == 'pl_col'){
fTo = tEle.closest('.pagelayer-ele.pagelayer-col');
if(fTo.length != 1) return false;
return fTo;
}
// Is the TARGET a row or column when the selected item is a element
if(tTag == 'pl_row' || tTag == 'pl_col'){
return false;
}
return tEle;
}
// Select an element
function pagelayer_paste_element(to){
// Copy data from localStorage
pagelayer_copy_from_localStorage();
var fTo = pagelayer_can_copy_to(to);
// Is it a valid to
if(!fTo){
return false;
}
if(!pagelayer_empty(pagelayer.copy_selected)){
pagelayer_copy_element(pagelayer.copy_selected, fTo);
return true;
}
pagelayer_show_msg(pagelayer_l('no_copied'));
return false;
}
// If copy_selected is empty then copy data from localStorage
function pagelayer_copy_from_localStorage(){
if(!pagelayer_empty(localStorage.getItem("pagelayer_ele"))){
// Set copy data from localStorage
pagelayer.copy_selected = localStorage.getItem("pagelayer_ele");
}
}
// Copy an element
// Note : insertAfter should always be an pagelayer-ele
function pagelayer_copy_element(selector, insertAfter){
var src = jQuery(selector);
var tag = pagelayer_tag(src);
insertAfter = insertAfter || src;
insertAfter = insertAfter.parent();
var jEle = pagelayer_element_unsetup(src);
// Give it an ID
var id = pagelayer_assign_id(jEle);
jQuery(insertAfter).after(jEle);
pagelayer_element_setup('[pagelayer-id='+id+'], [pagelayer-id='+id+'] .pagelayer-ele', true);
if(pagelayer_is_group(tag)){
pagelayer_sc_render(jEle);
}
// Save this element in history action
if(pagelayer.history_action){
var cEle = pagelayer_near_by_ele(id, tag);
pagelayer_history_action_push({
'title' : pagelayer_shortcodes[tag]['name'],
'action' : 'Copied',
'pl_id' : id,
'html' : jEle,
'cEle' : cEle
});
}
//If column then renumber columns
if(tag == 'pl_col'){
var row = src.parent().closest('.pagelayer-row');
pagelayer_renumber_col(row);
}
pagelayer_do_dirty();
return id;
};
// Save sections as template
function pagelayer_ajax_save_template(data, ajax_call_back = ''){
if(pagelayer_empty(data)){
return;
}
//save global sections and widgets
jQuery.ajax({
type: "POST",
url: pagelayer_ajax_url+'&action=pagelayer_save_templ_content&postID='+pagelayer_postID,
data: {
pagelayer_nonce: pagelayer_ajax_nonce,
global_widgets : data
},
success: function(response, status, xhr){
//alert(data);
var obj = jQuery.parseJSON(response);
if(!pagelayer_empty(ajax_call_back) || typeof ajax_call_back == 'function'){
ajax_call_back(obj);
}
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
// Save widgets as a global widget
function pagelayer_save_sections(sel, section = 'section'){
var jEle = jQuery(sel);
var pagelayer_ajax_func = {};
var label = 'Please enter the title';
var content = pagelayer_generate_sc(jEle, true);
var data = {};// create array for template data
data[0] = {};
switch(section){
case 'global_widget' :
var title = prompt(label, 'Global Widget');
if (title == null) return;
// Save the widget data in global widget array
if(pagelayer_empty(pagelayer_global_widgets)){
pagelayer_global_widgets = {};
}
break;
case'global_section' :
var title = prompt(label, 'Global Section');
if (title == null) return;
break;
case 'section':
var title = prompt(label, 'Section');
if (title == null) return;
break;
}
// Add Data
data[0]['title'] = title;
data[0]['post_type'] = 'pagelayer-template';
data[0]['type'] = section;
data[0]['content'] = content.replace(/pagelayer-id="(.*?)"/g, ""); // Need to remove pagelayer id,
data[0]['content'] = pagelayer_Base64.encode(data[0]['content']);
// This function for ajax success call back of global widget
pagelayer_ajax_func['global_widget'] = function(obj){
if(pagelayer_empty(obj['success'])){
return;
}
for(var post_id in obj['success']){
jEle.attr("pagelayer-a-global_id", post_id );
// Add global
jData = {};
jData['post_id'] = post_id;
jData['title'] = title; // TODO : create modal to input title
jData['$'] = jEle;
jData['is_dirty'] = true;
// Add the array in global widgets array
pagelayer_global_widgets[post_id] = jData;
pagelayer.$$('.pagelayer-elpd-close').click();
pagelayer.$$('.pagelayer-widget-tab').click();
break;
}
}
// This function for ajax success call back of global sections
pagelayer_ajax_func['global_section'] = function(obj){
// TODO: For global Sections
//console.log(obj);
}
// This function for ajax success call back of section s
pagelayer_ajax_func['section'] = function(obj){
//console.log(obj);
}
pagelayer_ajax_save_template(data, pagelayer_ajax_func[section]);
}
// Genrate sc for global widgets
function pagelayer_generate_sc_global_widget(){
var global_widgets = {};
// Create shortcode for all the global widgets
for(var y in pagelayer_global_widgets){
var cWidget = pagelayer_global_widgets[y];
// If is_dirty empty then continue the loop
if(pagelayer_empty(cWidget['is_dirty'])){
continue;
}
global_widgets[y] = {};
global_widgets[y]['title'] = cWidget['title'];
global_widgets[y]['post_id'] = pagelayer_empty(cWidget['post_id']) ? 0 : cWidget['post_id'];
global_widgets[y]['post_type'] = 'pagelayer-template';
global_widgets[y]['type'] = 'global_widget';
var content = pagelayer_generate_sc(jQuery(cWidget.$), true);
var tag = pagelayer_tag(jQuery(cWidget.$));
// IF is group then need to remove pagelayer id,
if(!pagelayer_empty(tag) && pagelayer_is_group(tag)){
content = content.replace(/pagelayer-id="(.*?)"/g, "");
}
global_widgets[y]['content'] = pagelayer_Base64.encode(content);
pagelayer_global_widgets[y]['is_dirty'] = false;
}
return global_widgets;
}
var pagelayer_set_global_timmer = {};
// If you edit one Global widget it shoud be copied to other instances of the same global widget
function pagelayer_setup_global_widgets(id, jEle){
if(pagelayer_empty(id) || pagelayer_empty(pagelayer_global_widgets[id])){
return;
}
var elData = pagelayer_global_widgets[id];
clearTimeout(pagelayer_set_global_timmer);
pagelayer_set_global_timmer = setTimeout(function(){
// Set attrs for all the global widgets
jQuery(pagelayer_editable+' [pagelayer-a-global_id='+ id +']').each(function(){
var cEle = jQuery(this);
var cEleID = pagelayer_id(cEle);
if( jEle.length > 0 && jEle.is(cEle)){
return true;
}
pagelayer.history_action = false;
pagelayer.global_render = false;
// Get HTML form global array
var html = pagelayer_element_unsetup(elData.$, cEleID);
if(cEle.parent().is('.pagelayer-ele-wrap')){
cEle.parent().children('.pagelayer-ele-overlay').remove();
cEle.unwrap();
}
cEle[0].outerHTML = html[0].outerHTML;
pagelayer_element_setup('[pagelayer-id='+cEleID+'], [pagelayer-id='+cEleID+'] .pagelayer-ele');
pagelayer_sc_render(jQuery('[pagelayer-id="'+cEleID+'"]'));
pagelayer.history_action = true;
pagelayer.global_render = true;
});
}, 3000);
}
// Language key
function pagelayer_l(k){
if(k in pagelayer_lang){
return pagelayer_lang[k];
}
return k;
}
// Get props based on the tag
function pagelayer_get_props(jEle){
var props = pagelayer_shortcodes[pagelayer_tag(jEle)];
return props;
}
// Get all props based on the tag but in a single structure
function pagelayer_make_props_ref(){
// Loop through pagelayer_shortcodes
for(var tag in pagelayer_shortcodes){
var all_props = pagelayer_shortcodes[tag];
pagelayer.props_ref[tag] = {};
// Loop through all props
for(var i in pagelayer_tabs){
var tab = pagelayer_tabs[i];
for(var section in all_props[tab]){
var props = section in pagelayer_shortcodes[tag] ? pagelayer_shortcodes[tag][section] : pagelayer_styles[section];
// In case of widgets its possible !
if(pagelayer_empty(props)){
continue;
}
for(var x in props){
// Create an easy REFERENCE for access
pagelayer.props_ref[tag][x] = props[x];
// Screen option REFERENCE is also needed for lookup
if('screen' in props[x]){
pagelayer.props_ref[tag][x+'_tablet'] = props[x];
pagelayer.props_ref[tag][x+'_mobile'] = props[x];
}
}
}
}
}
}
// Set the given jELE as active
function pagelayer_set_active(jEle){
// Make all other element as inactive
jQuery('[pagelayer-active]').each(function(){
var $j = jQuery(this);
$j.removeAttr('pagelayer-active');
});
jEle.attr('pagelayer-active', 1);
// Add and remove the class
jQuery('.pagelayer-active').removeClass('pagelayer-active');
jEle.parent().children('.pagelayer-ele-overlay').addClass('pagelayer-active');
// Hide active when not supported by tag
var props = pagelayer_get_props(jEle);
if(!pagelayer_empty(props['hide_active'])){
jEle.parent().children('.pagelayer-ele-overlay').addClass('pagelayer-hide-active');
}
}
function pagelayer_sc(sc){
return sc.replace('pl_', '');
};
// Create a HTML dom element of the Short code
// Return the jEle
function pagelayer_create_sc(sc){
var html;
var _sc = pagelayer_sc(sc);
var func = window['pagelayer_create_sc_'+sc];
// Generate the HTML
if(typeof func == 'function'){
html = window['pagelayer_create_sc_'+sc]();
}else{
html = '';
}
html = jQuery(html);
// Add the tag
html.attr('pagelayer-tag', sc);
// Give it an ID
id = pagelayer_assign_id(html);
// Try to set the default values over 5 loops
pagelayer_set_default_atts(html, 5);
return html;
};
// Returns a list of default attributes to set as per the current selection
function pagelayer_set_default_atts(jEle, set){
set = set || 0;
var hasSet = false;
for(var i = 1; i <= set;i++){
//console.log('[pagelayer_set_default_atts] Loop :'+i);
//console.log(jEle);
// Get existing data
var el = pagelayer_data(jEle, true);
// If it is the last loop and we are greater than 1
if(i > 1 && i == set){
console.log('[pagelayer_default_atts] Still vars to set. Please check your shortcode params !');
}
// We are supposed to set !
if('set' in el && !pagelayer_empty(el.set)){
pagelayer_set_atts(jEle, el.set);
hasSet = true;
}else{
break;
}
}
return hasSet;
}
// Returns the tag
function pagelayer_tag(jEle){
// It could be the wrap
if(jEle.hasClass('pagelayer-ele-wrap')){
return jEle.children('.pagelayer-ele').attr('pagelayer-tag');
}
// It could be the row or col holder
if(jEle.hasClass('pagelayer-row-holder') || jEle.hasClass('pagelayer-col-holder')){
return jEle.parent().attr('pagelayer-tag');
}
return jEle.attr('pagelayer-tag');
}
// Gets a single attribute value
function pagelayer_get_att(jEle, att){
return jEle.attr('pagelayer-a-'+att);
};
// Gets a single attribute value
function pagelayer_get_tmp_att(jEle, att){
return jEle.attr('pagelayer-tmp-'+att);
};
// This function will just set atts and not do anything else
// Atts can be string or object. If its string, then val is needed
function pagelayer_set_atts(jEle, atts, val){
if(typeof atts == 'string'){
var tmp = {};
tmp[atts] = val;
atts = tmp;
}
if(typeof atts != 'object'){
return false;
}
var tag = pagelayer_tag(jEle);
var trigger_onchange = 0;
if(pagelayer_empty(tag)){
console.log('Set atts found no tag');
console.log(jEle);
return;
}
// All props
var all_props = pagelayer_shortcodes[tag];//console.log(tag);console.log(jEle);
var trigger_props = {};
var no_val = {};
var defaults = {};
var _props = {};
// Loop through all props
for(var i in pagelayer_tabs){
var tab = pagelayer_tabs[i];
for(var section in all_props[tab]){
var props = section in pagelayer_shortcodes[tag] ? pagelayer_shortcodes[tag][section] : pagelayer_styles[section];
for(var x in props){
if('default' in props[x]){
defaults[x] = 1;
}
// Create an easy REFERENCE for access
_props[x] = props[x];
// Screen option REFERENCE is also needed for lookup
if('screen' in _props[x]){
_props[x+'_tablet'] = props[x];
_props[x+'_mobile'] = props[x];
}
// Dont set any val, but we set temp value
if('no_val' in props[x]){
no_val[x] = 1;
}
if('req' in props[x] || 'show' in props[x]){
var show = 'req' in props[x] ? props[x]['req'] : props[x]['show'];
// We have both req and show, so lets just combine the values and then show
// NOTE : We need to make an array and not just merge the 2 as they are references
if('req' in props[x] && 'show' in props[x]){
// Add the req values
show = JSON.parse(JSON.stringify(props[x]['req']));
// Now the show values need to be looped
for(var t in props[x]['show']){
show[t] = props[x]['show'][t];
}
}
for(var showParam in show){
var val = show[showParam];
var except = showParam.substr(0, 1) == '!' ? true : false;
showParam = except ? showParam.substr(1) : showParam;
trigger_props[showParam] = 1;
}
}
}
}
}
for(var x in atts){
// Are we to trigger change
if(x in trigger_props){
trigger_onchange = 1;
}
//console.log(x+'-'+atts[x]);
// Is this a pro feature and we are not pro ? Then we dont do anything and continue !
if(!pagelayer_empty(_props[x]) && 'pro' in _props[x] && pagelayer_empty(pagelayer_pro)){
continue;
}
if(x in no_val){
pagelayer_set_tmp_atts(jEle, x, atts[x]);
continue;
}
// Record History
if(pagelayer.history_action){
var old_val = pagelayer_get_att(jEle, x) || '';
pagelayer_history_action_push({
'title' : all_props['name'],
'subTitle' : _props[x]['label'],
'action' : 'Edited',
'attrType' : 'a_attr',
'pl_id' : pagelayer_id(jEle),
'atts' : x,
'oldVal' : old_val,
'newVal' : atts[x]
});
}
// Remove the attribute if its BLANK and there is no default for it
// If there is a default, we set it to blank to keep record of the current val
if(atts[x].length < 1){
// Dont remove the value as there is a default
if(!(x in defaults)){
jEle.removeAttr('pagelayer-a-'+x);
// Otherwise blank it
}else{
jEle.attr('pagelayer-a-'+x, atts[x]);
}
// Remove the tmp atts anyway
pagelayer_clear_tmp_atts(jEle, x);
// Set the value
}else{
jEle.attr('pagelayer-a-'+x, pagelayer_trim(atts[x]));
}
// Are you the active element
if(pagelayer_is_active(jEle)){
// TODO : Record Undo and Redo
}
}
// Trigger the change of the parameter and show the required properties
if(trigger_onchange){
pagelayer_elpd_show_rows();
}
pagelayer_do_dirty();
};
// This function will just set atts and not do anything else
// Atts can be string or object. If its string, then val is needed
function pagelayer_set_tmp_atts(jEle, atts, val){
if(typeof atts == 'string'){
var tmp = {};
tmp[atts] = val;
atts = tmp;
}
if(typeof atts != 'object'){
return false;
}
for(var x in atts){
// Record history
if(pagelayer.history_action){
var old_val = pagelayer_get_tmp_att(jEle, x) || '';
pagelayer_history_action_push({
'title' : pagelayer_shortcodes[pagelayer_tag(jEle)]['name'],
'subTitle' : x,
'action' : 'Edited',
'attrType' : 'tmp_attr',
'pl_id' : pagelayer_id(jEle),
'atts' : x,
'oldVal' : old_val,
'newVal' : atts[x]
});
}
jEle.attr('pagelayer-tmp-'+x, atts[x]);
}
};
// This function removes the temporary attributes of an ele
function pagelayer_clear_tmp_atts(jEle, attr){
var to_del = new Array();
var regexp = new RegExp('pagelayer\-tmp\-'+attr, 'gi');
jQuery.each(jEle[0].attributes, function(index, att){
if(!att) return;
if(att.name.match(regexp)){
to_del.push(att.name);
}
});
//console.log(to_del);
for(var n in to_del){
jEle.removeAttr(to_del[n]);
}
}
// Set the att and classes of an HTML which is not yet created
function pagelayer_sc_atts(classes, atts){
if(typeof atts != 'object'){
atts = new Object();
}
var r = new Array();
for(var x in atts){
r.push('pagelayer-a-'+x+'="'+atts[x]+'"');
}
return 'class="'+classes+' pagelayer-ele" '+r.join(' ');
}
// Is the jEle the active element ?
function pagelayer_is_active(jEle){
// Is this the active Element ?
if(pagelayer_empty(pagelayer_active.el) || jEle.attr('pagelayer-id') != pagelayer_active.el.id){
return false;
}
return true;
};
// Removes {{}} from the variable name
function pagelayer_var(val){
return val.substring(2, (val.length - 2));
}
// Take care of the CSS
function pagelayer_css_render(css, val, seperator){
//console.log('CSS '+css+' | '+val);
// Seperator
seperator = seperator || ',';
// Replace the val
css = css.split('{{val}}').join(pagelayer_hex8_to_rgba(val));
// If there is an array
if(css.match(/val\[\d/)){
val = val.split(seperator);
for(var i in val){
css = css.split('{{val['+i+']}}').join(pagelayer_hex8_to_rgba(val[i]));
}
}
//console.log('Final CSS '+css);
return css;
};
// Handle hexa to rgba and also remove alpha which is ff
function pagelayer_hex8_to_rgba(val){
// If opacity is ff then discard ff
if(val.match(/^#([a-f0-9]{6})ff$/)){
return val.substr(0,7);
}
// Lets handle the RGB+opacity
if(val.match(/^#([a-f0-9]{8})$/)){
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(val);
val = 'rgba('+parseInt(result[1], 16)+', '+parseInt(result[2], 16)+', '+parseInt(result[3], 16)+', '+(parseInt(result[4], 16)/255).toFixed(2)+')';
}
return val;
};
// Replace the variables
function pagelayer_parse_el_vars(str, el){
str = str.split('{{element}}').join(el.CSS.sel);
str = str.split('{{wrap}}').join(el.CSS.wrap);
str = str.split('{{ele_id}}').join(el.id);
return str;
}
// Replace the variables
function pagelayer_parse_vars(str, el){
for(var x in el.tmp){
str = str.split('{{{'+x+'}}}').join(el.tmp[x]);
}
for(var x in el.atts){
str = str.split('{{'+x+'}}').join(el.atts[x]);
}
return str;
};
// Render the Element
function pagelayer_sc_render(jEle){
// We render only the active element
if(!pagelayer_is_active(jEle)){
//return false;
}
//console.log('Rendering');
// Handle the CSS part
// Get the id, tag, atts, data, etc
var el = pagelayer_data(jEle, true);
var all_props = pagelayer_shortcodes[el.tag];
var elCSS = {
classes: [],
remove_classes: [],
attr: [],
remove_attr: [],
css: [],
edit: [],
sel: '[pagelayer-id="'+el.id+'"]',
wrap: '[pagelayer-wrap-id="'+el.id+'"]'
};
// Create a reference
el.CSS = elCSS;
//console.log(el.atts);
for(var i in pagelayer_tabs){
var tab = pagelayer_tabs[i];
for(var section in all_props[tab]){ //console.log(tab+' '+section);
var props = section in pagelayer_shortcodes[el.tag] ? pagelayer_shortcodes[el.tag][section] : pagelayer_styles[section];//console.log(props);
// Loop the props
for(var x in props){
// pagelayer_data will return attributes even if they are BLANK e.g. attr=""
// Render doesnt consider BLANK values as values, and we are unsetting them now
// If in any situation you need to consider blank values, please handle in the JS / PHP function of the Shortcode
if(x in el.atts && el.atts[x].length < 1){
delete el.atts[x];
}
// Any editor ?
if('edit' in props[x]){
elCSS.edit.push({prop: x, sel: props[x]['edit']});
}
// Do we have a addClass ?
// We are checking before the element has a value so that we can add or remove the class
if('addClass' in props[x]){
var addClasses;
// Convert the string to an array
if(typeof props[x]['addClass'] === 'string'){
addClasses = [props[x]['addClass']];
}else{
addClasses = props[x]['addClass'];
}
for(var c in addClasses){
// The selector
var tSel = jQuery.isNumeric(c) ? '' : c;
// If there is a VAL
// NOTE : Only val is allowed when there is a list
if(addClasses[c].match(/\{\{val\}\}/) && 'list' in props[x]){
for(var l in props[x]['list']){
var tmp = {'sel': tSel, 'val': addClasses[c].replace('{{val}}', l)};
if(el.atts[x] == l){
elCSS['classes'].push(tmp);
}else{
elCSS['remove_classes'].push(tmp);
}
}
}else{
var tmp = {'sel': tSel, 'val': addClasses[c]};
// If the value is there
if(x in el.atts){
elCSS['classes'].push(tmp);
}else{
elCSS['remove_classes'].push(tmp);
}
}
}
}
// Do we have a addAttr ?
// We are checking before the element has a value so that we can add or remove the attr
if('addAttr' in props[x]){
var addAttr;
// Convert the string to an array
if(typeof props[x]['addAttr'] === 'string'){
addAttr = [props[x]['addAttr']];
}else{
addAttr = props[x]['addAttr'];
}
for(var c in addAttr){
// The selector
var tSel = jQuery.isNumeric(c) ? '' : c;
var tmp = {'sel': tSel, 'val': addAttr[c]};
// If the value is there
if(x in el.atts){
elCSS['attr'].push(tmp);
}else{
elCSS['remove_attr'].push(tmp);
}
}
}
// Do we have a CSS ?
if('css' in props[x]){
var css;
// Convert the string to an array
if(typeof props[x]['css'] === 'string'){
css = [props[x]['css']];
}else{
css = props[x]['css'];
}
// Screen modes
var modes = {desktop: '', tablet: '_tablet', mobile: '_mobile'};
for(var m in modes){
var xm = x+modes[m];
// If the value is there
if(!(xm in el.atts)){
continue;
}
for(var c in css){
// The selector
var tSel = jQuery.isNumeric(c) ? '{{element}}' : c;
var tmp = {
sel: tSel,
val: pagelayer_css_render(css[c], el.atts[xm], (props[x].sep || ',')),
};
// Is this a tablet
if(m == 'tablet'){
tmp.sel = '@media (max-width: '+ pagelayer_settings['tablet_breakpoint'] +'px) and (min-width: '+ (pagelayer_settings['mobile_breakpoint'] +1) +'px){'+tmp.sel;
tmp.val = tmp.val+'}';
}
// Is this a mobile mode ?
if(m == 'mobile'){
tmp.sel = '@media (max-width: '+ pagelayer_settings['mobile_breakpoint'] +'px){'+tmp.sel;
tmp.val = tmp.val+'}';
}
// Push to store
elCSS.css.push(tmp);
}
}
}
}
}
}
// If there is an HTML, then process it
if('html' in pagelayer_shortcodes[el.tag]){
// Is there a function to render ?
var fn = window['pagelayer_render_'+jEle.attr('pagelayer-tag')];
if(typeof fn == 'function'){
fn(el);
}
el.iHTML = jQuery('
'+pagelayer_shortcodes[el.tag]['html']+'
');
// Lets process the 'if-ext'
el.iHTML.find('[if-ext]').each(function (){
var $j = jQuery(this);
var reqvar = pagelayer_var($j.attr('if-ext'));
$j.removeAttr('if-ext');
// Is the element there ?
if(!(reqvar in el.atts && !pagelayer_empty(el.atts[reqvar]))){
//console.log('HERE');
$j[0].outerHTML = $j.html();
}
});
// Lets process the 'if'
el.iHTML.find('[if]').each(function (){
var $j = jQuery(this);
var reqvar = pagelayer_var($j.attr('if'));
$j.removeAttr('if');
// Is the element there ?
if(!(reqvar in el.atts && !pagelayer_empty(el.atts[reqvar]))){
//console.log('HERE');
$j.remove();
}
});
//console.log(el.atts);
// Parse the variables
var new_html = pagelayer_parse_vars(el.iHTML.html(), el);
el.iHTML.html(new_html);
// Do we have to wrap the innerHTML ?
if('holder' in pagelayer_shortcodes[el.tag]){
var hSel = pagelayer_shortcodes[el.tag]['holder'];
var holder = jEle.find(hSel).first();
// Detach the holder
holder.detach();
// Add the new HTML
el.$.html(el.iHTML.html());
// reAttach the children only
el.$.find(hSel).html(holder.children());
// No holder
}else{
//console.log(el.iHTML.html());
el.$.html(el.iHTML.html());
}
// Rows, Cols and Groups
}else{
// Is there a function to render ?
var fn = window['pagelayer_sc_render_'+jEle.attr('pagelayer-tag')];
if(typeof fn == 'function'){
fn(el);
}
}
// Is there a function to render after HTML insertion but before CSS and attr ?
var post = window['pagelayer_render_html_'+jEle.attr('pagelayer-tag')];
if(typeof post == 'function'){
post(el);
}
////////////////////////////
// Are there any edit fields ?
////////////////////////////
if(elCSS.edit.length > 0){
for(var c in elCSS.edit){
var prop = elCSS.edit[c]['prop'];
var tSel = elCSS.edit[c]['sel'];
var node = tSel.length < 1 ? jEle : jEle.find(tSel);
node.attr('pagelayer-editable', prop);
}
}
////////////////////////////
// Are there any addClass ?
////////////////////////////
// If we have any classes to add
if(elCSS.classes.length > 0){
//console.log(elCSS.classes);
for(var c in elCSS.classes){
var tSel = elCSS.classes[c]['sel'].replace('{{element}}', '');
var node = tSel.length < 1 ? jEle : jEle.find(tSel);
if(!node.hasClass(elCSS.classes[c]['val'])){
node.addClass(elCSS.classes[c]['val']);
}
}
}
// If we have any classes to remove
if(elCSS.remove_classes.length > 0){
//console.log(elCSS.remove_classes);
for(var c in elCSS.remove_classes){
var tSel = elCSS.remove_classes[c]['sel'].replace('{{element}}', '');
var node = tSel.length < 1 ? jEle : jEle.find(tSel);
if(node.hasClass(elCSS.remove_classes[c]['val'])){
node.removeClass(elCSS.remove_classes[c]['val']);
}
}
}
////////////////////////////
// Are there any addAttr ?
////////////////////////////
// If we have any attributes to add
if(elCSS.attr.length > 0){
//console.log(elCSS.attr);
for(var c in elCSS.attr){
var tSel = elCSS.attr[c]['sel'].replace('{{element}}', '');
var node = tSel.length < 1 ? jEle : jEle.find(tSel);
var att = elCSS.attr[c]['val'].split('=');
att[1] = pagelayer_parse_vars(att[1], el);
att[1] = pagelayer_trim(att[1], '"');
// Is it the same val ?
if(!node.attr(att[0]) !== att[1]){
node.attr(att[0], att[1]);
}
}
}
// If we have any attributes to add
if(elCSS.remove_attr.length > 0){
//console.log(elCSS.remove_attr);
for(var c in elCSS.remove_attr){
var tSel = elCSS.remove_attr[c]['sel'].replace('{{element}}', '');
var node = tSel.length < 1 ? jEle : jEle.find(tSel);
var att = elCSS.remove_attr[c]['val'].split('=');
if(node.is('['+att[0]+']')){
node.removeAttr(att[0]);
}
}
}
// The style element
var style = pagelayer.$('[pagelayer-style-id='+el.id+']');
// If we have any RULES CSS, then handle it
if(elCSS.css.length > 0){
// Did we find it ?
if(style.length < 1){
jEle.prepend('');
}
// Get it again
style = pagelayer.$('[pagelayer-style-id='+el.id+']');
// Make the rules
var rules = [];
// Loop
for(var c in elCSS.css){
var tSel = pagelayer_parse_el_vars(elCSS.css[c]['sel'], el);
var rule = pagelayer_parse_vars(elCSS.css[c]['val'], el);
if(tSel.length > 0){
rules.push(tSel+'{'+rule+'}');
}else{
rules.push(pagelayer_parse_el_vars(rule, el));
}
}
// CSS Selector overide
if(!pagelayer_empty(all_props['overide_css_selector'])){
for(var r in rules){
var overide_css_selector = pagelayer_parse_el_vars(all_props['overide_css_selector'], el);
rules[r] = rules[r].split(el.CSS.sel).join(overide_css_selector);
rules[r] = rules[r].split(el.CSS.wrap).join(overide_css_selector);
}
}
// Set the style
style.html(rules.join("\n"));
//console.log(style);
}else{
style.remove();
}
// Is there a function to render at the end ?
var end = window['pagelayer_render_end_'+jEle.attr('pagelayer-tag')];
if(typeof end == 'function'){
end(el);
}
// If the element have any parent
var par = pagelayer_get_parent(jEle);
var eleId = el.id;
if(par){
eleId = par;
pagelayer_sc_render(pagelayer_ele_by_id(par));
}
// Render End trigger
pagelayer_trigger_action('pagelayer_sc_render_end', [el]);
var gEle = pagelayer_ele_by_id(eleId);
var gId = gEle.attr('pagelayer-a-global_id');
// If global id exist then update the global array and restup the all global element
if(!pagelayer_empty(gId) && !pagelayer_empty(pagelayer.global_render)){
if(!pagelayer_empty(pagelayer_global_widgets[gId])){
pagelayer_global_widgets[gId].$ = gEle;
pagelayer_global_widgets[gId]['is_dirty'] = true;
pagelayer_setup_global_widgets(gId, pagelayer_ele_by_id(eleId), true);
}else{
gEle.removeAttr('pagelayer-a-global_id');
}
};
};
// Is the given tag a group
function pagelayer_is_group(tag){
if('has_group' in pagelayer_shortcodes[tag] && !pagelayer_empty(pagelayer_shortcodes[tag]['has_group'])){
return true;
}
return false;
}
// Do action / event
function pagelayer_trigger_action(act, param = []){
jQuery(document).trigger(act, param);
}
// Perform a function on an action / event
function pagelayer_add_action(act, func){
jQuery(document).on(act, func);
}
// Create array of the contact from template params
function pagelayer_get_contact_templates(){
var contacts = jQuery(pagelayer_editable+' [pagelayer-tag=pl_contact]');
var contacts_props = {};
if(contacts.length > 0){
contacts.each(function(){
var tmp = pagelayer_data(jQuery(this));
var con_allowed = ['to_email', 'from_email', 'cont_subject', 'cont_header', 'cont_body', 'cont_use_html'];
if(pagelayer_empty(tmp.atts['contact_custom_templ'])) return true;
// Define blank array
contacts_props[tmp.id] = {};
for(var x in con_allowed){
var key = con_allowed[x];
if(!pagelayer_empty(tmp.atts[key])){
contacts_props[tmp.id][key] = tmp.atts[key];
}
}
});
}
return contacts_props;
}
// Save the post
function pagelayer_save(){
// hiding and showing loading animation
pagelayer.$$('.pagelayer-update-text').hide();
pagelayer.$$('.pagelayer-update-loader').show();
pagelayer_trigger_action('pagelayer_save');
var pagelayerajaxurl = pagelayer_ajax_url+'&action=pagelayer_save_content&postID='+pagelayer_postID;
var post = pagelayer_generate_sc(pagelayer_editable);//alert(post);return;
// Do we have contact templates ?
var contacts_props = pagelayer_get_contact_templates();
// Do we have any global widget to save ?
var global_data = {};
if(!pagelayer_empty(pagelayer_global_widgets)){
global_data = pagelayer_generate_sc_global_widget();
}
jQuery.ajax({
type: "POST",
url: pagelayerajaxurl,
data: {
pagelayer_update_content : pagelayer_Base64.encode(post),
pagelayer_nonce: pagelayer_ajax_nonce,
global_widgets: global_data,
contacts: contacts_props,
post_status: pagelayer.post_status,
copyright: pagelayer_copyright
},
success: function(response, status, xhr){
//alert(data);
var obj = jQuery.parseJSON(response);
//alert(obj);
if(obj['error']){
alert(obj['error']);
}else{
pagelayer_do_undirty();
alert(obj['success']);
pagelayer_get_revision();
}
},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
alert('An error occured while saving ! Status : '+textStatus+' and Error : '+errorThrown);
},
complete: function(xhr,status){
pagelayer.$$('.pagelayer-update-text').show();
pagelayer.$$('.pagelayer-update-loader').hide();
if(!pagelayer_empty(pagelayer.post_status)){
pagelayer.$$('.pagelayer-props-modal .pagelayer-meta-iframe').attr('src', pagelayer_post_props );
pagelayer.post_status = '';
}
}
});
};
//Close the Editor
function pagelayer_close(){
if(pagelayer_isDirty == true){
var r = confirm('Your Data has not been Saved yet! \n Press OK to stay on the Page.'+
'\n Press Cancel to Close Editor. ');
if(r == false){
window.top.location.href = pagelayer_returnURL;
}
}else{
window.top.location.href = pagelayer_returnURL;
}
};
function pagelayer_serializeAttributes(attributes) {
return JSON.stringify(attributes) // Don't break HTML comments.
.replace(/--/g, "\\u002d\\u002d") // Don't break non-standard-compliant tools.
.replace(//g, "\\u003e").replace(/&/g, "\\u0026") // Bypass server stripslashes behavior which would unescape stringify's
// escaping of quotation mark.
// See: https://developer.wordpress.org/reference/functions/wp_kses_stripslashes/
.replace(/\\"/g, "\\u0022");
}
// Generate blocks Post to save
function pagelayer_generate_sc(selector, selfEle){
selfEle = selfEle || false;
var txt = '';
var generate_sc_single = function(jEle){
// The ID
var id = jEle.attr('pagelayer-id');
// If there is an Add element wrapper
if(pagelayer_empty(id)){
return;
}
// Find the type of tag
var tag = jEle.attr('pagelayer-tag');
var final_tag = tag;
var closestEle = jEle.closest('.pagelayer-col-holder');
// Define inner row | Note : Commented as we now have a new widget of type inner_row
/*if(tag == 'pl_row' && closestEle.length > 0 && closestEle.closest(pagelayer_editable).length > 0){
final_tag = 'pl_inner_row';
}*/
if(pagelayer_empty(tag)){
var err = 'Found an error in the content as the TAG was missing. The console will have more details.';
alert(err);
console.log(err);
console.log(jEle);
}
// Define inner column
if(tag == 'pl_col' && closestEle.length > 0 && closestEle.closest(pagelayer_editable).length > 0){
final_tag = 'pl_inner_col';
}
//console.log(tag);
// Is there an innerHTML ele
var inner = '';
if('innerHTML' in pagelayer_shortcodes[tag]){
inner = pagelayer_shortcodes[tag]['innerHTML'];
}
// Create the tag
var data = {};
// Get the attributes to store
jQuery.each(jEle[0].attributes, function(i, attrib){
var res = attrib.name.match(/^pagelayer-a-(.+)/i);
if(res && res[1] != inner){
//console.log(attrib.name+' '+res[1]);
data[res[1]] = attrib.value;
}
});
data['pagelayer-id'] = id;
data = pagelayer_serializeAttributes(data);
var content = '';
// Any internal function to handle the save ?
var func = window['pagelayer_tag_'+tag];
if(typeof func == 'function'){
content = func(jEle);
// If its a Row or Column or Group then it will have children
}else if(jEle.hasClass('pagelayer-row') || jEle.hasClass('pagelayer-col') || jEle.hasClass('pagelayer-inner_row') || pagelayer_is_group(tag)){
var sel = "[pagelayer-id="+id+"]";
// Any holder which holds children ?
if('holder' in pagelayer_shortcodes[tag]){
sel = sel+' '+pagelayer_shortcodes[tag]['holder'];
}
// Select the top-most element
sel = jQuery(sel).first();
// Any child selector - Majorly for owl carousel
// NOTE : Child selector should be very specific with immediate child selection at all levels
var child_selector = false;
if('child_selector' in pagelayer_shortcodes[tag]){
sel = sel.find(pagelayer_shortcodes[tag]['child_selector']);
}
if(jQuery(sel).children(".pagelayer-ele-wrap").length < 1){
content = jQuery(sel).html(); // Backward Compatibility
}else{
content = pagelayer_generate_sc(sel);
content = "\n"+content;
}
// Its a normal element so we might need to handle the content
}else{
if(inner.length > 0){
content = pagelayer_get_att(jEle, inner);
if(!content){
content = '';
}
}else{
content = '';//jEle.html();
}
}
if (pagelayer_empty(content)) {
txt += "\n");
}else{
txt += "").concat(content, "\n");
}
};
// Are you an element for which to generate the codes ?
if(jQuery(selector).hasClass('pagelayer-ele') && selfEle){
generate_sc_single(jQuery(selector));
// The selector is the holder, so loop thru
}else{
jQuery(selector).children(".pagelayer-ele-wrap").each(function(){
var jEle = jQuery(this).children('.pagelayer-ele');
generate_sc_single(jEle);
});
}
return txt;
};
// Show the required leftbar tab
function pagelayer_leftbar_tab(tab){
pagelayer.$$('.pagelayer-leftbar-tab').hide();
pagelayer.$$('#'+tab).show();
}
// Sets up the leftbar
function pagelayer_leftbar(){
// Toggle the holder
pagelayer.$$('.pagelayer-leftbar-toggle').on('click', function(){
pagelayer.$$('.pagelayer-leftbar-table').toggleClass('pagelayer-leftbar-hidden');
pagelayer_trigger_action('pagelayer-leftbar-toggle');
});
// Close leftbar
pagelayer.$$('.pagelayer-leftbar-close').on('click', function(){
pagelayer.$$('.pagelayer-leftbar-toggle').click();
});
// Minimize leftbar
pagelayer.$$('.pagelayer-leftbar-minimize').on('click', function(){
pagelayer.$$('.pagelayer-leftbar-table').toggleClass('pagelayer-leftbar-minimize');
});
var html = '
'+
'
'+
'
'+
'
'+
'
Widgets
'+
'
Global
'+
'
'+
'
'+
'
'+
'×'+
'
';
for(var x in pagelayer_groups){
// Title
html += '
'+x+'
';
// Indivdual icon
for(var y in pagelayer_groups[x]){
var sc = pagelayer_groups[x][y];
if(!(sc in pagelayer_shortcodes) || 'not_visible' in pagelayer_shortcodes[sc]){
continue;
}
html += '
'+
'
'+
'
';
if('icon' in pagelayer_shortcodes[sc]){
html += '';
}else{
html += '';
}
html += '
'+
''+pagelayer_shortcodes[sc]['name']+''+
'
'+
'
';
}
html += '
';
}
html += '
'+
''+
'
'+
''+
''+
''+
''+
''+
'
'+
'
';
pagelayer.$$('.pagelayer-leftbar-holder').prepend(html);
pagelayer_leftbar_tab('pagelayer-shortcodes');
pagelayer.$$('.pagelayer-leftbar-scroll').slimScroll({
height: '100%',
railVisible: false,
alwaysVisible: true,
color: '#000',
size: '5px',
});
// Hide the ones which are not supposed to be shown
pagelayer.$$('.pagelayer-search-field').on('input', function(){
var val = jQuery(this).val();
var re = new RegExp(val, 'i');
// Show only the required tags
pagelayer.$$('.pagelayer-leftbar-group').each(function(){
var group = jQuery(this);
var res = group.find('[pagelayer-tag]');
var hidden = 0;
res.each(function(){
var tEle = jQuery(this);
if(tEle.find('.pagelayer-shortcode-text').html().match(re)){
tEle.show();
}else{
hidden += 1;
tEle.hide();
}
});
// Hide the whole group
if(hidden == res.length){
group.hide();
}else{
group.show();
}
});
});
// On click Pagelayer setting icon
pagelayer.$$('.pagelayer-settings-icon').click(function(event){
pagelayer_active = {};
var pl_tag = jQuery(this).attr('pagelayer-tag') || 'pl_post_props';
var nModal = jQuery(this).attr('pagelayer-modal-none');
if(pl_tag == 'pl_post_props' && pagelayer_empty(nModal) ){
var propsModal = pagelayer.$$('.pagelayer-props-modal');
if(propsModal.find('.pagelayer-meta-iframe').length < 1){
propsModal.find('.pagelayer-props-wrap').append('');
propsModal.find('.pagelayer-meta-iframe').load(function(){
propsModal.find('.pagelayer-props-loading-screen').hide();
propsModal.find('.pagelayer-props-modal-close').css('visibility','visible');
jQuery(this).show();
});
}
propsModal.show();
pagelayer.$$('.pagelayer-meta-iframe').contents().find('.pagelayer-tab-items[data-tab="post_props"]').click();
return;
}
pagelayer_post_settings(pl_tag);
});
// Pagelayer post advance setting modal handler
var propsModal = pagelayer.$$('.pagelayer-props-modal');
propsModal.find('.pagelayer-props-modal-close').on('click', function(event){
propsModal.hide();
});
propsModal.on('click', function(event){
var target = jQuery(event.target);
if(target.closest('.pagelayer-props-modal-wrap').length > 0){
return;
}
propsModal.hide();
});
// On click Pagelayer setting icon
var global_widget_list = function(){
var gHtml = '';
if(pagelayer_empty(pagelayer_pro)){
gHtml += '
'+pagelayer.pro_txt+
'
Using this feature, you can save the widgets globally and use them on the entire site. The global widget will be editable from one place.
';
}
pagelayer.$$('#pagelayer-global-widget').html(gHtml);
};
// The widget tabs
pagelayer.$$('.pagelayer-widget-tab').on('click', function(){
var attr = 'pagelayer-elpd-active-tab';
pagelayer.$$('.pagelayer-widget-tab').each(function(){
jQuery(this).removeAttr(attr);
});
var cEle = jQuery(this);
cEle.attr(attr, 1);
if(cEle.attr('pagelayer-widget-tab') == 'global'){
cEle.closest('#pagelayer-shortcodes').find('.pagelayer-shortcodes-widget').addClass('pagelayer-hidden');
cEle.closest('#pagelayer-shortcodes').find('.pagelayer-global-widget').removeClass('pagelayer-hidden');
// Trigger create global widgets
global_widget_list();
}else{
cEle.closest('#pagelayer-shortcodes').find('.pagelayer-shortcodes-widget').removeClass('pagelayer-hidden');
cEle.closest('#pagelayer-shortcodes').find('.pagelayer-global-widget').addClass('pagelayer-hidden');
}
});
// On click search empty
pagelayer.$$('.pagelayer-leftbar-search>.pagelayer-sf-empty').click(function(){
pagelayer.$$('.pagelayer-search-field').val('').trigger('input');
});
};
// Post setting holder
function pagelayer_post_settings(pl_tag, to_click){
to_click = to_click == -1 ? false : true;
// Is there a post settings ?
var jEle = jQuery(pagelayer_editable+' [pagelayer-tag='+ pl_tag +']');
// Could not find
if(jEle.length < 1){
jEle = pagelayer_create_sc(pl_tag);
var id = pagelayer_id(jEle);
jQuery(pagelayer_editable).prepend(jEle);
pagelayer_element_setup('[pagelayer-id='+id+']', true);
}
if(to_click){
jEle.click();
}
return jEle;
}
// Get the closest element and method
function pagelayer_near_by_ele(id, sc){
// Get the previous element of the id element
var prevEle_id = jQuery('[pagelayer-wrap-id="'+id+'"]').prev().attr('pagelayer-wrap-id') || '';
var method, cEle, args = {};
if(prevEle_id.length > 0){
// If have previous element of the id element
// Set the method and previous element selector
args = {'method' : 'after', 'cEle' : '[pagelayer-wrap-id="'+prevEle_id+'"]'};
}else{
// If don't have previous element of the id element then get parent element
if(sc == "pl_row"){
args = {'method' : 'prepend', 'cEle' : pagelayer_editable};
}else{
// Get the parent element
var pEle_id = pagelayer_id(jQuery('[pagelayer-wrap-id="'+id+'"]').closest('.pagelayer-ele'));
// Get the parent element tag
var pEle_tag = pagelayer_tag(jQuery('[pagelayer-id="'+pEle_id+'"]'));
var holder = pagelayer_shortcodes[pEle_tag]['holder'] || '';
args = {'method' : 'prepend', 'cEle' : '[pagelayer-id="'+pEle_id+'"] '+ holder+' '};
}
}
return args;
};
// Push the action data in the pagelayer_history_obj object
function pagelayer_history_action_push(args){
var currentTime = new Date();
var history_obj_len = pagelayer_history_obj['action_data'].length;
// If the history_obj_len is less then 1 then set the data in array 0 position
if(history_obj_len < 1){
pagelayer_history_obj['action_data'][0] = {'title' : 'Start Editing', 'action' : 'Start' };
pagelayer_history_obj['current_active_item_id'] = 0;
}
// Remove the second array element if the history_obj_len greater then 100
if(history_obj_len > 100){
pagelayer_history_obj['action_data'].splice(1, 1);
pagelayer_history_obj['current_active_item_id'] = pagelayer_history_obj['action_data'].length - 1;
}
// Get current active history action id
var action_id = parseInt(pagelayer_history_obj['current_active_item_id']) || 0;
// Remove the all array element after the active array element
var del_ele = history_obj_len - action_id - 1;
pagelayer_history_obj['action_data'].splice(action_id + 1, del_ele);
// Check if the same attr set as current active history
if(args.action == "Edited" && history_obj_len > 1 && currentTime - pagelayer.history_lastTime < 1000){
var atts = pagelayer_history_obj['action_data'][action_id] || '';
if(atts['atts'] == args['atts'] && atts['pl_id'] == args['pl_id'] && pagelayer_empty(atts['sub_actions_group']) ){
args['oldVal'] = atts['oldVal'];
pagelayer_history_obj['action_data'][action_id] = args;
pagelayer_history_setup();
// Set the last history time
pagelayer.history_lastTime = currentTime;
return true;
}
}
// If the action time within 200 millisecond then it count as sub-actions
if(currentTime - pagelayer.history_lastTime < 200 && history_obj_len > 1){
var sub_actions_len = pagelayer_history_obj['action_data'][action_id]['sub_actions_group'] || '';
// If the sub_actions_len is less then 1 then set the data in array 0 position
if(sub_actions_len.length < 1){
pagelayer_history_obj['action_data'][action_id]['sub_actions_group'] = [args];
}else{
pagelayer_history_obj['action_data'][action_id]['sub_actions_group'].push(args);
}
return true;
}
pagelayer_history_obj['action_data'].push(args);
pagelayer_history_obj['current_active_item_id'] = pagelayer_history_obj['action_data'].length - 1;
pagelayer_history_setup();
// Set the last history time
pagelayer.history_lastTime = currentTime;
}
// Setup pagelayer history
function pagelayer_history_setup(force){
var force = force || false;
// If the history tab is visible, only then setup
if(!pagelayer.$$('#pagelayer-history').is(':visible') && !force){
return;
}
// The current active action id
var current_id = pagelayer_history_obj['current_active_item_id'];
// pagelayer-HISTORY - Element Properties Dialog
var pagelayer_history_html = '
'+
'
Actions
'+
'
Revisions
'+
'
'+
'
'+
'
';
// Any actions
if(pagelayer_history_obj['action_data'].length > 0){
for(var x in pagelayer_history_obj['action_data']){
if(pagelayer_empty(pagelayer_history_obj['action_data'][x])){continue;}
var title = pagelayer_history_obj['action_data'][x]['title'] || '';
var subTitle = pagelayer_history_obj['action_data'][x]['subTitle'] || '';
var action = pagelayer_history_obj['action_data'][x]['action'] || '';
var tmp_attr = pagelayer_history_obj['action_data'][x]['attrType'] || '';
var eAttr = '';
if(!pagelayer_empty(tmp_attr) && tmp_attr == "tmp_attr"){
eAttr = "pagelayer-history-hidden";
}
pagelayer_history_html += '
';
// Create the dialog box
pagelayer.$$('#pagelayer-history').html(pagelayer_history_html);
var holder = pagelayer.$$('#pagelayer-history');
// Set active history holder
holder.find('.pagelayer-history-holder').on('click', function(){
var hEle = jQuery(this);
var prev_item_id = pagelayer_history_obj['current_active_item_id'];
hEle.parent().children().removeClass('current_active_item');
hEle.addClass('current_active_item');
var do_item_id = parseInt(hEle.attr('history-action-id'));
pagelayer_history_action_setup(do_item_id, prev_item_id);
});
// Apply revision
holder.find('.pagelayer-revision-holder').on('click', function(){
var revision_id = jQuery(this).attr('revision-id');
jQuery.ajax({
url: pagelayer_ajax_url+'&action=pagelayer_apply_revision&revisionID='+revision_id,
type: 'post',
data: {
pagelayer_nonce: pagelayer_ajax_nonce,
'pagelayer-live' : 1,
},
success: function(response, status, xhr){
var obj = jQuery.parseJSON(response);
if(obj['error']){
alert(obj['error']);
}else{
// Get the current post_name and post_status
var props = jQuery(pagelayer_editable).find('.pagelayer-post_props');
var post_name = '', post_status = '';
if(props.length > 0){
post_name = pagelayer_get_att(props, 'post_name');
post_status = pagelayer_get_att(props, 'post_status');
}
jQuery(pagelayer_editable).html(obj['content']);
// Add previous post_name and post_status
var props_new = jQuery(pagelayer_editable).find('.pagelayer-post_props');
if(props_new.length > 0){
if(pagelayer_empty(post_name)){
post_name = pagelayer_shortcodes.pl_post_props.params.post_name.default;
}
if(pagelayer_empty(post_status)){
post_status = pagelayer_shortcodes.pl_post_props.params.post_status.default;
}
props_new.attr('pagelayer-a-post_name', post_name);
props_new.attr('pagelayer-a-post_status', post_status);
}
// Need to pass true to render table
pagelayer_element_setup('.pagelayer-ele', true);
pagelayer_add_widget();
alert(obj['success']);
}
}
});
});
// Delete the revision
holder.find('.pagelayer-revision-delete').click(function(e){
e.stopPropagation();
var rEle = jQuery(this).closest('.pagelayer-revision-holder');
var revision_id = rEle.attr('revision-id');
if(confirm("Are you sure you want to delete the revision ?")){
jQuery.ajax({
url: pagelayer_ajax_url+'&action=pagelayer_delete_revision&revisionID='+revision_id,
type: 'post',
data: {pagelayer_nonce: pagelayer_ajax_nonce},
success: function(response, status, xhr){
var obj = jQuery.parseJSON(response);
if(obj['error']){
alert(obj['error']);
}else{
alert(obj['success']);
rEle.hide();
}
}
});
}
});
// The tabs
holder.find('.pagelayer-history-tab').on('click', function(){
var attr = 'pagelayer-history-active-tab';
holder.find('.pagelayer-history-tab').each(function(){
jQuery(this).removeAttr(attr);
});
jQuery(this).attr(attr, 1);
// Get the active tab
var active_tab = holder.find('[pagelayer-history-active-tab]').attr('pagelayer-history-tab');
// Trigger the showing of rows
holder.find('[pagelayer-show-tab]').each(function(){
var sec = jQuery(this);
// Is it the active tab ?
if(sec.attr('pagelayer-show-tab') != active_tab){
sec.hide();
}else{
sec.show();
}
});
});
}
// Get revisions Handler
function pagelayer_get_revision(){
jQuery.ajax({
url: pagelayer_ajax_url+'&action=pagelayer_get_revision&postID='+pagelayer_postID,
type: 'post',
data: {
pagelayer_nonce: pagelayer_ajax_nonce,
},
//async:false,
success: function(response, status, xhr){
var obj = jQuery.parseJSON(response);
if(!pagelayer_empty(obj['error'])){
alert(obj['error']);
}else{
pagelayer_revision_obj = obj;
pagelayer_history_setup(true);
}
}
});
};
// Do the history action - use for ctrl-z and ctrl-y
function pagelayer_do_history(action){
var cur_id = pagelayer_history_obj['current_active_item_id'];
var new_id = cur_id;
var action_data_len = pagelayer_history_obj['action_data'].length;
if(action == 'undo'){
// You cannot undo from the first movement
if(cur_id == 0){
return true;
}
for(var i = (cur_id - 1); i => 0; i--){
var action = pagelayer_history_obj['action_data'][i];
if('attrType' in action && action['attrType'] == 'tmp_attr'){
continue;
}
new_id = i;
break;
}
}else if(action == 'redo'){
for(var i = cur_id + 1; i < action_data_len; i++){
var action = pagelayer_history_obj['action_data'][i];
if('attrType' in action && action['attrType'] == 'tmp_attr'){
continue;
}
new_id = i;
break;
}
}
// Do the action
pagelayer_history_action_setup(new_id, cur_id);
pagelayer_history_setup();
};
// Action setup handle on ctrl-z and ctrl-y
function pagelayer_history_action_setup(current_item_id, prev_item_id){
// Set this as the current active
pagelayer_history_obj['current_active_item_id'] = current_item_id;
// Delete the element
var delete_ele = function(id){
// Set Pagelayer History FALSE to prevent saving delete action in action history
pagelayer.history_action = false;
pagelayer_delete_element('[pagelayer-id='+id+']');
// Set Pagelayer History TRUE
pagelayer.history_action = true;
};
// Re-setup the element
var resetup_ele = function(history_array){
jQuery(history_array.cEle.cEle)[history_array.cEle.method](history_array.html);
pagelayer_element_setup('[pagelayer-id='+history_array.pl_id+'], [pagelayer-id='+history_array.pl_id+'] .pagelayer-ele', true);
pagelayer_empty_col(jQuery('[pagelayer-id="'+history_array.pl_id+'"]').closest('.pagelayer-col-holder'));
};
// Re-setup the element attr
var reset_ele_attr = function(hEle, atts, val, attrType){
// Set Pagelayer History FALSE to prevent saving attributes in action history
pagelayer.history_action = false;
if(attrType == "tmp_attr"){
pagelayer_set_tmp_atts(hEle, atts, val);
}else{
pagelayer_set_atts(hEle, atts, val);
}
// The property holder
var holder = pagelayer.$$('.pagelayer-elpd-body');
holder.html(' ');
pagelayer_sc_render(hEle);
pagelayer_elpd_generate(hEle, holder);
pagelayer.history_action = true;
};
// Move element
var pagelayer_move_ele = function(id, move_loc){
var eWrap = pagelayer_wrap_by_id(id);
var pCol = eWrap.closest('.pagelayer-col-holder') || '';
jQuery(move_loc.cEle)[move_loc.method](eWrap);
// Ensure the column is not empty
if(!pagelayer_empty(pCol)){
pagelayer_empty_col(pCol);
pagelayer_empty_col(pagelayer_wrap_by_id(id).closest('.pagelayer-col-holder'));
}
};
// Undo actions
var pagelayer_undo_action = function(history_array){
var action = history_array.action;
var id = history_array.pl_id;
if(action == "Edited"){
hEle = jQuery('[pagelayer-id="'+id+'"]');
reset_ele_attr(hEle, history_array.atts, history_array.oldVal, history_array.attrType);
}else if(action == "Added"){
delete_ele(id);
}else if(action == "Deleted"){
resetup_ele(history_array);
}else if(action == "Copied"){
delete_ele(id);
}else if(action == "Moved"){
pagelayer_move_ele(id, history_array.before_loc);
}
};
// Redo actions
var pagelayer_redo_action = function(history_array){
var action = history_array.action;
var id = history_array.pl_id;
if(action == "Edited"){
hEle = jQuery('[pagelayer-id="'+id+'"]');
reset_ele_attr(hEle, history_array.atts, history_array.newVal, history_array.attrType);
}else if(action == "Added"){
resetup_ele(history_array);
if(history_array.tag != "pl_row" && history_array.tag != "pl_col" ){
// Ensure the column is not empty
pagelayer_empty_col(history_array.cEle.cEle);
}
}else if(action == "Deleted"){
delete_ele(id);
}else if(action == "Copied"){
resetup_ele(history_array);
}else if(action == "Moved"){
pagelayer_move_ele(id, history_array.after_loc);
}
};
if(prev_item_id > current_item_id){
// All Actions for undo here
var i = parseInt(prev_item_id);
for(i; i > current_item_id; i--){
var history_array = pagelayer_history_obj['action_data'][i];
var sub_actions_group = history_array['sub_actions_group'] || '';
// If it has sub-actions
if(!pagelayer_empty(sub_actions_group)){
var j = sub_actions_group.length;
for(j--; j >= 0; j--){
pagelayer_undo_action(sub_actions_group[j]);
}
}
// Main action
pagelayer_undo_action(history_array);
// Activate the current element and scroll it into viewport
var jEle = jQuery('[pagelayer-id="'+history_array.pl_id+'"]');
if(jEle.length > 0){
pagelayer_set_active(jEle);
pagelayer_scroll_to_viewport(jEle, 0);
}
}
}else{
// All Actions for redo here
var i = parseInt(prev_item_id)+1;
for(i; i <= current_item_id; i++){
var history_array = pagelayer_history_obj['action_data'][i];
var sub_actions_group = history_array['sub_actions_group'] || '';
// Main action
pagelayer_redo_action(history_array);
// If it has sub-actions
if(!pagelayer_empty(sub_actions_group)){
for(var x in sub_actions_group){
pagelayer_redo_action(sub_actions_group[x]);
}
}
// Activate the current element and scroll it into viewport
var jEle = jQuery('[pagelayer-id="'+history_array.pl_id+'"]');
if(jEle.length > 0){
pagelayer_set_active(jEle);
pagelayer_scroll_to_viewport(jEle, 0);
}
}
}
};
// Report an error
function pagelayer_error(error, func){
var prefix = func || '';
alert(prefix+error);
};
function pagelayer_bottombar(){
var holder = pagelayer.$$('.pagelayer-bottombar-holder');
var html = '
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
''+
'
'+
'
'+
''+
''+
''+
''+
//''+
'
'+
'
';
holder.html(html);
holder.find('.pagelayer-update-button').on('click', function(){
pagelayer_save();
pagelayer_history_setup();// Setup history tab after update
});
holder.find('.pagelayer-close-button').on('click', function(){
pagelayer_close();
});
holder.find('.screen-mode').on('click', function(){
var screen_mode = jQuery(this).attr('pagelayer-mode-data');
pagelayer_set_screen_mode(screen_mode);
holder.find('.pagelayer-mode-buttons-wrapper').toggle();
});
holder.find('.pagelayer-mode-button').on('click', function(){
holder.find('.pagelayer-mode-buttons-wrapper').toggle();
});
holder.find('.pagelayer-history-icon').click(function(){
pagelayer.$$('.pagelayer-elpd-header').show().find('.pagelayer-elpd-title').text(pagelayer_l('pagelayer_history'));
pagelayer.$$('.pagelayer-logo').hide();
pagelayer_leftbar_tab('pagelayer-history');
pagelayer_active = {};
pagelayer_history_setup();
});
holder.find('.pagelayer-navigator-icon').click(function(){
pagelayer.$$('.pagelayer-elpd-header').show().find('.pagelayer-elpd-title').text(pagelayer_l('pagelayer_navigator'));
pagelayer.$$('.pagelayer-logo').hide();
// If the navigator tab visible, then don't setup
if(!pagelayer.$$('#pagelayer-navigator').is(':visible')){
pagelayer_navigator_setup();
}
pagelayer_leftbar_tab('pagelayer-navigator');
pagelayer_active = {};
});
holder.find('.pagelayer-preview').click(function(){
// If the page is not dirty
if(!pagelayer_isDirty){
// Open in new tab the existing page itself
window.open(pagelayer_post_permalink, '_blank');
return;
}
// Get post content
var post = pagelayer_generate_sc(pagelayer_editable);//alert(post);return;
pagelayer.$$('.pagelayer-body').css({'opacity' : '0.33'});
jQuery.ajax({
url: pagelayer_ajax_url+'&action=pagelayer_create_post_autosave&postID='+pagelayer_postID,
type: 'POST',
data: {
'pagelayer_nonce': pagelayer_ajax_nonce,
'pagelayer_post_content': pagelayer_Base64.encode(post)
},
success: function(data) {
var data = JSON.parse(data);
// If there is some error
if(!pagelayer_empty(data['error']) || pagelayer_empty(data['id'])){
alert('Unable to set preview for some reason');
return;
}
var url = data['url']+'&preview_id='+pagelayer_postID+'&preview_nonce='+
pagelayer_preview_nonce;
// Open in new tab
window.open(url, '_blank');
},
complete: function(){
pagelayer.$$('.pagelayer-body').css({'opacity' : '1'});
}
});
});
};
///////////////////////////////
// Miscellaneuos Functions
///////////////////////////////
// Setup navigator
function pagelayer_navigator_setup(){
var navigator_ele = pagelayer.$$('#pagelayer-navigator'),
navigator_padding = 10,
navigator_html = '';
// Get the child elements list
var pagelayer_create_navi_list = function(selector){
var navigator_list = '';
selector.children('.pagelayer-ele-wrap, .pagelayer-ele').each(function(){
var cEle = jQuery(this),
tag = pagelayer_tag(cEle),
id = pagelayer_id(cEle),
child_ele = false,
ele_class = '';
// If tag is not found then return
if(pagelayer_empty(tag)){
return;
}
// if is row or col or inner-row
if(tag == 'pl_row' || tag == 'pl_col' || tag == 'pl_inner_row'){
ele_class = 'pagelayer-navigator-toggle';
child_ele = true;
}
navigator_list += '
'+
'
'+
''+
pagelayer_shortcodes[tag]['name']+
''+
'
';
// Create the list of child element
if(child_ele){
navigator_padding += 15; // Increment padding left for widget
navigator_list += pagelayer_create_navi_list( cEle.find(pagelayer_shortcodes[tag]['holder']).first() );
navigator_padding -= 15; // Decrement padding left for widget
}
navigator_list += '
';
});
return navigator_list;
}
// Create list of all rows and their child widgets
jQuery(pagelayer_editable).children('.pagelayer-wrap-row').each(function(){
navigator_html += pagelayer_create_navi_list(jQuery(this));
});
// Put the navigator list
navigator_ele.html('
'+navigator_html+'
');
// edit and delete element click handler
navigator_ele.find('.pagelayer-navigator-options .pli').on('click', function(event){
var sEle = jQuery(this).closest('.pagelayer-navigetor-ele');
var sId = sEle.attr('pagelayer-id');
var action = jQuery(this).data('action');
if( action == 'edit'){
pagelayer_edit_element('[pagelayer-id = '+sId+']', event);
}else if(action == 'delete'){
sEle.find('.pagelayer-ele-name').css({'background':'rgb(255, 114, 114)','opacity':'0.5'});
pagelayer_delete_element('[pagelayer-id = '+sId+']');
}
});
// On click toggle the element
navigator_ele.find('.pagelayer-ele-name').on('click', function(){
var tEle = jQuery(this);
var pl_id = tEle.parent().attr('pagelayer-id'); // Get Pagelayer id
var jEle = pagelayer_ele_by_id(pl_id);
// If the class "pagelayer-navigator-toggle" exist then toggle
if(tEle.hasClass('pagelayer-navigator-toggle')){
tEle.parent().toggleClass('pagelayer-navigator-open');
}
// Also open all parents
tEle.parent().parents('.pagelayer-navigetor-ele').addClass('pagelayer-navigator-open');
// Set the click element active
navigator_ele.find('.pagelayer-ele-name').removeClass('pagelayer-navi-active');
tEle.addClass('pagelayer-navi-active')
// Set the element active
if(jEle.length > 0){
//pagelayer_active.el = pagelayer_data(jEle);
pagelayer_set_active(jEle);
pagelayer_scroll_to_viewport(jEle);
}
});
// Do active ele tab open
if( pagelayer_active.el && pagelayer_active.el.id ){
navigator_ele.find('[pagelayer-id="'+pagelayer_active.el.id+'"]').children('.pagelayer-ele-name').click();
}
/* var posY = 0, orig_eleY= 0;
// On mouse down in pagelayer-ele-name
navigator_ele.find('.pagelayer-ele-name').on('mousedown', function(e){
e = e || window.event;
e.preventDefault();
// Get ele position
orig_eleY = jQuery(this).offset().top;
// Get the mouse cursor at startup:
posY = e.clientY;
// The variable needs to be empty.
newMethod = '';
// Mouse up handler
var ele_mousemove = function(){
}
// Mouse move handler
var ele_mouseup = function(){
pagelayer.$$(document).off('mouseup', ele_mouseup);
pagelayer.$$(document).off('mousemove', ele_mousemove);
}
pagelayer.$$(document).on('mouseup', ele_mouseup);
pagelayer.$$(document).on('mousemove', ele_mousemove);
}); */
}
// Scroll page to element view port
function pagelayer_scroll_to_viewport(jEle, timeout, parentEle){
var scrolled = parentEle || jQuery('html, body');
timeout = timeout || 500;
parentEle = parentEle || jQuery(window);
setTimeout(function(){
var parentHeight = parentEle.height(),
parentScrollTop = parentEle.scrollTop(),
elementTop = jEle.offset().top,
topToCheck = elementTop - parentScrollTop;
if (topToCheck > 0 && topToCheck < parentHeight) {
return;
}
var scrolling = elementTop - parentHeight / 2;
scrolled.stop(true).animate({
scrollTop: scrolling
}, 1000);
}, timeout);
}
// Generates a random string of "n" characters
function pagelayer_randstr(n, special){
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
special = special || 0;
if(special){
possible = possible + '$%@';
}
for(var i=0; i < n; i++){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
function pagelayer_update_site_title(val){
if(!pagelayer_empty(val)){
var site_name = jQuery('.pagelayer-wp-title').attr('pagelayer-a-site_name');
if(!pagelayer_empty(site_name)){
var site_title = jQuery.ajax({
url: pagelayer_ajax_url+'&action=pagelayer_fetch_site_title',
type: 'post',
async: false
}).responseText;
if(site_title != site_name){
var site_title = jQuery.ajax({
url: pagelayer_ajax_url+'&action=pagelayer_update_site_title',
type: 'post',
data: {'site_title': site_name},
async: false
}).responseText;
}
}
}
}
// Convert the regular URL of a Video to a Embed URL
function pagelayer_video_url(src){
var youtubeRegExp = /youtube\.com|youtu\.be/;
var vimeoRegExp = /vimeo\.com/;
var match = '';
var videoId = '';
if (youtubeRegExp.exec(src)) {
match = 'youtube';
} else if (vimeoRegExp.exec(src)) {
match = 'vimeo';
}
switch(match){
case 'youtube':
var youtubeRegExp1 = /youtube\.com/;
var youtubewatch = /watch/;
var youtubeembed = /embed/;
var youtube = /youtu\.be/;
if (youtubeRegExp1.exec(src)) {
if (youtubewatch.exec(src)) {
videoId = src.split('?v=');
} else if (youtubewatch.exec(src)) {
videoId = src.split('embed/');
}
} else if (youtube.exec(src)) {
videoId = src.split('.be/');
}
return '//youtube.com/embed/'+videoId[1];
break;
case 'vimeo':
var vimeoplayer = /player\.vimeo\.com/;
var vimeovideo = /video/;
if (vimeoplayer.exec(src) && vimeovideo.exec(src)) {
videoId = src.split('video/');
} else if (vimeoRegExp.exec(src)) {
videoId = src.split('.com/');
}
return '//player.vimeo.com/video/'+videoId[1];
break;
default:
return src;
}
};
// Add widget section
function pagelayer_add_widget(){
html='
'+
''+
''+
'
Click here to add new row OR drag widgets
'+
'
';
jQuery(pagelayer_editable).append(html);
var add_area = jQuery('.pagelayer-add-widget-area');
// Add a code before this
var add_sc = function(tag, global_id = ''){
var attr = '';
if(!pagelayer_empty(global_id)){
attr = ' pagelayer-global-id="'+global_id+'" ';
}
// Create Row
var row = jQuery('');
add_area.before(row);
var row_id = pagelayer_onadd(row, false);
var rEle = pagelayer_ele_by_id(row_id);
if(tag == 'pl_row' && !pagelayer_empty(global_id)){
rEle.click();
return row_id;
}
// Create Column
var col = jQuery('');
rEle.find('.pagelayer-row-holder').append(col);
var col_id = pagelayer_onadd(col, false);
var cEle = pagelayer_ele_by_id(col_id);
if(tag == 'pl_row'){
rEle.click();
return row_id;
}
if(tag == 'pl_col'){
cEle.click();
return col_id;
}
// Create element
var ele = jQuery('');
cEle.find('.pagelayer-col-holder').append(ele);
var id = pagelayer_onadd(ele);
var eEle = pagelayer_ele_by_id(col_id);
// Ensure the column is not empty
pagelayer_empty_col(cEle.find('.pagelayer-col-holder'));
if(tag == 'pl_inner_row' && pagelayer_empty(global_id)){
// Create Column
var in_col = jQuery('');
eEle.find('.pagelayer-row-holder').append(in_col);
var in_col_id = pagelayer_onadd(in_col, false);
}
return id;
}
// Handle Click
add_area.on('click', function(e){
e.stopPropagation();
add_sc('pl_col');
});
// Handle Click
add_area.find('.pagelayer-add-section').on('click', function(e){
e.stopPropagation();
pagelayer_add_section_area();// Setup and show sections modal
});
// Handle Drag over
add_area.on('dragover', function(e){
//console.log(e)
add_area.addClass('pagelayer-add-widget-drag');
});
// Handle Drag Leave
add_area.on('dragleave', function(e){
//console.log(e)
add_area.removeClass('pagelayer-add-widget-drag');
});
// Handle On Drop
add_area.on('drop', function(e){
//console.log(e);
//console.log(e.originalEvent.dataTransfer.getData('tag'));
add_area.removeClass('pagelayer-add-widget-drag');
jQuery('.pagelayer-is-dragging').removeClass('pagelayer-is-dragging');
var tag = e.originalEvent.dataTransfer.getData('tag');
var global_id = e.originalEvent.dataTransfer.getData('global_id');
// Is it an existing element ?
if(tag.length < 1){
return false;
}
e.preventDefault();
//console.log(tag);
add_sc(tag, global_id);
});
};
// Is the element in view while scrolling
function pagelayer_isElementInView(elem, holder, partial) {
partial = partial || true;
var container = jQuery(holder);
var contHeight = container.height();
var contTop = container.scrollTop();
var contBottom = contTop + contHeight ;
var elemTop = jQuery(elem).offset().top - container.offset().top;
var elemBottom = elemTop + jQuery(elem).height();
var isTotal = (elemTop >= 0 && elemBottom <=contHeight);
var isPart = ((elemTop < 0 && elemBottom > 0 ) || (elemTop > 0 && elemTop <= container.height())) && partial;
return isTotal || isPart ;
}
// Append section modal into body
function pagelayer_add_section_area(){
var body = pagelayer.$$('body');
var mEle = body.find('.pagelayer-add-section-modal-container');
if(mEle.length > 0){
mEle.show();
return;
}
var section_modal = '
'+
'
'+
'
'+
'
'+
'
Add Sections
'+
'
Type : '+
''+
'
'+
'
×
'+
'
'+
'
'+
'
'+
'
'+
'×'+
'
'+
''+
'
'+
'
'+
''+
'
'+
'
'+
'
'+
'
'+
'
'+
''+
'
'+
'Please wait a moment'+
'
'+
'
'+
'
'+
'
'+
'
';
mEle = jQuery(section_modal);
// Append the element in the body
body.append(mEle);
// On click close modal
mEle.find('.pagelayer-add-section-modal-close').on('click', function(){
mEle.hide();
});
// Search Empty
mEle.find('.pagelayer-sf-empty').on('click', function(){
mEle.find('.pagelayer-section-search').val('');
});
// On select section type
mEle.find('#pagelayer-section-type').on('change', function(){
var val = jQuery(this).val();
pagelayer_add_sections_list_setup(val);
});
// Append the list items into modal body
pagelayer_add_sections_list_setup();
mEle.show();// Show the modal
};
// Append section list into modal body
function pagelayer_add_sections_list_setup(type){
var mEle = pagelayer.$$('.pagelayer-add-section-modal-container');
var body = mEle.find('.pagelayer-add-section-modal-body');
var add_area = jQuery('.pagelayer-add-widget-area');
type = type || 'section';
// Find the number of cols
var body_width = jQuery(window.parent).width();
var num_cols = 3;
if(body_width >= 1500){
num_cols = 4;
}else if(body_width >= 992){
num_cols = 3;
}else if(body_width >= 768){
num_cols = 2;
}else if(body_width >= 360){
num_cols = 1;
}
//console.log(num_cols+' - '+body_width);
var viewer = '';
var selected_tags = {};
var result_set = {};
// Setup the scroll
mEle.find('.pagelayer-section-tags-holder').slimScroll({
height: 'calc(100vh - 150px)',
railVisible: false,
alwaysVisible: true,
color: '#000',
size: '5px',
});
// Create list of items
var pagelayer_section_list = function(){
// List the tags
if(!pagelayer_empty(pagelayer_add_section_data[type]['tags'])){
var tags_html = '';
var tags = pagelayer_add_section_data[type]['tags'];
for(var k in tags){
tags_html += ''+k+' ('+tags[k].length+')';
}
mEle.find('.pagelayer-section-tags-holder').html(tags_html);
// Handle tag click
mEle.find('.pagelayer-section-tags').unbind('click');
mEle.find('.pagelayer-section-tags').on('click', function(e){
var search = mEle.find('.pagelayer-section-search');
// Blank the search
if(search.val().length > 0){
search.val('');
selected_tags = {};
}
// Fill the selected_tags
tEle = jQuery(this);
var tag = tEle.attr('tag')
if(tEle.attr('on') == '1'){
delete selected_tags[tag];
tEle.removeAttr('on');
}else{
tEle.attr('on', 1);
selected_tags[tag] = 1;
}
// Filter
pagelayer_section_filter(false, 1);
});
}
// Fill in the result
result_set = { ...pagelayer_add_section_data[type]['list']};
show_result();
};
// How the result and setup scroll
var show_result = function(){
var html = '';
for(var i = 0; i < num_cols; i++){
html += '';
}
// Blank the body
body.html(html+viewer);
mEle.find('.pagelayer-section-modal-body-holder').unbind('scroll');
mEle.find('.pagelayer-section-modal-body-holder').on('scroll', pagelayer_section_body_scroll);
pagelayer_section_body_scroll();
}
var scroll_accessed = false;
// Section body ON scroll
var pagelayer_section_body_scroll = function(){
// Check if there is anything to display in the first place, as we do delete pagelayer_add_section_data
if(pagelayer_empty(result_set)){
return;
}
var tester = mEle.find('.pagelayer-section-is-visible');
var modal = mEle.find('.pagelayer-section-modal-body-holder');
// If we have scroll
if(!pagelayer_isElementInView(tester, modal) || scroll_accessed){
return;
}
scroll_accessed = true;
var html = '';
var i = 0;
// Loop result_set
for(var id in result_set){
if(i >= (num_cols * 5)){
break;
}
var col = i % num_cols;
//console.log(col);
i++;
var pro = 0;
// Is it pro ?
if(!pagelayer_empty(result_set[id]) && pagelayer_empty(pagelayer_pro)){
pro = 1;
}
html = '
'+
''+
(pro ? '
Pro
'+pagelayer.pro_txt+'
' : '')+
'
';
body.find('.pagelayer-section-holder[num='+col+']').append(html);
delete result_set[id];
}
//console.log(result_set);
mEle.find('.pagelayer-section-item').unbind('click');
mEle.find('.pagelayer-section-item').on('click', function(e){
pagelayer_section_item_clickable(jQuery(this));
});
scroll_accessed = false;
}
// If we have searched something / or clicked tags
var pagelayer_section_filter = function(event, not_input){
var txt = mEle.find('.pagelayer-section-search').val();
var tags = pagelayer_add_section_data[type]['tags'];
// Searched anything
if(!pagelayer_empty(txt) || pagelayer_empty(not_input)){
// Blank the tags
selected_tags = {};
mEle.find('.pagelayer-section-tags').removeAttr('on');
for(var k in tags){
if(k.search(txt) >= 0){
selected_tags[k] = 1;
mEle.find('.pagelayer-section-tags[tag="'+k+'"]').attr('on', 1);
}
}
}
var new_result = {};
var new_length = 0;
// Filter the content
for(var t in selected_tags){
for(var i in tags[t]){
new_length++;
new_result[tags[t][i]] = tags[t][i];
}
}
// Copy the result
result_set = {...new_result};
//console.log(type);console.log(selected_tags);console.log(result_set);
show_result();
}
// On search change
mEle.find('.pagelayer-section-search').unbind('input');
mEle.find('.pagelayer-section-search').on('input', pagelayer_section_filter);
// On click items
var pagelayer_section_item_clickable = function(jEle){
var section_id = jEle.attr('pagelayer-add-section-id');
// IF section id not found
if(pagelayer_empty(section_id)){
return false;
}
if(jEle.find('.pagelayer-section-pro-req').length > 0){
return false;
}
// Show the overlay
mEle.find('.pagelayer-add-section-modal-overlay').show();
// Do shortcode the content
jQuery.ajax({
url: pagelayer_ajax_url+'&action=pagelayer_get_section_shortcodes&postID='+pagelayer_postID,
type: 'POST',
data: {
'pagelayer_nonce': pagelayer_ajax_nonce,
'pagelayer_section_id': section_id,
'pagelayer-live': 1
},
success: function(data) {
try{
var data = JSON.parse(data);
if(!pagelayer_empty(data['error'])){
alert('Error getting the section');
mEle.find('.pagelayer-add-section-modal-overlay').hide();
mEle.hide();
return;
}
var cEle = jQuery(data['code']);
// Add section before add widget area
add_area.before(cEle);
// We need to it setup
cEle.each(function(){
var pl_id = pagelayer_id(jQuery(this));
if(!pagelayer_empty(pl_id)){
pagelayer_element_setup('[pagelayer-id="'+pl_id+'"], [pagelayer-id='+pl_id+'] .pagelayer-ele', true);
}
});
}catch(e){
alert('Error getting the section');
mEle.find('.pagelayer-add-section-modal-overlay').hide();
mEle.hide();
return;
}
},
complete: function(){
mEle.find('.pagelayer-add-section-modal-overlay').hide();
mEle.hide();
}
});
}
// Load the data if not there
if(!(type in pagelayer_add_section_data)){
// Show the loading
mEle.find('.pagelayer-add-section-modal-overlay').show();
// Get the sections list data and append it
jQuery.ajax({
url: pagelayer_api_url+'/library.php?give='+type,
type: 'post',
success: function(response){
var tmp = JSON.parse(response);
// Is the list there ?
if( !('list' in tmp && !pagelayer_empty(tmp['list'])) ){
return;
}
pagelayer_add_section_data[type] = tmp;
// Create the Type
pagelayer_section_list(type);
// Hide the loading
mEle.find('.pagelayer-add-section-modal-overlay').hide();
},
complete: function(){
mEle.find('.pagelayer-add-section-modal-overlay').hide();
}
});
// We have the data, so show it
}else{
pagelayer_section_list(type);
}
}
// Upload an image
function pagelayer_upload_image(fileName, blob, pagelayer_ajax_func){
var formData = new FormData();
formData.append('action', 'upload-attachment');
formData.append('_ajax_nonce', pagelayer_media_ajax_nonce);
formData.append('async-upload', blob, fileName);
jQuery.ajax({
url:pagelayer_ajax_url,
data: formData,// the formData function is available in almost all new browsers.
type:"post",
contentType:false,
processData:false,
cache:false,
beforeSend: function( xhr ) {
if(typeof pagelayer_ajax_func.beforeSend == 'function'){
pagelayer_ajax_func.beforeSend(xhr);
}
},
xhr: function() {
var xhr = new window.XMLHttpRequest();
if(typeof pagelayer_ajax_func.uploadProgress == 'function'){
xhr = pagelayer_ajax_func.uploadProgress(xhr);
}
return xhr;
},
error:function(err){
//console.error(err);
alert("Unable to upload image for some reason.");
},
success:function(response){
var obj = jQuery.parseJSON(response);
if(typeof pagelayer_ajax_func.success == 'function'){
pagelayer_ajax_func.success(obj);
}
},
complete:function(xhr){
if(typeof pagelayer_ajax_func.complete == 'function'){
pagelayer_ajax_func.complete(xhr);
}
}
});
};
// On editable area image paste handler
function pagelayer_editable_paste_handler(pasteEvent, pagelayer_ajax_func){
var items,
is_Paste = (pasteEvent.type == 'paste' ? true : false),
mustPreventDefault = false,
reader;
try {
if(is_Paste){
items = (pasteEvent.originalEvent || pasteEvent).clipboardData.items;
}else{
items = [pasteEvent];
}
for (var i = items.length - 1; i >= 0; i -= 1) {
if (items[i].type.match(/^image\//)) {
reader = new FileReader();
/* jshint -W083 */
reader.onloadend = function(event) {
var src = event.target.result;
if(src.indexOf('data:image') === 0 ) {
var block = src.split(";");
var contentType = block[0].split(":")[1];
var realData = block[1].split(",")[1];
if(is_Paste){
var fileName = "image."+contentType.split("/")[1];
}else{
var fileName = items[0]['name'];
}
// Convert it to a blob to upload
var blob = pagelayer_b64toBlob(realData, contentType);
pagelayer_upload_image(fileName, blob, pagelayer_ajax_func);
}
};
/* jshint +W083 */
if(is_Paste){
reader.readAsDataURL(items[i].getAsFile());
}else{
reader.readAsDataURL(items[i]);
}
mustPreventDefault = true;
}
}
if(mustPreventDefault && is_Paste){
pasteEvent.stopPropagation();
pasteEvent.preventDefault();
}
}catch(err){
console.log(err);
}
return mustPreventDefault;
}
// Convert base64 to Blob
function pagelayer_b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
// Function to check if the URL is external
function pagelayer_parse_theme_vars(img_url){
for(x in pagelayer_theme_vars){
img_url = img_url.replace(x, pagelayer_theme_vars[x]);
}
return img_url;
};
// Tooltip Setup for Editor
function pagelayer_tooltip_setup(){
//pagelayer.$$('[data-tlite]').each(function(){pagelayer_tlite.show(jQuery(this).get(0));});return;
pagelayer.$$('[data-tlite]').hover(function(){
pagelayer_tlite.show(jQuery(this).get(0));
}, function(){
pagelayer_tlite.hide(jQuery(this).get(0));
});
};
// Pagelayer Messages
function pagelayer_show_msg(msg, time){
time = time || 5000;
var nholder = pagelayer.$$('.pagelayer-editor-notice');
var mEle = jQuery('
');
pagelayer.$$('body').append(dialog);
dialog.find('.pagelayer-btnyes').on('click', function() {
dialog.remove();
if(typeof yesCallback == 'function'){
yesCallback();
}
});
dialog.find('.pagelayer-btnno').on('click', function() {
dialog.remove();
if(typeof noCallback == 'function'){
noCallback();
}
});
dialog.show();
}
function pagelayer_trim(str, charlist){
// discuss at: http://locutus.io/php/trim/
if(typeof str != 'string'){
return str;
}
var whitespace = [' ', '\n', '\r', '\t', '\f', '\x0b', '\xa0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200a', '\u200b', '\u2028', '\u2029', '\u3000' ].join('');
var l = 0;
var i = 0;
str += '';
if (charlist) {
whitespace = (charlist + '').replace(/([[\]().?/*{}+$^:])/g, '$1');
}
l = str.length;
for (i = 0; i < l; i++) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(i);
break;
}
}
l = str.length;
for (i = l - 1; i >= 0; i--) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(0, i + 1);
break;
}
}
return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
};
pagelayer_svg_cache = {};
var pagelayer_document_width;
// For automatic row parent change
jQuery(window).resize(function(){
var new_vw = jQuery(document).width();
if(new_vw == pagelayer_document_width){
return false;
}
pagelayer_document_width = new_vw;
// Set a timeout to prevent bubbling
setTimeout(function(){
jQuery(pagelayer_editable+' .pagelayer-row-stretch-full').each(function(){
var par = jQuery(this).parent();
pagelayer_pl_row_parent_full(par);
});
}, 200);
});
// Render for row
function pagelayer_render_pl_row(el){
var img_urls = !pagelayer_empty(el.tmp['bg_slider-urls']) ? JSON.parse(el.tmp['bg_slider-urls']) : [];
el.atts['slider'] = '';
if(!pagelayer_empty(img_urls)){
for(var x in img_urls){
el.atts['slider'] += '';
}
}
pagelayer_bg_video(el);
}
// Render for inner row
function pagelayer_render_pl_inner_row(el){
pagelayer_render_pl_row(el);
}
// Render for col
function pagelayer_render_pl_col(el){
var img_urls = !pagelayer_empty(el.tmp['bg_slider-urls']) ? JSON.parse(el.tmp['bg_slider-urls']) : [];
el.atts['slider'] = '';
if(!pagelayer_empty(img_urls)){
for(var x in img_urls){
el.atts['slider'] += '';
}
}
// We need the parent of type pagelayer-wrap-col
var par = el.$.parent('.pagelayer-wrap-col');
// Apply to wrapper
if(!pagelayer_empty(el.atts['col'])){
for(var x=1; x<=12; x++){
if(par.hasClass('pagelayer-col-'+x)){
par.removeClass('pagelayer-col-'+x);
break;
}
}
par.addClass('pagelayer-col-'+el.atts['col']);
par.css('width', '');
}
if(el.atts['col_width']){
par.css('width', '');
}
pagelayer_bg_video(el);
}
function pagelayer_bg_video(el){
var youtubeRegExp = /youtube\.com|youtu\.be/;
var vimeoRegExp = /vimeo\.com/;
el.tmp['bg_video_src-url'] = el.tmp['bg_video_src-url'] || el.atts['bg_video_src'];
var src = el.tmp['bg_video_src-url'];
var iframe_src = pagelayer_video_url(el.tmp['bg_video_src-url']);
// Adding mute and loop option in row or col
if(el.atts['mute'] == "true"){
iframe_src +="?&mute=1";
el.atts['mute'] = " muted ";
}else{
iframe_src +="?&mute=0";
el.atts['mute'] = "";
}
if(el.atts['stop_loop'] != "true"){
iframe_src +="&loop=1";
el.atts['stop_loop'] = " loop ";
}else{
iframe_src +="&loop=0";
el.atts['stop_loop'] ="";
}
if (youtubeRegExp.exec(src)) {
var youtubeRegExp1 = /youtube\.com/;
var youtubewatch = /watch/;
var youtubeembed = /embed/;
var youtube = /youtu\.be/;
var videoId;
if (youtubeRegExp1.exec(src)) {
if (youtubewatch.exec(src)) {
videoId = src.split('?v=');
} else if (youtubewatch.exec(src)) {
videoId = src.split('embed/');
}
} else if (youtube.exec(src)) {
videoId = src.split('.be/');
}
//console.log(frame_height);
el.atts['vid_src'] = '';
} else if (vimeoRegExp.exec(src)) {
el.atts['vid_src'] = '';
}else{
el.atts['vid_src'] = '';
}
}
// Load the full width row
function pagelayer_render_end_pl_row(el){
// The parent
var par = el.$.parent();
// Any class with full width
if(el.$.hasClass('pagelayer-row-stretch-full')){
// Give it the full width
pagelayer_pl_row_full(el.$);
// Give full width to the parent
pagelayer_pl_row_parent_full(par);
// Also add that we had a full width
el.$.addClass('pagelayer-row-stretch-had-full');
// Did this row have full width ?
}else if(el.$.hasClass('pagelayer-row-stretch-had-full')){
// Remove style
el.$.removeAttr('style');
par.removeAttr('style');
par.children('.pagelayer-ele-overlay').removeAttr('style');
// Remove HAD class
el.$.removeClass('pagelayer-row-stretch-had-full');
}
pagelayer_pl_row_video(el.$);
el.$.find('.pagelayer-parallax-window img').each(function(){
pagelayer_pl_row_parallax(jQuery(this));
});
el.$.find('.pagelayer-bgimg-slider').each(function(){
pagelayer_pl_row_slider(jQuery(this));
});
// Row shape
if('row_shape_type_top' in el.atts){
pagelayer_render_row_shape(el, 'top')
}
if('row_shape_type_bottom' in el.atts){
pagelayer_render_row_shape(el, 'bottom')
}
}
// Render for inner row
function pagelayer_render_end_pl_inner_row(el){
pagelayer_render_end_pl_row(el);
}
// Set Row parent width
function pagelayer_pl_row_parent_full(par){
var vw = jQuery('html').width();
par.css({'width': vw,'max-width': '100vw'});
par.offset({left: 0});
par.children('.pagelayer-row').css({left: 0});
}
// Row shape render
function pagelayer_render_row_shape(el, shape_pos){
var name = el.atts['row_shape_type_'+shape_pos]+'-'+shape_pos+'.svg';
// DO we have in cache
if(!(name in pagelayer_svg_cache)){
// Make url and fetch
var url = pagelayer_url+'/images/shapes/'+name;
jQuery.get(url, function(data){
el.$.find('.pagelayer-svg-'+shape_pos).html(data);
pagelayer_svg_cache[name] = data;
}, 'html');
// Fill with cache
}else{
el.$.find('.pagelayer-svg-'+shape_pos).html(pagelayer_svg_cache[name]);
}
}
// Load the col
function pagelayer_render_end_pl_col(el){
pagelayer_pl_row_video(el.$);
el.$.find('.pagelayer-parallax-window img').each(function(){
pagelayer_pl_row_parallax(jQuery(this));
});
el.$.find('.pagelayer-bgimg-slider').each(function(){
pagelayer_pl_row_slider(jQuery(this));
});
}
// Render the image object
function pagelayer_render_pl_image(el){
// Decide the image URL
el.atts['func_id'] = el.tmp['id-'+el.atts['id-size']+'-url'] || el.tmp['id-url'];
el.atts['func_id'] = el.atts['func_id'] || el.atts['id'];
// What is the link ?
if('link_type' in el.atts){
// Custom url
if(el.atts['link_type'] == 'custom_url'){
el.atts['func_link'] = el.tmp['link'] || '';
}
// Link to the media file itself
if(el.atts['link_type'] == 'media_file'){
el.atts['func_link'] = el.tmp['id-url'] || el.atts['id'];
}
// Lightbox
if(el.atts['link_type'] == 'lightbox'){
el.atts['func_link'] = el.tmp['id-url'] || el.atts['id'];
}
}
}
// Incase if there is a lightbox
function pagelayer_render_end_pl_image(el){
pagelayer_pl_image(el.$);
}
// Pre DragAndDrop function
function pagelayer_preDAndD_image(jEle){
dropzoneParent = jEle.find('.pagelayer-img').parent();
// Check if drop zone is already there then return
if(dropzoneParent.find('.pagelayer-image-drop-zone').length > 0){
return;
}
var dropDiv = '
'+
'
'+
''+
'
'+pagelayer_l('drop_file')+'
'+
'
'+
''+
'
'+
'
'+
'
';
dropzoneParent.prepend(dropDiv);
dropZone = dropzoneParent.find('.pagelayer-image-drop-zone');
// Inserting values in image drag and drop function
pagelayer_img_dragAndDrop(dropzoneParent, dropZone, jEle, '');
}
// Render for video
function pagelayer_render_pl_video(el){
el.atts['video_overlay_image-url'] = el.tmp['video_overlay_image-'+el.atts['custom_size']+'-url'] || el.tmp['video_overlay_image-url'];
el.atts['video_overlay_image-url'] = el.atts['video_overlay_image-url'] || el.atts['video_overlay_image'];
el.tmp['src-url'] = el.tmp['src-url'] || el.atts['src'];
el.tmp['ele_id'] = el['id'];
el.atts['vid_src'] = pagelayer_video_url(el.tmp['src-url']);
if(el.atts['autoplay'] == "true"){
el.atts['vid_src'] +="?&autoplay=1";
}else{
el.atts['vid_src'] +="?&autoplay=0";
}
if(el.atts['mute'] == "true"){
el.atts['vid_src'] +="&mute=1";
}else{
el.atts['vid_src'] +="&mute=0";
}
if(el.atts['loop'] == "true"){
el.atts['vid_src'] +="&loop=1";
}else{
el.atts['vid_src'] +="&loop=0";
}
}
// Incase if there is a lightbox
function pagelayer_render_end_pl_video(el){
pagelayer_pl_video(el.$);
}
// Render the testimonial
function pagelayer_render_pl_testimonial(el){
if(!pagelayer_empty(el.tmp['avatar-no-image-set'])){
el.atts['avatar'] = '';
return;
}
//console.log(el);
// Decide the image URL
el.atts['func_image'] = el.tmp['avatar-'+el.atts['custom_size']+'-url'] || el.tmp['avatar-url'];
el.atts['func_image'] = el.atts['func_image'] || el.atts['avatar'];
}
// Render the stars
function pagelayer_render_end_pl_stars(el){
pagelayer_stars();
};
// Render the service box
function pagelayer_render_pl_service(el){
// Decide the image URL
el.atts['func_image'] = el.tmp['service_image-'+el.atts['service_image_size']+'-url'] || el.tmp['service_image-url'];
el.atts['func_image'] = el.atts['func_image'] || el.atts['service_image'];
}
function pagelayer_render_end_pl_service(el){
// Drag and Drop function for image
if (typeof pagelayer_preDAndD_image !== "undefined") {
pagelayer_preDAndD_image(el.$);
}
}
function pagelayer_social(jEle,sel){
var holder = jEle.find(sel);
var icon = holder.data('icon');
//alert(icon);
var icon_splited = icon.split(' fa-');
//console.log(icon_splited);
holder.addClass('pagelayer-'+icon_splited[1]);
}
function pagelayer_social_icon_onchange(jEle, row, val){
var url = '';
// Lets get the value of the nearest social icon
for(var k in pagelayer_social_urls){
var patt = new RegExp(k, 'i');
if(patt.test(val)){
url = pagelayer_social_urls[k];
}
}
if(url.length > 0){
var social_url_row = row.parent().find('[pagelayer-elp-name="social_url"]');
//console.log(social_url_row);
social_url_row.find('.pagelayer-elp-link').val(url).trigger('change');
}
}
// Render the social icon
function pagelayer_render_end_pl_social(el){
pagelayer_social(el.$, '.pagelayer-icon-holder');
}
// Render the social profile group
function pagelayer_render_end_pl_social_grp(el){
// Removing extra animation classes
el.$.find('.pagelayer-icon-holder').removeClass (function (index, className) {
return (className.match (/(^|\s)pagelayer-animation-\S+/g) || []).join(' ');
});
pagelayer_pl_social_profile(el.$);
}
// Render the counter
function pagelayer_render_end_pl_counter(el){
pagelayer_counter();
};
// Render the progress
function pagelayer_render_end_pl_progress(el){
pagelayer_progress();
};
// Render the image slider
function pagelayer_render_pl_image_slider(el){
// The URLs
var img_urls = !pagelayer_empty(el.tmp['ids-urls']) ? JSON.parse(el.tmp['ids-urls']) : [];
var all_urls = !pagelayer_empty(el.tmp['ids-all-urls']) ? JSON.parse(el.tmp['ids-all-urls']) : [];
var img_title = !pagelayer_empty(el.tmp['ids-all-titles']) ? JSON.parse(el.tmp['ids-all-titles']) : [];
//console.log(img_urls);
var ul = '';
var is_link = 'link_type' in el.atts && !pagelayer_empty(el.atts['link_type']) ? true : false;
// Create figure HTML
for (var x in img_urls){
// Use the default URL first
var url = img_urls[x];
// But if we have a custom size, use that
if(el.atts['size'] != 'custom' && x in all_urls && el.atts['size'] in all_urls[x]){
url = all_urls[x][el.atts['size']];
}
ul += '
';
if(is_link){
var link = (el.atts['link_type'] == 'media_file' ? url : (el.tmp['link'] || ''))
ul += '';
}
ul += '';
if(is_link){
ul += '';
}
ul += '
';
}
if(pagelayer_empty(ul)){
ul = '
'+ pagelayer_l('Please select Images from left side Widget properties.')+'
';
}
el.atts['ul'] = ul;
// Which arrows to show
if('controls' in el.atts && (el.atts['controls'] == 'arrows' || el.atts['controls'] == 'none')){
el.CSS.attr.push({'sel': '.pagelayer-image-slider-ul', 'val': 'data-pager="false"'});
}
if('controls' in el.atts && (el.atts['controls'] == 'pager' || el.atts['controls'] == 'none')){
el.CSS.attr.push({'sel': '.pagelayer-image-slider-ul', 'val': 'data-controls="false"'});
}
};
// Render the image slider
function pagelayer_render_end_pl_image_slider(el){
pagelayer_owl_destroy(el.$, '.pagelayer-image-slider-ul');
pagelayer_pl_image_slider(el.$);
};
// Render the grid gallery
function pagelayer_render_pl_grid_gallery(el){
// The URLs
var img_urls = !pagelayer_empty(el.tmp['ids-urls']) ? JSON.parse(el.tmp['ids-urls']) : [];
var all_urls = !pagelayer_empty(el.tmp['ids-all-urls']) ? JSON.parse(el.tmp['ids-all-urls']) : [];
var img_title = !pagelayer_empty(el.tmp['ids-all-titles']) ? JSON.parse(el.tmp['ids-all-titles']) : [];
var img_links = !pagelayer_empty(el.tmp['ids-all-links']) ? JSON.parse(el.tmp['ids-all-links']) : [];
var img_captions = !pagelayer_empty(el.tmp['ids-all-captions']) ? JSON.parse(el.tmp['ids-all-captions']) : [];
//console.log(img_urls);
var ul = '';
var pagin = '
1
';
var is_link = 'link_to' in el.atts && !pagelayer_empty(el.atts['link_to']) ? true : false;
var i = 0;
var j = 1;
if(pagelayer_empty(el.tmp)){
ul = '
';
var gallery_rand = 'gallery-id-'+Math.floor((Math.random() * 100) + 1);
var imgInPage = el.atts['images_no'];
// Create figure HTML
for (var x in img_urls){
if(imgInPage != 0 && (i % imgInPage) == 0 && i != 0){
ul += '
';
j++;
pagin += '
'+j+'
';
}
// Use the default URL first
var url = img_urls[x];
// But if we have a custom size, use that
if(el.atts['size'] != 'custom' && x in all_urls && el.atts['size'] in all_urls[x]){
url = all_urls[x][el.atts['size']];
}
ul += '
';
}
// Required classes for particular rotate
el.atts['rotate_req'] = '';
var letters = ['pagelayer-aheading-rotate2','pagelayer-aheading-rotate3','type','pagelayer-aheading-scale'];
if(jQuery.inArray(el.atts['animations'], letters) != -1){
el.atts['rotate_req'] = 'letters ';
}
if(el.atts['animations'] == 'pagelayer-aheading-clip'){
el.atts['rotate_req'] = 'is-full-width ';
}
}
// Render animated heading
function pagelayer_render_end_pl_anim_heading(el){
var jEle = el.$;
pagelayer_anim_heading(jEle);
}
// Mega Menu popup handler
pagelayer_add_action('pagelayer_setup_history', function(){
if(!('pagelayer_template_type' in pagelayer_post && pagelayer_post['pagelayer_template_type'] == 'menu')){
return;
}
jQuery(pagelayer_editable).wrap('
'+'
');
pagelayer.$$('.pagelayer-settings-icon').attr("pagelayer-tag", "pl_mega_menu");
pagelayer.$$(".pagelayer-settings-icon").click();
pagelayer_mega_menu(jQuery('.pagelayer-mega-menu-editor'), pagelayer_post['ID']);
});
// Mega menu function place content editable in the menu
function pagelayer_mega_menu(mEle, postId){
var mainEle = jQuery('.pagelayer-mega-menu [menu-id="'+postId+'"]');
mainEle.empty();
mainEle.append(mEle);
mainEle.parents('.pagelayer-mega-menu').show();
}
////////////////
// Freemium End
////////////////
// The active pagelayer element
var pagelayer_active = {};
// List of pagelayer icons
var pagelayer_icons = {};
// The inline editor
var pagelayer_editor = {};
// The active pagelayer element
var pagelayer_active_tab = {};
// Loads the Data
function pagelayer_data(jEle, clean){
var ret = new Object();
// Get the data
ret.tag = pagelayer_tag(jEle);
ret.id = pagelayer_id(jEle);;
ret.$ = jEle;
// Parse the attributes
ret.atts = new Object();
ret.tmp = new Object();
jQuery.each(jEle[0].attributes, function(index, att){
if(att.name.match(/pagelayer\-a\-/i)){
ret.atts[att.name.substr(12)] = att.value;
}
if(att.name.match(/pagelayer\-tmp\-/i)){
ret.tmp[att.name.substr(14)] = att.value;
}
});
//console.log(ret.atts);
//console.log(ret.tmp);
clean = clean || false;
// Remove values which have 'req'. NOTE : 'show' ones will be allowed
if(clean){
var tag = ret.tag;
// Anything to set ?
ret.set = {};
// Function to clear any att data
var pagelayer_delete_atts = function(x){
delete ret.atts[x];
delete ret.atts[x+'_tablet'];// Any tablet and mobile values as well
delete ret.atts[x+'_mobile'];
delete ret.set[x];
}
// All props
var all_props = pagelayer_shortcodes[tag];
// Loop through all props
for(var i in pagelayer_tabs){
var tab = pagelayer_tabs[i];
for(var section in all_props[tab]){
var props = section in pagelayer_shortcodes[tag] ? pagelayer_shortcodes[tag][section] : pagelayer_styles[section];
// In case of widgets its possible !
if(pagelayer_empty(props)){
continue;
}
for(var x in props){
var prop = props[x];
// Any prop to skip ?
if(!pagelayer_empty(all_props['skip_props']) && jQuery.inArray(x, all_props['skip_props']) > -1){
pagelayer_delete_atts(x);
continue;
}
// Are we to set this value ?
if(!(x in ret.atts) && 'default' in prop && !pagelayer_empty(prop['default'])){
// We need to make sure its not a PRO value
if(!('pro' in prop && pagelayer_empty(pagelayer_pro))){
var tmp_val = prop['default'];
// If there is a unit and there is no unit suffix in atts value
if('units' in prop){
if(jQuery.isNumeric(prop['default'])){
tmp_val = prop['default']+prop['units'][0];
}else{
var sep = 'sep' in prop ? prop['sep'] : ',';
var tmp2 = prop['default'].split(sep);
for(var k in tmp2){
if(jQuery.isNumeric(tmp2[k])){
tmp2[k] = tmp2[k]+prop['units'][0];
}
}
tmp_val = tmp2.join(sep);
}
}
//console.log(x+' - '+tmp_val);
ret.set[x] = tmp_val;
}
}
if(!('req' in prop)){
continue;
}
//console.log('[pagelayer_data] Cleaning :'+x);
// List of considerations
var show = prop['req'];
// We will hide by default
var toShow = true;
for(var showParam in show){
var reqval = show[showParam];
var except = showParam.substr(0, 1) == '!' ? true : false;
showParam = except ? showParam.substr(1) : showParam;
var val = ret.atts[showParam] || '';
//console.log('Show '+x+' '+showParam+' '+reqval+' '+val);
// Is the value not the same, then we can show
if(except){
if(typeof reqval == 'string' && reqval == val){
toShow = false;
break;
}
// Its an array and a value is found, then dont show
if(typeof reqval != 'string' && reqval.indexOf(val) > -1){
toShow = false;
break;
}
// The value must be equal
}else{
if(typeof reqval == 'string' && reqval != val){
toShow = false;
break;
}
// Its an array and no value is found, then dont show
if(typeof reqval != 'string' && reqval.indexOf(val) === -1){
toShow = false;
break;
}
}
}
// Are we to show ?
if(!toShow){
//console.log('Delete : '+x);
pagelayer_delete_atts(x);
}
}
}
}
}
return ret;
};
// Setup the properties
function pagelayer_elpd_setup(){
// The Dialag box of the element properties
// pagelayer-ELPD - Element Properties Dialog
pagelayer_elpd_html = '
'+
'
Settings
'+
//'
Style
'+
'
Options
'+
'
'+
''+
''+
'
'+
'
'+
''+
'';
// Create the dialog box
pagelayer.$$('#pagelayer-elpd').append(pagelayer_elpd_html);
pagelayer_elpd = pagelayer.$$('#pagelayer-elpd');
pagelayer.$$('.pagelayer-elpd-close').on('click', function(){
pagelayer_leftbar_tab('pagelayer-shortcodes');
pagelayer.$$('.pagelayer-elpd-header').hide();
pagelayer.$$('.pagelayer-logo').show();
pagelayer.$$('.pagelayer-elpd-body').removeAttr('pagelayer-element-id').empty();
pagelayer_active = {};
});
// Copy
pagelayer.$$('.pagelayer-elpd-options>.pli-clone').on('click', function(){
pagelayer_copy_element(pagelayer_active.el.$);
});
// Delete
pagelayer.$$('.pagelayer-elpd-options>.pli-trashcan').on('click', function(){
pagelayer_delete_element(pagelayer_active.el.$);
//pagelayer.$$('.pagelayer-elpd-close').click();
});
// The tabs
pagelayer_elpd.find('.pagelayer-elpd-tab').on('click', function(){
var attr = 'pagelayer-elpd-active-tab';
pagelayer_elpd.find('.pagelayer-elpd-tab').each(function(){
jQuery(this).removeAttr(attr);
});
jQuery(this).attr(attr, 1);
// Trigger the showing of rows
pagelayer_elpd_show_rows();
});
};
// Open the properties
function pagelayer_elpd_open(jEle){
// Set pagelayer history FALSE
pagelayer.history_action = false;
// Set the position of the element and show
//pagelayer_elpd.css('left', pagelayer_elpd_pos[0]);
//pagelayer_elpd.css('top', pagelayer_elpd_pos[1]);
pagelayer_leftbar_tab('pagelayer-elpd');
pagelayer.$$('[pagelayer-elpd-tab=settings]').show();
pagelayer.$$('.pagelayer-elpd-header').show();
pagelayer.$$('.pagelayer-logo').hide();
// The property holder
var holder = pagelayer.$$('.pagelayer-elpd-body');
holder.html(' ');
var el = pagelayer_elpd_generate(jEle, holder);
// Set the active element
pagelayer_active.el = el;
// Set the header
pagelayer.$$('.pagelayer-elpd-title').html('Edit '+pagelayer_shortcodes[el.tag]['name']);
// Set pagelayer history TRUE
pagelayer.history_action = true;
// Render tooltips for the ELPD
pagelayer_tooltip_setup();
};
// Show the properties window
function pagelayer_elpd_generate(jEle, holder){
// Get the id, tag, atts, data, etc
var el = pagelayer_data(jEle);
//console.log(el);
// Is it a valid type ?
if(pagelayer_empty(pagelayer_shortcodes[el.tag])){
pagelayer_error('Could not find this shortcode : '+el.tag);
}
// Set the holder
holder.attr('pagelayer-element-id', el.id);
//console.log(el.id);
var all_props = pagelayer_shortcodes[el.tag];
var sec_open_class = 'pagelayer-elpd-section-open';
for(var i in pagelayer_tabs){
var tab = pagelayer_tabs[i];
var section_close = false;// First section always open
for(var section in all_props[tab]){
//console.log(tab+' '+section);
var props = section in pagelayer_shortcodes[el.tag] ? pagelayer_shortcodes[el.tag][section] : pagelayer_styles[section];
//console.log(props);
var sec = jQuery('
'+
'
'+all_props[tab][section]+'
'+
''+
'
');
holder.append(sec);
// The row holder
sec = sec.find('.pagelayer-elpd-section-rows');
// Close all except the first section
if(section_close){
sec.hide().prev().removeClass(sec_open_class);
}
section_close = true;
if('widget' in all_props && section == 'params'){
pagelayer_elpd_widget_settings(el, sec, true);
continue;
}
var mode = pagelayer_get_screen_mode();
// Reset / Create the cache
for(var x in props){
props[x]['c'] = new Object();
props[x]['c']['val'] = '';// Blank Val
props[x]['c']['name'] = x;// Add the Name of the row i.e. attribute of the element
var prop_name = x;
// Do we have screen ?
if('screen' in props[x] && mode != 'desktop'){
prop_name = x +'_'+mode;
}
// Set default to value of attribute if any
if(prop_name in el.atts){
props[x]['c']['val'] = el.atts[prop_name];
}
// Set element
props[x]['el'] = el;
// Any prop to skip ?
if(!pagelayer_empty(all_props['skip_props']) && jQuery.inArray(x, all_props['skip_props']) > -1){
continue;
}
// Add the row
pagelayer_elpd_row(sec, tab, section, props, x);
}
// Hide empty sections
if(sec.html().length < 1){
//console.log(section+' - '+sec.html().length);
sec.parent().remove();
}
}
}
/*// Set the default values in the PROPERTIES
var fn_load = window['pagelayer_load_elp_'+el.tag];
if(typeof fn_load == 'function'){
fn_load(el, props);
}*/
// Hide clone and delete options
if(!pagelayer_empty(all_props['hide_active'])){
pagelayer.$$('.pagelayer-elpd-options').addClass('pagelayer-hidden');
}else{
pagelayer.$$('.pagelayer-elpd-options').removeClass('pagelayer-hidden');
}
// Section open close
holder.find('>.pagelayer-elpd-section>.pagelayer-elpd-section-name').on('click', function(){
var _sec = jQuery(this);
var par = _sec.parent();
pagelayer_active_tab.id = el.id;
pagelayer_active_tab.section = par.attr('section');
// Get the active tab
var active_tab = pagelayer_elpd.find('[pagelayer-elpd-active-tab]').attr('pagelayer-elpd-tab');
// Close all but dont touch yourself
holder.children().each(function (){
var curSec = jQuery(this);
if(par.is(curSec)) return;// Skip the current option
if(curSec.attr('pagelayer-show-tab') != active_tab) return;// Skip the non active tabs as is
curSec.find('.pagelayer-elpd-section-rows').hide().prev().removeClass(sec_open_class);
});
// Now toggle your self
par.find('.pagelayer-elpd-section-rows').toggle();
if(_sec.next().is(':visible')){
_sec.addClass(sec_open_class);
}else{
_sec.removeClass(sec_open_class);
}
});
if(!pagelayer_empty(pagelayer_active_tab) && pagelayer_active_tab.id == el.id){
holder.find('>[section='+pagelayer_active_tab.section+']>.pagelayer-elpd-section-name').click();
}
// Handle the showing of rows
pagelayer_elpd_show_rows();
return el;
};
// Show a row
function pagelayer_elpd_row(holder, tab, section, props, name){
// The Prop
var prop = props[name];
//console.log(tab+' '+name+' '+prop.el.tag);
var fn = window['pagelayer_elp_'+prop['type']];
if(typeof fn == 'function'){
var row = jQuery('');
// Append the row
holder.append(row);
if('group' in prop){
row.attr('pagelayer-access-item', prop.group);
}
var fn_ui = window['pagelayer_elp_'+prop['type']+'_ui'];
// Is there a UI Handler ?
if(typeof fn_ui == 'function'){
fn_ui(row, prop);
// Use the default mechanism
}else{
// The label
pagelayer_elp_label(row, prop);
// The main property
fn(row, prop);
// Is there a description ?
if(!pagelayer_empty(prop['desc'])){
pagelayer_elp_desc(row, prop['desc']);
}
}
return row;
}
};
// Show the rows as per the active tab and also handle the rows that are supposed to be shown or not
function pagelayer_elpd_show_rows(){
//console.log('Called');
// Get the active tab
var active_tab = pagelayer_elpd.find('[pagelayer-elpd-active-tab]').attr('pagelayer-elpd-tab');
pagelayer_elpd.find('[pagelayer-show-tab]').each(function(){
var sec = jQuery(this);
// Is it the active tab ?
if(sec.attr('pagelayer-show-tab') != active_tab){
sec.hide();
}else{
sec.show();
}
});
// Find all Elements in the Property dialog and loop
pagelayer_elpd.find('[pagelayer-element-id]').each(function(){
var holder = jQuery(this);
var id = holder.attr('pagelayer-element-id');
var jEle = pagelayer_ele_by_id(id);
var tag = pagelayer_tag(jEle);
//console.log('Main : '+id+' - '+tag);
//console.log(pagelayer_active);
// All props
var all_props = pagelayer_shortcodes[tag];
// Loop through all props
for(var i in pagelayer_tabs){
var tab = pagelayer_tabs[i];
for(var section in all_props[tab]){
var props = section in pagelayer_shortcodes[tag] ? pagelayer_shortcodes[tag][section] : pagelayer_styles[section];
for(var x in props){
var prop = props[x];
// If the prop is a group, we continue
if(prop['type'] == 'group'){
continue;
}
// Find the row
var row = false;
holder.find('[pagelayer-elp-name='+x+']').each(function(){
var j = jQuery(this);
var _id = j.closest('[pagelayer-element-id]').attr('pagelayer-element-id');
//console.log(_id+' = '+id);
// Is the parent the same ?
if(_id == id){
row = j;
}
});
// Do you have a show or hide ?
if(!row){
//console.log('Not Found : '+x+' - '+id);
continue;
}
// Is the row visible ?
if(row.closest('[pagelayer-show-tab]').attr('pagelayer-show-tab') != active_tab){
row.hide();
continue;
}
// Now lets show or hide the element
if(!('req' in prop || 'show' in prop)){
row.show();
continue;
}
// List of considerations
var show = {};
// We have both req and show, so lets just combine the values and then show
// NOTE : We need to make an array and not just merge the 2 as they are references
if('req' in prop && 'show' in prop){
// Add the req values
show = JSON.parse(JSON.stringify(prop['req']));
// Now the show values need to be looped
for(var t in prop['show']){
show[t] = prop['show'][t];
}
}else{
show = 'req' in prop ? prop['req'] : prop['show'];
}
// We will hide by default
var toShow = true;
for(var showParam in show){
var reqval = show[showParam];
var except = showParam.substr(0, 1) == '!' ? true : false;
showParam = except ? showParam.substr(1) : showParam;
var val = pagelayer_get_att(jEle, showParam) || '';
//console.log('Show '+x+' '+showParam+' '+reqval+' '+val);
// Is the value not the same, then we can show
if(except){
if(typeof reqval == 'string' && reqval == val){
toShow = false;
break;
}
// Its an array and a value is found, then dont show
if(typeof reqval != 'string' && reqval.indexOf(val) > -1){
toShow = false;
break;
}
// The value must be equal
}else{
if(typeof reqval == 'string' && reqval != val){
toShow = false;
break;
}
// Its an array and no value is found, then dont show
if(typeof reqval != 'string' && reqval.indexOf(val) === -1){
toShow = false;
break;
}
}
}
// Are we to show ?
if(toShow){
row.show();
}else{
row.hide();
}
}
}
}
});
};
var pagelayer_widget_timer;
var pagelayer_widget_cache = {};
// Load the widget settings
function pagelayer_elpd_widget_settings(el, sec, onfocus){
var show_form = function(html){
sec.html('');
// Handle on form data change
sec.find('form :input').on('change', function(){
//console.log('Changed !');
// Clear any previous timeout
clearTimeout(pagelayer_widget_timer);
// Set a timer for constant change
pagelayer_widget_timer = setTimeout(function(){
pagelayer_elpd_widget_settings(el, sec);
//console.log('Calling');
}, 500);
});
}
// Is it onfocus ?
onfocus = onfocus || false;
// Its an onfocus
if(onfocus && el.id in pagelayer_widget_cache){
show_form(pagelayer_widget_cache[el.id]);
return true;
}
var post = {};
post['action'] = 'pagelayer_wp_widget';
post['pagelayer_nonce'] = pagelayer_ajax_nonce;
post['tag'] = el.tag;
post['pagelayer-id'] = el.id;
// Any atts ?
if('widget_data' in el.atts){
post['widget_data'] = el.atts['widget_data'];
}
// Post any existing data
var form = sec.find('form');
// Archive widget checkbox fix
var inputCheckbox = form.find('input[type=checkbox]');
for(var i=0; i 0){
//console.log(form.serialize());
post['values'] = form.serialize();
}
jQuery.ajax({
url: pagelayer_ajax_url,
type: 'post',
data: post,
success: function(data) {
//console.log('Widget Data');console.log(data);
// Show the form
if('form' in data){
show_form(data['form']);
// Store in cache
pagelayer_widget_cache[el.id] = data['form'];
}
// Show the content
if('html' in data){
el.$.html(data['html']);
pagelayer_sc_render(el.$);// Re-Render the CSS
}
// Any set attributes ?
if('widget_data' in data){
pagelayer_set_atts(el.$, 'widget_data', JSON.stringify(data['widget_data']));
}
},
fail: function(data) {
alert('Some error occured in getting the widget data');
}
});
}
// Will set the attribute and also render
function _pagelayer_set_atts(row, val, no_default){
var id = row.closest('[pagelayer-element-id]').attr('pagelayer-element-id');
var jEle = jQuery('[pagelayer-id='+id+']');
var tag = pagelayer_tag(jEle);
var prop_name = row.attr('pagelayer-elp-name');
// Is there a unit ?
var uEle = row.find('.pagelayer-elp-units');
if(uEle.length > 0){
var unit = uEle.find('[selected]').html();
if(Array.isArray(val)){
for(var i in val){
if(val[i].length < 1){
continue;
}
val[i] = val[i]+unit;
}
}else{
val = val+unit;
}
}
// Are we in another mode ?
var mEle = row.find('.pagelayer-elp-screen');
var mode = mEle.length > 0 && pagelayer_get_screen_mode() != 'desktop' ? '_'+pagelayer_get_screen_mode() : '';
pagelayer_set_atts(jEle, prop_name+mode, val);
// Are we to skip setting defaults ?
no_default = no_default || false;
if(!no_default){
// We need to set defaults for dependents
var hasSet = pagelayer_set_default_atts(jEle, 5);
// We need to reopen the left panel
// Note : If two simultaneous calls are made, then this will cause problems
// Also after this is called, ROW is destroyed and no other row related stuff will work i.e. set_atts in the same calls will fail
if(hasSet){
pagelayer_elpd_open(jEle);
}
}
//console.trace();console.log('Setting Attr');
// Render
pagelayer_sc_render(jEle);
if('onchange' in pagelayer.props_ref[tag][prop_name]){
var fn = window[pagelayer.props_ref[tag][prop_name]['onchange']];
if(typeof fn === 'function'){
fn(jEle, row, val);
}
}
};
// Will set the attribute but not render
function _pagelayer_set_tmp_atts(row, suffix, val){
var id = row.closest('[pagelayer-element-id]').attr('pagelayer-element-id');
var jEle = jQuery('[pagelayer-id='+id+']');
pagelayer_set_tmp_atts(jEle, row.attr('pagelayer-elp-name')+(suffix.length > 0 ? '-'+suffix : ''), val);
};
// Will clear the attribute but not render
function _pagelayer_clear_tmp_atts(row){
var id = row.closest('[pagelayer-element-id]').attr('pagelayer-element-id');
var jEle = jQuery('[pagelayer-id='+id+']');
pagelayer_clear_tmp_atts(jEle, row.attr('pagelayer-elp-name'));
};
// Get the tmp att
function _pagelayer_get_tmp_att(row, suffix){
var id = row.closest('[pagelayer-element-id]').attr('pagelayer-element-id');
var jEle = jQuery('[pagelayer-id='+id+']');
return pagelayer_get_tmp_att(jEle, row.attr('pagelayer-elp-name')+'-'+suffix);
};
// Create the Label
function pagelayer_elp_label(row, prop){
row.append('');
var label = row.children('.pagelayer-elp-label-div');
// Do we have screen ?
if('screen' in prop){
var mode = pagelayer_get_screen_mode();
var screen = '
'+
''+
''+
''+
''+
'
';
label.append(screen);
// Set screen mode on change
label.find('.pli:not(.pagelayer-prop-screen)').on('click', function(){
var mode = 'desktop';
var jEle = jQuery(this);
// Tablet ?
if(jEle.hasClass('pli-tablet')){
mode = 'tablet';
}
// Mobile ?
if(jEle.hasClass('pli-mobile')){
mode = 'mobile';
}
pagelayer_set_screen_mode(mode);
label.find('.pagelayer-elp-screen .pli').removeClass('open');
});
// On change of screen handle the values
label.find('.pagelayer-elp-screen').on('pagelayer-screen-changed', function(e){
label.find('.pagelayer-elp-screen .pli').removeClass('open');
var mode = pagelayer_get_screen_mode();
var modes = {desktop: '', tablet: '_tablet', mobile: '_mobile'};
// Get the current current new val
prop.c['val'] = pagelayer_get_att(prop.el.$, prop.c['name']+modes[mode]);
// Handle the amount
if(pagelayer_empty(prop.c['val'])){
prop.c['val'] = '';
}
// Remove the siblings
label.siblings().each(function(){
var j = jQuery(this);
if(j.hasClass('pagelayer-elp-desc')){
return;
}
j.remove();
});
// Create the vals again
var fn = window['pagelayer_elp_'+prop['type']];
// The main property
fn(row, prop);
});
label.find('.pagelayer-elp-screen .pagelayer-prop-screen').on('click', function(e){
jQuery(this).siblings().toggleClass('open');
})
}
// Do we have pro version requirement ?
if('pro' in prop && pagelayer_empty(pagelayer_pro)){
var txt = prop['pro'].length > 1 ? prop['pro'] : pagelayer.pro_txt;
var pro = jQuery('
Pro
');
pro.attr('data-tlite', txt);
label.append(pro);
}
// Do we have units ?
if('units' in prop){
var units = '';
var tmp_val = prop.c['val'];
var default_unit = 0;
// Get unit from value
if(!(pagelayer_empty(tmp_val))){
for(var i in prop['units']){
if(tmp_val.search(prop['units'][i]) != -1){
default_unit = i;
}
}
}
for(var i in prop['units']){
units += ''+prop['units'][i]+'';
}
label.append('
'+units+'
');
// Set unit on change
label.find('.pagelayer-elp-units span').on('click', function(){
label.find('.pagelayer-elp-units span').each(function(){
jQuery(this).removeAttr('selected');
});
jQuery(this).attr('selected', 1);
});
}
};
// Create the Description
function pagelayer_elp_desc(row, label){
row.append('
'+label+'
');
};
// The Text property
function pagelayer_elp_text(row, prop){
var div = '
'+
''+
'
';
row.append(div);
row.find('input').on('input', function(){
_pagelayer_set_atts(row, jQuery(this).val());// Save and Render
});
};
// The Select property
function pagelayer_elp_select(row, prop){
var options = '';
var option = function(val, lang){
var selected = (val != prop.c['val']) ? '' : 'selected="selected"';
return '';
}
for (x in prop['list']){
// Single item
if(typeof prop['list'][x] == 'string'){
options += option(x, prop['list'][x]);
// Groups
}else{
options += '';
}
}
var div = '
'+
''+
'
';
row.append(div);
row.find('select').on('change', function(){
var sEle = jQuery(this);
if(sEle.attr('name') == "animation"){
_pagelayer_trigger_anim(row, sEle.val());
}
_pagelayer_set_atts(row, sEle.val());// Save and Render
});
}
// The MultiSelect property
function pagelayer_elp_multiselect(row, prop){
var selection = [];
if(!pagelayer_empty(prop.c['val'])){
//selection = JSON.parse(prop.c['val']);
selection = prop.c['val'].split(',');
}
var options = '';
var option = function(val, lang){
var selected = (jQuery.inArray(val,selection) == -1 ? '' : 'selected="selected"');
return '
'+lang+'
';
}
var show_sel = function(val){
var sel_html = '';
jQuery.each(val, function(index, value){
sel_html += ''+prop['list'][value]+' x';
});
return sel_html;
}
var setup_remove = function(){
row.find('.pagelayer-elp-multiselect-remove').on('click', function(){
var sVal = jQuery(this).parent().attr('data-val');
row.find('.pagelayer-elp-multiselect-option[data-val='+sVal+']').click();
});
}
for (x in prop['list']){
options += option(x, prop['list'][x]);
}
var div = '
'+
'
'+show_sel(selection)+'
'+
'
'+options+'
'+
'
';
row.append(div);
setup_remove();
row.find('.pagelayer-elp-multiselect-option').on('click', function(){
var sVal = jQuery(this).attr('data-val');
if(jQuery.inArray(sVal,selection) == -1){
selection.push(sVal);
row.find('[data-val="'+sVal+'"]').attr('selected','selected');
}else{
selection.splice(jQuery.inArray(sVal,selection),1);
row.find('[data-val="'+sVal+'"]').removeAttr('selected');
}
//_pagelayer_set_atts(row,JSON.stringify(selection));// Save and Render
_pagelayer_set_atts(row, selection.join(','));// Save and Render
row.find('.pagelayer-elp-multiselect').html(show_sel(selection));
setup_remove();
});
// Open the selector
row.find('.pagelayer-elp-multiselect').on('click', function(){
row.find('.pagelayer-elp-multiselect-ul').slideToggle(100);
});
}
function _pagelayer_trigger_anim(row, anim){
var id = row.closest('[pagelayer-element-id]').attr('pagelayer-element-id');
var classList = jQuery('[pagelayer-id='+id+']').attr('class');
classList = classList.split(/\s+/);
//console.log(classList);
var options = [];
row.find('option').each(function(){
var found = jQuery.inArray( jQuery(this).val(), classList );
if( found != -1){
//var found = jQuery(this).val();
jQuery('[pagelayer-id='+id+']').removeClass(jQuery(this).val());
//break;
}
//options.push(jQuery(this).val());
});
jQuery('[pagelayer-id='+id+']').removeClass('pagelayer-wow').addClass(anim + ' animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
jQuery(this).removeClass(anim+ ' animated');
});
}
// The Checkbox property
function pagelayer_elp_checkbox(row, prop){
var div = '
'+
''+
'
';
row.append(div);
if(prop.c['val'].length > 0){
row.find('input').attr('checked', 'checked');
}else{
row.find('input').removeAttr('checked');
}
// When the change is called
row.find('input').on('change', function(){
// We set to string true or false
var val = jQuery(this).is(':checked') ? 'true' : '';
_pagelayer_set_atts(row, val);// Save and Render
});
}
// The Radio property
function pagelayer_elp_radio(row, prop){
var active = 'pagelayer-elp-radio-active';
var div = '
';
for(var x in prop.list){
var addclass = (prop.c['val'] == x) ? active : '';
div += ''+prop.list[x]+'';
}
div += '
';
row.append(div);
row.find('.pagelayer-elp-radio').each(function(){
jQuery(this).on('click', function (){
// Remove existing active class
jQuery(this).parent().find('.'+active).removeClass(active);
// Set active
jQuery(this).addClass(active);
_pagelayer_set_atts(row, jQuery(this).attr('val'));// Save and Render
});
});
}
// The Image Property
function pagelayer_elp_image(row, prop){
var style = '';
var tmp = prop.c['name']+'-url';
var def = pagelayer.blank_img;
var src = (tmp in prop.el.tmp) ? prop.el.tmp[tmp] : def;
// Do we have a URL set ?
style = 'style="background-image:url(\''+src+'\')"';
var div = '
'+
'
'+
'
'+
''+
'
'+pagelayer_l('drop_file')+'
'+
'
'+
''+
'
'+
'
'+
'
'+
''+
'
'+
'
';
row.append(div);
// Set an Image
row.find('.pagelayer-elp-image').on('click', function(){
var button = jQuery(this);
// Load the frame
var frame = pagelayer_select_frame('image');
// On select update the stuff
frame.on({
'select': function(){
var state = frame.state();
var id = url = '';
// External URL
if('props' in state){
id = url = pagelayer_parse_theme_vars(state.props.attributes.url);
// Internal from gallery
}else{
var attachment = frame.state().get('selection').first().toJSON();
//console.log(attachment);
// Set the new ID and URL
id = attachment.id;
url = attachment.url;
// To remove past temp attr so that they are not involve in future temp values
_pagelayer_clear_tmp_atts(row);
// Keep a list of all sizes
for(var x in attachment.sizes){
_pagelayer_set_tmp_atts(row, x+'-url', attachment.sizes[x].url);
}
}
// Update thumbnail
button.css('background-image', 'url(\''+url+'\')');
// Save and render
_pagelayer_set_tmp_atts(row, 'url', url);
_pagelayer_set_atts(row, id);
},
// On open select the appropriate images in the media manager
'open': function() {
var selection = frame.state().get('selection');
var wp_id = prop.el.$.attr('pagelayer-a-id');
selection.reset( wp_id ? [ wp.media.attachment( wp_id ) ] : [] );
}
});
frame.open(button);
return false;
});
// Finding and assigning values in the variables
var dropzoneParent = row.find('.pagelayer-elp-image-div');
var dropZone = row.find('.pagelayer-elp-drop-zone');
// Inserting values in image drag and drop function
pagelayer_img_dragAndDrop(dropzoneParent, dropZone, '', row);
// Delete this
row.find('.pagelayer-elp-image-delete').on('click', function(){
// Update thumbnail
row.find('.pagelayer-elp-image').css('background-image', 'url(\''+def+'\')');
// Set to blank and render
_pagelayer_set_atts(row, '', true);
_pagelayer_set_tmp_atts(row, 'no-image-set', 1);
_pagelayer_set_tmp_atts(row, 'url', def);
_pagelayer_set_atts(row, def);
});
}
// Main image drag and drop function
function pagelayer_img_dragAndDrop(dropzoneParent, dropZone, jEle, row){
var reset_dragging = false;
dropzoneParent.on('dragover', function(e){
e.preventDefault();
// Checking that the dragged element is a file or not
var dt = e.originalEvent.dataTransfer;
if(dt.types && (dt.types.indexOf ? dt.types.indexOf('Files') != -1 : dt.types.contains('Files'))){
if(e.originalEvent.dataTransfer.items[0].type.search('image/')!=-1){
dropZone.show();
reset_dragging = true;
}
}
});
dropzoneParent.on('dragleave', function(e){
var rect = this.getBoundingClientRect();
// Checking that the cursor is in the drag area or not
if (e.clientX >= (rect.left + rect.width) || e.clientX <= rect.left || e.clientY >= (rect.top + rect.height) || e.clientY <= rect.top) {
dropZone.hide();
reset_dragging = false;
}
});
dropzoneParent.on('drop', function(e){
// Is not dropable?
if(!reset_dragging){
return;
}
e.preventDefault();
var pagelayer_ajax_func = {};
// This function for ajax success call back
pagelayer_ajax_func['success'] = function(obj){
if(obj['success']){
// Set the new ID and URL
id = obj['data']['id'];
url = obj['data']['url'];
if(row == ''){
// Getting Id of jEle
var widgetid = jEle.closest('[pagelayer-id]').attr('pagelayer-id');
// Finding widget image setting using id of jEle. Finding image editor setting from all of the other settings.
row = pagelayer.$$('[pagelayer-element-id='+widgetid+']').find('.pagelayer-elp-image').eq(0).parent().parent();
}
row.find('.pagelayer-elp-image').css('background-image', 'url(\''+url+'\')');
// To remove past temp attr so that they are not involve in future temp values
_pagelayer_clear_tmp_atts(row);
for(var x in obj['data']['sizes']){
_pagelayer_set_tmp_atts(row, x+'-url', obj['data']['sizes'][x]['url']);
}
dropZone.find('.pagelayer-elp-img-up-bar').css('width', '3%');
dropZone.hide();
// Save and render
_pagelayer_set_tmp_atts(row, 'url', url);
_pagelayer_set_atts(row, id);
}else{
alert(obj['data']['message']);
}
}
// This function for ajax before send call back
pagelayer_ajax_func['beforeSend'] = function(xhr){
// It activate the image widget
if(row == ''){
jEle.click();
}
}
// This function for how much file is uploaded or for progress bar
pagelayer_ajax_func['uploadProgress'] = function(xhr){
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
if(row == ''){
dropZone.find('.pagelayer-img-up-bar').css('width', percentComplete+'%');
}else{
dropZone.find('.pagelayer-elp-img-up-bar').css('width', percentComplete+'%');
}
}
}, false);
return xhr;
}
// Uploading image to the media library
pagelayer_editable_paste_handler(e.originalEvent.dataTransfer.files[0], pagelayer_ajax_func);
reset_dragging = false;
});
}
// The Multi Image Property
function pagelayer_elp_multi_image(row, prop){
var div = '
'+
'
'+
''+
'
';
row.append(div);
var tmp = prop.c['name']+'-urls';
var ids = new Array();
// Any IDs ?
if(!pagelayer_empty(prop.c['val'])){
ids = prop.c['val'].split(',');
//console.log(ids);
}
// Do we have a URL set ?
if(ids.length > 0 && tmp in prop.el.tmp){
var images = JSON.parse(prop.el.tmp[tmp]);
//console.log(images);
for(var x in ids){
row.find('.pagelayer-elp-multi_image-thumbs').append('');
}
}
var pagelayer_init_frame = function(state){
var button = row.find('.pagelayer-elp-multi_image-thumbs');
//console.log(ids);
// Load the frame
var frame = pagelayer_select_frame('multi_image', state);
frame.on({
'select': function(){
var state = frame.state();
var id = url = '';
var urls = {};
// External URL
if('props' in state){
//console.log(state);
var urls_str = state.props.attributes.url;
var urls_arr = urls_str.split(',');
//console.log(urls_arr);
button.empty();
// Add to current selection
for(var i = 0; i < urls_arr.length; i++){
var single_url = pagelayer_parse_theme_vars(urls_arr[i]);
urls['i'+i] = single_url;
// Create thumbnails
button.append('');
}
urls_arr = Object.values(urls);
_pagelayer_set_tmp_atts(row, 'urls', JSON.stringify(urls));
_pagelayer_set_atts(row, urls_arr.join());
}
},
// Set the current selection if any
'open': function(){
// Do we have anything
if(ids.length > 0){
var selection = '';
if(state == 'gallery-edit'){
selection = frame.state().get('library');
}else if(state == 'gallery-library'){
selection = frame.state().get('selection');
}
// Add to current selection
if(!pagelayer_empty(selection)){
for(var x in ids){
attachment = wp.media.attachment(ids[x]);
attachment.fetch();
selection.add(attachment ? [ attachment ] : [] );
}
}
}
},
// When images are selected
'update': function(selection){
//console.log(selection);
// Remove thumbnails
row.find('.pagelayer-elp-multi_image-thumb').remove();
//Fetch selected images
var attachments = selection.map(function(attachment){
attachment.toJSON();
return attachment;
});
//console.log(attachments);
var img_ids = [];
var urls = {};
var img_urls = {};
var titles = {};
var links = {};
var captions = {};
for(var i = 0; i < attachments.length; ++i){
// Add Id and urls to array
var id = attachments[i].id;
var _id = 'i'+id;
img_ids.push(id);
urls[_id] = attachments[i].attributes.url;
// Create thumbnails
button.append('');
//get title
titles[_id] = attachments[i].attributes.title;
links[_id] = attachments[i].attributes.link;
captions[_id] = attachments[i].attributes.caption;
// Create a URL
img_urls[_id] = {}
for(var x in attachments[i].attributes.sizes){
img_urls[_id][x] = attachments[i].attributes.sizes[x].url;
}
}
//console.log(img_urls);
// Save and render
_pagelayer_set_tmp_atts(row, 'urls', JSON.stringify(urls));
_pagelayer_set_tmp_atts(row, 'all-urls', JSON.stringify(img_urls));
_pagelayer_set_tmp_atts(row, 'all-titles', JSON.stringify(titles));
_pagelayer_set_tmp_atts(row, 'all-links', JSON.stringify(links));
_pagelayer_set_tmp_atts(row, 'all-captions', JSON.stringify(captions));
_pagelayer_set_atts(row, img_ids);
// Update the IDs incase the user clicks on it again
ids = img_ids;
}
});
frame.open(button);
return false;
};
row.find('.pagelayer-elp-multi_image-thumbs').on('click', function(){
pagelayer_init_frame('gallery-edit');
});
row.find('.pagelayer-elp-button').on('click', function(){
//console.log(ids.length);
if(ids.length > 0){
if(isNaN(ids[0])){
pagelayer_init_frame('embed');
}else{
pagelayer_init_frame('gallery-library');
}
}else{
pagelayer_init_frame('gallery');
}
});
}
// The Video Property
function pagelayer_elp_video(row, prop){
var tmp = prop.c['name']+'-url';
var src = (tmp in prop.el.tmp) ? prop.el.tmp[tmp] : prop.c['val'];
var div = '
'+
''+
''+
'
';
row.append(div);
row.find('.pagelayer-elp-video-div .pli').on('click', function(){
var button = jQuery(this);
// Load the frame
var frame = pagelayer_select_frame('video');
// On select update the stuff
frame.on({
'select': function(){
var state = frame.state();
var id = url = '';
// External URL
if('props' in state){
id = url = pagelayer_parse_theme_vars(state.props.attributes.url);
// Internal from gallery
}else{
var attachment = frame.state().get('selection').first().toJSON();
//console.log(attachment);
id = attachment.id;
url = attachment.url;
}
// Update URL
button.prev().val(url);
// Save and render
_pagelayer_set_tmp_atts(row, 'url', url);
_pagelayer_set_atts(row, id);
}
});
frame.open(button);
return false;
});
// Edited the video URL directly
row.find('.pagelayer-elp-video').on('change', function(){
var input = jQuery(this);
// Set the new URL
_pagelayer_set_tmp_atts(row, 'url', input.val());
_pagelayer_set_atts(row, input.val());
});
}
// The Audio Property
function pagelayer_elp_audio(row, prop){
var tmp = prop.c['name']+'-url';
var src = (tmp in prop.el.tmp) ? prop.el.tmp[tmp] : prop.c['val'];
var div = '
'+
''+
''+
'
';
row.append(div);
// Choose from media
row.find('.pagelayer-elp-audio-div .pli').on('click', function(){
var button = jQuery(this);
// Load the frame
var frame = pagelayer_select_frame('audio');
frame.on({
'select': function(){
var state = frame.state();
var id = url = '';
// External URL
if('props' in state){
id = url = pagelayer_parse_theme_vars(state.props.attributes.url);
// Internal from gallery
}else{
var attachment = frame.state().get('selection').first().toJSON();
//console.log(attachment);
id = attachment.id;
url = attachment.url;
}
// Update URL
button.prev().val(url);
// Save and render
_pagelayer_set_tmp_atts(row, 'url', url);
_pagelayer_set_atts(row, id);
}
});
frame.open(button);
return false;
});
// Edited the media URL directly
row.find('.pagelayer-elp-audio').on('change', function(){
var input = jQuery(this);
// Set the new URL
_pagelayer_set_tmp_atts(row, 'url', input.val());
_pagelayer_set_atts(row, input.val());
});
}
// The Media Property
function pagelayer_elp_media(row, prop){
var tmp = prop.c['name']+'-url';
var src = (tmp in prop.el.tmp) ? prop.el.tmp[tmp] : prop.c['val'];
var div = '
'+
''+
''+
'
';
row.append(div);
row.find('.pagelayer-elp-media-div .pli-menu').on('click', function(){
var button = jQuery(this);
// Load the frame
var frame = pagelayer_select_frame('media');
frame.on({
'select': function(){
var state = frame.state();
var id = url = '';
// External URL
if('props' in state){
id = url = pagelayer_parse_theme_vars(state.props.attributes.url);
// Internal from gallery
}else{
var attachment = frame.state().get('selection').first().toJSON();
//console.log(attachment);
id = attachment.id;
url = attachment.url;
}
// Update URL
button.prev().val(url);
// Save and render
_pagelayer_set_tmp_atts(row, 'url', url);
_pagelayer_set_atts(row, id);
}
});
frame.open(button);
return false;
});
// Edited the media URL directly
row.find('.pagelayer-elp-media').on('change', function(){
var input = jQuery(this);
// Set the new URL
_pagelayer_set_tmp_atts(row, 'url', input.val());
_pagelayer_set_atts(row, input.val());
});
}
// The Slider Property
function pagelayer_elp_slider(row, prop){
var div = '
'+
''+
''+
'
'+
'';
row.append(div);
// Set an value in span
row.find('.pagelayer-elp-slider-div input').on('input', function(){
var value = parseFloat(this.value);
var max = parseFloat(this.max);
if(!pagelayer_empty(max) && value > max){
value = max;
}
row.find('.pagelayer-elp-slider-div input').val(value);
_pagelayer_set_atts(row, value);// Save and Render
});
}
// The Editor proprety
function pagelayer_elp_editor(row, prop){
var div = '
'+
''+
'
';
row.append(div);
var editor = row.find('.pagelayer-elp-editor');
editor.val(prop.c['val']);
// No SVG Icons for now
jQuery.trumbowyg.svgPath = false;
// Initiate the editor
editor.trumbowyg({
autogrow: false,
hideButtonTexts: true,
btns:[
['viewHTML'],
['wpmedia'],
['fontfamily'],
['formatting'],
['undo', 'redo'], // Only supported in Blink browsers
['fontsize'],
['lineheight'],
['foreColor', 'backColor',],
['strong', 'em', 'del'],
['horizontalRule'],
['superscript', 'subscript'],
['link'],
['unorderedList', 'orderedList'],
['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
['removeformat'],
['fullscreen']
],
plugins: {
fontsize: {
sizeList: ['12px','13px','14px','15px','16px','17px','18px','19px','20px','21px','22px','23px','24px','25px']
}
},
imageWidthModalEdit: true,
// Handle the changes made in the editor
}).on('tbwchange', function(){
_pagelayer_set_atts(row, editor.trumbowyg('html'));// Save and Render
});
}
// The Link proprety
function pagelayer_elp_link(row, prop){
var tmp = prop.c['name'];
var link = (tmp in prop.el.tmp) ? prop.el.tmp[tmp] : prop.c['val'];
var jEle = jQuery('[pagelayer-id='+prop.el.id+']');
var div = '
'+
''+
''+
'
'+
'
'+
'
';
row.append(div);
var listWrap = row.find('.pagelayer-elp-link-list');
var time = null;
//Add ID
var addID = function(permaID){
permaID = permaID || false;
var lDiv = row.closest('[pagelayer-elp-name]').find('.pagelayer-elp-label-div');
if(permaID){
lDiv.append('ID : '+permaID+'');
}else{
lDiv.find('.pagelayer-elp-link-id').remove();
}
};
if(!isNaN(prop.c['val'])){
addID(prop.c['val']);
}
// Set a Link
row.find('.pagelayer-elp-link').on('change', function(){
// Save and Render
_pagelayer_set_tmp_atts(row, '', jQuery(this).val());
_pagelayer_set_atts(row, jQuery(this).val());
// Remove ID Holder
addID();
});
// Set a Link
row.find('.pagelayer-elp-link').on('input click', function(e){
e.stopPropagation();
if(!listWrap.is(':visible')){
listWrap.show();
}
var val = jQuery(this).val();
clearTimeout(time);
time = setTimeout(function(){
jQuery.ajax({
url: pagelayer_ajax_url,
type: 'post',
data:{
'action' : 'wp-link-ajax',
'_ajax_linking_nonce' : pagelayer_internal_linking_nonce,
'search' : val,
},
success: function(response) {
var data = jQuery.parseJSON(response);
var html = '';
//console.log('Link Data');console.log(response);
if(pagelayer_empty(data)){
html = pagelayer_l('custom_url');
// Remove ID Holder
addID();
}else if(typeof data === 'object'){
for(var key in data){
var vals = data[key];
html += '
';
}
}
listWrap.html(html);
},
fail: function(data) {
listWrap.html('Some error occured in getting the link data');
}
});
}, 200);
});
listWrap.on('click', function(e){
e.stopPropagation();
var lEle = jQuery(e.target).closest('.pagelayer-elp-link-item');
// IF item not found
if(lEle.length < 1){
return;
}
var perma = lEle.attr('data-permalink');
var ID = lEle.attr('data-id');
// Save and Render
row.find('.pagelayer-elp-link').val(perma);
_pagelayer_set_tmp_atts(row, '', perma);
_pagelayer_set_atts(row, ID);
listWrap.hide();
// Show ID
addID(ID);
});
pagelayer.gDocument.on('click', function(e){
listWrap.hide();
});
}
// The Textarea property
function pagelayer_elp_textarea(row, prop){
var rows = prop.rows ? 'rows="'+prop.rows+' "' : '';
var div = '
'+
''+
'
';
row.append(div);
row.find('.pagelayer-elp-textarea').val(prop.c['val']);
// Handle on change
row.find('.pagelayer-elp-textarea').on('input', function(){
_pagelayer_set_atts(row, pagelayer_trim(jQuery(this).val()));// Save and Render
});
};
// Clear all editable
function pagelayer_clear_editable(dontDestroy){
// Destroy all
for(var x in pagelayer_editor){
if(dontDestroy == x){
console.log('Skipping '+dontDestroy);
continue;
}
pagelayer_editor[x].pen.destroy();
}
};
// Makes a field editable in the DOM
function pagelayer_make_editable(jEle, e){
// The parent element
var pEle = jEle.closest('.pagelayer-ele, [pagelayer-ref-id]');
// Mainly for editing table cells as pagelayer-ref-id is used by them
if(!pEle.hasClass('pagelayer-ele')){
var refID = pEle.attr('pagelayer-ref-id');
pEle = jQuery('[pagelayer-id="'+refID+'"]');
}
var prop = jEle.attr('pagelayer-editable');
var eId = pagelayer_id(pEle)+'|'+jEle.attr('pagelayer-editable');// Editing ID
// Is it already setup ?
if(jEle.hasClass('pagelayer-pen')){
//console.log('Already Penned');
//pagelayer_focus_editable(jEle, e, eId);
return true;
}
// Destroy the existing pen
/*if(!pagelayer_empty(pagelayer_editor[eId])){
pagelayer_editor[eId].pen.destroy();
pagelayer_editor[eId].$.removeClass('pagelayer-pen');
}*/
var options = {
class: 'pagelayer-pen',
editor: jEle[0],
list: ['bold', 'italic', 'underline', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'strike'],
stay: false
}
// Setup the editor
pagelayer_editor[eId] = {};
pagelayer_editor[eId].pen = new Pen(options);
pagelayer_editor[eId].$ = jEle;
// Are we the clicked object, then set the focus
if(e){
var target = jQuery(e.target);
if(target.is(jEle).length || jEle.find(target).length){
jEle.focus();
}
}
/*// Reverse setup the event
jEle.on('blur', function(){
//pagelayer_editor[eId].pen.destroy();
});
// Reverse setup the event
jEle.on('focus', function(){
//pagelayer_clear_editable(eId);
});*/
// Reverse setup the event
jEle.on('input', function(){
var val = pagelayer_trim(jEle.html());
// Set the property as well
pagelayer_set_atts(pEle, prop, val);
// Update the property
var input = pagelayer.$$('[pagelayer-elp-name='+prop+']').find('input,textarea,.trumbowyg-editor');
//console.log(input);
if(input.length > 0){
if(input.hasClass('trumbowyg-editor')){
input.html(val);
}else{
input.val(val);
}
}
});
}
// The Icon Property
function pagelayer_elp_icon(row, prop){
var $ = jQuery;
var sets_html = '';
pagelayer_loaded_icons.forEach(function(item){
sets_html += '';
});
var icons = {};
var cur_icon_set = pagelayer_loaded_icons[0];
var sel_icon = prop.c['val'];
var sel_name = prop.c['val'];
var icon_type = '';
var sorted_icons = {};
// Handle the icon name
var icon_name = sel_icon.split(' fa-');
sel_name = icon_name[1];
// Is there a specific list
if('list' in prop && prop.list.length > 0){
for(var i in pagelayer_icons){
icons[i] = {};
for(var j in pagelayer_icons[i]){
icons[i][j] = {};
var list_icons = [];
prop.list.forEach(function(item){
if(pagelayer_icons[i][j]['icons'].includes(item)){
list_icons.push(item);
}
});
icons[i][j]['icons'] = list_icons;
icons[i][j]['pre'] = j;
}
}
}else{
icons = pagelayer_icons;
}
// Icon function
var icon_html = function(name, cat){
return ''+
' '+name+
'';
}
var div = '
';
row.append(div);
// Make all icons list
var html = '
';
if(pagelayer_loaded_icons.length > 1){
html += '';
}
html += ''+
'
'+pagelayer_l('Solid')+'
'+
'
'+pagelayer_l('Regular')+'
'+
'
'+pagelayer_l('Brand')+'
'+
''+
''+
'
';
for(var y in icons[cur_icon_set]){
//console.log(icons[x][y])
for(var z in icons[cur_icon_set][y]['icons']){
html += icon_html(icons[cur_icon_set][y]['icons'][z], y);
}
}
html += '
'+
'
';
row.append(html);
// Open the selector
row.find('.pagelayer-elp-icon-div').on('click', function(){
row.find('.pagelayer-elp-icon-selector').slideToggle();
});
/*// When the set changes
row.find('.pagelayer-elp-icon-sets').on('change', function(){
var v = cur_icon_set = jQuery(this).val();
var span = '';
for(var x in icons[v]){
for(var z in icons[v][x]['icons']){
span += icon_html(icons[v][x]['icons'][z], x);
}
}
if(cur_icon_set == 'font-awesome5'){
row.find('.pagelayer-elp-icon-type').show();
sorted_icons = icons[cur_icon_set]['fas'];
row.find('.pagelayer-elp-icon-type [data-tab="fas"]').click();
}else{
row.find('.pagelayer-elp-icon-type').hide();
}
row.find('.pagelayer-elp-icon-list').empty().html(span);
if(row.find('.pagelayer-elp-search-icon').val() != ''){
row.find('.pagelayer-elp-search-icon').keyup();
}
});*/
// Handle type of icon
row.find('.pagelayer-elp-icon-type p').on('click', function(){
jQuery(this).toggleClass('active');
row.find('.pagelayer-elp-search-icon').keyup();
});
// Handle search of icon
row.find('.pagelayer-elp-search-icon').on('keyup', function(){
var v = this.value;
var span = '';
v = v.toLowerCase();
v = v.replace(/\s+/g, '-');
//console.log(sorted_icons);
row.find('.pagelayer-elp-icon-type p.active').each(function(){
var tab = jQuery(this).data('tab');
tab = tab.toLowerCase();
var cat = icons['font-awesome5'][tab]['icons'];
for(var x in cat){
if(cat[x].includes(v) || v.length < 1){
span += icon_html(cat[x], tab);
}
}
});
row.find('.pagelayer-elp-icon-list').empty().html(span);
});
// Handle click within the icon selector
row.find('.pagelayer-elp-icon-list').on('click', function(e){
var jEle = jQuery(e.target);
var i = jEle.children().attr('class');
var name = jEle.children().attr('icon');
if(pagelayer_empty(name)){
return false;
}
// Set the icon in this list
row.find('.pagelayer-elp-icon-preview').html(''+name+'');
row.find('.pagelayer-elp-icon-selector').slideUp();
_pagelayer_set_atts(row, i);// Save and Render
row.find('.pagelayer-elp-icon-close').show();
return false;
});
// Delete the icon
row.find('.pagelayer-elp-icon-close').on('click', function(){
// Set the icon in this list
row.find('.pagelayer-elp-icon-preview').html(''+pagelayer_l('choose_icon')+'');
// Save and Render
_pagelayer_set_atts(row, '');
jQuery(this).hide();
return false;
});
}
// The Access Property
function pagelayer_elp_access(row, prop){
var div = '
'+
''+
''+
'
';
row.append(div);
var holder = row.find('.pagelayer-elp-access-holder');
row.find('.pagelayer-elp-access').on('click', function(){
// Setup first
if(holder.children().length < 1){
var p = row.parent().find('[pagelayer-access-item='+prop.show_group+']').detach();
p.appendTo(holder);
p.addClass('pagelayer-access-item-visible');
}
// Show and hide
if(holder.is(':visible')){
holder.hide();
row.find('.pli-caret-right').removeClass('pli-caret-open');
}else{
holder.show();
row.find('.pli-caret-right').addClass('pli-caret-open');
}
});
};
// The Modal Property
function pagelayer_elp_modal(row, prop){
var style = pagelayer_empty(prop.width) ? '' : 'style="width:'+prop.width+'"';
var div = '
'+
''+
'
'+
'
'+
'
'+
prop.label +''+
'
'+
''+
'
'+
'
'+
'
';
row.append(div);
var wrapper = row.find('.pagelayer-elp-modal-wrapper');
var holder = row.find('.pagelayer-elp-modal-holder');
row.find('.pagelayer-elp-modal').on('click', function(){
// Setup first
if(holder.children().length < 1){
var p = row.parent().find('[pagelayer-access-item='+prop.show_group+']').detach();
p.appendTo(holder);
p.addClass('pagelayer-access-item-visible');
}
// Show and hide
wrapper.show();
});
// Close Modal Property
row.find('.pagelayer-elp-modal-close').on('click', function(){
wrapper.hide();
});
// On click Pagelayer setting icon
wrapper.on('click', function(event){
var target = jQuery(event.target);
if(target.closest('.pagelayer-elp-modal-wrap').length > 0){
return;
}
wrapper.hide();
});
};
// The Color Property
function pagelayer_elp_color(row, prop){
var div = '
'+
''+
''+
'
';
row.append(div);
row.find('.pagelayer-elp-color-preview').css('background', prop.c['val']);
var picker = new pagelayer_Picker({
parent : row.find('.pagelayer-elp-color-div')[0],
popup : 'left',
color : prop.c['val'],
doc: window.parent.document
});
var preview = row.find('.pagelayer-elp-color-preview');
// If no val, then set blank
if(pagelayer_empty(prop.c['val'])){
preview.addClass('pagelayer-blank-preview');
}
var handle_white = function(col){
if(col.charAt(1) == 'f'){
preview.addClass('pagelayer-white-border');
}else{
preview.removeClass('pagelayer-white-border');
}
}
handle_white(prop.c['val']);
// Handle selected color
picker.onChange = function(color) {
preview.removeClass('pagelayer-blank-preview').css('background', color.rgbaString);
handle_white(color.hex);
_pagelayer_set_atts(row, color.hex);// Save and Render
};
picker.onOpen = picker.onChange;
row.find('.pagelayer-elp-remove-color').on('click', function(event){
event.stopPropagation();
picker.setColor(prop.default, true);
preview.addClass('pagelayer-blank-preview');
handle_white('');
_pagelayer_set_atts(row, ' ');// Save and Render
});
}
// The Spinner property
function pagelayer_elp_spinner(row, prop){
var div = '
'+
''+
'
';
row.append(div);
row.find('input').on('input', function(){
var value = parseFloat(this.value);
var max = parseFloat(this.max);
if(!pagelayer_empty(max) && value > max){
value = max;
}
_pagelayer_set_atts(row, value);// Save and Render
});
}
// The Group Property
function pagelayer_elp_group(row, prop){
var btnHidden = '';
// Hide button, clone and delete
if(!pagelayer_empty(prop['hide'])){
btnHidden = 'pagelayer-hidden';
}
// Remove the pagelayer-show-tab
row.removeAttr('pagelayer-show-tab');
var div = ''+
'
';
row.append(div);
// Add button
var add_item = function(row){
var ele_id = row.closest('[pagelayer-element-id]').attr('pagelayer-element-id') || '';
var pEle = jQuery('[pagelayer-id="'+ele_id+'"]');
// First add the element inside the group element
var id = pagelayer_element_add_child(pEle, prop['sc']);
//pagelayer_element_setup('[pagelayer-id='+id+']', true);
show_item(id);
};
// Show the properties of the existing things
var show_item = function(id, sel){
// To append after an existing item
sel = sel || false;
// If pagelayer id empty then return
if(pagelayer_empty(id)){
return false;
}
// Since the element is added very fast, we reselect via jQuery for it to re-access the dom
jEle = jQuery('[pagelayer-id="'+id+'"]');
var label_param = prop['item_label']['param'] || '';
var title = pagelayer_get_att(jEle, label_param) || prop['item_label']['default'];
// We need to get the correct value for select based params which are the label
var child_props = pagelayer_shortcodes[prop.sc];
for(var section in child_props){
for(var _param in child_props[section]){
if(child_props[section][_param]['type'] == 'select'){
if(title in child_props[section][_param]['list']){
title = child_props[section][_param]['list'][title];
}
}
}
}
// Create the HTML
var holder = jQuery('
'+
'
'+
''+
''+title+''+
''+
''+
'
'+
''+
'
');
// Append to the row
if(sel){
row.find(sel).after(holder);
}else{
row.find('.pagelayer-elp-group-div').first().append(holder);
}
// Setup the toggle
holder.find('.pagelayer-elp-group-item-title').first().on('click', function(){
var rEle = holder.find('.pagelayer-elp-group-item-body').first();
var r_id = holder.attr('pagelayer-group-item-id');
// If the props are not already setup
if(rEle.html().length < 1){
pagelayer_elpd_generate(jQuery('[pagelayer-id="'+r_id+'"]'), rEle);
// Change the group item title
var tmp_title = holder.find('[pagelayer-elp-name="'+label_param+'"] [name="'+label_param+'"]');
if(tmp_title.length > 0){
jQuery(tmp_title).on('input', function(){
holder.find('.pagelayer-elp-group-item-title').html(tmp_title.val());
});
}
}
rEle.toggle('slow');
});
// Clone the item
holder.find('.pagelayer-elp-group-item-head .pli-clone').on('click', function(){
// If the element have any parent
var jEle = jQuery('[pagelayer-id="'+id+'"]');
var par = pagelayer_get_parent(jEle);
var clone_ele = pagelayer_copy_element(jEle);
//console.log(clone_ele);console.log('[pagelayer-group-item-id="'+id+'"]');
show_item(clone_ele, '[pagelayer-group-item-id="'+id+'"]');
if(par){
pagelayer_sc_render(pagelayer_ele_by_id(par));
}
});
// Delete the item
holder.find('.pagelayer-elp-group-item-head .pli-trashcan').on('click', function(){
// If the element have any parent
var jEle = jQuery('[pagelayer-id="'+id+'"]');
var par = pagelayer_get_parent(jEle);
holder.remove();
pagelayer_delete_element(jEle);
if(par){
pagelayer_sc_render(pagelayer_ele_by_id(par));
}
});
};
// Setup the drag
pagelayer.$$(".pagelayer-elp-group-div").sortable({
axis: 'y',
nested : false,
vertical : true,
handle : ".pagelayer-elp-group-item-drag",
start : function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
stop : function(event, ui){
var end_pos = ui.item.index();
var id = jQuery(ui.item).closest('[pagelayer-group-item-id]').attr('pagelayer-group-item-id');
var jEle = jQuery('[pagelayer-id="'+id+'"]');
pagelayer_moving_element(jEle, ui.item.data('start_pos'), end_pos);
var par = pagelayer_get_parent(jEle);
if(par){
pagelayer_sc_render(pagelayer_ele_by_id(par));
}
}
});
// Handle click of the group
row.find('.pagelayer-elp-button').on('click', function(){
if('pro' in prop && pagelayer_empty(pagelayer_pro)){
pagelayer_pro_notice();
return;
}
add_item(row);
});
// Find the existing items
prop.el.$.find('[pagelayer-tag='+prop['sc']+']').each(function(){
var jEle = jQuery(this);
var id = pagelayer_assign_id(jEle);
show_item(id);
});
};
function pagelayer_pro_notice(){
var div = pagelayer.$$('.pagelayer-pro-notice');
div.find('.pagelayer-pro-x').click(function(){
div.hide();
});
div.show();
}
// Moving an element
function pagelayer_moving_element(jEle, start_pos, end_pos){
if(start_pos==end_pos){
return;
}
var id = pagelayer_assign_id(jEle);
// Is there a wrap
var wrap = pagelayer_wrap_by_id(id);
var par = wrap.parent();
var children = par.children("div");
var element = children.eq(start_pos).detach();
if(end_pos < start_pos){
children.eq(end_pos).before(element);
}else{
children.eq(end_pos).after(element);
}
}
// The Datetime Property
function pagelayer_elp_datetime(row, prop){
var div = '
'+
''+
'
';
row.append(div);
row.find('.pagelayer-elp-datetime').on('change', function(){
_pagelayer_set_atts(row, jQuery(this).val());// Save and Render
});
};
// The padding property
function pagelayer_elp_padding(row, prop){
var val = ['', '', '', ''];
if(prop.c['val'].length > 0){
val = prop.c['val'].split(',');
//console.log(val)
}
var div = '
'+
''+
''+
''+
''+
''+
'
';
row.append(div);
// Is the value linked ?
var link = row.find('.pagelayer-elp-padding-div i');
var isLinked = 1;
//isLinked = isLinked == 2 ? false : true;
//console.log(isLinked);
var tmp_val = val[0];
for(var p_val in val){
// Check if unlinked
if(tmp_val != val[p_val] ){
isLinked = 0;
}
tmp_val = val[p_val];
}
if(isLinked){
link.addClass('pagelayer-elp-padding-linked');
}else{
link.removeClass('pagelayer-elp-padding-linked');
}
// Handle link on click
link.on('click', function(){
var linked = link.hasClass('pagelayer-elp-padding-linked');
if(linked){
link.removeClass('pagelayer-elp-padding-linked');
}else{
link.addClass('pagelayer-elp-padding-linked');
}
});
row.find('input').on('input', function(){
// Are the values linked
var linked = row.find('.pagelayer-elp-padding-div .pli').hasClass('pagelayer-elp-padding-linked');
if(linked){
var val = jQuery(this).val();
row.find('input').each(function(){
jQuery(this).val(val);
});
}
var vals = [];
// Get all values
row.find('input').each(function(){
var val = jQuery(this).val();
vals.push(val ? val : 0);
});
_pagelayer_set_atts(row, vals);// Save and Render
});
};
// The shadow property
function pagelayer_elp_shadow(row, prop){
var val =['','','',''];
// Do we have a val ?
if(!pagelayer_empty(prop.c['val'])){
val = prop.c['val'].split(',');
}
//var val = {color: '', blur: '', horizontal: '', vertical: ''};
var div = ''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
'
'+
''+
''+
'
'+
'
'+
'
';
row.append(div);
row.find('.pagelayer-prop-edit').on('click', function(){
row.find('.pagelayer-elp-shadow-div').toggleClass('pagelayer-prop-show');
});
var preview = row.find('.pagelayer-elp-color-preview');
preview.css('background', val[3]);
var picker = new pagelayer_Picker({
parent : row.find('.pagelayer-elp-color-div')[0],
popup : 'left',
color : val[3],
doc: window.parent.document
});
// If no val, then set blank
if(pagelayer_empty(val[3])){
preview.addClass('pagelayer-blank-preview');
}
var handle_white = function(col){
if(col.charAt(1) == 'f'){
preview.addClass('pagelayer-white-border');
}else{
preview.removeClass('pagelayer-white-border');
}
}
handle_white(val[3]);
// Handle selected color
picker.onChange = function(color) {
preview.removeClass('pagelayer-blank-preview').css('background', color.rgbaString);
handle_white(color.hex);
val[3] = (color.hex ? color.hex : '');
_pagelayer_set_atts(row, val);
};
// Remove Color
row.find('.pagelayer-elp-remove-color').on('click', function(event){
event.stopPropagation();
picker.setColor(prop.default, true);
preview.addClass('pagelayer-blank-preview');
handle_white('');
val[3] = '';
_pagelayer_set_atts(row, val);
});
row.find('input').on('input', function(){
var i = 0;
row.find('.pagelayer-elp-shadow-input').each(function(){
var value = jQuery(this).val();
val[i] = (value ? value : '');
i++;
});
_pagelayer_set_atts(row, val);
});
}
// The box shadow property
function pagelayer_elp_box_shadow(row, prop){
var val = ['','','','','',''];
// Do we have a val ?
if(!pagelayer_empty(prop.c['val'])){
val = prop.c['val'].split(',');
}
var val_pos = ['horizontal','vertical','blur','color','spread','inset'];
var div = ''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
'
'+
''+
''+
'
'+
'
'+
'
'+
''+
''+
'
'+
'
';
row.append(div);
row.find('.pagelayer-prop-edit').on('click', function(){
row.find('.pagelayer-elp-shadow-div').toggleClass('pagelayer-prop-show');
});
var preview = row.find('.pagelayer-elp-color-preview');
preview.css('background', val[3]);
var picker = new pagelayer_Picker({
parent : row.find('.pagelayer-elp-color-div')[0],
popup : 'left',
color : val[3],
doc: window.parent.document
});
// If no val, then set blank
if(pagelayer_empty(val[3])){
preview.addClass('pagelayer-blank-preview');
}
var handle_white = function(col){
if(col.charAt(1) == 'f'){
preview.addClass('pagelayer-white-border');
}else{
preview.removeClass('pagelayer-white-border');
}
}
handle_white(val[3]);
// Handle selected color
picker.onChange = function(color) {
row.find('.pagelayer-elp-color-preview').removeClass('pagelayer-blank-preview').css('background', color.rgbaString);
handle_white(color.hex);
val[3] = (color.hex ? color.hex : '');
_pagelayer_set_atts(row, val);
};
// Remove Color
row.find('.pagelayer-elp-remove-color').on('click', function(event){
event.stopPropagation();
picker.setColor(prop.default, true);
preview.addClass('pagelayer-blank-preview');
handle_white('');
val[3] = '';
_pagelayer_set_atts(row, val);
});
// Onchange set props
row.find('.pagelayer-elp-shadow-input').on('input change', function(){
//var i = 0;
row.find('.pagelayer-elp-shadow-input').each(function(){
var value = jQuery(this).val();
var name = jQuery(this).attr('name');
val[val_pos.indexOf(name)] = (value ? value : '');
//i++;
});
_pagelayer_set_atts(row, val);
});
}
// The filter property
function pagelayer_elp_filter(row, prop){
var val = [0,100,100,0,0,100,100];
// Do we have a val ?
if(!pagelayer_empty(prop.c['val'])){
val = prop.c['val'].split(',');
}
var filters = [['blur','10','0.1'],['brightness','200','1'],['contrast','200','1'],['grayscale','200','1'],['hue','360','1'],['opacity','100','1'],['saturate','200','1']];
var div = ''+
'
';
jQuery.each(val,function(key, value){
div += '
'+
''+
''+
''+value+''+
'
';
});
div += '
';
row.append(div);
row.find('.pagelayer-prop-edit').on('click', function(){
row.find('.pagelayer-elp-filter-div').toggleClass('pagelayer-prop-show');
});
row.find('input').on('input', function(){
var val = [];
jQuery(this).parent().find('span').html(this.value);
row.find('.pagelayer-elp-filter-input').each(function(){
var value = jQuery(this).val();
val.push(value ? value : 'none');
});
_pagelayer_set_atts(row, val);
});
}
// The gradient property
function pagelayer_elp_gradient(row, prop){
var val =['','','','','','',''];
// Do we have a val ?
if(!pagelayer_empty(prop.c['val'])){
val = prop.c['val'].split(',');
}
//var val = {color: '', blur: '', horizontal: '', vertical: ''};
var div = '
'+
'
'+
''+
''+
'
'+
'
'+
''+
'
'+
''+
'
'+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
'
'+
''+
'
'+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
'
'+
''+
'
'+
'
'+
'
'+
''+
''+
'
'+
'
';
row.append(div);
var i = 1;
row.find('.pagelayer-elp-color-preview').each(function(){
jQuery(this).css('background', val[i]);
i = i+2;
});
var picker1 = new pagelayer_Picker({
parent : row.find('.pagelayer-elp-gradient-color1')[0],
popup : 'left',
color : val[1],
doc: window.parent.document
});
// Handle selected color
picker1.onChange = function(color) {
row.find('.pagelayer-elp-gradient-color1').css('background', color.rgbaString);
val[1] = (color.hex ? color.hex : '');
_pagelayer_set_atts(row, val);
};
var picker2 = new pagelayer_Picker({
parent : row.find('.pagelayer-elp-gradient-color2')[0],
popup : 'left',
color : val[3],
doc: window.parent.document
});
// Handle selected color
picker2.onChange = function(color) {
row.find('.pagelayer-elp-gradient-color2').css('background', color.rgbaString);
val[3] = (color.hex ? color.hex : '');
_pagelayer_set_atts(row, val);
};
var picker3 = new pagelayer_Picker({
parent : row.find('.pagelayer-elp-gradient-color3')[0],
popup : 'left',
color : val[5],
doc: window.parent.document
});
// Handle selected color
picker3.onChange = function(color) {
row.find('.pagelayer-elp-gradient-color3').css('background', color.rgbaString);
val[5] = (color.hex ? color.hex : '');
_pagelayer_set_atts(row, val);
};
row.find('input').on('input', function(){
var i = 0;
row.find('.pagelayer-elp-gradient-input').each(function(){
var value = jQuery(this).val();
val[i] = (value ? value : '');
i = i+2;
});
_pagelayer_set_atts(row, val);
});
}
function pagelayer_elp_font_family(row, prop){
var options = '';
var option = function(val, lang){
var selected = (val != prop.c['val']) ? '' : 'selected="selected"';
var lang = pagelayer_empty(val) ? 'Default' : val;
return '';
}
for (x in pagelayer_fonts){
options += option(pagelayer_fonts[x], pagelayer_fonts[x]);
}
var div = '
'+
''+
'
';
row.append(div);
row.find('select').on('change', function(){
var sEle = jQuery(this);
var value = sEle.val();
if(sEle.val() == 'Default'){
return;
}
value = value.replace(' ', '+');
if(jQuery('#pagelayer-google-fonts').length == 0){
jQuery('head').append('');
}else{
var url = jQuery('#pagelayer-google-fonts').attr('href');
if(url.indexOf(value) == -1){
url = url+'|'+value+':100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i';
jQuery('#pagelayer-google-fonts').attr('href', url);
}
}
_pagelayer_set_atts(row, sEle.val());// Save and Render
});
}
// The typography property
function pagelayer_elp_typography(row, prop){
var val =['','','','','','','','','',''];
// Do we have a val ?
if(!pagelayer_empty(prop.c['val'])){
val = prop.c['val'].split(',');
}
var select = { 'style' : ['', 'Normal', 'Italic', 'Oblique'],
'weight' : ['', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'normal', 'lighter', 'bold', 'bolder', 'unset'],
'variant' : ['', 'Normal', 'Small-caps'],
'deco-line' : ['', 'None', 'Overline', 'Line-through', 'Underline', 'Underline Overline'],
'deco-style' : ['Solid', 'Double', 'Dotted', 'Dashed', 'Wavy'],
'transform' : ['', 'Capitalize', 'Uppercase', 'Lowercase'],
'fonts' : pagelayer_fonts,
}
var option = function(val, setVal){
var selected = (val != setVal) ? '' : 'selected="selected"';
var lang = pagelayer_empty(val) ? 'Default' : val;
return '';
}
var font_option = function(val, setVal){
var selected = (val != setVal) ? '' : 'selected="selected"';
var lang = pagelayer_empty(val) ? 'Default' : val;
return ''+ lang +'';
}
var div = ''+
'
'+
'
'+
''+
'
'+val[0]+'
'+
'
'+
''+
'
';
jQuery.each(select['fonts'],function(key, value){
div += font_option(value, val[0]);
});
div +='
'+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
'+
''+
''+
'
'+
'
';
row.append(div);
if(pagelayer_empty(val[5]) || val[5]=='none'){
row.find('.pagelayer-elp-typo-deco-style').hide();
}
row.find('.pagelayer-prop-edit').on('click', function(){
row.find('.pagelayer-elp-typo-div').toggleClass('pagelayer-prop-show');
});
row.find('.pagelayer-elp-typo-sele').on('click', function(){
row.find('.pagelayer-ele-type-sec').slideToggle();
});
row.find('.pagelayer-elp-typo-container').on('click', function(e){
var jEle = jQuery(e.target);
var set_val = jEle.attr('value');
row.find('.pagelayer-elp-typo-sele').data('val',set_val).html(set_val);
row.find('.pagelayer-ele-type-sec').slideUp();
val = [];
val[0] = set_val;
row.find('.pagelayer-elp-typo-input').each(function(){
var value = jQuery(this).val();
val.push(value ? value : '');
});
_pagelayer_set_atts(row, val);
});
row.find('.pagelayer-elp-typo-search').on('input', function(){
var val = jQuery(this).val().toLowerCase();
//console.log(val);
var html = '';
jQuery.each(select['fonts'],function(key, value){
//value = value.toLowerCase();
if(value.toLowerCase().includes(val)){
html += font_option(value, val[0]);
}
});
row.find('.pagelayer-elp-typo-container').html(html);
});
row.find('.pagelayer-elp-typo-input').on('change', function(){
val = [];
val[0] = row.find('.pagelayer-elp-typo-sele').data('val');
row.find('.pagelayer-elp-typo-input').each(function(){
var value = jQuery(this).val();
val.push(value ? value : '');
});
_pagelayer_set_atts(row, val);
});
row.find('.pagelayer-elp-typo-container').on('click', function(e){
var jEle = jQuery(e.target);
var value = jEle.attr('value');
value = value.replace(' ', '+');
if(jQuery('#pagelayer-google-fonts').length == 0){
jQuery('head').append('');
}else{
var url = jQuery('#pagelayer-google-fonts').attr('href');
if(url.indexOf(value) == -1){
url = url+'|'+value+':100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i';
jQuery('#pagelayer-google-fonts').attr('href', url);
}
}
});
row.find('.pagelayer-elp-typo-deco-line select').on('change', function(){
var value = jQuery(this).val();
if(pagelayer_empty(value) || value=='none'){
row.find('.pagelayer-elp-typo-deco-style').hide();
}else{
row.find('.pagelayer-elp-typo-deco-style').show();
}
});
}
// The dimension property
function pagelayer_elp_dimension(row, prop){
var val = ['', ''];
if(prop.c['val'].length > 0){
val = prop.c['val'].split(',');
//console.log(val)
}
var div = '
'+
''+
''+
''+
'
';
row.append(div);
// Is the value linked ?
var link = row.find('.pagelayer-elp-dimension-div .pli');
var isLinked = 1;
var tmp_val = val[0];
for(var p_val in val){
// Check if unlinked
if(tmp_val != val[p_val] ){
isLinked = 0;
}
tmp_val = val[p_val];
}
if(isLinked){
link.addClass('pagelayer-elp-dimension-linked');
}else{
link.removeClass('pagelayer-elp-dimension-linked');
}
// Handle link on click
link.on('click', function(){
var linked = link.hasClass('pagelayer-elp-dimension-linked');
if(linked){
link.removeClass('pagelayer-elp-dimension-linked');
}else{
link.addClass('pagelayer-elp-dimension-linked');
}
});
row.find('input').on('input', function(){
// Are the values linked
var linked = row.find('.pagelayer-elp-dimension-div .pli').hasClass('pagelayer-elp-dimension-linked');
if(linked){
var val = jQuery(this).val();
row.find('input').each(function(){
jQuery(this).val(val);
});
}
var vals = [];
// Get all values
row.find('input').each(function(){
var val = jQuery(this).val();
vals.push(val ? val : 0);
});
_pagelayer_set_atts(row, vals);// Save and Render
});
};
// Select frame to upload media
function pagelayer_select_frame(tag, state){
var state = state || '';
//console.log(state);
var frame;
switch(tag){
// Multi image selection frame
case 'multi_image':
frame = wp.media({
id: 'pagelayer-wp-multi-image-library',
frame: 'post',
state: state,
title: pagelayer_l('frame_multi_image'),
multiple: true,
library: wp.media.query({type: 'image'}),
button: {
text: pagelayer_l('insert')
},
});
break;
// Media selection frame
case 'media':
frame = wp.media({
id: 'pagelayer-wp-media-library',
frame: 'post',
state: 'pagelayer-media',
title: pagelayer_l('frame_media'),
multiple: false,
states: [
new wp.media.controller.Library({
id: 'pagelayer-media',
title: pagelayer_l('frame_media'),
multiple: false,
date: true
})
],
button: {
text: pagelayer_l('insert')
},
});
break;
//Default frame(for image, video, audio)
default:
frame = wp.media({
id: 'pagelayer-wp-'+tag+'-library',
frame: 'post',
state: 'pagelayer-'+tag,
title: pagelayer_l('frame_media'),
multiple: false,
library: wp.media.query({type: tag}),
states: [
new wp.media.controller.Library({
id: 'pagelayer-'+tag,
title: pagelayer_l('frame_media'),
library: wp.media.query( { type: tag } ),
multiple: false,
date: true
})
],
button: {
text: pagelayer_l('insert')
},
});
break;
}
frame.on({
'menu:render:default': function(view){
view.unset('insert');
view.unset('gallery');
view.unset('featured-image');
view.unset('playlist');
view.unset('video-playlist');
},
}, this);
return frame;
}
/*
* [hi-base64]{@link https://github.com/emn178/hi-base64}
*
* @version 0.2.1
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2014-2017
* @license MIT
*/
/*jslint bitwise: true */
/*Modified by Pagelayer*/
!function(){"use strict";var r="object"==typeof window?window:{};!r.HI_BASE64_NO_COMMON_JS&&"object"==typeof module&&module.exports,"function"==typeof define&&define.amd;var t,o,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),n={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,a:26,b:27,c:28,d:29,e:30,f:31,g:32,h:33,i:34,j:35,k:36,l:37,m:38,n:39,o:40,p:41,q:42,r:43,s:44,t:45,u:46,v:47,w:48,x:49,y:50,z:51,0:52,1:53,2:54,3:55,4:56,5:57,6:58,7:59,8:60,9:61,"+":62,"/":63,"-":62,_:63},a=function(r){var t,o,e,a,h=[],f=0,i=r.length;"="===r.charAt(i-2)?i-=2:"="===r.charAt(i-1)&&(i-=1);for(var C=0,c=i>>2<<2;C>>4),h[f++]=255&(o<<4|e>>>2),h[f++]=255&(e<<6|a);var g=i-c;return 2===g?(t=n[r.charAt(C++)],o=n[r.charAt(C++)],h[f++]=255&(t<<2|o>>>4)):3===g&&(t=n[r.charAt(C++)],o=n[r.charAt(C++)],e=n[r.charAt(C++)],h[f++]=255&(t<<2|o>>>4),h[f++]=255&(o<<4|e>>>2)),h},h=r.btoa,f=r.atob;h?(t=function(r){for(var t="",o=0;o>6)+String.fromCharCode(128|63&e):e<55296||e>=57344?t+=String.fromCharCode(224|e>>12)+String.fromCharCode(128|e>>6&63)+String.fromCharCode(128|63&e):(e=65536+((1023&e)<<10|1023&r.charCodeAt(++o)),t+=String.fromCharCode(240|e>>18)+String.fromCharCode(128|e>>12&63)+String.fromCharCode(128|e>>6&63)+String.fromCharCode(128|63&e))}return h(t)},o=function(r){var t=f(r.trim("=").replace(/-/g,"+").replace(/_/g,"/"));if(!/[^\x00-\x7F]/.test(t))return t;for(var o,e,n="",a=0,h=t.length,i=0;a191&&o<=223)e=31&o,i=1;else if(o<=239)e=15&o,i=2;else{if(!(o<=247))throw"not a UTF-8 string";e=7&o,i=3}for(var C=0;C191)throw"not a UTF-8 string";e<<=6,e+=63&o}if(e>=55296&&e<=57343)throw"not a UTF-8 string";if(e>1114111)throw"not a UTF-8 string";e<=65535?n+=String.fromCharCode(e):(e-=65536,n+=String.fromCharCode(55296+(e>>10)),n+=String.fromCharCode(56320+(1023&e)))}return n}):(h=function(r){for(var t,o,n,a="",h=r.length,f=0,i=3*parseInt(h/3);f>>2]+e[63&(t<<4|o>>>4)]+e[63&(o<<2|n>>>6)]+e[63&n];var C=h-i;return 1===C?(t=r.charCodeAt(f),a+=e[t>>>2]+e[t<<4&63]+"=="):2===C&&(t=r.charCodeAt(f++),o=r.charCodeAt(f),a+=e[t>>>2]+e[63&(t<<4|o>>>4)]+e[o<<2&63]+"="),a},t=function(r){for(var t,o,n,a="",h=function(r){for(var t=[],o=0;o>6,t[t.length]=128|63&e):e<55296||e>=57344?(t[t.length]=224|e>>12,t[t.length]=128|e>>6&63,t[t.length]=128|63&e):(e=65536+((1023&e)<<10|1023&r.charCodeAt(++o)),t[t.length]=240|e>>18,t[t.length]=128|e>>12&63,t[t.length]=128|e>>6&63,t[t.length]=128|63&e)}return t}(r),f=h.length,i=0,C=3*parseInt(f/3);i>>2]+e[63&(t<<4|o>>>4)]+e[63&(o<<2|n>>>6)]+e[63&n];var c=f-C;return 1===c?(t=h[i],a+=e[t>>>2]+e[t<<4&63]+"=="):2===c&&(t=h[i++],o=h[i],a+=e[t>>>2]+e[63&(t<<4|o>>>4)]+e[o<<2&63]+"="),a},f=function(r){var t,o,e,a,h="",f=r.length;"="===r.charAt(f-2)?f-=2:"="===r.charAt(f-1)&&(f-=1);for(var i=0,C=f>>2<<2;i>>4))+String.fromCharCode(255&(o<<4|e>>>2))+String.fromCharCode(255&(e<<6|a));var c=f-C;return 2===c?(t=n[r.charAt(i++)],o=n[r.charAt(i++)],h+=String.fromCharCode(255&(t<<2|o>>>4))):3===c&&(t=n[r.charAt(i++)],o=n[r.charAt(i++)],e=n[r.charAt(i++)],h+=String.fromCharCode(255&(t<<2|o>>>4))+String.fromCharCode(255&(o<<4|e>>>2))),h},o=function(r){for(var t,o,e="",n=a(r),h=n.length,f=0,i=0;f191&&t<=223)o=31&t,i=1;else if(t<=239)o=15&t,i=2;else{if(!(t<=247))throw"not a UTF-8 string";o=7&t,i=3}for(var C=0;C191)throw"not a UTF-8 string";o<<=6,o+=63&t}if(o>=55296&&o<=57343)throw"not a UTF-8 string";if(o>1114111)throw"not a UTF-8 string";o<=65535?e+=String.fromCharCode(o):(o-=65536,e+=String.fromCharCode(55296+(o>>10)),e+=String.fromCharCode(56320+(1023&o)))}return e});var i=function(r,t){return t?f(r):o(r)},C={encode:function(o,n){var a="string"!=typeof o;return a&&o.constructor===r.ArrayBuffer&&(o=new Uint8Array(o)),a?function(r){for(var t,o,n,a="",h=r.length,f=0,i=3*parseInt(h/3);f>>2]+e[63&(t<<4|o>>>4)]+e[63&(o<<2|n>>>6)]+e[63&n];var C=h-i;return 1===C?(t=r[f],a+=e[t>>>2]+e[t<<4&63]+"=="):2===C&&(t=r[f++],o=r[f],a+=e[t>>>2]+e[63&(t<<4|o>>>4)]+e[o<<2&63]+"="),a}(o):!n&&/[^\x00-\x7F]/.test(o)?t(o):h(o)},decode:i,atob:f,btoa:h};i.bytes=a,i.string=i,r.pagelayer_Base64=C}();
/*! Copyright (c) 2011 Piotr Rochala (http://rocha.la)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version: 1.3.8
*
*/
(function(e){e.fn.extend({slimScroll:function(f){var a=e.extend({width:"auto",height:"250px",size:"7px",color:"#000",position:"right",distance:"1px",start:"top",opacity:.4,alwaysVisible:!1,disableFadeOut:!1,railVisible:!1,railColor:"#333",railOpacity:.2,railDraggable:!0,railClass:"slimScrollRail",barClass:"slimScrollBar",wrapperClass:"slimScrollDiv",allowPageScroll:!1,wheelStep:20,touchScrollStep:200,borderRadius:"7px",railBorderRadius:"7px"},f);this.each(function(){function v(d){if(r){d=d||window.event;
var c=0;d.wheelDelta&&(c=-d.wheelDelta/120);d.detail&&(c=d.detail/3);e(d.target||d.srcTarget||d.srcElement).closest("."+a.wrapperClass).is(b.parent())&&n(c,!0);d.preventDefault&&!k&&d.preventDefault();k||(d.returnValue=!1)}}function n(d,g,e){k=!1;var f=b.outerHeight()-c.outerHeight();g&&(g=parseInt(c.css("top"))+d*parseInt(a.wheelStep)/100*c.outerHeight(),g=Math.min(Math.max(g,0),f),g=0=b.outerHeight()?k=!0:(c.stop(!0,
!0).fadeIn("fast"),a.railVisible&&m.stop(!0,!0).fadeIn("fast"))}function p(){a.alwaysVisible||(B=setTimeout(function(){a.disableFadeOut&&r||y||z||(c.fadeOut("slow"),m.fadeOut("slow"))},1E3))}var r,y,z,B,A,u,l,C,k=!1,b=e(this);if(b.parent().hasClass(a.wrapperClass)){var q=b.scrollTop(),c=b.siblings("."+a.barClass),m=b.siblings("."+a.railClass);x();if(e.isPlainObject(f)){if("height"in f&&"auto"==f.height){b.parent().css("height","auto");b.css("height","auto");var h=b.parent().parent().height();b.parent().css("height",
h);b.css("height",h)}else"height"in f&&(h=f.height,b.parent().css("height",h),b.css("height",h));if("scrollTo"in f)q=parseInt(a.scrollTo);else if("scrollBy"in f)q+=parseInt(a.scrollBy);else if("destroy"in f){c.remove();m.remove();b.unwrap();return}n(q,!1,!0)}}else if(!(e.isPlainObject(f)&&"destroy"in f)){a.height="auto"==a.height?b.parent().height():a.height;q=e("").addClass(a.wrapperClass).css({position:"relative",overflow:"hidden",width:a.width,height:a.height});b.css({overflow:"hidden",
width:a.width,height:a.height});var m=e("").addClass(a.railClass).css({width:a.size,height:"100%",position:"absolute",top:0,display:a.alwaysVisible&&a.railVisible?"block":"none","border-radius":a.railBorderRadius,background:a.railColor,opacity:a.railOpacity,zIndex:90}),c=e("").addClass(a.barClass).css({background:a.color,width:a.size,position:"absolute",top:0,opacity:a.opacity,display:a.alwaysVisible?"block":"none","border-radius":a.borderRadius,BorderRadius:a.borderRadius,MozBorderRadius:a.borderRadius,
WebkitBorderRadius:a.borderRadius,zIndex:99}),h="right"==a.position?{right:a.distance}:{left:a.distance};m.css(h);c.css(h);b.wrap(q);b.parent().append(c);b.parent().append(m);a.railDraggable&&c.bind("mousedown",function(a){var b=c.parent();z=!0;t=parseFloat(c.css("top"));pageY=a.pageY;b.bind("mousemove.slimscroll",function(a){currTop=t+a.pageY-pageY;c.css("top",currTop);n(0,c.position().top,!1)});b.bind("mouseup.slimscroll",function(a){z=!1;p();b.unbind(".slimscroll")});return!1}).bind("selectstart.slimscroll",
function(a){a.stopPropagation();a.preventDefault();return!1});m.hover(function(){w()},function(){p()});c.hover(function(){y=!0},function(){y=!1});b.hover(function(){r=!0;w();p()},function(){r=!1;p()});b.bind("touchstart",function(a,b){a.originalEvent.touches.length&&(A=a.originalEvent.touches[0].pageY)});b.bind("touchmove",function(b){k||b.originalEvent.preventDefault();b.originalEvent.touches.length&&(n((A-b.originalEvent.touches[0].pageY)/a.touchScrollStep,!0),A=b.originalEvent.touches[0].pageY)});
x();"bottom"===a.start?(c.css({top:b.outerHeight()-c.outerHeight()}),n(0,!0)):"top"!==a.start&&(n(e(a.start).position().top,null,!0),a.alwaysVisible||c.hide());window.addEventListener?(this.addEventListener("DOMMouseScroll",v,!1),this.addEventListener("mousewheel",v,!1)):document.attachEvent("onmousewheel",v)}});return this}});e.fn.extend({slimscroll:e.fn.slimScroll})})(jQuery);
/*!
* vanilla-picker v2.7.2 (MODIFIED by Pagelayer)
* https://vanilla-picker.js.org
*
* Copyright 2017-2019 Andreas Borgen (https://github.com/Sphinxxxx), Adam Brooks (https://github.com/dissimulate)
* Released under the ISC license.
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.pagelayer_Picker=t()}(this,function(){"use strict";var n=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},e=function(){function i(e,t){for(var r=0;r*{margin:.5em}.layout_default.picker_wrapper::before{content:'';display:block;width:100%;height:0;-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1}.layout_default .picker_slider,.layout_default .picker_selector{padding:1em}.layout_default .picker_hue{width:100%}.layout_default .picker_sl{-webkit-box-flex:1;-ms-flex:1 1 auto;flex:1 1 auto}.layout_default .picker_sl::before{content:'';display:block;padding-bottom:100%}.layout_default .picker_editor{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1;width:6rem}.layout_default .picker_editor input{width:calc(100% + 2px);height:calc(100% + 2px)}.layout_default .picker_sample{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1;-webkit-box-flex:1;-ms-flex:1 1 auto;flex:1 1 auto}.layout_default .picker_done{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1}.picker_wrapper{-webkit-box-sizing:border-box;box-sizing:border-box;background:#f2f2f2;-webkit-box-shadow:0 0 0 1px silver;box-shadow:0 0 0 1px silver;cursor:default;font-family:sans-serif;color:#444;pointer-events:auto}.picker_wrapper:focus{outline:none}.picker_wrapper button,.picker_wrapper input{margin:-1px}.picker_selector{position:absolute;z-index:1;display:block;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);border:2px solid white;border-radius:100%;-webkit-box-shadow:0 0 3px 1px #67b9ff;box-shadow:0 0 3px 1px #67b9ff;background:currentColor;cursor:pointer}.picker_slider .picker_selector{border-radius:2px}.picker_hue{position:relative;background-image:-webkit-gradient(linear, left top, right top, from(red), color-stop(yellow), color-stop(lime), color-stop(cyan), color-stop(blue), color-stop(magenta), to(red));background-image:linear-gradient(90deg, red, yellow, lime, cyan, blue, magenta, red);-webkit-box-shadow:0 0 0 1px silver;box-shadow:0 0 0 1px silver}.picker_sl{position:relative;-webkit-box-shadow:0 0 0 1px silver;box-shadow:0 0 0 1px silver;background-image:-webkit-gradient(linear, left top, left bottom, from(white), color-stop(50%, rgba(255,255,255,0))),-webkit-gradient(linear, left bottom, left top, from(black), color-stop(50%, rgba(0,0,0,0))),-webkit-gradient(linear, left top, right top, from(gray), to(rgba(128,128,128,0)));background-image:linear-gradient(180deg, white, rgba(255,255,255,0) 50%),linear-gradient(0deg, black, rgba(0,0,0,0) 50%),linear-gradient(90deg, gray, rgba(128,128,128,0))}.picker_alpha,.picker_sample{position:relative;background:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='2' height='2'%3E%3Cpath d='M1,0H0V1H2V2H1' fill='lightgrey'/%3E%3C/svg%3E\") left top/contain white;-webkit-box-shadow:0 0 0 1px silver;box-shadow:0 0 0 1px silver}.picker_alpha .picker_selector,.picker_sample .picker_selector{background:none}.picker_editor input{-webkit-box-sizing:border-box;box-sizing:border-box;font-family:monospace;padding:.1em .2em}.picker_sample::before{content:'';position:absolute;display:block;width:100%;height:100%;background:currentColor}.picker_done button{-webkit-box-sizing:border-box;box-sizing:border-box;padding:.2em .5em;cursor:pointer}.picker_arrow{position:absolute;z-index:-1}.picker_wrapper.popup{position:absolute;z-index:2;margin:1.5em}.picker_wrapper.popup,.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{background:#f2f2f2;-webkit-box-shadow:0 0 10px 1px rgba(0,0,0,0.4);box-shadow:0 0 10px 1px rgba(0,0,0,0.4)}.picker_wrapper.popup .picker_arrow{width:3em;height:3em;margin:0}.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{content:\"\";display:block;position:absolute;top:0;left:0;z-index:-99}.picker_wrapper.popup .picker_arrow::before{width:100%;height:100%;-webkit-transform:skew(45deg);transform:skew(45deg);-webkit-transform-origin:0 100%;transform-origin:0 100%}.picker_wrapper.popup .picker_arrow::after{width:150%;height:150%;-webkit-box-shadow:none;box-shadow:none}.popup.popup_top{bottom:100%;left:0}.popup.popup_top .picker_arrow{bottom:0;left:0;-webkit-transform:rotate(-90deg);transform:rotate(-90deg)}.popup.popup_bottom{top:100%;left:0}.popup.popup_bottom .picker_arrow{top:0;left:0;-webkit-transform:rotate(90deg) scale(1, -1);transform:rotate(90deg) scale(1, -1)}.popup.popup_left{top:0;right:100%}.popup.popup_left .picker_arrow{top:0;right:0;-webkit-transform:scale(-1, 1);transform:scale(-1, 1)}.popup.popup_right{top:0;left:100%}.popup.popup_right .picker_arrow{top:0;left:0}"}}(e.doc),this.setOptions(e)}return e(r,[{key:"setOptions",value:function(e){if(e){var t=this.settings;if(e instanceof HTMLElement)t.parent=e;else{t.parent&&e.parent&&t.parent!==e.parent&&(t.parent.removeEventListener("click",this._openProxy,!1),this._popupInited=!1),function(e,t,r){for(var i in e)r&&0<=r.indexOf(i)||(t[i]=e[i])}(e,t),e.onChange&&(this.onChange=e.onChange),e.onDone&&(this.onDone=e.onDone),e.onOpen&&(this.onOpen=e.onOpen),e.onClose&&(this.onClose=e.onClose);var r=e.color||e.colour;r&&this._setColor(r)}var i=t.parent;i&&t.popup&&!this._popupInited?(f(i,"click",this._openProxy),d(i,[" ","Spacebar","Enter"],this._openProxy),this._popupInited=!0):e.parent&&!t.popup&&this.show()}}},{key:"openHandler",value:function(e){if(this.show()){e&&e.preventDefault(),this.settings.parent.style.pointerEvents="none";var t=e&&e.type===l?this._domEdit:this.domElement;setTimeout(function(){return t.focus()},100),this.onOpen&&this.onOpen(this.colour)}}},{key:"closeHandler",value:function(e){var t=e&&e.type,r=!1;e?t===p||t===c?this.domElement.contains(e.target)||(r=!0):(u(e),r=!0):r=!0,r&&this.hide()&&(this.settings.parent.style.pointerEvents="",t!==p&&this.settings.parent.focus(),this.onClose&&this.onClose(this.colour))}},{key:"movePopup",value:function(e,t){this.closeHandler(),this.setOptions(e),t&&this.openHandler()}},{key:"setColor",value:function(e,t){this._setColor(e,{silent:t})}},{key:"_setColor",value:function(e,t){if("string"==typeof e&&(e=e.trim()),e){t=t||{};var r=void 0;try{r=new a(e)}catch(e){if(t.failSilently)return;throw e}if(!this.settings.alpha){var i=r.hsla;i[3]=1,r.hsla=i}this.colour=this.color=r,this._setHSLA(null,null,null,null,t)}}},{key:"setColour",value:function(e,t){this.setColor(e,t)}},{key:"show",value:function(){if(!this.settings.parent)return!1;if(this.domElement){var e=this._toggleDOM(!0);return this._setPosition(),e}var t,r,i,o=this.settings.template||'
").append(n);a(t.o.tagsToRemove.join(","),o).remove(),t.$ed.html(o.contents().html())}if(t.o.autogrow&&(t.height=t.$ed.height(),t.height!==t.$ta.css("height")&&(t.$ta.css({height:t.height}),t.$c.trigger("tbwresize"))),t.o.autogrowOnEnter){t.$ed.height("auto");var r=t.autogrowOnEnterWasFocused?t.$ed[0].scrollHeight:t.$ed.css("min-height");r!==t.$ta.css("height")&&(t.$ed.css({height:r}),t.$c.trigger("tbwresize"))}},semanticCode:function(e,t,n){var o=this;if(o.saveRange(),o.syncCode(e),o.o.semantic){if(o.semanticTag("b"),o.semanticTag("i"),o.semanticTag("s"),o.semanticTag("strike"),t){var r=o.o.inlineElementsSelector,i=":not("+r+")";o.$ed.contents().filter(function(){return 3===this.nodeType&&this.nodeValue.trim().length>0}).wrap("");var s=function(e){if(0!==e.length){var t=e.nextUntil(i).addBack().wrapAll("").parent(),n=t.nextAll(r).first();t.next("br").remove(),s(n)}};s(o.$ed.children(r).first()),o.semanticTag("div",!0),o.$ed.find("p").filter(function(){return(!o.range||this!==o.range.startContainer)&&(0===a(this).text().trim().length&&0===a(this).children().not("br,span").length)}).contents().unwrap(),a("[data-tbw]",o.$ed).contents().unwrap(),o.$ed.find("p:empty").remove()}n||o.restoreRange(),o.syncTextarea()}},semanticTag:function(e,t){var n;if(null!=this.o.semantic&&"object"==typeof this.o.semantic&&this.o.semantic.hasOwnProperty(e))n=this.o.semantic[e];else{if(this.o.semantic!==!0||!this.DEFAULT_SEMANTIC_MAP.hasOwnProperty(e))return;n=this.DEFAULT_SEMANTIC_MAP[e]}a(e,this.$ed).each(function(){var e=a(this);return 0!==e.contents().length&&(e.wrap("<"+n+"/>"),t&&a.each(e.prop("attributes"),function(){e.parent().attr(this.name,this.value)}),void e.contents().unwrap())})},createLink:function(){for(var e,t,n,o=this,r=o.doc.getSelection(),i=r.focusNode,s=(new XMLSerializer).serializeToString(r.getRangeAt(0).cloneContents());["A","DIV"].indexOf(i.nodeName)<0;)i=i.parentNode;if(i&&"A"===i.nodeName){var l=a(i);s=l.text(),e=l.attr("href"),o.o.minimalLinks||(t=l.attr("title"),n=l.attr("target"));var d=o.doc.createRange();d.selectNode(i),r.removeAllRanges(),r.addRange(d)}o.saveRange();var c={url:{label:"URL",required:!0,value:e},text:{label:o.lang.text,value:s}};o.o.minimalLinks||Object.assign(c,{title:{label:o.lang.title,value:t},target:{label:o.lang.target,value:n}}),o.openModalInsert(o.lang.createLink,c,function(e){var t=o.prependUrlPrefix(e.url);if(!t.length)return!1;var n=a(['',e.text||e.url,""].join(""));return o.o.minimalLinks||(e.title.length>0&&n.attr("title",e.title),e.target.length>0&&n.attr("target",e.target)),o.range.deleteContents(),o.range.insertNode(n[0]),o.syncCode(),o.$c.trigger("tbwchange"),!0})},prependUrlPrefix:function(e){var t=this;if(!t.urlPrefix)return e;var n=/^([a-z][-+.a-z0-9]*:|\/|#)/i;if(n.test(e))return e;var a=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return a.test(e)?"mailto:"+e:t.urlPrefix+e},unlink:function(){var e=this,t=e.doc.getSelection(),n=t.focusNode;if(t.isCollapsed){for(;["A","DIV"].indexOf(n.nodeName)<0;)n=n.parentNode;if(n&&"A"===n.nodeName){var a=e.doc.createRange();a.selectNode(n),t.removeAllRanges(),t.addRange(a)}}e.execCmd("unlink",void 0,void 0,!0)},insertImage:function(){var e=this;e.saveRange();var t={url:{label:"URL",required:!0},alt:{label:e.lang.description,value:e.getRangeText()}};e.o.imageWidthModalEdit&&(t.width={}),e.openModalInsert(e.lang.insertImage,t,function(t){e.execCmd("insertImage",t.url,!1,!0);var n=a('img[src="'+t.url+'"]:not([alt])',e.$box);return n.attr("alt",t.alt),e.o.imageWidthModalEdit&&n.attr({width:t.width}),e.syncCode(),e.$c.trigger("tbwchange"),!0})},fullscreen:function(){var e,n=this,o=n.o.prefix,r=o+"fullscreen";n.$box.toggleClass(r),e=n.$box.hasClass(r),a("body").toggleClass(o+"body-fullscreen",e),a(t).trigger("scroll"),n.$c.trigger("tbw"+(e?"open":"close")+"fullscreen")},execCmd:function(e,t,n,a){var o=this;a=!!a||"","dropdown"!==e&&o.$ed.focus();try{o.doc.execCommand("styleWithCSS",!1,n||!1)}catch(r){}try{o[e+a](t)}catch(r){try{e(t)}catch(i){"insertHorizontalRule"===e?t=void 0:"formatBlock"===e&&o.isIE&&(t="<"+t+">"),o.doc.execCommand(e,!1,t),o.syncCode(),o.semanticCode(!1,!0)}"dropdown"!==e&&(o.updateButtonPaneStatus(),o.$c.trigger("tbwchange"))}},openModal:function(e,n){var i=this,s=i.o.prefix;if(a("."+s+"modal-box",i.$box).length>0)return!1;i.o.autogrowOnEnter&&(i.autogrowOnEnterDontClose=!0),i.saveRange(),i.showOverlay(),i.$btnPane.addClass(s+"disable");var l=a("",{"class":s+"modal "+s+"fixed-top"}).css({top:i.$box.offset().top+i.$btnPane.height(),zIndex:99999}).appendTo(a(i.doc.body));i.$overlay.one("click",function(){return l.trigger(r),!1});var d=a("",{action:"",html:n}).on("submit",function(){return l.trigger(o),!1}).on("reset",function(){return l.trigger(r),!1}).on("submit reset",function(){i.o.autogrowOnEnter&&(i.autogrowOnEnterDontClose=!1)}),c=a("",{"class":s+"modal-box",html:d}).css({top:"-"+i.$btnPane.outerHeight()+"px",opacity:0}).appendTo(l).animate({top:0,opacity:1},100);return a("",{text:e,"class":s+"modal-title"}).prependTo(c),l.height(c.outerHeight()+10),a("input:first",c).focus(),i.buildModalBtn("submit",c),i.buildModalBtn("reset",c),a(t).trigger("scroll"),l},buildModalBtn:function(e,t){var n=this,o=n.o.prefix;return a("",{"class":o+"modal-button "+o+"modal-"+e,type:e,text:n.lang[e]||e}).appendTo(a("form",t))},closeModal:function(){var e=this,t=e.o.prefix;e.$btnPane.removeClass(t+"disable"),e.$overlay.off();var o=a("."+t+"modal-box",a(n.body));o.animate({top:"-"+o.height()},100,function(){o.parent().remove(),e.hideOverlay()}),e.restoreRange()},openModalInsert:function(e,t,n){var i=this,s=i.o.prefix,l=i.lang,d="";return a.each(t,function(e,t){var n=t.label||e,a=t.name||e,o=t.attributes||{},r=Object.keys(o).map(function(e){return e+'="'+o[e]+'"'}).join(" ");d+='"}),i.openModal(e,d).on(o,function(){var e=a("form",a(this)),r=!0,s={};a.each(t,function(t,n){var o=n.name||t,l=a('input[name="'+o+'"]',e),d=l.attr("type");switch(d.toLowerCase()){case"checkbox":s[o]=l.is(":checked");break;case"radio":s[o]=l.filter(":checked").val();break;default:s[o]=a.trim(l.val())}n.required&&""===s[o]?(r=!1,i.addErrorOnModalField(l,i.lang.required)):n.pattern&&!n.pattern.test(s[o])&&(r=!1,i.addErrorOnModalField(l,n.patternError))}),r&&(i.restoreRange(),n(s,t)&&(i.syncCode(),i.$c.trigger("tbwchange"),i.closeModal(),a(this).off(o)))}).one(r,function(){a(this).off(o),i.closeModal()})},addErrorOnModalField:function(e,t){var n=this.o.prefix,o=e.parent();e.on("change keyup",function(){o.removeClass(n+"input-error")}),o.addClass(n+"input-error").find("input+span").append(a("",{"class":n+"msg-error",text:t}))},getDefaultImgDblClickHandler:function(){var e=this;return function(){var t=a(this),n=t.attr("src"),o="(Base64)";0===n.indexOf("data:image")&&(n=o);var r={url:{label:"URL",value:n,required:!0},alt:{label:e.lang.description,value:t.attr("alt")}};return e.o.imageWidthModalEdit&&(r.width={value:t.attr("width")?t.attr("width"):""}),e.openModalInsert(e.lang.insertImage,r,function(n){return n.url!==o&&t.attr({src:n.url}),t.attr({alt:n.alt}),e.o.imageWidthModalEdit&&(parseInt(n.width)>0?t.attr({width:n.width}):t.removeAttr("width")),!0}),!1}},saveRange:function(){var e=this,t=e.doc.getSelection();if(e.range=null,t&&t.rangeCount){var n,a=e.range=t.getRangeAt(0),o=e.doc.createRange();o.selectNodeContents(e.$ed[0]),o.setEnd(a.startContainer,a.startOffset),n=(o+"").length,e.metaRange={start:n,end:n+(a+"").length}}},restoreRange:function(){var e,t=this,n=t.metaRange,a=t.range,o=t.doc.getSelection();if(a){if(n&&n.start!==n.end){var r,i=0,s=[t.$ed[0]],l=!1,d=!1;for(e=t.doc.createRange();!d&&(r=s.pop());)if(3===r.nodeType){var c=i+r.length;!l&&n.start>=i&&n.start<=c&&(e.setStart(r,n.start-i),l=!0),l&&n.end>=i&&n.end<=c&&(e.setEnd(r,n.end-i),d=!0),i=c}else for(var u=r.childNodes,g=u.length;g>0;)g-=1,s.push(u[g])}o.removeAllRanges(),o.addRange(e||a)}},getRangeText:function(){return this.range+""},updateButtonPaneStatus:function(){var e=this,t=e.o.prefix,n=e.getTagsRecursive(e.doc.getSelection().focusNode),o=t+"active-button "+t+"active";a("."+t+"active-button",e.$btnPane).removeClass(o),a.each(n,function(n,r){var i=e.tagToButton[r.toLowerCase()],s=a("."+t+i+"-button",e.$btnPane);if(s.length>0)s.addClass(o);else try{s=a("."+t+"dropdown ."+t+i+"-dropdown-button",e.$box);var l=s.parent().data("dropdown");a("."+t+l+"-button",e.$box).addClass(o)}catch(d){}})},getTagsRecursive:function(e,t){var n=this;if(t=t||(e&&e.tagName?[e.tagName]:[]),!e||!e.parentNode)return t;e=e.parentNode;var o=e.tagName;return"DIV"===o?t:("P"===o&&""!==e.style.textAlign&&t.push(e.style.textAlign),a.each(n.tagHandlers,function(a,o){t=t.concat(o(e,n))}),t.push(o),n.getTagsRecursive(e,t).filter(function(e){return null!=e}))},initPlugins:function(){var e=this;e.loadedPlugins=[],a.each(a.trumbowyg.plugins,function(t,n){n.shouldInit&&!n.shouldInit(e)||(n.init(e),n.tagHandler&&e.tagHandlers.push(n.tagHandler),e.loadedPlugins.push(n))})},destroyPlugins:function(){a.each(this.loadedPlugins,function(e,t){t.destroy&&t.destroy()})}}}(navigator,window,document,jQuery);
/**
* Trumbowyg v2.14.0 - A lightweight WYSIWYG editor
* Trumbowyg core file
* ------------------------
* @link http://alex-d.github.io/Trumbowyg
* @license MIT
* @author Alexandre Demode (Alex-D)
* Twitter : @AlexandreDemode
* Website : alex-d.fr
*/
jQuery.trumbowyg = {
langs: {
en: {
viewHTML: 'View HTML',
undo: 'Undo',
redo: 'Redo',
formatting: 'Formatting',
p: 'Paragraph',
blockquote: 'Quote',
code: 'Code',
header: 'Header',
bold: 'Bold',
italic: 'Italic',
strikethrough: 'Stroke',
underline: 'Underline',
strong: 'Strong',
em: 'Emphasis',
del: 'Deleted',
superscript: 'Superscript',
subscript: 'Subscript',
unorderedList: 'Unordered list',
orderedList: 'Ordered list',
insertImage: 'Insert Image',
link: 'Link',
createLink: 'Insert link',
unlink: 'Remove link',
justifyLeft: 'Align Left',
justifyCenter: 'Align Center',
justifyRight: 'Align Right',
justifyFull: 'Align Justify',
horizontalRule: 'Insert horizontal rule',
removeformat: 'Remove format',
fullscreen: 'Fullscreen',
close: 'Close',
submit: 'Confirm',
reset: 'Cancel',
required: 'Required',
description: 'Description',
title: 'Title',
text: 'Text',
target: 'Target',
width: 'Width'
}
},
// Plugins
plugins: {},
// SVG Path globally
svgPath: null,
hideButtonTexts: null
};
// Makes default options read-only
Object.defineProperty(jQuery.trumbowyg, 'defaultOptions', {
value: {
lang: 'en',
fixedBtnPane: false,
fixedFullWidth: false,
autogrow: false,
autogrowOnEnter: false,
imageWidthModalEdit: false,
prefix: 'trumbowyg-',
semantic: true,
resetCss: false,
removeformatPasted: false,
tagsToRemove: [],
tagsToKeep: ['hr', 'img', 'embed', 'iframe', 'input'],
btns: [
['viewHTML'],
['undo', 'redo'], // Only supported in Blink browsers
['formatting'],
['strong', 'em', 'del'],
['superscript', 'subscript'],
['link'],
['insertImage'],
['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
['unorderedList', 'orderedList'],
['horizontalRule'],
['removeformat'],
['fullscreen']
],
// For custom button definitions
btnsDef: {},
inlineElementsSelector: 'a,abbr,acronym,b,caption,cite,code,col,dfn,dir,dt,dd,em,font,hr,i,kbd,li,q,span,strikeout,strong,sub,sup,u',
pasteHandlers: [],
// imgDblClickHandler: default is defined in constructor
plugins: {},
urlProtocol: false,
minimalLinks: false
},
writable: false,
enumerable: true,
configurable: false
});
(function (navigator, window, document, $) {
'use strict';
var CONFIRM_EVENT = 'tbwconfirm',
CANCEL_EVENT = 'tbwcancel';
$.fn.trumbowyg = function (options, params) {
var trumbowygDataName = 'trumbowyg';
if (options === Object(options) || !options) {
return this.each(function () {
if (!$(this).data(trumbowygDataName)) {
$(this).data(trumbowygDataName, new Trumbowyg(this, options));
}
});
}
if (this.length === 1) {
try {
var t = $(this).data(trumbowygDataName);
switch (options) {
// Exec command
case 'execCmd':
return t.execCmd(params.cmd, params.param, params.forceCss);
// Modal box
case 'openModal':
return t.openModal(params.title, params.content);
case 'closeModal':
return t.closeModal();
case 'openModalInsert':
return t.openModalInsert(params.title, params.fields, params.callback);
// Range
case 'saveRange':
return t.saveRange();
case 'getRange':
return t.range;
case 'getRangeText':
return t.getRangeText();
case 'restoreRange':
return t.restoreRange();
// Enable/disable
case 'enable':
return t.setDisabled(false);
case 'disable':
return t.setDisabled(true);
// Toggle
case 'toggle':
return t.toggle();
// Destroy
case 'destroy':
return t.destroy();
// Empty
case 'empty':
return t.empty();
// HTML
case 'html':
return t.html(params);
}
} catch (c) {
}
}
return false;
};
// @param: editorElem is the DOM element
var Trumbowyg = function (editorElem, options) {
var t = this,
trumbowygIconsId = 'trumbowyg-icons',
$trumbowyg = $.trumbowyg;
// Get the document of the element. It use to makes the plugin
// compatible on iframes.
t.doc = editorElem.ownerDocument || document;
// jQuery object of the editor
t.$ta = $(editorElem); // $ta : Textarea
t.$c = $(editorElem); // $c : creator
options = options || {};
// Localization management
if (options.lang != null || $trumbowyg.langs[options.lang] != null) {
t.lang = $.extend(true, {}, $trumbowyg.langs.en, $trumbowyg.langs[options.lang]);
} else {
t.lang = $trumbowyg.langs.en;
}
t.hideButtonTexts = $trumbowyg.hideButtonTexts != null ? $trumbowyg.hideButtonTexts : options.hideButtonTexts;
// SVG path
var svgPathOption = $trumbowyg.svgPath != null ? $trumbowyg.svgPath : options.svgPath;
t.hasSvg = svgPathOption !== false;
t.svgPath = !!t.doc.querySelector('base') ? window.location.href.split('#')[0] : '';
if ($('#' + trumbowygIconsId, t.doc).length === 0 && svgPathOption !== false) {
if (svgPathOption == null) {
// Hack to get svgPathOption based on trumbowyg.js path
var scriptElements = document.getElementsByTagName('script');
for (var i = 0; i < scriptElements.length; i += 1) {
var source = scriptElements[i].src;
var matches = source.match('trumbowyg(\.min)?\.js');
if (matches != null) {
svgPathOption = source.substring(0, source.indexOf(matches[0])) + 'ui/icons.svg';
}
}
if (svgPathOption == null) {
console.warn('You must define svgPath: https://goo.gl/CfTY9U'); // jshint ignore:line
}
}
var div = t.doc.createElement('div');
div.id = trumbowygIconsId;
t.doc.body.insertBefore(div, t.doc.body.childNodes[0]);
$.ajax({
async: true,
type: 'GET',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
dataType: 'xml',
crossDomain: true,
url: svgPathOption,
data: null,
beforeSend: null,
complete: null,
success: function (data) {
div.innerHTML = new XMLSerializer().serializeToString(data.documentElement);
}
});
}
/**
* When the button is associated to a empty object
* fn and title attributs are defined from the button key value
*
* For example
* foo: {}
* is equivalent to :
* foo: {
* fn: 'foo',
* title: this.lang.foo
* }
*/
var h = t.lang.header, // Header translation
isBlinkFunction = function () {
return (window.chrome || (window.Intl && Intl.v8BreakIterator)) && 'CSS' in window;
};
t.btnsDef = {
viewHTML: {
fn: 'toggle',
class: 'trumbowyg-not-disable',
},
undo: {
isSupported: isBlinkFunction,
key: 'Z'
},
redo: {
isSupported: isBlinkFunction,
key: 'Y'
},
p: {
fn: 'formatBlock'
},
blockquote: {
fn: 'formatBlock'
},
h1: {
fn: 'formatBlock',
title: h + ' 1'
},
h2: {
fn: 'formatBlock',
title: h + ' 2'
},
h3: {
fn: 'formatBlock',
title: h + ' 3'
},
h4: {
fn: 'formatBlock',
title: h + ' 4'
},
subscript: {
tag: 'sub'
},
superscript: {
tag: 'sup'
},
bold: {
key: 'B',
tag: 'b'
},
italic: {
key: 'I',
tag: 'i'
},
underline: {
tag: 'u'
},
strikethrough: {
tag: 'strike'
},
strong: {
fn: 'bold',
key: 'B'
},
em: {
fn: 'italic',
key: 'I'
},
del: {
fn: 'strikethrough'
},
createLink: {
key: 'K',
tag: 'a'
},
unlink: {},
insertImage: {},
justifyLeft: {
tag: 'left',
forceCss: true
},
justifyCenter: {
tag: 'center',
forceCss: true
},
justifyRight: {
tag: 'right',
forceCss: true
},
justifyFull: {
tag: 'justify',
forceCss: true
},
unorderedList: {
fn: 'insertUnorderedList',
tag: 'ul'
},
orderedList: {
fn: 'insertOrderedList',
tag: 'ol'
},
horizontalRule: {
fn: 'insertHorizontalRule'
},
removeformat: {},
fullscreen: {
class: 'trumbowyg-not-disable'
},
close: {
fn: 'destroy',
class: 'trumbowyg-not-disable'
},
// Dropdowns
formatting: {
dropdown: ['p', 'blockquote', 'h1', 'h2', 'h3', 'h4'],
ico: 'p'
},
link: {
dropdown: ['createLink', 'unlink']
}
};
// Defaults Options
t.o = $.extend(true, {}, $trumbowyg.defaultOptions, options);
if (!t.o.hasOwnProperty('imgDblClickHandler')) {
t.o.imgDblClickHandler = t.getDefaultImgDblClickHandler();
}
t.urlPrefix = t.setupUrlPrefix();
t.disabled = t.o.disabled || (editorElem.nodeName === 'TEXTAREA' && editorElem.disabled);
if (options.btns) {
t.o.btns = options.btns;
} else if (!t.o.semantic) {
t.o.btns[3] = ['bold', 'italic', 'underline', 'strikethrough'];
}
$.each(t.o.btnsDef, function (btnName, btnDef) {
t.addBtnDef(btnName, btnDef);
});
// put this here in the event it would be merged in with options
t.eventNamespace = 'trumbowyg-event';
// Keyboard shortcuts are load in this array
t.keys = [];
// Tag to button dynamically hydrated
t.tagToButton = {};
t.tagHandlers = [];
// Admit multiple paste handlers
t.pasteHandlers = [].concat(t.o.pasteHandlers);
// Check if browser is IE
t.isIE = (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') !== -1);
t.init();
};
Trumbowyg.prototype = {
DEFAULT_SEMANTIC_MAP: {
'b': 'strong',
'i': 'em',
's': 'del',
'strike': 'del',
'div': 'p'
},
init: function () {
var t = this;
t.height = t.$ta.height();
t.initPlugins();
try {
// Disable image resize, try-catch for old IE
t.doc.execCommand('enableObjectResizing', false, false);
t.doc.execCommand('defaultParagraphSeparator', false, 'p');
} catch (e) {
}
t.buildEditor();
t.buildBtnPane();
t.fixedBtnPaneEvents();
t.buildOverlay();
setTimeout(function () {
if (t.disabled) {
t.setDisabled(true);
}
t.$c.trigger('tbwinit');
});
},
addBtnDef: function (btnName, btnDef) {
this.btnsDef[btnName] = btnDef;
},
setupUrlPrefix: function () {
var protocol = this.o.urlProtocol;
if (!protocol) {
return;
}
if (typeof(protocol) !== 'string') {
return 'https://';
}
return /:\/\/$/.test(protocol) ? protocol : protocol + '://';
},
buildEditor: function () {
var t = this,
prefix = t.o.prefix,
html = '';
t.$box = $('', {
class: prefix + 'box ' + prefix + 'editor-visible ' + prefix + t.o.lang + ' trumbowyg'
});
// $ta = Textarea
// $ed = Editor
t.isTextarea = t.$ta.is('textarea');
if (t.isTextarea) {
html = t.$ta.val();
t.$ed = $('');
t.$box
.insertAfter(t.$ta)
.append(t.$ed, t.$ta);
} else {
t.$ed = t.$ta;
html = t.$ed.html();
t.$ta = $('', {
name: t.$ta.attr('id'),
height: t.height
}).val(html);
t.$box
.insertAfter(t.$ed)
.append(t.$ta, t.$ed);
t.syncCode();
}
t.$ta
.addClass(prefix + 'textarea')
.attr('tabindex', -1)
;
t.$ed
.addClass(prefix + 'editor')
.attr({
contenteditable: true,
dir: t.lang._dir || 'ltr'
})
.html(html)
;
if (t.o.tabindex) {
t.$ed.attr('tabindex', t.o.tabindex);
}
if (t.$c.is('[placeholder]')) {
t.$ed.attr('placeholder', t.$c.attr('placeholder'));
}
if (t.$c.is('[spellcheck]')) {
t.$ed.attr('spellcheck', t.$c.attr('spellcheck'));
}
if (t.o.resetCss) {
t.$ed.addClass(prefix + 'reset-css');
}
if (!t.o.autogrow) {
t.$ta.add(t.$ed).css({
height: t.height
});
}
t.semanticCode();
if (t.o.autogrowOnEnter) {
t.$ed.addClass(prefix + 'autogrow-on-enter');
}
var ctrl = false,
composition = false,
debounceButtonPaneStatus,
updateEventName = 'keyup';
t.$ed
.on('dblclick', 'img', t.o.imgDblClickHandler)
.on('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && !e.altKey) {
ctrl = true;
var key = t.keys[String.fromCharCode(e.which).toUpperCase()];
try {
t.execCmd(key.fn, key.param);
return false;
} catch (c) {
}
}
})
.on('compositionstart compositionupdate', function () {
composition = true;
})
.on(updateEventName + ' compositionend', function (e) {
if (e.type === 'compositionend') {
composition = false;
} else if (composition) {
return;
}
var keyCode = e.which;
if (keyCode >= 37 && keyCode <= 40) {
return;
}
if ((e.ctrlKey || e.metaKey) && (keyCode === 89 || keyCode === 90)) {
t.semanticCode(false, true);
t.$c.trigger('tbwchange');
} else if (!ctrl && keyCode !== 17) {
var compositionEndIE = t.isIE ? e.type === 'compositionend' : true;
t.semanticCode(false, compositionEndIE && keyCode === 13);
t.$c.trigger('tbwchange');
} else if (typeof e.which === 'undefined') {
t.semanticCode(false, false, true);
}
setTimeout(function () {
ctrl = false;
}, 50);
})
.on('mouseup keydown keyup', function (e) {
if ((!e.ctrlKey && !e.metaKey) || e.altKey) {
setTimeout(function () { // "hold on" to the ctrl key for 50ms
ctrl = false;
}, 50);
}
clearTimeout(debounceButtonPaneStatus);
debounceButtonPaneStatus = setTimeout(function () {
t.updateButtonPaneStatus();
}, 50);
})
.on('focus blur', function (e) {
t.$c.trigger('tbw' + e.type);
if (e.type === 'blur') {
$('.' + prefix + 'active-button', t.$btnPane).removeClass(prefix + 'active-button ' + prefix + 'active');
}
if (t.o.autogrowOnEnter) {
if (t.autogrowOnEnterDontClose) {
return;
}
if (e.type === 'focus') {
t.autogrowOnEnterWasFocused = true;
t.autogrowEditorOnEnter();
}
else if (!t.o.autogrow) {
t.$ed.css({height: t.$ed.css('min-height')});
t.$c.trigger('tbwresize');
}
}
})
.on('cut drop', function () {
setTimeout(function () {
t.semanticCode(false, true);
t.$c.trigger('tbwchange');
}, 0);
})
.on('paste', function (e) {
if (t.o.removeformatPasted) {
e.preventDefault();
if (window.getSelection && window.getSelection().deleteFromDocument) {
window.getSelection().deleteFromDocument();
}
try {
// IE
var text = window.clipboardData.getData('Text');
try {
// <= IE10
t.doc.selection.createRange().pasteHTML(text);
} catch (c) {
// IE 11
t.doc.getSelection().getRangeAt(0).insertNode(t.doc.createTextNode(text));
}
t.$c.trigger('tbwchange', e);
} catch (d) {
// Not IE
t.execCmd('insertText', (e.originalEvent || e).clipboardData.getData('text/plain'));
}
}
// Call pasteHandlers
$.each(t.pasteHandlers, function (i, pasteHandler) {
pasteHandler(e);
});
setTimeout(function () {
t.semanticCode(false, true);
t.$c.trigger('tbwpaste', e);
t.$c.trigger('tbwchange');
}, 0);
});
t.$ta
.on('keyup', function () {
t.$c.trigger('tbwchange');
})
.on('paste', function () {
setTimeout(function () {
t.$c.trigger('tbwchange');
}, 0);
});
t.$box.on('keydown', function (e) {
if (e.which === 27 && $('.' + prefix + 'modal-box', t.$box).length === 1) {
t.closeModal();
return false;
}
});
},
//autogrow when entering logic
autogrowEditorOnEnter: function () {
var t = this;
t.$ed.removeClass('autogrow-on-enter');
var oldHeight = t.$ed[0].clientHeight;
t.$ed.height('auto');
var totalHeight = t.$ed[0].scrollHeight;
t.$ed.addClass('autogrow-on-enter');
if (oldHeight !== totalHeight) {
t.$ed.height(oldHeight);
setTimeout(function () {
t.$ed.css({height: totalHeight});
t.$c.trigger('tbwresize');
}, 0);
}
},
// Build button pane, use o.btns option
buildBtnPane: function () {
var t = this,
prefix = t.o.prefix;
var $btnPane = t.$btnPane = $('', {
class: prefix + 'button-pane'
});
$.each(t.o.btns, function (i, btnGrp) {
if (!$.isArray(btnGrp)) {
btnGrp = [btnGrp];
}
var $btnGroup = $('', {
class: prefix + 'button-group ' + ((btnGrp.indexOf('fullscreen') >= 0) ? prefix + 'right' : '')
});
$.each(btnGrp, function (i, btn) {
try { // Prevent buildBtn error
if (t.isSupportedBtn(btn)) { // It's a supported button
$btnGroup.append(t.buildBtn(btn));
}
} catch (c) {
}
});
if ($btnGroup.html().trim().length > 0) {
$btnPane.append($btnGroup);
}
});
t.$box.prepend($btnPane);
},
// Build a button and his action
buildBtn: function (btnName) { // btnName is name of the button
var t = this,
prefix = t.o.prefix,
btn = t.btnsDef[btnName],
isDropdown = btn.dropdown,
hasIcon = btn.hasIcon != null ? btn.hasIcon : true,
textDef = t.lang[btnName] || btnName,
$btn = $('', {
type: 'button',
class: prefix + btnName + '-button ' + (btn.class || '') + (!hasIcon ? ' ' + prefix + 'textual-button' : ''),
html: t.hasSvg && hasIcon ?
'' :
t.hideButtonTexts ? '' : (btn.text || btn.title || t.lang[btnName] || btnName),
title: (btn.title || btn.text || textDef) + ((btn.key) ? ' (Ctrl + ' + btn.key + ')' : ''),
tabindex: -1,
mousedown: function () {
if (!isDropdown || $('.' + btnName + '-' + prefix + 'dropdown', t.$box).is(':hidden')) {
$('body', t.doc).trigger('mousedown');
}
if ((t.$btnPane.hasClass(prefix + 'disable') || t.$box.hasClass(prefix + 'disabled')) &&
!$(this).hasClass(prefix + 'active') &&
!$(this).hasClass(prefix + 'not-disable')) {
return false;
}
t.execCmd((isDropdown ? 'dropdown' : false) || btn.fn || btnName, btn.param || btnName, btn.forceCss);
return false;
}
});
if (isDropdown) {
$btn.addClass(prefix + 'open-dropdown');
var dropdownPrefix = prefix + 'dropdown',
dropdownOptions = { // the dropdown
class: dropdownPrefix + '-' + btnName + ' ' + dropdownPrefix + ' ' + prefix + 'fixed-top'
};
dropdownOptions['data-' + dropdownPrefix] = btnName;
var $dropdown = $('', dropdownOptions);
$.each(isDropdown, function (i, def) {
if (t.btnsDef[def] && t.isSupportedBtn(def)) {
$dropdown.append(t.buildSubBtn(def));
}
});
t.$box.append($dropdown.hide());
} else if (btn.key) {
t.keys[btn.key] = {
fn: btn.fn || btnName,
param: btn.param || btnName
};
}
if (!isDropdown) {
t.tagToButton[(btn.tag || btnName).toLowerCase()] = btnName;
}
return $btn;
},
// Build a button for dropdown menu
// @param n : name of the subbutton
buildSubBtn: function (btnName) {
var t = this,
prefix = t.o.prefix,
btn = t.btnsDef[btnName],
hasIcon = btn.hasIcon != null ? btn.hasIcon : true;
if (btn.key) {
t.keys[btn.key] = {
fn: btn.fn || btnName,
param: btn.param || btnName
};
}
t.tagToButton[(btn.tag || btnName).toLowerCase()] = btnName;
return $('', {
type: 'button',
class: prefix + btnName + '-dropdown-button' + (btn.ico ? ' ' + prefix + btn.ico + '-button' : ''),
html: t.hasSvg && hasIcon ? '' + (btn.text || btn.title || t.lang[btnName] || btnName) : (btn.text || btn.title || t.lang[btnName] || btnName),
title: ((btn.key) ? ' (Ctrl + ' + btn.key + ')' : null),
style: btn.style || null,
mousedown: function () {
$('body', t.doc).trigger('mousedown');
t.execCmd(btn.fn || btnName, btn.param || btnName, btn.forceCss);
return false;
}
});
},
// Check if button is supported
isSupportedBtn: function (b) {
try {
return this.btnsDef[b].isSupported();
} catch (c) {
}
return true;
},
// Build overlay for modal box
buildOverlay: function () {
var t = this;
t.$overlay = $('', {
class: t.o.prefix + 'overlay'
}).appendTo(t.$box);
return t.$overlay;
},
showOverlay: function () {
var t = this;
$(window).trigger('scroll');
t.$overlay.fadeIn(200);
t.$box.addClass(t.o.prefix + 'box-blur');
},
hideOverlay: function () {
var t = this;
t.$overlay.fadeOut(50);
t.$box.removeClass(t.o.prefix + 'box-blur');
},
// Management of fixed button pane
fixedBtnPaneEvents: function () {
var t = this,
fixedFullWidth = t.o.fixedFullWidth,
$box = t.$box;
if (!t.o.fixedBtnPane) {
return;
}
t.isFixed = false;
$(window)
.on('scroll.' + t.eventNamespace + ' resize.' + t.eventNamespace, function () {
if (!$box) {
return;
}
t.syncCode();
var scrollTop = $(window).scrollTop(),
offset = $box.offset().top + 1,
bp = t.$btnPane,
oh = bp.outerHeight() - 2;
if ((scrollTop - offset > 0) && ((scrollTop - offset - t.height) < 0)) {
if (!t.isFixed) {
t.isFixed = true;
bp.css({
position: 'fixed',
top: 0,
left: fixedFullWidth ? '0' : 'auto',
zIndex: 7
});
$([t.$ta, t.$ed]).css({marginTop: bp.height()});
}
bp.css({
width: fixedFullWidth ? '100%' : (($box.width() - 1) + 'px')
});
$('.' + t.o.prefix + 'fixed-top', $box).css({
position: fixedFullWidth ? 'fixed' : 'absolute',
top: fixedFullWidth ? oh : oh + (scrollTop - offset) + 'px',
zIndex: 15
});
} else if (t.isFixed) {
t.isFixed = false;
bp.removeAttr('style');
$([t.$ta, t.$ed]).css({marginTop: 0});
$('.' + t.o.prefix + 'fixed-top', $box).css({
position: 'absolute',
top: oh
});
}
});
},
// Disable editor
setDisabled: function (disable) {
var t = this,
prefix = t.o.prefix;
t.disabled = disable;
if (disable) {
t.$ta.attr('disabled', true);
} else {
t.$ta.removeAttr('disabled');
}
t.$box.toggleClass(prefix + 'disabled', disable);
t.$ed.attr('contenteditable', !disable);
},
// Destroy the editor
destroy: function () {
var t = this,
prefix = t.o.prefix;
if (t.isTextarea) {
t.$box.after(
t.$ta
.css({height: ''})
.val(t.html())
.removeClass(prefix + 'textarea')
.show()
);
} else {
t.$box.after(
t.$ed
.css({height: ''})
.removeClass(prefix + 'editor')
.removeAttr('contenteditable')
.removeAttr('dir')
.html(t.html())
.show()
);
}
t.$ed.off('dblclick', 'img');
t.destroyPlugins();
t.$box.remove();
t.$c.removeData('trumbowyg');
$('body').removeClass(prefix + 'body-fullscreen');
t.$c.trigger('tbwclose');
$(window).off('scroll.' + t.eventNamespace + ' resize.' + t.eventNamespace);
},
// Empty the editor
empty: function () {
this.$ta.val('');
this.syncCode(true);
},
// Function call when click on viewHTML button
toggle: function () {
var t = this,
prefix = t.o.prefix;
if (t.o.autogrowOnEnter) {
t.autogrowOnEnterDontClose = !t.$box.hasClass(prefix + 'editor-hidden');
}
t.semanticCode(false, true);
setTimeout(function () {
t.doc.activeElement.blur();
t.$box.toggleClass(prefix + 'editor-hidden ' + prefix + 'editor-visible');
t.$btnPane.toggleClass(prefix + 'disable');
$('.' + prefix + 'viewHTML-button', t.$btnPane).toggleClass(prefix + 'active');
if (t.$box.hasClass(prefix + 'editor-visible')) {
t.$ta.attr('tabindex', -1);
} else {
t.$ta.removeAttr('tabindex');
}
if (t.o.autogrowOnEnter && !t.autogrowOnEnterDontClose) {
t.autogrowEditorOnEnter();
}
}, 0);
},
// Open dropdown when click on a button which open that
dropdown: function (name) {
var t = this,
d = t.doc,
prefix = t.o.prefix,
$dropdown = $('[data-' + prefix + 'dropdown=' + name + ']', t.$box),
$btn = $('.' + prefix + name + '-button', t.$btnPane),
show = $dropdown.is(':hidden');
$('body', d).trigger('mousedown');
if (show) {
var o = $btn.offset().left;
$btn.addClass(prefix + 'active');
$dropdown.css({
position: 'absolute',
top: $btn.offset().top - t.$btnPane.offset().top + $btn.outerHeight(),
left: (t.o.fixedFullWidth && t.isFixed) ? o + 'px' : (o - t.$btnPane.offset().left) + 'px'
}).show();
$(window).trigger('scroll');
$('body', d).on('mousedown.' + t.eventNamespace, function (e) {
if (!$dropdown.is(e.target)) {
$('.' + prefix + 'dropdown', t.$box).hide();
$('.' + prefix + 'active', t.$btnPane).removeClass(prefix + 'active');
$('body', d).off('mousedown.' + t.eventNamespace);
}
});
}
},
// HTML Code management
html: function (html) {
var t = this;
if (html != null) {
t.$ta.val(html);
t.syncCode(true);
t.$c.trigger('tbwchange');
return t;
}
return t.$ta.val();
},
syncTextarea: function () {
var t = this;
t.$ta.val(t.$ed.text().trim().length > 0 || t.$ed.find(t.o.tagsToKeep.join(',')).length > 0 ? t.$ed.html() : '');
},
syncCode: function (force) {
var t = this;
if (!force && t.$ed.is(':visible')) {
t.syncTextarea();
} else {
// wrap the content in a div it's easier to get the innerhtml
var html = $('
').html(t.$ta.val());
//scrub the html before loading into the doc
var safe = $('
').append(html);
$(t.o.tagsToRemove.join(','), safe).remove();
t.$ed.html(safe.contents().html());
}
if (t.o.autogrow) {
t.height = t.$ed.height();
if (t.height !== t.$ta.css('height')) {
t.$ta.css({height: t.height});
t.$c.trigger('tbwresize');
}
}
if (t.o.autogrowOnEnter) {
// t.autogrowEditorOnEnter();
t.$ed.height('auto');
var totalheight = t.autogrowOnEnterWasFocused ? t.$ed[0].scrollHeight : t.$ed.css('min-height');
if (totalheight !== t.$ta.css('height')) {
t.$ed.css({height: totalheight});
t.$c.trigger('tbwresize');
}
}
},
// Analyse and update to semantic code
// @param force : force to sync code from textarea
// @param full : wrap text nodes in
// @param keepRange : leave selection range as it is
semanticCode: function (force, full, keepRange) {
var t = this;
t.saveRange();
t.syncCode(force);
if (t.o.semantic) {
t.semanticTag('b');
t.semanticTag('i');
t.semanticTag('s');
t.semanticTag('strike');
if (full) {
var inlineElementsSelector = t.o.inlineElementsSelector,
blockElementsSelector = ':not(' + inlineElementsSelector + ')';
// Wrap text nodes in span for easier processing
t.$ed.contents().filter(function () {
return this.nodeType === 3 && this.nodeValue.trim().length > 0;
}).wrap('');
// Wrap groups of inline elements in paragraphs (recursive)
var wrapInlinesInParagraphsFrom = function ($from) {
if ($from.length !== 0) {
var $finalParagraph = $from.nextUntil(blockElementsSelector).addBack().wrapAll('
').parent(),
$nextElement = $finalParagraph.nextAll(inlineElementsSelector).first();
$finalParagraph.next('br').remove();
wrapInlinesInParagraphsFrom($nextElement);
}
};
wrapInlinesInParagraphsFrom(t.$ed.children(inlineElementsSelector).first());
t.semanticTag('div', true);
// Unwrap paragraphs content, containing nothing usefull
t.$ed.find('p').filter(function () {
// Don't remove currently being edited element
if (t.range && this === t.range.startContainer) {
return false;
}
return $(this).text().trim().length === 0 && $(this).children().not('br,span').length === 0;
}).contents().unwrap();
// Get rid of temporary span's
$('[data-tbw]', t.$ed).contents().unwrap();
// Remove empty
t.$ed.find('p:empty').remove();
}
if (!keepRange) {
t.restoreRange();
}
t.syncTextarea();
}
},
semanticTag: function (oldTag, copyAttributes) {
var newTag;
if (this.o.semantic != null && typeof this.o.semantic === 'object' && this.o.semantic.hasOwnProperty(oldTag)) {
newTag = this.o.semantic[oldTag];
} else if (this.o.semantic === true && this.DEFAULT_SEMANTIC_MAP.hasOwnProperty(oldTag)) {
newTag = this.DEFAULT_SEMANTIC_MAP[oldTag];
} else {
return;
}
$(oldTag, this.$ed).each(function () {
var $oldTag = $(this);
if($oldTag.contents().length === 0) {
return false;
}
$oldTag.wrap('<' + newTag + '/>');
if (copyAttributes) {
$.each($oldTag.prop('attributes'), function () {
$oldTag.parent().attr(this.name, this.value);
});
}
$oldTag.contents().unwrap();
});
},
// Function call when user click on "Insert Link"
createLink: function () {
var t = this,
documentSelection = t.doc.getSelection(),
node = documentSelection.focusNode,
text = new XMLSerializer().serializeToString(documentSelection.getRangeAt(0).cloneContents()),
url,
title,
target;
while (['A', 'DIV'].indexOf(node.nodeName) < 0) {
node = node.parentNode;
}
if (node && node.nodeName === 'A') {
var $a = $(node);
text = $a.text();
url = $a.attr('href');
if (!t.o.minimalLinks) {
title = $a.attr('title');
target = $a.attr('target');
}
var range = t.doc.createRange();
range.selectNode(node);
documentSelection.removeAllRanges();
documentSelection.addRange(range);
}
t.saveRange();
var options = {
url: {
label: 'URL',
required: true,
value: url
},
text: {
label: t.lang.text,
value: text
}
};
if (!t.o.minimalLinks) {
Object.assign(options, {
title: {
label: t.lang.title,
value: title
},
target: {
label: t.lang.target,
value: target
}
});
}
t.openModalInsert(t.lang.createLink, options, function (v) { // v is value
var url = t.prependUrlPrefix(v.url);
if (!url.length) {
return false;
}
var link = $(['', v.text || v.url, ''].join(''));
if (!t.o.minimalLinks) {
if (v.title.length > 0) {
link.attr('title', v.title);
}
if (v.target.length > 0) {
link.attr('target', v.target);
}
}
t.range.deleteContents();
t.range.insertNode(link[0]);
t.syncCode();
t.$c.trigger('tbwchange');
return true;
});
},
prependUrlPrefix: function (url) {
var t = this;
if (!t.urlPrefix) {
return url;
}
var VALID_LINK_PREFIX = /^([a-z][-+.a-z0-9]*:|\/|#)/i;
if (VALID_LINK_PREFIX.test(url)) {
return url;
}
var SIMPLE_EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (SIMPLE_EMAIL_REGEX.test(url)) {
return 'mailto:' + url;
}
return t.urlPrefix + url;
},
unlink: function () {
var t = this,
documentSelection = t.doc.getSelection(),
node = documentSelection.focusNode;
if (documentSelection.isCollapsed) {
while (['A', 'DIV'].indexOf(node.nodeName) < 0) {
node = node.parentNode;
}
if (node && node.nodeName === 'A') {
var range = t.doc.createRange();
range.selectNode(node);
documentSelection.removeAllRanges();
documentSelection.addRange(range);
}
}
t.execCmd('unlink', undefined, undefined, true);
},
insertImage: function () {
var t = this;
t.saveRange();
var options = {
url: {
label: 'URL',
required: true
},
alt: {
label: t.lang.description,
value: t.getRangeText()
}
};
if (t.o.imageWidthModalEdit) {
options.width = {};
}
t.openModalInsert(t.lang.insertImage, options, function (v) { // v are values
t.execCmd('insertImage', v.url, false, true);
var $img = $('img[src="' + v.url + '"]:not([alt])', t.$box);
$img.attr('alt', v.alt);
if (t.o.imageWidthModalEdit) {
$img.attr({
width: v.width
});
}
t.syncCode();
t.$c.trigger('tbwchange');
return true;
});
},
fullscreen: function () {
var t = this,
prefix = t.o.prefix,
fullscreenCssClass = prefix + 'fullscreen',
isFullscreen;
t.$box.toggleClass(fullscreenCssClass);
isFullscreen = t.$box.hasClass(fullscreenCssClass);
$('body').toggleClass(prefix + 'body-fullscreen', isFullscreen);
$(window).trigger('scroll');
t.$c.trigger('tbw' + (isFullscreen ? 'open' : 'close') + 'fullscreen');
},
/*
* Call method of trumbowyg if exist
* else try to call anonymous function
* and finaly native execCommand
*/
execCmd: function (cmd, param, forceCss, skipTrumbowyg) {
var t = this;
skipTrumbowyg = !!skipTrumbowyg || '';
if (cmd !== 'dropdown') {
t.$ed.focus();
}
try {
t.doc.execCommand('styleWithCSS', false, forceCss || false);
} catch (c) {
}
try {
t[cmd + skipTrumbowyg](param);
} catch (c) {
try {
cmd(param);
} catch (e2) {
if (cmd === 'insertHorizontalRule') {
param = undefined;
} else if (cmd === 'formatBlock' && t.isIE) {
param = '<' + param + '>';
}
t.doc.execCommand(cmd, false, param);
t.syncCode();
t.semanticCode(false, true);
}
if (cmd !== 'dropdown') {
t.updateButtonPaneStatus();
t.$c.trigger('tbwchange');
}
}
},
// Open a modal box
openModal: function (title, content) {
var t = this,
prefix = t.o.prefix;
// No open a modal box when exist other modal box
if ($('.' + prefix + 'modal-box', t.$box).length > 0) {
return false;
}
if (t.o.autogrowOnEnter) {
t.autogrowOnEnterDontClose = true;
}
t.saveRange();
t.showOverlay();
// Disable all btnPane btns
t.$btnPane.addClass(prefix + 'disable');
// Build out of ModalBox, it's the mask for animations
var $modal = $('
', {
class: prefix + 'modal ' + prefix + 'fixed-top'
}).css({
top: t.$box.offset().top + t.$btnPane.height(),
zIndex: 99999
}).appendTo($(t.doc.body));
// Click on overlay close modal by cancelling them
t.$overlay.one('click', function () {
$modal.trigger(CANCEL_EVENT);
return false;
});
// Build the form
var $form = $('', {
action: '',
html: content
})
.on('submit', function () {
$modal.trigger(CONFIRM_EVENT);
return false;
})
.on('reset', function () {
$modal.trigger(CANCEL_EVENT);
return false;
})
.on('submit reset', function () {
if (t.o.autogrowOnEnter) {
t.autogrowOnEnterDontClose = false;
}
});
// Build ModalBox and animate to show them
var $box = $('', {
class: prefix + 'modal-box',
html: $form
})
.css({
top: '-' + t.$btnPane.outerHeight() + 'px',
opacity: 0
})
.appendTo($modal)
.animate({
top: 0,
opacity: 1
}, 100);
// Append title
$('', {
text: title,
class: prefix + 'modal-title'
}).prependTo($box);
$modal.height($box.outerHeight() + 10);
// Focus in modal box
$('input:first', $box).focus();
// Append Confirm and Cancel buttons
t.buildModalBtn('submit', $box);
t.buildModalBtn('reset', $box);
$(window).trigger('scroll');
return $modal;
},
// @param n is name of modal
buildModalBtn: function (n, $modal) {
var t = this,
prefix = t.o.prefix;
return $('', {
class: prefix + 'modal-button ' + prefix + 'modal-' + n,
type: n,
text: t.lang[n] || n
}).appendTo($('form', $modal));
},
// close current modal box
closeModal: function () {
var t = this,
prefix = t.o.prefix;
t.$btnPane.removeClass(prefix + 'disable');
t.$overlay.off();
// Find the modal box
var $modalBox = $('.' + prefix + 'modal-box', $(t.doc.body));
$modalBox.animate({
top: '-' + $modalBox.height()
}, 100, function () {
$modalBox.parent().remove();
t.hideOverlay();
});
t.restoreRange();
},
// Preformated build and management modal
openModalInsert: function (title, fields, cmd) {
var t = this,
prefix = t.o.prefix,
lg = t.lang,
html = '';
$.each(fields, function (fieldName, field) {
var l = field.label || fieldName,
n = field.name || fieldName,
a = field.attributes || {};
var attr = Object.keys(a).map(function (prop) {
return prop + '="' + a[prop] + '"';
}).join(' ');
html += '';
});
return t.openModal(title, html)
.on(CONFIRM_EVENT, function () {
var $form = $('form', $(this)),
valid = true,
values = {};
$.each(fields, function (fieldName, field) {
var n = field.name || fieldName;
var $field = $('input[name="' + n + '"]', $form),
inputType = $field.attr('type');
switch (inputType.toLowerCase()) {
case 'checkbox':
values[n] = $field.is(':checked');
break;
case 'radio':
values[n] = $field.filter(':checked').val();
break;
default:
values[n] = $.trim($field.val());
break;
}
// Validate value
if (field.required && values[n] === '') {
valid = false;
t.addErrorOnModalField($field, t.lang.required);
} else if (field.pattern && !field.pattern.test(values[n])) {
valid = false;
t.addErrorOnModalField($field, field.patternError);
}
});
if (valid) {
t.restoreRange();
if (cmd(values, fields)) {
t.syncCode();
t.$c.trigger('tbwchange');
t.closeModal();
$(this).off(CONFIRM_EVENT);
}
}
})
.one(CANCEL_EVENT, function () {
$(this).off(CONFIRM_EVENT);
t.closeModal();
});
},
addErrorOnModalField: function ($field, err) {
var prefix = this.o.prefix,
$label = $field.parent();
$field
.on('change keyup', function () {
$label.removeClass(prefix + 'input-error');
});
$label
.addClass(prefix + 'input-error')
.find('input+span')
.append(
$('', {
class: prefix + 'msg-error',
text: err
})
);
},
getDefaultImgDblClickHandler: function () {
var t = this;
return function () {
var $img = $(this),
src = $img.attr('src'),
base64 = '(Base64)';
if (src.indexOf('data:image') === 0) {
src = base64;
}
var options = {
url: {
label: 'URL',
value: src,
required: true
},
alt: {
label: t.lang.description,
value: $img.attr('alt')
}
};
if (t.o.imageWidthModalEdit) {
options.width = {
value: $img.attr('width') ? $img.attr('width') : ''
};
}
t.openModalInsert(t.lang.insertImage, options, function (v) {
if (v.url !== base64) {
$img.attr({
src: v.url
});
}
$img.attr({
alt: v.alt
});
if (t.o.imageWidthModalEdit) {
if (parseInt(v.width) > 0) {
$img.attr({
width: v.width
});
} else {
$img.removeAttr('width');
}
}
return true;
});
return false;
};
},
// Range management
saveRange: function () {
var t = this,
documentSelection = t.doc.getSelection();
t.range = null;
if (!documentSelection || !documentSelection.rangeCount) {
return;
}
var savedRange = t.range = documentSelection.getRangeAt(0),
range = t.doc.createRange(),
rangeStart;
range.selectNodeContents(t.$ed[0]);
range.setEnd(savedRange.startContainer, savedRange.startOffset);
rangeStart = (range + '').length;
t.metaRange = {
start: rangeStart,
end: rangeStart + (savedRange + '').length
};
},
restoreRange: function () {
var t = this,
metaRange = t.metaRange,
savedRange = t.range,
documentSelection = t.doc.getSelection(),
range;
if (!savedRange) {
return;
}
if (metaRange && metaRange.start !== metaRange.end) { // Algorithm from http://jsfiddle.net/WeWy7/3/
var charIndex = 0,
nodeStack = [t.$ed[0]],
node,
foundStart = false,
stop = false;
range = t.doc.createRange();
while (!stop && (node = nodeStack.pop())) {
if (node.nodeType === 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && metaRange.start >= charIndex && metaRange.start <= nextCharIndex) {
range.setStart(node, metaRange.start - charIndex);
foundStart = true;
}
if (foundStart && metaRange.end >= charIndex && metaRange.end <= nextCharIndex) {
range.setEnd(node, metaRange.end - charIndex);
stop = true;
}
charIndex = nextCharIndex;
} else {
var cn = node.childNodes,
i = cn.length;
while (i > 0) {
i -= 1;
nodeStack.push(cn[i]);
}
}
}
}
documentSelection.removeAllRanges();
documentSelection.addRange(range || savedRange);
},
getRangeText: function () {
return this.range + '';
},
updateButtonPaneStatus: function () {
var t = this,
prefix = t.o.prefix,
tags = t.getTagsRecursive(t.doc.getSelection().focusNode),
activeClasses = prefix + 'active-button ' + prefix + 'active';
$('.' + prefix + 'active-button', t.$btnPane).removeClass(activeClasses);
$.each(tags, function (i, tag) {
var btnName = t.tagToButton[tag.toLowerCase()],
$btn = $('.' + prefix + btnName + '-button', t.$btnPane);
if ($btn.length > 0) {
$btn.addClass(activeClasses);
} else {
try {
$btn = $('.' + prefix + 'dropdown .' + prefix + btnName + '-dropdown-button', t.$box);
var dropdownBtnName = $btn.parent().data('dropdown');
$('.' + prefix + dropdownBtnName + '-button', t.$box).addClass(activeClasses);
} catch (e) {
}
}
});
},
getTagsRecursive: function (element, tags) {
var t = this;
tags = tags || (element && element.tagName ? [element.tagName] : []);
if (element && element.parentNode) {
element = element.parentNode;
} else {
return tags;
}
var tag = element.tagName;
if (tag === 'DIV') {
return tags;
}
if (tag === 'P' && element.style.textAlign !== '') {
tags.push(element.style.textAlign);
}
$.each(t.tagHandlers, function (i, tagHandler) {
tags = tags.concat(tagHandler(element, t));
});
tags.push(tag);
return t.getTagsRecursive(element, tags).filter(function (tag) {
return tag != null;
});
},
// Plugins
initPlugins: function () {
var t = this;
t.loadedPlugins = [];
$.each($.trumbowyg.plugins, function (name, plugin) {
if (!plugin.shouldInit || plugin.shouldInit(t)) {
plugin.init(t);
if (plugin.tagHandler) {
t.tagHandlers.push(plugin.tagHandler);
}
t.loadedPlugins.push(plugin);
}
});
},
destroyPlugins: function () {
$.each(this.loadedPlugins, function (i, plugin) {
if (plugin.destroy) {
plugin.destroy();
}
});
}
};
})(navigator, window, document, jQuery);
(function ($) {
'use strict';
$.extend(true, $.trumbowyg, {
langs: {
// jshint camelcase:false
en: {
fontFamily: 'Font'
},
da: {
fontFamily: 'Skrifttype'
},
fr: {
fontFamily: 'Police'
},
de: {
fontFamily: 'Schriftart'
},
nl: {
fontFamily: 'Lettertype'
},
tr: {
fontFamily: 'Yazı Tipi'
},
zh_tw: {
fontFamily: '字體',
},
pt_br: {
fontFamily: 'Fonte',
}
}
});
// jshint camelcase:true
var defaultOptions = {
fontList: [
{name: 'Arial', family: 'Arial, Helvetica, sans-serif'},
{name: 'Arial Black', family: '\'Arial Black\', Gadget, sans-serif'},
{name: 'Comic Sans', family: '\'Comic Sans MS\', Textile, cursive, sans-serif'},
{name: 'Courier New', family: '\'Courier New\', Courier, monospace'},
{name: 'Georgia', family: 'Georgia, serif'},
{name: 'Impact', family: 'Impact, Charcoal, sans-serif'},
{name: 'Lucida Console', family: '\'Lucida Console\', Monaco, monospace'},
{name: 'Lucida Sans', family: '\'Lucida Sans Uncide\', \'Lucida Grande\', sans-serif'},
{name: 'Palatino', family: '\'Palatino Linotype\', \'Book Antiqua\', Palatino, serif'},
{name: 'Tahoma', family: 'Tahoma, Geneva, sans-serif'},
{name: 'Times New Roman', family: '\'Times New Roman\', Times, serif'},
{name: 'Trebuchet', family: '\'Trebuchet MS\', Helvetica, sans-serif'},
{name: 'Verdana', family: 'Verdana, Geneva, sans-serif'}
]
};
// Add dropdown with web safe fonts
$.extend(true, $.trumbowyg, {
plugins: {
fontfamily: {
init: function (trumbowyg) {
trumbowyg.o.plugins.fontfamily = trumbowyg.o.plugins.fontfamily || defaultOptions;
trumbowyg.addBtnDef('fontfamily', {
dropdown: buildDropdown(trumbowyg),
hasIcon: false,
text: trumbowyg.lang.fontFamily
});
}
}
}
});
function buildDropdown(trumbowyg) {
var dropdown = [];
$.each(trumbowyg.o.plugins.fontfamily.fontList, function (index, font) {
trumbowyg.addBtnDef('fontfamily_' + index, {
title: '' + font.name + '',
hasIcon: false,
fn: function () {
trumbowyg.execCmd('fontName', font.family, true);
}
});
dropdown.push('fontfamily_' + index);
});
return dropdown;
}
})(jQuery);
(function ($) {
'use strict';
// jshint camelcase:true
function hex(x) {
return ('0' + parseInt(x).toString(16)).slice(-2);
}
function colorToHex(rgb) {
if (rgb.search('rgb') === -1) {
return rgb.replace('#', '');
} else if (rgb === 'rgba(0, 0, 0, 0)') {
return 'transparent';
} else {
rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
}
function colorTagHandler(element, trumbowyg) {
var tags = [];
if (!element.style) {
return tags;
}
// background color
if (element.style.backgroundColor !== '') {
var backColor = colorToHex(element.style.backgroundColor);
if (trumbowyg.o.plugins.colors.colorList.indexOf(backColor) >= 0) {
tags.push('backColor' + backColor);
} else {
tags.push('backColorFree');
}
}
// text color
var foreColor;
if (element.style.color !== '') {
foreColor = colorToHex(element.style.color);
} else if (element.hasAttribute('color')) {
foreColor = colorToHex(element.getAttribute('color'));
}
if (foreColor) {
if (trumbowyg.o.plugins.colors.colorList.indexOf(foreColor) >= 0) {
tags.push('foreColor' + foreColor);
} else {
tags.push('foreColorFree');
}
}
return tags;
}
var defaultOptions = {
colorList: ['ffffff', '000000', 'eeece1', '1f497d', '4f81bd', 'c0504d', '9bbb59', '8064a2', '4bacc6', 'f79646', 'ffff00', 'f2f2f2', '7f7f7f', 'ddd9c3', 'c6d9f0', 'dbe5f1', 'f2dcdb', 'ebf1dd', 'e5e0ec', 'dbeef3', 'fdeada', 'fff2ca', 'd8d8d8', '595959', 'c4bd97', '8db3e2', 'b8cce4', 'e5b9b7', 'd7e3bc', 'ccc1d9', 'b7dde8', 'fbd5b5', 'ffe694', 'bfbfbf', '3f3f3f', '938953', '548dd4', '95b3d7', 'd99694', 'c3d69b', 'b2a2c7', 'b7dde8', 'fac08f', 'f2c314', 'a5a5a5', '262626', '494429', '17365d', '366092', '953734', '76923c', '5f497a', '92cddc', 'e36c09', 'c09100', '7f7f7f', '0c0c0c', '1d1b10', '0f243e', '244061', '632423', '4f6128', '3f3151', '31859b', '974806', '7f6000']
};
// Default Options for font-size
var fontSizedefaultOptions = {
sizeList: ['x-small', 'small', 'medium', 'large', 'x-large'],
allowCustomSize: true
};
// Default Options for line height
var lineHeightOptions = {
sizeList: ['0.9', '1', '1.5', '2.0', '2.5','3.0', '3.5', '4.0', '4.5', '5.0'],
allowCustomSize: true
};
// If WP media is a button
function openwpmediaDef(trumbowyg) {
return {
fn: function() {
// WP media button logic
var func_media = window['pagelayer_select_frame'];
if(typeof func_media == 'function'){
// Load the frame
var frame = pagelayer_select_frame('image');
// On select update the stuff
frame.on({'select': function(){
var state = frame.state();
var url = '', alt = '', id = '';
// External URL
if('props' in state){
url = state.props.attributes.url;
alt = state.props.attributes.alt;
// Internal from gallery
}else{
var attachment = frame.state().get('selection').first().toJSON();
//console.log(attachment);
// Set the new and URL
url = attachment.url;
alt = attachment.alt;
id = attachment.id;
}
trumbowyg.execCmd('insertImage', url, false, true);
var $img = $('img[src="' + url + '"]:not([alt])', trumbowyg.$box);
$img.attr('alt', alt);
$img.attr('pl-media-id', id);
trumbowyg.syncCode;
trumbowyg.$c.trigger('tbwchange');
return true;
}
});
frame.open();
}
},
ico: 'insert-image'
}
}
$.extend(true, $.trumbowyg, {
// Add some translations
langs: {
en: {
wpmedia: 'Insert Image',
foreColor: 'Text color',
backColor: 'Background color',
fontsize: 'Font size',
fontsizes: {
'x-small': 'Extra small',
'small': 'Small',
'medium': 'Regular',
'large': 'Large',
'x-large': 'Extra large',
'custom': 'Custom'
},
fontCustomSize: {
title: 'Custom Font Size',
label: 'Font Size',
value: '48px'
},
lineheight: 'Line Height',
lineCustomHeight: {
title: 'Custom Line Height',
label: 'Line Height',
value: '7.0'
},
lineheights: {
'normal': 'Normal',
'custom': 'Custom',
}
},
},
// Add our plugin to Trumbowyg registred plugins
plugins: {
wpmedia: {
init: function(trumbowyg) {
var t = $(this);
// Fill current Trumbowyg instance with WP media default options
trumbowyg.o.plugins.wpmedia = $.extend(true, {},
defaultOptions,
trumbowyg.o.plugins.wpmedia || {}
);
// If WP media is a
trumbowyg.addBtnDef('wpmedia', openwpmediaDef(trumbowyg));
},
},
color: {
init: function (trumbowyg) {
trumbowyg.o.plugins.colors = trumbowyg.o.plugins.colors || defaultOptions;
var foreColorBtnDef = {
dropdown: buildDropdown('foreColor', trumbowyg)
},
backColorBtnDef = {
dropdown: buildDropdown('backColor', trumbowyg)
};
trumbowyg.addBtnDef('foreColor', foreColorBtnDef);
trumbowyg.addBtnDef('backColor', backColorBtnDef);
},
tagHandler: colorTagHandler
},
pasteImage: {
init: function (trumbowyg) {
trumbowyg.pasteHandlers.push(function (pasteEvent) {
var pagelayer_ajax_func = {};
// This function for ajax success call back
pagelayer_ajax_func['success'] = function(obj){
//alert(obj);
if(obj['success']){
trumbowyg.execCmd('insertImage', obj['data']['url'], false, true);
}else{
alert(obj['data']['message']);
}
}
// This function for ajax before send call back
pagelayer_ajax_func['beforeSend'] = function(xhr){
trumbowyg.showOverlay();
}
// This function for ajax complete call back
pagelayer_ajax_func['complete'] = function(xhr){
trumbowyg.hideOverlay();
}
pagelayer_editable_paste_handler(pasteEvent, pagelayer_ajax_func);
});
}
},
fontsize: {
init: function (trumbowyg) {
trumbowyg.o.plugins.fontsize = $.extend({},
fontSizedefaultOptions,
trumbowyg.o.plugins.fontsize || {}
);
trumbowyg.addBtnDef('fontsize', {
dropdown: fontSizeBuildDropdown(trumbowyg)
});
}
},
lineheight: {
init: function (trumbowyg) {
trumbowyg.o.plugins.lineheight = $.extend({},
lineHeightOptions,
trumbowyg.o.plugins.lineheight || {}
);
trumbowyg.addBtnDef('lineheight', {
dropdown: lineHeightDropdown(trumbowyg)
});
}
}
}
});
function buildDropdown(fn, trumbowyg) {
var dropdown = [];
$.each(trumbowyg.o.plugins.colors.colorList, function (i, color) {
var btn = fn + color,
btnDef = {
fn: fn,
forceCss: true,
param: '#' + color,
style: 'background-color: #' + color + ';'
};
trumbowyg.addBtnDef(btn, btnDef);
dropdown.push(btn);
});
var removeColorButtonName = fn + 'Remove',
removeColorBtnDef = {
fn: 'removeFormat',
param: fn,
style: 'background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAG0lEQVQIW2NkQAAfEJMRmwBYhoGBYQtMBYoAADziAp0jtJTgAAAAAElFTkSuQmCC);'
};
trumbowyg.addBtnDef(removeColorButtonName, removeColorBtnDef);
dropdown.push(removeColorButtonName);
// add free color btn
var freeColorButtonName = fn + 'Free',
freeColorBtnDef = {
fn: function () {
trumbowyg.openModalInsert(trumbowyg.lang[fn],
{
color: {
label: fn,
forceCss: true,
type: 'color',
value: '#FFFFFF'
}
},
// callback
function (values) {
trumbowyg.execCmd(fn, values.color);
return true;
}
);
},
text: '#',
// style adjust for displaying the text
style: 'text-indent: 0;line-height: 20px;padding: 0 5px;'
};
trumbowyg.addBtnDef(freeColorButtonName, freeColorBtnDef);
dropdown.push(freeColorButtonName);
return dropdown;
}
// Functions for font-size widget
function setFontSize(trumbowyg, size) {
trumbowyg.$ed.focus();
trumbowyg.saveRange();
var text = trumbowyg.range.startContainer.parentElement;
var selectedText = trumbowyg.getRangeText();
if ($(text).html() === selectedText) {
$(text).css('font-size', size);
} else {
trumbowyg.range.deleteContents();
var html = '' + selectedText + '';
var node = $(html)[0];
trumbowyg.range.insertNode(node);
}
}
function fontSizeBuildDropdown(trumbowyg) {
var dropdown = [];
$.each(trumbowyg.o.plugins.fontsize.sizeList, function (index, size) {
trumbowyg.addBtnDef('fontsize_' + size, {
text: '' + (trumbowyg.lang.fontsizes[size] || size) + '',
hasIcon: false,
fn: function () {
setFontSize(trumbowyg, size);
trumbowyg.syncCode();
trumbowyg.$c.trigger('tbwchange');
}
});
dropdown.push('fontsize_' + size);
});
if (trumbowyg.o.plugins.fontsize.allowCustomSize) {
var customSizeButtonName = 'fontsize_custom';
var customSizeBtnDef = {
fn: function () {
trumbowyg.openModalInsert(trumbowyg.lang.fontCustomSize.title,
{
size: {
label: trumbowyg.lang.fontCustomSize.label,
value: trumbowyg.lang.fontCustomSize.value
}
},
function (form) {
setFontSize(trumbowyg, form.size);
return true;
}
);
},
text: '' + trumbowyg.lang.fontsizes.custom + '',
hasIcon: false
};
trumbowyg.addBtnDef(customSizeButtonName, customSizeBtnDef);
dropdown.push(customSizeButtonName);
}
return dropdown;
}
// Build the dropdown for line-height
function lineHeightDropdown(trumbowyg) {
var dropdown = [];
$.each(trumbowyg.o.plugins.lineheight.sizeList, function(index, size) {
trumbowyg.addBtnDef('lineheight_' + size, {
text: trumbowyg.lang.lineheights[size] || size,
hasIcon: false,
fn: function(){
setLineHight(trumbowyg, size);
}
});
dropdown.push('lineheight_' + size);
});
if (trumbowyg.o.plugins.lineheight.allowCustomSize) {
var customSizeButtonName = 'lineheight_custom';
var customSizeBtnDef = {
fn: function () {
trumbowyg.openModalInsert(trumbowyg.lang.lineCustomHeight.title,
{
size: {
label: trumbowyg.lang.lineCustomHeight.label,
value: trumbowyg.lang.lineCustomHeight.value
}
},
function (form) {
setLineHight(trumbowyg, form.size);
return true;
}
);
},
text: '' + trumbowyg.lang.lineheights.custom + '',
hasIcon: false
};
trumbowyg.addBtnDef(customSizeButtonName, customSizeBtnDef);
dropdown.push(customSizeButtonName);
}
return dropdown;
}
// Set line-height
function setLineHight(trumbowyg, size) {
trumbowyg.$ed.focus();
trumbowyg.saveRange();
var parent = trumbowyg.range.startContainer.parentElement;
var text = trumbowyg.getRangeText();
if ($(parent).html() === text) {
$(parent).css('line-height', size);
} else {
trumbowyg.range.deleteContents();
var html = '' + text + '';
var node = $(html)[0];
trumbowyg.range.insertNode(node);
}
trumbowyg.syncCode();
trumbowyg.$c.trigger('tbwchange');
}
})(jQuery);
/*! Licensed under MIT, https://github.com/sofish/pen */
(function(root, doc) {
var Pen, debugMode, selection, utils = {};
var toString = Object.prototype.toString;
var slice = Array.prototype.slice;
// allow command list
var commandsReg = {
block: /^(?:p|h[1-6]|blockquote|pre)$/,
inline: /^(?:bold|italic|underline|insertorderedlist|insertunorderedlist|indent|outdent)$/,
source: /^(?:createlink|unlink)$/,
insert: /^(?:inserthorizontalrule|insertimage|insert)$/,
wrap: /^(?:code)$/
};
var lineBreakReg = /^(?:blockquote|pre|div)$/i;
var effectNodeReg = /(?:[pubia]|h[1-6]|blockquote|[uo]l|li)/i;
var strReg = {
whiteSpace: /(^\s+)|(\s+$)/g,
mailTo: /^(?!mailto:|.+\/|.+#|.+\?)(.*@.*\..+)$/,
http: /^(?!\w+?:\/\/|mailto:|\/|\.\/|\?|#)(.*)$/
};
var autoLinkReg = {
url: /((https?|ftp):\/\/|www\.)[^\s<]{3,}/gi,
prefix: /^(?:https?|ftp):\/\//i,
notLink: /^(?:img|a|input|audio|video|source|code|pre|script|head|title|style)$/i,
maxLength: 100
};
// type detect
utils.is = function(obj, type) {
return toString.call(obj).slice(8, -1) === type;
};
utils.forEach = function(obj, iterator, arrayLike) {
if (!obj) return;
if (arrayLike == null) arrayLike = utils.is(obj, 'Array');
if (arrayLike) {
for (var i = 0, l = obj.length; i < l; i++) iterator(obj[i], i, obj);
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) iterator(obj[key], key, obj);
}
}
};
// copy props from a obj
utils.copy = function(defaults, source) {
utils.forEach(source, function (value, key) {
defaults[key] = utils.is(value, 'Object') ? utils.copy({}, value) :
utils.is(value, 'Array') ? utils.copy([], value) : value;
});
return defaults;
};
// log
utils.log = function(message, force) {
if (debugMode || force)
console.log('%cPEN DEBUGGER: %c' + message, 'font-family:arial,sans-serif;color:#1abf89;line-height:2em;', 'font-family:cursor,monospace;color:#333;');
};
utils.delayExec = function (fn) {
var timer = null;
return function (delay) {
clearTimeout(timer);
timer = setTimeout(function() {
fn();
}, delay || 1);
};
};
// merge: make it easy to have a fallback
utils.merge = function(config) {
// default settings
var defaults = {
class: 'pen',
debug: false,
toolbar: null, // custom toolbar
stay: config.stay || !config.debug,
stayMsg: 'Are you going to leave here?',
textarea: '',
list: [
'blockquote', 'h2', 'h3', 'p', 'code', 'insertorderedlist', 'insertunorderedlist', 'inserthorizontalrule',
'indent', 'outdent', 'bold', 'italic', 'underline', 'createlink', 'insertimage'
],
titles: {},
cleanAttrs: ['id', 'class', 'style', 'name'],
cleanTags: ['script'],
linksInNewWindow: false
};
// user-friendly config
if (config.nodeType === 1) {
defaults.editor = config;
} else if (config.match && config.match(/^#[\S]+$/)) {
defaults.editor = doc.getElementById(config.slice(1));
} else {
defaults = utils.copy(defaults, config);
}
return defaults;
};
function commandOverall(ctx, cmd, val) {
var message = ' to exec 「' + cmd + '」 command' + (val ? (' with value: ' + val) : '');
try {
doc.execCommand(cmd, false, val);
} catch(err) {
// TODO: there's an error when insert a image to document, but not a bug
return utils.log('fail' + message, true);
}
utils.log('success' + message);
}
function commandInsert(ctx, name, val) {
var node = getNode(ctx);
if (!node) return;
ctx._range.selectNode(node);
ctx._range.collapse(false);
// hide menu when a image was inserted
if(name === 'insertimage' && ctx._menu) toggleNode(ctx._menu, true);
return commandOverall(ctx, name, val);
}
function commandBlock(ctx, name) {
var list = effectNode(ctx, getNode(ctx), true);
if (list.indexOf(name) !== -1) name = 'p';
return commandOverall(ctx, 'formatblock', name);
}
function commandWrap(ctx, tag, value) {
value = '<' + tag + '>' + (value||selection.toString()) + '' + tag + '>';
return commandOverall(ctx, 'insertHTML', value);
}
function commandLink(ctx, tag, value) {
if (ctx.config.linksInNewWindow) {
value = '< a href="' + value + '" target="_blank">' + (selection.toString()) + '';
return commandOverall(ctx, 'insertHTML', value);
} else {
return commandOverall(ctx, tag, value);
}
}
function initToolbar(ctx) {
var icons = '', inputStr = '';
ctx._toolbar = ctx.config.toolbar;
if (!ctx._toolbar) {
var toolList = ctx.config.list;
utils.forEach(toolList, function (name) {
var klass = 'pen-icon icon-' + name;
var title = ctx.config.titles[name] || '';
icons += '';
}, true);
if (toolList.indexOf('createlink') >= 0 || toolList.indexOf('insertimage') >= 0)
icons += inputStr;
} else if (ctx._toolbar.querySelectorAll('[data-action=createlink]').length ||
ctx._toolbar.querySelectorAll('[data-action=insertimage]').length) {
icons += inputStr;
}
if (icons) {
ctx._menu = doc.createElement('div');
ctx._menu.setAttribute('class', ctx.config.class + '-menu pen-menu');
ctx._menu.innerHTML = icons;
ctx._inputBar = ctx._menu.querySelector('input');
toggleNode(ctx._menu, true);
doc.body.appendChild(ctx._menu);
}
if (ctx._toolbar && ctx._inputBar) toggleNode(ctx._inputBar);
}
function initEvents(ctx) {
var toolbar = ctx._toolbar || ctx._menu, editor = ctx.config.editor;
var toggleMenu = utils.delayExec(function() {
ctx.highlight().menu();
});
var outsideClick = function() {};
function updateStatus(delay) {
ctx._range = ctx.getRange();
toggleMenu(delay);
}
if (ctx._menu) {
var setpos = function() {
if (ctx._menu.style.display === 'block') ctx.menu();
};
// change menu offset when window resize / scroll
addListener(ctx, root, 'resize', setpos);
addListener(ctx, root, 'scroll', setpos);
// toggle toolbar on mouse select
var selecting = false;
addListener(ctx, editor, 'mousedown', function() {
selecting = true;
});
addListener(ctx, editor, 'mouseleave', function() {
if (selecting) updateStatus(800);
selecting = false;
});
addListener(ctx, editor, 'mouseup', function() {
if (selecting) updateStatus(100);
selecting = false;
});
// Hide menu when focusing outside of editor
outsideClick = function(e) {
if (ctx._menu && !containsNode(editor, e.target) && !containsNode(ctx._menu, e.target)) {
removeListener(ctx, doc, 'click', outsideClick);
toggleMenu(100);
}
};
} else {
addListener(ctx, editor, 'click', function() {
updateStatus(0);
});
}
addListener(ctx, editor, 'keyup', function(e) {
if (e.which === 8 && ctx.isEmpty()) return lineBreak(ctx, true);
// toggle toolbar on key select
if (e.which !== 13 || e.shiftKey) return updateStatus(400);
var node = getNode(ctx, true);
if (!node || !node.nextSibling || !lineBreakReg.test(node.nodeName)) return;
if (node.nodeName !== node.nextSibling.nodeName) return;
// hack for webkit, make 'enter' behavior like as firefox.
if (node.lastChild.nodeName !== 'BR') node.appendChild(doc.createElement('br'));
utils.forEach(node.nextSibling.childNodes, function(child) {
if (child) node.appendChild(child);
}, true);
node.parentNode.removeChild(node.nextSibling);
focusNode(ctx, node.lastChild, ctx.getRange());
});
// check line break
addListener(ctx, editor, 'keydown', function(e) {
editor.classList.remove('pen-placeholder');
if (e.which !== 13 || e.shiftKey) return;
var node = getNode(ctx, true);
if (!node || !lineBreakReg.test(node.nodeName)) return;
var lastChild = node.lastChild;
if (!lastChild || !lastChild.previousSibling) return;
if (lastChild.previousSibling.textContent || lastChild.textContent) return;
// quit block mode for 2 'enter'
e.preventDefault();
var p = doc.createElement('p');
p.innerHTML = ' ';
node.removeChild(lastChild);
if (!node.nextSibling) node.parentNode.appendChild(p);
else node.parentNode.insertBefore(p, node.nextSibling);
focusNode(ctx, p, ctx.getRange());
});
var menuApply = function(action, value) {
ctx.execCommand(action, value);
ctx._range = ctx.getRange();
ctx.highlight().menu();
};
// toggle toolbar on key select
addListener(ctx, toolbar, 'click', function(e) {
var node = e.target, action;
while (node !== toolbar && !(action = node.getAttribute('data-action'))) {
node = node.parentNode;
}
if (!action) return;
if (!/(?:createlink)|(?:insertimage)/.test(action)) return menuApply(action);
if (!ctx._inputBar) return;
// create link
var input = ctx._inputBar;
if (toolbar === ctx._menu) toggleNode(input);
else {
ctx._inputActive = true;
ctx.menu();
}
if (ctx._menu.style.display === 'none') return;
setTimeout(function() { input.focus(); }, 400);
var createlink = function() {
var inputValue = input.value;
if (!inputValue) action = 'unlink';
else {
inputValue = input.value
.replace(strReg.whiteSpace, '')
.replace(strReg.mailTo, 'mailto:$1')
.replace(strReg.http, 'http://$1');
}
menuApply(action, inputValue);
if (toolbar === ctx._menu) toggleNode(input, false);
else toggleNode(ctx._menu, true);
};
input.onkeypress = function(e) {
if (e.which === 13) return createlink();
};
});
// listen for placeholder
addListener(ctx, editor, 'focus', function() {
if (ctx.isEmpty()) lineBreak(ctx, true);
addListener(ctx, doc, 'click', outsideClick);
});
addListener(ctx, editor, 'blur', function() {
checkPlaceholder(ctx);
ctx.checkContentChange();
});
// listen for paste and clear style
addListener(ctx, editor, 'paste', function() {
setTimeout(function() {
ctx.cleanContent();
});
});
}
function addListener(ctx, target, type, listener) {
if (ctx._events.hasOwnProperty(type)) {
ctx._events[type].push(listener);
} else {
ctx._eventTargets = ctx._eventTargets || [];
ctx._eventsCache = ctx._eventsCache || [];
var index = ctx._eventTargets.indexOf(target);
if (index < 0) index = ctx._eventTargets.push(target) - 1;
ctx._eventsCache[index] = ctx._eventsCache[index] || {};
ctx._eventsCache[index][type] = ctx._eventsCache[index][type] || [];
ctx._eventsCache[index][type].push(listener);
target.addEventListener(type, listener, false);
}
return ctx;
}
// trigger local events
function triggerListener(ctx, type) {
if (!ctx._events.hasOwnProperty(type)) return;
var args = slice.call(arguments, 2);
utils.forEach(ctx._events[type], function (listener) {
listener.apply(ctx, args);
});
}
function removeListener(ctx, target, type, listener) {
var events = ctx._events[type];
if (!events) {
var _index = ctx._eventTargets.indexOf(target);
if (_index >= 0) events = ctx._eventsCache[_index][type];
}
if (!events) return ctx;
var index = events.indexOf(listener);
if (index >= 0) events.splice(index, 1);
target.removeEventListener(type, listener, false);
return ctx;
}
function removeAllListeners(ctx) {
utils.forEach(this._events, function (events) {
events.length = 0;
}, false);
if (!ctx._eventsCache) return ctx;
utils.forEach(ctx._eventsCache, function (events, index) {
var target = ctx._eventTargets[index];
utils.forEach(events, function (listeners, type) {
utils.forEach(listeners, function (listener) {
target.removeEventListener(type, listener, false);
}, true);
}, false);
}, true);
ctx._eventTargets = [];
ctx._eventsCache = [];
return ctx;
}
function checkPlaceholder(ctx) {
ctx.config.editor.classList[ctx.isEmpty() ? 'add' : 'remove']('pen-placeholder');
}
function trim(str) {
return (str || '').replace(/^\s+|\s+$/g, '');
}
// node.contains is not implemented in IE10/IE11
function containsNode(parent, child) {
if (parent === child) return true;
child = child.parentNode;
while (child) {
if (child === parent) return true;
child = child.parentNode;
}
return false;
}
function getNode(ctx, byRoot) {
var node, root = ctx.config.editor;
ctx._range = ctx._range || ctx.getRange();
node = ctx._range.commonAncestorContainer;
if (!node || node === root) return null;
while (node && (node.nodeType !== 1) && (node.parentNode !== root)) node = node.parentNode;
while (node && byRoot && (node.parentNode !== root)) node = node.parentNode;
return containsNode(root, node) ? node : null;
}
// node effects
function effectNode(ctx, el, returnAsNodeName) {
var nodes = [];
el = el || ctx.config.editor;
while (el && el !== ctx.config.editor) {
if (el.nodeName.match(effectNodeReg)) {
nodes.push(returnAsNodeName ? el.nodeName.toLowerCase() : el);
}
el = el.parentNode;
}
return nodes;
}
// breakout from node
function lineBreak(ctx, empty) {
var range = ctx._range = ctx.getRange(), node = doc.createElement('p');
if (empty) ctx.config.editor.innerHTML = '';
node.innerHTML = ' ';
range.insertNode(node);
focusNode(ctx, node.childNodes[0], range);
}
function focusNode(ctx, node, range) {
range.setStartAfter(node);
range.setEndBefore(node);
range.collapse(false);
ctx.setRange(range);
}
function autoLink(node) {
if (node.nodeType === 1) {
if (autoLinkReg.notLink.test(node.tagName)) return;
utils.forEach(node.childNodes, function (child) {
autoLink(child);
}, true);
} else if (node.nodeType === 3) {
var result = urlToLink(node.nodeValue || '');
if (!result.links) return;
var frag = doc.createDocumentFragment(),
div = doc.createElement('div');
div.innerHTML = result.text;
while (div.childNodes.length) frag.appendChild(div.childNodes[0]);
node.parentNode.replaceChild(frag, node);
}
}
function urlToLink(str) {
var count = 0;
str = str.replace(autoLinkReg.url, function(url) {
var realUrl = url, displayUrl = url;
count++;
if (url.length > autoLinkReg.maxLength) displayUrl = url.slice(0, autoLinkReg.maxLength) + '...';
// Add http prefix if necessary
if (!autoLinkReg.prefix.test(realUrl)) realUrl = 'http://' + realUrl;
return '' + displayUrl + '';
});
return {links: count, text: str};
}
function toggleNode(node, hide) {
node.style.display = hide ? 'none' : 'block';
}
Pen = function(config) {
if (!config) throw new Error('Can\'t find config');
debugMode = config.debug;
// merge user config
var defaults = utils.merge(config);
var editor = defaults.editor;
if (!editor || editor.nodeType !== 1) throw new Error('Can\'t find editor');
// set default class
editor.classList.add(defaults.class);
// set contenteditable
editor.setAttribute('contenteditable', 'true');
// assign config
this.config = defaults;
// set placeholder
if (defaults.placeholder) editor.setAttribute('data-placeholder', defaults.placeholder);
checkPlaceholder(this);
// save the selection obj
this.selection = selection;
// define local events
this._events = {change: []};
// enable toolbar
initToolbar(this);
// init events
initEvents(this);
// to check content change
this._prevContent = this.getContent();
// enable markdown covert
if (this.markdown) this.markdown.init(this);
// stay on the page
if (this.config.stay) this.stay(this.config);
if(this.config.input) {
this.addOnSubmitListener(this.config.input);
}
};
Pen.prototype.on = function(type, listener) {
addListener(this, this.config.editor, type, listener);
return this;
};
Pen.prototype.addOnSubmitListener = function(inputElement) {
var form = inputElement.form;
var me = this;
form.addEventListener("submit", function() {
inputElement.value = me.config.saveAsMarkdown ? me.toMd(me.config.editor.innerHTML) : me.config.editor.innerHTML;
});
};
Pen.prototype.isEmpty = function(node) {
node = node || this.config.editor;
return !(node.querySelector('img')) && !(node.querySelector('blockquote')) &&
!(node.querySelector('li')) && !trim(node.textContent);
};
Pen.prototype.getContent = function() {
return this.isEmpty() ? '' : trim(this.config.editor.innerHTML);
};
Pen.prototype.setContent = function(html) {
this.config.editor.innerHTML = html;
this.cleanContent();
return this;
};
Pen.prototype.checkContentChange = function () {
var prevContent = this._prevContent, currentContent = this.getContent();
if (prevContent === currentContent) return;
this._prevContent = currentContent;
triggerListener(this, 'change', currentContent, prevContent);
};
Pen.prototype.getRange = function() {
var editor = this.config.editor, range = selection.rangeCount && selection.getRangeAt(0);
if (!range) range = doc.createRange();
if (!containsNode(editor, range.commonAncestorContainer)) {
range.selectNodeContents(editor);
range.collapse(false);
}
return range;
};
Pen.prototype.setRange = function(range) {
range = range || this._range;
if (!range) {
range = this.getRange();
range.collapse(false); // set to end
}
try {
selection.removeAllRanges();
selection.addRange(range);
} catch (e) {/* IE throws error sometimes*/}
return this;
};
Pen.prototype.focus = function(focusStart) {
if (!focusStart) this.setRange();
this.config.editor.focus();
return this;
};
Pen.prototype.execCommand = function(name, value) {
name = name.toLowerCase();
this.setRange();
if (commandsReg.block.test(name)) {
commandBlock(this, name);
} else if (commandsReg.inline.test(name)) {
commandOverall(this, name, value);
} else if (commandsReg.source.test(name)) {
commandLink(this, name, value);
} else if (commandsReg.insert.test(name)) {
commandInsert(this, name, value);
} else if (commandsReg.wrap.test(name)) {
commandWrap(this, name, value);
} else {
utils.log('can not find command function for name: ' + name + (value ? (', value: ' + value) : ''), true);
}
if (name === 'indent') this.checkContentChange();
else this.cleanContent({cleanAttrs: ['style']});
};
// remove attrs and tags
// pen.cleanContent({cleanAttrs: ['style'], cleanTags: ['id']})
Pen.prototype.cleanContent = function(options) {
var editor = this.config.editor;
if (!options) options = this.config;
utils.forEach(options.cleanAttrs, function (attr) {
utils.forEach(editor.querySelectorAll('[' + attr + ']'), function(item) {
item.removeAttribute(attr);
}, true);
}, true);
utils.forEach(options.cleanTags, function (tag) {
utils.forEach(editor.querySelectorAll(tag), function(item) {
item.parentNode.removeChild(item);
}, true);
}, true);
checkPlaceholder(this);
this.checkContentChange();
return this;
};
// auto link content, return content
Pen.prototype.autoLink = function() {
autoLink(this.config.editor);
return this.getContent();
};
// highlight menu
Pen.prototype.highlight = function() {
var toolbar = this._toolbar || this._menu
, node = getNode(this);
// remove all highlights
utils.forEach(toolbar.querySelectorAll('.active'), function(el) {
el.classList.remove('active');
}, true);
if (!node) return this;
var effects = effectNode(this, node)
, inputBar = this._inputBar
, highlight;
if (inputBar && toolbar === this._menu) {
// display link input if createlink enabled
inputBar.style.display = 'none';
// reset link input value
inputBar.value = '';
}
highlight = function(str) {
if (!str) return;
var el = toolbar.querySelector('[data-action=' + str + ']');
return el && el.classList.add('active');
};
utils.forEach(effects, function(item) {
var tag = item.nodeName.toLowerCase();
switch(tag) {
case 'a':
if (inputBar) inputBar.value = item.getAttribute('href');
tag = 'createlink';
break;
case 'img':
if (inputBar) inputBar.value = item.getAttribute('src');
tag = 'insertimage';
break;
case 'i':
tag = 'italic';
break;
case 'u':
tag = 'underline';
break;
case 'b':
tag = 'bold';
break;
case 'pre':
case 'code':
tag = 'code';
break;
case 'ul':
tag = 'insertunorderedlist';
break;
case 'ol':
tag = 'insertorderedlist';
break;
case 'li':
tag = 'indent';
break;
}
highlight(tag);
}, true);
return this;
};
// show menu
Pen.prototype.menu = function() {
var allMenus = document.getElementsByClassName('pen-menu');
// Hide all menus
for(var x in allMenus){
try{
if('style' in allMenus[x]){
allMenus[x].style.display = 'none';
}
}catch(e){}
}
if (!this._menu) return this;
if (selection.isCollapsed) {
this._menu.style.display = 'none'; //hide menu
this._inputActive = false;
return this;
}
if (this._toolbar) {
if (!this._inputBar || !this._inputActive) return this;
}
var offset = this._range.getBoundingClientRect()
, menuPadding = 10
, top = offset.top - menuPadding
, left = offset.left + (offset.width / 2)
, menu = this._menu
, menuOffset = {x: 0, y: 0}
, stylesheet = this._stylesheet;
// fixes some browser double click visual discontinuity
// if the offset has no width or height it should not be used
if (offset.width === 0 && offset.height === 0) return this;
// store the stylesheet used for positioning the menu horizontally
if (this._stylesheet === undefined) {
var style = document.createElement("style");
document.head.appendChild(style);
this._stylesheet = stylesheet = style.sheet;
}
// display block to caculate its width & height
menu.style.display = 'block';
menuOffset.x = left - (menu.clientWidth / 2);
menuOffset.y = top - menu.clientHeight;
// check to see if menu has over-extended its bounding box. if it has,
// 1) apply a new class if overflowed on top;
// 2) apply a new rule if overflowed on the left
if (stylesheet.cssRules.length > 0) {
stylesheet.deleteRule(0);
}
if (menuOffset.x < 0) {
menuOffset.x = 0;
stylesheet.insertRule('.pen-menu:after {left: ' + left + 'px;}', 0);
} else {
stylesheet.insertRule('.pen-menu:after {left: 50%; }', 0);
}
if (menuOffset.y < 0) {
menu.classList.add('pen-menu-below');
menuOffset.y = offset.top + offset.height + menuPadding;
} else {
menu.classList.remove('pen-menu-below');
}
menu.style.top = menuOffset.y + 'px';
menu.style.left = menuOffset.x + 'px';
return this;
};
Pen.prototype.stay = function(config) {
var ctx = this;
if (!window.onbeforeunload) {
window.onbeforeunload = function() {
if (!ctx._isDestroyed) return config.stayMsg;
};
}
};
Pen.prototype.destroy = function(isAJoke) {
var destroy = isAJoke ? false : true
, attr = isAJoke ? 'setAttribute' : 'removeAttribute';
if (!isAJoke) {
removeAllListeners(this);
try {
selection.removeAllRanges();
if (this._menu) this._menu.parentNode.removeChild(this._menu);
} catch (e) {/* IE throws error sometimes*/}
} else {
initToolbar(this);
initEvents(this);
}
this._isDestroyed = destroy;
this.config.editor[attr]('contenteditable', '');
return this;
};
Pen.prototype.rebuild = function() {
return this.destroy('it\'s a joke');
};
// a fallback for old browers
root.Pen = function(config) {
if (!config) return utils.log('can\'t find config', true);
var defaults = utils.merge(config)
, klass = defaults.editor.getAttribute('class');
klass = klass ? klass.replace(/\bpen\b/g, '') + ' pen-textarea ' + defaults.class : 'pen pen-textarea';
defaults.editor.setAttribute('class', klass);
defaults.editor.innerHTML = defaults.textarea;
return defaults.editor;
};
// export content as markdown
var regs = {
a: [/]*href=["']([^"]+|[^']+)\b[^>]*>(.*?)<\/a>/ig, '[$2]($1)'],
img: [/]*src=["']([^\"+|[^']+)[^>]*>/ig, ''],
b: [/]*>(.*?)<\/b>/ig, '**$1**'],
i: [/]*>(.*?)<\/i>/ig, '***$1***'],
h: [/]*>(.*?)<\/h\1>/ig, function(a, b, c) {
return '\n' + ('######'.slice(0, b)) + ' ' + c + '\n';
}],
li: [/<(li)\b[^>]*>(.*?)<\/\1>/ig, '* $2\n'],
blockquote: [/<(blockquote)\b[^>]*>(.*?)<\/\1>/ig, '\n> $2\n'],
pre: [/