/* ****************************************************

	@file         global.js
	@description  Comportements globaux
	vim: set noet ts=4 fdm=marker fenc=utf-8:

***************************************************** */

if ( !window.console ) {
	window.console = {
		log: function() {}
	}
}

// Création de l´élément ABBR pour IE6
document.createElement('abbr');

(function($) {
	
	$(function() {
		
		String.implement({
			
			removeAccents: function() {
				var string = this;
				
				var listA =  'Œ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö Ø Ù Ú Û Ü Ý ß à á â ã ä å ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ø ù ú û ü ý ÿ œ'.split(' '),
					listB = 'OE A A A A A A A C E E E E I I I I D N O O O O O O U U U U Y s a a a a a a c e e e e i i i i o n o o o o o o u u u u y y oe'.split(' ');
				
				var i = listA.length, regex;
				
				while (i--) {
					regex = new RegExp( listA[i], 'g' );
					string = string.replace( regex, listB[i] );
				}
				return string;
			},
			
			removeSpecialChars: function() {
				return this.replace( /[^0-9a-zA-Z -_]/g, '' );
			},
			
			splitWords: function() {
	 			return this.replace( /[ -_]+/g, ' ' ).split(' ');
			},
			
			splitKeywords: function() {
				return this.removeAccents().toLowerCase().removeSpecialChars().trim().splitWords().removeCommonWords();
			}
			
		});
		
		Array.implement({
			
			removeCommonWords: function() {
				var commonWords = 'rue avenue route boulevard chemin rang parc quartier st saint sainte le la les l du de des d'.split(' ');
				var w = this.length;
				while ( w-- ) {
					if ( commonWords.indexOf( this[ w ] ) != -1  ) {
						this.splice( w, 1 );
					}
				}
				return this;
			}
			
		});
		
		
		var scrollWheel = $('.template-clips').length ? true : false;
		
		var mapOptions = {
			center: (new google.maps.LatLng( 46.79747416096174, -71.28376007080078 )),
			zoom: 13,
			scrollwheel: scrollWheel,
			disableDefaultUI: true,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		
		if ( $('.template-clips').length ) {
			mapOptions.navigationControl = true;
			
			window.markersArray = [];
			window.infoWindow = new google.maps.InfoWindow();
			window.map = new google.maps.Map( $('#carte-inner')[0], mapOptions );
			
			google.maps.event.addListener(map, 'dragstart', function() {
				infoWindow.close();
			});
		}
		
		var ua = navigator.userAgent.toLowerCase();
		if ($('.template-clips').length == 0 && !(ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1)) {
			window.map = new google.maps.Map( $('#carte-inner')[0], mapOptions );
		}
		
		window.fitToMarkers = function( mapObject ) {
			var bounds = new google.maps.LatLngBounds();
			var i = markersArray.length;
			while (i--) {
				bounds.extend( markersArray[i].position );
			}
			mapObject.fitBounds( bounds );
		};
		
		window.addMarker = function( markerId, opts ) {
			var marker = new google.maps.Marker({
				position: opts.location,
				map: map,
				title: opts.title,
				icon: '/img/interface/img-marqueur.png'
			});
			google.maps.event.addListener(marker, 'click', function() {
				map.setZoom( 15 );
				map.setCenter( markersArray[ markerId ].getPosition() );
				showInfoWindow( markerId );
			});
			window.markersArray[ markerId ] = marker;
		};
		
		window.showInfoWindow = function( markerId ) {
			if (window.location.href.indexOf('foo=bar') !== -1) {
				infoWindow.setContent( window.inscriptions[0].contenuInfoWindow );
			} else {
				infoWindow.setContent( $('#info-window-content-'+ markerId).eq(0).clone()[0] );
			}
			infoWindow.open( map, window.markersArray[ markerId ] );
		};
		
		window.zoomIn = function( mapObject ) {
			mapObject.setZoom( mapObject.getZoom() + 1 );
		};
		window.zoomOut = function( mapObject ) {
			mapObject.setZoom( mapObject.getZoom() - 1 );
		};
		
		if ( $('body').is('.template-clips') ) {
			
			$('#overlay, #viewport').remove();
			
			var id = inscriptions.length;
			while (id--) {
				
				addMarker( id, {
					location: (new google.maps.LatLng( inscriptions[ id ].location.lat, inscriptions[ id ].location.lng )),
					title: inscriptions[ id ].nomRue
				});
				
				inscriptions[ id ].motsCle = inscriptions[ id ].nomRue.splitKeywords();
			}
			
			window.fitToMarkers( map );
			
			map.panBy( 0, 8 * $(window).height() / 100 );
			
			$('#zone-recherche > form').submit(function() {
				var motsCleEntres        = $('#recherche').val().splitKeywords().unique(),
					motsCleEntresLength  = motsCleEntres.length,
					inscriptionsTrouvees = [];
				
				var i = inscriptions.length, m;
				while (i--) {
					
					m = motsCleEntresLength;
					while (m--) {
						if ( inscriptions[i].motsCle.indexOf( motsCleEntres[m] ) != -1 ) {
							inscriptionsTrouvees.push( i );
							break;
						}
					}
					
					if ( !!inscriptionsTrouvees.length  ) {
						map.setZoom( 15 );
						map.setCenter( markersArray[ inscriptionsTrouvees[0] ].getPosition() );
						showInfoWindow( inscriptionsTrouvees[0] );
						break;
					}
				}
				
				if ( !inscriptionsTrouvees.length  ) {
					$('#zone-recherche p.erreur').text('Aucune vidéo n’a été soumise pour ce lieu.');
				} else {
					$('#zone-recherche p.erreur').text('');
				}
				
				return false;
			});
		}
		
		$('input[autofocus]').focus();
		
		/* @section Positionnement des éléments au load, resize et fontresize {{{
		******************************************************************************/
		$(window).resize(function() {
			redraw();
		});

		// $(document).bind("fontresize", function () {
		// 	redraw();
		// });

		function redraw() {
			
			var h_window = $(window).height() - 174;
			var h_contenu = $('#contenu').height();

			if ( h_window > h_contenu ) {
				$('#viewport').height( ($(window).height()-174) + 'px' );
			}
			var h = ( h_window - h_contenu ) / 2;
			if ( h >= 0 ) {
				$('#contenu').css('paddingTop', h+'px');
			}
		}

		redraw();
		/*}}}*/

		/* @section Affichage du vidéo modèle {{{
		******************************************************************************/
		$('.modele .lien a').click(function() {
			var $popup = $('.popup');
			if ( $popup.is('.visible') ) {
				$popup.css({'left':'-99999px','right':'auto'}).removeClass('visible');
			} else {
				$popup.css({'top':(-1 * $popup.height())+'px','left':'auto','right':'-150px'}).addClass('visible');
			}
			return false;
		});	
		$('.bulle-fermer').click(function() {
			$('.popup').css({'left':'-99999px','right':'auto'}).removeClass('visible');
		});
		/*}}}*/

		/* @section Formulaire de participation {{{
		******************************************************************************/
		$('body.template-participation form').each(function() {
			var $this = $(this);
			var compteur_jeunes = $this.find('.jeunes').attr('class').match(/jeunes-([0-9]+)/);
			compteur_jeunes = parseInt( compteur_jeunes[1] );
			$this.find('.jeunes').find('.ajouter a').click(function() {
				if ( compteur_jeunes < 2 ) {
					compteur_jeunes++;
					var html = '<ul class="groupe jeune">'+$(this).parents('.jeunes').find('ul').eq(0).html()+'</ul>';
					html = html.replace(/jeune-1-/g, 'jeune-'+compteur_jeunes+'-');
					html = html.replace(/jeune\[1\]/g, 'jeune['+compteur_jeunes+']');
					html = html.replace(/\s?champ-erreur\s?/g, '');
					$(html).insertBefore( $(this).parent() ).find('input').val('');
					$(this).parent('.ajouter').remove();
					return false;
				}
			});
			if ( !$.browser.msie || ( $.browser.msie && $.browser.version > 6 ) ) {
				$('.tip').attr('title', '<img src="/img/tooltips/tooltip-url.png" alt="" />').tooltip({
					track : true,
					delay : 0
				});
			}
		});
		/*}}}*/

	});

})(jQuery);


