function log() {
   if(console) {
      console.log.apply(this,arguments);
   }
}

function resizeGalSideNav(){
    var overlaynavapplied = false;
    var centerImgWidth; 
    $('ul.gallery li').each(function(i){
        //console.log('left',$(this).css('left'));
        if ( parseFloat($(this).css('left')) >= 0 && !overlaynavapplied ) {
            centerImgWidth = $(this).width();
            overlaynavapplied = true;
        }
    });
    var newWidth = (447 - centerImgWidth) / 2 ;
    //console.log(centerImgWidth);
    $('.gallery_nav_overlay').find('a.galoverlay_prev').css('width',newWidth);
    $('.gallery_nav_overlay').find('a.galoverlay_next').css('width',newWidth);
    //console.log('joie', newWidth, $('.gallery_nav_overlay'));
}

firstnav = {
	init : function(){
		// fading effect on the menu buttons :
		$('ul#menu a, #navtop li a').append('<span class="hover" />').each(function(){
			var $span = $('> span.hover', $(this)).css({'opacity':0});
      $span.text($(this).text());
			$(this).hover(function(){
				// on hover
				$span.stop().fadeTo(500, 1);
			},function(){
				// off hover
				if (!$(this).parent().is('.active')) {
					$span.stop().fadeTo(500, 0);
				}
			});
		});
		$('ul#menu li.active span.hover, #navtop li.active span.hover').css({'opacity':1});
	}
}

// calculate the the total width of all the elements of the submenu :
function compoundwidths (selector){
	compoundwidth = 0;
	$(selector).each(function(){
		compoundwidth += $(this).width();
		compoundwidth += parseInt($(this).css('padding-right'));
		compoundwidth += parseInt($(this).css('padding-left'));
	});
	return compoundwidth + ($(selector).length);
}

secondnav = {
	init : function(){
		var self = this;
		$('ul#sousmenu li').each(function(){
			$span = $('<span class="hover"></span>');
			$('a', $(this)).css({'padding-right':'0px'});
			paddingright = 0;
			// increment the "padding-right" of all the menu items so that it takes all the available space :
			while (compoundwidths('ul#sousmenu li a') < $('ul#sousmenu').width()) {
				paddingright ++;
				$('ul#sousmenu li a').css({'padding-right':paddingright+'px'});
			}
			$('a', $(this)).hover(function(){
				self.show($(this));
			},function(){
				self.hide($(this));
			}).append($span);
			$span.hide();
		});
	},
	show : function(caller){
		caller.stop().animate({backgroundColor:'#282828'});
		$('span.hover', caller).fadeIn();
	},
	hide : function(caller){
		caller.stop().animate({backgroundColor:'#fffff'});
		$('span.hover', caller).fadeOut();
	}
}

footernav = {
	init : function(closeprettypoppin,season_name){
		var self = this;
		$('#footer ul li').each(function(){
			$span = $('<span class="hover"></span>');
			$('a', $(this)).hover(function(){
				self.show($(this));
			},function(){
				self.hide($(this));
			}).append($span);
			$span.hide();
		});
		// center it according to the width of the container
		$('div.listfooter').each(function(){
			parentwidth = $(this).parent('#footer').width();
			$('ul',$(this)).css({'left':(parentwidth/2)-($(this).width()/2) + 'px'});
		});
		// do something special for those that we open in a prettypopin :
	  $('#foot_subitems li a.prettypopin').prettyPopin({
			modal : false, /* true/false */
			width : false, /* false/integer */
			height: false, /* false/integer */
			opacity: 0.95, /* value from 0 to 1 */
			animationSpeed: 'fast', /* slow/medium/fast/integer */
			followScroll: true, /* true/false */
			loader_path: 'images/prettyPopin/loader.gif', /* path to your loading image */
			season_name_prettypoppinfooter: season_name,
			closeprettypoppin: closeprettypoppin,
			callback: function(){},
			on_appear: function(){
				if (!$.browser.msie) {
					cufon.init();
				}	
			} 
		});
	},
	show : function(caller){
		caller.stop().animate({backgroundColor:'#282828'});
		$('span.hover', caller).fadeIn();
	},	
	hide : function(caller){
		caller.stop().animate({backgroundColor:'#fffff'});
		$('span.hover', caller).fadeOut();
	}
}

