/**
 * @author https://www.cosmosfarm.com
 */

/**
 * inViewport jQuery plugin by Roko C.B.
 * http://stackoverflow.com/a/26831113/383904 Returns a callback function with
 * an argument holding the current amount of px an element is visible in
 * viewport (The min returned value is 0 (element outside of viewport)
 */
(function($, win){
	$.fn.kboardViewport = function(cb){
		return this.each(function(i, el){
			function visPx(){
				var elH = $(el).outerHeight(), H = $(win).height(), r = el.getBoundingClientRect(), t = r.top, b = r.bottom;
				return cb.call(el, Math.max(0, t > 0 ? Math.min(elH, H - t) : (b < H ? b : H)));
			}
			visPx();
			$(win).on("resize scroll", visPx);
		});
	};
}(jQuery, window));

var kboard_ajax_lock = false;
if(typeof kboard_current == 'undefined') var kboard_current = {};
if(typeof window.kboard_editor_runtime == 'undefined') window.kboard_editor_runtime = null;

jQuery(document).ready(function(){
	var kboard_mod = kboard_current.mod ? kboard_current.mod : jQuery('input[name=mod]', '.kboard-form').val();
	if(kboard_mod == 'editor'){
		jQuery('.kboard-tree-category-wrap').each(function(){
			var wrap = jQuery(this);
			if(wrap.data('use-tree-category') == 'yes' || kboard_current.use_tree_category == 'yes'){
				kboard_tree_category_parents(wrap);
			}
		});
		
		if(kboard_current.use_editor == 'snote'){ // summernote
			jQuery('.summernote').each(function(){
				var height = parseInt(jQuery(this).height());
				var placeholder = jQuery(this).attr('placeholder');
				var lang = 'en-US';
				
				if(kboard_settings.locale == 'ko_KR'){
					lang = 'ko-KR';
				}
				else if(kboard_settings.locale == 'ja'){
					lang = 'ja-JP';
				}
				
				jQuery(this).summernote({
					toolbar: [
						['style', ['style']],
						['fontsize', ['fontsize']],
						['font', ['bold', 'italic', 'underline', 'clear']],
						['fontname', ['fontname']],
						['color', ['color']],
						['para', ['ul', 'ol', 'paragraph']],
						['height', ['height']],
						['table', ['table']],
						['insert', ['link', 'video', 'hr', 'media']],
						['view', ['fullscreen', 'codeview']],
						['help', ['help']]
					],
					buttons: {
						media: function (context) {
							var ui = jQuery.summernote.ui;
							var button = ui.button({
								contents: '<i class="note-icon-picture"></i>',
								tooltip: '이미지 입력',
								click: function () {
									kboard_editor_open_media();
								}
							});
							return button.render();
						}
					},
					disableDragAndDrop: true,
					fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande', 'Tahoma', 'Times New Roman', 'Verdana', 'Nanum Gothic', 'Malgun Gothic', 'Noto Sans KR', 'Apple SD Gothic Neo'],
					fontNamesIgnoreCheck: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande', 'Tahoma', 'Times New Roman', 'Verdana', 'Nanum Gothic', 'Malgun Gothic', 'Noto Sans KR', 'Apple SD Gothic Neo'],
					fontSizes: ['8','9','10','11','12','13','14','15','16','17','18','19','20','24','30','36','48','64','82','150'],
					lang: lang,
					height: height,
					placeholder: placeholder
				});
			});
		}

		kboard_editor_mount_scaffold();
	}
});

