/*------------------------------------------------
* APP MAIN FUNCTION
------------------------------------------------*/
(function($) {
	$(document).ready(function() {

		/*------------------------------------------------
		* MAP DES RÉSLISATIONS
		------------------------------------------------*/
		(function(){
			if (typeof locations !== 'undefined') {
				//https://mapbuildr.com/buildr
			  google.maps.event.addDomListener(window, 'load', init);
			  var map;


			  function showRealisation(marker){
					if($(window).width() < 768){
						$(marker.id).css('top', ($(window).scrollTop() + 16) + 'px');
					}
					$('.overlay').show();
					$(marker.id).fadeIn(1000);
			  }



			  $('.overlay, .close-realisation').on('click', function(){
			    closeRealisation();
			  });


			  function init() {
			    var customZoom = $(document).width() > 767 ? 8 : 5;
			    var mapOptions = {
			      center: new google.maps.LatLng(45.983683, -72.681607),
			      zoom: customZoom,
			      zoomControl: true,
			      zoomControlOptions: {
			        style: google.maps.ZoomControlStyle.DEFAULT,
			      },
			      disableDoubleClickZoom: true,
			      mapTypeControl: false,
			      scaleControl: true,
			      scrollwheel: false,
			      panControl: true,
			      streetViewControl: false,
			      draggable : /*isDraggable*/ true,
			      overviewMapControl: true,
			      overviewMapControlOptions: {
			        opened: false,
			      },
			      mapTypeId: google.maps.MapTypeId.ROADMAP,
			      styles: [ { "featureType": "landscape", "elementType": "labels", "stylers": [ { "visibility": "off" } ] },{ "featureType": "transit", "elementType": "labels", "stylers": [ { "visibility": "off" } ] },{ "featureType": "poi", "elementType": "labels", "stylers": [ { "visibility": "off" } ] },{ "featureType": "water", "elementType": "labels", "stylers": [ { "visibility": "off" } ] },{ "featureType": "road", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] },{ "stylers": [ { "hue": "#00aaff" }, { "saturation": -100 }, { "gamma": 2.15 }, { "lightness": 12 } ] },{ "featureType": "road", "elementType": "labels.text.fill", "stylers": [ { "visibility": "on" }, { "lightness": 24 } ] },{ "featureType": "road", "elementType": "geometry", "stylers": [ { "lightness": 57 } ] } ],
			    }
			    var mapElement = document.getElementById('realisations-map');
			    var map = new google.maps.Map(mapElement, mapOptions);


			    for (i = 0; i < locations.length; i++) {
			      if (locations[i][1] =='undefined'){ description ='';} else { description = locations[i][1];}
			      if (locations[i][2] =='undefined'){ telephone ='';} else { telephone = locations[i][2];}
			      if (locations[i][3] =='undefined'){ email ='';} else { email = locations[i][3];}
			      if (locations[i][4] =='undefined'){ web ='';} else { web = locations[i][4];}
			      if (locations[i][7] =='undefined'){ markericon ='';} else { markericon = locations[i][7];}
			      marker = new google.maps.Marker({
			        icon: markericon,
			        position: new google.maps.LatLng(locations[i][5], locations[i][6]),
			        map: map,
			        title: locations[i][0],
			        desc: description,
			        tel: telephone,
			        email: email,
			        web: web,
			        id: locations[i][8]
			      });
			      link = '';            bindInfoWindow(marker, map, locations[i][0], description, telephone, email, web, link);
			    }
			    function bindInfoWindow(marker, map, title, desc, telephone, email, web, link) {
			      var infoWindowVisible = (function () {
			        var currentlyVisible = false;
			        return function (visible) {
			          if (visible !== undefined) {
			            currentlyVisible = visible;
			          }
			          return currentlyVisible;
			        };
			      }());
			      iw = new google.maps.InfoWindow();
			      google.maps.event.addListener(marker, 'click', function() {
			        if (infoWindowVisible()) {
			          iw.close();
			          infoWindowVisible(false);
			        } else {
			          showRealisation(marker);
			        }
			      });
			      google.maps.event.addListener(iw, 'closeclick', function () {
			        infoWindowVisible(false);
			      });
			    }
			  }
			}
		})();

		/*------------------------------------------------
		* TEST IF JAVASCRIPT IS ACTIVATED
		------------------------------------------------*/
		$('html').removeClass('no-js').addClass('js');

		/*------------------------------------------------
		* CHECK MOBILE
		------------------------------------------------*/
		var $isMobile = $('.is-mobile').length > 0;
		var	$isTablet = $('.is-tablet').length > 0;

		/*------------------------------------------------
		* ANIMATIONS
		------------------------------------------------*/
		if(!$isMobile && !$isTablet){
			new WOW().init();
		}

		//Caroussel de l'accueil
		$('.flexslider').flexslider({
			animation: "slide",
			animationLoop: true,
			itemWidth: 451,
			itemMargin: 0,
			move: 1,
			slideshow: false,
			controlNav: false,
			minItems: 1,
			maxItems: 4,
			prevText: "",
			nextText: "",
		});

		/*------------------------------------------------
		* FILTRES DES PRODUITS
		------------------------------------------------*/
		$('#product-list').on('click', '.produit-filter-btn', function(){
			var that = $(this);
			$('.produit-col:not('+$(this).data('target')+')').hide();
			$(that.data('target')).fadeIn(1000);
			$('.produit-filter-btn').removeClass('active');
			that.addClass('active');
		});

		/*------------------------------------------------
		* Réalisations items
		------------------------------------------------*/
		function showRealisationPopup(selector){
			if($(window).width() < 768){
				$(selector).css('top', ($(window).scrollTop() + 16) + 'px');
			}
			$(selector).fadeIn('fast');
			$('.overlay').fadeIn('fast');
			//console.log($(window).width(), $(window).scrollTop());
		}

		function closeRealisation(){
			$('.realisation-popup').fadeOut(500);
			$('.overlay').fadeOut(1000);
		}

		$( "#realisations-list, #realisations-caroussel" ).on('click', '.realistion-item', function(){
			showRealisationPopup($(this).data('target'));
		});

		$('.overlay, .close-realisation').on('click', function(){
			closeRealisation();
		});

		/*------------------------------------------------
		* Produits des Réalisations
		------------------------------------------------*/
		$('.realisations-related-products-link').on('click', function(e){
			e.preventDefault();
			$that = $(this);
			$.post( "/liste-produits/"+jsLangGetArg, {'ids': $(this).data('ids')} , function( data ) {
				$( "#product-list" ).append( data );
			});

			$( "#product-list" ).html('');
			$( "#product-list" ).prepend('<div class="col-1"><h2 class="produit-filtered-title">' + productUsedForText + ' : ' + $that.data('name') + '</h2></div>');
			$('.realisation-popup, .overlay').fadeOut('slow', function(){
				$('html, body').stop().animate({
					scrollTop: $("#product-list").offset().top
				}, 1000);
			});
		});

		$( "#product-list" ).on('click', '#btn-show-all-products', function(){
			console.log('test');
			$.post( "/liste-produits/"+jsLangGetArg, function( data ) {
				$( "#product-list" ).html( data );
			});
		});



		/*------------------------------------------------
		* Réalisations par produits
		------------------------------------------------*/
		var realisationTitleInitialText = $('#realisations-title').text();
		$('#product-filter-box').on('change', function(){
			var realisationTitle = achievementsText + ': <em>' + $("#product-filter-box option:selected").text() + '</em>';
			if($(this).val() == ""){
				realisationTitle = realisationTitleInitialText;
			}

			$.post( "/liste-realisations/"+jsLangGetArg, {'id': $(this).val()} , function( data ) {
				$( "#realisations-list" ).html( data );
				$('#realisations-title').html(realisationTitle);
			});

		});

		$('#product-list').on('click', '.produit-realisations-link', function(e){
			e.preventDefault();
			$.post( "/liste-realisations/"+jsLangGetArg, {'id': $(this).data('id')} , function( data ) {
				$( "#realisations-list" ).html( data );
			});
			console.log($(this).data('noproduit'));
			$('#realisations-title').html(achievementsText + ': <em>' + $(this).data('name') + ' ('+ $(this).data('noproduit') +') </em>' ) ;
			$('#product-filter-box').val($(this).data('id'));
			$('html, body').stop().animate({
				scrollTop: $("#realistions-wrapper").offset().top
			}, 1000);
		});





		/*------------------------------------------------
		* RESPONSIVE VIDEOS
		------------------------------------------------*/
		$(".row").fitVids();

		var homeVid = $('#bgvid');


		if(homeVid.length){
			var volButton = $('#volume-button');
			var playButton = $('#play-button');

			if($isMobile || $isTablet){
				volButton.toggleClass('fa-volume-up');
				$('#bgvid').get(0).pause();
			} else{
				playButton.hide();
			}

			homeVid.on('click', function(){
				if(!homeVid.prop('paused')){
					playButton.fadeIn('slow');
					$('#bgvid').get(0).pause();
				}
			});

			playButton.on('click', function(){

				if(homeVid.prop('paused')){
					$('#bgvid').get(0).play();
					playButton.fadeOut('slow');
				} else{
					$('#bgvid').get(0).pause();
				}
			});

			volButton.on('click', function(){
				volButton.toggleClass('fa-volume-up');
				if(homeVid.prop('muted')){
					homeVid.prop('muted', false);
				} else{
					homeVid.prop('muted', true);
				}
			});
		}

		/*------------------------------------------------
		* RESPONSIVE NAV
		------------------------------------------------*/
		$(function(){
			$('#main-nav-list').slicknav({
				prependTo:'#mobile-nav'
			});
		});

		/*------------------------------------------------
		* ZOOMABLE IMAGES : TODO INCLUDE IN PAI (IMAGE) PATTERN
		------------------------------------------------*/
		$zoomedImages = $('.zoomable-image-link');
		if($zoomedImages){
			$zoomedImages.fancybox({
				helpers	: {
					title	: {
						type: 'inside'
					}
				},
				afterLoad: function(){
					this.title = $(this.element).find('img').attr('alt');
				}
			});
		}
		$('.zoom').fancybox();
		$('.zoom-frame').fancybox({
			'width'		: 570,
			'height'		: 800,
			'autoDimensions'    : false
		});

		/*------------------------------------------------
		* SLIDER
		------------------------------------------------*/
		(function(){
			var $cycler = $('.cycler');

			$cycler.each(function(){
				var $that = $(this);
				var go = function(commande){
					$that.cycle(commande);
					console.log($that);
				},
				$cycleNext = $that.parent().find('.cycle-next'),
				$cyclePrev =$that.parent().find('.cycle-prev')
				;
				$cycleNext.on('click', function(){
					go('next');
					go('pause');
				});
				$cyclePrev.on('click', function(){
					go('prev');
					go('pause');
				});
			});

			//Animations
			if($('.slide-text-container').length){
				animDefaults($('.slide').eq(0));
			}
			function setAnim($el, $anim){
				var $temp;
				if($el.length){
					$el.removeClass('animated');
					$el.removeClass($anim);
					$el.each(function(){
						$temp = $(this).height();
					});
					$el.addClass('animated ' + $anim);
				}
			}
			if($('.slide-text-container').length){
				$cycler.on('cycle-before', function(event, optionHash, outgoingSlideEl, incomingSlideEl, forwardFlag) {
					animDefaults(incomingSlideEl);
				});
			}
			function animDefaults(incomingSlideEl){
				setAnim($(incomingSlideEl).find('.slide-text-text'), 'zoomInLeft');
				setAnim($(incomingSlideEl).find('.slide-text-image'), 'zoomInRight');
			}
		})();

		/*------------------------------------------------
		* IMAGES GALLERY
		------------------------------------------------*/
		(function(){
			if($('.gallerie-list').length){
				var fancyLinks = $('.gallerie-list a');
				fancyLinks.fancybox({
					prevEffect		: 'none',
					nextEffect		: 'none',
					closeBtn		: true,
					helpers	: {
						title	: {
							type: 'inside'
						},
						thumbs	: {
							width	: 50,
							height	: 50
						}
					},
					afterLoad: function(){
						this.title = $(this.element).find('img').attr('alt');
					}
				});
			}
		}());

	});
})(jQuery);
