/**
 * @author michael
 */
var alerte = new Array;

var search_count = 0;
var curr_page = 1;

var curr_sens = 1;

var all_tooltips = [];
var login_opened = false;

var swfu;

var base_url = "";
var nb_search = 0;

jQuery.noConflict();

$j = jQuery;
jQuery('img').ready(function(){

        $j.prettySociable({
            animationSpeed: 'fast', /* fast/slow/normal */
            opacity: 0.90, /* Value between 0 and 1 */
            share_label: 'Partager', /* Text displayed when a user rollover an item */
            share_on_label: 'Partager sur ', /* Text displayed when a user rollover a website to share */
            hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettySociable */
            hover_padding: 0,
            websites: {
                    facebook : {
                            'active': true,
                            'encode':true, // If sharing is not working, try to turn to false
                            'title': 'Facebook',
                            'url': 'http://www.facebook.com/share.php?u=',
                            'icon':'/images/prettySociable/large_icons/facebook.png',
                            'sizes':{'width':70,'height':70}
                    },
                    twitter : {
                            'active': true,
                            'encode':true, // If sharing is not working, try to turn to false
                            'title': 'Twitter',
                            'url': 'http://twitter.com/home?status=',
                            'icon':'/images/prettySociable/large_icons/twitter.png',
                            'sizes':{'width':70,'height':70}
                    },
                    delicious : {
                            'active': false,
                            'encode':true, // If sharing is not working, try to turn to false
                            'title': 'Delicious',
                            'url': 'http://del.icio.us/post?url=',
                            'icon':'/images/prettySociable/large_icons/delicious.png',
                            'sizes':{'width':70,'height':70}
                    },
                    digg : {
                            'active': false,
                            'encode':true, // If sharing is not working, try to turn to false
                            'title': 'Digg',
                            'url': 'http://digg.com/submit?phase=2&url=',
                            'icon':'/images/prettySociable/large_icons/digg.png',
                            'sizes':{'width':70,'height':70}
                    },
                    linkedin : {
                            'active': false,
                            'encode':true, // If sharing is not working, try to turn to false
                            'title': 'LinkedIn',
                            'url': 'http://www.linkedin.com/shareArticle?mini=true&ro=true&url=',
                            'icon':'/images/prettySociable/large_icons/linkedin.png',
                            'sizes':{'width':70,'height':70}
                    },
                    reddit : {
                            'active': false,
                            'encode':true, // If sharing is not working, try to turn to false
                            'title': 'Reddit',
                            'url': 'http://reddit.com/submit?url=',
                            'icon':'/images/prettySociable/large_icons/reddit.png',
                            'sizes':{'width':70,'height':70}
                    },
                    stumbleupon : {
                            'active': false,
                            'encode':false, // If sharing is not working, try to turn to false
                            'title': 'StumbleUpon',
                            'url': 'http://stumbleupon.com/submit?url=',
                            'icon':'/images/prettySociable/large_icons/stumbleupon.png',
                            'sizes':{'width':70,'height':70}
                    },
                    tumblr : {
                            'active': false,
                            'encode':true, // If sharing is not working, try to turn to false
                            'title': 'tumblr',
                            'url': 'http://www.tumblr.com/share?v=3&u=',
                            'icon':'/images/prettySociable/large_icons/tumblr.png',
                            'sizes':{'width':70,'height':70}
                    }
            },
            urlshortener : {
                    bitly : {
                            'active' : false
                    }
            },
            tooltip: {
                    offsetTop:0,
                    offsetLeft: 15
            },
            popup: {
                    width: 900,
                    height: 500
            },
            callback: function(){} /* Called when prettySociable is closed */
        });



	/*----------------- LISTE TRAILER -----------------*/
	if ($j("div#trailer_slider .film_media").length > 0) {
		
		var _size = $j('.film_media').children().length;
		
		$j("div#trailer_slider .film_media").cycle({
			fx: 'scrollHorz',
			speed: 100,
			timeout: 0,
			next: '.film_bright',
			prev: '.film_bleft',
			continious: 0/*,

			prevNextClick: function(isNext, zeroBasedSlideIndex, slideElement){
				//console.log(isNext + " ." + zeroBasedSlideIndex + ". "  +slideElement);
				
				// Sur derniere page, on remonte du nb d'elements
				if (zeroBasedSlideIndex == _size - 1) {
					//console.log('go up');
					for (var i = 0; i < _size; i++) {
						this.fx = 'scrollLeft';
					}
					return false;
				}
				else {
					// Actions normales
					if (isNext) 
						this.fx = 'scrollLeft';
					else 
						this.fx = 'scrollRight';
				}
				
				return false;
			}*/
			
		});
	}
	/* END LISTE TRAILER */

});	
	
