//cursor
// Because of a WebKit-Issue which renders (even SVG) cursors blurry on Retina-Displays I decided to go for a solution which renders the cursor within a custom <div>.
// var rotatingCursor = (function() {
//
//   /* Local Variables */
//   const INTERVAL_POSITION = 5;
//   const INTERVAL_ROTATION = 50;
//   let lastCursorPos = {x: -999, y: -999};
//   let currentCursorPos = {x: -999, y: -999};
//   let lastCursorAngle = 0, cursorAngle = 0;
//   let cursorEl, cursorImageEl;
//
//
//   /* Local Functions */
//
//   // NOTE: I am transform two different elements here because so I can only animate the rotation with 'transition-property: transform'.
//   function setCurrentCursorProps() {
//     // Apply translation (set to actual cursor position)
//     cursorEl.style.transform = `translate(${currentCursorPos.x}px, ${currentCursorPos.y}px)`;
//
//     // Ensure correct rotation transition direction
//     while (Math.abs(lastCursorAngle - cursorAngle) > 180) {
//       if (cursorAngle > lastCursorAngle) {
//         cursorAngle -= 360;
//       } else if (cursorAngle < lastCursorAngle) {
//         cursorAngle += 360;
//       }
//     }
//     // Apply rotation
//     cursorImageEl.style.transform = `rotate(${cursorAngle - 90}deg)`;
//   }
//
//   function updateCursor() {
//     window.addEventListener('mousemove', event => {
//       currentCursorPos = {x: event.clientX, y: event.clientY};
//     });
//
//     // Interval for updating cursor-position
//     setInterval(setCurrentCursorProps, INTERVAL_POSITION);
//
//     // Interval for updating cursor-rotation
//     setInterval(() => {
//       const delt = {
//         x: lastCursorPos.x - currentCursorPos.x,
//         y: lastCursorPos.y - currentCursorPos.y
//       }
//       if (Math.abs(delt.x) < 3 && Math.abs(delt.y) < 3) return;
//       cursorAngle = (Math.atan2(delt.y, delt.x) * 180 / Math.PI);
//
//       setCurrentCursorProps();
//
//       lastCursorPos = currentCursorPos;
//       lastCursorAngle = cursorAngle;
//     }, INTERVAL_ROTATION);
//   }
//
//
//   /* Public Functions */
//
//   return {
//
//     'initialize' : () => {
//       cursorEl = document.querySelector('#cursor');
//       cursorImageEl = document.querySelector('#cursor > img');
//       updateCursor();
//     }
//
//   };
//
// })();
//
// document.addEventListener('DOMContentLoaded', rotatingCursor.initialize);