function kboard_editor_mount_scaffold(){
	var adapter = kboard_current.use_editor;
	var mountEditor = function(){
		try{
			window.kboard_editor_runtime = window.KBoardEditorBootstrap.mount({
				adapter: adapter,
				selector: kboard_current.editor_root_selector ? kboard_current.editor_root_selector : '#kboard-editor-root',
				textareaId: kboard_current.editor_textarea_id ? kboard_current.editor_textarea_id : 'kboard_content',
				formSelector: '.kboard-form'
			});
		}
		catch(error){
			window.kboard_editor_runtime = null;
			if(window.console && console.error){
				console.error('[KBoard] Failed to mount editor scaffold:', error);
			}
			jQuery('#kboard_content').show();
		}

		return window.kboard_editor_runtime;
	};

	if(adapter != 'tiptap' && adapter != 'editorjs'){
		return null;
	}
	if(window.kboard_editor_runtime && window.kboard_editor_runtime.adapter){
		return window.kboard_editor_runtime;
	}
	if(typeof window.KBoardEditorBootstrap == 'undefined' || !window.KBoardEditorBootstrap.mount){
		return null;
	}

	if(adapter == 'tiptap' && window.kboardTipTapReady && typeof window.kboardTipTapReady.then === 'function'){
		window.kboardTipTapReady.then(function(){
			mountEditor();
		}).catch(function(error){
			if(window.console && console.error){
				console.error('[KBoard] TipTap runtime failed:', error);
			}
			jQuery('#kboard_content').show();
		});
		return null;
	}

	return mountEditor();
}

function kboard_editor_sync_content(form){
	var runtime = window.kboard_editor_runtime;
	var textarea = jQuery('#kboard_content', form).length ? jQuery('#kboard_content', form) : jQuery('#kboard_content');

	if(runtime && runtime.adapter && typeof runtime.adapter.getHTML === 'function' && textarea.length){
		textarea.val(runtime.adapter.getHTML());
	}

	return textarea.length ? textarea.val() : '';
}

function kboard_tree_category_search(index, value, element){
	var length = jQuery('.kboard-search-option-wrap').length;
	var tree_category_index;
	var form = null;

	if(element){
		form = jQuery(element).closest('form');
	}

	// index에 tree_category_ 접두사가 포함되어 있는지 확인
	var search_index = (index.toString().indexOf('tree_category_') === -1) ? 'tree_category_' + index : index;
	tree_category_index = parseInt(search_index.replace('tree_category_', '')) + 1;

	if(value){
		if(form){
			jQuery('input[name="kboard_search_option['+search_index+'][value]"]', form).val(value);
		}
		else{
			jQuery('input[name="kboard_search_option['+search_index+'][value]"]').val(value);
		}
	}
	else{
		if(form){
			jQuery('input[name="kboard_search_option['+search_index+'][value]"]', form).val('');
		}
		else{
			jQuery('input[name="kboard_search_option['+search_index+'][value]"]').val('');
		}
	}
	
	for(var i=tree_category_index; i<=length; i++){
		if(form){
			jQuery('.kboard-search-option-wrap-'+i, form).remove();
		}
		else{
			jQuery('.kboard-search-option-wrap-'+i).remove();
		}
	}
	
	if(form){
		form.submit();
	}
	else if(kboard_current.board_id){
		jQuery('#kboard-tree-category-search-form-'+kboard_current.board_id).submit();
	}
	
	return false;
}

function kboard_tree_category_parents(wrap){
	if(!wrap) wrap = jQuery('.kboard-tree-category-wrap');
	
	var use_tree_category = wrap.data('use-tree-category') ? wrap.data('use-tree-category') : kboard_current.use_tree_category;
	var tree_category = wrap.data('tree-category') ? wrap.data('tree-category') : kboard_current.tree_category;
	var board_id = wrap.data('board-id') ? wrap.data('board-id') : kboard_current.board_id;
	
	if(use_tree_category == 'yes' || use_tree_category === true){
		var tree_category_name;
		var tree_category_index = 1;
		
		tree_category_name = 'kboard_option_tree_category_';
		
		wrap.prepend('<select id="kboard-tree-category-'+tree_category_index+'" class="kboard-tree-category kboard-tree-category-'+tree_category_index+'"></select>');
		jQuery('#kboard-tree-category-'+tree_category_index, wrap).append('<option value="">'+kboard_localize_strings.category+' '+kboard_localize_strings.select+'</option>');
		jQuery('#kboard-tree-category-'+tree_category_index, wrap).after('<input type="hidden" id="'+tree_category_name+tree_category_index+'" name="'+tree_category_name+tree_category_index+'" class="kboard-tree-category-hidden-'+tree_category_index+'">');
		
		jQuery('#kboard-tree-category-'+tree_category_index, wrap).change(function(){
			kboard_tree_category_children(this.value, tree_category_index, tree_category_name, wrap);
			jQuery('#kboard-tree-category-search-form-'+board_id).submit();
		});
		
		jQuery.each(tree_category, function(index, element){
			if(!element.parent_id){
				jQuery('#kboard-tree-category-'+tree_category_index, wrap).append('<option value="'+element.id+'">'+element.category_name+'</option>');
			}
		});

		kboard_tree_category_selected(tree_category_index, tree_category_name, wrap);
	}
}

