// $Id: gallery-with-map.js 2688 2012-01-25 12:50:08Z sdalu $

/*
 * Copyright (c)  2007-2012  Stephane D'Alu
 * http://www.sdalu.com/
 */

// This function is from Google's polyline utility.
function decode_google_polyline (encoded) {
    var len   = encoded.length;
    var index = 0;
    var array = [];
    var lat   = 0;
    var lng   = 0;

    while (index < len) {
	var b;
	var shift  = 0;
	var result = 0;
	do { b = encoded.charCodeAt(index++) - 63;
	     result |= (b & 0x1f) << shift;
	     shift += 5;
	   } while (b >= 0x20);
	var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
	lat += dlat;
	
	shift  = 0;
	result = 0;
	do { b = encoded.charCodeAt(index++) - 63;
	     result |= (b & 0x1f) << shift;
	     shift += 5;
	   } while (b >= 0x20);
	var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
	lng += dlng;
	
	array.push(new google.maps.LatLng(lat * 1e-5, lng * 1e-5));
    }
    
    return array;
}


function handle_map() {
/*
 * Make data for use in google maps
 */
// Create capital icon for google maps Marker
var capitalMarkerImage       = 
	new google.maps.MarkerImage('/images/red-pushpin.png',
				    new google.maps.Size(32, 32), 
				    new google.maps.Point(0,0),
				    new google.maps.Point(10, 30));

// Tweek geomap_country (from geomap.js) for google maps usage
//  - add location marker for capitals
//  - convert encoded polylines to Polygon
var country = geomap_country;
for (c in country) {
    var paths = [];
    for (var i = 0 ; i < country[c].poly.length ; i++)
        paths.push(decode_google_polyline(country[c].poly[i].points));

    country[c].loc    = new google.maps.LatLng(country[c].lat, country[c].lng);
    country[c].marker = new google.maps.Marker({position: country[c].loc, 
						title   : country[c].name,
						icon    : capitalMarkerImage});
    country[c].poly   = new google.maps.Polygon({
	clickable     : false,          paths         : paths,
	fillColor     : '#728f1f',	fillOpacity   : 0.2,
	strokeColor   : '#728f1f',	strokeOpacity : 1,
	strokeWeight  : 2
    });
}

// Where to center the map by default
var center  = new google.maps.LatLng(33, 11);



/*
 * Create map
 */
// Map creation with control elements
var map     = new google.maps.Map(document.getElementById('gallery-map'), {
    zoom                     : 2,
    center                   : center,
    mapTypeId                : google.maps.MapTypeId.TERRAIN,
    mapTypeControl           : true,
    mapTypeControlOptions    : {
      style      : google.maps.MapTypeControlStyle.DROPDOWN_MENU,
      mapTypeIds : [ google.maps.MapTypeId.ROADMAP,
                     google.maps.MapTypeId.HYBRID,
                     google.maps.MapTypeId.SATELLITE,
                     google.maps.MapTypeId.TERRAIN ] },
    streetViewControl	     : false,
    navigationControl        : true,
    navigationControlOptions : {
      style      : google.maps.NavigationControlStyle.SMALL }
});

// Take action according to zoom level (restriction and dragging)
google.maps.event.addListener(map, 'zoom_changed', function() { 
    // Ensure that zoom level is included beetwen 1 and 4
    var zoom = map.getZoom();
    if      (zoom > 4) { map.setZoom(4); } 
    else if (zoom < 1) { map.setZoom(1); } 
    
    // Desactive dragging if useless according to zoom level
    if (map.getZoom() <= 1) { 
	map.setCenter(center); 
	map.setOptions({ draggable: false });
    } else {
	map.setOptions({ draggable: true  });
    }
});



/*
 * Selection country according to thumbnail
 */
var navigation  = $('#gallery-main'   );
var info_img    = $('#gallery-img'    );
var info_caption= $('#gallery-caption');
var overlays    = [];

var select_task = $.task(function(thumb) {
    thumb = $(thumb);
    var match   = thumb.attr('id').match(/^gallery-country-(.*)/);
    if (! match) return;
    var isocode = match[1];
    var info    = country[isocode];

    // Clear previous overlays
    for (i in overlays) overlays[i].setMap(null);
    overlays.length = 0;

    // Set new overlays
    info.marker.setMap(map);
    info.poly.setMap(map);
    overlays.push(info.marker, info.poly);

    // If zoomed center map to the current capital
    if (map.getZoom() > 1) map.panTo(info.loc);

    // Extract information from thumbnail
    //  and put in view (reserved emplacement in layout)
    var img     = thumb.find('.frame img').attr('src');
    var caption = thumb.find('.caption');			  
    info_img.attr('src', img);
    info_caption.html(caption.clone());

    // Remove warning asking from selection
    navigation.removeClass('please-select'); 
});


$('.gallery')
    .on('mouseenter', '.thumbnail', function(evt) { 
	select_task.delay(350, [evt.target]);   })
    .on('mouseleave', '.thumbnail', function(evt) { 
        select_task.cancel();  		    	});


// Start with highlighting a country
var first = $('#gallery-country-fr')[0] || $('#gallery .thumbnail')[0];
if (first) select_task.now([first]);
}


/* Load the google map api with the correct language
 *  according to MoXoW settings if not present use english
 *  as default
 */

function yo() {
    handle_map();

}
google.load('maps', '3', {
    other_params:'sensor=false',
    language    : MoXoW.getLang() || 'en',
    callback    : yo
});



$(function() {



/*
 * Switching between list view and map view
 */
var cookie = function() {};
if (typeof MoXoW !== 'undefined')	cookie = MoXoW.cookie;
else if ($.cookie)    			cookie = $.cookie

$('#gallery-view-as-list').on('click', function(evt) {
    $('#gallery-main')
	.replaceClass('gallery-as-map',  'gallery-as-list')
	.replaceClass('compact-view',    'full-view'      );
    $('#gallery-view-as-list').radioClass('selected');
    cookie('gallery-view-as', 'list');
});
$('#gallery-view-as-map').on('click', function(evt) {
    $('#gallery-main')
	.replaceClass('gallery-as-list', 'gallery-as-map' )
	.replaceClass('full-view',       'compact-view'   );
    $('#gallery-view-as-map').radioClass('selected');
    cookie('gallery-view-as', 'map');
});

if (cookie('gallery-view-as') == 'list') {
    $('#gallery-main')
	.replaceClass('gallery-as-map',  'gallery-as-list')
	.replaceClass('compact-view',    'full-view'      );
    $('#gallery-view-as-list').radioClass('selected');
}


/*
 * Whole thumbnail is a link
 */
// Make cursor a pointer on whole thumbnail
$.rule('.gallery .thumbnail').css({ cursor: 'pointer' }).appendTo('link');

$('.gallery').on('click', '.thumbnail', function(evt) { 
    var a = $(this).find('.frame a');
    if (a) window.location.href = a.attr('href');
});


});

