soundManager.url = 'lib/soundmanager/swf/';
soundManager.debugMode = false;
soundManager.useHTML5Audio = true;
var song = false;


$.address.change(url2menu);

$(window).resize(adjust_dimensions);


(function($){
    $.fn.extend({
        center: function () {
            return this.each(function() {
                var top = ($(window).height() - $(this).outerHeight()) / 2;
                var left = ($(window).width() - $(this).outerWidth()) / 2;
                $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
            });
        }
    }); 
})(jQuery);

$(document).ready(function() {	
	$('#stripe_left').mouseover(function(){
		left = setInterval('stripe_left()', 17);
		$('#stripe_right').fadeIn(150);
	}).mouseout(function(){clearInterval(left)});
	$('#stripe_right').mouseover(function(){
		right = setInterval('stripe_right()', 17);
		$('#stripe_left').fadeIn(150);
	}).mouseout(function(){clearInterval(right)});

	$('#stripe .item').fadeTo(0, 0.5);
	$('#stripe .item').mouseenter(function(){
		$(this).fadeTo(150, 1);
	}).mouseleave(function(){
		$(this).fadeTo(150, 0.5);
	})

	$('#stripe .item .video_mask').fadeTo(0, 0.8);
	$('#stripe .item .video_mask').mouseenter(function(){
		$(this).fadeTo(150, 1);
	}).mouseleave(function(){
		$(this).fadeTo(150, 0.8);
	})

	$('#bg img').maxImage({
		isBackground: true,
		overflow: 'auto'
	});

	flag_stripe = true;
	$('#stripe_toggle').bind('click', toggle_stripe);

	$('#stripe').bind('mouseenter', function(){
		$('#stripe_toggle').show();
	}).bind('mouseleave', function(){
		$('#stripe_toggle').hide();
	});

	$('#menu').bind('mouseenter', function(){
		$('#stripe_toggle').show();
	}).bind('mouseleave', function(){
		$('#stripe_toggle').hide();
	});

	$('.video_mask').click(function(e){
		append_video(e.target);
	});

	adjust_dimensions();

	keep_session();
});

function bind_elements() {
	$('#field_nick').focus(function(){
		if($(this).val() == 'Nom / Pseudo')
			$(this).val('');
	}).blur(function(){
		if($(this).val() == '')
			$(this).val('Nom / Pseudo');
	});
	$('#field_commentaire').focus(function(){
		if($(this).val() == 'Commentaire')
			$(this).val('');
	}).blur(function(){
		if($(this).val() == '')
			$(this).val('Commentaire');
	});

	$('a.ext_link').click(function(event){
		event.preventDefault();
		window.open($(this).attr('href'));
	});

	$('.share a.link').click(function(event){
		event.preventDefault();
		window.open($(this).attr('href'));
	});
	$('.share a.bookmark').click(function(event){
		event.preventDefault();
		if(navigator.appName != 'Microsoft Internet Explorer')
			window.sidebar.addPanel(window.document.title, $(this).attr('href'),"");
		else
			window.external.AddFavorite($(this).attr('href'), window.document.title);
	});

	$('.thumb_realsize').unbind('click');
	$('.thumb_realsize').bind('click', function(){
		$('#img_realsize').remove();
		var filename = $(this).attr('src').replace(/(.+)filename=([^&]+)(.*)/g, '$2');
		$('body').append('<img id="img_realsize" src="'+filename+'" alt="img" title="Cliquez sur l\'image pour fermer" onclick="$(this).fadeOut(150).remove();" />');
		$('#img_realsize').delay(150).center().fadeTo(150,1, function(){$('#img_realsize').center();});
	});

	$('.song a').unbind('click').bind('click', function(event){
		event.preventDefault();

		if($(this).hasClass('play')) {
			soundManager.stopAll();
			if(song !== false)
				song.destruct();

			$('.song a.pause').addClass('play').removeClass('pause');
			$('.song a.paused').addClass('play').removeClass('paused');

			$('.song .bar .loaded .progression').css('width', '0px');

			$(this).addClass('pause').removeClass('play');

			var div_song = $(this).parent('.song');

			$('.song.light').css('backgroundColor', 'transparent');
			if(div_song.hasClass('light'))
				div_song.css('backgroundColor', '#f5f5f5');

			$('.song .bar .loaded').unbind('click').css('cursor', 'auto');
			div_song.children('.bar').children('.loaded').bind('click', function(event){
				song.setPosition((event.pageX - $(this).offset().left) * song.duration / $(this).width());
			}).css('cursor', 'pointer');
			$('.song').children('.time').html('--:--');

			song = soundManager.createSound({
				id : $(this).attr('href'),
				url : $(this).attr('href'), volume : 100,
				whileloading : function() {
					div_song.children('.bar').children('.loaded').css('width', (song.bytesLoaded * div_song.children('.bar').width()) / song.bytesTotal + 'px');
				},
				whileplaying : function() {
					div_song.children('.bar').children('.loaded').children('.progression').css('width', (song.position * parseInt(div_song.children('.bar').children('.loaded').width())) /song.duration + 'px');
					act_sec = parseInt(this.position/1000 % 60,10);
					if(act_sec<10) { act_sec = "0"+act_sec; }
					act_min = parseInt(this.position/1000/60,10);
					div_song.children('.time').html(act_min + ':' + act_sec);

				},
				onfinish : function() {
					div_song.children('a').addClass('play').removeClass('pause');
				}
			});



			song.setPosition(0);
			song.togglePause();
		}
		else if($(this).hasClass('pause')) {
			song.togglePause();
			$(this).addClass('paused').removeClass('pause');
		}
		else if($(this).hasClass('paused')) {
			song.togglePause();
			$(this).addClass('pause').removeClass('paused');
		}

	});

}

