import { useState, useEffect, useLayoutEffect } from '@wordpress/element';

const pagelayer_widgets_timer = {}
const pagelayer_svg_cache = {}

var pagelayer_gt_skeleton = '.interface-interface-skeleton__content';

// Render for row
export function pagelayer_render_pl_row(el){
	
	var img_urls = !pagelayer_empty(el.tmp['bg_slider-urls']) ? (typeof(el.tmp['bg_slider-urls']) == 'object' ? 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'] += '<div class="pagelayer-bgimg-slide" style="background-image:url('+img_urls[x]+')"></div>'; 
		}
	}
	
	// Row background parallax image.
	if(!pagelayer_empty(el.atts['parallax_img'])){
		el.atts['parallax_img_src'] = el.tmp['parallax_img-'+el.atts['parallax_id_size']+'-url'] || el.tmp['parallax_img-url'];
		el.atts['parallax_img_src'] = el.atts['parallax_img_src'] || el.atts['parallax_img'];
	}
	
	pagelayer_bg_video(el);
}

// Load the full width row
export 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.$, jQuery(pagelayer_gt_skeleton));
		
		// 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');
		
		// Remove HAD class
		el.$.removeClass('pagelayer-row-stretch-had-full');
		
	}
	
	// TODO: remove pagelayer-setup attribute code from pagelayer_pl_row_video function if posible
	el.$.children('.pagelayer-background-video').removeAttr('pagelayer-setup');
	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')
	}
}

// Set Row parent width
function pagelayer_pl_row_parent_full(par){
	var vw = jQuery(pagelayer_gt_skeleton).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]);
	}

}

// Render for inner row
export function pagelayer_render_pl_inner_row(el){
	pagelayer_render_pl_row(el);
}

// Render for col
export function pagelayer_render_pl_col(el){
	
	var img_urls = !pagelayer_empty(el.tmp['bg_slider-urls']) ? (typeof(el.tmp['bg_slider-urls']) == 'object' ? 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'] += '<div class="pagelayer-bgimg-slide" style="background-image:url('+img_urls[x]+')"></div>'; 
		}
	}
	
	// Col background parallax image.
	if(!pagelayer_empty(el.atts['parallax_img'])){
		el.atts['parallax_img_src'] = el.tmp['parallax_img-'+el.atts['parallax_id_size']+'-url'] || el.tmp['parallax_img-url'];
		el.atts['parallax_img_src'] = el.atts['parallax_img_src'] || el.atts['parallax_img'];
	}
	
	pagelayer_bg_video(el);
}

// Load the col
export function pagelayer_render_end_pl_col(el){
	
	// We need the parent of type pagelayer-wrap-col
	var par = el.$.parent();
	
	if(!par.hasClass('pagelayer-col')){
		par.addClass('pagelayer-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', '');
	}
	
	// TODO: remove pagelayer-setup attribute code from pagelayer_pl_row_video function if posible
	el.$.children('.pagelayer-background-video').removeAttr('pagelayer-setup');
	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));
	});
	
}
	
export function pagelayer_bg_video(el){
	
	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'];
	
	if(pagelayer_empty(src)){
		return;
	}
	
	var iframe_atts = pagelayer_video_url(src, true);
	// console.log(iframe_atts);
  
	iframe_atts['src'] += (iframe_atts['src'].indexOf('?') == -1 ? '?' : '');
  
	// Adding mute and loop option in row or col	
	if(el.atts['mute'] == "true"){
		iframe_atts['src'] +="&mute=1";
		el.atts['mute'] = " muted ";
	}else{
		iframe_atts['src'] +="&mute=0";
		el.atts['mute'] = "";
	}

	if(el.atts['stop_loop'] != "true"){
		iframe_atts['src'] +="&loop=1";	
		el.atts['stop_loop'] = " loop ";
	}else{
		iframe_atts['src'] +="&loop=0";	
		el.atts['stop_loop'] ="";
	}
  
	if (iframe_atts['type'] == 'youtube') {
		
		var settings = 'data-loop="'+(!pagelayer_empty(el['atts']['stop_loop']) ? 1 : 0)+'" data-mute="'+ (!pagelayer_empty(el['atts']['mute']) ? 1 : 0)+'" data-videoid="'+(iframe_atts['id'].split('&')[0])+'"';
		
		el.atts['vid_src'] =  '<div class = "pagelayer-youtube-video" '+ settings +'></div>';

	} else if (iframe_atts['type'] == 'vimeo') {
		
		el.atts['vid_src'] = '<iframe src="'+iframe_atts['src']+'&background=1&autoplay=1&byline=0&title=0" allowfullscreen="1" webkitallowfullscreen="1" mozallowfullscreen="1" frameborder="0"></iframe>';
		
	}else{
		
		el.atts['vid_src'] = '<video autoplay playsinline '+el.atts['mute']+el.atts['stop_loop']+'>'+
				'<source src="'+iframe_atts['src']+'" type="video/mp4">'+
			'</video>';
			
	}
	
}

export function pagelayer_render_end_pl_accordion(el){
	pagelayer_pl_accordion(el.$);
}

export function pagelayer_render_end_pl_collapse(el){
	pagelayer_pl_collapse(el.$);
}

export function pagelayer_render_pl_google_maps(el){
	
	el.atts['show_v2'] = true;
    
	if(pagelayer_empty(el.atts['api_version'])){		
		el.atts['src_code'] = '';
		return;
	}

	const { pagelayer_gmaps_key } = pagelayer_config;
	
	el.atts['show_v2'] = false;
	
	var gmaps_key = (pagelayer_empty(pagelayer_gmaps_key) ? '' : pagelayer_gmaps_key);
	
	var api_key = (pagelayer_empty(el.atts['api_key']) ? gmaps_key : el.atts['api_key']);
	
	if(el.atts['map_modes'] == 'view'){
		el.atts['center'] = pagelayer_empty(el.atts['center']) ? '-33.8569,151.2152' : el.atts['center'];
	}
		
	var src_code = (pagelayer_empty(el.atts['center']) ? '' : '&center='+el.atts['center'])+(el.atts['map_modes'] == 'streetview' ? '' : '&maptype='+el.atts['map_type']+'&zoom='+el.atts['zoom']);
	
	switch(el.atts['map_modes']){
		case 'place':
			src_code += encodeURI('&q='+(pagelayer_empty(el.atts['address']) ? 'New York, New York, USA' : el.atts['address'] ));
			break;
			
		case 'directions':
			src_code += encodeURI('&origin='+(pagelayer_empty(el.atts['direction_origin']) ? 'Oslow Norway' : el.atts['direction_origin'] ));
			src_code += encodeURI('&destination='+(pagelayer_empty(el.atts['direction_destination']) ? 'Telemark Norway' : el.atts['direction_destination'] ));
			src_code += (pagelayer_empty(el.atts['direction_waypoints']) ? '' : '&waypoints='+(el.atts['direction_waypoints'].trim()).split(' ').join('|') );
			src_code += (pagelayer_empty(el.atts['direction_modes']) ? '' : '&mode='+el.atts['direction_modes'] );
			src_code += (pagelayer_empty(el.atts['direction_avoid']) ? '' : '&avoid='+el.atts['direction_avoid'].split(',').join('|') );
			src_code += (pagelayer_empty(el.atts['direction_units']) ? '' : '&units='+el.atts['direction_units'] );
			break;
			
		case 'streetview':
			src_code += '&pano='+(pagelayer_empty(el.atts['streetview_pano']) ? 'eTnPNGoy4bxR9LpjjfFuOw' : el.atts['streetview_pano'] );
			src_code += '&location='+(pagelayer_empty(el.atts['streetview_location']) ? '46.414382,10.013988' : el.atts['streetview_location'] );
			src_code += (pagelayer_empty(el.atts['streetview_heading']) ? '' : '&heading='+el.atts['streetview_heading'] );
			src_code += (pagelayer_empty(el.atts['streetview_pitch']) ? '' : '&pitch='+el.atts['streetview_pitch'] );
			src_code += (pagelayer_empty(el.atts['streetview_fov']) ? '' : '&fov='+el.atts['streetview_fov'] );
			break;
			
		case 'search':
			src_code += encodeURI('&q='+(pagelayer_empty(el.atts['search_term']) ? 'Record stores in Seattle' : el.atts['search_term'] ));
			break;
	}

	var src_code_url = 'https://www.google.com/maps/embed/v1/'+el.atts['map_modes']+'?key='+api_key+src_code;
	el.atts['src_code'] = '<iframe width="600" height="450" style="border:0" loading="lazy" allowfullscreen src="'+src_code_url+'"></iframe>';
}

