$(document).ready(function(){
	
	var ua = navigator.userAgent.toLowerCase();
	var check = function(r){
            return r.test(ua);
	}
	var isIE9 = Ext.isIE && check(/msie 9/);

	if (Ext.isIE6 && !isIE9) {
		
		var IE6Panel = Ext.get('IE6isEvil');
		var panelHeight = Ext.get('footer').getBottom();
		var target;
		var current;
		
		IE6Panel.setHeight(panelHeight);
		
		Ext.get('IE6isEvil_langBtn').addListener('click', function(e){
			if (e.target.innerHTML == 'English') {
				current = 'fr';
				target = 'en';
			}
			else {
				current = 'en';
				target = 'fr';
			}
			
			Ext.get('IE6isEvil_langBtn_'+current).fadeOut({
				useDisplay:true,
				callback : function(){
					Ext.get('IE6isEvil_langBtn_'+target).fadeIn({useDisplay:true});
				}
			});
			
			Ext.get('IE6isEvil_closeBtn_'+current).fadeOut({
				useDisplay:true,
				callback : function(){
					Ext.get('IE6isEvil_closeBtn_'+target).fadeIn({useDisplay:true});
				}
			});
			
			Ext.get('IE6isEvil_'+current).fadeOut({
				useDisplay:true,
				callback : function(){
					Ext.get('IE6isEvil_'+target).fadeIn({useDisplay:true});
				}
			});
		});
		Ext.get('IE6isEvil_closeBtn').addListener('click', function(e){IE6Panel.hide(true);});
		
		IE6Panel.show(true);
	}
	
	$("a").attr('title', '');	// enleve l'attribut titre des liens
	$("img").attr('title', '');	// enleve l'attribut titre des images
	
	/* GESTION DE L'EFFET PARALLAX */
	var $sections = $('#wrapper > .section'),
	navlocations = new Array($sections.length);
	$sections.each(function(i)
	{
			var $this = $(this),
			winH = parseInt($(window).height() / 3);
			navlocations[i] = { "start":parseInt($this.offset().top) - winH, "stop":parseInt($this.offset().top) + parseInt($this.height()), "id":$this.attr('id'),"isactive":false };
		});
	$(window).scroll(function(){
	for(var i in navlocations)
	{
		var scrolltop = $(window).scrollTop();
		if (scrolltop >= navlocations[i].start && scrolltop <= navlocations[i].stop)
		{
			$('#inner-nav ul li a.active').removeClass('active');
			$('#inner-nav #'+navlocations[i].id+'-nav').addClass('active');
		}
		else if (scrolltop >= navlocations[i].stop)
		{
			$('#nav-inner ul li a.active').removeClass('active');
		}
	}
	});

						   
	$('.para-element').each(function(){
					
		$(this).parallax({ 
			'coeff': $(this).attr('data-offset'),
			'stop': $(this).parents('.section').offset().top + $(this).parents('.section').height(),
			'start': $(this).parents('.section').offset().top - $(window).height()
		});
	
	});
	

	$('.para-image').each(function(){
	
		$(this).parallax({ 
			'coeff': $(this).attr('data-offset'),
			'stop': $(this).parents('.section').offset().top + $(this).parents('.section').height(),
			'start': $(this).parents('.section').offset().top - $(window).height(),
			'type' : 'image'
		});
	
	});
	
	
	
	/* MET L'EFFET DE HOVER DANS TOUR */
	$('.tour_list_line').hover(function(e){
		e.currentTarget.style.backgroundColor = "#0f0f0f";
	}, function(e){
		
		e.currentTarget.style.backgroundColor = "";
	});
	
	/* HOVER SUR LES LIGNES MUSIC */
	$('.music_line').hover(function(e){
		e.currentTarget.style.backgroundColor = "#0d0d0d";
	},function(e){
		e.currentTarget.style.backgroundColor = "";
	});
	
	/* AFFICHE LES IMAGES QUAND ON CLICK SUR LE COVER DE L'ALBUM */
	$('.album_display').click(function(e){
		showAlbum(e.currentTarget.id);
	
	});

	/* BOUTON RETOUR AUX ALBUMS */
	$('#gallery_back_btn').click(function(){
		$('#gallery_display_photos').fadeOut(300,function(){
		$('#gallery_display_albums').fadeIn(300);});
	});
	
	/* FONCTIONS SCROLLTO POUR FAIRE "glisser" QUAND ON CLIC DANS LE MENU */
	$('#navbar ul li a').click(function(e){
		var rel = e.currentTarget.rel;
		$.scrollTo($('#'+rel), 2500);

	});

	/* FAIT DÉFILER LES NEWS */
	if($('.slide_news').length > 1){
		$('.banner_controler').css('visibility', 'visible');
		$('.banner_controler').css('visibility', 'visible');
		
		$('#banner_center').cycle({
			fx : 'scrollHorz',
			timeout : 0,
			next : '#banner_controler_to_right',
			prev : '#banner_controler_to_left'
		});
	}
	
	/* HOVER SUR LES IMAGES DANS LA BANDE DE DROITE POUR LES RÉSEAUX SOCIAUX */
	$('#social_share div img').hover(function(e){
		e.currentTarget.src = e.currentTarget.src.replace('up', 'down');
	},function(e){
		e.currentTarget.src = e.currentTarget.src.replace('down', 'up');
	});
	
	
	/* AFFICHE LES LYRICS POUR UNE CHANSON CLIQUÉE */
	$('.music_lyrics_col').live('click',function(e){
		var id_song = e.currentTarget.id;
		showLyrics(id_song);
	});
	
	/* AFFICHE LE POPUP POUR UNE CHANSON NON PARRUES */
	$('.music_soon_btn').live('click',function(e){
		showMusicNotReleasedPopup();
	});
	
	/* VERIFIE SI ON A CLIQUÉ À L'EXTERIEUR DU POPUP ET LE FERME */
	$(document).click(function(e){
		var divLeft = 0, divRight = 0, divTop = 0, divBottom = 0;
		if ( $('#lyrics').is(':visible') ) {
			divLeft = $('#lyrics').offset().left;
			divRight = divLeft + $('#lyrics').width();
			divTop = $('#lyrics').offset().top + 45;
			divBottom = divTop + $('#lyrics').height();
			if ( $(e.target).is('#lyrics') || ( divLeft < e.pageX && e.pageX < divRight && divTop < e.pageY && e.pageY < divBottom ) ) {
				return;
			}
			else {
				$('#lyrics').remove();
				$('#music .content_container').append('<div id="lyrics" style="display:none;" class="flexcroll"><div id="lyrics_close_btn"></div></div>');
				$(window).unbind("mousewheel"); // reactive le scroll
			}
		}
		else if ( $('#not_released_popup').is(':visible') ) {
			divLeft = $('#not_released_popup').offset().left;
			divRight = divLeft + $('#not_released_popup').width();
			divTop = $('#not_released_popup').offset().top +45;
			divBottom = divTop + $('#not_released_popup').height();
			if ( $(e.target).is('#not_released_popup') || e.target.className == 'music_soon_btn' || ( divLeft < e.pageX && e.pageX < divRight && divTop < e.pageY && e.pageY < divBottom ) ) {
				return;
			}
			else {
				$('#not_released_popup').hide();
			}
		}
	});
	
	/* EMPECHE LE SCROLL DU DOCUMENT LORS DU SCROLL DES ALBUMS */
	$('#gallery_display_albums').bind("mouseenter", function(){
		albumPreventScroll('albums');
	});
	
	$('#gallery_display_photos').bind("mouseenter", function(){
		albumPreventScroll('albums');
	});
	
	$('#gallery_display_albums').bind("mouseleave", function(){
		$(window).unbind("mousewheel");
	});
	
	$('#gallery_display_photos').bind("mouseleave", function(){
		$(window).unbind("mousewheel");
	});
	
	/* SI ON A DES TOURNÉES, ON RAJOUTE DE LA MARGE A CELLE DE GAUCHE */
	if($('.tour_block').length > 0){
		var first_col_tour = $('.tour_block');
		first_col_tour = first_col_tour[0];
		first_col_tour.style.marginRight = '15px';
	}
	
	/* HOVER SUR LES IMAGES DANS LES ALBUMS */
	$('.album_display_hover').live({mouseenter:function(e){
		var id = e.currentTarget.parentNode.id;
		$('#'+id).css('background-image', 'url(wp-content/themes/marilou/images/album_background_out.png)');
	}, mouseleave:function(e){
		var id = e.currentTarget.parentNode.id;
		$('#'+id).css('background-image', 'url(wp-content/themes/marilou/images/album_background_over.png)');
	}});
	
	/* AFFICHE LE MENU QUAND TOUT EST PRET */
	// Idéalement, il faudrait vérifier si toutes les images sont loadés
	$('#navbar').css('visibility', 'visible');
	
	if (Ext.get('newsletter_form')) {
		manageFields(Ext.get('nl_email').dom, 'init',  mbiz.lang.nl_email);
		Ext.get('nl_email').addListener('focus',function(e){manageFields(e.target, 'focus',  mbiz.lang.nl_email);});
		Ext.get('nl_email').addListener('blur',function(e){manageFields(e.target, 'blur',  mbiz.lang.nl_email);});
	}
	if (Ext.get('not_released_popup_nl')) {
		manageFields(Ext.get('nrp_nl_email').dom, 'init',  mbiz.lang.nl_email);
		Ext.get('nrp_nl_email').addListener('focus',function(e){manageFields(e.target, 'focus',  mbiz.lang.nl_email);});
		Ext.get('nrp_nl_email').addListener('blur',function(e){manageFields(e.target, 'blur',  mbiz.lang.nl_email);});
	}
	
	if ($('#home_loading')) {
		/*var yCoor = Ext.get('footer').getTop();
		Ext.get('home_loading').setHeight(yCoor);*/
		setTimeout("removeLoading()", 500);
	}
	
	setTimeout("showHomeIcon()",800);
	
});

