﻿// JavaScript Document
var Language = '';
jQuery.fn.extend({
   findPos : function() {
       obj = $(this).get(0);
       var curleft = obj.offsetLeft || 0;
       var curtop = obj.offsetTop || 0;
       while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
       }
       return {x:curleft,y:curtop};
   }
});

function trad(FR, EN){
	switch (Language){
	case "FR":
		return FR;
		break;
	case "EN":
		return EN;
		break;
	}
}

var getflashplayer = '<a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_adobe_flash_player.png" alt="Get Adobe Flash player" /></a>';

function ChargeLecteurMP3(ele, audio)
{
	var flashvars={
		configxml: audio
		};
	var params={
		wmode: 'transparent'
		//bgcolor: "#252525"
		};
	var attributes={
  		id: ele,
  		name: ele
 		};
	swfobject.embedSWF("/swf/player_mp3_multi.swf", ele, "200", "20", "9.0.0", '/swf/expressinstall.swf', flashvars, params, attributes);
}

function ChargeAlbum(ele, album)
{
	if (swfobject.hasFlashPlayerVersion("6.0.65")) {
  // has Flash
	var flashvars={
		imageHeight: 250,
 		imageWidth: 250,
 		loadText: trad("Chargement de l'image", "Loading image"),
 		loadOf: trad("sur", "of"),
 		loadXML: trad("Récupération de la liste des oeuvres", "Loading data"),
 		reflectionTopAlpha: 0.50,
 		reflectionBottomAlpha: 0.00,
 		reflectionSpace: 0,
 		LightBox: 'NO',
 		startAt: 'middle',
 		easeSpeed: 0.80,
 		shelveAngle: 80,
		shelveSpacing: 50,
		shelveOffset: 135,
 		scrollBar: 'YES',
 		ySpacing: 25,
 		FlickrStatus: 'NO',
 		TitleColor: 'ffffff',
 		DescriptionColor: 'ffffff',
 		trackBar: 'YES',
 		loader: 'YES',
 		loadType: 0,
 		flickrSet: ' ',
 		target: '_self',
		xmlPath: "/"+Language+"/albuminfo.xml?ID=" + album,
		loader: 'YES'
		};
	var params={
		wmode: 'transparent',
		bgcolor: "#252525",
		quality: 'best',
		allowScriptAccess: 'always'
		};
	var attributes={
  		id: ele,
  		name: ele,
  		styleclass: 'coverflow'
 		};
	swfobject.embedSWF("/swf/coverflow.swf", ele, "800", "400", "9.0.0", '/swf/expressinstall.swf', flashvars, params, attributes);
	}
	else {
	  $('#' + ele).html(getflashplayer);
	}
};

function ChargeDiapo(ele, diaporama)
{
	if (swfobject.hasFlashPlayerVersion("6.0.65")) {
  // has Flash
	var flashvars={
		xmlfile: "/"+Language+"/carouselinfo.xml?ID=" + diaporama,
		loaderColor: '0xFFFFFF',
		messages: trad('Chargement','Loading') + '::'+ trad("Récupération de la liste des oeuvres", "Loading data") + '::'+ trad('Chargement des images','Loading images') + '::'+ trad('Utilisez les touches flechées pour interagir avec le carousel','Use arrow keys to move the Carousel')
		};
	var params={
		allowscriptaccess: 'always',
		allowfullscreen: "true",
		quality: 'high',
		//wmode: 'transparent',
		bgcolor: "#252525"
		};
	var attributes={
  		id: ele,
  		name: ele
 		};
	swfobject.embedSWF("/swf/carousel.swf", ele, "800", "400", "9.0.0", '/swf/expressinstall.swf', flashvars, params, attributes);
	}
	else {
	  $('#' + ele).html(getflashplayer);
	}
};

function ChargeVideo(ele, video, l, h, videoHD)
{
	if (swfobject.hasFlashPlayerVersion("6.0.65")) {
  // has Flash
	var flashvars={
		file: video,
		controlbar: 'over',
		screencolor: '141414',
		backcolor: '141414',
		frontcolor: 'DF5715',
		plugins: 'hd-1',
		'hd.file': videoHD,
		displayclick: 'fullscreen'
		};
	var params={
		allowscriptaccess: 'always',
		allowfullscreen: "true",
		bgcolor: "#252525"
		};
	var attributes={
  		id: ele.id + 'swf',
  		name: ele.id,
		styleclass: 'video'
 		};
	swfobject.embedSWF("/swf/Player.swf", ele, l, h, "9.0.0", '/swf/expressinstall.swf', flashvars, params, attributes);
	}
	else {
	  $('#' + ele).html(getflashplayer);
	}
};