// Render the progress
export function pagelayer_render_pl_progress(el){
	const { attributes } = el.props;
	
	useEffect(() => {
		clearTimeout(pagelayer_widgets_timer[el.id]);
		pagelayer_widgets_timer[el.id] = setTimeout( () => {
			el.$.find('.pagelayer-progress-container').removeAttr('pagelayer-setup');
			pagelayer_progress();
		}, 500);
	}, [attributes]);
	
	// We need to call the is visible thing to show the widgets loading effect
	var win = pagelayerGetCurrentWindow();
	
	jQuery(win).unbind('scroll.progressbar', pagelayer_progress);
	jQuery(win).on('scroll.progressbar', pagelayer_progress);
};

// Render the stars
export function pagelayer_render_end_pl_stars(el){
	var jEle = el.$.find('.pagelayer-stars-container');
	
	jEle.removeAttr('pagelayer-setup');
	pagelayer_stars(jEle);
};

// Render the counter
export function pagelayer_render_end_pl_counter(el){
	el.$.find('.pagelayer-counter-content').removeAttr('pagelayer-setup');
	pagelayer_counter();
	
	// We need to call the is visible thing to show the widgets loading effect
	var win = pagelayerGetCurrentWindow();
	
	jQuery(win).unbind('scroll.plcounter', pagelayer_counter);
	jQuery(win).on('scroll.plcounter', pagelayer_counter);
};

// Render the animated heading
export function pagelayer_render_pl_anim_heading(el){
	
	el.atts['rotate_html'] = '';
	
	// Creates html for rotating text
	if(!pagelayer_empty(el.atts['rotate_text'])){
		
		var rotate_text = '';
		rotate_text = el.atts['rotate_text'].split(',');
		
		el.atts['rotate_html'] += '<div class="pagelayer-animated-heading pagelayer-rotating-text pagelayer-words-wrapper">';
		
		jQuery.each(rotate_text, function(i){
			el.atts['rotate_html'] += '<span';
			if(i == 0){
				el.atts['rotate_html'] += ' class="pagelayer-is-visible"';
			}
			el.atts['rotate_html'] += '>' + rotate_text[i] + '</span>';
		});
		
		el.atts['rotate_html'] += '</div>';
	   
	}
	
	// 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
export function pagelayer_render_end_pl_anim_heading(el){
	pagelayer_anim_heading(el.$);	
}

// Retina image setting attribute.
export function pagelayer_get_img_src(el, image_atts){
	
	// Check if retina images is set
	if(!pagelayer_empty(el.tmp[image_atts.name+'-retina-url']) && el.tmp[image_atts.name+'-retina-url'].includes('default-image') == false){
		var retina_image = el.tmp[image_atts.name+'-retina-'+el.atts[image_atts.size]+'-url'];
		retina_image = pagelayer_empty(retina_image) ? el.tmp[image_atts.name+'-retina-url'] : retina_image;
		el.atts['pagelayer-srcset'] += retina_image +' 2x, ';			
	}
	
	// Check if retina mobile images is set
	if(!pagelayer_empty(el.tmp[image_atts.name+'-retina-mobile-url']) && el.tmp[image_atts.name+'-retina-mobile-url'].includes('default-image') == false){			
		var retina_image_mobile = el.tmp[image_atts.name+'-retina-mobile-'+el.atts[image_atts.size]+'-url'];
		retina_image_mobile = pagelayer_empty(retina_image_mobile) ? el.tmp[image_atts.name+'-retina-mobile-url'] : retina_image_mobile;		
		el.atts['pagelayer-srcset'] += retina_image_mobile +' 3x';
	}
}

// Render the image object
export 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'];
	el.atts['pagelayer-srcset'] = el.atts['func_id']+', '+el.atts['func_id']+' 1x, ';
	
	var image_atts = {
		name : 'id',
		size : 'id-size'
	};
	
	pagelayer_get_img_src(el, image_atts);
	
	// 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
export function pagelayer_render_end_pl_image(el){
	pagelayer_pl_image(el.$);
}

// Render the social profile
export function pagelayer_social(jEle, sel){
	var holder = jEle.find(sel);
	
	var icon = holder.attr('data-icon');
	if(pagelayer_empty(icon)){
		return;
	}

	var icon_splited = icon.split(' fa-');
	
	// TODO: from the shortcode
	//Reset privious class
	holder.attr('class', sel.substr(1));
	holder.addClass('pagelayer-'+icon_splited[1]);
	
}

// Render the social profile
export function pagelayer_render_end_pl_social(el){
	pagelayer_social(el.$, '.pagelayer-icon-holder');
}

// Render the social profile group
export 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.$);
}

export function pagelayer_render_pl_testimonial(el) {
	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'];
}

export function pagelayer_render_pl_countdown(el) {
	if (pagelayer_empty(el.atts['custom_label_text'])) {
		el.atts['days_label_text'] = 'Days';
		el.atts['hours_label_text'] = 'Hours';
		el.atts['minutes_label_text'] = 'Minutes';
		el.atts['seconds_label_text'] = 'Seconds';
	}
	
	const { attributes } = el.props;
	useEffect(() => {
		var jEle = pagelayer_query(el.CSS.cssSel);
		var exp = el['atts']['display_expired_text'];
		if (exp) {
			jEle.attr('display_expired_text', exp);
		} else {
			jEle.removeAttr('display_expired_text', exp);
		}

		jEle.find('.pagelayer-countdown-expired').hide();
		jEle.find('.pagelayer-countdown-counter').css('display', 'flex');

		pagelayer_countdown(jEle);

		if (pagelayer_empty(el['atts']['days']) && pagelayer_empty(el['atts']['hours']) && pagelayer_empty(el['atts']['minutes']) && pagelayer_empty(el['atts']['seconds'])) {
			jEle.find('.pagelayer-countdown-counter').html('<h2>Countdown Timer Holder</h2>');
		}
	}, [attributes])

}

// Render the share
export function pagelayer_render_pl_share(el){
	
	if('text' in el.atts && !pagelayer_empty(el.atts['text'])){
		el.atts['icon_label'] = el.atts['text'];
		return;
	}
		
	var icon = '';
	
	if(!pagelayer_empty(el.atts['icon'])){
		var icon_splited = el.atts['icon'].split(' fa-');
		icon = icon_splited[1];
	}
	
	var labelList = { 'Facebook' : ['facebook', 'facebook-official', 'facebook-f', 'facebook-messenger', 'facebook-square'],
		'Twitter' : ['twitter', 'twitter-square'],
		'X' : [ 'x-twitter', 'x-twitter-square'],
		'Google+' : ['google-plus', 'google-plus-square', 'google-plus-g'],
		'Instagram' : ['instagram'],
		'Linkedin' : ['linkedin', 'linkedin-square', 'linkedin-in'],
		'Pinterest' : ['pinterest', 'pinterest-p', 'pinterest-square'],
		'Reddit' : ['reddit-alien', 'reddit-square', 'reddit'],
		'Skype' : ['skype'],
		'Stumbleupon' : ['stumbleupon', 'stumbleupon-circle'],
		'Telegram' : ['telegram', 'telegram-plane'],
		'Tumblr' : ['tumblr', 'tumblr-square'],
		'VK' : ['vk'],
		'Weibo' : ['weibo'],
		'WhatsApp' : ['whatsapp', 'whatsapp-square'],
		'WordPress' : ['wordpress', 'wordpress-simple'],
		'Xing' : ['xing', 'xing-square'],
		'Delicious' : ['delicious'],
		'Dribbble' : ['dribbble', 'dribbble-square'],
		'Snapchat' : ['snapchat-ghost'],
		'Pocket' : ['get-pocket'],
		'Email' : ['envelope', 'envelope-open', 'envelope-o']
	}
	
	jQuery.each(labelList, function(key, value){
		if(jQuery.inArray(icon, value) != -1){
			el.atts['icon_label'] = key;
		}
	});
	
}