jQuery(document).ready(function(){
	/*
	$j('#header_nav').superfish({
		delay:			200,
		speed: 			1000,
		pathClass: 		'nav_current', 
        animation:   	{opacity:'show'},
        autoArrows:  	false, 
        dropShadows: 	false
	});
	*/
	
	/*----------------- LOGIN BOX -----------------*/
	

	focusMe('#s');
	focusMe('#n');
	focusMe('.inplace_field');
	
	
	
	 /* kill take a tour */
	 if(getCookie('close_takeatour_video')=='1')
	{
		$j("#takeatour_container").empty();	
		
	}
	 
	 
	/* mailbox select */
	$j('.mail_select2 a').click(function(e){
		
		$j('input.checklist').attr("checked","checked");

		
		});
		
	$j('.mail_deselect2 a').click(function(e){
		
		$j('input.checklist').removeAttr("checked");

		
		});	
	
	/*******************/
	
	/*  swith friends tab */
	
	if ($j('.friend_tab2').attr('rel') > 0) {
		$j('#friend_tab2').show(); $j('.friend_tab2').addClass('current');
		$j('#friend_tab1').hide(); $j('.friend_tab1').removeClass('current');
	}
	else {
		$j('#friend_tab2').hide(); $j('.friend_tab2').removeClass('current');;
		$j('#friend_tab1').show(); $j('.friend_tab1').addClass('current');;		
	}	
	
	$j('ul.friend_tab li').each(function(inc,el){
		
		
		
		$j(el).click(function(e){
		
			if(inc>1)
				return;
			$j('ul.friend_tab li').removeClass('current');
			$j(this).addClass('current');
			
			if(inc==0)
			{
				$j('#friend_tab2').slideUp(200,function(){$j('#friend_tab1').slideDown();});
				
			}
			else
			{
				$j('#friend_tab1').slideUp(200,function(){$j('#friend_tab2').slideDown();});
			}
			
			return false;
		});
		
		
		
		});
	
	/*********************/
	
	if ($j('#header_loginbutton').length > 0) {
		$j('#header_loginbutton').click(function(){
			close_tooltips();
			if (!login_opened) {
				$j('#loginbox').stop().hide().slideDown(200);
				login_opened = true;
			}
			else {
				$j('#loginbox').stop().slideUp(200);
				login_opened = false;
			}
		});
		
		
		$j('#close_login').click(function(){
			close_tooltips();
			$j('#loginbox').slideUp(200);
		});
		
		$j('#mdp_link').click(function(){
			close_tooltips();
			$j('#bloc_login').stop().animate({
				'top': '-148px'
			}, 300);
		});
		
		$j('#login_link').click(function(){
			close_tooltips();
			$j('#bloc_login').stop().animate({
				'top': '0px'
			}, 300);
		});
		
		$j("#loginFORM").submit(function(){
			return false;
		}).validate({
			errorElement: "em",
//			onblur: function(element){
//				$j(element).valid();
//				return false;
//			},
//			onkeyup: function(element){
//				$j(element).valid();
//			},
			success: function(label){
				label.html('<img src="/images/accept.png" alt="" title=""/>');
			},
			rules: {
				login: {
					required: true,
					email: true
				},
				password: {
					required: true
				}
			},
			messages: {
				login: "<img src='/images/cross.png' alt='' title='Veuillez saisir un email' onload='init_tooltips2()'/>",
				password: "<img src='/images/cross.png' alt='' title='Veuillez saisir un mot de passe' onload='init_tooltips2()'/>"
			},
			submitHandler: function(form){
			
				$j(form).ajaxSubmit({
					url: $j(form).attr("action") + "Ajax",
					dataType: 'json',
					success: function(data){
						if (data.status == '1') {
                                                    
                                                        location.href = data.msg;

                                                        if(data.remember != '') setCookie('remember', data.remember );
                                                        

						}
						else { 
							open_alert($j("#loginMSG"), (data.msg), 'Erreur');
						}
					}
				});
				
			}
		});
		
		$j("#mdpFORM").submit(function(){
			close_tooltips();
			return false;
		}).validate({
			errorElement: "em",
			success: function(label){
				label.html('<imgsrc="/images/accept.png" alt="" title=""/>');
				return false;
			},
			rules: {
				email: {
					required: true,
					email: true
				}
			},
			messages: {
				email: "<img src='/images/cross.png' alt='' title='Veuillez saisir un email' onload='init_tooltips2()'/>"
			},
			submitHandler: function(form){
				$j(form).ajaxSubmit({
					url: $j(form).attr("action") + "Ajax",
					dataType: 'json',
					success: function(data){
						_title = "Erreur";
						if (data.status == 1) {
							_title = "Mot de passe oubli&eacute;";
						}
						open_alert($j("#mdpMSG"), (data.msg), _title);
					}
				});
			}
		});
		
	/* END LOGIN BOX */
	}
        if($j("#freeFORM").length > 0) {
            $j("#freeFORM").submit(function(){
                    return false;
            }).validate({
                    errorElement: "em",
                    success: function(label){
                            label.html('<img src="/images/accept.png" alt="" title=""/>');
                    },
                    rules: {
                            "openInviter[email]": {
                                    required: true,
                                    email: true
                            },
                            "openInviter[email2][]": {
                                    email: true
                            },
                            message: {
                                    required: true
                            }
                    },
                    messages: {
                            "openInviter[email]": {
                                required : "<img src='/images/cross.png' alt='' title='Veuillez saisir un email' onload='init_tooltips2()'/>",
                                email : "<img src='/images/cross.png' alt='' title='Veuillez saisir un email' onload='init_tooltips2()'/>"
                            },
                            "openInviter[email2][]": {
                                email : "<img src='/images/cross.png' alt='' title='Veuillez saisir un email' onload='init_tooltips2()'/>"
                            },
                            message: "<img src='/images/cross.png' alt='' title='Veuillez saisir un mot de passe' onload='init_tooltips2()'/>"
                    },
                    submitHandler: function(form){

                            $j(form).ajaxSubmit({
                                    url: $j(form).attr("action") + "Ajax",
                                    dataType: 'json',
                                    beforeSubmit : showLoading(),
                                    success: function(data){
                                            if (data == '1') {
                                                    open_alert($j("#freeFORM"), 'Votre message a bien été envoyé. Merci.', 'Message');
                                            }
                                            else {
                                                    open_alert($j("#freeFORM"), 'Une erreur est survenue, veuillez réessayer plus tard. Merci.', 'Erreur');
                                            }
                                            $j(".fancy_loading").hide();
                                    }
                            });

                    }
            });

            $j('#addEmail').click(function(){
                if($j('#listEmail .input').length > 9) return false;

                $j('#listEmail').append('<p class="input"><input class="openinviiter_email" type="text" value="" name="openInviter[email2][]"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="delEmail" onclick="$j(this).parent(\'p\').remove();return false;">supprimer</a></p>');
                return false;
            });
            

        }

        if($j("#parrainageFORM").length > 0) {

            $j("#parrainageFORM").submit(function(){
                    return false;
            }).validate({
                    errorElement: "em",
                    success: function(label){
                            label.html('<img src="/images/accept.png" alt="" title=""/>');
                    },
                    rules: {
                            "filleuil[email]": {
                                    required: true,
                                    email: true
                            },
                            "filleuil[email2][]": {
                                    email: true
                            },
                            message: {
                                    required: true
                            }
                    },
                    messages: {
                            "filleuil[email]": {
                                required : "<img src='/images/cross.png' alt='' title='Veuillez saisir un email' onload='init_tooltips2()'/>",
                                email : "<img src='/images/cross.png' alt='' title='Veuillez saisir un email' onload='init_tooltips2()'/>"
                            },
                            "filleuil[email2][]": {
                                email : "<img src='/images/cross.png' alt='' title='Veuillez saisir un email' onload='init_tooltips2()'/>"
                            },
                            message: "<img src='/images/cross.png' alt='' title='Veuillez saisir un message' onload='init_tooltips2()'/>"
                    },
                    submitHandler: function(form){

                            $j(form).ajaxSubmit({
                                    url: $j(form).attr("action"),
                                    dataType: 'json',
                                    beforeSubmit : showLoading(),
                                    success: function(data){
                                            if (data == '1') {
                                                    open_alert($j("#parrainageFORM"), 'Votre message a bien été envoyé. Merci.', 'Message');
                                            }
                                            else {
                                                    open_alert($j("#parrainageFORM"), 'Une erreur est survenue, veuillez réessayer plus tard. Merci.', 'Erreur');
                                            }
                                            $j(".fancy_loading").hide();
                                    }
                            });

                    }
            });

            $j('#addEmailFilleuil').click(function(){
                if($j('#listEmail .input').length > 4) return false;

                $j('#listEmail').append('<p class="input"><input class="openinviiter_email" type="text" value="" name="filleul[email2][]"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="delEmail" onclick="$j(this).parent(\'p\').remove();return false;">supprimer</a></p>');
                return false;
            });
        }
        
        if($j('#newsletterform').length > 0) {
            $j("#newsletterform").submit(function(){
                    close_tooltips();
                    return false;
            }).validate({

                    submitHandler: function(form){
                            $j(form).ajaxSubmit({
                                    url: $j(form).attr("action"),
                                    dataType: 'json',
                                    success: function(data){
                                            
                                            if (data.status == 1) {
                                                _title = "Newsletter";
                                                $j(form).find('#n').attr("value","Votre email...");
                                            }
                                            else {
                                                _title = "Erreur";                                                
                                            }

                                            open_alert($j("#newsletterform"), (data.msg), _title);
                                    }
                            });
                    }
            });
        }


	if ($j('#footer_partners').length > 0) {

		$j('#footer_partners div').cycle({
			fx: 'scrollHorz',
			speed: 'slow',
			timeout: 3000,
                        pagerEvent: 'mouseover',
                        pauseOnPagerHover: true,
                        pause: 1,
			next: '#footer_partners a.footer_btn_right',
			prev: '#footer_partners a.footer_btn_left'
		});
	}

	/*----------------- MENU -----------------*/
	if ($j('#header_nav li a').length > 0) {
		$j('#header_nav li a').each(function(i){
		
			var arbo = $j(this).attr("id");
			
			//if ($j("#nav_" + arbo).length > 0) {
			if ($j(this).parent('li').hasClass('current')) 
				showSub(i);
			
			$j(this).hover(function(){
				showSub(i);
			}, function(){
				return false;
			});
		//}	
		});
	}
	/*
	$j("#nav_accueil, #nav_films, #nav_membres, #nav_video, #nav_actus").lavaLamp({
        speed: 300,
		fx: "backout",
        click: function(event, menuItem) {
            return false;
        }
    });
	*/
	
	/* END MENU */
	
	
	
	/*----------------- API FACEBOOK -----------------*/
	window.fbAsyncInit = function() {
            FB.init({appId: apikey, status: true, cookie: true,
                 xfbml: true});
            FB.getLoginStatus(update_user_box);
        };
        (function() {
            var e = document.createElement('script'); e.async = true;
            e.src = document.location.protocol +
              '//connect.facebook.net/fr_FR/all.js';
            document.getElementById('fb-root').appendChild(e);
        }());
        /*
	//Initialisation de l'api
	if (typeof(apikey) != 'undefined') {
            FB.init({appId: apikey, status: true,
               cookie: true, xfbml: true});


			
			FB.init(apikey, "/xd_receiver.htm", {
				//Si la session existe on actualise
				"ifUserConnected": update_user_box,
                                status: true,
                                cookie: true,
                                xfbml: true
			});
			//Connection au webservice Facebook
			client = new FB.ApiClient(apikey);

                        FB.XFBML.Host.parseDomTree();
                        
			dispatch_action();
			
			if ($j("posts") != null) 
				get_posts(id_user);
	}		*/

	/* END API FACEBOOK */
	
	
	/*----------------- LOGIN PAGE -----------------*/
	
	if ($j("#loginPAGE").length > 0) {
		$j("#loginPAGE").validate({
			errorElement: "em",
			onblur: function(element){
				$j(element).valid();
				return false;
			},
//			onkeyup: function(element){
//				$j(element).valid();
//			},
			success: function(label){
				label.html('<img src="/images/accept.png" alt="" title=""/>');
				return false;
			},
			rules: {
				login: {
					required: true,
					email: true
				},
				password: {
					required: true
				}
			},
			messages: {
				login: "<img src='/images/cross.png' alt='' title='Veuillez saisir un email' onload='init_tooltips2()'/>",
				password: "<img src='/images/cross.png' alt='' title='Veuillez saisir un mot de passe' onload='init_tooltips2()'/>"
			}
		});
		
		$j("#mdpPAGE").validate({
			errorElement: "em",
			onblur: function(element){
				$j(element).valid();
				return false;
			},
//			onkeyup: function(element){
//				$j(element).valid();
//			},
			success: function(label){
				label.html('<img src="/images/accept.png" alt="" title=""/>');
				return false;
			},
			rules: {
				email: {
					required: true,
					email: true
				}
			},
			messages: {
				email: "<img src='/images/cross.png' alt='' title='Veuillez saisir un email' onload='init_tooltips2()'/>"
			}
		});
	}
	/*----------------- SLIDER INV -----------------*/
	if ($j('.part_slider').length > 0) {
		$j('.part_slider').css('margin-left', (parseInt($j('.part_slider').width()) / 2 * (-1)) + 'px');
	}
	/* END SLIDER INV */
	
	
	
	/*----------------- LISTE VIDEO -----------------*/
	/*
	$j("div.film_carousel").carousel({
		nextBtn: '<a title="suivant" class="next film_bright hidden">suivant</a>',
		prevBtn: '<a title="pr&eacute;c&eacute;dent" class="forward film_bleft hidden">pr&eacute;c&eacute;dent</a>',  
		dispItems: 1,
		loop: true
	});
	*/
	/* END LISTE VIDEO*/
	
	
	
	/*----------------- HL BG -----------------*/
	if ($j("#spotlight_prev").length > 0) {
		$j("#spotlight_prev").click(function(){
			$j("#spotlight_bg").css('margin-left', '-280px').animate({
				marginLeft: -170
			}, 600);
		})
		$j("#spotlight_next").click(function(){
			$j("#spotlight_bg").css('margin-left', '-60px').animate({
				marginLeft: -170
			}, 600);
		})
		
		$j("#spotlight_bg").appendTo("#spotlight ul");
	}
	/* END HL BG */

	/*----------------- HOME HIGHLIGHT V2 -----------------*/
	if ($j('#highlight_body_container').length > 0) {
            $j('#highlight_body_container').cycle({
                    fx: 'fade',
                    speed: 'fast',
                    timeout: 6000,
                    pager: '#highlight_thumbs',
                    pagerEvent: 'mouseover',
                    pauseOnPagerHover: true,
                    pause: 1,
                    pagerAnchorBuilder: function(idx, slide){
                            return '<li id="highlight_thumb'+idx+'"><img onclick=\'location.href="'+$j(slide).find('a').attr('href')+'"; return false;\' src="'+$j(slide).find('img').attr('rel')+'" alt="" border=""/></li>';
                    }
            }).find('li').animate({opacity:20}, 20);

            $j.fn.cycle.updateActivePagerLink = function(pager, currSlideIndex) {
                $j(pager).find('li').animate({ opacity : 0.2 },1, function(){
                    $j('#highlight_thumb'+currSlideIndex).css({ opacity : 1 });
                });
            };

            $j('#highlight_body_container li').hover(
                function(){
                    $j(this).find('a.high_text').stop().animate({ bottom : 0 }, 200);
                },
                function(){
                    $j(this).find('a.high_text').stop().animate({ bottom : -90 }, 200);
                }
            );
            
	}
	/* END HIGHLIGHT V2 */
	
	/*----------------- HOME ZOOM, STUDIO -----------------*/	
	if ($j('#list_zoom_sur').length > 0) {
		$j('.footerd .slider').css('background-image', 'url(/images/slider_x' + $j('#list_zoom_sur').children('ul').length + '.jpg)');
		$j('.footer_e_double_content .slider').css('background-image', 'url(/images/slider_x' + $j('#list_zoom_sur').children('ul').length + '.jpg)');
		$j('#list_zoom_sur').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			pager: '#zoom_pager',
			
			// callback fn that creates a thumbnail to use as pager anchor 
			pagerAnchorBuilder: function(idx, slide){
				return '<div class="zoom_pager_item" title="Page ' + (idx + 1) + '" rel="' + idx + '"></div>';
			}
		});
		$j('#zoom_pager div').click(function(){
			var idx = parseInt($j(this).attr('rel'));
			$j("#zoom_slider").css('backgroundPosition', 'left ' + (idx) * 20 * (-1) + 'px');
		});
	}
	/* END HOME ZOOM */
	
	/* --------------------- STUDIO LISTE MISES ---------------- */
	if ($j('#studio_liste_mise').length > 0) {
		$j('#studio_liste_mise').cycle({
			fx: 'scrollVert',
			speed: 'fast',
			timeout: 0,
			pager: '#mise_pager',
			
			// callback fn that creates a thumbnail to use as pager anchor 
			pagerAnchorBuilder: function(idx, slide){
				return '<li title="' + $j(slide).find('.mise_img').attr('title') + '">' + $j(slide).attr('rel') + '</li>';
			}
		});
	}
	
	/*----------------- PAGE MEMBRE -----------------*/
	if ($j('#film_membre_slider').length > 0) {
		$j('.film_slider').css('background-image', 'url(/images/slider_x' + $j('#film_membre_slider ul').length + '.jpg)');
		$j('#film_membre_slider').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			pager: '#film_pager',
			
			// callback fn that creates a thumbnail to use as pager anchor 
			pagerAnchorBuilder: function(idx, slide){
				return '<div class="film_pager_item" title="Page ' + (idx + 1) + '" rel="' + idx + '"></div>';
			}
		});
	}
		
		
	if ($j('#statusEditable').length > 0 || $j('#descriptionEditable').length > 0) {
		$j('#statusEditable, #descriptionEditable').each(function(){
			var myurl = $j(this).attr('rel');
			$j(this).editInPlace({
				type     : 'textarea',
				url: myurl,
				show_buttons: true
			});
		});
	}
		
	if ($j('.seeMore').length > 0) {
		$j('.seeMore').each(function(){
			var myurl = $j(this).attr('href');
			var target = $j(this).attr('rel');
			$j.ajax({
				url: myurl,
				success: function(msg){
					$j('#' + target).html(msg);
				}
			});
			return false;
		});
	}
	/* END PAGE MEMBRE */
	
	/*----------------- PAGE PROFIL -----------------*/
	if ($j('#film_profil_slider').length > 0) {
		$j('.film_slider').css('background-image', 'url(/images/slider_x' + $j('#film_profil_slider ul').length + '.jpg)');
		$j('#film_profil_slider').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			pager: '#film_pager',
			
			// callback fn that creates a thumbnail to use as pager anchor 
			pagerAnchorBuilder: function(idx, slide){
				return '<div class="film_pager_item" title="Page ' + (idx + 1) + '" rel="' + idx + '"></div>';
			}
		});
	}
	if ($j('.my_videos_container').length > 0) {
		
		$j('.my_videos_container .my_videos').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			next: '.my_videos_container a.btn_right',
			prev: '.my_videos_container a.btn_left'
		});
	}
	if ($j('.my_photos_container').length > 0) {
		
		$j('.my_photos_container .my_photos').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			next: '.my_photos_container a.btn_right',
			prev: '.my_photos_container a.btn_left'
		});
	}
        
	if ($j('.my_films_container').length > 0) {
		
		$j('.my_films_container .my_films').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			next: '.my_films_container a.btn_right',
			prev: '.my_films_container a.btn_left'
		});
	}
	if ($j('.films_user_container').length > 0) {

		$j('.films_user_container .films_user').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			next: '.films_user_container a.btn_right',
			prev: '.films_user_container a.btn_left'
		});
	}
	/* END PAGE PROFIL */
	
	/*-------------------- SIDEBAR ACTU --------------*/
        /*
	if ($j('.my_notifs_container').length > 0) {
		$j('.my_notifs_container').each(function(){
		
			var _self = this;
			
			$j(_self).find('.my_notifs').cycle({
				fx: 'fade',
				speed: 'slow',
				timeout: 0,
				continuous: 0,
				prevNextClick: function(isNext, zeroBasedSlideIndex, slideElement){
					
					this.speedOut= this.speed;this.easeIn=this.easing;this.easeOut=this.easing;this.delay= 0 ;
					if(this.last==this.elements.length-1 && zeroBasedSlideIndex==0)		{	this.fx = 'scrollDown';	this.easeOut='backin'; this.easeIn='backin';		this.last = zeroBasedSlideIndex;	return false;	}
					else if(this.last==0 && zeroBasedSlideIndex==this.elements.length-1)		{	this.fx = 'scrollUp';this.easeOut='backin';	this.easeIn='backin';		this.last = zeroBasedSlideIndex;	return false;	}
					else
						this.last = zeroBasedSlideIndex;
											
				
					
					
					
					if (isNext) 						
						this.fx = 'scrollUp';
					else 
						this.fx = 'scrollDown';
					return false;
					
					
				},
				
				next: 'a.btn_down_' + $j(_self).attr('id'),
				prev: 'a.btn_up_' + $j(_self).attr('id')
			});
		});
		
				 //$('#s1').cycle(0);
    			//return false;
    		 
	}
            */
	/*
	if ($j('.actus_list_container').length > 0) {
		
		// Nb elements ul de la div slider
		var _size = $j('.actus_list').children().length;
		var _first = $j('.actus_list').children()[0];
		
		$j('.actus_list_container').each(function(){
		
			var _self = this;
                        
			$j(_self).find('.actus_list').cycle({
				fx: 'fade',
				speed: 1500,
				timeout: 0,
				continuous: 0,
				
				prevNextClick: function(isNext, zeroBasedSlideIndex, slideElement){
					//console.log(isNext + " ." + zeroBasedSlideIndex + ". "  +slideElement);
					
					this.speedOut= this.speed;this.easeIn=this.easing;this.easeOut=this.easing;this.delay= 0 ;
					if(this.last==this.elements.length-1 && zeroBasedSlideIndex==0)		{	this.fx = 'scrollDown';	this.easeOut='backin'; this.easeIn='backin';		this.last = zeroBasedSlideIndex;	return false;	}
					else if(this.last==0 && zeroBasedSlideIndex==this.elements.length-1)		{	this.fx = 'scrollUp';this.easeOut='backin';	this.easeIn='backin';		this.last = zeroBasedSlideIndex;	return false;	}
					else
						this.last = zeroBasedSlideIndex;
						
					if (isNext) 						
						this.fx = 'scrollUp';
					else 
						this.fx = 'scrollDown';
					return false;
					
					
				},
				
				next: 'a.btn_down_' + $j(_self).attr('id'),
				prev: 'a.btn_up_' + $j(_self).attr('id')
			});
		})
	}
	*/
	/*----------------- HOME FILM -----------------*/
	if ($j('#film_list_slider').length > 0) {
		$j('#slideshow_content .film_slider').css('background-image', 'url(/images/slider_x' + $j('#film_list_slider ul').length + '.jpg)');
		$j('#film_list_slider').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			pager: '#film_pager',
			
			// callback fn that creates a thumbnail to use as pager anchor 
			pagerAnchorBuilder: function(idx, slide){
				return '<div class="film_pager_item" title="Page ' + (idx + 1) + '" rel="' + idx + '"></div>';
			}
		});
		$j('#film_pager div').click(function(){
			var idx = parseInt($j(this).attr('rel'));
			$j("#film_slider").css('backgroundPosition', 'left ' + (idx) * 20 * (-1) + 'px');
		});
		
		$j(".film_cat").cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			next: '.film_bright',
			prev: '.film_bleft'
		});
	}
	/* END HOME FILM */
	
	
	/*----------------- PAGE FILM -----------------*/
	if ($j('#film_carousel .film_media').length > 0) {
		$j('#film_carousel .film_media').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			next: '.film_bright',
			prev: '.film_bleft',
			continious: 1
		});
		
		if ($j('#film_carousel .film_media').length > 0 && $j('.film_media ul').length < 2) {
			$j('.film_bright, .film_bleft').css('visibility', 'hidden');
		}
	}
	/* END PAGE FILM */
	
	
	/*----------------- TOOLTIPS -----------------*/
	
	init_tooltips();
	
	/* END TOOLTIPS */
	
	
	
	/*----------------- STEP1 -----------------*/
	
	if ($j("#step1FORM").length > 0) {
		
		$j("#step1FORM").validate({
			errorElement: "em",
			onblur: function(element){
				$j(element).valid();
				return false;
			},
//			onkeyup: function(element){
//				$j(element).valid();
//			},
			success: function(label){
				if (label.selector.indexOf('cgu') > 1) 
					label.html('<img src="/images/accept.png" class="check_error" alt="" title=""/>');
				else 
					label.html('<img src="/images/accept.png" alt="" title=""/>');
				return false;
			},
			rules: {
				"matrix[fr][name]": {
					required: true,
					minlength: 4,
					maxlength: 32,
					checkLogin: true,
					remote: "/index.php/accueil/ajaxcheckfield"
				},
				"matrix[matuserdata][email]": {
					required: true,
					minlength: 4,
					maxlength: 255,
					//email: true,
					remote: "/index.php/accueil/ajaxcheckfield"
				},
				"matrix[matuserdata][email2]": {
					required: true,
					minlength: 4,
					maxlength: 255,
					email: true,
					equalTo: "#matrix_matuserdata_email"
				},
				"matrix[matuserdata][password]": {
					required: true,
					minlength: 4,
					maxlength: 32,
					checkPwd: true
				},
				"matrix[matuserdata][password2]": {
					required: true,
					minlength: 4,
					maxlength: 32,
					equalTo: "#matrix_matuserdata_password"
				},
				"matrix[matuserdata][mat_civility_id]": {
					required: true
				},
				"matrix[matuserdata][first_name]": {
					required: true,
					maxlength: 255,
					checkInfo: true
				},
				"matrix[matuserdata][last_name]": {
					required: true,
					maxlength: 255,
					checkInfo: true
				},
				"matrix[option][cgu]": {
					//required: true
				},
				"matrix[captcha]": {
					required: true
				}
			},
			messages: {
				"matrix[fr][name]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir votre pseudo' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre pseudo est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre pseudo est trop long' onload='init_tooltips2()'/>",
					checkLogin: "<img src='/images/cross.png' alt='' title='Votre pseudo est incorrecte' onload='init_tooltips2()'/>",
					remote: "<img src='/images/cross.png' alt='' title=\"Ce nom d'utilisateur est déjà pris. Essayez de le rendre unique en y ajoutant un mot ou un chiffre.\" onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][email]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir votre email' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre email est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre email est trop long' onload='init_tooltips2()'/>",
					remote: "<img src='/images/cross.png' alt='' title='Votre email est déjà enregistré dans la base de données des utilisateurs Peopleforcinema' onload='init_tooltips2()'/>",
					email: "<img src='/images/cross.png' alt='' title='Veuillez saisir une adresse email correcte' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][email2]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez ressaisir votre email' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre email est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre email est trop long' onload='init_tooltips2()'/>",
					equalTo: "<img src='/images/cross.png' alt='' title='Veuillez ressaisir correctement votre email' onload='init_tooltips2()'/>",
					email: "<img src='/images/cross.png' alt='' title='Veuillez saisir une adresse email correcte' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][password]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir un mot de passe' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre mot de passe est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre mot de passe est trop long' onload='init_tooltips2()'/>",
					checkPwd: "<img src='/images/cross.png' alt='' title='Votre mot de passe est incorrecte' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][password2]": "<img src='/images/cross.png' alt='' title='Veuillez ressaisir correctement votre mot de passe' onload='init_tooltips2()'/>",
				"matrix[matuserdata][mat_civility_id]": "<img src='/images/cross.png' alt='' title='Veuillez sélectionner votre civilité' onload='init_tooltips2()'/>",
				"matrix[matuserdata][first_name]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir votre prénom' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre prénom est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre prénom est trop long' onload='init_tooltips2()'/>",
					checkInfo: "<img src='/images/cross.png' alt='' title='Votre prénom est incorrecte' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][last_name]":  {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir votre nom' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre nom est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre nom est trop long' onload='init_tooltips2()'/>",
					checkInfo: "<img src='/images/cross.png' alt='' title='Votre nom est incorrecte' onload='init_tooltips2()'/>"
				},
				"matrix[captcha]": "<img src='/images/cross.png' alt='' title='Veuillez saisir le captcha' onload='init_tooltips2()'/>",
				"matrix[option][cgu]": '<img class="check_error" src="/images/cross.png" alt="" title="Vous devez accepter les Conditions Générales d\'Utilisation pour être inscrit" onload="init_tooltips2()"/>'
			}
		});
		
	}
	/* STEP 1 */
	
	/*----------------- STEP2 -----------------*/
	
	if ($j("#step2FORM").length > 0) {
		$j("#step2FORM").validate({
			errorElement: "em",
			onblur: function(element){
				$j(element).valid();
				return false;
			},
//			onkeyup: function(element){
//				$j(element).valid();
//			},
			success: function(label){
				label.html('<img src="/images/accept.png" alt="" title=""/>');
				return false;
			},
			rules: {
				"matrix[adresse][rue]": {
					required: true
				},
				"matrix[adresse][code_postal]": {
					required: true,
					checkCP: true
				},
				"matrix[adresse][ville]": {
					required: true
				},
				"matrix[adresse][pays]": {
					required: true
				},
				"matrix[matuserdata][phone]": {
					checkPhone: true
				}
			},
			messages: {
				"matrix[adresse][rue]": "<img src='/images/cross.png' alt='' title='Veuillez saisir une adresse' onload='init_tooltips2()'/>",
				"matrix[adresse][code_postal]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir un code postal' onload='init_tooltips2()'/>",
					checkCP: "<img src='/images/cross.png' alt='' title='Votre code postal est incorrect' onload='init_tooltips2()'/>"
				},
				"matrix[adresse][ville]": "<img src='/images/cross.png' alt='' title='Veuillez saisir un nom de ville' onload='init_tooltips2()'/>",
				"matrix[adresse][pays]": "<img src='/images/cross.png' alt='' title='Veuillez sélectionner un pays' onload='init_tooltips2()'/>",
				"matrix[matuserdata][phone]": {
					checkPhone: "<img src='/images/cross.png' alt='' title='Votre numéro de téléphone est incorrect' onload='init_tooltips2()'/>"
				}
			}
		});
		
		
	}
	/* --------- STUDIO -------------- */
		
	if ($j("#groupNEW").length > 0) {
		$j("#groupNEW").validate({
			errorElement: "em",
			onblur: function(element){
				$j(element).valid();
				return false;
			},
			success: function(label){
				label.html('<img src="/images/accept.png" alt="" title=""/>');
				return false;
			},
			rules: {
				"matrix[fr][name]": {
					required: true
				},
				"matrix[fr][description]": {
					required: true
				}
			},
			messages: {
				"matrix[fr][name]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir un nom' onload='init_tooltips2()'/>"
				},
				"matrix[fr][description]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir une description' onload='init_tooltips2()'/>"
				}
			}
		});
	}
	/* --------- STUDIO -------------- */
	
	if ($j("#groupNEW").length > 0) {
		$j("#groupNEW").validate({
			errorElement: "em",
			onblur: function(element){
				$j(element).valid();
				return false;
			},
			success: function(label){
				label.html('<img src="/images/accept.png" alt="" title=""/>');
				return false;
			},
			rules: {
				"matrix[fr][name]": {
					required: true
				},
				"matrix[fr][description]": {
					required: true
				}
			},
			messages: {
				"matrix[fr][name]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir un nom' onload='init_tooltips2()'/>"
				},
				"matrix[fr][description]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir une description' onload='init_tooltips2()'/>"
				}
			}
		});
	}
	
	if ($j("#groupNEW").length > 0) {
		$j("#groupNEW").validate({
			errorElement: "em",
			onblur: function(element){
				$j(element).valid();
				return false;
			},
			success: function(label){
				label.html('<img src="/images/accept.png" alt="" title=""/>');
				return false;
			},
			rules: {
				"matrix[fr][name]": {
					required: true
				},
				"matrix[fr][description]": {
					required: true
				}
			},
			messages: {
				"matrix[fr][name]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir un nom' onload='init_tooltips2()'/>"
				},
				"matrix[fr][description]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir une description' onload='init_tooltips2()'/>"
				}
			}
		});
	}

	/* -------------- ALL SELECTBOX ----------------- */
	if ($j('#matrix_matuserdata_birth_day').length > 0) {
		$j('#matrix_matuserdata_birth_day').addClass('selectBox');
	}
	if ($j('#matrix_matuserdata_birth_month').length > 0) {
		$j('#matrix_matuserdata_birth_month').addClass('selectBox');
	}
	if ($j('#matrix_matuserdata_birth_year').length > 0) {
		$j('#matrix_matuserdata_birth_year').addClass('selectBox');
	}
	if ($j('#matrix_matuserdata_mat_profession_id').length > 0) {
		$j('#matrix_matuserdata_mat_profession_id').addClass('selectBox');
	}
	if ($j('#matrix_adresse_pays').length > 0) {
		$j('#matrix_adresse_pays').addClass('selectBox');
	}
	if ($j('#matrix_matuserdata_mat_civility_id').length > 0) {
		$j('#matrix_matuserdata_mat_civility_id').addClass('selectBox');
	}

	if ($j('#matrix_matuserdata_parrain').length > 0) {
		$j('#matrix_matuserdata_parrain').addClass('selectBox');
	}
	
	if ($j('#openInviter_provider').length > 0) {
		$j('#openInviter_provider').addClass('selectBox');
	}
	/* END SELECTBOX */
	
	/* -------------- LIST FRIENDS ------------------- */
	
	if($j("#fcbklist").length > 0) $j.fcbkListSelection("#fcbklist","535","50","2");

	/* END LIST FRIENDS */

	
	
	/* ------------------ SELECTBOX VALIDATOR -------------  */
	/*if($j('#matrix_matuserdata_mat_civility_id_container li'))
	$j('#matrix_matuserdata_mat_civility_id_container li').click(function(){
		$j("#profilINFOS, #step1FORM").validate().element("#matrix_matuserdata_mat_civility_id");
	})
	
	if($j('#matrix_adresse_pays_container li'))
	$j('#matrix_adresse_pays_container li').click(function(){
		$j("#profilINFOS, #step2FORM").validate().element("#matrix_adresse_pays");
	})*/
	
	/* ------------------ TOP FRIENDS --------------------- */
	if ($j('#zone_friends').length > 0) {
		window.$zone_friends = $j('#zone_friends');
		window.$zone_top = $j('#top_friends');
		
		$j('#zone_friends li, #top_friends li').draggable({
			revert: 'invalid',
			helper: 'clone',
			cursor: 'move'
		});
		
		$zone_top.droppable({
			accept: 'li',
			drop: function(ev, ui){
				addTopfriend(ui.draggable);
			}
		});
		
		$zone_friends.droppable({
			accept: 'li',
			drop: function(ev, ui){
				removeTopfriend(ui.draggable);
			}
		});
		
		function addTopfriend($item){
		
			var id = $item.attr('rel');
			
			$j.ajax({
				url: '/matrix/addFriendAjax?id=' + id,
				success: function(){
					$item.fadeOut(function(){
						$item.appendTo($zone_top.find('ul')).fadeIn();
					});
				}
			});
		}
		
		function removeTopfriend($item){
		
			var id = $item.attr('rel');
			
			$j.ajax({
				url: '/matrix/removeFriendAjax?id=' + id,
				success: function(){
					$item.fadeOut(function(){
						$item.appendTo($zone_friends.find('ul')).fadeIn();
					});
				}
			});
		}
	}
	  
	
	
	/* --------------- SEARCH ---------------- */
	if ($j("#search_select li span").length > 0) {
		$j("#search_select li span").click(function(){
			if (curr_sens) {
				curr_sens = 0;
				$j(this).parent().find('a.search_asc').click();
				return false;
			}
			else {
				curr_sens = 1;
				$j(this).parent().find('a.search_desc').click();
				return false;
			}
		});
	}
	
	

	
	if ($j('#takeatour_video').length > 0) {
		$j('.demo').click(function(){
			$j("#takeatour_video").toggle();
			return false;
		});
		$j('.close').click(function(){
			$j("#takeatour_video").empty();
			$j("#takeatour_container").slideUp(600);
			setCookie('close_takeatour_video', '1',  15 );

			return false;
		});
	}
	
	/* ------------------------ COMM ----------------------- */
	
	/* ------------------------- BLOG ----------------------- */
	if ($j('.rotator_content').length > 0) {
		var cur_slide = 0;
		$j('.rotator_content').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			pager: '.rotator_bar ul',
			next: '.rotator_nav .next a',
			prev: '.rotator_nav .previous a',
			prevNextClick: function(isNext, idx, slide){
				if (isNext) {
					if (idx == 0) 
						hide_item(2);
					else 
						hide_item(idx - 1);
					show_item(idx);
				}
				else {
					if (idx == 2) 
						hide_item(0);
					else 
						hide_item(idx + 1);
					show_item(idx);
				}
				cur_slide = idx;
			},
			pagerClick: function(idx, slide){
				hide_item(cur_slide);
				show_item(idx);
				cur_slide = idx;
			},
			pagerAnchorBuilder: function(idx, slide){
				return '<li><a href="#" onclick="return false;" id="navbar' + idx + '">' + $j(slide).attr('title') + '</a></li>';
			}
		});
		function hide_item(currSlideElement){
			$j('#mea'+currSlideElement).fadeOut('fast');
		}
		function show_item(nextSlideElement){
			$j('#mea'+nextSlideElement).fadeIn('slow');	
		}
	}
	
	/*----------------- HOME ZOOM, STUDIO -----------------*/	
	
	// Galerie
	if ($j(".galleryblock ").length > 0) {
		
		page_galleryblock(1);
		
		$j(".gallery").cycle({
			fx: 'scrollHorz',
			speed: 100,
			timeout: 0,
			next: '.next',
			prev: '.previous',
			continious: 0,
			after: function(curr, next, opts){
				page_galleryblock(opts.currSlide);
			}
		});
	}	
	
	// Affiche la pagination
	function page_galleryblock(current) {
		$j(".current").html(current + 1 + " sur " + $j(".sub_gallery").length);	
	}
	
	// Films