function kboard_tree_category_children(category_id, tree_category_index, tree_category_name, wrap){
	if(!wrap) wrap = jQuery('.kboard-tree-category-wrap');
	
	var tree_category = wrap.data('tree-category') ? wrap.data('tree-category') : kboard_current.tree_category;
	var board_id = wrap.data('board-id') ? wrap.data('board-id') : kboard_current.board_id;
	
	var length = jQuery('.kboard-tree-category', wrap).length;
	var check = 0;
	
	for(var i=tree_category_index+1; i<=length; i++){
		jQuery('.kboard-tree-category-'+i, wrap).remove();
		jQuery('.kboard-tree-category-hidden-'+i, wrap).remove();
	}
	
	jQuery.each(tree_category, function(index, element){
		if(jQuery('#kboard-tree-category-'+tree_category_index, wrap).val() == element.id){
			jQuery('#'+tree_category_name+tree_category_index, wrap).val(element.category_name);
		}
	});
	
	if(jQuery('#kboard-tree-category-'+tree_category_index, wrap).val()){
		jQuery.each(tree_category, function(index, element){
			if(category_id === element.parent_id){
				if(check==0){
					jQuery('#kboard-tree-category-'+tree_category_index, wrap).after('<select id="kboard-tree-category-'+(tree_category_index+1)+'" class="kboard-tree-category kboard-tree-category-'+(tree_category_index+1)+'"></select>');
					jQuery('#kboard-tree-category-'+(tree_category_index+1), wrap).append('<option value="">'+kboard_localize_strings.category+' '+kboard_localize_strings.select+'</option>');
					
					jQuery('#kboard-tree-category-'+(tree_category_index+1), wrap).after('<input type="hidden" id="'+tree_category_name+(tree_category_index+1)+'" name="'+tree_category_name+(tree_category_index+1)+'" class="kboard-tree-category-hidden-'+(tree_category_index+1)+'">');
					
					jQuery('#kboard-tree-category-'+(tree_category_index+1), wrap).change(function(){
						kboard_tree_category_children(this.value, (tree_category_index+1), tree_category_name, wrap);
						jQuery('#kboard-tree-category-search-form-'+board_id).submit();
					});
				}
				check++;
				jQuery('#kboard-tree-category-'+(tree_category_index+1), wrap).append('<option value="'+element.id+'">'+element.category_name+'</option>');
			}
		});
		kboard_tree_category_selected(tree_category_index+1, tree_category_name, wrap);
	}
	else{
		for(var i=tree_category_index; i<=length; i++){
			jQuery('.kboard-tree-category-hidden-'+i, wrap).val('');
			jQuery('.kboard-tree-category-hidden-'+(i+1), wrap).remove();
		}
	}
	
	if(jQuery('.kboard-tree-category-search', wrap).length){
		jQuery('input[name="kboard_search_option[tree_category_'+tree_category_index+'][value]"', wrap).val(jQuery('#'+tree_category_name+tree_category_index, wrap).val());
		jQuery('input[name="kboard_search_option[tree_category_'+tree_category_index+'][key]"', wrap).val('tree_category_'+tree_category_index);
	}
}