// Render the share icon
export function pagelayer_render_end_pl_share(el){
	pagelayer_social(el.$, '.pagelayer-share-content');
}

// Render the service box
export 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'];
	el.atts['pagelayer-srcset'] = el.atts['func_image']+', '+el.atts['func_image']+' 1x, ';
	
	var image_atts = {
		name : 'service_image',
		size : 'service_image_size'
	};
	
	pagelayer_get_img_src(el, image_atts);
	
}

// Render the contact form
export function pagelayer_render_pl_contact(el){
	const { attributes }= el.props;
	
	useEffect(() => {
		
		const Timer = setTimeout( () => {
			
			// To prevent unwanted calls
			if(pagelayer_empty(attributes['contact_custom_templ'])){
				return;
			}
			
			const contacts_data = pagelayer_get_contact_templates();
			
			// To prevent unwanted calls
			if(pagelayer_empty(contacts_data)){
				return;
			}
			
			// Dispatch an action to update post meta
			wp.data.dispatch('core/editor').editPost({meta: { 'pagelayer_contact_templates' : contacts_data } });
			
		}, 500);
		
		return ( () => {
			clearTimeout(Timer);
		});
		
	}, [attributes['pagelayer-id'], attributes['to_email'], attributes['from_email'], attributes['cont_subject'], attributes['cont_header'], attributes['cont_body'], attributes['cont_use_html']]);
	
	// Set post id in atts (if we add the contact form in header or footer)
	el.atts['con_post_id'] = pagelayer_postID;
	el.atts['grecaptcha'] = pagelayer_recaptch_site_key;	

		if(pagelayer_recaptch_version == 'v3') {
			el.atts['grecaptcha_v3'] = true; 
		}else{
			el.atts['grecaptcha_v2'] = true;
		}
}

// Create array of the contact from template params 
function pagelayer_get_contact_templates(){
	
	var contacts = jQuery('[data-type="pagelayer/pl-contact"]');
	var contacts_props = {};
	
	if(contacts.length > 0){
		const blockIds = [];
		
		contacts.each(function(){
			blockIds.push(jQuery(this).data('block'));
		});
			
		// Get the current editor state
		const { select } = wp.data;
		const editor = select('core/block-editor');

		const blocks = editor.getBlocksByClientId(blockIds); // Get all blocks in the editor
		
		blocks.map((block) => {
			
			const { attributes } = block;
			const id = attributes['pagelayer-id'];
			
			var con_allowed = ['to_email', 'from_email', 'cont_subject', 'cont_header', 'cont_body', 'cont_use_html'];
			
			if(pagelayer_empty(attributes['contact_custom_templ'])){
				return true;
			}
			
			// Define blank array
			contacts_props[id] = {};
			
			for(var x in con_allowed){
				var key = con_allowed[x];
				if(!pagelayer_empty(attributes[key])){
					contacts_props[id][key] = attributes[key];
				}
			}
		});
	
	}
	
	return contacts_props;
}

// Render the contact form
export function pagelayer_render_end_pl_contact(el){
	
	const { attributes, setAttributes } = el.props;
	
	jQuery(el.$).find('.pagelayer-recaptcha').each(function(){
		var recaptcha = jQuery(this);
		var widgetID = recaptcha.attr('recaptcha-widget-id');
		
		if( !pagelayer_empty(window.grecaptcha) && (!pagelayer_empty(widgetID) || widgetID == 0) ){
			grecaptcha.reset(widgetID);
		}else{
			pagelayer_recaptcha_loader(recaptcha, true);
		}
	});
	
	var msgBox = el.$.find('.pagelayer-message-box');
	// Showing contact form message in the editor only.
	if(el.atts['show_msg_box']){
		if(msgBox.length == 2){
			msgBox.eq(0).text('Demo success box');
			msgBox.eq(0).addClass('pagelayer-cf-msg-suc');
			msgBox.eq(1).text('Demo failed box');
			msgBox.eq(1).addClass('pagelayer-cf-msg-err');
		}
	}else{
		msgBox.removeClass('pagelayer-cf-msg-suc pagelayer-cf-msg-err');
		msgBox.text('');
	}
	
	if(! ( 'con_post_id' in attributes) || pagelayer_postID != attributes.con_post_id){
		setAttributes({con_post_id: pagelayer_postID });
	}
}

// Render the contact form
export function pagelayer_render_pl_contact_item(el){ 
	var html = '';
	var options = '';
	var placeholder = '';
	var required = '';
	
	if(!pagelayer_empty(el.atts['required'])){
		required = 'required';
	}

	if(!pagelayer_empty(el.atts['label_name']) && pagelayer_empty(el.atts['label_as_holder'])){
		html = '<label for="'+el.atts['field_name']+'">'+
				'<span class="pagelayer-form-label">'+el.atts['label_name']+'</span>';
				
		if(!pagelayer_empty(required)){
			html += ' *';
		}
		
		html += '</label>';
	}
		
	if(!pagelayer_empty(el.atts['label_as_holder'])){
		placeholder = el.atts['label_name'];
	}else{
		if(!pagelayer_empty(el.atts['placeholder'])) placeholder = el.atts['placeholder'];
	}
	
	// File accept
	var file_accept = '.jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.ppt,.pptx,.odt,.avi,.ogg,.m4a,.mov,.mp3,.mp4,.mpg,.wav,.wmv';
	
	if(!pagelayer_empty(el.atts['accept_file'])){
		file_accept = el.atts['accept_file'];
	}
	
	if(el.atts['field_type'] == 'select'){
	html += '<select name="'+el.atts['field_name']+'" '+required+'>'
		if(!pagelayer_empty(el.atts['label_name']) && !pagelayer_empty(el.atts['label_as_holder'])){
		   html += '<option value="" disabled selected>'+el.atts['label_name']+'</option>';
		}else{
			html += '<option value="" disabled selected>---</option>';
		}
		
		if(!pagelayer_empty(el.atts['values'])){
			options = el.atts['values'].split("\n");
			for(var x in options){
				html += '<option value="'+options[x].trim()+'">'+options[x].trim()+'</option>';
			}
		}
		html += '</select>';
	}else if(el.atts['field_type'] == 'checkbox'){
		if(!pagelayer_empty(el.atts['values'])){
			options = el.atts['values'].split("\n");
			html += '<div class="pagelayer-radcheck-holder pagelayer-contact-checkbox" '+required+'>';
			for(var x in options){
				html += '<div><input type="checkbox" id="'+el.id+options[x].trim()+'" name="'+el.atts['field_name']+'[]" '+
				'value="'+options[x].trim()+'" /><label for="'+el.id+options[x].trim()+'" class="pagelayer-form-label">'+options[x].trim()+'</label></div>';
			}
			html += '</div>';
		}
	}else if(el.atts['field_type'] == 'radio'){
		if(!pagelayer_empty(el.atts['values'])){
			options = el.atts['values'].split("\n");
			html += '<div class="pagelayer-radcheck-holder">';
			for(var x in options){
				html += '<div><input type="radio" name="'+el.atts['field_name']+'" '+
				'value="'+options[x].trim()+'" '+required+'/><span>'+options[x].trim()+'</span></div>';
			}
			html += '</div>';
		}
	}else if(el.atts['field_type'] == 'textarea'){
		html += '<textarea name="'+el.atts['field_name']+'" rows="'+el.atts['textarea_rows']+'" placeholder="'+placeholder+'" '+
				''+required+'></textarea>';
	}else if(el.atts['field_type'] == 'file'){
		html += '<input type="'+el.atts['field_type']+'" '+
				'name="'+el.atts['field_name']+'" placeholder="'+placeholder+'" accept="'+file_accept+'" '+required+' />';
	}else if(el.atts['field_type'] == 'label'){
		html += '';
	}else{
		html += '<input type="'+el.atts['field_type']+'" '+
				'name="'+el.atts['field_name']+'" placeholder="'+placeholder+'" '+required+'/>';
	}
	
	el.atts['fieldhtml'] = html;
}
// Render the archive Posts
export function pagelayer_render_pl_archive_posts(el){
	// Need to do empty
	el.atts['pagelayer_pagination_top'] = '';
	el.atts['pagelayer_pagination_bottom'] = '';
}

