// JavaScript Document
var debugMode = true; // affiche les debug log ou non ccf function debug js
// var loadVideo_timerId = 0;
var ypg = {
	debug: true,
	lib_js:{
		jQuery:'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js',
        swfobject:'https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js'
	},
	youtube:{
		channel : {
			'en':"http://www.youtube.com/user/YellowPagesGroupCa",
			'fr':"http://www.youtube.com/user/GroupePagesJaunes"
		},
		default_video : {
            'en': "2EU2nMVoCus", // "http://www.youtube.com/YellowPagesGroupCa#p/u/17/2EU2nMVoCus", //'http://www.youtube.com/watch?v=2EU2nMVoCus",
            'fr': "Nm-OBS-PzZY" // "http://www.youtube.com/GroupePagesJaunes#p/u/13/Nm-OBS-PzZY"
		},
        init_gallery : function() {
            debug('function init_gallery()');
            if($('#mediagallery').length <= 0){
				var mediagallery_title= "Video Tour";
				if(getLang()=="fr"){mediagallery_title = "Présentation Vidéo";}
				$('body').append("<div class='mediagallery' id='mediagallery'>"
                    +"<h1 id='mediagallery_title'>"+mediagallery_title+"</h1>"
                    +"<a href='"+ypg.youtube.channel[getLang()]+"'></a>"
                    +"</div>");
			}
            
            Modernizr.load([
            {
                test : window.jQuery,
                nope : [ypg.lib_js.jQuery]
            },
            {
                test : window.swfobject,
                nope : [ypg.lib_js.swfobject]
            },
            {
                test : ($('.mediagallery').length > 0),
                yep : ['/js/jquery-ui-1.8.11.custom.min.js','/js/jquery.mousewheel.min.js', '/js/jquery.mediaGallery.js', '/css/mediagallery/mediagallery_normal.css' ],
                complete : function () {
                    if( ($('#mediagallery_video_wrap').length <= 0) ){
                        debug('$("#mediagallery").mediaGallery({autoplay:1});');
                        $("#mediagallery").mediaGallery({autoplay:1});
                    }
                    $('#mediagallery_video_descr').append("<div class='slider'></div>");
                }
            }
            ]); 
        },
		set_gallery : function(youtube_id){
			debug("function set_gallery("+youtube_id+")");
            
            // instanciate slider (COPIED FROM MEDIAGALLERY.JS)
            var vert_scroll = $("#mediagallery_scroll");
            if( !vert_scroll.hasClass('ui-slider')) {
                debug('$("#med_list_cont").height() : '+$("#med_list_cont").height());
                vert_scroll.slider({
                    orientation: "vertical"
                    , range: "max"
                    , min: 0
                    , value: $("#med_list_cont").height()+$('#mediagallery_more').height()
                    , max: $("#med_list_cont").height()
                    , slide: function( event, ui ) {
                        $("#med_list_cont").css("margin-top",((($("#med_list_cont").height()-ui.value))*-1)+"px");
                    }
                    , change: function(event, ui) {
                        $("#med_list_cont").css("margin-top",((($("#med_list_cont").height()-ui.value))*-1)+"px");
                    }
                });
                
                $("#med_list_cont , #mediagallery_more").mousewheel( function(event, delta) {
                    var speed = 30;
                    var sliderVal = vert_scroll.slider("value");//read current value of the slider
                    sliderVal += (delta*speed);//increment the current value
                    vert_scroll.slider("value", sliderVal);//and set the new value of the slider
                    event.preventDefault();//stop any default behaviour
                });
            }
            
            // si on a prevu une video youtube_id
            if(youtube_id){
                debug('move ' + youtube_id + ' on 1st position');
                $('#med_list_cont').prepend($('#mediagallery_list #'+youtube_id).parent());
            } else {
                debug('no first video, default : '+ypg.youtube.default_video[getLang()]);
                $('#med_list_cont').prepend($('#mediagallery_list #'+ypg.youtube.default_video[getLang()] ).parent());
            }
            
            // launch 1st video
            $('#mediagallery_list li:first').trigger('click');
		}
	}
}

//PROTECTION DES COURRIELS DES BOTS
var mailto      = 'mailto:';
var arroba      = '@';
var courriels   = new Array(6);
courriels[4]    = 'custserv-ont';
courriels[5]    = 'ypg.com';

courriels[2]    = 'custserv-que';
courriels[3]    = 'ypg.com';

courriels[0]    = 'call.centre';
courriels[1]    = 'ypg.com';