function pageload(url)
{
	var reg=new RegExp("/(FR|EN)/(.+)\.html$");
	var tabexec = url.match(reg);
	Language = tabexec[1];
	var msg = '<div class="chargement"></div>';
	$('#main').slideUp("normal", function(){
		$('#main').html(msg).slideDown("fast", function(){
			$('#main').load(url+" #corps", null, function(responsText, statut, code){
				var msg = '<div class="chargement"></div>';
				switch (statut){
					case 'success':
						var tampon = $('#main').html();
						$('#main').html(msg);
						piwik_ajax(url,piwik_idsite, piwik_url,'url',function(){
							$('#main').html(msg).slideUp("fast",function(){
								$('#main').html(tampon);
								Switch = false;
								$('#substitutalbum').hide();
								$('#main').slideDown("normal");
							});
						});
						break;
					default:
						alert("erreur");
						break;
				}
			});
		});
		$.getJSON(url, {Info: true}, function(json){
			document.title = json['Titre'];
			$('#lien2FR').attr("href", '/FR/' + json['Lien_FR']);
			$('#lien2EN').attr("href", '/EN/' + json['Lien_EN']);
		});
	});
}
function piwik_ajax(url, _pk_site, _pk_url, _pk_type, Callback) 
{
	$.get(_pk_url + '?idsite=' + _pk_site + '&' + _pk_type + '=' + escape(url) + '&rand=' + Math.random() + '&redirect=0', null, Callback);
}
function rechargemenu(Langue)
{
	$('#menubox').fadeOut("normal", function(){
		$('#menu').load('/menu.php?Lang=' + Langue, null, function(){
			$('#menubox').hide();
			//$('.menubutton').css('width', Math.max($('#menubox').width() / $(".menubutton").length,100));
			$('#menubox').fadeIn("slow");
		});
	});
}

function rechargeactu(Langue)
{
	$('#actus').fadeOut("normal", function(){	
		$('#actudefilante').load('/actu.php?Lang=' + Langue, null, function(){
			$('#actus').hide().fadeIn("normal");
		});
	});
}

function rechargecopyright(Langue)
{
	$('#copyright').fadeOut("normal", function(){	
		$('#copyright').load('/copyright.php?Lang=' + Langue, null, function(){
			$('#copyright').hide().fadeIn("normal");
		});
	});
}
var Switch = false;
var SwitchHTML = "";

function SwitchtabalbumAlbum(){
	if (!Switch){
		$('.coverflow').slideUp("normal", function(){
			SwitchHTML = $('#texttabalbum a').html();
			$('#texttabalbum a').html(trad("Revenir au Coverflow","Back to the Coverflow"));
			$('.vignettes').slideDown("normal", function(){
				Switch = true;
			});
		});
	} else {
		$('.vignettes').slideUp("normal", function(){
			$('#texttabalbum a').html(SwitchHTML);
			$('.coverflow').slideDown("normal", function(){
				Switch = false;
			});
		});
	}
};

function AfficheBoxAlbum(idtableau){
	$.getJSON("/"+Language+"/tableauinfojson.js", {id: idtableau}, function(json){
		if (json["Statut"]) {
			AfficheImageBox(json["Nom"],"/tableau.php?id=" + json["ID"] + "&l=1000&h=1000" ,"");
		};
	});
};

function AfficheImageBox(titre,url,ID){
	Shadowbox.open({
		language:	Language.toLowerCase(),
        player:     'img',
        title:      titre,
        content:    url,
		options:{
			handleOversize:'resize'
			}
		});
	piwik_ajax('/' + Language + '/POPUP/' +titre+ (ID != '' ? '/'+ID : ''),piwik_idsite, piwik_url,'url');
};
function GeoGooleMap(Adresse){
	
}
function AfficheGoogleMapBox(Adresse){
    Shadowbox.open({
        player:     'html',
        content:    '',
		title: Adresse,
        height:     800,
        width:      800,
        options:    {
			autoDimensions: true,
			handleOversize:'none',
			handleUnsupported:  "remove",
            onFinish: function(item){
                if(GBrowserIsCompatible()){
                    var body = document.getElementById(Shadowbox.contentId());
					var mapOptions = {
						googleBarOptions : {
						  style : "new"
						}
					  }
                    var map = new GMap2(body, mapOptions);
					map.setMapType(G_HYBRID_MAP);
					var geocoder = new GClientGeocoder();
					geocoder.getLatLng(Adresse,function(point) {
						if (!point) {
							alert(address + " not found");
					  	} else {
							map.setCenter(point, 13);
							var marker = new GMarker(point);
							map.addOverlay(marker);
							marker.openInfoWindowHtml('<span style="color:black">'+Adresse+'</span>');
					  	}
					});
					map.setUIToDefault();
  					//map.enableGoogleBar();

                    //map.addControl(new GSmallMapControl());
					//map.addControl(new GMapTypeControl());
                }
            }
        }
    });
}

