/** 
 * @projectDescription main script file
 *
 * @author 	MEDIAGONG Integration Team E.D.
 * @version 	1.6 
 */
function sendTag(Name,Type,Action){LVQR.sendTag(Name,Type,Action);}
function showGame(url){
	Popup(url,900,500);
	return false;
}

function showPopup(url){
	Popup(url,760,630);
	return false;
}

function Popup(url,w,h){
	var left = Math.max(0, (screen.width - w) / 2);
	var top = Math.max(0, (screen.height - h) / 2);
	window.open(url,'popup_lvqr','top='+top+',left='+left+',toolbar=no,status=no,scrollbars=no,resizable=no,menubar=no,location=no,directories=no,width='+w+', height='+h+'');
}

/**
 *	@function trace: function to debug by passing a parameter in the URL of the page
 *  @param msg: String message to show
 *  @param clear: Bolean to clear debug box message
 **/
var msgdebug='';
var trace=false;
var _console=false;

(function($,window,undefined){
    $.fn.trace=function(msg,clear){
		msgdebug += msg;
       if ( window.addEventListener ) {
			var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65", T = "84,82,65,67,69";
			window.addEventListener("keydown", function(e){
				kkeys.push( e.keyCode );
				if ( kkeys.toString().indexOf( konami ) >= 0 || kkeys.toString().indexOf( T ) >= 0 ){
					trace=true;
					jQuery(this).trace('');
				}
			}, true);
		}
		var wl=window.location.search;		
        if(wl.match(/_trace/) || trace == true){
			var debugBox=jQuery('#debugBox');
            if(debugBox.length) debugBox.remove();
            debugBox=jQuery("<div>",{"id":"debugBox"});
            var titleBox=jQuery("<h2>").html('DEBUG BOX');
            var Close=jQuery("<a href='#' class='close'>").html('=[ Fermer ]=<br />');
            var Empty=jQuery("<a href='#' class='empty'>").html('=[ Vider ]=');
			debugBox.css({position:'fixed',bottom:'0',right:'0',width:'auto',minWidth:'200px',maxHeight:jQuery(window).height(),padding:'5px',fontSize:'100%',border:'2px solid #fc0',background:'#f00',color:'#fff',wordWrap:'break-word',zIndex:'99999999'}).css('overflow','hidden').css('overflow-y','auto');
            Close.css({color:'#fff',display:'block',width:'50%',float:'left',textAlign:'center',fontWeight:'bold',fontSize:'125%'});
			Empty.css({color:'#fff',display:'block',width:'50%',float:'left',textAlign:'center',fontWeight:'bold',fontSize:'125%'});
            titleBox.css({clear:'both'});
			debugBox.fadeOut();
			
            if(clear==true) debugBox.html('');
            debugBox.append(Empty).append(Close).append(titleBox);
			
			msg=msgdebug;
			debugBox.append(msg);
            debugBox.fadeIn();
            jQuery('body').append(debugBox);
			jQuery('#debugBox').live('dblclick',function(event){event.preventDefault();msgdebug='';jQuery(this).remove();});
			jQuery('#debugBox a.close').live('click',function(event){event.preventDefault();jQuery('#debugBox').hide();});
			jQuery('#debugBox a.empty').live('click',function(event){event.preventDefault();msgdebug='';debugBox.html('');debugBox.append(Empty).append(Close).append(titleBox);});
        }
		else if(wl.match(/_consolelog/) || _console == true){if(window.console && console.log){console.log(msg.replace(/(<([^>]+)>)/ig,""));}}
    }
})(jQuery,this);

/**
 * @classDescription LVQR main Javascript Class
 */