$(document).ready(function () {

	//open menu
	$(".btn-open-menu").click(function(){
		$('.holder-nav').slideToggle();
		$('.btn-open-menu').toggleClass('active');
		$('.header__menu-btn').toggleClass('active');
		$('body').toggleClass('overflow');
		return false;
	});

    initPlayerForm();
    wow = new WOW();

    $(window).on('load', function () {
		wow.init();
        $('body').addClass('load');
        setTimeout(function() {
            $('.load-block').css('display','none');
            wow.init();


        }, 0);
    });


    // sliders
	$('.starlite__2__slick').slick({
		slidesToShow: 1,
		slidesToScroll: 1,
		dots: false,
		variableWidth: true,
		infinite: false,
		prevArrow: "<div class='starlite__2__slick__prev'><svg><use xlink:href='./images/icons.svg#left'></use></svg></div>",
		nextArrow: "<div class='starlite__2__slick__next'><svg><use xlink:href='./images/icons.svg#right'></use></svg></div>"
	});

	// portfolio filter
	let $grid = $('.portfolio__wrap').isotope({
		itemSelector: '.portfolio__block',
		layoutMode: 'fitRows'
	});

	let filterValue = '';

	$('.portfolio__filter__block').click(function () {

		if ($(this).hasClass('portfolio__filter__block--all')) {
			filterValue = '';
			if (!$(this).hasClass('portfolio__filter__block--active')){
				$('.portfolio__filter__block--active').removeClass('portfolio__filter__block--active');
				$(this).addClass('portfolio__filter__block--active');
			}
		}
		else{
			$('.portfolio__filter__block--all').removeClass('portfolio__filter__block--active');
			$(this).toggleClass('portfolio__filter__block--active');
		}
		if (filterValue != '' && filterValue != '*') {
			filterValue = filterValue + ', ' + $(this).attr('data-filter');
		}
		else{
			filterValue = $(this).attr('data-filter');
		}
		$grid.isotope({ filter: filterValue });

	});

	$('.message-request .check-block').click(function (){
		if($(this).find('.square').hasClass('active'))
			$(this).find('.square').removeClass('active');
		else
			$(this).find('.square').addClass('active');
	});

	$('.message-request .request__close').click(function (){
		$('.message-request').removeClass('animate__fadeInRight');
		$('.message-request').addClass('animate__fadeOutRight');
		$('.message-request').fadeOut();
	});

	$('.message-request .items .item').click(function (){
		if(!$(this).hasClass('active'))
			$(this).addClass('active');
		else
			$(this).removeClass('active');
	});

	$('.header__menu-btn').click(function (){
		// $('.message-request').removeClass('animate__fadeOutRight');
		// $('.message-request').addClass('animate__fadeInRight');
		$('.message-request').fadeIn();
	});

	$('.bottom__title').click(function (){
		// $('.message-request').removeClass('animate__fadeOutRight');
		// $('.message-request').addClass('animate__fadeInRight');
		$('.message-request').fadeIn();
	});

	$('.projects__block--wide').click(function (){
		$('.message-request').fadeIn();
	});

	//right menu hover
	$('.right-menu__block').hover(
		function () {
			if (!$(this).hasClass('right-menu__block--active')) {
				$('.right-menu__block--active').removeClass('right-menu__block--active');
				$(this).addClass('right-menu__block--active');
			}
		}
	);

	$('.blob-btn').click(function (){
		if($('.square').hasClass('active')){
			var name = $('#name').val();
			var phone = $('#phone').val();
			var email = $('#email').val();
			var description = $('#description').val();
			var props = [];

			$( ".message-request .items .item.active" ).each(function( index ) {
				var prop = $(this).text();
				props.push(prop.trim());
			});

			$.ajax({
				url: "/ajax/message_event.php",
				type: "POST",
				dataType: "json",
				data: {
					"name":name,
					"phone":phone,
					"email":email,
					"description":description,
					"props":props
				},
				success: function(json){
					// alert('Ваша заявка успешно отправлена!');
					$('.blob-btn .message').css('color', 'white');
					$('.blob-btn .message').text('Ваша заявка отправлена');
					$('.blob-btn').css('background-color', '#169B00');
					$('.blob-btn .message:after').css('display', 'none');
				}
			});

		}
		else{
			alert('Вы не подтвердили условия обработки персональных данных')
		}
	});

	//map
	if ($('div').is('#map-canvas')){
		function initialize() {
			var styles = [
				{
					"featureType": "all",
					"elementType": "labels.text.fill",
					"stylers": [
						{
							"saturation": 36
						},
						{
							"color": "#000000"
						},
						{
							"lightness": 40
						}
					]
				},
				{
					"featureType": "all",
					"elementType": "labels.text.stroke",
					"stylers": [
						{
							"visibility": "on"
						},
						{
							"color": "#000000"
						},
						{
							"lightness": 16
						}
					]
				},
				{
					"featureType": "all",
					"elementType": "labels.icon",
					"stylers": [
						{
							"visibility": "off"
						}
					]
				},
				{
					"featureType": "administrative",
					"elementType": "geometry.fill",
					"stylers": [
						{
							"color": "#000000"
						},
						{
							"lightness": 20
						}
					]
				},
				{
					"featureType": "administrative",
					"elementType": "geometry.stroke",
					"stylers": [
						{
							"color": "#000000"
						},
						{
							"lightness": 17
						},
						{
							"weight": 1.2
						}
					]
				},
				{
					"featureType": "landscape",
					"elementType": "geometry",
					"stylers": [
						{
							"color": "#000000"
						},
						{
							"lightness": 20
						}
					]
				},
				{
					"featureType": "landscape.man_made",
					"elementType": "geometry.stroke",
					"stylers": [
						{
							"visibility": "on"
						},
						{
							"color": "#f6dd2b"
						},
						{
							"lightness": "-43"
						},
						{
							"saturation": "-97"
						}
					]
				},
				{
					"featureType": "poi",
					"elementType": "geometry",
					"stylers": [
						{
							"color": "#000000"
						},
						{
							"lightness": 21
						}
					]
				},
				{
					"featureType": "road",
					"elementType": "labels.text.fill",
					"stylers": [
						{
							"color": "#f6dd2b"
						},
						{
							"visibility": "on"
						},
						{
							"lightness": "-41"
						}
					]
				},
				{
					"featureType": "road.highway",
					"elementType": "geometry.fill",
					"stylers": [
						{
							"color": "#000000"
						},
						{
							"lightness": 17
						}
					]
				},
				{
					"featureType": "road.highway",
					"elementType": "geometry.stroke",
					"stylers": [
						{
							"color": "#000000"
						},
						{
							"lightness": 29
						},
						{
							"weight": 0.2
						}
					]
				},
				{
					"featureType": "road.arterial",
					"elementType": "geometry",
					"stylers": [
						{
							"color": "#000000"
						},
						{
							"lightness": 18
						}
					]
				},
				{
					"featureType": "road.local",
					"elementType": "geometry",
					"stylers": [
						{
							"color": "#000000"
						},
						{
							"lightness": 16
						}
					]
				},
				{
					"featureType": "transit",
					"elementType": "geometry",
					"stylers": [
						{
							"color": "#000000"
						},
						{
							"lightness": 19
						}
					]
				},
				{
					"featureType": "water",
					"elementType": "geometry",
					"stylers": [
						{
							"color": "#000000"
						},
						{
							"lightness": 17
						}
					]
				}
			];

			var styledMap = new google.maps.StyledMapType(styles, {name: "Styled Map"});
			var mapCanvas = document.getElementById('map-canvas');
			var mapOptions = {
				center: new google.maps.LatLng(55.633568, 37.440806),
				disableDefaultUI: true,
				scrollwheel: false,
				maxZoom: 20,
				minZoom: 14,
				zoomControl: true,
				zoomControlOptions: {
					style: google.maps.ZoomControlStyle.SMALL,
					position: google.maps.ControlPosition.LEFT_CENTER
				},
				zoom: 17
			}
			var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
			map.mapTypes.set('map-canvas', styledMap);
			map.setMapTypeId('map-canvas');

			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(55.633889, 37.442651),
				map: map,
				icon: 'images/geo.png',
				visible: true,
				animation: google.maps.Animation.DROP
			});
			var marker2 = new google.maps.Marker({
				position: new google.maps.LatLng(55.633005, 37.443316),
				map: map,
				icon: 'images/metro.png',
				visible: true,
				animation: google.maps.Animation.DROP
			});

			var directionsDisplay;
			var directionsService = new google.maps.DirectionsService();
			directionsDisplay = new google.maps.DirectionsRenderer({ polylineOptions: { strokeColor: "#f6dd2b" }, suppressMarkers: true });
			directionsDisplay.setMap(map);
			// var request = {
			// 	origin:start,
			// 	destination:end,
			// 	travelMode: google.maps.TravelMode.WALKING
			// };
			// directionsService.route(request, function(response, status) {
			// 	if (status == google.maps.DirectionsStatus.OK) {
			// 		directionsDisplay.setDirections(response);
			// 	}
			// });
		}

		google.maps.event.addDomListener(window, 'load', initialize);
	}

	// starlite
	$('.starlite__3__left__block').click(function () {
		if (!$(this).hasClass('.starlite__3__left__block--active')) {
			$('.starlite__3__left__block--active').removeClass('starlite__3__left__block--active');
			$(this).addClass('starlite__3__left__block--active');
			let index = $(this).index();
			$('.starlite__3__right__block--active').css('display', 'none');
			$('.starlite__3__right__block--active').removeClass('starlite__3__right__block--active');
			$('.starlite__3__right__block').eq(index).addClass('starlite__3__right__block--active');
			$('.starlite__3__right__block').eq(index).fadeIn();
		}
	});

});