$(document).ready(function(e) {
        if($.browser.msie){$('body').addClass("ie"+IE().version);}
        
        //Tooltip for image-forms
        $("#lien_regles a").tooltip({
		position: "center left",
		offset: [0, -3],
		effect: "fade",
		opacity: 1
	});
        
         
	//Binding clicks for bottom bar
	$('.bottomBar_navLink').click(function(){
		bottomBarIndex = $(this).index();
                
                $('.yt-iframe').attr('src',$('.yt-iframe').attr('src'));
                $('.yt-iframe').removeClass('yt-iframe');
		$('.bottomBar_navLink').removeClass('selected');
                
          
		$('.bottomBar_content').slideUp();
		if ( $('.bottomBar_content:nth-child('+(bottomBarIndex+1)+')').is(':hidden') ){
                         var bar_content = $('.bottomBar_content:nth-child('+(bottomBarIndex+1)+')');
                        bar_content.find('iframe').addClass('yt-iframe');
                        
			$(this).addClass('selected');
			$('.bottomBar_content:nth-child('+(bottomBarIndex+1)+')').slideDown();
                        
		}
		return false;
	});
	
	
       //REDIRECTION DANS SOLUTIONS/POUR-MOTEURS-DE-RECHERCHE
       $('#linkSES3').trigger('click');
       
       //PROTECTION DES COURRIELS DES BOTS
       $('#contactCourriel1').mouseover(function() {
            $('#contactCourriel1').attr('href',mailto+courriels[4]+arroba+courriels[5]);
        });
        
         $('#contactCourriel1').mouseout(function() {
             $('#contactCourriel1').attr('href','#');
        });
        
       $('#contactCourriel2').mouseover(function() {
            $('#contactCourriel2').attr('href',mailto+courriels[2]+arroba+courriels[3]);
        });
        
         $('#contactCourriel2').mouseout(function() {
             $('#contactCourriel2').attr('href','#');
        });
        
        $('#contactCourriel3').mouseover(function() {
            $('#contactCourriel3').attr('href',mailto+courriels[0]+arroba+courriels[1]);
        });
        
         $('#contactCourriel3').mouseout(function() {
             $('#contactCourriel3').attr('href','#');
        });
    
	info("!! IE:"+ IE() +" version:"+ IE().version);
        
	// warning("!! IE:"+ IE() +" version:"+ IE().version);
	IE6_alert();
	subMenu();  // main navigation dropdown
	subMenuMarketing(); //SubMenu Marketing advice
	subMenuAbout();
	subMenuContact();
	pageInit(); // page content interactivities initialisation
	if(! $('body').is('.diagnostic') ){
		debug("$('body').is('.diagnostic') : "+$('body').is('.diagnostic'));
		initFormBoxLoad();
	}
	homeInit();
	accordionInit();
	if( $('body').is('.home') ){termsInit();}
	if( $('body').is('.solutions-ses-search-engine-solutions') ){sesInit();}
	initSolutionBox();
	// ajaxNavigationInit();
	if( $('.contact form').length > 0 && typeof initForm == 'function' ){
		// initForm();
	}else if( $('.contact form').length > 0 ){
	}
	msp_ssInit(); //MSP SlideShow initialisation
    
    // !!! keep this code out of completeFancyForm, it causes conflicts between fancybox v/s bottomBar
    //Add wrappers for bottomBar form
    $(".bottomBar_content #ContactNamefirstConsult").parent().wrapAll("<div class=\"form_left\"></div>");
    $(".bottomBar_content #ContactNameConsult, .bottomBar_content #ContactEmailConsult").parent().appendTo('.bottomBar_content .form_left');
    $(".bottomBar_content #ContactCompanyConsult").parent().wrapAll("<div class=\"form_right\"></div>");
    $(".form2 .phone1, .bottomBar_content #ContactPhonedirectConsult").parent().appendTo('.bottomBar_content .form_right');
        
	$('#learnMore').click(function(event){
		event.preventDefault();
		var url = $("#slideshow li:visible a").attr('href');
		debug("Slideshow URL : "+url);
		// $.address.crawling(true);
		if(url.length>0){
			// location.replace(url);
			if(url=='#videoTour'){
				location.assign($('#menu_whyus').attr('href'));
			}else{
				location.assign(url);
			}
		}else{
			location.assign('/pricing/overview');
		}
		// $.address.crawling(false);
		return;
	});
	//Fancybox zoom icons - Big zoom icon appears on hover
	$('a.zoom, a.zoomBox').hover(function() {
		$(this).parent().children('.zoomBox').children('.zoomBigIcon').stop().fadeTo(200, 1);
		$(this).parent().children('.zoomBox').children('.zoomImg').stop().fadeTo(200, 0.5);
	}, function() {
		$(this).parent().children('.zoomBox').children('.zoomBigIcon').stop().fadeTo(200, 0);
		$(this).parent().children('.zoomBox').children('.zoomImg').stop().fadeTo(200, 1);
	});
	$('.zoomBigIcon').click(function() {
		$(this).parent().click();
	});
	$('#YPGBottomBar').find('div.li_title,.li_boxClose').click(function() {
		//Check if click is on the selected li
		if($(this).closest('li').hasClass('selected')){
			$('#YPGBottomBar').find('li').removeClass('selected');
			$(this).trackEvent360("BOTTOMBAR","Click-Close");
		}else{
			$('#YPGBottomBar').find('li').removeClass('selected');
			$(this).closest('li').addClass('selected');
			$(this).trackEvent360("BOTTOMBAR","Click-Open");
		}
	});
	$('#bottomBarOpen').click(function() {
		$('#bottomBarOpen').animate({
			bottom: '-20px'
		},500, function() {
			$('#YPGBottomBar').animate({
				bottom: 0
			}, 500);
		});
		$.cookie('bottomBar', null, {expires: 7, path: '/'});
	});
	$('#bottomBarClose').click(function() {
		$('.bottomBar_content').hide();
		$('.bottomBar_navLink').removeClass('selected');
		$('#YPGBottomBar').animate({
			bottom: '-40px'
		},500, function() {
			$('#bottomBarOpen').animate({
				bottom: '40px'
			}, 500);
		});
		$.cookie('bottomBar', 'closed', {expires: 7, path: '/'});
	});
	if($.cookie('bottomBar')){
		$('#YPGBottomBar').css('bottom','-40px');
		$('#bottomBarOpen').css('bottom','40px');
	}
		
	//Make elements not selectable
	$('.noselect').live('selectstart dragstart', function(evt){evt.preventDefault();return false;});
	//--- Slider home--------------------------------------
    //Hide all
    $('#slideshow li').not(':first').hide();
    var currentIndex = $('#slideshow li:first').index();
	var sliderTimeout;
	var timerInterval;
	var pause = false;
	var timer = 1.0;
	setTimer = function() {
		clearInterval(timerInterval);
		timerInterval = setInterval(function() {
			$('.slideLinkHover').css('width', timer * (188 / 500) + 7.5);
			timer += 1;
		}, 10);
	}
    //Define de sliderTime callback
    sliderTimer = function(duration) {
		if(duration == null)
			duration = 5000;
		//Clear sliderTimeout instance
		clearTimeout(sliderTimeout);
        sliderTimeout = setTimeout(function() {
			clearInterval(timerInterval);
			timer = 1.0;
            //Hide current slide
			$('#slideshow li').eq(currentIndex).fadeOut(750);
			$('#slideLink' +(currentIndex)).parent().find('.pause').fadeTo(500, 0).css('display', 'none');
			//Adjust navigation
			$('#slideLink' +currentIndex).fadeTo(750, 0.5);
			//Check if current slide is last
			if($('#slideshow li').eq(currentIndex + 1).length)
			{
				$('#slideshow li').eq(currentIndex + 1).fadeIn(750);
				$('.slideLinkHover').animate({
					left: '+=193px',
					width: '1px'
				}, 500, function() {
					//Callback
					setTimer();
					sliderTimer();
				});
				$('#slideLink' +(currentIndex + 1)).fadeTo(750, 1);
				$('#slideLink' +(currentIndex + 1)).parent().find('.pause').fadeTo(500, 1).css('display', 'inline-block');
			}else{
				$('#slideshow li:first').fadeIn(750);
				$('.slideLinkHover').animate({
					left: '0px',
					width: '1px'
				}, 500, function() {
					//Callbacks
					setTimer();
					sliderTimer();
				});
				$('#slideLink0').fadeTo(750, 1);
				$('#slideshow li:first .pause').fadeIn(750);
				$('#slideLink0').parent().find('.pause').fadeTo(500, 1).css('display', 'inline-block');
			}
			//Define next index
			if(!$('#slideshow li').eq(currentIndex + 1).length){ 
				currentIndex = 0;
			}else{currentIndex += 1;}
			timer = 1.0;
		}, duration);
	}
	//Set slider navigation clicks
	$('.slideLink').click(function() {
		if(!$('.slideLink').is(':animated')) {
			clearInterval(timerInterval);
			//Hide previous slide
			$('#slideshow li').eq(currentIndex).fadeOut(750);
			//Show clicked slide
			$('#slideshow li').eq($(this).index('.slideLink')).fadeIn(750);
			$('#slideLink' +(currentIndex)).parent().find('.pause').fadeTo(500, 0).css('display', 'none');
			//Adjust navigation
			//Calculate movement
			var movement = 193*($(this).index('.slideLink') - currentIndex);
			$('.slideLinkHover').animate({
				left: '+=' +movement,
				width: '1px'
			}, 500, function() {
				timer = 1.00;
				//Callbacks
				setTimer();
				sliderTimer();
			});
			$('#slideLink' +currentIndex).fadeTo(750, 0.5);
			$('#slideLink' +$(this).index('.slideLink')).fadeTo(750, 1);
			$('#slideLink' +$(this).index('.slideLink')).parent().find('.pause').fadeTo(500, 1).css('display', 'inline-block');
			//Set new index
			currentIndex = $(this).index('.slideLink');
			pause = false;
			$('.slideShow_nav .pause').removeClass('true');
		}
	});
	//Set slider pause buttons
	$('.slideShow_nav .pause').click(function() {
		//Check if not pausing
		if(!pause)
		{
			clearInterval(timerInterval);
			clearTimeout(sliderTimeout);
			pause = true;
			$(this).addClass('true');
		}else{
			setTimer();
			sliderTimer(5000 - (timer * 10));
			pause = false;
			$(this).removeClass('true');
		}
	});
	sliderTimer();
	setTimer();
	//-----------------------------------------------------------------------------------------------------------------------------------
    //--- Animated grid ------------------------------------------------------------------------------------------------------------------
    $('.animatedGrid').children('div').each(function(i) {
        var col = $(this).attr('class').substr(4, 1);
        var row = $(this).attr('class').substr(1, 1);
		$(this).css('position', 'absolute');
		$(this).css('left', col*188 - 188);
		$(this).css('top', row*188 - 188 + 50);
		$('.animatedGrid').css('height', row*190 + 200);
        nbCols = 0;
        $('.animatedGrid').children('div').each(function(i) {
            if(nbCols < $(this).attr('class').substr(4, 1))
                nbCols = $(this).attr('class').substr(4, 1);
        });
        $('.c' +nbCols).addClass('last');
		$('.c' +(nbCols - 1)).addClass('last');
    });
    $('.animatedGrid').children('div').click(function() {
        //Make sure nothing is animated
        if(!$('.animatedGrid').find('div').is(':animated'))
        {
            grid = new Object;
            grid.object = $('.animatedGrid');
            grid.block = new Object;
            grid.activeBlock = new Object;
            grid.block.baseWidth = 170;
            grid.block.baseHeight = 170;
			grid.block.margin = 18;
            grid.block.expandWidth = grid.block.baseWidth*3 + grid.block.margin*2;
            grid.block.moveLengthX = grid.block.baseWidth*2 + grid.block.margin*2;
            grid.block.moveLengthY = grid.block.baseHeight + grid.block.margin;
            grid.block.animateMoveTime = 200;
            grid.block.animateExpandTime = 200;
            grid.block.animateFadeTime = 200;
            grid.nbCols = 0;
            grid.nbRows = 0;
            grid.activeBlock.object = this;
            grid.activeBlock.col = $(grid.activeBlock.object).attr('class').substr(4, 1);
            grid.activeBlock.row = $(grid.activeBlock.object).attr('class').substr(1, 1);
            grid.activeBlock.index = $(grid.activeBlock.object).index();
            grid.indexClose;
            //Count number of rows and cols
            $(grid.object).children('div').each(function(i) {
                if(grid.nbRows < $(this).attr('class').substr(1, 1))
                    grid.nbRows = $(this).attr('class').substr(1, 1);
                if(grid.nbCols < $(this).attr('class').substr(4, 1))
                    grid.nbCols = $(this).attr('class').substr(4, 1);
            });
            //Close if there is one opened
            var boxOpened;
            $(grid.object).children('div').each(function(i) {
                if($(this).hasClass('open'))
                {
                    grid.closingBlock = new Object;
                    grid.closingBlock.object = this;
                    grid.closingBlock.col = $(grid.closingBlock.object).attr('class').substr(4, 1);
                    grid.closingBlock.row = $(grid.closingBlock.object).attr('class').substr(1, 1);
                    grid.closingBlock.index = $(grid.closingBlock.object).index();
                    boxOpened = true;
                    closeGridBox(grid);
                    grid.indexClose = i;
                }
            });
            if(!boxOpened)
                 openGridBox(grid);
        }
    });
	setTimeout(function() {
		$('.addthis_toolbox.addthis_default_style, .at_item').click(function() {
			$(this).trackEvent360("Share");
		});
	}, 1500);
    //---------------------------------------------------------------------------------------------------------------------------------------
});
function msp_ssInit(){
	if(debugMode){try{console.groupCollapsed("function msp_ssInit()");}catch(e){}}
	try{
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
			$('.mobileSponsoredPlacement #fadeshow').before('<div id="naviss"></div>').cycle({
				fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
				timeout: 5000,
				speed: 0,
				delay: 0 ,
				pager:  '#naviss'
			});
		}else{
			$('.mobileSponsoredPlacement #fadeshow').before('<div id="naviss"></div>').cycle({
				fx: 'fade',// choose your transition type, ex: fade, scrollUp, shuffle, etc...
				timeout: 5000,
				delay: 0 ,
				pager:  '#naviss'
			});
		}
	}catch(err){
		debug('function cycle() is undefined');
	}
	if(debugMode){try{console.groupEnd();}catch(e){}}
}
function slideCallAjax(){
	debug("function slideCallAjax()");
	$.ajax({url: $('#banner #slideshow a:visible').attr('href'), context: $('#banner #slideshow a:visible'),
		success: function(data){
			ajaxSuccess(data, $('#banner #slideshow a:visible'));
			// $.address.queryString($(this).attr('href'));
			$('#banner .next_slide').attr('href', $('#banner #slideshow a:visible').prev().attr('href') ).text( $('#banner #slideshow a:visible').prev().attr('title') );
			$('#banner .previous_slide').attr('href', $('#banner #slideshow a:visible').next().attr('href') ).text( $('#banner #slideshow a:visible').next().attr('title') );
		},
		error: function(){$('body', this).removeClass('loading');}
	});
}
function pageInit() {
	debug("function pageInit()");
	if(debugMode){try{console.groupCollapsed("function pageInit()");}catch(e){}}
	if(typeof initForm == 'function'){
		initForm();
	}
	$('#page-container').css({background:'none'} );
	$('.solutions_ancre, .anchorLink').click( function(event) {
		// alert($('.solutions_ancre').size());
		$("body").scrollTo( $(this).attr('rel'), 400 );
		event.preventDefault();
	});
	$('.anchor_slideTo').click( function(event) {
		var slide_to = $(this).attr('val');
		$("body").scrollTo( $('.produit:eq('+slide_to+')'), 400 );
		event.preventDefault();
	});
	$(".fancybox").fancybox({
		titleShow : false,
		transitionIn : 'elastic',
		transitionOut : 'elastic',
		easingIn : 'easeOutBack',
		easingOut : 'easeInBack',
		padding: 0,
		onStart : function(){debug("fancybox onStart");},
		onClosed : function(){debug("fancybox onClosed");}
	});
	$("#RATINGS .fancyboxPage").fancybox({
		titleShow : false,
		'autoDimensions' : false,
		width:855,
		height:1708,
		'onComplete'	:	function() {
			$('#fancybox-wrap').css({width:'855px','margin-left':'-214px'});
			$('#fancybox-content').css({width:'855px',height:'1708px'});
			$('#fancybox-content img').css({width:'855px',height:'1708px'});
		}
	});
  	$('.topLink').click(function(){
		$("body").scrollTo($('#header-container'), 800 );
	});
	$('#id').click(function(){
		$("body").scrollTo($('#vers'), 800 );
	});
	$('.selected .solutions_ancre').hover(function(){
		$(this).css('text-decoration','underline')
	},
	function(){
		$(this).css('text-decoration','none')
	});
	// CLOSE debug group
	if(debugMode){try{console.groupEnd();}catch(e){}}
};
function embedVideo(my_id){
	debug('embedVideo(my_id : '+my_id+')');
	var l = 'fr';
	if( $('body').is('.en') ){
		l = 'en';
	}
	var flashvars= params= attributes= {};
	var w = '674';
	var h = '494';
	var swf = "videoTour.swf";
	switch(my_id){
		case 'overview-video':
			flashvars = {
				xmlfile: 'xml/overview_video_'+l+'.xml',
				videoId: my_id
			};
			params = {
				base: '.',
				xmlfile: 'xml/overview_video_'+l+'.xml',
				videoId: my_id
			};
			attributes = {
				base: '.',
				xmlfile: 'xml/overview_video_'+l+'.xml',
				videoId: my_id
			};
			w = '800';
			h = '450';
			swf = "player.swf";
		case "sem":
			flashvars = {
				xmlfile: 'xml/videos_'+l+'.xml',
				videoId: my_id
			};
			params = {
				base: '.',
				xmlfile: 'xml/videos_'+l+'.xml',
				videoId: my_id
			};
			attributes = {
				base: '.',
				xmlfile: 'xml/videos_'+l+'.xml',
				videoId: my_id
			};
			w = '800';
			h = '450';
			swf = "player.swf";
		break;
		case 'solutions':
		case 'world-is-changing':
		default:
			flashvars = {
				xmlfile: 'xml/video_tour_'+l+'.xml',
				videoId: my_id
			};
			params = {
				base: '.',
				xmlfile: 'xml/video_tour_'+l+'.xml',
				videoId: my_id
			};
			attributes = {
				base: '.',
				xmlfile: 'xml/video_tour_'+l+'.xml',
				videoId: my_id
			};
			swf = "videoTour.swf";
			if(l=='fr'){
				w = '720';
				h = '406';
				swf = "player.swf";
			}else{
				w = '480';
				h = '472';
			}
		break;
	}
	debug('flashvars[videoId]:'+flashvars['videoId']+')'
		+'\n params[videoId]:'+params['videoId']+')'
		+'\n attributes[videoId]:'+attributes['videoId']+')'
	);
	swfobject.embedSWF("/sspro/"+swf, "videoTour", w, h, "9.0.0","expressInstall.swf", flashvars, params, attributes);
};
function accordionInit(){
	debug('accordionInit ');
	if( $('#accordion').length > 0 ){
		var hash = window.location.hash;
		// debug('hash: '+hash+", hash.length: "+hash.length +", hash.search('terms'): "+hash.search('terms'));
		if( hash.length > 0 && (hash.search(/terms/i)>0 || hash.search(/fraude/i)>0) ){
			if(hash.search(/terms/i)>0){
				var activeAncre = Number(hash.replace("#terms", '')) -1;
				debug('open:'+hash+" ,  activeAncre:"+ activeAncre);
				if( IE().version == 7 ){
					$( "#accordion, .accordion" ).accordion({autoHeight: false, active: activeAncre});
				}else{
					$( "#accordion" ).accordion({autoHeight: false, collapsible: true, active: activeAncre});
					$( ".accordion" ).accordion({autoHeight: false, collapsible: true, active: false});
				}
				scrollToActiv();
			}else if(hash.search(/fraude/i)>0){
				debug('open:'+hash+" ,  activeAncre:");
				if( IE().version == 7 ){
					$( "#accordion, .accordion" ).accordion({autoHeight: false});
				}else{
					$( "#accordion" ).accordion({autoHeight: false, collapsible: true, active: false});
					$( ".accordion" ).accordion({autoHeight: false, collapsible: true, active: 0});
				}
				$("body").scrollTo( $("#fraude"), 800 );
			}
		}else{
			if( IE().version == 7 ){
				$( "#accordion, .accordion" ).accordion({autoHeight: false});
			}else{
				$( "#accordion, .accordion" ).accordion({autoHeight: false, collapsible: true, active: false});
			}
			scrollToActiv();
		}
    }
}
function scrollToActiv(){
	try{$("body").scrollTo( $("h4.ui-state-active"), 800 );
	}catch(err){$("body").scrollTo( $("body"), 800 );}
	$( "#accordion" ).bind("accordionchange", function(event, ui) {
		var header = $( "#accordion" ).accordion( "option", "header" );
		try{$("body").scrollTo( $("h4.ui-state-active"), 800 );
		}catch(err){$("body").scrollTo( $("body"), 800 );}
	});
}
function termsInit(){
	debug('function termsInit()');
	if( $('.terms').length > 0 ){
		if( IE().version == 7 ){
			$( "#accordion" ).accordion({autoHeight: false});
		}else{
			$( "#accordion" ).accordion({autoHeight: false, collapsible: true, active: false});
		}
		$( "#accordion" ).bind( "accordionchange", function(event, ui) {
			var header = $( "#accordion" ).accordion( "option", "header" );
			$("body").scrollTo( $("h4.ui-state-active"), 800 );
		});
    }
}
function homeInit(){
	debug('function homeInit()');
	if($('.btn_videoTour').hasClass('gallery')){
	}else{
		// insert video content for inline fancybox
		if( $('#videoTour-container, .btn_videoTour').length > 0 ){
	       	debug('call function embedVideo('+$('#videoTour-container').attr('class')+')');
			embedVideo($('#videoTour-container').attr('class'));
	    }
		$("#solution_box .btn_videoTour").bind("mouseover", function(event){
			debug('$(".en #solution_box .btn_videoTour").mouseover');
			embedVideo('solutions');
		});

	}
    
    // video tour (new)
    if($('a.btn_videoTour').length) {
        ypg.youtube.init_gallery();
    }
    
	$("a.btn_videoTour").bind("click", function(event){
		event.preventDefault();
		$(this).trackEvent360("VIDEOS");
		var defaults = {
			titleShow : false,
			padding: 0,
			border: 0,
			autoDimensions:true,
			href: $(this).attr('href')
		};
		var options;
		if($(this).hasClass('gallery')){
			options = {
				width: 960,
				height: 760,
                centerOnScroll: true,
				autoDimensions: false,
				onClosed : function(){
					debug("fancybox onClosed remove class mediaGallery");
					$("#fancybox-wrap").removeClass('mediaGallery');
                    $("#mediagallery").parent().hide();
				},
                onComplete : function(){
                    ypg.youtube.set_gallery(youtube_id);
                },
                onStart : function(){
                    // scroll top before video tour
                    
                }
			}
            var youtube_id = $(this).find('.youtube_id').html();
			$("#fancybox-wrap").addClass('mediaGallery');
		}
		options = $.extend(defaults, options);
		$.fancybox(options);
	});
    
	//Overview video
	var l = 'fr';
	if( $('body').is('.en') ){
		l = 'en';
	}
		flashvars = {
			xmlfile: 'xml/overview_video_'+l+'.xml',
			videoId: 'overviewVideo',
			wmode: 'transparent'
		};
		params = {
			base: '.',
			xmlfile: 'xml/overview_video_'+l+'.xml',
			videoId: 'overviewVideo',
			wmode: 'transparent'
		};
		attributes = {
			base: '.',
			xmlfile: 'xml/overview_video_'+l+'.xml',
			videoId: 'overviewVideo',
			wmode: 'transparent'
		};
		w = '350';
		h = '263';
		swf = "player-overview.swf";
	swfobject.embedSWF("/sspro/"+swf, "overviewVideo", w, h, "9.0.0","expressInstall.swf", flashvars, params, attributes);
    
	// TRACK EVENT
	$("#fd, #menu_diagnostic").live("click", function(event){
		event.preventDefault();
		debug("LEAVE TO MARKET PROFILER");
		$(this).trackEvent360("LEAVE TO MARKET PROFILER");
		window.location.href = $(this).attr("href");
		return false;
	});
};
function sesInit(){
	debug("function sesInit()");
	if( $('#videoTour-container').length > 0 ){
       embedVideo($('#videoTour-container').attr('class'));
    }
	$("a.btn_videoTour").bind("click", function(event){
		event.preventDefault();
		$(this).trackEvent360("VIDEOS");
		$.fancybox({
			titleShow : false,
			padding: 0,
			border: 0,
			onStart : function(){
				debug("fancybox onStart");
			},
			onClosed : function(){debug("fancybox onClosed");}
		});
	});
};
// Change la liste a choix multiple du formulaire request a callback en plusieurs listes
function initFormListProduct(fancyBox){
	// Cacher le vrai formulaire qui va etre envoyé
	$("#ContactEditForm .unit1 fieldset#productList").css('display','none');
	$("#ContactEditForm select#ContactProductId").removeAttr('multiple');
	// Id des nouvelles listes déroulantes a choix unique
	var nbListeCourant = 1;
	// Clone de la liste a manipuler
	var $cloneListe = $("#ContactEditForm .unit1 fieldset#productList").clone();
	// on garde juste le select
	$cloneListe.find('select').attr('id','ContactProductId'+nbListeCourant);
	$cloneListe.find('input').remove();
	//$cloneListe.find('select').attr('onchange','javascript:majListeProduct(this.options[this.selectedIndex].value)');
	// on met le clone dans un fieldset, on l'insere apres le champs hidden
	$('<fieldset id="productList'+nbListeCourant+'">'+$cloneListe.html()+'</fieldset>').insertAfter('#ContactEditForm .unit1 fieldset#productList');
	// ?
        var results = $(fancyBox).attr('href').match('#');
	if (results == true) {
		var anchor = $(fancyBox).attr('href').split('#')[1];
		console.log('anchor2 = '+anchor);
		$("#ContactEditForm select#ContactProductId1 option[value="+productLabel_arr[anchor]['id']+"]").attr('selected','selected')
	}
	// on lance le selectBox !
	var options = {
		'menuTransition': 'slide',
		'menuSpeed' : 'fast'
	};
	debug('selectBox : ligne 723');
	$("#ContactEditForm select#ContactProductId1").selectBox( options );
	// Remise en etat de la liste de départ pour lenvoyer correctement par la suite
	$("#ContactEditForm select#ContactProductId").attr('multiple','multiple');
	$("#ContactEditForm select#ContactProductId").remove();	// Donne les bon choix en BD si lon supprime la select dorigine
	// Ajout dune liste
	$("#addItem").click(function() {
		if(nbListeCourant < 5){
			nbListePrec = nbListeCourant;
			nbListeCourant++;
			$cloneListe.find('select').attr('id','ContactProductId'+nbListeCourant);
			$('<fieldset id="productList'+nbListeCourant+'">'+$cloneListe.html()+'</fieldset>').css('opacity','0').insertAfter('#ContactEditForm .unit1 fieldset#productList'+nbListePrec);
			$('fieldset#productList'+nbListeCourant).fadeTo(600,1);
			debug('selectBox : ligne 737');
			$("#ContactEditForm select#ContactProductId"+nbListeCourant).selectBox(options);
			if(nbListeCourant == 5){
				$('#addItem').remove();
			}
		}
	});
}
function initFormBoxLoad() {
	debug('function initFormBoxLoad()');
    
    // #modal_menuMarketing .callback -> open bottom bar 
    $('#modal_menuMarketing .callback').bind("click", function(event){
        event.preventDefault();
        $('#bottom-menu-3 a').trigger('click');
    });	


	$('#pushLnk_freead').bind("click", function(event){
        event.preventDefault();
        $('#bottom-menu-1 a').trigger('click');
    });
    
	$('.pushLnk_consult, .act.callBack a, #header_callback a, .orderNow .requestInfo, a#footer_callback').bind("click", function(event){
		event.preventDefault();
		debug("CLICK ON -> "+this);
		var el = this;
		var $el = $(this);
		var elId = $(this).attr("id");
		var elClass = $(this).attr("class");
		if ( typeof $.fn.trackEvent360 == 'function' ) {
			if( 		$el.is('#pushLnk_freead') )					{$el.trackEvent360("PUSH");
			}else if( 	$el.is('.orderNow') )						{$el.trackEvent360("ORDER NOW");
			}else if( 	$el.is('.act.callBack a') )					{$el.trackEvent360("FORM OPEN");
			}else if( 	$el.is('#modal_menuMarketing .callback') )	{$el.trackEvent360("FORM OPEN");
			}else if( 	$el.is('#header_callback a') )				{$el.trackEvent360("FORM OPEN");
			}else if( 	$el.is('#footer_callback') )				{$el.trackEvent360("FORM OPEN");
			}
		} else {
            debug("$.fn.trackEvent360 is not a valid function");
        }
		var contact_height = 400;
		if($(this).is('#pushLnk_freead')){
			contact_height = 480;
		}
		debug("$.fancybox");
		var defaults = {
			titleShow : false,
			padding: 0,
			border: 0,
			width:774,
			autoDimensions:true,
			href : this.href,
			onStart: function(array, index, opts){debug("fancybox onStart "+array+", "+index+", "+opts);},
			onComplete : function() {completeFancyForm(this);},
			onClosed : function(){
				debug("fancybox onClosed");
				// on remove le ul qui a été crée par selectBox, pour corriger le bug de 2e ouverture du fancybox
				$('.ContactProductId1').remove(); // $('.selectBox-dropdown-menu').remove();
				// meme chose avec les tooltip
				$('.tooltip').remove();
			},
			ajax: {
				url: $(this).attr('href'),
				context: document.body,
				// dataType: "json" ,
				// data: $(this).serialize(),
				beforeSend: function(x) {},
				success: function(data,textStatus,XMLHttpRequest) {},
				error: function(){}
			}
		};
		var options = {};
		// Could hav use functions.js BROWSER DETECTION if(IE())
		if (navigator.appVersion.indexOf("MSIE 7.") >= 0){
			options = {
				width: 800,
				/*height: 680,*/
                                height: 410,
				autoDimensions:false
			}
		}
		options = $.extend(defaults, options);
		$.fancybox(options);//fancybox
		return false;
	});
};
function completeFancyForm(fancyBox){

	debug("initFormBoxLoad() : fancybox.onComplete");
	if(typeof initForm == 'function'){
		initForm();
	}
	$('.close_window').click(function(){
		$.fancybox.close();
	});
    
	// TOOLTIP
	$(".ContactEditForm input[title], .ContactEditForm select[title]").tooltip({
		position: "center left",
		offset: [0, -5],
		effect: "fade",
		opacity: 1,
		relative: false,
		onBeforeShow: function(event, tabIndex) {
			var toolTip = this.getTip();
			toolTip.css('visibility', 'hidden');
		},
		onShow: function(event, tabIndex) {
			var trigger = this.getTrigger();
			var toolTip = this.getTip();
			var toolTop = toolTip.css('top').replace("px", "");
			var distance = $(document).scrollTop();
			toolTip.css('top', toolTop - distance + 'px');
			toolTip.css('opacity',0);
			toolTip.css('visibility', '');
			toolTip.animate({opacity: 1}, 200);
		}
	});
    
	// add class 'address' to specific input
	$('.ContactEditForm #ContactAddress1numberFreead').parent().addClass('addressnumber');
	$('.ContactEditForm #ContactAddress1streetFreead').parent().addClass('addressstreet');
	$(".addressnumber, .addressstreet").wrapAll("<div id=\"address-input\"></div>");
    
	// same for phone !
	$('.ContactEditForm #ContactPhone1Freead, .ContactEditForm #ContactPhone1Info, .ContactEditForm #ContactPhone1Consult').parent().addClass('phone1');
	$('.ContactEditForm #ContactPhone2Freead, .ContactEditForm #ContactPhone2Info, .ContactEditForm #ContactPhone2Consult').parent().addClass('phone2');
	$('.ContactEditForm #ContactPhone3Freead, .ContactEditForm #ContactPhone3Info, .ContactEditForm #ContactPhone3Consult').parent().addClass('phone3');
    
    // wrap phone input (only if not wrapped)
    if(!$("#ContactEditFormfreead .phone1, #ContactEditFormfreead .phone2, #ContactEditFormfreead .phone3").parent().hasClass('phone-input')){
        $("#ContactEditFormfreead .phone1, #ContactEditFormfreead .phone2, #ContactEditFormfreead .phone3").wrapAll("<div class=\"phone-input\"></div>");
        $('.phone-input').after('<div style="clear:both;"></div>');
        $('.phone-input').before('<div style="clear:both;"></div>');
    }
    if(!$("#ContactEditFormconsult .phone1, #ContactEditFormconsult .phone2, #ContactEditFormconsult .phone3").parent().hasClass('phone-input')){
        $("#ContactEditFormconsult .phone1, #ContactEditFormconsult .phone2, #ContactEditFormconsult .phone3").wrapAll("<div class=\"phone-input\"></div>");
        $('.phone-input').after('<div style="clear:both;"></div>');
        $('.phone-input').before('<div style="clear:both;"></div>');

    }
    if(!$("#ContactEditForminfo .phone1, #ContactEditForminfo .phone2, #ContactEditForminfo .phone3").parent().hasClass('phone-input')){
        $("#ContactEditForminfo .phone1, #ContactEditForminfo .phone2, #ContactEditForminfo .phone3").wrapAll("<div class=\"phone-input\"></div>");
        $('.phone-input').after('<div style="clear:both;"></div>');
        $('.phone-input').before('<div style="clear:both;"></div>');
    }    
    
	// add container for all input, correct bug in IE7
	$('form .unit').each(function(){
		$(fancyBox).children().wrapAll('<div class=\"input-wrapper\"></div>');
	});
	// onchange, phone
	$(".phone1 input").keyup(function(){
		if($(".phone1 input").val().length >= 3 ) {
			debug('toomuch');
			$(".phone2 input").focus();
			$('.tooltip').hide();
		}
	});
	$(".phone2 input").keyup(function(){
		if($(".phone2 input").val().length >= 3 ) {
			debug('toomuch');
			$(".phone3 input").focus();
            $('.tooltip').hide();
		}
	});
	$(".phone3 input").keyup(function(){
		if($(".phone3 input").val().length >= 4 ) {
			debug('toomuch');
			$(".phone3 input").blur();
            $('.tooltip').hide();
		}
	});
        
	debug("href="+$(fancyBox).attr('href'));
	if( !isset(toBeHidden_arr['optimisation']) ){
		initFormListProduct(fancyBox);
	}
	var type = $('.form.contact').attr("id");
	callGadds(type);
}
function callGadds(){
	if(window.console && console.group && debugMode ){
		console.group("function callGadds()");
	}
	var type = "freead";
	var google_conversion_id = 1017322491;
	var google_conversion_language = l;
	var google_conversion_format = '3';
	var google_conversion_color = 'ffffff';
	var google_conversion_label = '2UztCP2xiQMQ-7eM5QM';
	var google_conversion_value = 0;
	var guid = 'ON';
	if($('.form.contact').length>0){type = $('.form.contact').attr("id");}
	var l = "en"
	if(typeof getLang == 'function'){l=getLang();}
	debug("l="+l);
	debug("type="+type);
	switch(type)
	{
		case 'freead':
			debug("type="+type);
			google_conversion_id = 1017322491;
			google_conversion_language = l;
			google_conversion_format = '3';
			google_conversion_color = 'ffffff';
			google_conversion_label = '2UztCP2xiQMQ-7eM5QM';
			google_conversion_value = 0;
			break;
		case 'info':
			debug("type="+type);
			google_conversion_id = 1017322491;
			google_conversion_language =  l;
			google_conversion_format = '3';
			google_conversion_color = 'ffffff';
			google_conversion_label = '9KAKCIWxiQMQ-7eM5QM';
			google_conversion_value = 0;
			break;
		default:
			break;
	}
	// trackConv( google_conversion_id, google_conversion_label );
	// asyncScriptGAds();
	// $.getScript( "http://www.googleadservices.com/pagead/conversion.js");
	if(debugMode){try{console.groupEnd();}catch(e){}}
}
function trackConv(google_conversion_id, google_conversion_label) {
		debug("function trackConv("+google_conversion_id+", "+google_conversion_label+")");
		// image = new Image(1,1);
		// image.src = "http://www.googleadservices.com/pagead/conversion/"+google_conversion_id+"/?label="+google_conversion_label +"&amp;guid=ON&amp;script=0";
		// var noscript = document.createElement('noscript');  noscript.id = "noscript_"+google_conversion_id;
		// document.getElementById("noscript_"+google_conversion_id).appendChild( image );
		var img = document.createElement('img');
		img.src = "http://www.googleadservices.com/pagead/conversion/"+google_conversion_id+"/?label="+google_conversion_label +"&amp;guid=ON&amp;script=0";
}
function asyncScriptGAds(){
	debug("function asyncScriptGAds()");
	var e = document.createElement('script');e.async = true;
	e.src = document.location.protocol + '//www.googleadservices.com/pagead/conversion.js';
	document.getElementById('content').appendChild(e);
}
function checkProduct(IDorURL) {
	// try {
		if(window.console && console.group && debugMode ){
			console.group("function checkProduct("+IDorURL+")");
		}
		if( IDorURL != 'undefined' && IDorURL != '#' && IDorURL != '' ){
			debug('checkProduct('+IDorURL+')');
			var hash = IDorURL.split('#');
			if(hash.length > 0){
				var index = (hash.length-1);
				debug("hash index : "+index);
				var pId = hash[index];
				debug("pId = "+pId);
				if( pId.length > 0 ){
					if( pId.match('/') <= 0 ){
						if( $('#info.form.contact input#'+pId).length > 0 ){
							$('#info.form.contact input#'+pId).attr('checked', 'checked');
						}else{
								var s = pId.split('Id');
								debug("s = " + s);
								debug("select#"+s[0]+" : " + $('#info.form.contact select#'+s[0]).length);
								s[0] = s[0] + 'Id';
								debug("select#"+s[1]+" : " + $('#info.form.contact option[value='+s[1]+']').length);
								if( $('#info.form.contact select#'+s[0]).length > 0 && $('#info.form.contact select option[value='+s[1]+']').length > 0 ){
								}
						}
						// $('#info.form.contact input#'+pId).attr('checked', 'checked');
					}
				}
			}
		}else{
			debug('ID or URL is undefined');
		}
// }
// catch(err) {
// 	//Handle errors here
// 	txt="There was an error on this page.\n\n";
// 	txt+="Error description: " + err.description + "\n\n";
// 	txt+="Click OK to continue.\n\n";
//
// 	if(window.console && console.debug && debugMode ){ console.debug("catch(err) : \n"+txt); }
// }
	if(debugMode){try{console.groupEnd();}catch(e){}}
}
function subMenu(){
	var menuSolutionsTimeout;
	//Set hover on modal menu
	$('#modal_menu').hover(function() {
		clearTimeout(menuSolutionsTimeout);
	}, function() {
		menuSolutionsTimeout = setTimeout(function() {
			$('#modal_menu').hide();
		}, 500);
	});
	//Set hover on menu to open modal menu
	$('#menu_solutions').hover(function() {
		clearTimeout(menuSolutionsTimeout);
		$('#modal_menu').css('left', ($(window).width() - 764) / 2 + 96);
		$('.modal_menu').not('#modal_menu').hide();
		$('#modal_menu').show();
	}, function() {
		menuSolutionsTimeout = setTimeout(function() {
			$('#modal_menu').hide();
		}, 500);
	});
	$("#menu_solutions").live("click", function(event){
		event.preventDefault();
		return false;
	});
	$("#menu_aboutus").live("click", function(event){
		event.preventDefault();
		return false;
	});
}
function subMenuMarketing(){
	var menuMarketingTimeout;
	//Set mouseout on modal menu
	$('#modal_menuMarketing').hover(function() {
		clearTimeout(menuMarketingTimeout);
	}, function() {
		menuMarketingTimeout = setTimeout(function() {
			$('#modal_menuMarketing').hide();
		}, 500);
	});
	$('#menu_diagnostic').hover(function(){
		clearTimeout(menuMarketingTimeout);
		$('#modal_menuMarketing').css('left', ($(window).width() - 764) / 2 +96);
		$('.modal_menu').not('#modal_menuMarketing').hide();
		$('#modal_menuMarketing').show();
	}, function() {
		menuMarketingTimeout = setTimeout(function() {
			$('#modal_menuMarketing').hide();
		}, 500);
	}).click(function(event){event.preventDefault();return false;});
}
function subMenuAbout(){
	var menuAboutTimeout;
	//Set mouseout on modal menu
	$('#modal_menuAbout').hover(function() {
		clearTimeout(menuAboutTimeout);
	}, function() {
		menuAboutTimeout = setTimeout(function() {
			$('#modal_menuAbout').hide();
		}, 500);
	});
	$('#menu_aboutus').hover(function(){
		clearTimeout(menuAboutTimeout);
		$('#modal_menuAbout').css('left', ($(window).width() - 764) / 2 + 95);
		$('.modal_menu').not('#modal_menuAbout').hide();
		$('#modal_menuAbout').show();
	}, function() {
		menuAboutTimeout = setTimeout(function() {
			$('#modal_menuAbout').hide();
		}, 500);
	}).click(function(event){event.preventDefault();return false;});
}
function subMenuContact(){
	var menuContactTimeout;
	//Set mouseout on modal menu
	$('#modal_menuContact').hover(function() {
		clearTimeout(menuContactTimeout);
	}, function() {
		menuContactTimeout = setTimeout(function() {
			$('#modal_menuContact').hide();
		}, 500);
	});
	$('#menu_contactus').hover(function(){
		clearTimeout(menuContactTimeout);
		$('#modal_menuContact').css('left', ($(window).width() - 191) / 2 + 380);
		$('.modal_menu').not('#modal_menuContact').hide();
		$('#modal_menuContact').show();
	}, function() {
		menuContactTimeout = setTimeout(function() {
			$('#modal_menuContact').hide();
		}, 500);
	}).click(function(event){event.preventDefault();return false;});
}
//=============================================================================================================================================
//---- Animated Grid --------------------------------------------------------------------------------------------------------------------------
//=== closeGridBox ==============================================================
// @description ; Close a grid box -- Animated grid
function closeGridBox(grid) {
	//Hide hidden content
	$(grid.closingBlock.object).find('.hidden-content').fadeOut(grid.animateFadeTime, function(){
		//Expand to the left if Last block of the line
		if($(grid.closingBlock.object).hasClass('c' +grid.nbCols) || $(grid.closingBlock.object).hasClass('c' +(grid.nbCols - 1))){
			$(grid.closingBlock.object).animate({
				width: grid.block.baseWidth,
				marginLeft: '+=' +grid.block.moveLengthX
			}, grid.block.animateExpandTime, function() {
				openGridBox(grid);
			});
		}else{
			$(grid.closingBlock.object).animate({
				width: grid.block.baseWidth
			}, grid.block.animateExpandTime, function() {
				openGridBox(grid);
			});
		}
		//Normal Behavior for closing block
		if(grid.closingBlock.col < grid.nbCols - 1){
			$(grid.object).children('div').each(function(i){
				if(i > grid.closingBlock.index){
					//Last block of the line behavior
					if($(this).hasClass('c' +grid.nbCols) || $(this).hasClass('c' +(grid.nbCols - 1))){
						$(this).animate({
							left: '+=' +(grid.nbCols - 2)*(grid.block.moveLengthX / 2),
							top: '-=' +grid.block.moveLengthY
						}, grid.block.animateMoveTime);
					}else{//Normal behavior
						$(this).animate({left: '-=' +grid.block.moveLengthX}, grid.block.animateMoveTime);
					}
				}
			});
		}else{
			//Last block of the line behavior for closing block
			//Move the previous block to the bottom
			var previousBlock = $('.r' +grid.closingBlock.row+ '.c' +(grid.closingBlock.col - 1));
			var secondPreviousBlock = $('.r' +grid.closingBlock.row+ '.c' +(grid.closingBlock.col - 2));
			var indexToStart = parseInt($(previousBlock).index()) + parseInt(grid.nbCols) - 2;
			$(previousBlock).animate({top: '-=' +grid.block.moveLengthY}, grid.block.animateMoveTime);
			$(secondPreviousBlock).animate({top: '-=' +grid.block.moveLengthY}, grid.block.animateMoveTime);
			//Move every block after the one we're expanding
			$(grid.object).children('div').each(function(i) {
				if(i > indexToStart){
					//Last block behavior
					if($(this).hasClass('c' +grid.nbCols) || $(this).hasClass('c' +(grid.nbCols - 1))){
						$(this).animate({
							left: '+=' +(grid.nbCols - 2)*(grid.block.moveLengthX / 2),
							top: '-=' +grid.block.moveLengthY
							}, grid.block.animateMoveTime);
					}else{ //Normal behavior
						$(this).animate({left: '-=' +grid.block.moveLengthX}, grid.block.animateMoveTime);
					}
				}
			});
		}
	});
	$(grid.closingBlock.object).find('.div-content').children('h5').css('color', '#333');
	$(grid.closingBlock.object).removeClass('open');
}