// cufon
cufon = {
init : function(){		
		Cufon.replace('h1 a', { fontFamily: 'Aaux ProRegular Italic' });
		Cufon.replace('h2', { fontFamily: 'Aaux ProRegular' });
		Cufon.replace('a#rss', { fontFamily: 'Aaux ProLight' });
		Cufon.replace('a#b_close', { fontFamily: 'Aaux ProLight' });
		/*
			ajout pour collection video
		*/
		Cufon.replace('body.collection h3', { fontFamily: 'Aaux ProRegular' });
	}
}

// Blocs :
var blocs = {
	init : function() {
		var self = this;
		var hauteur = 70;
		$('.contin').css({'height': hauteur+'px'});

		$('div.details').each(function() {
			if (!$(this).is('.showdetails')) {
				$(this).hide();
			}
		}); // tout cacher
	},
	toutCacher : function(saufLui){
		$('.ltcol,.rtcol').not(saufLui).slideUp('slow');	
	},
	toutMontrer : function(saufLui){
		$('.ltcol,.rtcol').not(saufLui).slideDown('slow');
	}
};

var prettyGal = {
	selecteur : "ul.gallery",
	loaded_callback : function(){},
	init : function(selecteur,prevlabel,nextlabel,season_name,callback){
		var self = this;
		if (selecteur) {
			self.selecteur = selecteur;
		};
		self.loaded_callback = callback;
		var $obj = $(self.selecteur);
		$subimages = $('img', $obj); 
		// preload every images before applying the prettyGallery :
		$subimages.each(function(i){
			var isloaded = false;
			var doafterload = function(){
				if (isloaded) {
					return false; // ne rien faire si il est deja loaded
				}
				if ((i+1) == $subimages.length) {
					// pretty gallerie :
					var ret = $obj.prettyGallery({
						itemsPerPage : 1,
						animationSpeed : 'normal', /* fast/normal/slow */
						navigation : 'bottom',  /* top/bottom/both */
						of_label: ' of ', /* The content in the page "1 of 2" */
						previous_title_label: 'Previous page', /* The title of the previous link */
						next_title_label: 'Next page', /* The title of the next link */
						previous_label: prevlabel, /* The content of the previous link */
						next_label: nextlabel, /* The content of the next link */
						season_name_gal: season_name,
						loop: true,
						loaded_callback:self.loaded_callback
					});
				};
				isloaded = true; // pour avertir qu'on a loaded
			}
			$(this).load(doafterload);
			// HACK a cause du cache :
			if($(this)[0].complete){
				doafterload();
			}
			// /HACK
		});
	}, 
	agrandirbutton : function(){
		//expositions OU activites
		if ($('body.boutique').length == 1 || $('body.expositions').length ==1 || $('body.activites').length ==1 || $('body.collection').length ==1) {
			$("a.agrandir").css({
				"position" : "absolute",
				"top" : "285px"
			});
		};
	},
	getCurrentIndex : function(){
		var self = this;
		var $obj = $(self.selecteur);
		return $obj.data('currentindex');
	}
}

var prettyPhotoGal = {
	init : function(closebutton,pp_nextbutton,pp_previousbutton, season_name, callback) {
		// lightbox
		$("ul.gallery li a").prettyPhoto({
			animationSpeed: 'normal', /* fast/slow/normal */
			padding: 40, /* padding for each side of the picture */
			opacity: 0.90, /* Value betwee 0 and 1 */
			showTitle: false, /* true/false */
			allowresize: true, /* true/false */
			counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
			closelabel: closebutton,
			pp_next: pp_nextbutton,
			pp_previous: pp_previousbutton,
			season_name: season_name,
			callback: callback
		});
	}
}

var searchbox = {
	init : function(){
		var a_inputStrings = new Array();
		$('.input').each(function(i){
			a_inputStrings[i] = $('.input:eq('+i+')').val();
			$('.input:eq('+i+')').focus(function(){
				if($(this).val() == a_inputStrings[i]) {
					$(this).val('');
					$(this).css({'color' : '#000000'});
				}
			})
			.blur(function(){
		    if($(this).val() == '') {
					$(this).val(a_inputStrings[i]);
					$(this).css({'color' : '#b0b0b0'});
				}
			});
		});
	}
}		

