

//document.getElementById('bookings-right-col').innerHTML = 'Hello world';

function removeLastOccurrence(str, target) {
  const lastIndex = str.lastIndexOf(target);
  if (lastIndex === -1) {
    return str;
  }
  const regex = new RegExp(target, 'g');
  const matches = [];
  let match;

  while ((match = regex.exec(str)) !== null) {
    matches.push({ index: match.index, text: match[0] });
  }

  if (matches.length > 0) {
    const lastMatch = matches.pop();
    return str.slice(0, lastMatch.index) + str.slice(lastMatch.index + lastMatch.text.length);
  }
  return str;
}

function uuid()
{
  return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
    (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)
  );
}


function ajaxGet(url, callback, stripFormTags = true)
{
		$.ajaxSetup({async:false});

	    $.get(url, function(content, status)
	    {

		   data = stripTags(content, stripFormTags);
		   callback(data);
  	 });
}

/**
 * remove body tag and other div tags
 */
function stripTags(content, stripFormTags = true)
{
	content = content.replace('</body>', '');

	content = content.replace(/<div class="dialog-off-canvas-main-canvas" .+>/, '');
	content = removeLastOccurrence(content, '</div>');

	content = content.replace('<div id="block-ajax-content">', '');
	content = removeLastOccurrence(content, '</div>');

	content = content.replace(/<div>/, '');
	content = removeLastOccurrence(content, '</div>');

	if (stripFormTags) {
		content = content.replace(/<form .+>/, '');
		content = content.replace('</form>', '');
	}
	return content;
}

function getGuestsForm(data)
{
  setTimeout(function() {
	$("#bookings-right-col").html('<div id="times-right-col" class="shadow">' + data + '</div>');
  }, 500)
}

function getCalendar(data)
{
  $("#htmlcalendar-top").html(data);
}

function getCalendarLink(data)
{
  dataform = data;
  setTimeout(function() {
  	$("#bookings-right-col").html('<div id="times-right-col" class="shadow">' + data + '</div>');
    }, 500)

}

