var currentGalerie = null;
var lastGalerie = '';
var lastUrlArray = [];
var isTouchScreen = 0;

var lastImage = '';

var imagesLeft = new Array();

var logged = false;

$(function(){
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
 		isTouchScreen = 1;
 	}
	

	$(this).bind("contextmenu", function(e) {
		e.preventDefault();
	});
    
	
	
	auChargement();
	
	var url =  window.location.pathname.split('/');
	currentGalerie = url[1];

	if(url.length > 3){
		$('#detail').css('top', '-'+$('#detail').height()+'px');
		$('#detail').animate({ "top": "0px"}, 500);
	}
	
	lastUrlArray = trimArray(url);
	
	$('.galerieLink').hover(function(event){
			var url = $(this).attr('href').split('/');
			changeAdresse(url[1]);
		},function(event){
			if(currentGalerie != ''){
				changeAdresse(currentGalerie);
			}
			else{
				$("#adresse").html('');
			}
	});
	
	if(logged){
		$('#connection_button').attr('src','/style/images/A3.png');
	}

	$('#co').click(function() {
		if(logged){
			logged = false;
			$.post('/logoff', {'AJAX':'AJAX'});
			$('#connection_button').attr('src','/style/images/A2.png');
		}
		else{
			$('#connection').animate({"top": '0px'}, 500);
		}
	});
	
	$('.connection').click(function() {
		$.post('/login', {'AJAX':'AJAX', 'user':$('input[name="username"]').val(), 'pass':$('input[name="password"]').val()}, function(data) {
			if(data == 'ok'){
				$('#connection').animate({"top": '-' + $('#connection').height() + 'px'}, 500);
				
				logged = true;
				$('#connection_button').attr('src','/style/images/A3.png');
				
				$('input[name="username"]').val('');
				$('input[name="password"]').val('');
			}
			else{
				alert('Compte inconnu.');
			}
		});
	});
	
	$('.fermer a').click(function() {
		$('#connection').animate({"top": '-' + $('#connection').height() + 'px'}, 500);
	});
});

var timer = null;
function hoverTimer(img)
{
	if(timer != null){
		hoverStopTimer();
	}
	
	timer = setTimeout(function(){
		$('#image2').stop(true, true);
		$('#image2').hide();
		$('#image2').css('background-image', 'url(/files/right/'+ img + ')');
		$('#image2').fadeIn(300);
	}, 300);
}

function hoverStopTimer(){
	clearTimeout(timer);
	timer = null;
}

function scrollCheck(element)
{
	$('.scrollarea', element).each(function(){
		var box = $(this);

		var totalH = 550;
		if($('#menu').length == 0){
			totalH+= 105;
		}
		else if($(this).parent().hasClass('bio')){
			totalH = 420;
		}
		
		var max = totalH - box.position().top;
		
		var startHeight = max;
		
		box.parent('.bio').css("display", "block");
			
		box.css("height", "auto");
		var maxHeight = box.height();
		box.height(startHeight);
		
		box.parent('.bio').css("display", "none");
		
		box.children('p').children('iframe, img').load(function() {
			$(this).height($(this).height()/$(this).width()*box.width());
			$(this).width(box.width());
			
			if(startHeight > maxHeight){
				scrollCheck(element);
			}
			
			startHeight = max;
			box.css( "height", "auto" );
			maxHeight = box.height();
			box.height( startHeight );
		});
		
		box.css({'overflow':'hidden'});
		
		if(maxHeight > startHeight && box.parent().children('.scroll').length == 0){
			box.height(startHeight);
			box.wrap('<div id="scrollbox"></div>');
			box.before('<div class="scroll"><div class="scrollbar"></div></div>');
			box.css({'margin-right':'15px'});
			
			
			var sb = $('.scrollbar');
			var min = sb.position().top;

			if(totalH == 425){
				min = 86;
			}
			
			var ht = startHeight;
			
			box.parent().children().height(ht);
			
			var maxTopScroll = ht - 14;

			
			box.bind('mousewheel', function(event, delta) {
				var sb = $('.scrollbar');
				sb.css({'top': Math.max(0, Math.max(0, Math.min(maxTopScroll, parseFloat(sb.css('top')) - delta*20)))+'px'});
				
				box.scrollTop((maxHeight-box.height())*(parseFloat(sb.css('top'))/maxTopScroll));
				event.preventDefault();
			});
		}
		
		var e= element.children('.liste');
		var h = e.height();
		
		e.css({"overflow":"hidden", "height": "0", "opacity": "0"});
		e.animate({opacity:1, height: h}, 1500, function(){
			$(this).height('auto'); 
			
			box.css( "height", "auto" );
			maxHeight = box.height();
			box.height( startHeight );
		});
	});
}