function showHomeIcon() {
	Ext.get('nav_home').show();
}

function albumPreventScroll(target, bypass) {
	
	$(window).unbind("mousewheel");
	
	if (bypass === true || $('#gallery_display_'+target+'_vscrollerbase').css('visibility') == 'visible') {
		$(window).bind("mousewheel", function() { return false; });
	}
	
}

function removeLoading() {
	/*
	$('#home_loading').slideUp({
		duration: 2000,
		complete: function(){$(this).remove();}
	});
	$('#banner_center').css('visibility', 'visible');
	*/
	$('#banner_center').css('display', 'none');	// Impossible de le mettre dans le CSS sinon au chargement les elements ne se placent pas bien.
	$('#banner_center').css('visibility', 'visible');
	$('#home_loading').fadeOut({
		duration: 1750,
		complete: function(){
			$(this).remove();
		}
	});
	$('#banner_center').fadeIn({
		duration: 1500
	});
}

function showAlbum(id_album){
	// Load les images avec AJAX
	var lang = Ext.get('c_lang').dom.innerHTML;
	var id_album = id_album.split('-');
	id_album = id_album[1];
	
	$.ajax({
		url : 'wp-content/themes/marilou/ajax/album_task.php',
		type : 'POST',
		data : 'task=getPhotos&id_alb='+id_album+'&lang='+lang,
		dataType : 'json',
		success : function(response){
			var arr_photos = response.arr_photos;
			var html = "";
			for(var i = 0; i <  arr_photos.length; i++){
					
				html += "<div id='pic-"+arr_photos[i]['ID']+"'class='photo_display float_left'>";
                html += arr_photos[i]['thumb'];
                html += "<div class='album_title'>"+arr_photos[i]['post_title']+"</div>";
                html += "<a href='"+arr_photos[i]['large']+"' title='"+arr_photos[i]['post_title'].replace("'", " ")+"-|-"+arr_photos[i]['post_content'].replace("'", " ")+"'><div class='album_display_hover'></div></a>";
                html += "</div> ";
			}
			
			$('.photo_display').remove();
			$('#gallery_back_btn').after(html+'<div class="clear_float"></div>');
			
			albumPreventScroll('photos', true);
			
			$('#gallery_display_albums').fadeOut(300,function(){
				$('#gallery_display_photos').fadeIn(300, function(){fleXenv.fleXcrollMain("gallery_display_photos");});
			});
			
			$('.photo_display a').lightBox();
		}
	});
}