// Render the Post comment
export function pagelayer_render_end_pl_post_comment(el) {
	
	var postID = pagelayer_postID;

	if (el['atts']['post_type'] == 'custom' && el['atts']['post_id']) {
		postID = el['atts']['post_id'];
	}

	jQuery.ajax({
		url: pagelayer_ajax_url + '&action=pagelayer_post_comment&postID=' + postID,
		type: 'post',
		data: {
			pagelayer_nonce: pagelayer_ajax_nonce,
		},
		success: function (response) {
			// TODO: this with react
			el.$.find('.pagelayer-post-comment-container').html(response);
		}
	});

}

//render post  title
export function pagelayer_render_pl_post_title(el) {
	el['atts']['open_html_tag'] = !pagelayer_empty(el['atts']['html_tag']) ? '<' + el['atts']['html_tag'] + '>' : '';
	el['atts']['close_html_tag'] = !pagelayer_empty(el['atts']['html_tag']) ? '</' + el['atts']['html_tag'] + '>' : '';
}

// Render the post content
export function pagelayer_render_pl_post_content(el) {
	el.atts['post_content'] = 'Post Content Holder';
	el.CSS.css.push({ 'sel': '{{element}} .entry-content', 'val': 'min-height:20px;background-color:#e3e3e3;' });
}

// Render the excerpt
export function pagelayer_render_html_pl_post_excerpt(el) {
	el.$.find('.pagelayer-post-excerpt').addClass('pagelayer-empty-widget');
}

// Render the post excertp
export function pagelayer_render_pl_post_excerpt(el) {
	el.tmp['post_excerpt'] = '<div class="pagelayer-post-excerpt pagelayer-empty-widget"></div>';
}

// Render the featured image 
export function pagelayer_render_pl_featured_img(el) {
	
	var param = {};

	param['pagelayer_nonce'] = pagelayer_ajax_nonce;

	// Post Id
	param['post_id'] = pagelayer_postID;

	// Image size
	if ('size' in el.atts) {
		param['size'] = el.atts['size'];
	}

	jQuery.ajax({
		url: pagelayer_ajax_url + 'action=pagelayer_fetch_featured_img',
		type: 'post',
		data: param,
		dataType: 'json',
		success: function (data) {

			var src = '';
			var title = '';
			var alt = '';
			if (pagelayer_empty(data)) {
				src = el.tmp['img-' + el.atts['size'] + '-url'] || el.tmp['img-url'];
				src = src || el.atts['img'];
			} else {
				src = data['url'];
				alt = data['alt'];
				title = data['title'];
				if (el.atts['size'] + '-url' in data) {
					src = data[el.atts['size'] + '-url'];
				}
			}
			var blankImg = pagelayer_url + '/images/default-image.png';
			var img_html = '<img class="pagelayer-img" src="' + blankImg + '" />';
			if (src) {
				img_html = '<img class="pagelayer-img" src="' + src + '" title="' + title + '" alt="' + alt + '"/>';
			}

			el.$.find('.pagelayer-featured-img').html(img_html);

			if ('link_type' in el.atts) {

				// Custom url
				if (el.atts['link_type'] == 'custom_url') {
					el.$.find('a').attr('href', el.tmp['link']);
				}

				// Link to the media file itself
				if (el.atts['link_type'] == 'media_file' || el.atts['link_type'] == 'lightbox') {
					el.$.find('a').attr('href', src);
				}
			}

			pagelayer_pl_image(el.$);
		}
	});
}

// Render the site title
export function pagelayer_render_pl_wp_title(el) {
	// Use default logo
	if (pagelayer_empty(el.atts['logo_img_type'])) {

		// But is there a default logo
		if (!pagelayer_empty(pagelayer_site_logo)) {
			el.atts['func_image'] = pagelayer_site_logo[el.atts['logo_img_size'] + '-url'] || pagelayer_site_logo['url'];

			el.atts['logo_img-title'] = pagelayer_empty(pagelayer_site_logo.title) ? '' : pagelayer_site_logo.title;
			el.atts['logo_img-alt'] = pagelayer_empty(pagelayer_site_logo.alt) ? '' : pagelayer_site_logo.alt;
		}

		// Custom logo
	} else {
		el.atts['func_image'] = el.tmp['logo_img-' + el.atts['logo_img_size'] + '-url'] || el.tmp['logo_img-url'];
		el.atts['func_image'] = pagelayer_empty(el.atts['func_image']) ? el.atts['logo_img'] : el.atts['func_image'];
	}
}

// Render the flipbox
export function pagelayer_render_pl_flipbox(el) {
	clearTimeout(Timer)
	var Timer = setTimeout(() => {
		var jEle = el.$;
		const { attributes } = el.props;
		el.atts['func_image'] = el.tmp['heading_image-' + el.atts['heading_image_size'] + '-url'] || el.tmp['heading_image-url'];
		el.atts['func_image'] = el.atts['func_image'] || el.atts['heading_image'];

		var back = attributes?.back_section;

		if (back) {
			jEle.attr('back_section', back);
		}
		else {
			jEle.removeAttr('back_section', back);
		}
	}, 500)
}

// Render the post navigation
export function pagelayer_render_pl_post_nav(el) {
	
	const { attributes } = el.props;
	
	useEffect(() => {
		
		pagelayer_widgets_timer[el.id] = setTimeout( () => {
			jQuery.ajax({
				url: pagelayer_ajax_url + '&action=pagelayer_post_nav&postID=' + pagelayer_postID,
				type: 'post',
				data: {
					pagelayer_nonce: pagelayer_ajax_nonce,
					data: el['atts'],
				},
				async: false,
				success: function (response) {
					var obj = jQuery.parseJSON(response);
					var jEle = pagelayer_query(el.CSS.cssSel);
					jEle.find('.pagelayer-prev-post').html(obj['atts']['prev_link']);
					jEle.find('.pagelayer-next-post').html(obj['atts']['next_link']);
				}
			
			});
		}, 500);
		
		return (() => {
			clearTimeout(pagelayer_widgets_timer[el.id]);
		});
	}, [attributes]);

}

// Render the Post info list
var pagelayer_post_info_timer = {};
export function pagelayer_render_pl_post_info_list(el) {
	el.atts['post_info_content'] = 1;
	const { attributes } = el.props;
	useEffect(() => {
		clearTimeout(pagelayer_post_info_timer[el.id]);
		// Set a timer for constant change
		pagelayer_post_info_timer[el.id] = setTimeout(function () {
			// Make the call
			jQuery.ajax({
				url: pagelayer_ajax_url + '&action=pagelayer_post_info&postID=' + pagelayer_postID,
				type: 'post',
				data: {
					pagelayer_nonce: pagelayer_ajax_nonce,
					el: el.atts,
				},
				success: function (response) {
					var obj = jQuery.parseJSON(response);
					if (pagelayer_empty(obj['post_info_content'])) {
						el.$.find('.pagelayer-post-info-list-container').hide();
						return;
					}
					el.$.find('.pagelayer-post-info-list-container').show();
					el.$.find('.pagelayer-post-info-label').html(obj['post_info_content']);
					el.$.find('.pagelayer-post-info-icon img').attr('src', obj['avatar_url']);
					el.$.find('.pagelayer-post-info-list-container > a').attr('href', obj['link']);
				}
			});

		}, 500);
	}, [attributes])
}

// Render the fb embed
export function pagelayer_render_pl_fb_embed(el) {
	const { attributes } = el.props;
	useEffect(() => {
		pagelayer_fb_apps( pagelayer_query(el.CSS.cssSel));
	}, [attributes]);
};

