// $Id: gallery-with-map.js 1394 2010-05-01 08:01:42Z sdalu $

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

YUI().use('node', 'event', 'event-simulate', 'stylesheet', 'cookie',
	  'node-extra', 'task', 'myweb', function(Y) {




function handle_map() {

/*
 * Make data for use in google maps
 */
// Create capital icon for google maps Marker
var capitalIcon              = new google.maps.Icon();
capitalIcon.iconSize         = new google.maps.Size(32,32);
capitalIcon.iconAnchor       = new google.maps.Point(10,30);
capitalIcon.infoWindowAnchor = new google.maps.Point(16,0);       
capitalIcon.image            = '/images/red-pushpin.png';

// 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 polylines = [];
    for (var i = 0 ; i < country[c].poly.length ; i++) {
	var poly = country[c].poly[i];
        polylines.push({ color     : '#8FB327',
        	         weight    : 2,
 		         opacity   : 1.0,
 		         points    : poly.points,
 		         levels    : poly.levels,
 		         zoomFactor: 2,
 		         numLevels : 18});
    }
    country[c].loc    = new google.maps.LatLng(country[c].lat, 
					       country[c].lng);
    country[c].marker = new google.maps.Marker(country[c].loc, 
					       { icon: capitalIcon });
    country[c].poly   = new google.maps.Polygon.fromEncoded({
           polylines: polylines,
 	   fill     : true,
 	   color    : '#728f1f',
 	   opacity  : 0.2,
 	   outline  : true
    });
}

// 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.Map2(document.getElementById('gallery-map'), {
	mapTypes: [ google.maps.NORMAL_MAP,
		    google.maps.HYBRID_MAP,
		    google.maps.SATELLITE_MAP,
		    google.maps.PHYSICAL_MAP ] } );
map.addControl(new google.maps.MenuMapTypeControl());
map.addControl(new google.maps.SmallZoomControl3D());

// Ensure that zoom level is included beetwen 1 and 4
var mapTypes = map.getMapTypes(); 
for (var i = 0; i < mapTypes.length; i++) { 
    mapTypes[i].getMinimumResolution = function() {return 1;} 
    mapTypes[i].getMaximumResolution = function() {return 4;} 
}

// Desactive dragging if useless according to zoom level
google.maps.Event.addListener(map, 'zoomend', function(o, n) {
    if (n <= 1) { map.setCenter(center);
	          map.disableDragging(); }
    else        { map.enableDragging();  }
});

// Start with the center at zoom level 2
map.setCenter(center, 2);



/*
 * Selection country according to thumbnail
 */
var navigation  = Y.one('#gallery-main'   );
var info_img    = Y.one('#gallery-img'    );
var info_caption= Y.one('#gallery-caption');

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

    // Clear previous marker and place new one
    map.clearOverlays();
    map.addOverlay(info.marker);
    map.addOverlay(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.one('.frame img').getAttribute('src');
    var caption = thumb.one('.caption');			  
    info_img.setAttribute('src', img);
    info_caption.setContent(Y.Node.getDOMNode(caption.cloneNode(true)));

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


Y.all('.gallery').each(function(gallery) { 
    gallery.delegate('mouseenter',  function(evt) { 
        var tgt = evt.target.closest('.thumbnail');
	select_task.delay(350, tgt);
      }, '.thumbnail');
    gallery.delegate('mouseleave',  function(evt) { 
        select_task.cancel();
      }, '.thumbnail');
});


// Start with highlighting a country
var first = Y.one('#gallery-country-fr');
if (!first) first = Y.one('#gallery .thumbnail');
if (first) select_task.now(first);
    

}





/* Load the google map api with the correct language
 *  according to MyWEB settings if not present use english
 *  as default
 */
google.load('maps', '2', {
    language: (Y.MyWEB && Y.MyWEB.opts.lang) ? Y.MyWEB.opts.lang : 'en',
    callback: function() { Y.on('domready', handle_map); }
});




Y.on('domready', function() {


/*
 * Switching between list view and map view
 */
Y.one('#gallery-view-as-list').on('click', function(evt) {
    Y.one('#gallery-main')
	.replaceClass('gallery-as-map',  'gallery-as-list')
	.replaceClass('compact-view',    'full-view'      );
    Y.one('#gallery-view-as-list').radioClass('selected');
    if (Y.Cookie) 
	Y.Cookie.set('gallery-view-as', 'list', Y.MyWEB.opts.cookie);
});
Y.one('#gallery-view-as-map').on('click', function(evt) {
    Y.one('#gallery-main')
	.replaceClass('gallery-as-list', 'gallery-as-map' )
	.replaceClass('full-view',       'compact-view'   );
    Y.one('#gallery-view-as-map').radioClass('selected');
    if (Y.Cookie) 
	Y.Cookie.set('gallery-view-as', 'map', Y.MyWEB.opts.cookie);
});


if (Y.Cookie && Y.Cookie.get('gallery-view-as') == 'list') {
    Y.one('#gallery-main')
	.replaceClass('gallery-as-map',  'gallery-as-list')
	.replaceClass('compact-view',    'full-view'      );
    Y.one('#gallery-view-as-list').radioClass('selected');
    //Y.one('#gallery-view-as-list').simulate('click');
}

if (Y.one('body').hasClass('handheld')) {
    Y.one('#gallery-main')
	.replaceClass('gallery-as-map',  'gallery-as-list')
	.replaceClass('compact-view',    'full-view'      );
    Y.one('.gallery-view-as').setStyle('display', 'none');
}

/*
 * Whole thumbnail is a link
 *   Except if using a slideshow galery (currently: highslide)
 */
// Make cursor a pointer on whole thumbnail
var sheet = Y.StyleSheet('gallery');
sheet.set('.gallery .thumbnail', { cursor: 'pointer' });

// Delegate thumbnail click to each gallery
/* XXX: Strange delegate behaviour on webkit
Y.all('.gallery').each(function(gallery) { 
    gallery.delegate('click',  function(evt) { 
  	var tgt = evt.target.closest('.thumbnail');
	var a   = tgt.one('.frame a');
	if (a) window.location.href = a.getAttribute('href');
    }, '.thumbnail');
});
*/
Y.all('.gallery .thumbnail').each(function(thumb) { 
    thumb.on('click',  function(evt) { 
	var a   = thumb.one('.frame a');
	if (a) window.location.href = a.getAttribute('href');
    });
});



});
});