//	if ($j(".filmsblock ").length > 0) {
//		
//		$j(".test").before().cycle({
//			   fx:     'turnDown', 
//			    speed:  'fast', 
//			    timeout: 3000, 
//		});
//	}	
	
	
	/*
	 * 		$j('.footerd .slider').css('background-image', 'url(/images/slider_x' + $j('#list_zoom_sur').children('ul').length + '.jpg)');
		$j('.footer_e_double_content .slider').css('background-image', 'url(/images/slider_x' + $j('#list_zoom_sur').children('ul').length + '.jpg)');
		$j('#list_zoom_sur').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			pager: '#zoom_pager',
			
			// callback fn that creates a thumbnail to use as pager anchor 
			pagerAnchorBuilder: function(idx, slide){
				return '<div class="zoom_pager_item" title="Page ' + (idx + 1) + '" rel="' + idx + '"></div>';
			}
		});
		$j('#zoom_pager div').click(function(){
			var idx = parseInt($j(this).attr('rel'));
			$j("#zoom_slider").css('backgroundPosition', 'left ' + (idx) * 20 * (-1) + 'px');
		});
	 * 
	 */
	
	if ($j('.filmsblock').length > 0) {
		$j('.film_sur').cycle({
			fx: 'scrollHorz',
			speed: 'fast',
			timeout: 0,
			pager: '#film_pager',
			// callback fn that creates a thumbnail to use as pager anchor 
			pagerAnchorBuilder: function(idx, slide){
				//console.log('pagerAnchorBuilder = ' + idx);
				return '<div class="film_pager_item" title="Page ' + (idx + 1) + '" rel="' + idx + '"></div>';
			}
		});
		
		$j('#film_pager div').click(function(){
			var idx = parseInt($j(this).attr('rel'));
			//console.log('click = ' + idx);
			$j("#filmblock_pager").css('backgroundPosition', 'left ' + ((-1 * 20) *  (idx)) + 'px');
		});
	}	
	
	
	
	
	// Clic sur l'image du caroussel du blog
	if($j('.rotator_content img')) {
	       $j('.rotator_content img').click(function(e){
	    	   // Get du rel de l'image pour envoyer sur la bonne url
	    	   mea_id = $j(this).attr('rel');
	    	   document.location.href = $j('#mea' + mea_id + ' .rotator_title a').attr('href');
	       	});
	}

	
	if ($j("#takeatour_vid").length > 0) {
		
		var flashvars = {
			file: "http://www.vdoencode.com/get_file_MTQ5ODc0MjM3MyMjODkjIzExNyMjRklOQUxfUDRDXzAxLmZsdiMjODQwIyMxNDkwIyNGSU5BTF9QNENfMDEuZmx2IyNhYjIyMzlhNmFhYjlkNDkxNDdiNTJiNmUzMjE2MzI2Mw==.flv",
			skin: "/swf/skin/modieus.swf",
			image: "/images/teaser.jpg",
			stretching: "fill"
		};
		
		var params = {
			menu: "false",
			width: "490",
			height: "300",
			WMODE: "transparent",
			allowfullscreen: "true"
		};
		

		swfobject.embedSWF("/swf/player.swf", "takeatour_vid", "490", "300", "9.0.0", "/swf/expressInstall.swf", flashvars, params);

	}
	
	if ($j("#pub_video").length > 0) {
		var flashvars = {
			file: "httpv://www.youtube.com/watch?v=",
			skin: "/swf/skin/modieus.swf",
			stretching: "fill"
		};
		
		var params = {
			menu: "false",
			width: "100%",
			height: "100%",
			WMODE: "transparent",
			allowfullscreen: "true"
		};
		//swfobject.embedSWF("/swf/player.swf", "pub_video", "100%", "100%", "9.0.0", "/swf/expressInstall.swf", flashvars, params);
	}
	
	if ($j("#spotlight").length > 0) spotlight();
	
	if($j("#PaymentRequest").length > 0){
		$j("#PaymentRequest").submit(function(){
			
			var tmp =  $j("#PaymentRequest").attr('rel').split('|');
			$j.ajax({
				url : tmp[1],
				type: "POST",
				data : tmp[0],
				success: function(msg){
					
					if(msg == '0') return false;
					
					location.href = "/accueil/index";
					return true;					
				}
			});
			
		});
		
	}
	if($j('#inviterFORM').length > 0){
		window.open_lightview = true;
		$j('#inviterFORM #loginsubmit').click(function(){
			
			document.observe('lightview:opened', function(event) {
			  
			  if (window.open_lightview) {
			  	var target = $j('#lightviewContent').attr('name');
			  	
			  	$j('#lightviewContent').css('background', '#ffffff url(/images/ajax-loader.gif) no-repeat center center');
			  	
			  	$j('#inviterFORM').attr('target', target);
			  	$j('#inviterFORM').submit();
			  }
			});
			
			Lightview.show({
				href: $j('#inviterFORM').attr('rel'),
				title: '',
				options: {
					width: 570,
					height: 680
				}
			});
			
			return false;
		});
		
	}
	
	if($j('.jauge_little_white').length > 0){
		$j('.jauge_little_white').each(function(){
			init_jauge(this);
		});
	}
	
	if($j('.jauge_little_dark').length > 0){
		$j('.jauge_little_dark').each(function(){
			init_jauge(this);
		});
	}
	
	if($j('.jauge_big').length > 0){
		$j('.jauge_big').each(function(){
			init_jauge(this);
		});
	}
	
	if($j('#Investissement_Investissement').length > 0){
		$j("#total").html(parseInt($j("#Investissement_Investissement").val())*20);
		var nb_parts = (parseInt($j("#Investissement_Investissement").val()) == 0)? '?':parseInt($j("#Investissement_Investissement").val());
                $j("#parts").html(nb_parts);
	}
	
	open_modal();
	createPagination();
	init_comm();
	init_validator();
	
	
	/* --------------- PROFILL INFO ------------------ */
	
	if($j("#profilINFOS").length > 0) {
		$j("#profilINFOS").validate({
			errorElement: "em",
			onfocusout: function(element){
				$j(element).valid();
			},
//			onkeyup: function(element){
//				$j(element).valid();
//			},
			success: function(label){
				label.html('<img src="/images/accept.png" alt="" title=""/>');
			},
			rules: {
				"matrix[matuserdata][email]": {
					required: true,
					minlength: 4,
					maxlength: 255,
					email: true,
					remote: "/index.php/accueil/ajaxcheckfield?id=" + $j('#matrix_id').val()
				},
				"matrix[matuserdata][email2]": {
					onChange: "#matrix_matuserdata_email"
				},
				"matrix[matuserdata][password]": {
					minlength: 4,
					maxlength: 32,
					checkPwd: true
				},
				"matrix[matuserdata][password2]": {
					minlength: 4,
					maxlength: 32,
					onChangePwd: "#matrix_matuserdata_password"
				},
				"matrix[matuserdata][mat_civility_id]": {
					required: true
				},
				"matrix[matuserdata][first_name]": {
					required: true,
					maxlength: 255,
					checkInfo: true
				},
				"matrix[matuserdata][last_name]": {
					required: true,
					maxlength: 255,
					checkInfo: true
				},
				"matrix[adresse][rue]": {
					required: true
				},
				"matrix[adresse][code_postal]": {
					required: true,
					checkCP: true
				},
				"matrix[adresse][ville]": {
					required: true
				},
				"matrix[adresse][pays]": {
					required: true
				},
				"matrix[matuserdata][phone]": {
					checkPhone: true
				}
			},
			messages: {
				"matrix[fr][name]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir votre pseudo' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre pseudo est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre pseudo est trop long' onload='init_tooltips2()'/>",
					remote: "<img src='/images/cross.png' alt='' title='Votre pseudo est déjà pris' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][email]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir votre email' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre email est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre email est trop long' onload='init_tooltips2()'/>",
					remote: "<img src='/images/cross.png' alt='' title='Votre email est déjà enregistré' onload='init_tooltips2()'/>",
					email: "<img src='/images/cross.png' alt='' title='Veuillez saisir une adresse email correcte' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][email2]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez ressaisir votre email' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre email est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre email est trop long' onload='init_tooltips2()'/>",
					equalTo: "<img src='/images/cross.png' alt='' title='Veuillez ressaisir correctement votre email' onload='init_tooltips2()'/>",
					email: "<img src='/images/cross.png' alt='' title='Veuillez saisir une adresse email correcte' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][password]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir un mot de passe' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre mot de passe est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre mot de passe est trop long' onload='init_tooltips2()'/>",
					checkPwd: "<img src='/images/cross.png' alt='' title='Votre mot de passe est incorrecte' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][mat_civility_id]": "<img src='/images/cross.png' alt='' title='Veuillez sélectionner votre civilité' onload='init_tooltips2()'/>",
				"matrix[matuserdata][first_name]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir votre prénom' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre prénom est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre prénom est trop long' onload='init_tooltips2()'/>",
					checkInfo: "<img src='/images/cross.png' alt='' title='Votre prénom est incorrecte' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][last_name]":  {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir votre nom' onload='init_tooltips2()'/>",
					minlength: "<img src='/images/cross.png' alt='' title='Votre nom est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre nom est trop long' onload='init_tooltips2()'/>",
					checkInfo: "<img src='/images/cross.png' alt='' title='Votre nom est incorrecte' onload='init_tooltips2()'/>"
				},
				"matrix[adresse][rue]": "<img src='/images/cross.png' alt='' title='Veuillez saisir une adresse' onload='init_tooltips2()'/>",
				"matrix[adresse][code_postal]": {
					required: "<img src='/images/cross.png' alt='' title='Veuillez saisir un code postal' onload='init_tooltips2()'/>",
					checkCP: "<img src='/images/cross.png' alt='' title='Votre code postal est incorrect' onload='init_tooltips2()'/>"
				},
				"matrix[adresse][ville]": "<img src='/images/cross.png' alt='' title='Veuillez saisir un nom de ville' onload='init_tooltips2()'/>",
				"matrix[adresse][pays]": "<img src='/images/cross.png' alt='' title='Veuillez sélectionner un pays' onload='init_tooltips2()'/>",
				"matrix[matuserdata][phone]": {
					checkPhone: "<img src='/images/cross.png' alt='' title='Votre numéro de téléphone est incorrect' onload='init_tooltips2()'/>"
				}
			}
		});
		
	}
	
	
	if($j("#profilINFOS2").length > 0){
		$j("#profilINFOS2").validate({
			errorElement: "em",
			onfocusout: function(element){
				$j(element).valid();
			},
//			onkeyup: function(element){
//				$j(element).valid();
//			},
			success: function(label){
				label.html('<img src="/images/accept.png" alt="" title=""/>');
			},
			rules: {
				"matrix[matuserdata][oldpassword]": {
					required: true,
					minlength: 4,
					maxlength: 32,
					required: true
				},
				"matrix[matuserdata][password]": {
					minlength: 4,
					maxlength: 32,
					checkPwd: true
				},
				"matrix[matuserdata][password2]": {
					minlength: 4,
					maxlength: 32,
					onChangePwd: "#matrix_matuserdata_password"
				}
			},
			messages: {
				"matrix[matuserdata][oldpassword]": {
					required: "<img src='/images/cross.png' alt='' title='Vous devez saisir votre mot de passe actuel pour pouroir le modifier' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][password]": {
					minlength: "<img src='/images/cross.png' alt='' title='Votre mot de passe est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre mot de passe est trop long' onload='init_tooltips2()'/>",
					checkPwd: "<img src='/images/cross.png' alt='' title='Votre mot de passe est incorrecte' onload='init_tooltips2()'/>"
				},
				"matrix[matuserdata][password2]": {
					minlength: "<img src='/images/cross.png' alt='' title='Votre mot de passe est trop court' onload='init_tooltips2()'/>",
					maxlength: "<img src='/images/cross.png' alt='' title='Votre mot de passe est trop long' onload='init_tooltips2()'/>",
					onChangePwd: "<img src='/images/cross.png' alt='' title='Veuillez ressaisir correctement votre nouveau mot de passe' onload='init_tooltips2()'/>"
				}
			}
		});
		
	}
	
	if ($j('.actionAjax').length > 0) {
		$j('.actionAjax').click(function(){
			
			var _self = this;
			var _target = $j(_self).attr('name');
			var _from = $j(_self).attr('alt');
			
			var myurl = $j(_self).attr('href');
			var action = $j(_self).attr('rel');
			
			var delete_link = true;
			
			showLoading();
			
			$j.ajax({
				url: myurl,
				success: function(msg){
				
					switch (action) {
						case 'send_award':{
							open_alert(_self, 'Le membre a bien reçu votre award.', 'Message');
							delete_link = false;
							break;
						}
						
						case 'invite_studio':{
							open_alert(_self, 'Votre invitation à rejoindre votre studio a bien été envoyée à ce membre.', 'Message');
							break;
						}
						
						case 'add_friend':{
							open_alert(_self, 'Votre demande d\'ami a bien été envoyée à ce membre.', 'Message');
							break;
						}
						
						case 'add_favori':{
							open_alert(_self, 'Le film a bien été ajouté dans vos favoris.', 'Message');
							break;
						}
						
						case 'accept_invitation':{
							open_alert(_self, 'Vous faites désormais partie du studio de '+_from, 'Message');
							break;	
						}
						
						case 'refuse_invitation':{
							open_alert(_self, 'Vous avez refusé l\'invitation à rejoindre le studio de '+_from, 'Message');
							break;	
						}
						
						case 'demande_studio':{
							open_alert(_self, 'Votre demande d\'intégration a été envoyée à l\'administrateur du studio.', 'Message');
							break;	
						}
						
						default:{
							open_alert(_self, 'Action réussie', 'Message');
							break;
						}
					}
					
					 {
						if (_target == '') {
							if (delete_link) $j(_self).remove();
						}
						else {
							if (delete_link) $j(_target).remove();
						}
					}
					
					$j(".fancy_loading").hide();
				}
			});
			
			return false;
		});
	}
	
	if ($j('.contactFORM').length > 0) {
		$j(".contactFORM").validate({
			errorElement: "em",
			onfocusout: function(element){
				$j(element).valid();
			},
			success: function(label){
				label.html('<img src="/images/accept.png" alt="" title=""/>');
			},
			rules: {
				"contact[nom]": {
					required: true
				},
				"contact[prenom]": {
					required: true
				},
				"contact[email]": {
					required: true
				},
				"contact[message]": {
					required: true
				}
			},
			messages: {
				"contact[nom]": {
					required: "<img src='/images/cross.png' alt='' title='Vous devez saisir votre nom' onload='init_tooltips2()'/>"
				},
				"contact[prenom]": {
					required: "<img src='/images/cross.png' alt='' title='Vous devez saisir votre prénom' onload='init_tooltips2()'/>"
				},
				"contact[email]": {
					required: "<img src='/images/cross.png' alt='' title='Vous devez saisir votre email' onload='init_tooltips2()'/>"
				},
				"contact[message]": {
					required: "<img src='/images/cross.png' alt='' title='Vous devez saisir votre message' onload='init_tooltips2()'/>"
				}
			},
			submitHandler: function(form){
			
				$j(form).ajaxSubmit({
					url: $j(form).attr("action"),
					success: function(data){
						if (data == '1') {
							$j(".contactFORM").find('input, textarea').val('');
							open_alert($j(".contactFORM"), 'Votre message a bien été envoyé. Merci', 'Message');
						}
						else { 
							open_alert($j(".contactFORM"), 'Veuillez saisir les informations demandées. Merci', 'Erreur');
						}
					}
				});
				
			}
		});
			
	}
	
	if($j("#search_count").length > 0 && $j("#resultats_recherche").length > 0)
		$j("#search_count").html("("+$j("#resultats_recherche").attr('rel')+")");

        if($j(".actus_list").length > 0)
                $j('.actus_list').jScrollPane();

        if($j(".my_notifs").length > 0)
                $j('.my_notifs').jScrollPane();

        if($j("ol.step").length >0){
            i = 0;
            $j("ol.step li").each(function (i) {
                i = i+1;
                $j(this).addClass("step_"+i);
            });
        }
        if($j("ol.number").length >0){
            i = 0;
            $j("ol.number li").each(function (i) {
                i = i+1;
                $j(this).addClass("number_"+i);
            });

        }
        
        if($j("#cccOnglets").length > 0){
                $j(".cccOnglets").corner( "top");
                $j(".cccPages").corner();
                $j("#cccOnglets").tabs(1);
        }

        $j("#header_login").corner("bottom");
        $j("#mainBody").corner();

        //$j.jGrowl("A message with a header", { header: 'Important' });
        
        if(alerte['msg'] != ''){
            open_alert('#fancy_loading', alerte['msg'], alerte['title'], '', '');
        }

});