function kboard_tree_category_selected(tree_category_index, tree_category_name, wrap){
	if(!wrap) wrap = jQuery('.kboard-tree-category-wrap');
	
	var check = jQuery('#tree-category-check-'+tree_category_index, wrap.parent()).val();
	
	if(check){
		jQuery('#kboard-tree-category-'+tree_category_index+' option', wrap).each(function(index, element){
			if(jQuery(element).text() == check){
				jQuery(element).attr('selected', 'selected');
				kboard_tree_category_children(this.value, tree_category_index, tree_category_name, wrap);
			}
		});
	}
	return false;
}

function kboard_editor_open_media(){
	var w = 900;
	var h = 500;
	var media_popup_url = kboard_current.add_media_url;
	
	if(kboard_current.board_id){
		if(jQuery('#kboard_media_wrapper').length){
			jQuery('#kboard_media_wrapper').show();
			jQuery('#kboard_media_wrapper').html(jQuery('<iframe frameborder="0"></iframe>').attr('src', media_popup_url));
			jQuery('#kboard_media_background').show();
		}
		else{
			var wrapper = jQuery('<div id="kboard_media_wrapper"></div>');
			var background = jQuery('<div id="kboard_media_background"></div>').css({opacity:'0.5'}).click(function(){
				kboard_media_close();
			});
			
			function init_window_size(){
				if(window.innerWidth <= 900){
					wrapper.css({left:0, top:0, margin:'10px', width:(window.innerWidth-20), height:(window.innerHeight-20)});
				}
				else{
					wrapper.css({left:'50%', top:'50%', margin:0, 'margin-left':(w/2)*-1, 'margin-top':(h/2)*-1, width:w, height:h});
				}
			}
			init_window_size();
			jQuery(window).resize(init_window_size);
			
			wrapper.html(jQuery('<iframe frameborder="0"></iframe>').attr('src', media_popup_url));
			jQuery('body').append(background);
			jQuery('body').append(wrapper);
			
			if(!jQuery('input[name="media_group"]').filter(function(){return this.value==kboard_settings.media_group}).length){
				jQuery('[name="board_id"]').parents('form').append(jQuery('<input type="hidden" name="media_group">').val(kboard_settings.media_group));
			}
		}
	}
}

function kboard_editor_insert_media(url){
	if(window.kboard_editor_runtime && window.kboard_editor_runtime.adapter && typeof window.kboard_editor_runtime.adapter.insertMedia == 'function'){
		window.kboard_editor_runtime.adapter.insertMedia(url);
	}
	else if(kboard_current.use_editor == 'snote'){ // summernote
		jQuery('#kboard_content').summernote('editor.saveRange');
		jQuery('#kboard_content').summernote('editor.restoreRange');
		jQuery('#kboard_content').summernote('editor.focus');
		jQuery('#kboard_content').summernote('editor.pasteHTML', "<img src=\""+url+"\" alt=\"\">");
	}
	else if(typeof tinyMCE != 'undefined' && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()){
		tinyMCE.activeEditor.execCommand('mceInsertContent', false, "<img id=\"last_kboard_media_content\" src=\""+url+"\" alt=\"\">");
		tinyMCE.activeEditor.focus();
		tinyMCE.activeEditor.selection.select(tinyMCE.activeEditor.dom.select('#last_kboard_media_content')[0], true);
		tinyMCE.activeEditor.selection.collapse(false);
		tinyMCE.activeEditor.dom.setAttrib('last_kboard_media_content', 'id', '');
	}
	else if(jQuery('#kboard_content').length){
		jQuery('#kboard_content').val(function(index, value){
			return value + (!value?'':' ') + "<img src=\""+url+"\" alt=\"\">";
		});
	}
}

function kboard_media_close(){
	jQuery('#kboard_media_wrapper').hide();
	jQuery('#kboard_media_background').hide();
}

function kboard_document_print(url){
	window.open(url, 'kboard_document_print');
	return false;
}