function formFields(form)
{
	str = form.match(/<input .+type=\".+\" name="form_token" .+/).toString();
	str = str.match(/value=\".*?\"/).toString();
	str = str.replace(/value\=\"/, '').toString();
	this.form_token = str.replace(/\"/, '').toString();

	str = form.match(/<input .+type=\".+\" name="form_id" .+/).toString();
	str = str.match(/value=\".*?\"/).toString();
	str = str.replace(/value\=\"/, '').toString();
	this.form_id = str.replace(/\"/, '').toString();

	str = form.match(/<input .+type=\".+\" name="form_build_id" .+/).toString();
	str = str.match(/value=\".*?\"/).toString();
	str = str.replace(/value\=\"/, '').toString();
	this.form_build_id = str.replace(/\"/, '').toString();
}

$(".select-time").click (function(select) {
	select.preventDefault();
	return false;
});

dataform = '';



$( document ).ready(function()
{

   const html = $("#spinner-wrap").html();

   //var rightcolwidth = ($("#bookings-right-col").width() / 2) - 35;
   var rightcolwidth = ($("#bookings-right-col").width() / 2) - 250;
   //var rightcolheight = ($("#bookings-right-col").height() / 2) - 35;
   var rightcolheight = ($("#bookings-right-col").height() / 2) - 100;

   spinner = html.replace('img', 'img style="margin-left: ' + rightcolwidth + 'px; margin-top: ' + rightcolheight + 'px;" ');

   if ($("#edit-guests").length) {

     const selectElement = document.querySelector("#edit-guests");
	   selectElement.addEventListener("change", (e) =>
	   {

	   	num = $("#edit-guests").val();

		$("#bookings-right-col").html(spinner);
	    ajaxGet("/booking/ajax/times/" + num, getGuestsForm, true);


	   	guests = document.getElementById('guests');
	   	guests.innerHTML = num;
	   	if (num == 1) {
	   	 	document.getElementById('persons').innerHTML = 'person';
	   	} else {
	   	 	document.getElementById('persons').innerHTML = 'people';
	   	}
	  	return false;
	 });

	}

	function isValid(fields)
	{
		var valid = true;
		for (i=0; i<fields.length; i++)
		{
			var value = $("#" + fields[i]).val();
			if (!value.length) {
				valid = false;
			}
		}
		return valid;
	}

	function requirementsForm()
	{

		/*$(".right-button").off();
		$(".right-button").click (function (event)
		{
			event.preventDefault();
			$("#user-requirements").submit();
		});*/
	}

	//function

	//if ($("#add-ajax-booking").length) {
    setInterval(function() {


	  $(".select-time2").off();
	  $(".select-time2").click (function(selecttime) {

      //console.log ('hello world');
      //return false;

		  selecttime.preventDefault();

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

		  $("#bookings-right-col").html(spinner);

          ajaxGet(href, getCalendarLink, false);


	  });

	  if ($("#user-data").length) {
		//detailsForm();
	  }

	  if ($("#user-requirements").length) {

		requirementsForm();
	  }

	  //submit form from right-button
	  $(".right-button").off();
	  $(".right-button").click (function (right) {
		right.preventDefault();

		str = dataform.match(/<input .+type=\".+\" name="form_id" .+/).toString();
		str = str.match(/value=\".*?\"/).toString();
		str = str.replace(/value\=\"/, '').toString();
		form_id = str.replace(/\"/, '').toString();

		href = this.href;


		switch (form_id) {
			case 'user_data':

					str = '?form_id=' + 'user_data';
					str += '&email=' + encodeURIComponent($("input[name=email]").val());
					str += '&firstname=' + encodeURIComponent($("input[name=firstname]").val());
					str += '&lastname=' + encodeURIComponent($("input[name=lastname]").val());
					str += '&phone=' + encodeURIComponent($("input[name=phone]").val());
					str += '&company=' + encodeURIComponent($("input[name=company]").val());
					str += '&title=' + encodeURIComponent($("select[name=title]").val());

					url = href + str;

					$.ajaxSetup({async:true});
					$("#bookings-right-col").html(spinner);
					setTimeout(function () {

						$.ajaxSetup({async:false});
						$.get(url, function(content, status)
						{
							data = '<div class="shadow">' + stripTags(content, true) + '</div>';
							$("#bookings-right-col").html(data);
							dataform = data;
						});

						}, 10);

				break;

			case 'user_requirements':

					str = '?form_id=' + 'user_requirements';

					$("input[type=checkbox]:checked").each(
						function () {
							value = $(this).val();
							str += '&checkrequirements[' + value + ']=' + value;
						}

					);

					str += '&requirements=' + encodeURIComponent($("textarea[name=requirements]").val());

					url = href + str;

					$.ajaxSetup({async:true});
					$("#bookings-right-col").html(spinner);
					setTimeout(function () {

							$.get(url, function(content, status)
							{
								data = '<div class="shadow">' + stripTags(content, true) + '</div>';
								$("#bookings-right-col").html(data);
								dataform = data;
							});


					}, 10);


				break;


			default:

				//console.log (this.href);



				$.ajaxSetup({async:false});
				$("#bookings-right-col").html(spinner);
				setTimeout(function () {

						$.get(href, function(content, status)
						{
							data = '<div class="shadow">' + stripTags(content, true) + '</div>';
							$("#bookings-right-col").html(data);
							dataform = data;
						});


					}, 10);


		}


	  });

	  $(".left-button").off();
	  $(".left-button").click (function (left) {

		  href = this.href;

		  left.preventDefault();

		  $.ajaxSetup({async:true});
		  $("#bookings-right-col").html(spinner);

		  setTimeout(function () {

			  //http://restauranthq.local/booking/ajax/data/1762589700

				$.get(href, function(content, status)
				{
					data = '<div class="shadow">' + stripTags(content, true) + '</div>';
					$("#bookings-right-col").html(data);
					dataform = data;
				});


			}, 10);
	  });



      ///booking/ajax/day/{time}
      $(".calendar-link-day").off();
      $(".calendar-link-day").click (function(day)
      {
          day.preventDefault();
          var href = $(this).attr('href');

		  //$.ajaxSetup({async:true});
		  $("#bookings-right-col").html(spinner);
          ajaxGet(href, getCalendarLink, true);

		  result = href.replace('/booking/ajax/day/', '/booking/ajax/calendar/');

		  ajaxGet(result, getCalendar, true);

      });



     //event handler for calendar link
      $(".calendar-link").off();
      $(".calendar-link").click (function(linkevent)
      {
        linkevent.preventDefault();
        var href = $(this).attr('href');
        $("#htmlcalendar-top").hide();
        ajaxGet(href, getCalendarLink, true);
      });
      //end event click handler for calendar link


      //assign a click function to the calendar-link-arrow class
      $(".calendar-link-arrow").off();
      $(".calendar-link-arrow").click(function(arrowEvent)
      {

		arrowEvent.preventDefault();

		var href = $(this).attr('href');
		$("#htmlcalendar-top").html('');
		ajaxGet (href, getCalendar, true);

		calendarlink = href.replace('/booking/ajax/calendar/', '/booking/ajax/time/');
		$("#bookings-right-col").html(spinner);
		ajaxGet(calendarlink, getCalendarLink, true);

      });
      //end calendar-link-arrow event


   }, 10);
   //} /* end if form **/

});