function auChargement(element)
{
	if(element == undefined){
		var element = $('*');
	}
	
	// S'il s'agit d'un iPhone/iPad
	if (isTouchScreen == 1){
		$('.scrollarea').touchScroll(); // On ne custom pas la scrollbar vu qu'elle ne s'affiche pas sur iPhone/iPad
	}
	else{
		scrollCheck(element); // Sinon on utilise un custom pour la scrollbar
	}

	$('a:not(.disabled)', element).click(function(event){
		var url = $(this).attr('href');
		if(typeof url == "string"){
			if(url.indexOf('http://') == -1){
				event.preventDefault();
				gotoUrl($(this).attr('href'));
			}
		}
	});
	
	if(lastGalerie != currentGalerie){
		var $menuback = $('#menuback');
		var $menu = $('.menu');
		
		var width = $menuback.width();
		var height = $menu.height();
		
		$menuback.css({ 'width': '180px'});
		$menu.css({'opacity': 0, 'height': 0, "background":"white"});
		
		$menuback.animate({'width': width}, 1000, function(){
			$menu.animate({'opacity': 1, 'height': height}, 1000);
		});
	}
	
	if(lastImage != ''){
		if($('#image').css('background-image') != $('#image2').css('background-image')){
			$('#image').css('background-image', lastImage);
			$('#image2').hide();
			$('#image2').fadeIn(2000, function() {$('#image').css('background-image', $(this).css('background-image'));});
		}
		else{
			lastImage = $('#image').css('background-image');
		}
	}
	
	lastImage = $('#image2').css('background-image');
	
	$('#image #bouton').hide();
	$('#image #bouton').fadeIn(2000);
	
	/*--- GESTION HOVER MENU ---*/
	$('.galerie').hover(function(){
		if($(this).attr('src') != '/files/menu/'+$(this).attr('id')+'-on.png'){
			$(this).attr('src', '/files/menu/'+$(this).attr('id')+'-hover.png');

			hoverTimer(galeries[$(this).attr('id')]["image"]);
		}
	},function(){
		if($(this).attr('src') != '/files/menu/'+$(this).attr('id')+'-on.png'){
			hoverStopTimer();
			
			$(this).attr('src', '/files/menu/'+$(this).attr('id')+'-off.png');
			$('#image2').stop(true, true);
			$('#image2').show();
			$('#image2').fadeOut(300, function() {
				if(lastImage != '')
				{
					$('#image2').css('background-image', lastImage);
					$('#image').css('background-image', lastImage);
				}
			});
		}
	});
	
	$('.scrollarea ul li', element).hover(function(){
		var id = $(this).index();
		if(imagesLeft[id] != ""){
			hoverTimer(imagesLeft[id]);
		}
	},function(){
		var id = $(this).index();
		if(imagesLeft[id] != ""){
			hoverStopTimer();
			
			$('#image2').stop(true, true);
			$('#image2').show();
			$('#image2').fadeOut(300, function() {
				if(lastImage != ''){
					$('#image2').css('background-image', lastImage);
					$('#image').css('background-image', lastImage);
				}
			});
		}
	});
	
	
	$("a.showbio").unbind('click').bind('click', function(e){
		//animate({"opacity": "1"});
		$(".bio").fadeIn();
		$(".imgbloc").fadeOut();
		$(this).hide();
		$("a.showpic").show();
		$("a.showrev").show();
		e.preventDefault();
	});

	$("a.showpic").unbind('click').bind('click', function(e){
		$(".bio").fadeOut();
		$(".imgbloc").fadeIn();
		$(this).hide();
		$("a.showbio").show();
		e.preventDefault();
	});
	
	$("a.showrev").unbind('click').bind('click', function(e){
		$(".bio").fadeOut();
		$(".imgbloc").fadeIn();
		$(this).hide();
		$("a.showbio").show();
		e.preventDefault();
	});
	
	$(".medias img").unbind('mouseenter').bind('mouseenter', function(e){
		if(parseFloat($(this).css('opacity')) == 1){
			$(this).css('opacity', 0.4);
		}
	});
	
	$(".medias img").unbind('mouseleave').bind('mouseleave', function(e){
		if(parseFloat($(this).css('opacity')) >= 0.4){
			$(this).css('opacity', 1);
		}
	});
	
	$('#contact_envoyer').click(function() {
		var error = false;
		
		if($.trim($('.contactform input[name="nom"]').val()) == '') {
			$('#label_nom').css('color', 'red');
			error = true;
		}
		else {
			$('#label_nom').css('color', '#666666');
		}
		
		if($.trim($('.contactform input[name="prenom"]').val()) == '') {
			$('#label_prenom').css('color', 'red');
			error = true;
		}
		else {
			$('#label_prenom').css('color', '#666666');
		}
		
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if(reg.test($('.contactform input[name="email"]').val()) == false) {
			$('#label_email').css('color', 'red');
			error = true;
		}
		else {
			$('#label_email').css('color', '#666666');
		}
		
		if(!error) {
			var arr = {'AJAX':'AJAX', 'contact':'contact'};
			
			$('.contactform input').each(function() {
				arr[$(this).attr('name')] = $(this).val();
			});
			
			$('.contactform select').each(function() {
				arr[$(this).attr('name')] = $('option:selected', this).val();
			});
			
			$('.contactform textarea').each(function() {
				arr[$(this).attr('name')] = $(this).val();
			});
			
			$.post('/login', arr, function(data) {
				$('#contact').html(data);
			});
		}
	});
	
	if($.browser.msie || $.browser.opera) {
		$('.galerieLink').css('margin-left', '-1px');
	}
	
	$('iframe', element).attr('src', $('iframe', element).attr('src') + '?wmode=transparent');
	
	$('p a', element).attr('target','_blank');
}