function kboard_document_like(button, callback){
	if(!kboard_ajax_lock){
		kboard_ajax_lock = true;
		jQuery.post(kboard_settings.ajax_url, {'action':'kboard_document_like', 'document_uid':jQuery(button).data('uid'), 'security':kboard_settings.ajax_security}, function(res){
			kboard_ajax_lock = false;
			if(typeof callback === 'function'){
				callback(res);
			}
			else{
				if(res.result == 'error'){
					alert(res.message);
				}
				else{
					jQuery('.kboard-document-like-count', button).text(res.data.like);
				}
			}
		});
	}
	else{
		alert(kboard_localize_strings.please_wait);
	}
	return false;
}

function kboard_document_unlike(button, callback){
	if(!kboard_ajax_lock){
		kboard_ajax_lock = true;
		jQuery.post(kboard_settings.ajax_url, {'action':'kboard_document_unlike', 'document_uid':jQuery(button).data('uid'), 'security':kboard_settings.ajax_security}, function(res){
			kboard_ajax_lock = false;
			if(typeof callback === 'function'){
				callback(res);
			}
			else{
				if(res.result == 'error'){
					alert(res.message);
				}
				else{
					jQuery('.kboard-document-unlike-count', button).text(res.data.unlike);
				}
			}
		});
	}
	else{
		alert(kboard_localize_strings.please_wait);
	}
	return false;
}

function kboard_comment_like(button, callback){
	if(!kboard_ajax_lock){
		kboard_ajax_lock = true;
		jQuery.post(kboard_settings.ajax_url, {'action':'kboard_comment_like', 'comment_uid':jQuery(button).data('uid'), 'security':kboard_settings.ajax_security}, function(res){
			kboard_ajax_lock = false;
			if(typeof callback === 'function'){
				callback(res);
			}
			else{
				if(res.result == 'error'){
					alert(res.message);
				}
				else{
					jQuery('.kboard-comment-like-count', button).text(res.data.like);
				}
			}
		});
	}
	else{
		alert(kboard_localize_strings.please_wait);
	}
	return false;
}

function kboard_comment_unlike(button, callback){
	if(!kboard_ajax_lock){
		kboard_ajax_lock = true;
		jQuery.post(kboard_settings.ajax_url, {'action':'kboard_comment_unlike', 'comment_uid':jQuery(button).data('uid'), 'security':kboard_settings.ajax_security}, function(res){
			kboard_ajax_lock = false;
			if(typeof callback === 'function'){
				callback(res);
			}
			else{
				if(res.result == 'error'){
					alert(res.message);
				}
				else{
					jQuery('.kboard-comment-unlike-count', button).text(res.data.unlike);
				}
			}
		});
	}
	else{
		alert(kboard_localize_strings.please_wait);
	}
	return false;
}

function kboard_fields_validation(form, callback){
	jQuery('.kboard-attr-row.required', form).each(function(index, element){
		var required;
		
		if(jQuery(element).hasClass('kboard-attr-content')){
			if(kboard_current.use_editor == 'yes'){
				if(jQuery('#wp-kboard_content-wrap').hasClass('tmce-active')){
					jQuery('#kboard_content').val(tinymce.get('kboard_content').getContent());
				}
			}
			else if(kboard_current.use_editor == 'tiptap' || kboard_current.use_editor == 'editorjs'){
				kboard_editor_sync_content(form);
			}
			required = jQuery('#kboard_content');
		}
		else{
			required = jQuery(element).find('.required');
		}
		
		if(jQuery(required).is(':checkbox') || jQuery(required).is(':radio')){
			if(jQuery(element).find('.required:checked').length == 0){
				alert(kboard_localize_strings.required.replace('%s', jQuery(element).find('.field-name').text()));
				callback(jQuery(required).eq(0));
				return false;
			}
		}
		else if(jQuery(required).val() == 'default' || !jQuery(required).val()){
			if(jQuery(element).hasClass('kboard-attr-address')){
				if(!jQuery('.kboard-row-postcode input').val() || !jQuery('.kboard-row-address-1 input').val()){
					alert(kboard_localize_strings.required.replace('%s', jQuery(element).find('.field-name').text()));
					callback(required);
					return false;
				}
				else{
					return true;
				}
			}
			else if(jQuery(element).hasClass('kboard-attr-file')){
				if(jQuery('input[name="'+jQuery(element).children('.attr-value').children().attr('name')+'"]').val() == ''){
					alert(kboard_localize_strings.required.replace('%s', jQuery(element).find('.field-name').text()));
					callback(required);
					return false;
				}
				else{
					return true;
				}
			}
			else{
				alert(kboard_localize_strings.required.replace('%s', jQuery(element).find('.field-name').text()));
				callback(required);
				return false;
			}
		}
	});
}