function AfficheSiteBox(titre,url){
	Shadowbox.open({
		//language:	Language.toLowerCase(),
        player:     'iframe',
        title:      titre||'',
        content:    url,
		options:{
			handleOversize:'resize'
			}
		});
	piwik_ajax(url,piwik_idsite, piwik_url,'link');
};

$(document).ready(function(){
	//$('.menubutton').css('width', Math.max($('#menubox').width() / $(".menubutton").length,100));
	$(document).keypress(function(e) {
    	key = e.charCode || e.keyCode || 0;
		if(e.ctrlKey && e.shiftKey && (key==12 || key==76)){
			Login();
			return false;
		};
	});
	ChargeLecteurMP3('playeraudio',"/" + Language + "/configaudio.xml");
});

// Masque les substitusalbums si javascript activé
$("#substitutalbum").livequery(function(){
	$(this).hide();
});

// Ajax les actualités
$("ul#ticker").livequery(
	function(){$(this).liScroll({travelocity: 0.05, pause: false},
	function(){$(this).stop()}							
	); 
});

// Ajax les menus
$(".menubutton a").livequery('click',function(event){ 
	pageload(this.href);
	return false;
});
$(".sousmenubutton a").livequery('click',function(event){ 
	$(".sousmenu").fadeOut('fast');
	return false;
});
$('.menubutton').livequery(function()
	{ 
        $(this).mouseenter(function()
			{ 
				var pos = $(this).findPos();
				$(this).children('.sousmenu').css('left',pos.x);
				$(this).children('.sousmenu').css('top',pos.y + $(this).height());
				$(this).children('.sousmenu').slideDown("fast");
			});
		$(this).mouseleave(function() { $(this).children('.sousmenu').slideUp("fast"); }); 
    }, function()
	{ 
        $(this).unbind('mouseenter');
        $(this).unbind('mouseleave'); 
    }
); 
// Ajax les substituts
$(".lientabalbum a").livequery('click',
	function(event){ 
		SwitchtabalbumAlbum();
		return false;
		}	
);
// Ajax les liens retour et autres
$(".retour, .ajaxlien").livequery('click',function(event){ 
	pageload(this.href);
	return false;
});

// Ajax les liens externes
$(".lienexternelien a, .lienexterne").livequery('click',function(event){
	AfficheSiteBox(this.title,this.href);
	return false;
});
// Ajax les drapeaux
$(".drapeau a, .choixLanguage a").livequery('click',function(event){								   
	pageload(this.href);
	rechargemenu($(this).attr('id').substring(5));
	rechargeactu($(this).attr('id').substring(5));
	rechargecopyright($(this).attr('id').substring(5));
	return false;
});

// Ajax les images (shadowbox)
$(".shadowboxtableau").livequery('click',function(event){
	AfficheImageBox(this.title, "/tableau.php?id=" + $(this).attr('id').substring(7) + "&l=1000&h=1000",'');
	return false;
});
$(".shadowboxexpo").livequery('click',function(event){
	AfficheImageBox(this.title, "/exposition.php?id=" + $(this).attr('id').substring(4) + "&l=1000&h=1000",$(this).attr('id').substring(4));
	return false;
});
// Ajax GoogleMap
$(".googlemap a").livequery('click',function(event){
	AfficheGoogleMapBox(this.title);
	return false;
});
// Ajax les flux RSS
$(".rss").livequery('click',function(event){
	//ChargeAlbum("album",0);
	//return false;
});	
// Ajax les banières
function changebaniere(dimensionbaniere){
	$("#imagebaniere").attr('src',"/banieres/baniere" + dimensionbaniere + ".gif");
	$("#codebaniere").text('<a title="www.jeancharlesvalley.com" href="http://www.jeancharlesvalley.com"><img alt="Jean Charles VALLEY" src="http://www.jeancharlesvalley.com/banieres/baniere'+ dimensionbaniere + '.gif"</img></a>');
}
$("#selectbaniere").livequery('change',function(event){
	changebaniere($(this).attr('value'));
});
$("#selectbaniere").livequery(function(event){
	changebaniere($(this).attr('value'));
});
// Ajax le chargement des albums
$('.album').livequery(function(){
	ChargeAlbum(this.id,$(this).attr('id').substring(5));
})
// Ajax le chargement des albums
$('.diaporama').livequery(function(){
	ChargeDiapo(this.id,$(this).attr('id').substring(5));
})
// Ajax le chargement des vidéos
$('#videoFrance3').livequery(function(){
 	ChargeVideo(this.id, '/videos/France3BD.flv', 384, 288, '/videos/France3HD.flv');
})

