// Check length for string and object
window.pagelayerBlockNameByTag = (tag) => {
	return 'pagelayer/'+tag.replaceAll('_', '-');
}

// Check length for string and object
window.pagelayerLength = (mixed_var) => {
	
	var length = 0;
	var undef, key, i, len;
	var emptyValues = [undef, null, false];

	for(i = 0, len = emptyValues.length; i < len; i++) {
		if (mixed_var === emptyValues[i]) {
			return length;
		}
	}
	
	// Is array, object or jQuery object?
	if(typeof mixed_var === 'object'){
		
		// If is jQuery object
		if( mixed_var.hasOwnProperty('length')){
			return mixed_var.length;
		}
		
		for (key in mixed_var) {
			// TODO: should we check for own properties only?
			//if (	.hasOwnProperty(key)) {
			length++;
			//}
		}
		
		return length;
	}
	
	length = String(mixed_var).length;

	return length;
};

// Convert the regular URL of a Video to a Embed URL
window.pagelayer_video_url = (src, no_url) => {

	no_url = no_url || false;
	var youtubeRegExp = /youtube\.com|youtu\.be/;
	var vimeoRegExp = /vimeo\.com/;
	var match = '';
	var videoId = '';
	var vid_params = {};
		
	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/');
			}
			
			vid_params = {
				type : 'youtube',
				src : 'https://www.youtube.com/embed/'+videoId[1],
				id : videoId[1]
			};

			pagelayer_yt_api_register();
			
			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/');
			}
			
			vid_params = {
				type : 'vimeo',
				src : 'https://player.vimeo.com/video/'+videoId[1],
				id : videoId[1]
			};
			
			break;
		default:
			vid_params = {
				type : 'local',
				src : src
			};
			
	}
  
	if(!no_url){
		return vid_params.src;
	}
  
	return vid_params;
}

// Youtube API Register
window.pagelayer_yt_api_register = () => {
	if(jQuery('#pagelayer-youtube-script-js').length > 0){
		return;
	}

	jQuery('body').append('<script src="https://www.youtube.com/iframe_api" id="pagelayer-youtube-script-js"></script>');
}

window.pagelayer_owl_destroy = (jEle, slides_class) => {
	
	if(jEle.length < 1){
		return;
	}
	
	var ul = jEle.find(slides_class);
	var setup = jEle.attr('pagelayer-setup');
	
	// Already setup ?
	if(setup && setup.length > 0){
		if(ul.children('.pagelayer-owl-stage-outer').length > 0){
			ul.pagelayerOwlCarousel('destroy');
			ul.find('[class^="pagelayer-owl-"]').remove();
			jEle.removeAttr('pagelayer-setup');
		}
	}
}

// Parse typography and handle Backward compatibility
window.pagelayerParseTypo = (value, noglobal, desk_global, mode) => {
	
	noglobal = noglobal || false;
	mode = mode || 'desktop';
	desk_global = desk_global || '';
	
	if(pagelayer_empty(value)){
		value = {};
	}
	
	// Backward compatibility for comma seperated val
	if(pagelayer_is_string(value) && value.substr(0, 1) != '$'){
		return value.split(',');
	}
	
	var val = ['','','','','','','','','','',''];
	var typos = ['font-family', 'font-size', 'font-style', 'font-weight', 'font-variant', 'text-decoration-line', 'text-decoration-style', 'line-height', 'text-transform', 'letter-spacing', 'word-spacing'];
	
	var global_typo = pagelayerIsGlobalTypo(value);
	var _desk_global = false;
	
	if(pagelayer_empty(global_typo)){
		global_typo = desk_global;
		_desk_global = true;
	}
	
	// Apply global typo
	for(var typo in typos){
		
		var typoKey = typos[typo];
		
		// Backspace compatibility for normal array
		if(typeof value == 'object' && !pagelayer_empty(value[typo])){
			val[typo] = value[typo];
		}
		
		if(!pagelayer_empty(value[typoKey])){
			val[typo] = value[typoKey];
		}
		
		if(pagelayer_empty(global_typo) || !pagelayer_empty(val[typo]) || noglobal){
			continue;
		}
		
		var globalVal = pagelayer_global_fonts[global_typo]['value'];
		
		if( !(typoKey in globalVal) || pagelayer_empty(globalVal[typoKey]) || (typeof globalVal[typoKey] == 'object' && pagelayer_empty(globalVal[typoKey][mode])) || (typeof globalVal[typoKey] != 'object' && !pagelayer_empty(_desk_global) && mode != 'desktop') ){
			continue;
		}
		
		val[typo] = 'var(--pagelayer-font-'+global_typo+'-'+typoKey+')';
	}
	
	return val;
}

// Is the given global color
window.pagelayerIsGlobalTypo = (value) => {
	
	var typo_key = '';
	
	// Backward compatibility
	if(pagelayer_is_string(value) && value.substr(0, 1) == '$'){
		typo_key = value.substr(1);
	}
	
	if(typeof value == 'object' && 'global-font' in value){
		typo_key = value['global-font'];
	}
		
	// If global color not exist
	if(!pagelayer_empty(typo_key) && !(typo_key in pagelayer_global_fonts)){
		typo_key = 'primary';
	}
	
	return typo_key;
	
}

window.pagelayerUcwords = (str) => {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

window.pagelayer_htmlEntities = (str) => {
	return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

// Is the element in view while scrolling
window.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 ;
}

window.pagelayerIsGlobalColor = (color) => {
	var color_key = color.substr(0, 1) == '$' ? color.substr(1) : '';
	if (!pagelayer_empty(color_key)) {

		if (!(color_key in pagelayer_global_colors)) {
			color_key = 'primary';
		}

		return color_key;
	}
	return false;
}

window.pagelayerParseColor = (value, glob_var = true) =>{

	var is_global = pagelayerIsGlobalColor(value);
	if (pagelayer_empty(is_global)) {
		return value;
	}

	if (pagelayer_empty(glob_var)) {
		return pagelayer_global_colors[is_global]['value'];
	}
	
	return 'var(--pagelayer-color-' + is_global + ')';
}

window.pagelayerTrim = (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 : '';
};

// Compare two objects
window.pagelayer_compare_object = (obj1, obj2) => {
   var objectsAreSame = true;
   for(var propertyName in obj1){
	  if(obj1[propertyName] !== obj2[propertyName]){
		 objectsAreSame = false;
		 break;
	  }
   }
   for(var propertyName in obj2){
	  if(obj1[propertyName] !== obj2[propertyName]){
		 objectsAreSame = false;
		 break;
	  }
   }
   return objectsAreSame;
}

// Generates a random string of "n" characters
window.pagelayerRandstr = (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;
};