function showLyrics(id_song){
	var yCoor = 0;
	var id_song = id_song.split('-');
	id_song = id_song[1];
	
	$.ajax({
		url : 'wp-content/themes/marilou/ajax/music_task.php',
		type : 'POST',
		data : 'task=getLyrics&id_song='+id_song,
		dataType : 'json',
		success : function(response){
			var title = urldecode(response.title);
			var lyrics = urldecode(response.lyrics);
			//var lyrics = response.lyrics;
			$('#lyrics').html("");
			$('#lyrics').html('<div id="lyrics_header"><div id="lyrics_close_btn"></div><span class="title">'+title+'</span></div>'+lyrics+'<p class="clear_float"></p>');
			if(!$('#lyrics').is(":visible")){
				yCoor = $('#music').position().top;
				$.scrollTo(yCoor + 375, 1000);
				$('#lyrics').fadeIn(300, function(){
					fleXenv.fleXcrollMain("lyrics");
					$(window).bind("mousewheel", function() {
						return false;	// desactive le scroll
					});
				});
			}
		}
	});
}

function showMusicNotReleasedPopup(){
	
	if(!$('#not_released_popup').is(":visible")){
		yCoor = $('#music').position().top;
		$.scrollTo(yCoor + 375, 1000);
		$('#not_released_popup').fadeIn(300);
	}
	
}