function Login(){
	//alert($.load('/FR/login.html'));
	$('#popup').load('/'+Language+'/login.html' +" #popuplogin", null, function(){
	Shadowbox.open({
        player:     'html',
        title:      'Connexion à www.jeancharlesvalley.com',
		height: 	$('#popup').height(), //150,
		width:		$('#popup').width(), //350,
		content:	$('#popup').html(),
		options: {//},{
			enableKeys:false,
			displayNav:false,
			modal:true
			}
		});
	$('#popup').empty();
	});
}

function MessageBox(message, titre){
	titre = titre || "Information";
	$('#popup').html('<div class="Messagebox" id="Messagebox"></div>');
	$('#Messagebox').append('<div>' + message + '</div>');
	$('#Messagebox').append("<div><input type='button' class='button' value='Fermer' name='MBFermer'/></div>");
	Shadowbox.open({
        player:     'html',
        title:      titre,
		height: 	$('#popup').height(), //150,
		width:		$('#popup').width()+1, //350,
		content:	$('#popup').html(),
		options: {//},{
			enableKeys:false,
			displayNav:false,
			modal:true
			}
		});
	$('#popup').empty();
}
// Ajoute le champ 'ajax' aux formulaires pour ajaxisation
$("form").livequery(function(){
	$(this).prepend('<input name="ajax" type="hidden" value=""/>');
	$(this).validate();
});
// Ajax le formulaire de login
$("#formlogin input[name=cancel]").livequery(function(){
	$(this).click(function(){
		$('#login').resetForm();
		Shadowbox.close();
		return false;
	});
});
$("input[name=MBFermer]").livequery(function(){
	$(this).click(function(){
		Shadowbox.close();
		return false;
	});
});
$("input[type=submit]").livequery(function(){
	$(this).click(function(){
		if ($(this.form).valid()){
			$('#' + $($(this).attr('form')).attr('id') + " input[name=ajax]").attr('value',$(this).attr('name'));
			$($(this).attr('form')).ajaxSubmit({dataType:  'json', success: ResponseAjax});
		};
		return false;
	});
});
// Définit les règles de validation de formulaire
$("form .inpemail").livequery(function(){
	$(this).rules("add", {
 		required: true,
 		email: true,
 		messages: {
   		required: trad("Veuillez entrer une adresse mail","Please enter your mail"),
		email: trad("Email non valide","Invalid mail")
 		}
	});
});
$(".creation").livequery(function(){
	if ($(this).find(".creationdate").html() != '') {$(this).show();};
});
$(".modification").livequery(function(){
	if ($(this).find(".modificationdate").html() != '') {$(this).show();};
});
function ResponseAjax(responseJSON, statusText)  { 
    if(statusText == 'success') {
		switch (responseJSON['Action']){
			case 'Login':
				Shadowbox.close();
				rechargemenu(Language);
				$('#lien' + Language).click();
				break;
			case 'Deconnexion':
				rechargemenu(Language);
				$('#lien' + Language).click();
				break;
			case 1: // Ajout d'une actualité
				$('#actuAjout').resetForm();
				$(responseJSON['Form']).appendTo('#formactus').hide().slideDown("fast");
				rechargeactu(Language);
				break;
			case 2: // Mise à jour d'une actualité
				//var hauteur = $("#actu"+responseJSON['ID']).height();
				$(responseJSON['Form']).replaceAll("#actu"+responseJSON['ID']);
				rechargeactu(Language);
				break;
			case 4: // Suppression d'une actualité
				$("#actu"+responseJSON['ID']).slideUp("fast", function(){$("#actu"+responseJSON['ID']).remove()});
				rechargeactu(Language);
				break;
			case 8: // Ajout d'une exposition
				$('#expoAjout').resetForm();
				$(responseJSON['Form']).appendTo('#formexpos').hide().slideDown("fast");
				break;
			case 16: // Mise à jour d'une exposition
				$(responseJSON['Form']).replaceAll("#expo"+responseJSON['ID']);
				break;
			case 32: // Suppression d'une exposition
				$("#expo"+responseJSON['ID']).slideUp("fast", function(){$("#expo"+responseJSON['ID']).remove()});
				break;
			case 'EnvoiMailContact':
				$('#formcontact').resetForm();
				MessageBox(responseJSON['Statut']);
				break;
		}
		//if (!responseJSON['Resultat']) {
			//alert(responseJSON['Statut']);
		//};
	}
}