function initPlayerForm(){
    $('form').each(function(){
        var form=$(this),
            input=form.find('input:text, input:password');
        form.find('.required').blur(function(){
            var val=$(this).val();
            if(val.length){
                $(this).closest('.rows').removeClass('error');
                $(this).removeClass('error');
            }
            else{
                $(this).closest('.rows').addClass('error');
                $(this).addClass('error');
            }
        });
        form.on('keyup keydown', '.required.error', function(){
            var val=$(this).val();
            if(val.length){
                $(this).closest('.rows').removeClass('error');
                $(this).removeClass('error');
            }
            else{
                $(this).closest('.rows').addClass('error');
                $(this).addClass('error');
            }
        });
        form.find('.phone').blur(function(){
            var val=$(this).val();
            if((/[0-9\(\) \+]/).test(val)){
                $(this).closest('.rows').removeClass('error');
                $(this).removeClass('error');
            }
            else{
                $(this).closest('.rows').addClass('error');
                $(this).addClass('error');
            }
        });
        form.on('keyup keydown', '.phone.error', function(){
            var val=$(this).val();
            if((/^[0-9\s-\(\)\+]{18}$/ig).test(val)){
                $(this).closest('.rows').removeClass('error');
                $(this).removeClass('error');
            }
            else{
                $(this).closest('.rows').addClass('error');
                $(this).addClass('error');
            }
        });
        form.find('.emailv').blur(function(){
            var val=$(this).val();
            if((/^[-\._a-z0-9]+@(?:[a-z0-9][-a-z0-9]+\.)+[a-z]{2,6}$/ig).test(val) && val.length<=30){
                $(this).closest('.rows').removeClass('error');
                $(this).removeClass('error');
            }
            else{
                $(this).closest('.rows').addClass('error');
                $(this).addClass('error');
            }
        });
        form.on('keyup keydown', '.emailv.error', function(){
            var val=$(this).val();
            if((/^[-\._a-z0-9]+@(?:[a-z0-9][-a-z0-9]+\.)+[a-z]{2,6}$/ig).test(val) && val.length<=30){
                $(this).closest('.rows').removeClass('error');
                $(this).removeClass('error');
            }
            else{
                $(this).closest('.rows').addClass('error');
            }
        });
        form.find('select').on('change', function() {
            $(this).closest('.rows').removeClass('error');
        });
        form.find('.check-required').on('change', function() {
            if($(this).prop('checked')){
                $(this).closest('label').removeClass('error');
            } else {
                $(this).closest('label').addClass('error');
            }
        });
        form.submit(function(e){
            input.trigger('blur');
            form.find('select').each(function() {
                if(!$(this).val()){
                    $(this).closest('.rows').addClass('error');
                }
            });
            form.find('.check-required').each(function() {
                if(!$(this).prop('checked')){
                    $(this).closest('label').addClass('error');
                    return false;
                }
            });
            if(form.find('.error').length){
                //alert('error');
                return false;
            } else {
                return false;
            }
        });
    });
};