/*--- CHANGEMENT ADRESSE TEXTE GALERIE ---*/
function changeAdresse(url){
	if(url != '' && url != undefined)
	{
		var galerie = galeries[url];
		
		var nom = galerie["nom"];
		var adr = galerie["adresse"];
		var adr2 =  galerie["adresse2"];
		var tel = galerie["tel"];
		var fax = galerie["fax"];
		var email = galerie["email"];
		
		var html = '';
		
		if(nom != "") html+= '<h2>' + nom + '</h2>';
		if(adr != "") html+= '<h3>' + adr + '</h3>';
		
		html+= '<p>';
		
		if(adr != "") html+= '' + adr + '<br/>';
		if(adr2 != "") html+= '' + adr2 + '<br/>';
		if(tel != "") html+= 'Tel : ' + tel + '<br/>';
		if(fax != "") html+= 'Fax : ' + fax + '<br/>';
		if(email != "") html+= '<span class="email">Email : ' + email + '</span>';
		
		html+= '</p>';
		$("#adresse").html(html);
	}
	else if(url != undefined)
	{
		$("#adresse").html('');
	}
}

function gotoUrl(url, pop){
	if(url != ''){
		$('#connection').animate({"top": '-' + $('#connection').height() + 'px'}, 500);
	}
	
	_gaq.push(['_trackPageview', url]);
	
	var urlArray = url.split('/');
	var galerie = urlArray[1];

	if(galerie != '' && galerie != undefined){
		lastGalerie = currentGalerie;
		currentGalerie = galerie;
		
		changeAdresse(galerie);
		
		for(key in galeries){
			if(key != galerie){
				$("#"+key).attr('src', '/files/menu/' + key + '-off.png');	
			}
		}
		$("#"+galerie).attr('src', '/files/menu/' + galerie + '-on.png');
		
		if(pop != false){
			try{
				window.history.pushState(url, "Promenarts", url);
			}
			catch(e){}
		}
	
		urlArray = trimArray(urlArray);
	
		if(urlArray.length > 2 && (urlArray[1] == 'artistes' || urlArray[1] == 'expositions' || urlArray[1] == 'archives')){
			if(lastUrlArray[1] != urlArray[1]){
				$.post(url, {'AJAX':'AJAX'}, function(data) {
					$('#ajax').html(data);
					$('#detail').css('top', '-' + $('#detail').height() + 'px');
					$('#detail').animate({ "top": "0px"}, 500);
					auChargement($('#ajax'));
					lastUrlArray = urlArray;
				});
			}
			else if(urlArray.length > 3 && urlArray[0] == 'editions'){
				$.post(url, {'AJAX':'AJAX', 'DETAIL':'DETAIL', 'REVUES':'REVUES'}, function(data) {
					$('#revuesAjax').html(data);
					$rev = $('#revues li.revue');
					$rev.css({"opacity": "0"});
					$('#revues li.revue:first').animate({"opacity": "1"}, 800);
					setTimeout(function(){changeOpacity($('#revues li.revue:first'));}, 150);
					function changeOpacity(t){
						n = $(t).next('#revues li.revue');
						n.animate({"opacity": "1"}, 800);
						if(n.index() > t.index()){
							setTimeout(function(){changeOpacity(n);}, 150);
						}
					}
					auChargement($('#revuesAjax'));
				});
			}
			else if(urlArray.length > 3){
				$.post(url, {'AJAX':'AJAX', 'DETAIL':'DETAIL', 'MEDIAS':'MEDIAS'}, function(data) {
					$('#mediasAjax').html(data);
					$img = $('.medias img');
					$img.css({"opacity": "0"});
					$('.medias img:first').animate({"opacity": "1"}, 800);
					setTimeout(function(){changeOpacity($('.medias img:first'));}, 150);
					function changeOpacity(t){
						n = $(t).next('.medias img');
						n.animate({"opacity": "1"}, 800);
						if(n.index() > t.index()){
							setTimeout(function(){changeOpacity(n);}, 150);
						}
					}
					auChargement($('#mediasAjax'));
				});
			}
			else{
				$.post(url, {'AJAX':'AJAX', 'DETAIL':'DETAIL'}, function(data) {
					$('#detail').html(data);
					$('#detail').css('top', '-' + $('#detail').height() + 'px');
					$('#detail').animate({ "top": "0px"}, 500);
					auChargement($('#detail'));
					lastUrlArray = urlArray;
				});
			}
		}
		else if(lastUrlArray.length > 2 && (lastUrlArray[1] == 'artistes' || lastUrlArray[1] == 'expositions' || lastUrlArray[1] == 'archives')){
			$('#detail').animate({
					"top": '-' + $('#detail').height() + 'px'
				}, 500, 
				function() {
					if(lastUrlArray[1] != urlArray[1] || lastUrlArray[0] != urlArray[0])
					{
						$.post(url, {'AJAX':'AJAX'}, function(data) {
							$('#ajax').html(data);
							auChargement($('#ajax'));
						});
					}
					
					lastUrlArray = urlArray;
			});
		}
		else{
			$.post(url, {'AJAX':'AJAX'}, function(data) {
				$('#ajax').html(data);
				auChargement($('#ajax'));
				lastUrlArray = urlArray;
			});
		}
	}
}