// Render the fb page
export function pagelayer_render_pl_fb_page(el) {
	const { attributes } = el.props;
	useEffect(() => {
		pagelayer_fb_apps( pagelayer_query(el.CSS.cssSel) );
	}, [attributes]);
};

///////////////////////
////// PREMIUM  ///////
///////////////////////

// Render for audio
export function pagelayer_render_pl_audio(el){
	
	const { clientId } = el.props;
	
	el.tmp['src-url'] = el.tmp['src-url'] || el.atts['src'];
	
	useEffect(() => {
		var jEle = pagelayer_query('#block-'+clientId);
		
		if(jEle.length < 1){
			return;
		}
		
		jEle.find('.pagelayer-audio-container').html(`<audio controls>
			<source src="${el.tmp['src-url']}"></source>
		</audio>`);
	});
};

export function pagelayer_render_end_pl_audio(el){
	pagelayer_audio(el.$);
}

//Render before after slider
export function pagelayer_render_pl_before_after(el){
	el.tmp['before_image-url'] = el.tmp['before_image-url'] || el.atts['before_image'];
	el.tmp['after_image-url'] = el.tmp['after_image-url'] || el.atts['after_image'];
}

// Render before after
export function pagelayer_render_end_pl_before_after(el){
	pagelayer_before_after_slider(el.$);
}

// Grid gallery
export function pagelayer_render_pl_grid_gallery(el){
	
	// The URLs
	var img_urls = !pagelayer_empty(el.tmp['ids-urls']) ? (typeof(el.tmp['ids-urls']) == 'object' ? el.tmp['ids-urls'] : JSON.parse(el.tmp['ids-urls'])) : [];
	var all_urls = !pagelayer_empty(el.tmp['ids-all-urls']) ? (typeof(el.tmp['ids-all-urls']) == 'object' ? el.tmp['ids-all-urls'] : JSON.parse(el.tmp['ids-all-urls'])) : [];
	var img_title = !pagelayer_empty(el.tmp['ids-all-titles']) ? (typeof(el.tmp['ids-all-titles']) == 'object' ? el.tmp['ids-all-titles'] : JSON.parse(el.tmp['ids-all-titles'])) : [];
	var img_links = !pagelayer_empty(el.tmp['ids-all-links']) ?  (typeof(el.tmp['ids-all-links']) == 'object' ? el.tmp['ids-all-links'] : JSON.parse(el.tmp['ids-all-links'])) : [];
	var img_captions = !pagelayer_empty(el.tmp['ids-all-captions']) ? (typeof(el.tmp['ids-all-captions']) == 'object' ? el.tmp['ids-all-captions']: JSON.parse(el.tmp['ids-all-captions'])) : [];
	
	var ul = '';
	var pagin = '<li class="pagelayer-grid-page-item active">1</li>';
	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 = '<h4 style="text-align:center;">Please Select Images!</h4>';
		el.atts['ul'] = ul;
		el.atts['pagin'] = '';
		return;
	}
  
	ul += '<ul class="pagelayer-grid-gallery-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 += '</ul><ul class="pagelayer-grid-gallery-ul">';
			j++;
			pagin += '<li class="pagelayer-grid-page-item">'+j+'</li>';			
		}
		
		// 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 += '<li class="pagelayer-gallery-item" >';
		
		if(!is_link){
			ul += '<div>';
		}
		
		if(is_link && el.atts['link_to'] == 'media_file'){
			var link = (el.atts['link_to'] == 'media_file' ? url : (el.atts['link'] || ''));
			ul += '<a href="'+link+'" class="pagelayer-ele-link">';
		}
		
		if(is_link && el.atts['link_to'] == 'attachment'){
			var link = img_links[x];
			ul += '<a href="'+link+'" class="pagelayer-ele-link">';
		}
		
		if(is_link && el.atts['link_to'] == 'lightbox'){			
			ul += '<a href="'+img_urls[x]+'" class="pagelayer-ele-link" data-lightbox-gallery="'+gallery_rand+'" alt="'+img_title[x]+'" pagelayer-grid-gallery-type="'+el.atts['link_to']+'">';
		}
		
		ul += '<img class="pagelayer-img" src="'+url+'" title="'+img_title[x]+'" alt="'+img_title[x]+'">';
		
		if(el.atts['caption'] == 'true'){
			ul += '<span class="pagelayer-grid-gallery-caption">'+img_captions[x]+'</span>';
		}
		
		if(is_link){
			ul += '</a>';
		}
		
		if(!is_link){
			ul += '</div>';
		}
		
		ul += '</li>';
		i++;
	}
	ul += '</ul>';
	
	el.atts['pagin'] = (j > 1) ? '<div class="pagelayer-grid-gallery-pagination"><ul class="pagelayer-grid-page-ul">'+'<li class="pagelayer-grid-page-item">&laquo;</li>'+
						pagin+
						'<li class="pagelayer-grid-page-item">&raquo;</li>'+'</ul></div>' : '';
	
	el.tmp['gallery-random-id'] = gallery_rand;
	
	el.atts['ul'] = ul;

}

// Render the grid gallery
export function pagelayer_render_end_pl_grid_gallery(el){
	pagelayer_pl_grid_lightbox(el.$);
}

export function pagelayer_render_pl_author_box(el) {
	if (el.atts["box_source"] == "current") {
		el.tmp["avatar-url"] = pagelayer_author["avatar"];
		el.atts["display_name"] = pagelayer_author["display_name"];
		el.atts["description"] = pagelayer_author["description"];
		el.atts["user_url"] = pagelayer_author["user_url"];
	} else {
		el.tmp["avatar-url"] = el.tmp["avatar-url"] || el.atts["avatar"];
	}
	el.atts["display_html"] =
		"<" +
		el.atts["name_style"] +
		">" +
		el.atts["display_name"] +
		"</" +
		el.atts["name_style"] +
		">";
	el.atts['avatar_html'] = '<img class="pagelayer-img pagelayer-author-image" src="' + el.tmp['avatar-url'] + '" title="{{{avatar-title}}}" alt="{{{avatar-alt}}}">';

	// when we remove image the tmpAtts['src-url'] getting undefined there fore i use this check to remove the pagelayer_render_html_pl_featured_img.php html for image remove this if image property set the default image
	if (el.atts.tmpAtts['avatar-url'] === undefined) {
		jQuery('.pagelayer-author-profile-pic').css('display', 'none');
	}
}

// End Render for splash
export function pagelayer_render_end_pl_splash(el){

	var jEle = el.$;
	var container = jEle.find('.pagelayer-splash-container');	

	jEle.unbind('click');
	jEle.on('click','.pagelayer-splash-close, .pagelayer-splash-bg-close', function(e){
		e.stopPropagation();
		container.fadeOut();
	})

	jEle.on('click', function(e){
		container.fadeIn();
	})

	if(el.atts['style'] == 'custom'){
		container.css({'background': el.atts['shadow_color'], 'color': el.atts['content_color']});
	}else{
		container.css({'background': '', 'color': ''});
	}
	
	container.removeClass().addClass('pagelayer-splash-container pagelayer-splash-'+el.atts['style']);
}

// Render the search form
export function pagelayer_render_pl_search(el){
	if('placeholder' in el.atts){
		el.tmp['placeholder'] = pagelayer_htmlEntities(el.atts['placeholder']);
	}
}

// Render the search form
export function pagelayer_render_end_pl_search(el){
	
	// To keep typing in search input
	el.$.find('input').on('click input', function(e){
		e.stopPropagation();
	});
	
	pagelayer_search_form(el.$);
}

// Render the image hotspot
export function pagelayer_render_pl_image_hotspot(el){  	
	// Decide the image URL
	el.tmp['img-url'] = el.tmp['img-url'] || el.atts['img'];
}

// Setup of image hotspot
export function pagelayer_render_end_pl_image_hotspot(el){
	
	// Remove animation classes
	el.$.find('.pagelayer-hotspots-icon-holder').removeClass (function (index, className) {
		return (className.match (/(^|\s)pagelayer-animation-\S+/g) || []).join(' ');
	});
	
	pagelayer_image_hotspot(el.$);
};

// Render the img portfolio
export function pagelayer_render_end_pl_img_portfolio(el){
	pagelayer_pl_img_portfolio(el.$);
}

