/**
 * DealerLocatorAdv.js
 * Controller for search in google map
 */
petzl.controllers.map = function(centerLat, centerLong, markerImgBasePath, mapZoom)
{
	window.thePetzlMap = this;
	var mapOptions = {
		center: new google.maps.LatLng(centerLat, centerLong),
		zoom: mapZoom ? mapZoom : 12,
		panControl: false,
		zoomControl: true,
		scaleControl: false,
		streetViewControl: false,
		overviewMapControl: false,
		mapTypeControl: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	var theMap = new google.maps.Map(document.getElementById("map"), mapOptions);
	
	this.getZoom = function() {
		return theMap.getZoom();
	}
	
	this.setZoom = function(zoom) {
		theMap.setZoom(zoom);
	}
	
	var infobulle = null;
	
	this.closeInfoBulle = function() {
		if(infobulle) {
			infobulle.close();
		}
	}
	/**
	 * INIT MARKERS
	 */
	var markers =[];
	
	this.clearMap = function() { 
		if(markers.length > 0) {
			for(var x = 0; x < markers.length; x++) {
				markers[x].setMap(null);
			}
			markers = [];
		}	
	}
	
	
	this.showDealers = function(zoom) {
	
		if(zoom) theMap.setZoom(zoom);
		
		if(markers.length > 0) {
			for(var x = 0; x < markers.length; x++) {
				markers[x].setMap(null);
			}
			markers = [];
		}
		//var infobulle = null;
		
		// Pour chaque dealer
		$('.dealerLists .dealer').each(function(dIndex, oneDealer){

			//var store 		= JSON.parse($(this).attr("data-value"));
			var store 		= JSON.parse($(oneDealer).attr("data-value"));
			var markersType = ['expert', 'revendeur', 'distributeur'];
			
			var markerPath;
			var zIndex;
			if($(this).attr("class").search(/Expert/ig) >= 0) {
				if($('.MarketPro').size() === 1)
					markerPath = markerImgBasePath + "/static/img/picto-expert-yellow.png";
				else
					markerPath = markerImgBasePath + "/static/img/picto-expert.png";
				
				zIndex = 3;
			}
			else if($(this).attr("class").search(/distributor/ig) >= 0) {
				markerPath = markerImgBasePath + "/static/img/picto-distributeur.png";
				zIndex = 2;
			}
			else {
				markerPath = markerImgBasePath + "/static/img/picto-revendeur.png";
				zIndex = 1;
			}
			
			// On cr�e un marker
			//icon : markerImgBasePath + '/picto-'+ markersType + '.png',
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(store.Geocode__latitude__s, store.Geocode__longitude__s),
				map     : theMap,
				icon    : markerPath,
				zIndex	: zIndex,
				title   : store.Name,
				store   : store	
			});

			// On l'ajoute � la map
			//marker.setMap(theMap);

			// On l'ajoute aux markers
			markers.push(marker);

			// On bind l'info window au marker
			google.maps.event.addListener(marker, 'click', function() {

				var index = markers.indexOf(marker);
				//var lat = markers[index].position.k + 0.008;
				//var lng = markers[index].position.D;
				var lat = markers[index].position.lat() + 0.008;
				var lng = markers[index].position.lng();

				// On center la map sur le point
				//map.setCenter(new google.maps.LatLng(lat + 0.01, lng));
				theMap.setCenter(new google.maps.LatLng(lat, lng));
		
				// On ouvre l'infobulle
				if(infobulle) {
					infobulle.close();	
				}
				
				infobulle = window.infobulle = buildInfoBubble(marker);
				infobulle.open(theMap,marker);
			
			});

			google.maps.event.addListener(theMap, "click", function () { 
				if(infobulle) {
					infobulle.close();
				}
			});

			// Au click sur une croix de popin
			$('.hitArea').click(function(){
				infobulle.close();
			});
		});
	
		// Au click sur un dealer
		$('.dealerLists .dealer').click(function(){

			// On r�cup�re l'index de celui ci
			var index =  parseInt($(this).index()) + ( (parseInt($("#currentPage").html()) - 1) * 5 );
			// On center la map sur le point
			//theMap.setCenter(new google.maps.LatLng(markers[index].position.k + 0.018, markers[index].position.D ));
			theMap.setCenter(new google.maps.LatLng(markers[index].position.lat() + 0.018, markers[index].position.lng()));
			
			// On ouvre l'infobulle associ�e
			if(null != infobulle)
				infobulle.close();
				
			infobulle = window.infobulle = buildInfoBubble(markers[index]);	
			infobulle.open(theMap, markers[index]);
			
			
			//for google analitic
			var var_retailer_name = 'Adrenaline';

		});
		
		$("#resultSize").html($('.dealerLists .dealer').length);
		
		function buildInfoBubble(marker) {
			var sitedomain = $("#sitedomain_b2c").attr("href");
			var url = 'https://maps.google.com/maps?z=25&t=s&daddr=' + marker.store.Street__c + ',' + marker.store.City__c + ',' + marker.store.Zipcode__c;// +'&saddr=' + mylocation;
			
			// Nurit edit 17/12/15 - adding condition to the img attribute and adding div
			var contenHtml =
			'<div class="infoWindow"><div class="close" onclick="window.thePetzlMap.closeInfoBulle()"></div>';
			if(marker.store.Storefront__c){
				contenHtml += '<img src="' + sitedomain + '' + marker.store.Storefront__c +'" />';
			}
			contenHtml += '<p class="dealerName">' + (marker.store.Name || '') + '</p>'+
			'<p >'+ (marker.store.Street__c || '') + '</p>' + 
			'<p style="margin-top: 0px;">' + (marker.store.Zipcode__c || '') + ' ' +
			(marker.store.City__c||'') + ' - ' + (marker.store.Country__rName||'') +
			'</p>'+
			'<p>';// 
			if(marker.store.Phone__c)
				contenHtml += marker.store.Phone__c;
			if(marker.store.Website__c) {
				// Removed _Blank!!!!!!!!!
				contenHtml += '<br/>' + '<a href="' + marker.store.Website__c + '"' + ' html-data="' + marker.store.Name +'"' +
							  ' onclick = "googleStat(this)" >' + 
							  marker.store.Website__c + '</a><br/>';
			}
			if(marker.store.Email__c) {
				contenHtml += '<br/>' + '<a href="mailto:' + marker.store.Email__c + '">' + marker.store.Email__c + '</a><br/>';
			}
			if(!contenHtml.endsWith('<br/>'))
			{
				contenHtml += '<br/>';
			}
			contenHtml += '<a href="' + url + '">' + $('#voir_sur_google_map').html().trim()  +'</a><br/>'+
			'</p></div>';
			
			//console.log("contenHtml >> " + contenHtml);
			
			var ib = new InfoBubble({
						map: theMap,
						content: contenHtml,  // Contenu de l'infobulle
						//position: event.latLng,  // Coordonn�es latitude longitude du marker
						shadowStyle: 0,  // Style de l'ombre de l'infobulle (0, 1 ou 2)
						padding: 0,  // Marge interne de l'infobulle (en px)
						backgroundColor: 'rgb(255,255,255)',  // Couleur de fond de l'infobulle
						borderRadius: 0, // Angle d'arrondis de la bordure
						arrowSize: 10, // Taille du pointeur sous l'infobulle
						disableAutoPan: true, // D�sactiver l'adaptation automatique de l'infobulle
						hideCloseButton: false, // Cacher le bouton 'Fermer'
						arrowPosition: 50,  // Position du pointeur de l'infobulle (en %)
						arrowStyle: 0,  // Type de pointeur (0, 1 ou 2)
						disableAnimation: false,  // D�activer l'animation � l'ouverture de l'infobulle
						maxWidth :   275,  // Largeur minimum de l'infobulle  (en px)
						minWidth :   270
					});
			
			// Nurit edit 17/12/15 			
			

			return ib;
		}
	}//showDealers
	
	google.maps.event.addListenerOnce(theMap, 'idle', function() {
		
		var params = null;
		
		
		google.maps.event.addListener(theMap, 'bounds_changed', function() {
				
			params =  {
				mode 		: "map_changed"
			   ,bounds		: theMap.getBounds()	
			   ,zoom		: theMap.getZoom()
			   ,country		: (markers && markers.length > 0) ? markers[0].store.Country__rCountry_Code__c : $(".countryNameFromServer").html()
			};
		});
		
		google.maps.event.addListener(theMap, 'dragend', function() {
			onSearchDealer(params);
		});
	
		google.maps.event.addListener(theMap, 'zoom_changed', function() {
			
			var zcParams =  {
				mode 		: "map_changed"
			   ,bounds		: theMap.getBounds()	
			   ,zoom		: theMap.getZoom()
			   ,country		: (markers && markers.length > 0) ? markers[0].store.Country__rCountry_Code__c : $(".countryNameFromServer").html()
			};
			onSearchDealer(zcParams);
		});
			
	});	
	
	this.showDealers();
}//end of map 