var PicBrowser = Base.extend({
	
  constructor: function(selector, index) {
		self = this;
    self.selector = selector;
		self.gal_index = index;
		self.itemWidth = $(self.selector+' li:first').width();
		$.each($(self.selector+':eq('+index+') li'), function(i){
			$(self.selector+':eq('+index+') li:eq('+i+')').css({
				'position' : 'absolute',
				'left' : self.itemWidth * i
			});
		});
		$(self.selector+':eq('+index+')').next('.prettyNavigation').find('li.prev a:eq(0)').click(function(){
			self.previous(index); 
			return false;
		});
		$(self.selector+':eq('+index+')').next('.prettyNavigation').find('li.next a:eq(0)').click(function(){
			self.next(index);
			return false;
		});
  },
	
  // properties :
  selector: "ul.gallery",
	itemWidth: 0,
	gal_index: 0,
  
  next: function(index) {
		self = this;
    $.each($(self.selector+':eq('+index+') li'), function(i){ // loop into the "ul.gallery:eq(index) li"
			
			$(self.selector+':eq('+index+') li:eq('+i+')').animate({ // pour le LI qu'on est, animer le left :
			   left: (i * self.itemWidth) - self.itemWidth
			 }, 500, function(){ // quand on a fini d'animer le left du LI :
				$.each($(self.selector+':eq('+index+') li'), function(j){ // on replace tous les li du meme ul :
					$(this).css({
						'position' : 'absolute',
						'left' : (self.itemWidth * j)
					});
				});
			});
		});

		$(self.selector+':eq('+index+') li:first').appendTo($(self.selector));
  },
  
  previous: function(index) {
    $(self.selector+' li:last-child').css('left', - self.itemWidth);

		$(self.selector+' li:last-child').prependTo($(self.selector));

		$.each($(self.selector+' li'), function(i){
			$(self.selector+' li:eq('+i+')').animate({
			   left: (i * self.itemWidth)
			 }, 500);
		});
  }

});
		

var newsletter = {
	send : function(caller) {
		var self = this;
		$caller = $(caller);
		email = $caller.find('#courriel').val();
		$.post($caller.attr('action'), {'data[Lettersubscription][email]':email},
		function(data){
			eval('var dataobj = '+data);
			alert(dataobj.text);
	  });
	}
};

var sendtofriend = {
	init : function() {
		var self = this;
		$('#send.send_to_friend_button').click(function(){
			$(this).closest('form').triggerHandler('submit');
			$(this).closest('form').submit(function(){
				$(this).ajaxSubmit({
		        target: '#output'
		    });
		    return false; // <-- important!
			});
		});
	}
}


var videos = {
  init : function(){
    var self = this;
    $('.videos_link a').each(function(i){
      $(this).click(function(){
        self.instanciateVideo($(this));
        return false;
      });
    });
    self.instanciateVideo($('.videos_link a:eq(0)'));
    self.adjustBorder();
  },
  instanciateVideo : function(caller) {
    var self = this;
    var $caller = $(caller);
    var hosting = $caller.attr('rel');
    var videokey = $caller.attr('title');
    var htmlvideo;
    if (hosting == 'vimeo') {
      htmlvideo = '<object width="447" height="276"><param name="allowfullscreen" value="true" />\
      <param name="allowscriptaccess" value="always" />\
      <param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='+videokey+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" />\
        <embed src="http://vimeo.com/moogaloop.swf?clip_id='+videokey+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="447" height="276"></embed>\
      </object>';
    }else{
      // youtube :
      htmlvideo = '<object width="447" height="276"> \
      <param name="movie" value="http://www.youtube.com/v/'+videokey+'&hl=fr_FR&fs=1&"></param> \
      <param name="allowFullScreen" value="true"></param> \
      <param name="allowscriptaccess" value="always"></param> \
        <embed src="http://www.youtube.com/v/'+videokey+'&hl=fr_FR&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="447" height="276"></embed> \
      </object>';
    };
    $('#videocontainer').empty().append(htmlvideo);
  },
  adjustBorder : function() {
      var self = this;
      if ( $('ul.gallery').length === 0 ) {
          // If we ONLY have some videos and no gallery, then show this line above the title of the video gallery :
          $('.video_youtube').css({
              'border-top': '1px solid #e3e3e3',
              'margin-top': 0,
              'padding-top': '14px'
          });
      }
  }
}