// Render the img portfolio
export function pagelayer_render_pl_single_img(el){
	
	el.atts['func_img'] = el.tmp['img-'+el.atts['img-size']+'-url'] || el.tmp['img-url'];
	el.atts['func_img'] = el.atts['func_img'] || el.atts['img'];
	
	// What is the link ?
	if('link_type' in el.atts){
		
		// Custom url
		if(el.atts['link_type'] == 'custom_url'){
			el.atts['func_link'] = pagelayer_empty(el.tmp['link']) ? '' : el.tmp['link'];
		}
		
		// Link to the media file itself
		if(el.atts['link_type'] == 'media_file'){
			el.atts['func_link'] = el.tmp['img-url'] || el.atts['img'];
		}
		
		// Lightbox
		if(el.atts['link_type'] == 'lightbox'){
			el.atts['func_link'] = el.tmp['img-url'] || el.atts['img'];
		}
	}
}

// Incase if there is a lightbox
export function pagelayer_render_end_pl_single_img(el){
	jQuery(el.$).parent().attr('data-groups','["'+el.atts['cat_name']+'"]');
	pagelayer_pl_image(el.$);
}

// Render the Single Review
export function pagelayer_render_end_pl_review(el){
	var jEle = el.$.find('.pagelayer-stars-container');
	jEle.removeAttr('pagelayer-setup');
	pagelayer_stars(jEle);
}

// Render the chart
export function pagelayer_render_pl_chart(el){
	el['atts']['xcolor'] = pagelayer_empty(el['atts']['xcolor']) ? '' : pagelayerParseColor(el['atts']['xcolor'], false);
	el['atts']['ycolor'] = pagelayer_empty(el['atts']['ycolor']) ? '' : pagelayerParseColor(el['atts']['ycolor'], false);
}

// Render the chart
export function pagelayer_render_end_pl_chart(el){ 
	var jEle = el.$;
	pagelayer_chart(jEle);
}

// Render the chart Dataset
export function pagelayer_render_pl_chart_datasets(el){
	el['atts']['chart_border_color'] = pagelayer_empty(el['atts']['chart_border_color']) ? '' : pagelayerParseColor(el['atts']['chart_border_color'], false);
	el['atts']['bg_color'] = pagelayer_empty(el['atts']['bg_color']) ? '' : pagelayerParseColor(el['atts']['bg_color'], false);
}

export function pagelayer_render_pl_call(el) {
	el.tmp['cta_image-url'] = el.tmp['cta_image-url'] || el.atts['cta_image'];
}

// Render the fb comments
export function pagelayer_render_pl_fb_comments(el) {
	if (el.atts['link_type'] == "current") {
		el.atts['custom-url'] = pagelayer_post_permalink;
	}
};

// Render the fb comments
export function pagelayer_render_end_pl_fb_comments(el) {
	pagelayer_fb_apps(el.$);
};

export function pagelayer_render_pl_image_map(el){
	const [mapPath, setMapPath] = useState('');
	el.atts['map_img_id'] = el.tmp['img_map-id-'+el.atts['img_map-size']+'-url'] || el.tmp['map_img-id-url'];
	el.atts['map_img_id'] = el.atts['map_img_id'] || el.atts['map_img-id'];
	el.atts['pagelayer-srcset'] = el.atts['map_img_id']+', '+el.atts['map_img_id']+' 1x, ';

	useEffect(()=>{
		if (el.atts && el.atts['pagelayer_image_map']) {
			let pathString = '';
			el.atts['pagelayer_map_path'] = ''; 
			for (const key in el.atts['pagelayer_image_map']) {
				const data_cord = el.atts['pagelayer_image_map'][key]?.path || '';
				const data_id = key; 
				const data_link = el.atts['pagelayer_image_map'][key]?.link || '';
			pathString += `<path class='pagelayer-imgmap-item' d='' stroke-width='2' data-cord='${data_cord}' data-id='${data_id}' fill-opacity='0.3' fill-rule='evenodd' data-link='${data_link}'></path>`;
			}
			setMapPath(pathString);
		}
	},[]);

	el.atts['pagelayer_map_path'] = mapPath;

	var image_atts = {
		name : 'map_img-id',
		size : 'img_map-size'
	};

	pagelayer_get_img_src(el, image_atts);
};

export function pagelayer_render_end_pl_image_map(el){
	// Re-render image maps

	pagelayer_pl_image_map(el.$);
	// el.$.find('.pagelayer-image-map-svg g').append();
		
	// Re-render image map handler
	pagelayer_imgmap_handler(el.$, el);
};

