/* ********************************* INIT */
var init = function() {
	navProv();					// navigation provisoire (retirer avant mise en prod)
	flashHeader();				// flash equipes header
	flashVideo();				// flash videos
	flashGP();					// flash player generic
	setHeightTwin();			// home - meme hauteur blocs tiers
	car2();						// home - carousel photo
	tabs();						// col-r - tabs photo video
	car();						// colr-r - carousel photo
	flashPlayer();				// col-r - player video
	overTeam();					// col-r - equipes
	tabs2();					// page photo - tabs
	cyclePhotos(); 				// cycle
}

/* ********************************* CYCLE PHOTO */
function cyclePhotos() {
	if( jQuery(".listePhotos").size() < 1 )
		return false;	
	
	$('.listePhotos').cycle({
		fx: 	'scrollHorz',
		prev:   '.btPrev', 
	    	next:   '.btNext', 
	    	timeout: 5000,
		before:	 refreshIframes,  	// appel fonction derefresh des iframes
		after:   onAfter			// incrementation du numero
		});

	$('.btDiaporama').text("Arrêter le diaporama");


	function onAfter(curr, next, opts) {
		var index = $(this).parent().children().index(this);
		$('.numPhoto').html("").append((index+1) + '/' + opts.slideCount);
	}
	
	$('.btDiaporama').toggle(
		function() { 
			$('.listePhotos').cycle('resume');
			$(this)
				.addClass("resume")
				.text("Arrêter le diaporama");
			return false;
		},
		function() { 
			$('.listePhotos').cycle('pause');
			$(this)
				.removeClass("resume")
				.text("Lancer le diaporama");
			return false;
		}
	);
}

/* ********************************* CYCLE TRANSITION */
(function($) {
	// scrollHorz
	$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
		$cont.css('overflow','hidden').width();
		opts.before.push(function(curr, next, opts, fwd) {
			$(this).show();
			var currW = curr.offsetWidth, nextW = next.offsetWidth;
			opts.cssBefore = fwd ? { left: nextW } : { left: -nextW };
			opts.animIn.left = 0;
			opts.animOut.left = fwd ? -currW : currW;
			$slides.not(curr).css(opts.cssBefore);
		});
		opts.cssFirst = { left: 0 };
		opts.cssAfter = { display: 'none' }
	};
})(jQuery);


/* ********************************* REFRESH IFRAME */


function refreshIframes() {
//	window.parent.frames['pub-megaban'].location.reload();
	window.parent.frames['pub-coldroite'].location.reload();	
	window.parent.frames['pub-bouton1'].location.reload();
	window.parent.frames['pub-bouton2'].location.reload();
}

/* ********************************* OVER TEAM */
var overTeam = function() {
	if( jQuery("#team").size() < 1 )
		return false;	
	
	var teamCurrent = jQuery("#team .current");
	$('#team li').mouseover( function(){

	var urlMedium = 'img/team-'+$('a .ordre', this).html()+'.jpg';
		$('#team .visu img').attr('src',urlMedium);
		$('#team p').html($('a', this).attr("title") );
		
		if (teamCurrent) {
			if (teamCurrent.size()==1) {
				teamCurrent.removeClass("current");
				$(this).addClass("current");
				teamCurrent = $(this);
			}
		}
	});
}

/* ********************************* TABS PHOTO VIDEO */
var tabs = function() {
	if( jQuery("#photos-videos").size() < 1 )
	return false;

	$('#photos-videos .ul').tabs();
}

/* ********************************* TABS PAGE PHOTO */
var tabs2 = function() {
	if( jQuery("#galeries").size() < 1 )
	return false;

	$('#galeries .ul').tabs();


	// Selectionner l'onglet via l'url avec # en PREMIER paramètre
	var currentPage = $("#galeries").parent().attr('class');
	var currentUrl = window.location.href;
	var urlParams = currentUrl.split('#');
	if (urlParams.length > 1) {
	
		// Onglets Photos
		if (currentPage == "photos") {
			if (urlParams[1] == "au-coeur-de-l-action") {
				var selectedTab = '1';
			} else if (urlParams[1] == "equipes") {
				var selectedTab = '2';
			} else {
				var selectedTab = '1';
			}

		// Onglets Vidéos
		} else if (currentPage == "videos") {
			if (urlParams[1] == "etapes") {
				var selectedTab = '1';
			} else if (urlParams[1] == "equipes") {
				var selectedTab = '2';
			} else if (urlParams[1] == "interviews") {
				var selectedTab = '3';
			} else if (urlParams[1] == "inedites") {
				var selectedTab = '4';
			} else if (urlParams[1] == "castings") {
				var selectedTab = '5';
			} else {
				var selectedTab = '1';
			}
		}

		$('#galeries .ul').tabs("select", selectedTab);
	}

}