function kboard_content_update(content_uid, data, callback){
	if(!kboard_ajax_lock){
		kboard_ajax_lock = true;
		jQuery.post(kboard_settings.ajax_url, {'action':'kboard_content_update', 'content_uid':content_uid, 'data':data, 'security':kboard_settings.ajax_security}, function(res){
			kboard_ajax_lock = false;
			if(typeof callback === 'function'){
				callback(res);
			}
		});
	}
	else{
		alert(kboard_localize_strings.please_wait);
	}
	return false;
}

function kboard_ajax_builder(args, callback){
	if(!kboard_ajax_lock){
		kboard_ajax_lock = true;
		var callback2 = (typeof callback === 'function') ? callback : args['callback'];
		args['action'] = 'kboard_ajax_builder';
		args['callback'] = '';
		args['security'] = kboard_settings.ajax_security;
		jQuery.get(kboard_settings.ajax_url, args, function(res){
			kboard_ajax_lock = false;
			if(typeof callback2 === 'function'){
				callback2(res);
			}
		});
	}
	else{
		alert(kboard_localize_strings.please_wait);
	}
	return false;
}

function kboard_recaptcha_v3_token(form, callback){
	var $form = jQuery(form);
	var $recaptcha = jQuery('.kboard-recaptcha-v3', $form).first();
	if(!$recaptcha.length){
		callback(false);
		return;
	}
	
	var siteKey = $recaptcha.data('sitekey');
	var action = $recaptcha.data('action') || 'kboard_submit';
	var $token = jQuery('input[name=g-recaptcha-response]', $form).first();
	
	if(!siteKey || !$token.length){
		callback(false);
		return;
	}
	
	if(typeof grecaptcha === 'undefined' || !grecaptcha.execute){
		callback(false);
		return;
	}
	
	grecaptcha.ready(function(){
		grecaptcha.execute(siteKey, {action: action}).then(function(token){
			$token.val(token);
			callback(true);
		}, function(){
			callback(false);
		});
	});
}

document.addEventListener('submit', function(event){
	var form = event.target;
	if(!form || !form.querySelector || !form.querySelector('.kboard-recaptcha-v3')){
		return;
	}
	if(form.dataset.kboardRecaptchaV3Ready == '1'){
		form.dataset.kboardRecaptchaV3Ready = '';
		return;
	}
	if(form.dataset.kboardRecaptchaV3Loading == '1'){
		event.preventDefault();
		if(event.stopImmediatePropagation){
			event.stopImmediatePropagation();
		}
		event.stopPropagation();
		return;
	}
	
	event.preventDefault();
	if(event.stopImmediatePropagation){
		event.stopImmediatePropagation();
	}
	event.stopPropagation();
	form.dataset.kboardRecaptchaV3Loading = '1';
	
	kboard_recaptcha_v3_token(form, function(success){
		form.dataset.kboardRecaptchaV3Loading = '';
		if(success){
			form.dataset.kboardRecaptchaV3Ready = '1';
			if(typeof form.requestSubmit === 'function'){
				form.requestSubmit();
			}
			else{
				var submitButton = document.createElement('button');
				submitButton.type = 'submit';
				submitButton.style.display = 'none';
				form.appendChild(submitButton);
				submitButton.click();
				form.removeChild(submitButton);
			}
		}
		else{
			jQuery(form).removeData('submitted');
			if(typeof kboard_localize_strings !== 'undefined' && kboard_localize_strings.please_wait){
				alert(kboard_localize_strings.please_wait);
			}
			else{
				alert('Please wait.');
			}
		}
	});
}, true);
