/**
 * Custom scripts needed for the colorpicker, image button selectors,
 * and navigation tabs.
 */

jQuery(document).ready(function($) {

	"use strict";
	
	$(document).on('change', '.selectcountry', function() {

		var get_ID = this.value;

		$('.selectregion').remove();
		$('.selectcity').remove();

		$.ajax({
			type: "POST",
			url: ajaxurl,
			data: { action: 'get_countries', id: get_ID, location_type: 'country' }
		}).done(function( msg ) {
			$('.datebook-country-last').before(msg.response);
			
		});
	});

	$(document).on('change', '.selectregion', function() {

		var get_ID = $(this).val();

		$('.selectcity').remove();

		$.ajax({
			type: "POST",
			url: ajaxurl,
			data: { action: 'get_countries', id: get_ID, location_type: 'region' }
		}).done(function( msg ) {
			$('.datebook-country-last').before(msg.response);
		});
	});

	// Loads the color pickers
	$('.of-color').wpColorPicker();

	// Image Options
	$('.of-radio-img-img').on('click', function(){
		$(this).parent().parent().find('.of-radio-img-img').removeClass('of-radio-img-selected');
		$(this).addClass('of-radio-img-selected');
	});

	$('.of-radio-img-label').hide();
	$('.of-radio-img-img').show();
	$('.of-radio-img-radio').hide();

	// Loads tabbed sections if they exist
	if ( $('.datebook-framework-panel.nav-tab-wrapper').length > 0 ) {
		options_framework_tabs();
	}

	function options_framework_tabs() {

		var $group = $('.group'),
			$navtabs = $('.nav-tab-wrapper a'),
			datebook_active_tab = '';

		// Hides all the .group sections to start
		$group.hide();

		// Find if a selected tab is saved in localStorage
		if ( typeof(localStorage) !== 'undefined' ) {
			datebook_active_tab = localStorage.getItem('datebook_active_tab_framework');
		}
		
		if (datebook_active_tab === undefined || datebook_active_tab === null) {

			$('.group:first').fadeIn();
			$('.nav-tab-wrapper a:first').addClass('nav-tab-active');

		} else {

			var matches = /page=([^&#=]*)/.exec(datebook_active_tab);
			var get_page = matches[1];

			// If active tab is saved and exists, load it's .group
			if ( get_page === 'datebook-options-framework' ) {
				var hash = '#' + datebook_active_tab.substring(datebook_active_tab.indexOf("#")+1);
				$(hash).fadeIn();
				$(hash + '-tab').addClass('nav-tab-active');
			} else {
				$('.group:first').fadeIn();
				$('.nav-tab-wrapper a:first').addClass('nav-tab-active');
			}

		}


		// Bind tabs clicks
		$navtabs.click(function(e) {

			e.preventDefault();

			// Remove active class from all tabs
			$navtabs.removeClass('nav-tab-active');

			$(this).addClass('nav-tab-active').blur();

			if (typeof(localStorage) !== 'undefined' ) {
				localStorage.setItem('datebook_active_tab_framework', 'page=datebook-options-framework' + $(this).attr('href') );
			}

			var selected = $(this).attr('href');

			$group.hide();
			$(selected).fadeIn();

		});
	}
	

	// Loads tabbed sections if they exist
	if ( $('.datebook-design-panel.nav-tab-wrapper').length > 0 ) {
		options_design_tabs();
	}

	function options_design_tabs() {

		var $group = $('.group'),
			$navtabs = $('.nav-tab-wrapper a'),
			datebook_active_tab = '';

		// Hides all the .group sections to start
		$group.hide();

		// Find if a selected tab is saved in localStorage
		if ( typeof(localStorage) !== 'undefined' ) {
			datebook_active_tab = localStorage.getItem('datebook_active_tab_design');
		}
		
		if (datebook_active_tab === undefined || datebook_active_tab === null) {

			$('.group:first').fadeIn();
			$('.nav-tab-wrapper a:first').addClass('nav-tab-active');

		} else {

			var matches = /page=([^&#=]*)/.exec(datebook_active_tab);
			var get_page = matches[1];

			// If active tab is saved and exists, load it's .group
			if ( get_page === 'datebook-options-design' ) {
				var hash = '#' + datebook_active_tab.substring(datebook_active_tab.indexOf("#")+1);
				$(hash).fadeIn();
				$(hash + '-tab').addClass('nav-tab-active');
			} else {
				$('.group:first').fadeIn();
				$('.nav-tab-wrapper a:first').addClass('nav-tab-active');
			}

		}


		// Bind tabs clicks
		$navtabs.click(function(e) {

			e.preventDefault();

			// Remove active class from all tabs
			$navtabs.removeClass('nav-tab-active');

			$(this).addClass('nav-tab-active').blur();

			if (typeof(localStorage) !== 'undefined' ) {
				localStorage.setItem('datebook_active_tab_design', 'page=datebook-options-design' + $(this).attr('href') );
			}

			var selected = $(this).attr('href');

			$group.hide();
			$(selected).fadeIn();

		});
	}
	
	
	// Function for creating Profile Form
	//$(document).on('mouseover', '#repeatable-container', function() {

		// Sort the whole section
		$('#repeatable-container').sortable({
			opacity: 0.6,
			revert: true,
			cursor: 'move',
			handle: '.sort',
			connectWith: ".datebook-drag-box"
		}).disableSelection();
	//});

	//$(document).on('mouseover', '.datebook-drag-box', function() {

		// Sort one field
		$('.datebook-drag-box').sortable({
			opacity: 0.5,
			revert: true,
			cursor: 'move',
			handle: '.sort',
			helper: 'original',
			connectWith: ".datebook-drag-box"
		}).disableSelection();
	//});

	$('#form-fields .datebook-form-field').draggable({
		revert: "invalid",
		appendTo: "body",
		helper: "clone",
		cursor: "move",
	});

	//$(document).on('mouseover', '.datebook-draggable-area .datebook-form-lab .datebook-child-box div', function() {

		// Drag and drop from available fields to the section
		$(".datebook-drag-box-saved").droppable({
			tolerance: "intersect",
			connectWith: $('.datebook-form-lab'),
			accept: ":not(.ui-sortable-helper)",
			over: ".datebook-drag-box-saved",
			activeClass: 'highlight',
			hoverClass: "ui-state-hover",
			drop: function(event, ui) {
				$(this).addClass("ui-state-highlight");
				var formfieldid = ui.draggable.attr("data-id");
				if(self.find("[data-id=" + formfieldid + "]").length){ return; }
				$("[data-id=" + formfieldid + "]").hide();
				$("#repeatable-container .datebook-drag-here").hide();

				$('<div></div>', {
					"html": ui.draggable.html(),
					"data-id": formfieldid,
				}).appendTo(this);

			}
		});
		
	//});


	$(document).on('click', '.add-row', function() {

		// store the current count in a variable (this will not change if the user adds another row)
		var rowNum = "";
		var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		
		for (var i = 0; i < 12; i++) {
			rowNum += possible.charAt(Math.floor(Math.random() * possible.length));
		}

		$(".datebook-column-notice").hide();

		if ($(this).attr("data-function") === 'addonecolumn') {

			var row = $('.empty-row.onerow-column').clone(true);

			var rowName = 'onecolumnrow_';

			$('<input/>', { name: 'rowColumn_0_' + rowNum, value: 1, type: 'hidden' }).appendTo(row.children(".datebook-column-0").stop(true, true));

		} 

		if ($(this).attr("data-function") === 'addtwocolumn') {

			var row = $('.empty-row.tworow-column').clone(true);

			var rowName = 'twocolumnrow_';

			$('<input/>', { name: 'rowColumn_1_' + rowNum, value: 1, type: 'hidden' }).appendTo(row.children(".datebook-column-1").stop(true, true));
			$('<input/>', { name: 'rowColumn_2_' + rowNum, value: 1, type: 'hidden' }).appendTo(row.children(".datebook-column-2").stop(true, true));

		}

		row.removeClass('empty-row screen-reader-text');

		row.attr('id', 'rowid_' + rowNum);

		$('<input/>', { name: rowName + rowNum, value: 1, type: 'hidden' }).prependTo(row);

		row.insertBefore('#repeatable-container .datebook-column-notice');
		
		$("#rowid_" + rowNum + " .datebook-drag-box").droppable({
			tolerance: "intersect",
			connectWith: $('.datebook-form-lab'),
			accept: ":not(.ui-sortable-helper)",
			over: '#rowid_' + rowNum + ' .datebook-drag-box',
			activeClass: 'highlight',
			hoverClass: "ui-state-hover",
			drop: function(event, ui) {
				$(this).addClass("ui-state-highlight");
				var formfieldid = ui.draggable.attr("data-id");
				if(self.find("[data-id=" + formfieldid + "]").length){ return; }
				$("[data-id=" + formfieldid + "]").hide();
				$("#repeatable-container .datebook-drag-here").hide();

				$('<div></div>', {
					"html": ui.draggable.html(),
					"data-id": formfieldid,
				}).appendTo(this);

			}
		});

		for(i=0;i<3;i++) {
			row.fadeTo('slow', 0.5).fadeTo('slow', 1.0);
		}

		$('#rowid_' + rowNum + ' .datebook-select-title').attr('name', 'rowTitle_' + rowNum);

		return false;

	});


	$(document).on('click', '.datebook-delete-item', function() {

		var confirmdelete = confirm(datebookdeletepopup.datebook_delete_confirm_text);

		if (confirmdelete) {
			
			if ($(this).attr("data-function") === 'datebook-deleterow') {

				$(this).parent().parent().find('[data-id]').each(function() {

					var formfieldid = $(this).attr('data-id');

					$('.datebook-fields-area').find("[data-id=" + formfieldid + "]").each(function() {
						$("[data-id=" + formfieldid + "]").show();
					});

				});

				$(this).parent().parent().fadeOut(1200, function() { $(this).remove(); });

			}

			if ($(this).attr("data-function") === 'datebook-deletefield') {

				var formfieldid = $(this).parent().attr('data-id');

				$(this).parent().fadeOut(800, function() { $(this).remove(); });

				$('.datebook-fields-area').find("[data-id=" + formfieldid + "]").each(function() {
					$("[data-id=" + formfieldid + "]").show();
	   			});

			}

			return true;

		} else {

			return false;

		}

	});


	// Add more Prices and Periods in Subscription plan
	$(document).on('click', '#datebook-addprice', function() {
		$('#datebook-pricetable tr').last().clone().appendTo('#datebook-pricetable');
	});
	
	// Remove row with Price and Period
	$(document).on('click', '.datebook-removeprice', function() {
		
		var rowCount = $('#datebook-pricetable tr').length;
		
		// Do not remove a row if it is last
		if(rowCount > 1){
		
			$(this).closest('tr').remove();
		
		}
	});


    function display_wc_product_subscription_options(){
        if( $('#_datebook_subscribe').prop('checked')){
            $('.wcaddon_price_is_per, .wcaddon_max_length').show();
        }else{
            $('.wcaddon_price_is_per, .wcaddon_max_length').hide();
        }
    }
    $('#_datebook_subscribe').on('change', function(){
        display_wc_product_subscription_options();
    });
    display_wc_product_subscription_options();

    $('#_wcaddon_price_time_option').on('change', function(){
        $('.wcaddon_max_length .description span').text( $(this).val() );
		var selected = $(this).find(':selected'),
            max_value = selected.data('max');
        $('.wcaddon_max_length .description .max-l').text( max_value );
    });
	

	// Enable country slug input
	$(document).on('click', '.datebook-country-slug-button', function() {
		document.getElementById("datebook-country-slug").disabled = false;
	});
	
	$( document ).on( 'click', '.datebook-custom-fields-dismiss-notice', function() {
		var data = {
			action: 'datebook_custom_fields_dismiss_notice',
		};

		$.post( ajaxurl, data, function() {
		
		});
	})


	$(".tooltip-hover").on("mouseover", function () {

		var className = $(this).attr("tooltip-id");

		const button = document.querySelector('.' + className);
		const tooltip = document.querySelector('.tooltip-window-' + className);

		const popperInstance = Popper.createPopper(button, tooltip, {
			modifiers: [{
				name: 'offset',
				options: {
					offset: [0, 8],
				},
			},],
			placement: 'top',
		});

		function show() {
        // Make the tooltip visible
        tooltip.setAttribute('data-show', '');

        // Enable the event listeners
        popperInstance.setOptions({
          modifiers: [{ name: 'eventListeners', enabled: true }],
        });

        // Update its position
        popperInstance.update();
      }

      function hide() {
        // Hide the tooltip
        tooltip.removeAttribute('data-show');

        // Disable the event listeners
        popperInstance.setOptions({
          modifiers: [{ name: 'eventListeners', enabled: false }],
        });
      }

      const showEvents = ['mouseenter', 'focus'];
      const hideEvents = ['mouseleave', 'blur'];

      showEvents.forEach(event => {
        button.addEventListener(event, show);
      });

      hideEvents.forEach(event => {
        button.addEventListener(event, hide);
      });

	});
	
	
	
	function datebook_profiletype_media_upload(button_class) {
         var _custom_media = true,
         _orig_send_attachment = wp.media.editor.send.attachment;
         $('body').on('click', button_class, function(e) {
           var button_id = '#'+$(this).attr('id');
           var send_attachment_bkp = wp.media.editor.send.attachment;
           var button = $(button_id);
           _custom_media = true;
           wp.media.editor.send.attachment = function(props, attachment){
             if ( _custom_media ) {
               $('#datebook-profiletype-image-id').val(attachment.id);
               $('#datebook-profiletype-image-wrapper').html('<img class="custom_media_image" src="" style="margin:0;padding:0;max-height:100px;float:none;" />');
               $('#datebook-profiletype-image-wrapper .custom_media_image').attr('src',attachment.url).css('display','block');
             } else {
               return _orig_send_attachment.apply( button_id, [props, attachment] );
             }
            }
         wp.media.editor.open(button);
         return false;
       });
     }
     datebook_profiletype_media_upload('.ct_tax_media_button.button'); 
     $('body').on('click','.ct_tax_media_remove',function(){
       $('#datebook-profiletype-image-id').val('');
       $('#datebook-profiletype-image-wrapper').html('<img class="custom_media_image" src="" style="margin:0;padding:0;max-height:100px;float:none;" />');
     });

     $(document).ajaxComplete(function(event, xhr, settings) {
       var queryStringArr = settings.data.split('&');
       if( $.inArray('action=add-tag', queryStringArr) !== -1 ){
         var xml = xhr.responseXML;
         $response = $(xml).find('term_id').text();
         if($response!=""){
           // Clear the thumb image
           $('#datebook-profiletype-image-wrapper').html('');
         }
       }
     });
   
	
});