var clickOnMyLocal = false;	
petzl.controllers.DealerLocator = function ()
{

	var ClassicSlideshow = petzl.views.ClassicSlideshow;

	var currentIndex = 0;

	var selectDefaultValue = $('#defaultValue').html();
	

	function init(){

		$('#nbPage').html($('.dealerPage').length);
		
		if($('.dealerPage').length <= 1) {
			$(".possible").removeClass("possible");
		}
		
		if($('.dealerPage').length < 1) {
			$('#currentPage').html('0');		
		}

		// On initialise le slideshow et les thumbs
		var slideshow = new ClassicSlideshow('.dealerListContainer', {
			autoStart: false,
			index: 1,
			duration: 4000,
			opacityAnimation : false,
			transitionDuration: 500,
			selectStrict : true
		});

		resizeDealers();

		$(window).resize(function(){
			resizeDealers();
		});

		$("#searchAddress").unbind("click").click(function(){ 
			onSearchDealer({ mode : 'search' });
		});	
		
		$("#locateAddress").unbind("click").click(function(){
			onSearchDealer({ mode : 'current_position' });
			clickOnMyLocal = true;
		});
		
		var theAddressInput = $("#addressInput");
		
		theAddressInput.unbind("keypress").keypress(function(e){
			if(e.keyCode==13){
				onSearchDealer({ mode : 'search' });
			}
		});
		
		/*AEF: set country after geolocation
		var currentEntry = theAddressInput.val();
		var countryNameFromServer = $(".countryNameFromServer").html();
		if(!currentEntry && countryNameFromServer)
           theAddressInput.val(countryNameFromServer);
		*/
		
		// Quand on revient sur la page pr�c�dente
		$('.dealerPageLeft').click(function(){
			// Previous
			slideshow.prev();

			// On update l'index courant
			currentIndex = (currentIndex >= 1) ? currentIndex-1 : currentIndex;

			// On update la navigation
			updateCurrentPageNav();
		});

		// Quand va sur la page suivant
		$('.dealerPageRight').click(function(){
			// Next
			slideshow.next();

			// On update l'index courant
			currentIndex = (currentIndex < $('.dealerPage').length-1) ? currentIndex+1 : currentIndex;

			// On update la navigation
			updateCurrentPageNav();
		});

		// Click sur le body pour fermer
		$('body').click(function(){
			// Pour chaque select
			$('.select').each(function(){
				// S'il est ouvert
				if($(this).hasClass('opened')){
					// On le toggle (et donc le ferme)
					toggleSelect($(this));
				}
			});
		});
		
		// Click sur un select
		$('.select').bind('click', function(event){
			selectClickHandler(event, $(this))
		});
		
		// Click sur un des choix du du select 
		$('.select .selectChoices span').click(function(event){
			if(event.preventDefault) event.preventDefault();
			if(event.stopPropagation) event.stopPropagation();
			event.returnValue = false;

			var select = $(this).parents('.select');
			var selectChoices = $(this).parents('.selectChoices');

			// On r�cup�re les les valeurs � afficher/changer
			var affichage = $(this).html();
			var value = $(this).data('value');
			

			// On change/affiche les valeurs
			select.find('input').val(value);
			select.find('.currentChoice').html(affichage);
			
			
			//ADD BY MY 18.6.2015 -ADDING DATA ID OF THE TYPE OR ACTIVITY
			var idVal = $(this).attr('data-id');
			select.find('.currentChoice').attr('data-id',idVal);
			var nameVal = $(this).attr('data-name');
			select.find('.currentChoice').attr('data-name',nameVal);

			// On referme le select
			selectChoices.css('display', 'none');
			select.removeClass('opened');

			select.addClass('selected');
			select.unbind('click');
			//google analitic
			//ga("send", "event", "dealerlocator", "select_filter", affichage.trim());
			_gaq.push(['_trackEvent', 'dealerlocator', 'select_filter', affichage.trim()]);
			return false;
		});

		$('.crossSelect').click(function(event){

			var select = $(this).parents('.select');

			// On vire le gris 
			select.removeClass('selected');

			// On vide ce qui a �t� s�lectionn�
			select.find('input').val(selectDefaultValue);
			select.find('.currentChoice').html(selectDefaultValue);
			
			//ADD BY MY 18.6.2015 -ADDING DATA ID OF THE TYPE OR ACTIVITY
			select.find('.currentChoice').removeAttr('data-id');
			select.find('.currentChoice').removeAttr('data-name');


			// Click sur un select
			select.bind('click', function(event){
				selectClickHandler(event, select)
			});

			if(event.preventDefault) event.preventDefault();
			if(event.stopPropagation) event.stopPropagation();
			event.returnValue = false;
			return false;

		});

		//if($('#map').length > 0){
		//	map();
		//}
	}

	function resizeDealers(){
		$('.dealer').css('width', $('.dealerListContainer').width());
	}

	function selectClickHandler(event, select){
		if(event.preventDefault) event.preventDefault();
			if(event.stopPropagation) event.stopPropagation();
			event.returnValue = false;


			// Pour chaque select
			$('.select').each(function(){
				// Si il est ouvert
				if(select.hasClass('opened')){
					// On le ferme
					toggleSelect(select);
				}
			});
			// On ouvre celui l�
			toggleSelect(select);

			
	}

	function updateCurrentPageNav(){

		// On update la page actuelle
		$('#currentPage').html(currentIndex+1);

		// On vire les classes possible
		$('.dealerPageChangeIcon').removeClass('possible');

		// Si on est pas sur la premi�re
		if(currentIndex != 0){
			// On peut cliquer pour revenir � la page pr�c�dente
			$('.dealerPageLeft .dealerPageChangeIcon').addClass('possible');

		// Si on est pas sur la derni�re page
		}
		if(currentIndex != $('.dealerPage').length-1){
			// On peut cliquer pour aller � la page pr�c�dente
			$('.dealerPageRight .dealerPageChangeIcon').addClass('possible');
		}
	}
	
	/*** here was map***/
	
	// Ouverture/Fermeture du select
	function toggleSelect(elem) {
		// On r�cup�re la visibilit� du biniou
		var visibility = (elem.find('.selectChoices').css('display') == 'block') ? 'none' : 'block';

		// On toggle sa visbilit�
		elem.find('.selectChoices').css('display', visibility);
		elem.toggleClass('opened');
	}
	
	/**
	 * Initialisation
	 */
	init();
	// OneTrust
	window.initGmaps = function () {
    	console.log("DealerLocator - initGmaps");
    	// Run search on current position
    	// after google map api is loaded
        onSearchDealer({ mode : 'current_position' });    	
    	if ($('#map').length > 0) {
        	map();
    	}
	};	
};
/*
	AEF:22/06/2015
*/
function onSearchDealer(params) {

	// OneTrust:
	// avoid "Uncaught ReferenceError: google is not defined" error
	// due asynch loading of google ma api.
	// Can't call this function before google is loaded.
	if (!window.google) return;

	var addressInput = $("#addressInput").val();
	var filter = $('.currentChoice').attr('data-name');
	var typeFilter = ''
	var activityFilter = '';
	
	if('activity' === filter) {
		activityFilter = $('.currentChoice').attr('data-id');
	}
	else if('type' === filter) {
		typeFilter = $('.currentChoice').attr('data-id');
	}		

	//AEF: request to google map to get location of entry address
	if("current_position" == params.mode) {
		$("#addressInput").val("");
		navigator.geolocation.getCurrentPosition(
					function(position) { //get current position
													
						/*position = {
							coords : {
								latitude  : 45.27202 
								,longitude : 5.88303
							}
							
						};*/							
													
						var geocoder = new google.maps.Geocoder();
						var latlng   = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
						
						//get country
						geocoder.geocode({'latLng': latlng}, function(results, status) {
							
							//console.log(" result >> ", JSON.stringify(results));
							var countryCode = (status == google.maps.GeocoderStatus.OK) ? getCountryFromResult(results) : null;
							console.log("countryCode >> " + countryCode);
							searchDealer(position.coords.latitude
										,position.coords.longitude
										,typeFilter
										,activityFilter
										,25
										,countryCode
										,"current_position");
						});
					},
					function(err) 
					{
						var errMsg = "Current Position Error >> " + err.message;
						if(clickOnMyLocal)
						{
							$("#errorBlock").show();
							$("#defualtMsg").hide();
							clickOnMyLocal = false;
						}
							

						//$("#errorBlock").html(err.message);
						
						if(console.warn) {
							console.warn(errMsg);
						}
					}					
		);
	}
	else if("search" == params.mode){
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode( { 'address': addressInput }, function(results, status) { 	
			//console.log("onSearchDealer >> " + JSON.stringify(results[0]));
			if (status == google.maps.GeocoderStatus.OK) {
				searchDealer(results[0].geometry.location.lat()
							,results[0].geometry.location.lng()
							,typeFilter
							,activityFilter
							,25
							//,results[0].address_components[results[0].address_components.length-1].short_name
							,getCountryFromResult(results)
							,"search");
			} else {
				noResult();//'','','','','','',
			}
		});
	}
	else if("map_changed" == params.mode) {
		
		window.thePetzlMap.clearMap();
		
		if(params.country) {
			changeMap(params.bounds.getCenter().lat()
					, params.bounds.getCenter().lng()
					, params.bounds.getSouthWest().lat()
					, params.bounds.getSouthWest().lng()
					, params.bounds.getNorthEast().lat()
					, params.bounds.getNorthEast().lng()
					, typeFilter
					, activityFilter
					, params.country
					, "map_changed");
		} else {
			var geocoder = new google.maps.Geocoder();
			geocoder.geocode( { 'address': addressInput }, function(results, status) { 
				if (status == google.maps.GeocoderStatus.OK) {
					changeMap( params.bounds.getCenter().lat()					
							  ,params.bounds.getCenter().lng()
							  ,params.bounds.getSouthWest().lat()
							  ,params.bounds.getSouthWest().lng()
							  ,params.bounds.getNorthEast().lat()
							  ,params.bounds.getNorthEast().lng()
							  ,typeFilter
							  ,activityFilter
							  //,results[0].address_components[results[0].address_components.length - 1].short_name
							  ,getCountryFromResult(results)
							  ,"map_changed");
				}
			});
		}
	}
}

function onChangeMapComplete() {
	//console.log("onChangeMapComplete");
	new petzl.controllers.DealerLocator();
	window.thePetzlMap.showDealers();
}

function googleStat(obj) {
	var fName = obj.getAttribute("html-data");
	//ga("send", "event","dealerlocator", "click_retailer",fName);
	_gaq.push(['_trackEvent', 'dealerlocator', 'click_retailer', fName]);
}

function getCountryFromResult(results) {
	
	//return results[0].address_components[results[0].address_components.length - 1].short_name;
	var address_components = results[0].address_components;
	for(var x = 0; x < address_components.length; x++) {
		if(address_components[x].types.indexOf("country") >= 0) {
			return address_components[x].short_name;
		}		
	}
	return null;
}	