function bind_menu() {
	$('#menu .item a').mouseenter(function(){
		$(this).children('.bg').animate({marginTop : '-15px' , height : '50px'}, 150);
	}).mouseleave(function(){
		$(this).children('.bg').animate({marginTop : '45px' , height : '0'}, 150);
	});

	$('#menu .item a .bg').each(function(){
		$(this).css('width', $(this).parent().outerWidth() + 'px');
	});
}

function toggle_stripe() {
	$('#stripe_toggle').unbind('click');
	if(!flag_stripe) {
		$('#stripe_content').animate({height : '80px'}, 400);
		$('#stripe').animate({top : '-=80px'}, 400, function(){
			$('#stripe_toggle').children('div').css('backgroundImage', 'url(img/stripe_down.png)');
			flag_stripe = true;
			$('#stripe_toggle').bind('click', toggle_stripe);
		});
	}
	else {
		$('#stripe_content').animate({height : '50px'}, 400);
		$('#stripe').animate({top : '+=80px'}, 400, function(){
			$('#stripe_toggle').children('div').css('backgroundImage', 'url(img/stripe_up.png)');
			flag_stripe = false;
			$('#stripe_toggle').bind('click', toggle_stripe);
		});
	}
}

function url2menu() {
	menu(document.location.hash.substring(3));
}

function menu(selected) {
	var menu = new Array('accueil','news','biographie','musique','photos','videos','presse','partenaires','boutique');

	var menu_tmp = selected.split('/');
	var menu_selected = menu_tmp[0];
	var menu_params = '';
	for(i=1; i<menu_tmp.length; i++)
		menu_params += '/'+menu_tmp[i];	

	if(jQuery.inArray(menu_selected, menu) == -1) {
		document.location.hash = '#!/'+menu[0];
		menu_selected = menu[0];
	}
	if(menu_selected == menu[0]) {
		$('#corps_content').hide(500);
		$('#encart_liens').css('backgroundColor', 'transparent');
		$('#encart_liens').fadeTo(150, 1);
		$('#encart_liens').unbind('mouseenter');
		$('#encart_liens').unbind('mouseleave');
		if(!flag_stripe)
			toggle_stripe();
		bind_elements();
	}
	else {
		if(flag_stripe)
			toggle_stripe();
		
		$('#encart_liens').css('backgroundColor', '#000');
		$('#encart_liens').fadeTo(150, 0.2);
		$('#encart_liens').bind('mouseenter', function(){
			$(this).fadeTo(150, 1);
		});
		$('#encart_liens').bind('mouseleave', function(){
			$(this).fadeTo(150, 0.2);
		});
		$.ajax({url: 'content/'+menu_selected+'/controller.php?params='+menu_params,
			success: function(data) {
				$('#corps_content').html(data);
				$('#corps_content').show(500);
				bind_elements();
				window.document.title = 'April - '+$('.main_titre').last().text();
		}});
	}
	$.ajax({url: 'menu.php?menu='+menu_selected,
		success: function(data) {
		$('#menu').html(data);
		bind_menu();
	}});
}