// Image Map handler
function pagelayer_imgmap_handler(jEle, el){
	const { attributes, setAttributes } = el.props;
	var mapObj = attributes['pagelayer_image_map'] || {},
		sEle = jEle.find('svg'),
		cordWrap = jEle.find('.pagelayer-imgmap-coordinates-wraper'),
		toolbar = jEle.find('.pagelayer-imgmap-toolbar'),
		wrap = jEle.find('.pagelayer-imgmap-wrapper');
	
	// Cords drag handler
	var handle_cord_drag = function(jEle){
		var cordEle = jEle.find('.pagelayer-imgmap-coord');
		var isDragging = false;

		const stopDragging = () => {
			isDragging = false;
			cordEle.removeClass('pagelayer-mapele-dragging').off('mouseup click');
			jQuery(document).off('mouseup.imgmap');
		};

		cordEle.off('mousedown').on('mousedown', function (e) {
			e.stopPropagation();
			e.preventDefault();

			if (jQuery(e.target).hasClass('pagelayer-imgmap-remove-cord')) return;

			isDragging = true;
			jQuery(this).addClass('pagelayer-mapele-dragging').mouseup(stopDragging).click(stopDragging);

			jQuery(document).on('mouseup.imgmap', stopDragging);

			sEle.off('mouseup mousemove');

			sEle.mouseup(function(e){
				isDragging = false;
			});

			sEle.mousemove(function (e) {
				if (!isDragging) return;

				const dragEle = jEle.find('.pagelayer-imgmap-coord.pagelayer-mapele-dragging');
				if (!dragEle.length) return;

				const xPer = ((e.offsetX / wrap.width()) * 100).toFixed(2);
				const yPer = ((e.offsetY / wrap.height()) * 100).toFixed(2);

				dragEle.css({ left: `${xPer}%`, top: `${yPer}%` });
				update_active_element_coordinates(xPer, yPer, dragEle.data('id'));
			});
		});
	}

	// Update active element's coordinates
	var update_active_element_coordinates = function(x, y, id){
		const activeEle = jEle.find('.pagelayer-imgmap-item.pagelayer-map-item-active');
		const coords = activeEle.attr('data-cord').split(',');
		coords.splice(id * 2, 2, x, y);
		activeEle.attr('data-cord', coords.join(','));
		pagelayer_resize_imgmap(jEle);
	};
	
	// Delete cord handler
	var cord_delete_handler = function(e){
		e.stopPropagation();
		const parent = jQuery(this).parent();
		const cordPos = parent.attr('data-id');
		const activeEle = sEle.find('.pagelayer-map-item-active');
		const activeEleId = activeEle.attr('data-id');
		// Remove coordinates
		const cords = activeEle.attr('data-cord').split(',');
		cords.splice(cordPos * 2, 2);
		activeEle.attr('data-cord', cords.join(','));
		parent.remove();
		// Reindex coordinates and resize the image map
		jEle.find(`.pl-cord-${activeEleId}`).each((index, elem) => {
			jQuery(elem).attr('data-id', index);
		});
		pagelayer_resize_imgmap(jEle);
	}
	
	// Map items click handler
	var handleClick = function(){

		if(sEle.find('.pagelayer-map-item-active').length > 0){
			return;
		}
		
		sEle.find('.pagelayer-map-item-active_is_editable').removeClass('pagelayer-map-item-active_is_editable')

		var imageMapItem = jQuery(this).addClass('pagelayer-map-item-active_is_editable');

		set_toolbar_editable(true, 'selected');
		
		// Edit map item
		toolbar.find('.pagelayer-map_edit').off('click').on('click', function (e){
			e.preventDefault();
			editItem(imageMapItem);
		});
		
		
		jEle.on('click.handleOutsideClick', function(event){
			event.preventDefault();
			if(sEle.find('.pagelayer-map-item-active').length > 0){
				return;
			}

			if(!jQuery(event.target).hasClass('pagelayer-imgmap-item')){
				imageMapItem.removeClass('pagelayer-map-item-active_is_editable');
				set_toolbar_editable(false, 'selected');
				set_toolbar_editable(false);
				jEle.off('click.handleOutsideClick');
			}
		});
	}
	
	// Remove image map item
	var remove_map_item = function(id){
		if(id in mapObj) delete mapObj[id];
		setAttributes({ 'pagelayer_image_map': { ...mapObj } });
		handle_navigator(id,'delete');
		cordWrap.find('.pl-cord-'+id).remove();
		jEle.find('.pagelayer-imgmap-item[data-id="'+id+'"]').remove();
	}
	
	// Edit Map Item
	var editItem = function(imageMapItem){
		setTimeout(() => {
			set_toolbar_editable(true);
			
			imageMapItem.removeClass('pagelayer-map-item-active_is_editable').addClass('pagelayer-map-item-active');
		
			sEle.css('cursor', 'crosshair');
			
			var updatedActId = imageMapItem.attr('data-id');
			var link = (mapObj[updatedActId] && mapObj[updatedActId].link && mapObj[updatedActId].link.length > 0) ? mapObj[updatedActId].link : '';
			if (link.length > 0) toolbar.find('.pagelayer-map_href').css('color', 'blue');
			cordWrap.find(`.pl-cord-${updatedActId}`).show();
			toolbar.find('.pagelayer-imgmap-toolbar-link input[type=text]').val(link);
			
			handle_navigator(updatedActId, 'set_active');
			handle_cord_drag(jEle);
			
			cordWrap.find('.pagelayer-imgmap-remove-cord').off('click').on('click', cord_delete_handler);
			
		}, 100);
	}
	
	// Add Toolbar
	if(toolbar.length < 1){
		var toolbarHtml = `<div class="pagelayer-imgmap-toolbar">
			<span class="pagelayer-imgmap-toolbar-mover" title="Drag Toolbar"></span>
			<button class="pagelayer-imgmap-toolbar-item pagelayer-map_append" title="Add"><i class="fas fa-plus"></i></button>
			<button class="pagelayer-imgmap-toolbar-item pagelayer-map_save" title="Save"><i class="fas fa-check"></i></button>
			<button class="pagelayer-imgmap-toolbar-item pagelayer-map_edit" title="Edit"><i class="fas fa-edit"></i></button>
			<button class="pagelayer-imgmap-toolbar-item pagelayer-map_href" title="Insert Link"><i class="fas fa-link"></i></button>
			<button class="pagelayer-imgmap-toolbar-item pagelayer-map_remove" title="Delete"><i class="fas fa-trash"></i></button>
			<div class="pagelayer-imgmap-toolbar-link">
				<input type="text" name="url" placeholder="https://example.com" autocomplete="off">
				<span class="pagelayer-imgmap-save-link pagelayer-btn-success">Save</span>
			</div>
			<button class="pagelayer-map-list-trigger" title="Navigator"><i class="fas fa-sitemap"></i></button>
			<div class="pagelayer-imgmap-navigator">
				<div class="pagelayer-imgmap-navigator-header">
					<i class="fas fa-sitemap"></i><span>Navigator</span>
					<span class="fa fa-remove pagelayer-imgmap-navigator-close"></span>
				</div>
				<div class="pagelayer-imgmap-navigator-wrap"></div>
			</div>
		</div>`;

		toolbar = wrap.append(toolbarHtml).find('.pagelayer-imgmap-toolbar');
	}
	
	var linkWrap = toolbar.find('.pagelayer-imgmap-toolbar-link'),
		linkEle = linkWrap.find('input[type="text"]'),
		navigator = toolbar.find('.pagelayer-imgmap-navigator'),
		navigatorWrap = navigator.find('.pagelayer-imgmap-navigator-wrap');
		
	// Change mode of Toolbar
	var set_toolbar_editable = function(on = true, mode = 'edit'){
		
		var edit = mode;
		var select = mode == 'edit'? 'selected' : 'edit';
		
		// Toggle editing options
		if(on){
			toolbar.addClass('pagelayer-imgmap-'+edit);
			toolbar.removeClass('pagelayer-imgmap-'+select);
			return;
		}
		
		toolbar.removeClass('pagelayer-imgmap-'+edit);
	}
	
	// On move Toolbar	
	var doc = jQuery(pagelayerGetDocumentElement());
	toolbar.find('.pagelayer-imgmap-toolbar-mover').off('mousedown').on('mousedown', e => {
		e.preventDefault();

		toolbar.addClass('pagelayer-imgmap-toolbar-dragging');
		sEle.on('mousemove', e => {
			toolbar.hasClass('pagelayer-imgmap-toolbar-dragging') &&
				toolbar.css({ left: `${e.offsetX - 5}px`, top: `${e.offsetY - 35}px` });
		});

		jQuery(doc).off('mousedown.pl_svg_ele').on('mouseup.pl_svg_ele', () => {
			toolbar.removeClass('pagelayer-imgmap-toolbar-dragging');
			sEle.off('mousemove');
		});

	});


	// Toolbar actions
	toolbar.find('.pagelayer-imgmap-toolbar-item').off('click').on('click', function(e){
		e.stopPropagation();

		var tEle = jQuery(this),
			activeEle = sEle.find('.pagelayer-map-item-active'),
			actEleId = activeEle.attr('data-id'),
			isEditing = false;

		if(linkEle.length < 1) toolbar.find('.pagelayer-map_href').css('color', 'inherit');
		sEle.css('cursor','initial');
		
		// Add new map item
		if(tEle.hasClass('pagelayer-map_append')){
			var eleId = pagelayerRandstr(6),
				attrs = [
					['d',''], ['data-id', eleId], ['stroke-linejoin', 'round'],
					['fill-rule', 'evenodd'], ['fill-opacity', '0.3'], ['stroke-width', '2'],
					['data-cord', '{{data}}'], ['data-link', '{{link_href}}']
				],
				pathEle = pagelayer_create_imgmap_svg(['pagelayer-imgmap-item','pagelayer-map-item-active'], attrs);

			handle_navigator(eleId, 'append', true);
			sEle.find('g')[0].appendChild(pathEle);
			sEle.find('.pagelayer-imgmap-item').off('click').on('click', handleClick);
			isEditing = true;
		}
		
		// Remove map item
		if(tEle.hasClass('pagelayer-map_remove')){
			let activeId = sEle.find('.pagelayer-map-item-active, .pagelayer-map-item-active_is_editable').attr('data-id');
			remove_map_item(activeId);
		}
		
		// Link to map item
		if(tEle.hasClass('pagelayer-map_href')){
			toolbar.find('.pagelayer-imgmap-toolbar-link').fadeToggle();
			isEditing = true;
		}
		
		// Save map item cords
		if(tEle.hasClass('pagelayer-map_save')){
			if(cordWrap.find('.pl-cord-' + actEleId).length < 3){
				return alert('Please draw at least 3 coordinates!');
			}
			
			var finalValues = activeEle.attr('data-cord') || '',
			currentItem = navigatorWrap.find(`.pagelayer-imgmap-navigator-item[data-id="${actEleId}"]`),
			title = currentItem.find('.pagelayer-imgmap-navigator-title').text();
			
			mapObj[actEleId] = mapObj[actEleId] || {};
			mapObj[actEleId].path = finalValues || '';
			mapObj[actEleId].title = title || '';

			setAttributes({ 'pagelayer_image_map': { ...mapObj } });
			// pagelayer_set_atts(jEle, 'pagelayer_image_map', mapObj);
	
			jQuery('.pagelayer-map_href').css('color', linkWrap.css('display') == 'block' && linkEle.val() ? 'blue' : 'inherit');
			handle_navigator(actEleId, 'reset_active');
	
			cordWrap.find('.pl-cord-' + actEleId).hide();
			cordWrap.find('.pagelayer-imgmap-coord').removeClass('pagelayer-mapele-dragging');
			sEle.find('.pagelayer-imgmap-item').removeClass('pagelayer-map-item-active');
		}
		
		// Toggle editing options
		set_toolbar_editable(isEditing);
		
	});
	
	// Save link of map items
	jEle.find('.pagelayer-imgmap-save-link').click(function() {
		let parent = jQuery(this).parent();
		let actEleId = sEle.find('.pagelayer-map-item-active').data('id');
		mapObj = mapObj || {};
		(mapObj[actEleId] = mapObj[actEleId] || {}).link = parent.find('input').val() || '';
		parent.fadeOut();
	});
	
	// SVG click handler and add new cords to map items
	sEle.off('click').on('click', function(e){
		var activeEle = sEle.find('.pagelayer-map-item-active');

		if(activeEle.length < 1){
			toolbar.css({ left: e.offsetX - 15, top: e.offsetY - 40 });
			return;
		}

		linkEle.val(''); // Reset Link field
		sEle.css('cursor','crosshair'); // Change cursor property

		var [mapWidth, mapHeight] = [wrap.width(), wrap.height()];
		var [xPer, yPer] = [(e.offsetX / mapWidth * 100).toFixed(2), (e.offsetY / mapHeight * 100).toFixed(2)];
		var coords = (activeEle.attr('data-cord') || '');

		coords = (coords == '{{data}}' || coords == '') ? [] : coords.split(',');
		coords.push(xPer, yPer);
		activeEle.attr('data-cord', coords);

		// Append cordinates
		const cordLen = cordWrap.find(`.pl-cord-${activeEle.attr('data-id')}`).length;
		const coordHTML = `<div class="pagelayer-imgmap-coord pl-cord-${activeEle.attr('data-id')}" 
			title="Drag to reposition" data-id="${cordLen}" 
			style="left:${e.offsetX}px; top:${e.offsetY}px;">
				<span class="pagelayer-imgmap-remove-cord fa fa-trash"></span>
			</div>`;

		cordWrap.append(coordHTML);

		setTimeout(() => pagelayer_resize_imgmap(jEle), 100);
		handle_cord_drag(jEle);
		cordWrap.find('.pagelayer-imgmap-remove-cord').off('click mousedown').on('click', cord_delete_handler);
	});
	
	// Map items click handler
	sEle.find('.pagelayer-imgmap-item').off('click').on('click', handleClick);
	
	// Toggle navigator
	toolbar.find('.pagelayer-map-list-trigger').off('click').on('click', function(){
		navigator.toggle();
	});
	
	navigator.find('.pagelayer-imgmap-navigator-close').on('click',function(){
		navigator.hide();
	});
	
	// Navigator item move handler
	var navigator_move_item = function(curEle, is_next = false) {
		const arr = Object.keys(mapObj);
		const curPos = arr.indexOf(curEle);
	
		if (curPos === -1 || (curPos === 0 && !is_next) || (curPos === arr.length - 1 && is_next)) {
			return false;
		}
		const swapIndex = is_next ? curPos + 1 : curPos - 1;
		[arr[curPos], arr[swapIndex]] = [arr[swapIndex], arr[curPos]]
		mapObj = arr.reduce((newEl, key) => ({ ...newEl, [key]: mapObj[key] }), {});

		setAttributes({'pagelayer_image_map' : mapObj})
		// pagelayer_set_atts(jEle, 'pagelayer_image_map', mapObj);
		const elem = jEle.find(`path[data-id="${curEle}"]`);
		is_next ? elem.next().after(elem) : elem.prev().before(elem);
	
		return true;
	}
	
	// Navigator handler
	var handle_navigator = function(id, opr = 'append', is_active = false){
		if (!id) return;		
		const item = navigatorWrap.find(`.pagelayer-imgmap-navigator-item[data-id="${id}"]`);

		switch(opr){
			case 'append':
				if (item.length > 0) return;
				const wrapItems = navigatorWrap.children('.pagelayer-imgmap-navigator-item').length + 1;
				const cls = is_active ? 'pagelayer-navigator-item-active' : '';
				const title = mapObj[id]?.title || `Map Item ${wrapItems}`;

				const content = `
				<div class="pagelayer-imgmap-navigator-item ${cls}" data-id="${id}">
					<div data-id="${id}" class="pagelayer-imgmap-navigator-item-drag"><i class="fas fa-th-list"></i></div>
					<div class="pagelayer-imgmap-navigator-title">${title}</div>
					<div class="pagelayer-imgmap-navigator-actions">
						${['Move Up', 'Edit', 'Delete', 'Move Down'].map((action, i) => `
							<button value="${id}" class="pagelayer-map-navigator-trigger ${['navigator_move_up', 'navigator_pagelayer-map_edit', 'navigator_pagelayer-map_remove', 'navigator_move_down'][i]}" title="${action}">
								<i class="${['fa fa-arrow-up', 'fa fa-pencil', 'fas fa-trash', 'fa fa-arrow-down'][i]}"></i>
							</button>`).join('')}
					</div>
				</div>`;
				navigatorWrap.append(content);

				var trigger = navigatorWrap.find('.pagelayer-map-navigator-trigger');
				trigger.off('click').on('click', function(e){
					e.stopPropagation();
					var eleId = jQuery(this).val();

					if(jQuery(this).hasClass('navigator_pagelayer-map_edit')){
						const activeEle = sEle.find('.pagelayer-map-item-active');
						
						// Multi Item editing
						if(activeEle.length > 0){
							if(eleId === activeEle.attr('data-id')) return;
							toolbar.find('.pagelayer-imgmap-toolbar-item.pagelayer-map_save').click();
						}
						
						let iEle = jEle.find(`.pagelayer-imgmap-item[data-id="${eleId}"]`);
						iEle.on('click', editItem(iEle));
						
					}else if (jQuery(this).hasClass('navigator_move_down') || jQuery(this).hasClass('navigator_move_up')){
						const par = jQuery(this).closest('.pagelayer-imgmap-navigator-item');
						const moveUp = jQuery(this).hasClass('navigator_move_up');
						const sibling = moveUp ? par.prev() : par.next();

						if(sibling.length > 0){
							navigator_move_item(eleId, !moveUp);
							moveUp ? sibling.before(par) : sibling.after(par);
						}				
					}else if(jQuery(this).hasClass('navigator_pagelayer-map_remove')){
						remove_map_item(eleId);
						toolbar.removeClass('pagelayer-imgmap-edit');
					}
				});
				
				// Make title editable
				navigatorWrap.find(`.pagelayer-imgmap-navigator-item[data-id="${id}"] .pagelayer-imgmap-navigator-title`).off('blur').on('click', function (){
					const editable = jQuery(this).attr('contenteditable', 'true').focus();
					const oldVal = editable.text().trim();
					
					editable.on('blur', function (e) {
						const newValue = editable.text().trim();
						if (!newValue) {
							alert('Error changing title');
							editable.text(oldVal);
						}else{
							mapObj[id].title = newValue;
							setAttributes({'pagelayer_image_map': {...mapObj}});
							// pagelayer_set_atts(jEle, 'pagelayer_image_map', mapObj);
						}
						editable.attr('contenteditable', 'false').off('blur');
					});
				});
				break;

			case 'delete':
				item.remove();
				break;
			case 'reset_active':
				navigatorWrap.find('.pagelayer-imgmap-navigator-item').removeClass('pagelayer-navigator-item-active');
				break;
			case 'set_active':
				if(!item.hasClass('pagelayer-navigator-item-active')){
					item.addClass('pagelayer-navigator-item-active');
					jQuery('.pagelayer-imgmap-navigator-wrap').animate({
						scrollTop: 0
					});
				}
				break;
		}
	}
	
	// Build Navigator
	if(Object.keys(mapObj).length > 0){
		for (var mapId in mapObj) {
			handle_navigator(mapId);
		}
	}

	pagelayer_resize_imgmap(jEle);
	jQuery(window).on('resize', function(){pagelayer_resize_imgmap(jEle)});
}