/* ----------------- FUNCTIONS -------------------- */
function init_validator(){
	
		jQuery.validator.addMethod("checkLogin", function(value, element) {
			var pattern = /^([a-zA-Z]){1}([a-zA-Z0-9_])*$/;
			return (element.value.match(pattern) !== null);
		});
		jQuery.validator.addMethod("checkPwd", function(value, element) {
			var pattern = /^([^\s])*$/;
			return (element.value.match(pattern) !== null);
		});
		jQuery.validator.addMethod("checkInfo", function(value, element) {
			var pattern = /^([a-zA-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ\-\s\'])*$/;
			return (element.value.match(pattern) !== null);
		});
		
		jQuery.validator.addMethod("checkCP", function(value, element) {
			//var pattern = /^([0-9]{5})*$/;
			var pattern = /^([a-zA-z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ\-\s\'])*$/;
			return (element.value.match(pattern) !== null);
		});
		jQuery.validator.addMethod("checkPhone", function(value, element) {
			var pattern = /^([0-9\+\s\-\(\)])*$/;
			return (element.value.match(pattern) !== null);
		});
		$j.validator.addMethod("onChange", function(value, element, param){
			return this.optional(element) || !(value != $j(param).val());
		}, "<img src='/images/cross.png' alt='' title='Veuillez ressaisir correctement votre email' onload='init_tooltips2()'/>");
		
		$j.validator.addMethod("onChangePwd", function(value, element, param){
			return ($j(param).val() == '' && this.optional(element)) || value == $j(param).val();
		}, "<img src='/images/cross.png' alt='' title='Veuillez ressaisir correctement votre mot de passe' onload='init_tooltips2()'/>");
}

function init_comm(){
	
	if ($j('.comDelete').length > 0) {
		$j('.comDelete').click(function(){
			var myurl = $j(this).attr('href');
			
			$j.ajax({
				url: myurl,
				success: function(msg){
					$j('#lola').html(msg);
					init_comm();
				}
			});
			
			return false;
		});
	createPagination();
	}
	
	if ($j('.comEditable').length > 0) {	
		$j('.comEditable').each(function(){
			var myurl = $j(this).attr('rel');
			$j(this).editInPlace({
				type     : 'textarea',
				url: myurl,
				show_buttons: true
			});
		});
	createPagination();
	}
	
	if ($j('#comForm2').length > 0) {	
		$j('#comForm2').ajaxForm({
			target: ".comContainer",
			beforeSubmit: function(formData, jqForm, options){
				if(formData[6].value == ''){
					open_alert('#comForm2','Veullez saisir un commentaire. Merci','Erreur','','');
					return false;
				}
			},
			success: function(){
				Lightview.hide();
				init_comm();
			}
		});
	createPagination();
	}


        if ($j('.comForm').length > 0) {
		$j('.comForm').ajaxForm({
			target: ".comContainer",
			beforeSubmit: function(formData, jqForm, options){
				if(formData[6].value == ''){
					open_alert('.comForm','Veullez saisir un commentaire. Merci','Erreur','','');
					return false;
				}
			},
			success: function(){
				Lightview.hide();
				init_comm();
			}
		});
            createPagination();
	}
        
	/*
	if ($j('.comForm').length > 0) {
            $j('.comForm').validate({
		submitHandler: function(form){
                    
                    $j(form).ajaxSubmit({
                            //target: ".comContainer",
                            beforeSubmit: function(formData, jqForm, options){
                                if(formData[6].html() == ''){
                                        open_alert('.comForm','Vous devez saisir un commentaire','Erreur','','');
                                        return false;
                                }
                            },
                            success: function(data){
                                Lightview.hide();

                                if($j(form).attr('rel') != 'reply'){
                                    init_comm();
                                    createPagination();
                                }
                                else {
                                    alert('data');
                                    $j('#comment_num'+$j(form).attr('to')).html(data);
                                }
                            }
                    });
                    return false;
                }
            });
	}
	*/
}

function showTakeatour(){
	
}

	
function createPagination(){
	
	var search_count = 0;
	
	if ($j(".pagenavi_src").length > 0) {
		search_count = $j("#resultats_recherche").attr('rel');

		$j(".pagenavi_src").pagination($j("#resultats_recherche").attr('rel'), {
			items_per_page: $j("#resultats_recherche").attr('alt'),
			target: "#resultats_recherche_container",
			url_ajax: $j("#resultats_recherche").attr('name'),
			num_display_entries:5,
			num_edge_entries:3,
			callback: handlePaginationClickAjax,
			next_text: 'Suiv',
			prev_text: 'Préc'
		});
		if ($j("#resultats_recherche").children().length == 0) 
			$j(".pagenavi").hide();
			
		$j(".pagenavi a").click(function(){
			return false
		});
	}
	
	if ($j(".commnavi_src").length > 0) {
		
		search_count = $j(".commentlist").children().length;
		
		$j(".commnavi_src").pagination($j(".commentlist").children().length, {
			items_per_page: 5,
			target: ".commentlist",
			callback: handlePaginationClick,
			num_display_entries:5,
			num_edge_entries:3,
			next_text: 'Suiv',
			prev_text: 'Préc'
		});
		if ($j(".commentlist").children().length == 0) 
			$j(".commnavi").hide();
		$j(".commnavi a").click(function(){
			return false
		});
	}
	
	if($j("#search_count").length > 0 && search_count) $j("#search_count").html("("+search_count+")");
}

function handlePaginationClick(page_index, jq){

	var nav = jq;

	$j(".commnavi").empty();
	$j(nav).children().prependTo(".commnavi");
	
	if(curr_page > page_index) var sens = -1;
	else var sens = 1;

	curr_page = page_index;

	$j(this.target).children().css('display','none');
	
    var items_per_page = this.items_per_page;
	var members = $j(this.target).children();
    var max_elem = Math.min((page_index+1) * items_per_page, members.length);
	

    for(var i=page_index*items_per_page;i<max_elem;i++)
    {
		$j(members[i]).css('display','block');
    }

    return false;
}

function handlePaginationClickAjax(page_index, jq){

	var nav = jq;
	var url_ajax = this.url_ajax;
	var target = this.target;
	
	$j(".pagenavi").empty();
	$j(nav).children().prependTo(".pagenavi");
	
	showLoading();
	
	if(curr_page != (page_index+1)){
		$j.ajax({
			url: this.url_ajax + '?page=' + (page_index+1),
			success: function(msg){
				$j(target).html(msg);
				$j(".fancy_loading").hide();
			}
		});
		curr_page = (page_index+1);
		//new Ajax.Updater('resultats_recherche_container', '/search/recherche_result/orderby/top_d/s/topmembres', {asynchronous:true, evalScripts:false, onComplete:function(request, json){init_page()}, onLoading:function(request, json){showLoading();}, onSuccess:function(request, json){$j(".fancy_loading").hide();}});; return false;
	}
	else{
		$j(".fancy_loading").hide();
	}
    return false;
}

function close_alert(id){

    setCookie('pc_alertes_' + id, 'off', 365);
    
    $j('#fancy_loading').qtip('destroy');
    
}

function open_alert(self,msg,title,action,referer){
	
	var content = '';
	
	switch(msg){
		case 'notlogged':{
			
			content += '<form action="'+ action +'" method="post" id="gotoLogin">';
			content += '<input type="hidden" name="referer" value="'+ referer +'"/>';
			content += 'Vous devez être connecté pour pouvoir effectuer cette action.';
			content += '<a href="#" onclick="$j(\'#gotoLogin\').submit(); return false;">cliquez ici</a>'
			content += '</form>';
			
			break;
		}
		case 'add_to_confirm':{
			content += "Confirmer en cliquant <a href='#' onclick=\"$j.ajax({ type: 'POST', dataType: 'html', url: '" +  action + "' }); $j('#qtip-blanket').hide(); $j('.qtip').hide(); $j('#" + referer + "').hide(); return false;\">ici</a>";
			
			break;
		}		
		case 'login':{
			
			content += 'Vos identifiants sont incorectes. Veuillez les ressaisir. Merci';
			
			break;
		}
		case 'mdp':{
			
			content += 'Votre adresse email n\'a pas été reconnu. Merci';
			
			break;
		}
		default:{
			content = msg;
			break;
		}
		
			
	}
	
	$j(self).qtip({
		content: {
			title: {
				text: title,
				button: 'Fermer'
			},
			text: content
		},
		position: {
			target: $j('body'), // Position it via the document body...
			corner: 'center' // ...at the center of the viewport
		},
		show: {
			when: {event:'click'},
			ready: true
		},
		hide: false,
		style: {
			width: {
				max: 400,
				min: 100
			},
			padding: '14px',
			border: {
				width: 9,
				radius: 9,
				color: '#666666'
			},
			name: 'light'
		},
		api: {
			onHide: function(){
				$j(self).qtip('destroy');
			}
		}
	});

}

function open_modal(){

	if ($j('.errorFORM').length > 0 && $j('.errorFORM').find('li').length > 0) {
		/* --------------- MODAL BOX --------------*/
		
		// Create the modal backdrop on document load so all modal tooltips can use it
		$j('<div id="qtip-blanket">').css({
			position: 'absolute',
			top: $j(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
			left: 0,
			height: $j(document).height(), // Span the full document height...
			width: '100%', // ...and full width
			opacity: 0.7, // Make it slightly transparent
			backgroundColor: 'black',
			cursor:'pointer',
			zIndex: 5000 // Make sure the zIndex is below 6000 to keep it below tooltips!
		}).appendTo(document.body) // Append to the document body
		.hide().click(function(){
			$j('.errorFORM').qtip('hide');
		}); // Hide it initially
		
		$j('.errorFORM').qtip({
			content: {
				title: {
					text: 'Erreur(s)',
					button: 'Fermer'
				},
				text: $j('.errorFORM').html()
			},
			position: {
				target: $j(document.body), // Position it via the document body...
				corner: 'center' // ...at the center of the viewport
			},
			show: {
				ready: true
			},
			hide: false,
			style: {
				width: {
					max: 350,
					min: 100
				},
				padding: '14px',
				border: {
					width: 9,
					radius: 9,
					color: '#666666'
				},
				name: 'light'
			},
			api: {
				beforeShow: function(){
					// Fade in the modal "blanket" using the defined show speed
					$j('#qtip-blanket').fadeIn(this.options.show.effect.length);
				},
				beforeHide: function(){
					// Fade out the modal "blanket" using the defined hide speed
					$j('#qtip-blanket').fadeOut(this.options.hide.effect.length).remove();
				},
				onHide: function(){
					$j('.errorFORM').qtip('destroy');
				}
			}
		});
		/*
		Lightview.show({
			href: '.errorFORM',
			title: 'Erreur',
			autosize:true
		});
		*/
	}
}

function init_tooltips(){
		
	$j('*').not('.lightview').not('.rotator_content img').not('.notitle').filter(function(){ return ($j(this).attr('title') != ''); }).each(function(){
		$j(this).qtip({
		   content: $j(this).attr('title'),
		   position: {
	          corner: {
	             tooltip: 'bottomMiddle', // Use the corner...
	             target: 'topMiddle' // ...and opposite corner
	          }
	       }, // Don't specify a hide event
	       style: {
	          border: {
	             width: 1,
	             radius: 5,
				 color: '#ff4200'
	          },
		      background: '#ff4200',
		   	  color: '#FFFFFF',
	          padding: 2, 
	          textAlign: 'center',
	          tip: true, // Give it a speech bubble tip with automatic corner detection
	          name: 'blue' // Style it according to the preset 'cream' style
	       }
		});
		$j(this).attr('title','');
	});
	
	
}

function init_tooltips2(){
		
	$j('*').not('.notitle').filter(function(){ return ($j(this).attr('title') != ''); }).each(function(){
		$j(this).qtip({
		   content: $j(this).attr('title'),
		   position: {
	          corner: {
	             tooltip: 'bottomMiddle', // Use the corner...
	             target: 'topMiddle' // ...and opposite corner
	          }
	       },
		   	hide : { delay: 1000 },
			show: { ready: false, solo: true },
			style: {
	          border: {
	             width: 1,
	             radius: 5,
				 color: '#ff0000'
	          },
		      background: '#ff0000',
		   	  color: '#FFFFFF',
	          padding: 2, 
	          textAlign: 'center',
	          tip: true, // Give it a speech bubble tip with automatic corner detection
	          name: 'blue' // Style it according to the preset 'cream' style
	       }
		});
		$j(this).attr('title',null);
	});
}

function showFile(target, file){
	$j(target+' .cancel a').css({
		marginBottom: '0',
		borderBottom: '0 none'
	});				
	$j(target+' .fileName').html('<a href="'+file+'" target="_blank">'+$j(target+' .fileName').html()+'</a>');				
	$j(target+' .fileUploadProgress').fadeOut(500);	
}

function showSub(inc)
{
	var zetop = inc*28;
	$j(".subnav_cont").stop().animate({'top':-(zetop)},200);
	
}

function showVideo(id) {
	$j('#thumb_film').hide();
	$j('#video').show(); 
	$j('#rotator div').hide();
	$j('#rotator #video_'+id).show();
}

function create_tooltip(error, element){
	
	
	if(typeof(error) == 'object')
		var err = error.html();
	else
		var err = error;

	$j(element).qtip({
	   content: err,
	   position: {
          corner: {
             tooltip: 'bottomMiddle', // Use the corner...
             target: 'topMiddle' // ...and opposite corner
          }
       },
       show: {
	   		when: false,
			ready: true
	   },
       hide: {
	   		when: { event: 'keyup' },
			ready: true
	   }, // Don't specify a hide event
       style: {
          border: {
             width: 1,
             radius: 5,
			 color: '#FF0000'
          },
	      background: '#FF0000',
	   	  color: '#FFFFFF',
          padding: 2, 
          textAlign: 'center',
          tip: true, // Give it a speech bubble tip with automatic corner detection
          name: 'blue' // Style it according to the preset 'cream' style
       }
	});
	all_tooltips.push($j(element));
	
}

function create_tooltip2(error, element){
	
	if(typeof(error) == 'object')
		var err = error.html();
	else
		var err = error;

	$j(element).qtip({
	   content: err,
	   position: {
          corner: {
             tooltip: 'bottomLeft', // Use the corner...
             target: 'topRight' // ...and opposite corner
          }
       },
       show: {
	   		when: false,
			ready: true
	   },
       hide: {
	   		when: { event: 'keyup' },
			ready: true
	   }, // Don't specify a hide event
       style: {
          border: {
             width: 1,
             radius: 5,
			 color: '#FF0000'
          },
	      background: '#FF0000',
	   	  color: '#FFFFFF',
          padding: 2, 
          textAlign: 'center',
          tip: true, // Give it a speech bubble tip with automatic corner detection
          name: 'blue' // Style it according to the preset 'cream' style
       }
	});
	all_tooltips.push($j(element));
	
}


function create_tooltip3(error, element){
	
	$j(element).qtip({
	   content: error,
	   position: {
          corner: {
             tooltip: 'leftMiddle', // Use the corner...
             target: 'rightMiddle' // ...and opposite corner
          }
       },
       show: {
	   		when: false,
			ready: true
	   },
       hide: {
	   		when: { event: 'keyup' },
			ready: true
	   }, // Don't specify a hide event
       style: {
          border: {
             width: 1,
             radius: 3,
			 color: '#01dc01'
          },
	      background: '#01dc01',
	   	  color: '#01dc01',
          padding: 0, 
          textAlign: 'center',
          tip: true, // Give it a speech bubble tip with automatic corner detection
          name: 'blue' // Style it according to the preset 'cream' style
       }
	});
	all_tooltips.push($j(element));
	
}

function close_tooltips(){
	$j(".qtip").remove();
}
/*
function slider(part, max, jackpot, prix){
	var el = $j('#setGain');
	
	var updateGain = function(a){
		if (a >= max) {
			el.html(Math.round(jackpot * prix * ((3 * part / max) * a - part)));
		}
		else {
			el.html(Math.round(prix * ((3 * part / max) * a - part)));
		}
	};
	
	// We call that function to initially set the color output
	updateGain();
	
	$j('div.slider.advanced').each(function(el, i){
		var slider = new Slider(el, $j(el).find('.knob'), {
			steps: max * 1.33,
			wheel: true, // Using the mousewheel is possible too
			onChange: function(){
			
				updateGain(this.step);
			}
		}).set(0);
	});
}
*/
function init_jauge(jauge){
	
	var new_color = 'FF0000';
	var ratio = parseInt($j(jauge).attr("rel"));
	var new_width = parseInt($j(jauge).width())*parseInt($j(jauge).attr("rel"))/100;
	
        
	if(ratio > 33) new_color = 'FFA800';
	if(ratio > 66) new_color = '00FF00';
        if(ratio == 100) new_color = '0BC9E4';

        if(new_width < 6.61) new_width = 6.61;

	$j(jauge).find('p').stop().animate({ backgroundColor : '#'+new_color, paddingLeft : new_width }, 2000);
	
}

function init_page(){
	
	$j('.jauge_little_white').each(function(){
		init_jauge(this);
	});
	createPagination();
	init_tooltips();
}


function update_cursor(a){
	$j('.part_slider_text').html(a);
	$j('.part_slider').css('margin-left',(parseInt($j('.part_slider').width())/2*(-1)) + 'px');
}

function init_membre_avatar(target,id, width, height, path){
	var settings = {
		flash_url : "/swf/swfupload.swf",
		upload_url: "/ws/upload.php?id="+id+"&width="+width+"&height="+height+"&path="+path,
		file_size_limit : "1500",
		file_types : "*.jpg;*.gif;*.png",
		file_types_description : "Type d'images",
		file_upload_limit : 100,
		file_queue_limit : 0,
		custom_settings : {
			progressTarget : "fsUploadProgress",
			//cancelButtonId : "btnCancel",
			completeTarget : target
		},
		debug: false,

		// Button settings
		button_image_url : '/images/inscription/upload_button.jpg',
		button_width : 107,
		button_height : 28,
		button_placeholder_id: "button",
		button_window_mode : 'transparent',
		
		// The event handler functions are defined in handlers.js
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,
		queue_complete_handler : queueComplete	// Queue plugin event
	};
	swfu = new SWFUpload(settings);
	/*
	$j('#uploadsubmit').swfupload({
		upload_url: "/ws/upload.php?id="+id+"&width="+width+"&height="+height+"&path="+path,
		file_size_limit : "1500", 
		file_types : "*.jpg;*.gif;*.png",
		file_types_description : "All Files",
		file_upload_limit : "100",
		flash_url : "/swf/swfupload.swf",
		button_image_url : '/images/inscription/upload_button.jpg',
		button_width : 107,
		button_height : 28,
		button_placeholder : $j('#button')[0],
		button_window_mode : 'transparent',
		custom_settings : {something : "here"}
	})
		.bind('swfuploadLoaded', function(event){
			//console.log('uplodaded');
			init_membre_avatar(target,id, width, height, path);
		})
		.bind('fileQueued', function(event, file){
			$j(this).swfupload('startUpload');
		})
		.bind('fileQueueError', function(event, file, errorCode, message){
			//console.log('fileQueueError');
		})
		.bind('fileDialogStart', function(event){
			//console.log('fileDialogStart');
		})
		.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
			//console.log('fileDialogComplete');
		})
		.bind('uploadStart', function(event, file){
			showLoading();
		})
		.bind('uploadProgress', function(event, file, bytesLoaded){
			$j('#progress').html('chargement   '+parseInt(bytesLoaded*100/file.size)+'%');
		})
		.bind('uploadSuccess', function(event, file, serverData){
			$j(target).attr('src', serverData);
			$j(".fancy_loading").hide();
		})
		.bind('uploadComplete', function(event, file){
			$j(this).swfupload('startUpload');
		})
		.bind('uploadError', function(event, file, errorCode, message){
			//console.log('uploadError');
		});*/
}

var loadingTimer;
var loadingFrame = 1;

function getViewport() {
	return [$j(window).width(), $j(window).height(), $j(document).scrollLeft(), $j(document).scrollTop() ];
};

function animateLoading() {
	if (!$j("#fancy_loading").is(':visible')){
		clearInterval(loadingTimer);
		return;
	}

	$j("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px');

	loadingFrame = (loadingFrame + 1) % 12;
};

function showLoading() {
	clearInterval(loadingTimer);

	var pos = getViewport();

	$j("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show();

	loadingTimer = setInterval(animateLoading, 66);
};

function hideLoading() {
	$j(".fancy_loading").hide();
};

//Action après publication sur Facebook
function callback (msg) {
	return true;
} 


function focusMe(elt)
{
		 var el = $j(elt);
		 if(!el)
		 return false;
		 
		 var defaultText = el.val();
		
		el.focus(function(e){
			if(el.val()==defaultText)
			el.val('');
			
			})
		.blur(function(e) {		
			if(el.val()=='')
			el.val(defaultText);
			
			});
			
			
		 
		 
}



function setCookie(c_name,value,expiredays,path)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+
	((path==null) ? ";path=/" : ";path="+path);
}



function getCookie(c_name)
{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    {
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    }
	  }
	return "";
}

function slider2(part) {
	$j('.tot').html(0);

	$j('.recup').each(function(){
		
		var recup = parseFloat($j(this).attr('rel'));
		var result = part*recup;
		$j(this).html(result.toFixed(2));
		
		var old = parseFloat($j('#'+$j(this).attr('alt')).html());
		var tot = parseFloat(old) + parseFloat(result);
		
		$j('#'+$j(this).attr('alt')).html(tot.toFixed(2));
	});
}