/* ********************************* CAROUSEL HOME */
var car2 = function() {
	if( jQuery("#carouHome").size() < 1 )
	return false;

	$('#carouHome').jcarousel({scroll: 1});
}

/* ********************************* CAROUSEL PHOTO COL-R */
var car = function() {
	if( jQuery("#carouPhotoEtape").size() < 1 )
	return false;

	$('#carouPhotoEtape').jcarousel({scroll: 1});
}

/* ********************************* SAME HEIGHT HOME TIERS */
var setHeightTwin = function() {
	if( jQuery(".home .tiers").size() < 1 )
		return false;
	                    
	var heightBlockMax=0;
	$('.home .tiers').each(function(){ if( $(this).height() > heightBlockMax ) heightBlockMax = $(this).height(); }); // get max height
	$('.home .tiers').each(function(){ $(this).css("height",heightBlockMax+"px"); }); // assign max height
	heightBlockMax=0;
}

/* ********************************* FLASH VIDEO */

var flashVideo = function() {

	if( jQuery("#videoFlash").length < 1 ) {
		return false;
	} else {
		var idVideo = jQuery('#videoFlash').attr('class');
		var flashvars = {};
		flashvars.appWidth = "635";
		flashvars.appHeight = "357";
		flashvars.xmlLink = "http://pekin-express.m6.fr/xml/config_" + idVideo + ".xml?v" + (new Date()).getTime() + "=" + (new Date()).getTime();
		flashvars.domain = "http://pekin-express.m6.fr/";
		var params = {};
		params.menu = "false";
		params.quality = "high";
		params.wmode = "transparent";
		params.base = "http://video.m6.fr/players/flash/generic/";
		params.allowscriptaccess = "always";
		var attributes = {};
		swfobject.embedSWF("http://video.m6.fr/players/flash/generic/m6webtv.swf", "videoFlash", "635", "357", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
	}
}

/* ********************************* FLASH HEADER */
var flashHeader = function() {
	if( jQuery("#flash-equipe").length < 1 )
		return false;
	var flashvars = {};
	flashvars.monXml = "xml/equipes.xml";
	var params = {};
	params.menu = "false";
	params.quality = "high";
	params.wmode = "transparent";
	var attributes = {};
	swfobject.embedSWF("swf/1004-100.swf", "flash-equipe", "1000", "100", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);	
}

/* ********************************* FLASH GP */
var flashGP = function() {
	if(jQuery('#gp').length < 1)
		return false;
	var flashvars = {};
	flashvars.xmlLink = "xml/pg-config.xml?v" + (new Date()).getTime() + "=" + (new Date()).getTime();

	var params = {};
//	params.bgcolor = "#000000";
	params.allowscriptaccess = "always";
	params.wmode = "transparent";
	var attributes = {};
	attributes.id = "base";
//	swfobject.embedSWF("swf/pg-player.swf?v" + (new Date()).getTime() + "=" + (new Date()).getTime(), "flashId", "418", "340", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
	swfobject.embedSWF("swf/homeplayergen.swf?v" + (new Date()).getTime() + "=" + (new Date()).getTime(), "flashId", "418", "340", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);

}

/* ********************************* FLASH PLAYER VIDEO COL-R */
var flashPlayer = function(video) {
	if(jQuery('#contenuVideos').length < 1)
		return false;
	var flashvars = {};
	var attributes = {};
	var params = {};
	params.allowscriptaccess = "always";
	params.quality = "high";
	params.menu = "false";
	params.wmode = "transparent";
	params.base = "swf/";
	var videoCatalog = $('#contenuVideos span').attr('id');
	swfobject.embedSWF("swf/playerLittle.swf?flv=http://groupemsix.rd.llnwd.net/u/videonum/" + videoCatalog + "_Webtv.flv", "contenuVideos", "300", "250", "8.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
}

/* ********************************* OPEN/CLOSE NAV PROVISOIRE */
var navProv = function() {
	$('.navProvOC a').click(function() {	
		if($(this).html()=='ouvrir la nav') {
			$(this).html('fermer la nav');	
		}
		else {
			$(this).html('ouvrir la nav');
		}		
		$('.navProvContent').animate({height: "toggle"}, 100);
		return false;		
	});
}

/* ********************************* HOVER CLASSE POUR IE6 */
$.fn.hoverClass = function(c) {
	return this.each(function(){
		$(this).hover( 
			function() { $(this).addClass(c);  },
			function() { $(this).removeClass(c); }
		);
	});
};

/* ********************************* PNG */
// PNGHack 1.0.1 (2008-06-18)
// Copyright (c) 2008 Yves Van Goethem and png-hack project contributors
document.write('<!--[if lte IE 6]><style type="text/css">.hack-png{visibility:hidden}</style><![endif]-->');
var PNGHack = function(spacer) {
	var remoteUrl = 'css/skin/pix.gif';
	var hackMethod = function(obj, method, that) {
		// browser check
		if (that.checkIE && !navigator.userAgent.match(that.checkIE))
			return;
		
		// settings
		if (!obj) obj = {};
		var d	= obj.scope || document;
		var elm = (!obj.elm && method != 2) ? d.all : d.getElementsByTagName(obj.elm);
		var src = obj.src || 'src';
		var ext = new RegExp((obj.ext) ? '\\w+.'+obj.ext.toUpperCase() : '\.PNG$');
		
		// hack core
		var hack = function(elm, source) {
			var style = elm.style;
			if (!elm.pngsrc)
				that.elements.push(elm);
			elm.pngsrc = elm.getAttribute(source);
			style.width = elm.clientWidth;
			style.height = elm.clientHeight;
			style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+elm.pngsrc+"',sizingMethod='scale')";
			
			// using hosted spacer, set it up to rescue local spacer or cancel remotehost
			if (that.remotehost == true)
				spacer = remoteUrl;
			else if (that.remotehost != false) {
				var rescueSpacer = function() {
					elm.setAttribute(source, remoteUrl);
				};
				var setRescueSpacer = function() {
					if (elm.readyState == 'complete') {
						elm.detachEvent('onerror', rescueSpacer);
						elm.detachEvent('onreadystatechange', setRescueSpacer);
					}
				};
				elm.attachEvent('onerror', rescueSpacer);
				elm.attachEvent('onreadystatechange', setRescueSpacer);
			}
			
			// displaying element / removing hack-png class
			elm.setAttribute(source, spacer || 'images/spacer.gif');
			if (elm.className.match(/\bhack-png\b/))
				var x = setTimeout(function(){elm.className = elm.className.replace(/hack-png/g,'');clearTimeout(x);},300);
		};
		
		// hack method
		if (method == 2) {
			hack(obj.elm, src);
			return;
		}
		
		// go and crush method
		for (var i = 0; i < elm.length; ++i) {
			var isrc = elm[i].getAttribute(src) || '';
			if (method == 0 && elm[i].className.match(/\bhack-png\b/)
			|| (method == 1 && isrc.toUpperCase().match(ext)))
				hack(elm[i], src);
		}
	};
	return {
		hackClass : function(obj) {
			hackMethod(obj, 0, this);
		},
		hackExtension : function(obj) {
			hackMethod(obj, 1, this);
		},
		hackElement : function(obj) {
			hackMethod(obj, 2, this);
		},
		elements : [],
		checkIE : 'MSIE 5\.5|MSIE 6',
		remotehost : null
	};
};


/* ********************************* Poster Commentaire */
function postCommentaire(id) {
	$('#commentForm').submit(function() { return false; });
    	var pseudo = document.getElementById('pseudo').value;
	var email = document.getElementById('email').value;
	var commentaire = document.getElementById('commentaire').value;
	var code = document.getElementById('code').value;
	var idBreve = id;

	$.post('commentaires.php', {id:idBreve, pseudo:pseudo, email:email, commentaire:commentaire, code:code}, function (data){
		$('#postCommentResult').html(data).fadeIn();
		var img = document.getElementById('cryptogram');
		img.src = 'lib/crypto/cryptographp.php?cfg=0&' + Math.random();
		$('#code').val('');


		if ($("#msgComment").attr('class') == "commentValid") {
		$('#pseudo').val('');
		$('#email').val('');
		$('#commentaire').val('');
		setTimeout("window.location.reload()", 500);
		}

	});
}


/* ********************************* APPEL DES FONCTIONS */
$(document).ready(function() {	
	init();
});