function scroll_fix_absolute() {
	$('#menu').css('top', $(window).height() + $(window).scrollTop() - $('#menu').height()+'px');

	if(flag_stripe)
		$('#stripe').css('top', $(window).height() + $(window).scrollTop() - $('#menu').height() - $('#stripe_content').height() - $('#stripe_toggle').height() + 'px');
	else
		$('#stripe').css('top', $(window).height() + $(window).scrollTop() - $('#menu').height() - $('#stripe_toggle').height() + 'px');

	$('#teaser').css('top', $(window).height() + $(window).scrollTop() - 200 - $('#teaser').outerHeight());

	$('#encart_liens').css('top', $(window).scrollTop() + 'px');
}

function adjust_dimensions() {
		var minheight = parseFloat($('body').css('minHeight'));
		var minwidth = parseFloat($('body').css('minWidth'));
		window_width = $(window).width() > minwidth ? $(window).width() : minwidth;
		window_height = $(window).height() > minheight ? $(window).height() : minheight;

		if($(window).width() < minwidth || $(window).height() < minheight) {
			$('.fixed').css('position', 'absolute');
			$(window).bind('scroll', scroll_fix_absolute);
			scroll_fix_absolute();
		}
		else {
			$('.fixed').css('position', 'fixed');
			$(window).unbind('scroll');
		}

		$('#menu').css('top', window_height - $('#menu').height()+'px');

		if(flag_stripe)
			$('#stripe').css('top', window_height - $('#menu').height() - $('#stripe_content').height() - $('#stripe_toggle').height() + 'px');
		else
			$('#stripe').css('top', window_height - $('#menu').height() - $('#stripe_toggle').height() + 'px');

		$('#teaser').css('top', window_height - 200 - $('#teaser').outerHeight());

		$('#encart_liens').css('left', window_width - $('#encart_liens').outerWidth() + 'px');

		if(parseFloat($('#stripe .item').last().css('left')) + $('#stripe .item').last().outerWidth() <= window_width)
			$('#stripe_right').hide();

		$('#corps_content').css({'left' : window_width / 2 + 'px' , 'marginLeft' : $('#corps_content').width() / (-2) + 'px'});

		$('#encart_liens').css('top', '0px');

		if($(window).width() < minwidth || $(window).height() < minheight)
			scroll_fix_absolute();
}

function stripe_left() {
	if(parseFloat($('#stripe .item').first().css('left')) > -14) {
		var delta = parseFloat($('#stripe .item').first().css('left')) * -1;
		$('#stripe .item').css({left: function(index, value) { return parseFloat(value) + delta; }});
		clearInterval(left);
		$('#stripe_left').fadeOut(150);
	}
	else
		$('#stripe .item').css({left: function(index, value) { return parseFloat(value) + 15; }});
}
function stripe_right() {
	if(parseFloat($('#stripe .item').last().css('left')) + $('#stripe .item').last().outerWidth() - 15 <= window_width) {
		var delta = parseFloat($('#stripe .item').last().css('left')) + $('#stripe .item').last().outerWidth() - window_width;
		$('#stripe .item').css({left: function(index, value) { return parseFloat(value) - delta; }});
		clearInterval(right);
		$('#stripe_right').fadeOut(150);
	}
	else
		$('#stripe .item').css({left: function(index, value) { return parseFloat(value) - 15; }});
}