/* UTILE POUR RÉCUPERER LES LYRICS */
function urldecode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +   improved by: Orlando
    // %        note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
    
    var replacer = function (search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The hash_map is identical to the one in urlencode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';
    hash_map['%20'] = '+';
    hash_map['\u00DC'] = '%DC';
    hash_map['\u00FC'] = '%FC';
    hash_map['\u00C4'] = '%D4';
    hash_map['\u00E4'] = '%E4';
    hash_map['\u00D6'] = '%D6';
    hash_map['\u00F6'] = '%F6';
    hash_map['\u00DF'] = '%DF';
    hash_map['\u20AC'] = '%80';
    hash_map['\u0081'] = '%81';
    hash_map['\u201A'] = '%82';
    hash_map['\u0192'] = '%83';
    hash_map['\u201E'] = '%84';
    hash_map['\u2026'] = '%85';
    hash_map['\u2020'] = '%86';
    hash_map['\u2021'] = '%87';
    hash_map['\u02C6'] = '%88';
    hash_map['\u2030'] = '%89';
    hash_map['\u0160'] = '%8A';
    hash_map['\u2039'] = '%8B';
    hash_map['\u0152'] = '%8C';
    hash_map['\u008D'] = '%8D';
    hash_map['\u017D'] = '%8E';
    hash_map['\u008F'] = '%8F';
    hash_map['\u0090'] = '%90';
    hash_map['\u2018'] = '%91';
    hash_map['\u2019'] = '%92';
    hash_map['\u201C'] = '%93';
    hash_map['\u201D'] = '%94';
    hash_map['\u2022'] = '%95';
    hash_map['\u2013'] = '%96';
    hash_map['\u2014'] = '%97';
    hash_map['\u02DC'] = '%98';
    hash_map['\u2122'] = '%99';
    hash_map['\u0161'] = '%9A';
    hash_map['\u203A'] = '%9B';
    hash_map['\u0153'] = '%9C';
    hash_map['\u009D'] = '%9D';
    hash_map['\u017E'] = '%9E';
    hash_map['\u0178'] = '%9F';
    hash_map['\u00C6'] = '%C3%86';
    hash_map['\u00D8'] = '%C3%98';
    hash_map['\u00C5'] = '%C3%85';

    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);

    return ret;
}

function manageFields(el, action, dval) {
	
	if (action == 'init') {
		if (el.style.setAttribute) {	// IE
			el.style.setAttribute('color','silver');
			el.value = dval;
		}
		else {
			el.style.setProperty('color','silver', null);
			el.value = dval;
		}
	}
	else if (action == 'focus') {
		if (el.value == dval) {
			if (el.style.removeAttribute) { // IE
				el.style.removeAttribute('color');
				el.value = '';
			}
			else {
				el.style.removeProperty('color');
				el.value = '';
			}
		}
	}
	else if (action == 'blur') {
		if (el.value == '') {
			if (el.style.setAttribute) {	// IE
				el.style.setAttribute('color','silver');
				el.value = dval;
			}
			else {
				el.style.setProperty('color','silver', null);
				el.value = dval;
			}
		}
	}
	
}

function submitNewsletter(opt) {
	
	var dh = Ext.DomHelper;
	
	var email_el	= Ext.get('nl_email');
	var email		= email_el.dom.value;
	var url			= Ext.get('nl_url').dom.value;
	var err			= 'nl_errorMsg';
	var msg			= '';
	
	if (opt && opt == 'nrp') {
		email_el	= Ext.get('nrp_nl_email');
		email		= email_el.dom.value;
		url			= Ext.get('nrp_nl_url').dom.value;
		err			= 'nrp_nl_errorMsg';
	}	
	
	if(email != "" && email != mbiz.lang.nl_email){
		
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				
		if(filter.test(email) == false){
			msg =  mbiz.lang.nl_invalid_email;
		}else{
			Ext.Ajax.request({
				url : url+'/wp-content/themes/marilou/ajax/nl_task.php',
				method : 'POST',
				params : {
					email	: email,
					task	: 'newsletter_add'
				},
				success : function(response, options){
					var responseData = Ext.decode(response.responseText);
					
					if(responseData.success === true){
						msg = mbiz.lang.nl_success;
						
						email_el.dom.value = "";
					}else{
						msg = mbiz.lang.nl_error;
					}
					dh.overwrite(err, msg);
				}
			});
		}
	}
	else{
		msg = mbiz.lang.nl_required;
	}
	
	if(msg != ""){
		var dh = Ext.DomHelper;
		dh.overwrite(err, msg);
	}
	
}

function pScrollTo(y) {
	
	$.scrollTo(y, 1000);

}

