// 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',
		'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});
	
	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;
        default:
            lcid = 1036;		
            break;
    }
    // create GMap
    box.dom(W).load(function() { 
        
        if(GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById("googleMap"));
            map.addControl (new GLargeMapControl3D());
            map.addControl (new GMapTypeControl());
            map.addControl (new GScaleControl());
            map.enableScrollWheelZoom();
            if(lg=="it-IT"){
				currZoom = 6;
				map.setCenter(new GLatLng(42.98857645832184, 13.53515625), 6);
			}else if(lg=="en-AU"){
				currZoom = 3;
				map.setCenter(new GLatLng(-25.2743980, 133.7751360), 3);
			}else if(lg=="es-ES"){
				currZoom = 6;
				map.setCenter(new GLatLng(40.896906, -3.669434), 6);
			}else if(lg=="es-CL"){
				currZoom = 3;
				map.setCenter(new GLatLng(-22.593726, -72.246094), 3);
			}else if(lg=="pt-BR"){
				currZoom = 4;
				map.setCenter(new GLatLng(-12.382928, -53.173828), 4);
			}else if(lg=="nl-BE"){
				currZoom = 6;
				map.setCenter(new GLatLng(51.599595,5.029907), 6);
			}else{
				currZoom = 6;
				map.setCenter(new GLatLng(52.41582261237877, -5.20751953125), 6);
			}			
			GEvent.addListener(map, "moveend", function() {
			  var center = map.getCenter();	
			  
				/*console.log(center.lat());
				console.log(center.lng());*/
			  
			});
			
			
			
        }
        
    }).unload(GUnload);
    
    // add form validation
    box.dom(D).ready(function() {
       // console.log("ready");		
		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);
				}
							
				//console.log("hello");		
			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');
		}
	
        if(!clientGeocoder) {
            clientGeocoder = new GClientGeocoder();
        }
        	
        clientGeocoder.getLocations(address, function(locations) {
            // console.log(locations);
            if(locations.Placemark) {				
                //alert('results ok with (new GClientGeocoder()).getLocations');
                if(locations.Placemark.length > 0) {							
                    askStoreLocator(fullAddress, locations.Placemark[0].Point.coordinates);
                } else{
                    //alert('no result with (new GClientGeocoder()).getLocations + locations.Placemark.length === 0');
					noResult();
				}
            } else {
                //alert('no result with (new GClientGeocoder()).getLocations');
                noResult();
            }
        });
    }
    
    /**
     * Request the StoreLocator WebService
     * @param {String} address
     * @param {Array} coords
     */
    function askStoreLocator(address, coordinates) {
        
        var AddressName = address,
            AddressDesc = address,
            longitude = coordinates[0],
            latitude = coordinates[1];
        
		curLatitude = latitude;
		curLongitude = longitude;
		
		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];
		
		var origin = map.fromLatLngToContainerPixel(new GLatLng(latitude, longitude));
		
		var decalage =2*ratio;
        if (lg == 'en-GB') {
            /* enhance search perimeter only for UK */
            decalage = 4 * ratio;
        }
        if (lg == 'pl-PL') {
            /* enhance search perimeter only for PL */
            decalage = 8 * ratio;
        }
		
		var l1 = map.fromDivPixelToLatLng(new GPoint(origin.x - decalage, origin.y - decalage));
		var lg1 = l1.lng();
		var lt1 = l1.lat();
		
		var l2 = map.fromDivPixelToLatLng(new GPoint(origin.x- decalage , origin.y + decalage));
		var lg2 = l2.lng();
		var lt2 = l2.lat();
		
		var l3 = map.fromDivPixelToLatLng(new GPoint(origin.x + decalage, origin.y + decalage));
		var lg3 = l3.lng();
		var lt3 = l3.lat();
		
		var l4 = map.fromDivPixelToLatLng(new GPoint(origin.x + decalage, origin.y - decalage));
		var lg4 = l4.lng();
		var lt4 = l4.lat();
		
		var lg5 = lg1;
		var lt5 = lt1;
		
		/* var polyline = new GPolyline([
  		  l1,
  		 l2,
		 l3,
		 l4,
		 l1		 
		], "#ff0000", 5);
		map.addOverlay(polyline);
		*/
		
		var points = [lg1, lt1, lg2, lt2, lg3, lt3, lg4, lt4, lg5, lt5];
	
       //wsStoreLocator.GetStoresAddresses(points, AddressName, AddressDesc, longitude, latitude, lcid, onSuccess, onError);
	   var top_code="Rule1";
	  
	   var filter;
	   filter = ['', ''];
	   
	   if($('#institutesOnly').attr('checked')){
		 filter = ['', '2'];
	   }
	   if($('#chronologisteOnly').attr('checked')){
		 filter = ['', '1'];
	   } 
	   
	   
	   
	   //alert(filter);
	   
	   /*var top_code="Rule2";
	  
	   var filter1;
	   if($('#chronologisteOnly').attr('checked')){
		 filter1 = ['', '1'];
	   }else{
			filter1 = ['', ''];
	   }*/
	   
       wsStoreLocator.GetStoresAddressesByTopic(points, AddressName, AddressDesc, longitude, latitude, lcid, 50, top_code, filter, onSuccess, onError);
		/*$.ajax({
			method: 'GET',
			url: '/js/dev/file.js',
			dataType: 'text',
			success: onSuccess,
			error: 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(new GLatLng(curLatitude, curLongitude), 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(){
	
		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);
		// 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');	
		markersMemory[id].openInfoWindowHtml(storesMemory[id].htmlTooltip);
	}
		 
    function createStoreItem(store, id) {
        var html = '<li id="item_' + id + '" class="box[longitude=' + store.Longitude + ';latitude=' + store.Latitude + ']">';
			html+= '<div class="item">';
            html+= '<div class="visual">';
			if(store.StrExt1==1){
				html+= '<img alt="Salon Kérastase" src="/img/icon/institutes.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>';
			}
			
			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>';			
			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 GLatLng(store.Latitude, store.Longitude);
		var iconWidth  = 22;
		var iconHeight  = 25;
		var kIcon = new GIcon();
			if(store.StrExt1==1){
				kIcon.image ="/img/icon/institutes.png";
			}else{
				kIcon.image ="/img/icon/salons.png";
			}
			kIcon.iconSize	= new GSize(iconWidth, iconHeight);
			kIcon.iconAnchor = new GPoint(iconWidth/2, iconHeight/2);
			kIcon.infoWindowAnchor = new GPoint(iconWidth/2, iconHeight/2);			
		var markerOptions = { icon:kIcon };

		var marker = new GMarker(point, markerOptions);
		
		GEvent.addListener(marker, "click", function(nIndex) {			
				marker.openInfoWindowHtml(store.htmlTooltip);	
				highlightCarouselItem(id);
		});			
		map.addOverlay(marker);
		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);
	 }
   
})();