var LVQR = {	
	/**
	 *  settlement
	 * @method
	 */
	intro: function(){
		if (!jQuery.browser.msie) {
		}
	},
	/**
	 * Initialization of LVQR class
	 * All calls of other methods go in there
	 * @method
	 */
	init: function(){
		var Manage = {
			Init: function(){
				//if (jQuery('body').hasClass('index') || jQuery('body').hasClass('espace_parents')) {
					LVQR.verticalCenter();
					jQuery(window).resize(function(){
						LVQR.verticalCenter();
					});
				//}
				//LVQR.scrollPane('.scroll-pane');
				// scrollPane for fiche perso
				if (jQuery('body').hasClass('fiche')) {
					LVQR.scrollPane('.fiche_perso ul li.history p.scroll-pane');
				}				
				// scrollPane for mentions_legales
				if (jQuery('body').hasClass('mentions_legales')) {
					LVQR.scrollPane('#global_content div.scroll-pane');
				}
				// scrollPane for reglement
				if (jQuery('body').hasClass('reglement')) {
					LVQR.scrollPane('#global_content div.scroll-pane');
				}				
				
				/* Tracking Google*/
				LVQR.trackingGoogle();
				
				/* campain e-StatTracking */
				LVQR.eStatCampaign();
				
				if (jQuery('body').hasClass('mentions_legales')) {
					if (!document.referrer) return;
					var myReferrer 		= document.referrer;
					var text 			= myReferrer.toString() ;
					
					//appel de la page via index.html
					var stringToFind 	= "index.html";
					var regExp 			= new RegExp( stringToFind, "gi") ;
					if (text.search(regExp) == -1){
						LVQR.eStatClic('Homepage_Footer_Clic_InfosLegales-Site_Parents');
					}else{
						//appel de la page via espace-parents.html
						stringToFind 	= "espace-parents.html";
						regExp 			= new RegExp( stringToFind, "gi") ;
						if (text.search(regExp) == -1) {
							LVQR.eStatClic('Parents_Footer_Clic_InfosLegales-Site_Parents');
						}
					}
				}
				
				/* open external url http://... in a new window */ 
				//jQuery('a.external').live("click", function(event){
				jQuery('a').bind("click", function(event){					
					// eStatClic
					if(jQuery(this).hasClass('eStatClic')){
						event.preventDefault();
						LVQR.eStatClic(jQuery(this).attr('rel'));
						jQuery(this).queue(function(){
					      	if (jQuery(this).hasClass('external')) {
								window.open(jQuery(this).attr('href'));
							}
							else 
								if (jQuery(this).hasClass('popup')) {
								//do nothing
								}
								else {
									window.location = jQuery(this).attr('href');
								}
					       jQuery(this).dequeue();
						});	
					}else{
				      	if (jQuery(this).hasClass('external')) {
							window.open(jQuery(this).attr('href'));
						}
						else 
							if (jQuery(this).hasClass('popup')) {
							//do nothing
							}
							else {
								window.location = jQuery(this).attr('href');
							}
					}
					event.preventDefault();
				});	
				
				// manage bouton close to show or hide if window popup
				var locationHref 	= window.location.href;
				reg 				= new RegExp("#popup", "g");
				if (locationHref.search(reg) == -1){
					//do nothing
				}else{
					jQuery('body').addClass('popup');
				}
				// /manage bouton close to show or hide if window popup				
								
				// animate html
				var Duration = 200; //time in milliseconds

				//animate logo
				jQuery('.espace_parents #header h1 a img').attr('src','/img/content/logo-lvqr_parents.png').mouseenter(function() {
					jQuery(this).effect('shake', { distance: 2, times:1 }, Duration/2);
				})
				.mouseleave(function() {
					//
				});
				jQuery('.index #header h1 a img').attr('src','/img/content/logo-lvqr.png').mouseenter(function() {
					jQuery(this).effect('shake', { distance: 2, times:1 }, Duration/2);
				})
				.mouseleave(function() {
					//
				});
				
				jQuery('.index #header h2 img')
				.mouseenter(function() {
					jQuery('#sun a')
					.css('backgroundPosition','0px -344px')
				})
				.mouseleave(function() {
					jQuery('#sun a')
					.css('backgroundPosition','0px -172px')	
				});		
				// /animate logo
			
				// lvqr animation up effect
				if (!jQuery.browser.msie) {
					jQuery('img#lvqr')
					.css('marginTop','258px')
					.animate(
						{ 
							marginTop: "-286px"
						}
						, Duration*4
						, function(){
						    //callback
						}
					);
				}else{
					jQuery('img#lvqr')
					.css('marginTop','258px')
					.animate(
						{ 
							marginTop: "-30px"
						}
						, Duration*4
						, function(){
						    //callback
						}
					);
				}				
				// /lvqr animation up effect				
			
				// sun animation
				jQuery('.index #header, .espace_parents #header').prepend('<div id="sun"><a href="/">&nbsp;</a></div>');
				jQuery('#sun a')
				.mouseenter(function() {
					jQuery(this)
					.css('backgroundPosition','0px -344px')
				})
				.mouseleave(function() {
					jQuery(this)
					.css('backgroundPosition','0px -172px')	
				});	
				// /sun animation
				
				// bt_play animation skake effect
				jQuery('#bt_play img')
				.attr('src','/img/content/bt_play.png')
				.mouseenter(function() {
					jQuery(this).effect('shake', { distance: 10, times:1 }, Duration);
				})
				.mouseleave(function() {
					//
				});
				// /bt_play animation skake effect					
			
				// bt_parents animation shake effect				
				jQuery('#bt_parents img')
				.attr('src','/img/content/bt_parents_space.png')
				.mouseenter(function() {
					jQuery(this).effect('shake', { distance: 5, times:1 }, Duration);
				})
				.mouseleave(function() {
					//
				});
				// /bt_parents animation shake effect				
			
			
				// open link in a new window					
				jQuery('#col2 p a').bind("click", function(event){
					window.open(jQuery(this).attr('href'));			
					event.preventDefault();					
				});				
				// /open link in a new window
				
				// bt_close link to clode window popup
				jQuery('#bt_close').bind("click", function(event){
					window.close();
					event.preventDefault();					
				});				
				
				// /bt_close link to clode window popup			
			
				// gestion formulaire inscription NL
				if (jQuery('body').hasClass('espace_parents')) {
					jQuery('form#newsletterForm input[type="text"]').focus(function(){
						jQuery('form#newsletterForm input[type="text"]').val('');
					});
					jQuery('form#newsletterForm').submit(function(event){
						event.preventDefault();
						LVQR.eStatClic(jQuery(this).attr('name'));
						jQuery(this).queue(function(){
							jQuery.ajax({
								url: 'newsletter_parents.php',
								type: 'POST',
								data: {
									email: jQuery('form#newsletterForm input[type="text"]').val()
								},
								success: function(data){
									jQuery('form#newsletterForm label:first').html(data);
								}
							});
						});
					});
				}
				// /gestion formulaire inscription NL
			
			},
			Action: function(obj){
			}
		}
		Manage.Init();
	},
	verticalCenter: function(){	/* verticalCenter */	
		var Manage = {
			Init: function(){								
			},
			Action: function(){
				if (jQuery(window).height() > 658) {
					//jQuery('body.index, body.espace_parents').css({
					jQuery('body.index').css({
						background: "#321B0F"
					});
					//jQuery('body.index #wrapper_page, body.espace_parents #wrapper_page').css({
					jQuery('body.index #wrapper_page').css({
						position: "absolute",
						top: "50%",
						height: "735px",
						margin: "-329px auto 0"
					});
					jQuery('body.produits #wrapper_page').css({position:"absolute",top:"50%",height:"735px",margin:"-329px auto 0"});

				}
				else {
					//jQuery('body.index, body.espace_parents').css({
					jQuery('body.index').css({
						background: "#321B0F url(/img/css/bg_body_medium.jpg) no-repeat 50% 0%"
					});
					//jQuery('body.index #wrapper_page, body.espace_parents #wrapper_page').css({
					jQuery('body.index #wrapper_page').css({
						position: "relative",
						top: "0",
						margin: "0 auto"
					});
					jQuery('body.produits #wrapper_page').css({position:"relative",top:"0",margin:"0 auto"});
				}
			}
		}
		Manage.Init();
		Manage.Action();
	},	
	scrollPane: function(obj){	/* scroll-pane */
	
		var Manage = {
			Init: function(){								
			},
			Action: function(obj){
				jQuery(obj).jScrollPane({scrollbarWidth:13, showArrows:true});
			}
		}
		Manage.Init();
		Manage.Action(obj);
	},		
	eStatClic: function(obj){	
		var Manage = {
			estat_serial:'282082192854',
			estat_cumul:'216016192936',			
			Init: function(){				
			},
			Action: function(obj){
				if(obj !='' || obj != undefined){
					var elements = obj.split("-"); 
				
					jQuery(this).trace('<br /><b>estat_serial :: </b>'+ Manage.estat_serial +'<br /><b>estat_cumul :: </b>'+ Manage.estat_cumul +'<br /><b>elements[0] :: </b>'+ elements[0] +'<br /><b>elements[1] :: </b>'+ elements[1] +'<br />');
								
					if(_PJS) _estatl(Manage.estat_serial,Manage.estat_cumul,elements[0],elements[1]);
				}
			}
		}
		Manage.Init();
		Manage.Action(obj);
	},		
	eStatCampaign: function(obj){	
		var Manage = {
			Init: function(){	
				// variables
				var myUrl = document.location.href;		
				var temp = myUrl.lastIndexOf("/");
				myUrl = myUrl.substr(temp+1);				
				Manage.Action(myUrl);							
			},
			Action: function(obj){
				var stringToFind = "le-monde-du-rire.html#";
				var regExp = new RegExp( stringToFind, "gi") ;
				if (obj.search(regExp) == -1){
					// notfound
				}else{
					// found
					// no time to optimise Regex 
					var stringToFind2 = "-campaign";
					regExp = new RegExp( stringToFind2, "gi") ;
					if (obj.search(regExp) == -1) {
					// notfound
					}
					else {
						result = obj.replace(stringToFind, '');
						LVQR.eStatClic(result);
					}
				}
			}
		}
		Manage.Init();
	},
	sendTag: function(Name,Type,Action) {
		var Manage = {
			UA:'UA-28209751-1',
			estat_serial:'282082192854',
			estat_cumul:'216016192936',			
			Init: function(){				
			},
			Action: function(Name,Type,Action){
				jQuery(this).trace('<br />## sendTag ##<br /><b>Type :: </b>'+Type +'<br /><b>Action :: </b>'+ Action +'<br /><br /><b>Name :: </b>'+ Name +'<br />');
				try {
					switch(Type) {
						default:
						case	"GA" :
						case	"google" :
						case	"stats_google" :
							if(Name !='' || Name != undefined){
								var elements = Name.split("~");
								var category = (elements[0] == '' || elements[0] == undefined) ? '':elements[0];
								var action = (elements[1] == '' || elements[1] == undefined) ? '':elements[1];
								var tmp =  (action == '' || action == undefined) ? '':action.split("|");
								action = (tmp[0] == '' || tmp[0] == undefined) ? '':tmp[0];
								var opt_label = (tmp[1] == '' || tmp[1] == undefined) ? '':tmp[1];
								var opt_value = 0;
								
								jQuery(this).trace('<b>UA :: </b>'+ Manage.UA +'<br />');
				
								switch(Action) {
									case	"event" :
										jQuery(this).trace('"click" => '+ Manage.UA +'<br /><b>category :: </b>'+ category +'<br /><b>action :: </b>'+ action +'<br /><b>opt_label :: </b>'+ opt_label +'<br />');
										_gaq.push(['_setAccount', Manage.UA]);
										/*_gaq.push(['_trackEvent', "click", Name]);*/
										_gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
									break;
									default:
									case	"page" :
										var elements = Name.split("|");
										jQuery(this).trace('"page" => Name :: '+elements[0]);
										_gaq.push(['_setAccount', Manage.UA]);
										_gaq.push(['_trackPageview', elements[0]]);
										/*
										var index = 2;
										var name = category;
										var value = action;
										if (value === 'Home') index = 1;
										var opt_scope = '3';
										_gaq.push(['_setCustomVar',
											index,	// correspond au numero - la clé primaire - de vos variables personnalisées (« slot »). Les valeurs de « index » vont de 1 à 5. Ce qui signifie qu’on peut avoir jusqu’à cinq variables personnalisées par niveau d’engagement (cette limite pourrait bien être augmentée un de ces jours…)
											name,	// le nom de la variable personnalisée. C’est lui qui apparaitra en premier dans vos rapports sur Google Analytics
													// maximum de 64 caractères
											value,	// la valeur qui va de paire avec le nom de la variable. Il y a plusieurs valeurs possibles par nom de variable. Par exemple on pourra définir un nom de variable « genre » et lui attribuer les valeurs « homme » et « femme ». Les valeurs apparaitront dans les rapports une fois que vous aurez cliqué sur un nom de variable.
											opt_scope //Le niveau de la variable personnalisée : 1 (visite), 2 (session), ou 3 (page)
										]);
										_gaq.push(['_trackPageview']);
										*/
									break;
								}
							}
						break;				
						case "stats_estat":
						case "estat":
						case "e-stat":
							if(Name !='' || Name != undefined){
								var elements = Name.split("-");
								
								jQuery(this).trace('<br /><b>estat_serial :: </b>'+ Manage.estat_serial +'<br /><b>estat_cumul :: </b>'+ Manage.estat_cumul +'<br /><b>elements[0] :: </b>'+ elements[0] +'<br /><b>elements[1] :: </b>'+ elements[1] +'<br />');
								
								_estatl(Manage.estat_serial,Manage.estat_cumul,elements[0],elements[1]);
							}								
						break;
					}
				} catch(exc) {}
			}
		}
		Manage.Init();
		Manage.Action(Name,Type,Action);	
	},
	/**
	 *  Method for tracking element event click and page loading
	 **/
	trackingGoogle:function(){
		var Manage={
			myLocation:'',
			oElmIds: {
				'event':{
						"body.index #play a" 						: "HOMEPAGE~Click_WebsiteChildren|Clic sur le push du MDR",
						"body.index #parents a" 					: "HOMEPAGE~Click_WebsiteParents|Clic sur le push de l'Espace Parents",
						"body.index #alternate a#croque" 			: "HOMEPAGE~Click_Toastinette|Clic sur le push OPERATION CROQUE",
						"body.index #alternate a#rembourse" 		: "HOMEPAGE~Click_Remboursement|Clic sur le push 100% REMBOURSE",									
						
						"body.espace_parents #croque a" 			: "WEBSITE_PARENT~Click_Toastinette|Clic sur le push OPERATION CROQUE",
						"body.espace_parents #rembourse a" 			: "WEBSITE_PARENT~Click_Remboursement|Clic sur le push 100% REMBOURSE",
						"body.espace_parents a#pub-tv" 				: "WEBSITE_PARENT~Click_Video|Clic sur player video",
						"body.espace_parents #lvqrhouse a" 			: "WEBSITE_PARENT~Click_MVQR|Clic sur le push Maison de la vache qui rit",
						"body.espace_parents #shop a" 				: "WEBSITE_PARENT~Click_eShop|Clic sur Accéder à la boutique",
						"body.espace_parents a#bt_fb" 				: "WEBSITE_PARENT~Click_Facebook|Clic sur Devenez fan de LVQR",
						"body.espace_parents #col_contact a" 		: "WEBSITE_PARENT~Click_Contact|Clic sur Nous contacter",
						'body.espace_parents form#newsletterForm input[type="submit"]' 	: "WEBSITE_PARENT~Click_Newsletter|Clic sur bouton valider",
						
						"body.histoire #sitemap a.tchizbox" 			: "WEBSITE_PARENT~History_Click_BelTchizbox|Clic sur le lien BEL de la page Histoire",
						"body.nutrition #sitemap a.tchizbox" 			: "WEBSITE_PARENT~Nutrition_Click_BelTchizbox|Clic sur le lien BEL de la page Nutrition",
						"body.gamme_de_produits #sitemap a.tchizbox" 	: "WEBSITE_PARENT~Products_Click_BelTchizbox|Clic sur le lien BEL de la page Produits",
						"body.recettes #sitemap a.tchizbox" 			: "WEBSITE_PARENT~Recipes_Click_BelTchizbox|Clic sur le lien BEL de la page Recettes",
						"body.bon_de_reduction #sitemap a.tchizbox" 	: "WEBSITE_PARENT~Coupon_Click_BelTchizbox|Clic sur le lien BEL de la page BR",

						"body.croque .form a" 						: "PROMO~Toastinette_EntryForm|Téléchargement du formulaire de participation à l'OP Toastinette",
						"body.croque .reglement a" 					: "PROMO~Toastinette_Regulation|Téléchargement du règlement de l'OP Toastinette",

						"body.rembourse a.dowload-btn"				: "PROMO~100Rembourse_EntryForm|Téléchargement du formulaire de demande de remboursement"
					}
			},
			Init: function(){			
			},
			Action: function(){
				Manage.eventTrack('event');
			},
			eventTrack: function(type){
				$.each(Manage.oElmIds[type], function(key, value){
					if(jQuery(key).length){
						jQuery(key).each(function(){
							var t=jQuery(this);
							t.value=(Manage.oElmIds[type][key] == '' || Manage.oElmIds[type][key] == undefined) ? '':Manage.oElmIds[type][key];
							t.bind('click',function(event){
								var tag_name=t.value;
								if(tag_name !='' || tag_name != undefined){
									var value=tag_name.substr(0,123);
									tag_name=value;
									LVQR.sendTag(tag_name,"stats_google",type);
								}
							});
						});
					}else{
						var T=jQuery(key);
						T.value=(Manage.oElmIds[type][key] == '' || Manage.oElmIds[type][key] == undefined) ? '':Manage.oElmIds[type][key];
						T.live('click',function(event){
							var t=jQuery(this);
							var tag_name=T.value;
							if(tag_name !='' || tag_name != undefined){
								var value=tag_name.substr(0,123);
								tag_name=value;
								LVQR.sendTag(tag_name,"stats_google",type);
							}
						});				
					}
				});
			}
		}
		Manage.Init();
		Manage.Action();	
	}		
}   
/* launching scripts */
jQuery(document).ready(function(){
	LVQR.init();	
});