//=== openGridBox ==============================================================
// @description : Open a grid box -- Animated grid
function openGridBox(grid){
	if(grid.indexClose != grid.activeBlock.index){
		//Normal behavior
		if(grid.activeBlock.col < grid.nbCols - 1){
			//Move every block after the one we're expanding
			$(grid.object).children('div').each(function(i) {
				if(i > grid.activeBlock.index){
					//Last block or previous last
					if($(this).hasClass('c' +grid.nbCols) || $(this).hasClass('c' +(grid.nbCols - 1))){
						$(this).animate({
							left: '-=' +(grid.nbCols - 2)*(grid.block.moveLengthX / 2),
							top: '+=' +grid.block.moveLengthY
						}, grid.block.animateMoveTime);
					}else{
						$(this).animate({left: '+=' +grid.block.moveLengthX}, grid.block.animateMoveTime);
					}
				}
			});
	}else{ //Last block of the line behavior
		var previousBlock = $('.r' +grid.activeBlock.row+ '.c' +(grid.activeBlock.col - 1));
		var secondPreviousBlock = $('.r' +grid.activeBlock.row+ '.c' +(grid.activeBlock.col - 2));
		var indexToStart = parseInt($(previousBlock).index()) + parseInt(grid.nbCols) - 2;
		//Move the previous block to the bottom
		$(previousBlock).animate({
			top: '+=' +grid.block.moveLengthY
			}, grid.block.animateMoveTime);
		$(secondPreviousBlock).animate({
			top: '+=' +grid.block.moveLengthY
			}, grid.block.animateMoveTime);
			//Move every block from the new position of the previous block
		$(grid.object).children('div').each(function(i) {
			if(i > indexToStart){
				if($(this).hasClass('c' +grid.nbCols) || $(this).hasClass('c' +(grid.nbCols - 1))){
					$(this).animate({
						left: '-=' +(grid.nbCols - 2)*(grid.block.moveLengthX / 2),
						top: '+=' +grid.block.moveLengthY
					}, grid.block.animateMoveTime);
				}else{
					$(this).animate({
						left: '+=' +grid.block.moveLengthX
						}, grid.block.animateMoveTime);
					}
				}
			});
		}
		//Expand to the left if Last block of the line
		if($(grid.activeBlock.object).hasClass('c' +grid.nbCols) || $(grid.activeBlock.object).hasClass('c' +(grid.nbCols - 1))){
			$(grid.activeBlock.object).animate({
				width: grid.block.expandWidth,
				marginLeft: -grid.block.moveLengthX
			}, grid.animateExpandTime, function() {
				//Show hidden content (with a little hack to avoid title moving around)
				$(grid.activeBlock.object).find('.hidden-content').fadeTo(grid.animateFadeTime, 1);
			}).find('.hidden-content').fadeTo(0, 0.01);
		}else{
			$(grid.activeBlock.object).animate({width: grid.block.expandWidth}, grid.animateExpandTime, 
				function() {
					//Show hidden content (with a little hack to avoid title moving around)
					$(grid.activeBlock.object).find('.hidden-content').fadeTo(grid.animateFadeTime, 1);
			}).find('.hidden-content').fadeTo(0, 0.01);
		}
		$(grid.activeBlock.object).find('.div-content').children('h5').css('color', '#ccc');
		$(grid.activeBlock.object).addClass('open');
	}
}
//=============================================================================================================================================
function initSlideTo(){
	// initializes the slide to function for the solutions pages
	$('.solutions_ancre, .anchorLink').click( function(event) {
		// alert($('.solutions_ancre').size());
		$("body").scrollTo( $(this).attr('rel'), 400 );
		event.preventDefault();
	});
	$('.anchor_slideTo').click( function(event) {
		var slide_to = $(this).attr('val');
		$("body").scrollTo( $('.produit:eq('+slide_to+')'), 400 );
		event.preventDefault();
	});
}
(function($) {
	debugMode = true;
	/*
	 * Public methods
	 *
	 * trackEvent360
	 */
	// $(document).ready( function() { $.ga.load("UA-16395280-1"); } );
	$.fn.trackEvent360 = function(cat) {
		// var _gaq = $._gaq || [];
		if(debugMode){try{console.groupCollapsed("$.fn.trackEvent360 = function("+cat+","+dump(arguments)+") : this is #"+$(this).attr('id')+", ."+$(this).attr('class') );}catch(e){}}
		var action = "Click";
		// if( arguments[1] ){ action = arguments[1]; }
		var label, l=getLang();
		label=l=l.toUpperCase();
		if( $(this).attr("id") && $(this).attr("id").length>0 ){
			debug('$(this).attr("id") = '+$(this).attr("id") );
			label=$(this).attr("id")+"-"+label;}
		else {label = $(this).text().replace(/[\n\t\s"']+/i,"")+" - "+label;}

		if( $(this).attr("id") && $(this).attr("class").length>0 ){label=label+"["+$(this).attr("class").replace(/[\n\t\s"']+/i,"")+"]";}
		switch(cat){
			case "FORM SUBMIT":
				action = "Submit";
				label = "CallBack-Form";
				debug(" $(this).parents('#freead').length:"+ $(this).parents('#freead').length);
				if( $(this).parents('#freead').length > 0 ) {
					debug(" $(this).parents('#freead').length:"+ $(this).parents('#freead').length);
					label = "FOL-Form";
				}
				label = l+'-'+label+"-"+action;
			break;
			case "FORM OPEN":
				label = l+"-form-open-"+$(this).attr('class');
			break;
			case "ORDER NOW":
				var slug = $(this).attr('href');
				debug("slug = "+slug);
				slug = slug.split('#');
				if( isArray(slug) ){
					slug = slug[1];
					debug("slug = "+slug);
				}
				label = l+'-'+slug+'-btn';
			break;
			case "VIDEOS":
				label = "videoTour-btn";
				debug(" $(this).parents('#freead').length : "+ $(this).parents('#freead').length);
				if( $(this).parents('#freead').length > 0 ) {
					debug(" $(this).parents('#freead').length : "+ $(this).parents('#freead').length);
					label = "FOL-Form";
				}
				label = l+'-'+label+"-"+action;
			break;
			case "SLIDER":
				debug("SLIDER : "+$(this).attr('href') );
				var slide = $(this).parent();
				var slideIndex = $("#slideshow li").index(slide)+1;
				debug(slide+" : "+slideIndex);
				action = "Click";
				label = l+"-slide"+slideIndex+"-learn-more-btn";
				debug("SLIDER");
			break;
			case "PUSH":
				label = l+'-'+"Push-"+$(this).attr('id')+"-btn";
			break;
			default:
				// label = action+" "+cat;description = label;
				debug("default: action="+action+", cat="+cat+", label="+label+"");
			break;
		}
		try{
			_gaq.push(['_trackEvent', cat, action, label ]);
		}catch(e){
			if (typeof(self.urchinTracker) != 'undefined') {
				debug("!not isset(_gaq) try urchin method !!");
				// test for standalone Urchin
				urchinTracker(label);
				// return true;
			}
		}
		if(debugMode){try{console.groupEnd();}catch(e){}}
		return this.each( function() {});
	};
})(jQuery)