function append_video(obj) {
	var tmp = $(obj).attr('alt').split('|');
	var service = tmp[0];
	var id = tmp[1];

	if($('.video_player_centered').get().length > 0)
		$('.video_player_centered').remove();

	if(service == 'youtube')
		$('body').append('<div class="video_player_centered '+id+'"><a href="#" onclick="$(this).parent().remove(); return false;">fermer X</a><object style="display:block;" width="640" height="390"><param name="movie" value="http://www.youtube.com/v/'+id+'?version=3&amp;hl=fr_FR&amp;rel=0&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+id+'?version=3&amp;hl=fr_FR&amp;rel=0&autoplay=1" type="application/x-shockwave-flash" width="640" height="390" allowscriptaccess="always" allowfullscreen="true"></embed></object></div>');

	$('.'+id).css({'left' : window_width/2 + $('.'+id).width()/-2 + 'px' , 'top' : window_height/2 + $('.'+id).height()/-2 + 'px'});

	makeDraggable($('.video_player_centered'));
}

function makeDraggable(element) {
	element.mousedown(function(event){
		var div = $(this);
		var x_relative = event.pageX - div.offset().left;
		var y_relative = event.pageY - div.offset().top;
		$(window).bind('mousemove', function(event){
			div.offset({left : event.pageX - x_relative , top : event.pageY - y_relative});
		});
		$(window).mouseup(function(){
			$(window).unbind('mousemove');
		});
	});
}

function destroy_popup() {
	$('#popup').fadeOut(200, function(){$('#popup').remove();});
	$('#popup_bg').fadeOut(200, function(){$('#popup_bg').remove();});
}

function popup(txt) {
	$('body').append('<div id="popup_bg" onclick="destroy_popup()"></div><div id="popup"><a href="#" onclick="destroy_popup();return false;">x</a>'+txt+'</div>');
	$('#popup').center();
	$('#popup_bg').fadeIn(200);
	$('#popup').fadeIn(200);
}

function send_commentaire(obj) {
	var menu_tmp = $(obj).attr('action').substring(3).split('/');
	var menu_selected = menu_tmp[0];
	var menu_params = '';
	for(i=1; i<menu_tmp.length; i++)
		menu_params += '/'+menu_tmp[i];


	if(obj.field_nick.value == '' || obj.field_commentaire.value == '')
		popup('Un champ n\'est pas rempli.');
	else {
		$.ajax({url: 'content/send_commentaire.php',
			type: 'POST',
			data: 'nick='+obj.field_nick.value+'&commentaire='+obj.field_commentaire.value+'&url='+$(obj).attr('action'),
			success: function(data) {
				if(data == 'ok') {
					$.ajax({url: 'content/'+menu_selected+'/controller.php?params='+menu_params,
						success: function(data2) {
							$('#corps_content').html(data2);
							bind_elements();
					}});
				}
				else
					popup('Une erreur est survenue. '+data);	
		 	}
		});
	}
}

function add_panier(article) {
	$.ajax({url: 'content/boutique/add_article.php',
		type: 'POST',
		data: 'article='+article,
		success: function(data) {
			$('#col_panier').fadeTo(150,0, function(){
				$('#col_panier').html(data).delay(150).fadeTo(150,1);
				$('#msg_add_'+article).fadeIn(150).delay(1000).fadeOut(2000);
			});
	 	}
	});
}

function remove_panier(article) {
	$.ajax({url: 'content/boutique/remove_article.php',
		type: 'POST',
		data: 'article='+article,
		success: function(data) {
			$('#col_panier').fadeTo(150,0, function(){
				$('#col_panier').html(data).delay(150).fadeTo(150,1);
			});
	 	}
	});
}

function keep_session(){
	$.ajax({url: 'lib/keep_session.php',
		success: function(data) {
			setTimeout('keep_session()', 1000*60*15);
	 	}
	});
}

function valid_checkout() {
	var erreur = '';
	if(isNaN(parseFloat($('#frm_paypal [name="amount"]').val())) || parseFloat($('#frm_paypal [name="amount"]').val()) == 0)
		erreur += 'Le montant est nul. Votre panier est vide ?<br />';
	if($('#field_nom').val() == '' || $('#field_nom').val() == 'Nom')
		erreur += 'Le champ "Nom" n\'est pas correctement rempli.<br />';
	if($('#field_prenom').val() == '' || $('#field_prenom').val() == 'Prénom')
		erreur += 'Le champ "Prénom" n\'est pas correctement rempli.<br />';
	if($('#field_adresse').val() == '' || $('#field_adresse').val() == 'Adresse')
		erreur += 'Le champ "Adresse" n\'est pas correctement rempli.<br />';
	if(!$('#field_cp').val().match(/^[0-9]{5}$/))
		erreur += 'Le champ "Code postal" n\'est pas correctement rempli (ex: 75000).<br />';
	if($('#field_ville').val() == '' || $('#field_ville').val() == 'Ville')
		erreur += 'Le champ "Ville" n\'est pas correctement rempli.<br />';
	if(!$('#field_tel').val().match(/[+ .0-9-]{8,}/))
		erreur += 'Le champ "Téléphone" n\'est pas correctement rempli.<br />';
	if(!$('#field_mail').val().match(/^[^@%*<> ]+@[^@%*<> ]{2,255}\.[^@%*<> ]{2,100}$/))
		erreur += 'Le champ "E-mail" n\'est pas correctement rempli. (ex: exemple@domaine.extension)';
	if(erreur != '') {
		popup(erreur);
		return false;
	}
	else {
		$.ajax({url: 'content/boutique/save_infos_commande.php',
			type: 'POST',
			data: 'nom='+$('#field_nom').val()+'&prenom='+$('#field_prenom').val()+'&adresse='+$('#field_adresse').val()+'&cp='+$('#field_cp').val()+'&ville='+$('#field_ville').val()+'&telephone='+$('#field_tel').val()+'&mail='+$('#field_mail').val(),
			success: function(data) {
				$('#frm_paypal').submit();
		 	}
		});
	}
}