function IsNumeric(input){
   return (input - 0) == input && input.length > 0;
}

function trimArray(arr){
	var finalArray = new Array();
	$(arr).each(function(index, value){
		var v = $.trim(value);
		if(v != "" && v != null && v != undefined)
		{
			finalArray.push(value);
		}
	});

	return finalArray;
}

var expo = false;
var exposition_id = 0;
var media_id = 0;


/*--- GALERIE PHOTO ---*/
function slideShow(is_expo, page , idExpo, idMedia, nbMedias){
	if($.browser.mozilla){
		$('#img').css({'float':'left', 'margin-right': 0});
	}
	
	expo = is_expo;
	
	if(page == 1)
	{
		$.post('/media/' + ((expo)?'exposition':'artiste') + '/' + idExpo + '/' + idMedia, {'AJAX':'AJAX'}, function(data) {
			if(data != ''){
				$('#img').css('overflow','hidden');
				$('#img').html(data);
				$('#img').children().load(function(){
					$('#backSlideshow').fadeIn(500, function(){$(this).css('opacity',0.5);});
					$('#slideshow').fadeIn(500);
					
					var h = $(this).height();
					var w = $(this).width();
					
					var ph = $(window).height()/$(this).height();
					var pw = $(window).width()/$(this).width();
					
					if(pw > ph){
						$(this).height($(window).height() - 100);
					}
					else{
						$(this).width($(window).width() - 100);
					}
					
					if ( (idMedia - 1) < 0){
						$('#slideGauche').css('opacity', 0);
						$('#slideGauche').css('margin-top', $(this).height()/2);
					}
					else{
						$('#slideGauche').css('opacity', 1);
						$('#slideGauche').css('margin-top', $(this).height()/2);
					}
					
					if ( (idMedia + 1) == nbMedias ){
						$('#slideDroite').css('opacity', 0);
						$('#slideDroite').css('margin-top', $(this).height()/2);
					}
					else{
						$('#slideDroite').css('opacity', 1);
						$('#slideDroite').css('margin-top', $(this).height()/2);
					}
					

					var title = $(this).attr('title');
					
					if(logged){
						var titles = title.split('-');
						var privilege = titles.pop();
						var price = titles.pop();
						
						title = titles.join('-') + ' - <b>' + price + '</b> - <b>' + privilege + '</b>';
					}
					else{
						var titles = title.split('-');
						var price = titles.pop();
						
						title = titles.join('-');
					}
					
					$('.titre').html(title);
					
					$('#img').animate({'height': $(this).height(), 'width': $(this).width()}, {
						duration: 400,
						step: function( currentLeft ){
							$('#slideshow').css({'margin-top': '-' + ($('#slideshow').height()/2) + 'px', 'margin-left': '-' + ($('#slideshow').width()/2) + 'px'});
						},
						complete: function(){
							$('#slideshow').css({'margin-top': '-' + ($('#slideshow').height()/2) + 'px', 'margin-left': '-' + ($('#slideshow').width()/2) + 'px'});
						}
					});
					
				});
			
				exposition_id = idExpo;
				media_id = idMedia;
				nb_medias = nbMedias;
				page_current = page;
			}
		});
	}
	else
	{
		if(page == 0)
		{
			$.post('/media/' + ((expo)?'exposition':'archives') + '/' + idExpo + '/' + idMedia, {'AJAX':'AJAX'}, function(data) {
			if(data != ''){
				$('#img').css('overflow','hidden');
				$('#img').html(data);
				$('#img').children().load(function(){
					$('#backSlideshow').fadeIn(500, function(){$(this).css('opacity',0.5);});
					$('#slideshow').fadeIn(500);
					
					var h = $(this).height();
					var w = $(this).width();
					
					var ph = $(window).height()/$(this).height();
					var pw = $(window).width()/$(this).width();
					
					if(pw > ph){
						$(this).height($(window).height() - 100);
					}
					else{
						$(this).width($(window).width() - 100);
					}
					
					if ( (idMedia - 1) < 0){
						$('#slideGauche').css('opacity', 0);
						$('#slideGauche').css('margin-top', $(this).height()/2);
					}
					else{
						$('#slideGauche').css('opacity', 1);
						$('#slideGauche').css('margin-top', $(this).height()/2);
					}
					
					if ( (idMedia + 1) == nbMedias ){
						$('#slideDroite').css('opacity', 0);
						$('#slideDroite').css('margin-top', $(this).height()/2);
					}
					else{
						$('#slideDroite').css('opacity', 1);
						$('#slideDroite').css('margin-top', $(this).height()/2);
					}
					

					var title = $(this).attr('title');
					
					if(logged){
						var titles = title.split('-');
						var privilege = titles.pop();
						var price = titles.pop();
						
						title = titles.join('-') + ' - <b>' + price + '</b> - <b>' + privilege + '</b>';
					}
					else{
						var titles = title.split('-');
						var price = titles.pop();
						
						title = titles.join('-');
					}
					
					$('.titre').html(title);
					
					$('#img').animate({'height': $(this).height(), 'width': $(this).width()}, {
						duration: 400,
						step: function( currentLeft ){
							$('#slideshow').css({'margin-top': '-' + ($('#slideshow').height()/2) + 'px', 'margin-left': '-' + ($('#slideshow').width()/2) + 'px'});
						},
						complete: function(){
							$('#slideshow').css({'margin-top': '-' + ($('#slideshow').height()/2) + 'px', 'margin-left': '-' + ($('#slideshow').width()/2) + 'px'});
						}
					});
					
				});
			
				exposition_id = idExpo;
				media_id = idMedia;
				nb_medias = nbMedias;
				page_current = page;
			}
			});
		}
		else
		{
			$.post('/media/' + 'exposition' + '/' + idExpo + '/' + idMedia, {'AJAX':'AJAX'}, function(data) {
			if(data != ''){
				$('#img').css('overflow','hidden');
				$('#img').html(data);
				$('#img').children().load(function(){
					$('#backSlideshow').fadeIn(500, function(){$(this).css('opacity',0.5);});
					$('#slideshow').fadeIn(500);
					
					var h = $(this).height();
					var w = $(this).width();
					
					var ph = $(window).height()/$(this).height();
					var pw = $(window).width()/$(this).width();
					
					if(pw > ph){
						$(this).height($(window).height() - 100);
					}
					else{
						$(this).width($(window).width() - 100);
					}
					
					if ( (idMedia - 1) < 0){
						$('#slideGauche').css('opacity', 0);
						$('#slideGauche').css('margin-top', $(this).height()/2);
					}
					else{
						$('#slideGauche').css('opacity', 1);
						$('#slideGauche').css('margin-top', $(this).height()/2);
					}
					
					if ( (idMedia + 1) == nbMedias ){
						$('#slideDroite').css('opacity', 0);
						$('#slideDroite').css('margin-top', $(this).height()/2);
					}
					else{
						$('#slideDroite').css('opacity', 1);
						$('#slideDroite').css('margin-top', $(this).height()/2);
					}
					

					var title = $(this).attr('title');
					
					if(logged){
						var titles = title.split('-');
						var privilege = titles.pop();
						var price = titles.pop();
						
						title = titles.join('-') + ' - <b>' + price + '</b> - <b>' + privilege + '</b>';
					}
					else{
						var titles = title.split('-');
						var price = titles.pop();
						
						title = titles.join('-');
					}
					
					$('.titre').html(title);
					
					$('#img').animate({'height': $(this).height(), 'width': $(this).width()}, {
						duration: 400,
						step: function( currentLeft ){
							$('#slideshow').css({'margin-top': '-' + ($('#slideshow').height()/2) + 'px', 'margin-left': '-' + ($('#slideshow').width()/2) + 'px'});
						},
						complete: function(){
							$('#slideshow').css({'margin-top': '-' + ($('#slideshow').height()/2) + 'px', 'margin-left': '-' + ($('#slideshow').width()/2) + 'px'});
						}
					});
					
				});
			
				exposition_id = idExpo;
				media_id = idMedia;
				nb_medias = nbMedias;
				page_current = page;
			}
			});
		}
	}
}

function precMedia(){
	slideShow(expo, page_current,exposition_id, media_id - 1, nb_medias);
}

function nextMedia(){
	slideShow(expo, page_current, exposition_id, media_id + 1, nb_medias);
}

function quitSlideshow(){
	$('#imgSlideshow iframe').hide();
	$('#backSlideshow').fadeOut(500);
	$('#slideshow').fadeOut(500);
	$('#img').html('');
}

window.onpopstate = function(event) {
	if(event.state != null){
		gotoUrl(event.state, false);
	}
}; 