/*
** @description popup modale
** @author gduval
*/
function modalPopup(popID, popWidth) {
    if (typeof(popID) == 'undefined') popID = 'modal-popup';
	if (typeof(popWidth) == 'undefined') popWidth = 500;

    //Fade in the Popup and add close button
    $('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="/img/css/close_pop.png" class="btn_close" title="Fermer la fen&ecirc;tre" alt="Fermer" /></a>');

    //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
    var popMargTop = ($('#' + popID).height() + 40) / 2;
    var popMargLeft = ($('#' + popID).width() + 40) / 2;

    //Apply Margin to Popup
    $('#' + popID).css({'margin-top' : -popMargTop, 'margin-left' : -popMargLeft});
    //Fade in Background
    $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
    $('#fade').css({'filter': 'alpha(opacity=70)'}).fadeIn(); //Fade in the fade layer filter fixes IE Bug on fading transparencies

	// sending play to the flash player (IE FIX)
	if ($('#nonverblaster').length) { sendToNonverBlaster('play'); }

	//Close Popups and Fade Layer
	$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
		$('#fade , .popup_block').fadeOut(); //fade them both out
		$('#fade').remove();
		// sending pause to the flash player (IE FIX)
		if ($('#nonverblaster').length) { sendToNonverBlaster('pause'); }
		return false;
	});
    return false;
}



/**
 *	Callback de mise à jour des contacts MS Live
 *@param	string		type		le type de contacts récupéré
 */
function MSNCallback(type) {
	document.getElementById("flashcontent").msnCallback(type);
}
