// http://www.lorealprofessionnel.fr/_fr/_fr/salon-locator/
// http://code.google.com/apis/maps/documentation/index.html
// http://code.google.com/apis/maps/documentation/reference.html
 
(function() {
    
    var countryCodeToName = {
        'en-AU': 'australia',
        'en-NZ': 'new-zealand',
		'es-CL': 'chile',
		'es-AR': 'argentina',
		'de-DE': 'germany',
		'de-AU': 'austria',
		'es-CO': 'colombia'
    };

    var W = this, D = W.document, map, clientGeocoder, wsStoreLocator, resultsNode;
    var markersMemory= [];
    var storesMemory= [];
    var nbResult;
	var curLatitude, curLongitude;
	var curItem;
	var fullAddress;
	var gAddress;
	box.ui('form').configure({webbox: true});
	/* temp var */
	var geocoder;
	var marker;
	var currentLatLn;
	var infowindow = null;

	var currZoom = 6;
	var phone="Phone:";
    // get the correct language code
    var lg = (D.documentElement || D.getElementsByTagName('html')[0]).lang, lcid;
    switch(lg) {
        case 'fr-FR':
            lcid = 1036;
            break;
		case 'it-IT':
            lcid = 1040;
			phone ="Tel:"; 
			country="italia";
         break;
		 case 'nl-BE':
            lcid = 2067;
			phone ="Phone:"; 
			country="belgium";
         break;
		case 'en-GB':
            lcid = 2057;			
            break;
		case 'en-AU':
            lcid = 3081;		
            break;	
		case 'es-ES':
            lcid = 3082;		
            break;		
		case 'es-CL':
            lcid = 13322;
            break;		
		case 'pt-BR':
            lcid = 1046;
			phone ="Telefone:";			
            break;
		case 'de-DE':
            lcid = 1031;
			phone ="Telefon:";	
            break;
        default:
            lcid = 1036;		
            break;
    }
    // create GMap
    box.dom(W).load(function() { 
	
		var latlng;
		
		if(lg=="it-IT"){
				currZoom = 6;
				latlng = new google.maps.LatLng(42.98857645832184, 13.53515625);
			}else if(lg=="en-AU"){
				currZoom = 3;
				latlng = new google.maps.LatLng(-25.2743980, 133.7751360);
				
			}else if(lg=="es-ES"){
				currZoom = 6;
				latlng = new google.maps.LatLng(40.896906, -3.669434);
				
			}else if(lg=="es-CL"){
				currZoom = 3;
				latlng = new google.maps.LatLng(-22.593726, -72.246094);
				
			}else if(lg=="pt-BR"){
				currZoom = 4;
				latlng = new google.maps.LatLng(-12.382928, -53.173828);
				
			}else if(lg=="nl-BE"){
				currZoom = 6;
				latlng = new google.maps.LatLng(51.599595,5.029907);
				
			}else if(lg=="de-DE"){
				currZoom = 6;
				latlng = new google.maps.LatLng(49.181703,12.019043);
				
			}else{
				currZoom = 6;
				latlng = new google.maps.LatLng(52.41582261237877, -5.20751953125);
				
			}

		var myOptions = {
		  zoom: currZoom,
		  center: latlng,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById("googleMap"),
			myOptions);

			
		infowindow = new google.maps.InfoWindow({
		content: "holding..."
		});
        
        
    });
    
    // add form validation
    box.dom(D).ready(function() {
		wsStoreLocator = MicrosoftFrance.MCS.Commerce.WS.AJAXProject.StoreLocatorWebService;
		resultsNode = box.dom('#results');
		
        // just for static tests, will be removed afterward
        box.ui('carousel').create({
            id: 'results',
            element: '#results',
            horizontal: true,
            display: 4,
            duration: 600,
            circular: true
        });
        
        box.ui('carousel.results').element.click(function(e) {
            e.preventDefault();
            // display map tooltip and activate
        });
        
        box.ui('form').create({
            element: '#searchForm',
            submit: 'div.actions a'
        }).addReplacement().mustValidate(function(form) {
			
            // form.field('address').mustValidate(function(field) {
            //     if(field.isEmpty() && !field.isEmpty()) {
            //         return l10n.errors.required.address;
            //     }
            // });
			
			form.field('city').mustValidate(function(field) {
				if(field.isEmpty()) {
					return l10n.errors.required.city;
				}
			});
		});
    });
	
	box.bind({
		'valid.form': function(e, domEvent) {	
			
			domEvent.preventDefault();
			var address = box.ui('form.searchForm').field('address').getValue();	
				
				if(address && !address.match(/[0-9]/)) address = "1 "+ address;	
				zipCode = box.ui('form.searchForm').field('zipCode').getValue();
				city = box.ui('form.searchForm').field('city').getValue();
				fullAddress = address + (zipCode ? ',' + zipCode : '') + ',' + city;
				if(box.ui('form.searchForm').field('country')){
					countryCode = box.ui('form.searchForm').field('country').getValue();
					fullAddress += countryCode;
				}
				
				gAddress = "";
				if(address) gAddress+=address;
				if(zipCode) gAddress+=(gAddress.length>0 ? ',' + zipCode : zipCode);
				if(city) gAddress+=(gAddress.length>0 ? ',' + city : city);
				if(box.ui('form.searchForm').field('country')){
				    var countryName = countryCodeToName[countryCode] || countryCode;
					if(countryCode) gAddress+=(gAddress.length>0 ? ',' + countryName : countryName);
				}
							

			checkAddressInGMap(gAddress);
		}
	});
    
    
    /**
     * Check if user entered address is valid for GMap
     * @param {String} address
     */
    function checkAddressInGMap(address) {
		clearResults();
		var hasSignInFormError = $('#resultMessage').html();
		if(hasSignInFormError) {
			$('#resultMessage').css('display', 'none');
		}
		geocoder = new google.maps.Geocoder();
		geocoder.geocode( { 'address': address}, function(results, status) {
		  if (status == google.maps.GeocoderStatus.OK) {
			currentLatLn = results[0].geometry.location;
			map.setCenter(currentLatLn);
			askStoreLocator(fullAddress, currentLatLn);
			/*marker = new google.maps.Marker({
				map: map,
				position: results[0].geometry.location
			});*/
		  } else {
			alert("Geocode was not successful for the following reason: " + status);
		  }
		});
    }
    
    /**
     * Request the StoreLocator WebService
     * @param {String} address
     * @param {Array} coords
     */
    function askStoreLocator(address, coordinates) {
			//console.log(coordinates);
		   var AddressName = address,
            AddressDesc = address,
            longitude = currentLatLn.lng(),
            latitude = currentLatLn.lat();
			
		var scales = new Array(1,2,3.75,7.5,15,30,60,120,240,500,1000,2000,3750,7500,15000,30000,60000,120000);
		var ratio = scales[map.getZoom()]/scales[currZoom];
		// TO DO corriger cette histoire de ratio
		//var decalage = 2*ratio;
		var decalage = 1;

		var projection = map.getProjection();
		
		var origin = projection.fromLatLngToPoint(coordinates);

		var l1 = projection.fromPointToLatLng(new google.maps.Point(origin.x - decalage, origin.y - decalage));
		var lg1 = l1.lng();
		var lt1 = l1.lat();
		
		var l2 = projection.fromPointToLatLng(new google.maps.Point(origin.x- decalage , origin.y + decalage));
		var lg2 = l2.lng();
		var lt2 = l2.lat();
		
		var l3 = projection.fromPointToLatLng(new google.maps.Point(origin.x + decalage, origin.y + decalage));
		var lg3 = l3.lng();
		var lt3 = l3.lat();
		
		var l4 = projection.fromPointToLatLng(new google.maps.Point(origin.x + decalage, origin.y - decalage));
		var lg4 = l4.lng();
		var lt4 = l4.lat();
		
		var lg5 = lg1;
		var lt5 = lt1;
		
		
		var points = [lg1, lt1, lg2, lt2, lg3, lt3, lg4, lt4, lg5, lt5];
		
		var top_code="Rule1";
	  
	   var filter;
	   filter = ['', '1,2,3'];
	   
	   if($('#institutesOnly').attr('checked')){
		 filter = ['', '3'];
	   }
	   if($('#chronologisteOnly').attr('checked')){
		 filter = ['', '2'];
	   } 
	   
	   
       wsStoreLocator.GetStoresAddressesByTopic(points, AddressName, AddressDesc, longitude, latitude, lcid, 50, top_code, filter, onSuccess, onError);
		
    }
    
	function getZoom(distance) {
		
		var zoom = map.getZoom();
		//donnÃ©e en km pour 100px dans l'ordre croissant de zoom
		var scales = new Array(1,2,3.75,7.5,15,30,60,120,240,500,1000,2000,3750,7500,15000,30000,60000,120000);
		
		// 1- on calcule le nombre max de px que l'on possÃ¨de = plus petit dimention entre la hauteur et la largeur de la div
		var maxPx = document.getElementById("googleMap").offsetHeight;
		if(document.getElementById("googleMap").offsetWidth < maxPx) maxPx = document.getElementById("googleMap").offsetWidth;
		maxPx = maxPx - 100;//delta d'erreur dans le calcul du tableau "scale"
		
		//2- pour chaque niveau de zoom 
		//  a- on recalcule le rapport pour la distance passÃ© en param -> (maxPx*100/scales[i])
		//  b- le plus petit Ã©cart positif entre cette valeur et la distance passÃ© en param donne le niveau de zoom adÃ©quate
		var minDistance = 9999999;
		var minDistancetmp;
		for(var i=0;i<scales.length;i++) {
			minDistancetmp = distance-(maxPx*100/scales[i]);
			if(minDistancetmp > 0 && minDistancetmp < minDistance) {
				minDistance = minDistancetmp;
				zoom = i;
			}
		}		
				
		return zoom;
	}
	
    /**
     * Callback when stores are successfully retrieved
     * @param {String} response: stores list, in JSON format
     */
    function onSuccess(response) {
        // check if response evaluation is necessary and call createResults
		//eval bug so I don't use it
		var stores = response;
		nbResult = stores.length;
		if(stores.length>0){
			var radius = 10	;
			if(lg =='en-AU') radius = 10;
			if(lg =='es-AR') radius = 10;
			map.setCenter(currentLatLn);
			map.setZoom(getZoom(radius));
			createResults(stores);
			//
			
			 $('div.item').click(function(){		
				showMarker($(this.parentNode).attr('id'));
			})
			//
		}else{
			noResult();
		}
    }
    
    /**
     * Callback when stores are not retrieved
     * @param {String} response: error message
     */
    function onError(response) {
        // check if response evaluation is necessary		
		var test = "";
		for (variable in response)
		 {
			test+=variable+""+response[variable]+"\n";
		 }
    }
	
	function noResult(){	
		var hasSignInFormError = $('#resultMessage').html();
		if(hasSignInFormError) {
			$('#resultMessage').css('display', 'block');
		}

	}
	
    function clearResults(){
		if (markersMemory) {
			for (i in markersMemory) {
			  markersMemory[i].setMap(null);
			}
		}

		
	//	map.clearOverlays(); 
		
        box.ui('carousel').destroy('results');
        resultsNode.empty();
	}
    /**
     * Create results list (carousel and map markers)
     * @param {Object} stores
     */
    function createResults(stores) {
		
		markersMemory= new Array();
		storesMemory= new Array();
		var carouselHTML = '<div id="resultsInner"><ul>';
		
		for(var i=0; i<stores.length-1; i++){
			var storeObj = stores[i];			
			storesMemory['item_' + i] = storeObj;
			storeObj.html = createStoreItem(storeObj, i);
			storeObj.htmlTooltip = createTooltipContent(storeObj, i);			
			carouselHTML += storeObj.html;			
			createStoreMarker(storeObj, i);						
		}
		
		carouselHTML += '</ul></div>';
		
		
				
		resultsNode.html(carouselHTML);
		
		$('#resultsInner ul').prepend($('#resultsInner').find('.institutes'));
		
		// create a new carousel
		box.ui('carousel').create({
			id: 'results',
			element: '#results',
			horizontal: true,
			display: 4,
			duration: 600,
			circular: true
        });
		
		var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
		if(isIE6){
			$(D.body).correctPNG();
		}
    }
 
    /**
     * Create a store item to add in the results list (carousel)
     * @param {Object} store: description of the store item
     * @param {String} id: store identification
     */
	  
	function showMarker(id){		

		if(curItem) curItem.removeClass('on');
		curItem = $('#'+id);
		curItem.addClass('on');	
		
		infowindow.setContent(storesMemory[id].htmlTooltip);
		infowindow.open(map, markersMemory[id]);
		//markersMemory[id].openInfoWindowHtml(storesMemory[id].htmlTooltip);
	}
		 
    function createStoreItem(store, id) {
        var html = '<li id="item_' + id + '" class="box[longitude=' + store.Longitude + ';latitude=' + store.Latitude + ']';
				if(store.StrExt1==3){
					html+= ' institutes';
				}
			html+= '">';

			html+= '<div class="item">';
            html+= '<div class="visual">';
			if(store.StrExt1==1){
				html+= '<img alt="Salon Kérastase" src="/img/icon/salons.png" />';
			}else if(store.StrExt1==2){
				html+= '<img alt="Salon Kérastase" src="/img/icon/institutes.png" />';
			}else if(store.StrExt1==3){
				html+= '<img alt="Salon Kérastase" src="/img/icon/salon.png" />';
			}else if(store.StrExt1==2.3){
			//Insitutes + Chronologiste --> icone blanche
				html+= '<img alt="Salon Kérastase" src="/img/icon/salon.png" />';
			}else if(store.StrExt1=='2,5'){
			//Insitutes + Chronologiste --> icone blanche
				html+= '<img alt="Salon Kérastase" src="/img/icon/ritual.png" />';
			}else if(store.StrExt1==5){
			// FreeRitual --> icone verte
				html+= '<img alt="Salon Kérastase" src="/img/icon/ritual.png" />';
			}else{
				html+= '<img alt="Salon Kérastase" src="/img/icon/salons.png" />';
			}
            html+= '</div>';
			html+= '<div class="content">';			
			html+= '<h2>'+store.Name+'</h2>';
			
			if(lcid == 3081) {
			    var compAddress = (store.Address2 ? ', ' + store.Address2 : '') + (store.Address3 ? ', ' + store.Address3 : '');
			    
			    html+= '<p>'+store.Address1+compAddress+'<br />'+store.City+' '+store.Zip_Code+'<br /><span>'+phone+'</span> '+store.Phone+'</p>';
			} else {
			    html+= '<p>'+store.Address1+'<br />'+store.Zip_Code+' '+store.City+'<br /><span>'+phone+'</span> '+store.Phone+'</p>';
			}
			if( store.StrExt10 ) {
			    html+= '<p><a href="'+ store.StrExt10+ '" target="_blank">'+ store.StrExt10+ '</a></p>';
			}
			
			html+= '</div>';			
			html+= '</div>';                     
        html += '</li>';
        return html;
    }
	
   function createTooltipContent(store, id) {
        var html= '<div id="popin" class="item">';
            html+= '<div class="visual">';
            html+= '<img alt="Salon Kérastase" src="/img/icon/kerastase.png" /><a href="#" onclick="window.print();return false;" style="position: absolute; top: 0pt; right: 25px;"><img alt="Print" src="/img/icon/print.png" /></a>';
            html+= '</div>';
			html+= '<div class="content">';			
			html+= '<h2>'+store.Name+'</h2>';			
			html+= '<p>'+store.Address1+'<br />'+store.Zip_Code+' '+store.City+'<br /><span>'+phone+'</span> '+store.Phone+'</p>';			
			if( store.StrExt10 ) {
			    html+= '<p><a href="'+ store.StrExt10+ '" target="_blank">'+ store.StrExt10+ '</a></p>';
			}
			html+= '</div>';			
			html+= '</div>'; 
        return html;
    }
  
	
    /**
     * Create a store marker to add on the map
     * @param {Object} store: description of the store item
     */
    function createStoreMarker(store, id) {      
		var point = new google.maps.LatLng(store.Latitude, store.Longitude);
		
		var iconWidth  = 22;
		var iconHeight  = 25;
		var kIcon = new google.maps.MarkerImage();
			if(store.StrExt1==1){
				kIcon.url ="/img/icon/salons.png";
			}else if(store.StrExt1==2){
				kIcon.url ="/img/icon/institutes.png";
			}else if(store.StrExt1==3){
				kIcon.url ="/img/icon/salon.png";
			}else if(store.StrExt1==2.3){
			//Insitutes + Chronologiste --> icone blanche
				kIcon.url ="/img/icon/salon.png";
			}else if(store.StrExt1=='2,5'){
			//Insitutes + Chronologiste --> icone blanche
				kIcon.url ="/img/icon/ritual.png";
			}else if(store.StrExt1==5){
			//Insitutes + Chronologiste --> icone verte
				kIcon.url ="/img/icon/ritual.png";
			}else{
				kIcon.url ="/img/icon/salons.png";
			}
			kIcon.size	= new google.maps.Size(iconWidth, iconHeight);
			kIcon.anchor = new google.maps.Point(iconWidth/2, iconHeight/2);
			/*kIcon.origin = new google.maps.Point(iconWidth/2, iconHeight/2);*/
			
		var markerOptions = {position : point, icon : kIcon};
		
		var marker = new google.maps.Marker(markerOptions);
		google.maps.event.addListener(marker, 'click', function () {
		// where I have added .html to the marker object.
			infowindow.setContent(store.htmlTooltip);
			infowindow.open(map, this);
			highlightCarouselItem(id);
		});
		
		marker.setMap(map);
		markersMemory["item_"+id] = 	marker;
		
    }
    
	 function highlightCarouselItem(id){
		if(curItem) curItem.removeClass('on');
		curItem = $('#item_'+id);
		curItem.addClass('on');
		if(nbResult>4) box.ui('carousel.results').moveToItem(id + 1);
	 }
   
})();