//recording
//webkitURL is deprecated but nevertheless
URL = window.URL || window.webkitURL;
var gumStream;
//stream from getUserMedia()
var rec;
//Recorder.js object
var input;
//MediaStreamAudioSourceNode we'll be recording
// shim for AudioContext when it's not avb.
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext;
//new audio context to help us record
var recordButton = document.getElementById("recordButton");
var stopButton = document.getElementById("stopButton");
//add events to those 3 buttons
recordButton.addEventListener("click", startRecording);
stopButton.addEventListener("click", stopRecording);

function startRecording() {
	console.log("recordButton clicked");
	/* Simple constraints object, for more advanced audio features see

	https://addpipe.com/blog/audio-constraints-getusermedia/ */

	var constraints = {
		audio: true,
		video: false
	}
	/* Disable the record button until we get a success or fail from getUserMedia() */

	recordButton.disabled = true;
	stopButton.disabled = false;

	/* We're using the standard promise based getUserMedia()

	https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia */

	navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
		console.log("getUserMedia() success, stream created, initializing Recorder.js ...");
		/* assign to gumStream for later use */
		gumStream = stream;
		/* use the stream */
		input = audioContext.createMediaStreamSource(stream);
		/* Create the Recorder object and configure to record mono sound (1 channel) Recording 2 channels will double the file size */
		rec = new Recorder(input, {
			numChannels: 1
		})
		//start the recording process
		rec.record()
		console.log("Recording started");
	}).catch(function(err) {
		//enable the record button if getUserMedia() fails
		recordButton.disabled = false;
		stopButton.disabled = true;
	});
}

function stopRecording() {
	console.log("stopButton clicked");
	//disable the stop button, enable the record too allow for new recordings
	stopButton.disabled = true;
	recordButton.disabled = false;
	pauseButton.disabled = true;
	//reset button just in case the recording is stopped while paused
	pauseButton.innerHTML = "Pause";
	//tell the recorder to stop the recording
	rec.stop(); //stop microphone access
	gumStream.getAudioTracks()[0].stop();
	//create the wav blob and pass it on to createDownloadLink
	rec.exportWAV(createDownloadLink);
}

function createDownloadLink(blob) {
	var url = URL.createObjectURL(blob);
	var au = document.createElement('audio');
	var li = document.createElement('li');
	var link = document.createElement('a');
	//add controls to the <audio> element
	au.controls = true;
	au.src = url;
	//link the a element to the blob
	link.href = url;
	link.download = new Date().toISOString() + '.wav';
	link.innerHTML = link.download;
	//add the new audio and a elements to the li element
	li.appendChild(au);
	li.appendChild(link);
	//add the li element to the ordered list
	var filename = new Date().toISOString();
	//filename to send to server without extension
	//upload link
	var upload = document.createElement('a');
	upload.href = "#";
	upload.innerHTML = "Upload";
	upload.addEventListener("click", function(event) {
		var xhr = new XMLHttpRequest();
		xhr.onload = function(e) {
			if (this.readyState === 4) {
				console.log("Server returned: ", e.target.responseText);
			}
		};
		var fd = new FormData();
		fd.append("audio_data", blob, filename);
		xhr.open("POST", "upload.php", true);
		xhr.send(fd);
	})
	li.appendChild(document.createTextNode(" ")) //add a space in between
	li.appendChild(upload) //add the upload link to li
	recordingsList.appendChild(li);
}

