/**
 * @package The All Seeing Eye - Lightning Strike Displayer
 * @version 1.0
 * @author Benjamin Sinke
 */

 var plottedStrikes = [];

 function getStrikeCountAjax() {
     $.ajax({
        url: '/strikedata/index.php',
        type: "GET",
        data: {loadData: 1, method: 'getCount'},
        dataType: "JSON",
        success: function(e) {

            if(e.count > window.strikeCount) {

                if(window.allowSound) {
                    $(".audiomsg source").prop("src", "https://www.onweer-online.nl/audio/strikeBleep.mp3");
                    $(".audiomsg").find("audio").load();
                    $(".audiomsg").find("audio")[0].play();
                }

                $(".oo-top-bar .oo-top-bar-inner .oo-top-bar-user.tstorm-counter span small").effect("shake", {
                    times: 2,
                    distance: 3
                });

            }

            window.strikeCount = e.count;
            $(".oo-top-bar .oo-top-bar-inner .oo-top-bar-user.tstorm-counter span small").html(e.count);
            $(".oo-top-bar .oo-top-bar-inner .oo-top-bar-user.tstorm-counter a").css('text-indent', ($(".oo-top-bar .oo-top-bar-inner .oo-top-bar-user.tstorm-counter span small").width())+'px');
        }
    });
 }

 function getStrikeAjax() {
     var _allowStrikeLoad = false;

     var _northEast = {
         lat: 0,
         lng: 0
     };

     var _southWest = {
         lat: 0,
         lng: 0
     }

     if(typeof window.stMap != 'undefined') {
         var _viewPortBounds = window.stMap.getBounds();

         if(_viewPortBounds) {
             var _northEast = _viewPortBounds.getNorthEast();
             var _southWest = _viewPortBounds.getSouthWest();

             _allowStrikeLoad = true;
         }
     }

	 $.ajax({
        url: '/strikedata/index.php',
        type: "GET",
        data: {loadData: 1, latSW: _southWest.lat, lngSW: _southWest.lng, latNE: _northEast.lat, lngNE: _northEast.lng, allowStrikes: _allowStrikeLoad},
        dataType: "JSON",
        success: function(e) {

            /**
	         * Strikes
             */

            var strikeImages = [
	          '/images/strike_age_0.png?r=2',
	          '/images/strike_age_1.png?r=2',
	          '/images/strike_age_2.png?r=2',
              '/images/strike_age_3.png?r=2', //Gogo gadget langere strikedata mofos.
              '/images/strike_age_4.png?r=2', //Gogo gadget langere strikedata mofos.
            ];

            var strikeOpacities = [
                1,
                0.9,
                0.7,
                0.3,
                0.2
            ];

            var strikeZs = [
                99999,
                9999,
                999,
                99,
                9
            ];


            var strikeAnimations = [
                null, //google.maps.Animation.DROP,
                null,
                null,
                null,
                null
            ];

            /**
             * Live ticker
             */

            $.each(e.livefeed, function(index, o) {
	            if(!$('[data-notificationid="'+o.id+'"]').length) {

		            $('<div class="notification icon icon-'+o.icon+'" data-notificationid="'+o.id+'"><p>'+o.notification+'</p><small>'+o.time+'</small></div>').insertBefore('[data-notificationid]:first');
		            $('[data-notificationid="'+o.id+'"]').effect("pulsate", {times: 5}, 3000);

		            if(window.allowSound && $('[data-notificationid]').length) {
		                $(".audiomsg source").prop("src", "https://www.onweer-online.nl/audio/newNotification.mp3");
		                $(".audiomsg").find("audio").load();
		                $(".audiomsg").find("audio")[0].play();
	                }
	            }

            });

            $.each(plottedStrikes, function(e, strike) {
	            if(strike) {
	           		strike.setMap(null);
	            }
            });

            if(!$('.liveticker.cutoff [data-notificationid]').length) {
                if(!$('.liveticker.cutoff .no-notifications').length) {
                    $('.liveticker.cutoff').append('<p class="no-notifications"><strong>Up to date!</strong> Er zijn geen nieuwe notificaties voor je :)</p>');
                }
            } else {
                $('.liveticker.cutoff .no-notifications').remove();
            }

            plottedStrikes = [];
            var heatMapStrikes = [];

            if($('html').find('.st-container').is(':visible')) {
                $.each(e.strikes, function(_age, strikes) {
    	            $.each(strikes, function(i, bolt) {
    		            var strikeIcon = new google.maps.MarkerImage(strikeImages[_age], new google.maps.Size(12, 12), new google.maps.Point(0, 0), new google.maps.Point(6, 6));

                        //heatMapStrikes.push(new google.maps.LatLng(parseFloat(bolt.latitude), parseFloat(bolt.longitude)));
    				    var pPos = new google.maps.LatLng(parseFloat(bolt.latitude), parseFloat(bolt.longitude));
      					var marker = new google.maps.Marker({
      						position: pPos,
      						map: window.stMap,
      						icon: strikeIcon,
                            opacity: strikeOpacities[_age],
                            zIndex: strikeZs[_age],
                            animation: strikeAnimations[_age]
      					});

                        plottedStrikes.push(marker);

    	            });
                });
            }

        }
    });


 }

 $(document).ready(function() {
	 /**
	  * Force data reload for each user, only once per session.
	  */

	 if(Cookies.get('allowrefresh') === "true" || !Cookies.get('allowrefresh')) {
		// $.ajax({
	    //     url: 'https://www.onweer-online.nl/lib/theAllSeeingEye.class.php',
	    //     type: 'GET',
	    //     data: {'forcemode':1},
	    //     success: function() {}
        // });

        Cookies.set('allowrefresh', 'false');
	 }


	 window.allowSound = true;
	 var fromCookie = Cookies.get('allowsound');

	 if(fromCookie === "false") {
		window.allowSound = false;
		$('.sound').addClass('soundoff').removeClass('soundon');
	 }

	 if($('[data-theallseeingeye]').length) {
         getStrikeAjax();
         
		 setInterval(function() {

	        getStrikeAjax();

        }, $('[data-theallseeingeye]').attr('data-tase-interval') * 20);

	 }

     if($('[data-theallseeingeye]').length) {
		 setInterval(function() {
	        getStrikeCountAjax();
        }, ((1000 * 60) * 5));

	 }

	 function turnOnSound() {
		 window.allowSound = true;
		 Cookies.set('allowsound', 'true', { expires: 365 });
	 }

	 function turnOffSound() {
		 window.allowSound = false;
		 Cookies.set('allowsound', 'false', { expires: 365 });
	 }

	 $('.sound').click(function() {
		if($(this).hasClass('soundon')) {
			$(this).addClass('soundoff').removeClass('soundon');
			turnOffSound();
		}
		else {
			$(this).addClass('soundon').removeClass('soundoff');
			turnOnSound();
		}
	 });

	 $('.info').click(function() {
		$('.oo-top-bar-info').css('left', ($('.info').offset().left -160)+'px').fadeToggle('fast');
	 });

	 $('.country').click(function() {
		$('.oo-top-bar-country').css('left', ($('.country').offset().left -93)+'px').fadeToggle('fast');
	 });

	 $('.oo-top-bar-user.loggedin a').click(function(e) {
		 e.preventDefault();
		 $('.oo-top-bar-profile-controls').css('left', ($('.oo-top-bar-user.loggedin').offset().left)+'px').fadeToggle('fast');
	 });

	 $('.toggle-more-notifications').click(function() {

		$('.block_content.dark_body.liveticker').toggleClass('cutoff');
		if(!$('.cutoff').length) {
			$(this).text('Laat minder zien');
		} else {
			$(this).text('Laat meer zien');
		}

	 });
});
