/*global jQuery, $, $$, addEventListener, alert, blur, clearInterval, clearTimeout, close, closed, confirm, console, Debug, defaultStatus, document, window, event, events, focus, frames, getComputedStyle, history, Image, length, location, moveBy, moveTo, name, navigator, onblur: true, onerror: true, onfocus: true, onload: true, onresize: true, onunload: true, open, opener, opera, Option, parent, print, prompt, resizeBy, resizeTo, screen, scroll, scrollBy, scrollTo, setInterval, setTimeout, status, top, XMLHttpRequest */


/*  DGS : Digitas Javascript Object, version 0.0.0.1
 *--------------------------------------------------------------------------*/
/*
 *  Create the DGS namespace, on which framework's elements will be based
 */
var DGS = function(){	
	this.id = "DGS Javascript Object";
	this.version= "0.0.0.1";
	this.browser= {
		IE:     !!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1),
		Opera:  navigator.userAgent.indexOf('Opera') > -1,
		WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
		Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') === -1,
		MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
	};
	// create a few global framework settings 
	// choose using google.load or not
	// if using it, choose loading a specific js library from google CDN or not
	this.settings={
		useGoogleLoad : false,// true/false to use google load for js library
		jsLib : "jquery",// name of js library to load through google load
		jsLibVersion: "1.3.2",// version of js library to load through google load
		jsLibIsloaded : false,// true/false flag to indicate if the js library has been loaded		
		useJsLibLocalLoad : false,// true/false to use the js local library or not
		jsLibLocalUrl: "/scripts/lib/Jquery/jquery-1.3.2.min.js",// local url for js library
		jsPluginPath : '/scripts/lib/ottawan/',// path for all DGS plugins
		loadedJsListing : '',// will contain a list of external js file loaded through the DGS loading module
		ieFirebugLiteUrl : 'http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js',// url for firebug lite debugging tool
		debugMode : false// true/false to activate the debug mode
	};
	
	// list DGS plugin with external javascript files associated
	// "settings.jsPluginPath" will be used as path to find these plugins
	this.pluginList={
		thumbnails : 'thumbnails.js',
		modimodo : 'modimodo.js'			
	};	

	// log feature that will display the console.log or an alert if non available
	this.log = function(message){			
		if(this.settings.debugMode){			
			if(window.console){
				console.debug("DGS log> "+message );
			}else{
				alert("DGS log> "+message);
			}
		}
	};	
	// debug function to trap errors
	this.debug = function(object,message,number) {	
	//use globale variable because we lost track for the current instance with the onerror
		this.instance.log("DGS.debug(): Error \n -> " + object+"\n -> line "+number+" \n -> in file "+message);		
		return true;
	};	
	// in debug mode, if using a browser without console, load firebug lite
	this.initLogMode = function(obj){
		if(obj.settings.debugMode && !window.console && obj.browser.IE){
			obj.loadJSFile(obj.settings.ieFirebugLiteUrl,false,function(){	
				firebug.env.height = 150;
			});
		}
	};
	
	// check and load the plugin if not loaded and present in the plugin list
	this.checkAndLoadPlugin=function(name,objName,callback,callbackParams){
		if(this.pluginList[name]){
			var fileName=this.settings.jsPluginPath+this.pluginList[name];
			this.loadJSFile(fileName,objName,callback,callbackParams);
		}
	};	
	// external js loader (url of the file, function to run at callback)
	this.jsLoader = function(file,callback){
	   var s = document.createElement("script");
		s.type = "text/javascript";		
		if (s.readyState){  //IE
			s.onreadystatechange = function(){
				if (s.readyState == "loaded" ||
						s.readyState == "complete"){
					s.onreadystatechange = null;
					if(callback){callback();}
				}
			};
		} else {  //Others
			s.onload = function(){
				if(callback){callback();}
			};
		}		
		s.src = file;
		document.getElementsByTagName("head")[0].appendChild(s);
	};
	// load js file and run requested feature at callback
	this.loadJSFile= function(filename,objName,callback,callbackParams){	
		if (this.settings.loadedJsListing.indexOf(filename)==-1){ 				
			this.jsLoader(filename,function(){
				if(objName && callback){
					var fcnt = eval(callback);
					fcnt("'"+objName+"'",callbackParams);	
				}else if(!objName && callback){
					var fcnt = eval(callback);
					fcnt(this);
				}
			});					
			this.log(filename);				
			this.settings.loadedJsListing+="|"+filename; //List of files added in the form "|filename1|filename2..."
		}
	};
	// to init library and error handling
	this.initialize = function(obj){
		//set a global variable to keep track of current DGS instance
		window.instance = obj;	
		// debug mode + non compatible browser (IE), load firefug lite to allow console
		obj.initLogMode(obj);
		// if google load requested on global settings, load
		if(obj.settings.useGoogleLoad){
				google.load(obj.settings.jsLib, obj.settings.jsLibVersion);
				google.setOnLoadCallback(function() {				
					obj.settings.jsLibIsloaded = true;
					obj.log("javascript library google loaded : "+obj.settings.jsLib+" "+obj.settings.jsLibVersion);					
				});				
		}else if(obj.settings.useJsLibLocalLoad){
			this.loadJSFile(this.settings.jsLibLocalUrl,false,function(){
				obj.settings.jsLibIsloaded = true;				
				obj.log("no js library loaded via googleLoad, but local "+obj.settings.jsLibLocalUrl);
			});
		}		
		// error catching
		window.onerror = obj.debug;		
	};
};


// init DGS framework generic instance to be used
var OT = new DGS();
		
//initialize the instance (load js library, plugins, etc)
OT.initialize(OT);




// ----------------------------
// ! ///// DEBUGG START //////////
// ----------------------------
(function($) {
    /* ! Warning !!! set debugg to false in production mode */
    var debugg = false;

    if ((debugg)) {
        jQuery(document).ready(function() {
            $("body").prepend('<div id="debugg" class="box"><h2><a href="#logger" id="toggle-logger">Logger</a></h2><ol id="logger"></ol></div>');
        });
    }
    jQuery.fn.debug = function() {
        return this.each(function() {
            jQuery.log(this);
        });
    };
    jQuery.log = function(message) {
        if ((window.console) && (debugg)) {
            console.debug(message);
            jQuery("#debugg h2").empty().text("Debugg on");
        }
        else {
            jQuery("#debugg ol").append("<li>" + message + "</li>");
        }
    };
} (jQuery));


// ----------------------------
// ! ///// DEBUGG END //////////
// ----------------------------

(function($) {
	jQuery.fn.miniModal = function(options) {
   
    // ----------------------------
    // ! DEFAULT SETTINGS
    // ----------------------------
    var defaults = {       
        containerAttrs : {
        	className : "container_16"
        },
        maskAttrs : {
			id : "modal-mask"
		},
		loaderAttrs : {
			id : "modal-loader"
		},
		windowAttrs :{
			id : "modal-window"
		},
		closeAttrs :{
			id : "modal-close"
		},
        closeText : "close",
        
        onBeforeStart : function () {},
        onComplete : function () {
	           alert("Content Loaded \n(Ajax Callback)\n(Modal ready for new javascript features)");
	
		}

    };
   	var settings = $.extend(true, {}, defaults, options);
   
    return this.each(function(){
    
    	// ----------------------------
        // ! Plugin Start here...
        // ----------------------------
    	
		
		function showModalDialog(event){
			event.preventDefault();
			event.stopPropagation();
			
			// ----------------------------
			// ! references for href and hash values
			// ----------------------------
			var modalHref = jQuery(this).attr("href").split("#")[0];
			//var modalResponse = jQuery(this).attr("hash");
						
			// ----------------------------
			// ! references for mask, loader window and close button 
			// ----------------------------
			var modalMask= jQuery("<div />").attr(settings.maskAttrs);
			var modalLoader= jQuery("<div />").attr(settings.loaderAttrs);
			var modalWindow= jQuery("<div />").attr(settings.windowAttrs);
			var modalClose= jQuery("<a href='#' />").attr(settings.closeAttrs).text(settings.closeText);

	        // ----------------------------
			// ! Append mask, loader and window in first body container 
			// ----------------------------

			jQuery("body").prepend(modalMask);
			jQuery(modalMask).after(modalLoader);
			modalLoader.after(modalWindow);

	        // ----------------------------
			// ! Trigger Request in callback mask animation
			// ----------------------------
	        jQuery(modalMask).animate({opacity: 0.75}, 200, "swing",function(){
	        
				jQuery.ajax({
					type: "GET",
					url: modalHref,
					dataType: "html",
					processData: "false",
					
					beforeSend: function(XMLHttpRequest){
						// ----------------------------
				    	// ! trigger onBeforeStart plugin method
				    	// ----------------------------
						settings.onBeforeStart.call(this);
					
					},
					error: function(XMLHttpRequest, textStatus, errorThrow) {
					},
					success: function(XMLHttpRequest, textStatus) {
						//jQuery.log("success modal XMLHttpRequest");
					},
					complete: function(XMLHttpRequest, textStatus){
						//jQuery.log("complete modal XMLHttpRequest");

						// ----------------------------
				    	// ! append data response to modal window (hidden)
				    	// ----------------------------
						jQuery(XMLHttpRequest.responseText).find("#modal-response").each(function(){
		
							jQuery(modalWindow).append(this);
							jQuery(this).prepend(modalClose);
							
							// close pop with MASK click
							jQuery(modalMask).click(function(){
								jQuery(modalClose).trigger("click");
						
							});
							
							
							
							jQuery(modalClose).click(function(event){
								event.preventDefault();
								event.stopPropagation();
								jQuery("body").removeClass("offer-print");
								jQuery(modalWindow).slideUp("slow",function(){
									jQuery(this).remove()
									
								});
								 jQuery(modalMask).slideUp("normal",function(){
									jQuery(this).remove()
								});
							});
						});
						

						// ----------------------------
				    	// ! get/set modal position / margin
				    	// ----------------------------
						var modalScope = Math.round(((jQuery(modalWindow).height())/2)*-1);
						jQuery(modalWindow).css("margin-top", modalScope);
						
						
						// ----------------------------
				    	// ! hide loader 
				    	// ----------------------------
						jQuery(modalLoader).animate({opacity: 0}, 400, "swing", function(){
						
							jQuery(this).remove();
						});
						
						
						// ----------------------------
				    	// ! show modal window  (visible)
				    	// ----------------------------
						jQuery(modalWindow).animate({opacity: 1}, 200, "swing", function(){
						
							// ----------------------------
				    		// ! trigger onComplete plugin method
				    		// ----------------------------
							settings.onComplete.call(this);
						
						});
						

						
						//jQuery("body").addClass("modalActiveBody");

						
					}
				});
	
	        });
			
		}
		

    	/* ! bind click event function */
    	jQuery(this).bind("click", showModalDialog);
 
        
    });
    
};
}(jQuery));

	// ----------------------------
    // ! ///// MINI MODAL END //////////
    // ----------------------------

// ----------------------------
// ! ///// MINI TOGGLE START ////////// 
// ----------------------------

function onToggle(){
	var targetHeight= new Array();
	var targetText= new Array();  
	var texteFermer = new Array();
	jQuery("a[id*=toggle]").each(function (i) {
		targetHeight[i] =jQuery(this.hash).height();
		targetText[i]=jQuery(this).text();
		texteFermer[i] = jQuery(this).parent().parent().parent().find(".hiddenText").text();
		jQuery(this).toggle(
			function () {
				jQuery(this.hash).animate({"height":jQuery(this.hash+" .protected").height()-9}, 400);
				jQuery(this).parent().addClass("close");
				jQuery(this).text(targetText[i]);
			},
			function () {
				jQuery(this.hash).animate({"height":targetHeight[i]}, 400);
				jQuery(this).parent().removeClass("close");
				jQuery(this).text(texteFermer[i]);
			}
		);
	});
	jQuery("a[id*=toggle]").trigger("click");
}
// ----------------------------
// ! ///// MINI TOGGLE END //////////previous
// ----------------------------

function handler(event) {
	var className = jQuery(this).attr("class");
	var idarticle = jQuery(".idarticle").html();
	var idssarticle = jQuery(".idssarticle").html();
	var ordreEvent = jQuery(".ordreEvent").html();
	
	if(ordreEvent==1) 
	{
	   var dataString = 'submit=valider&action=slideEvent&direction='+className+'&idarticle='+idarticle+'&idssarticle='+idssarticle;
	}
	else
	{
		var dataString = 'submit=valider&action=slide&direction='+className+'&idarticle='+idarticle+'&idssarticle='+idssarticle;
	}
		jQuery.ajax( {
			type :"POST",
			url :"/FRONT/NISSAN_CUBE/include/action_selection.php",
			data :dataString,
			success : function(data) {
			
				var var_data=data.split("#");
				var newIdArticle 	= var_data[0];
				var newImageArticle = var_data[1];
				var newTexteArticle = var_data[2];
				
				/*Mettre a jour lid du sous article*/
				jQuery(".idssarticle").empty();
				jQuery(".idssarticle").append(newIdArticle);
				/*Mettre a jour lid du sous article*/
				
				/*Mettre a jour limage de larticle*/
				jQuery(".sousArticleImage").empty();
				jQuery(".sousArticleImage").html(newImageArticle);
				/*Mettre a jour limage de larticle*/
				
				/*Mettre a jour le texte de larticle*/
				jQuery(".sousArticleTexte").empty();
				jQuery(".sousArticleTexte").html(newTexteArticle);
				/*Mettre a jour le texte de larticle*/
				
			}				
		});  
	}



function handlerEnvoiInvit(type,optin,mobile) {
	
	var eventid = jQuery("#eventid").attr("value");
	var ordre 	= jQuery("#ordre").attr("value");	
	
	var dataString = 'submit=valider&action=beNotified&type='+type+'&optin='+optin+'&mobile='+mobile+'&eventid='+eventid+'';
	var boxStatusNotifiedHidden;
	jQuery.ajax( {
		type :"POST",
		url :"/FRONT/NISSAN_CUBE/include/action_selection.php",
		data :dataString,
		success : function(data) {
				jQuery(".error").hide();//success
				/**********cacher tous les champs*****/
				jQuery("#request-mail").slideUp();
				jQuery("#request-sms").slideUp(); 
				jQuery(".request-intro").slideUp(); 
				jQuery(".request-list").slideUp();
				/**********cacher tous les champs*****/
				if(data=="notPremium")
				{	
					/**********cacher tous les champs*****/
					jQuery("#request-mail").slideUp();
					jQuery("#request-sms").slideUp(); 
					jQuery(".request-intro").slideUp(); 
					jQuery(".request-list").slideUp();
					/**********cacher tous les champs*****/
					jQuery("#mesErrorNotPremium").show();//error
				}
				else if(data==1)
				{
					jQuery("#mesValid").show();//success
					/****************************BLOC MESSAGE INSTANTANE***************/
					boxStatusNotifiedHidden = jQuery("#boxStatusNotifiedHidden").html();
					jQuery("#article-"+ordre+" .grid_3").html(boxStatusNotifiedHidden);
					/****************************BLOC MESSAGE INSTANTANE***************/
				}
				else
					jQuery("#mesError").show();//error
				
		}				
	});  
	
}

//MESSAGE DIRECT AU CLIC SUR LA NOTIF
function handlerVerifNotif() {
	
	var eventid = jQuery("#eventid").attr("value");
	var ordre 	= jQuery("#ordre").attr("value");
	var dataString = 'submit=valider&action=verifNotif&eventid='+eventid+'';
	var boxStatusNotifiedHidden;
	jQuery.ajax( {
		type :"POST",
		url :"/FRONT/NISSAN_CUBE/include/action_selection.php",
		data :dataString,
		success : function(data) {
				
				if(data==1)
				{		
						jQuery(".error").hide();//success
						/**********cacher tous les champs*****/
						jQuery("#request-mail").hide();
						jQuery("#request-sms").hide(); 
						jQuery(".request-intro").hide(); 
						jQuery(".request-list").hide();
						/**********cacher tous les champs*****/	
						jQuery("#mesValid").show();//success
						/****************************BLOC MESSAGE INSTANTANE***************/
						boxStatusNotifiedHidden = jQuery("#boxStatusNotifiedHidden").html();
						jQuery("#article-"+ordre+" .grid_3").html(boxStatusNotifiedHidden);
						/****************************BLOC MESSAGE INSTANTANE***************/
				}else
					if(data=="notPremium")
					{	
						/**********cacher tous les champs*****/
						jQuery("#request-mail").hide();
						jQuery("#request-sms").hide(); 
						jQuery(".request-intro").hide(); 
						jQuery(".request-list").hide();
						/**********cacher tous les champs*****/	
						jQuery("#mesErrorNotPremium").show();//error
					}
		}				
	});  
	
}

function handlerInvitUser() {
	
	var eventid = jQuery("#eventid").attr("value");
	var ordre 	= jQuery("#ordre").attr("value");
	var dataString = 'submit=valider&action=invitUser&eventid='+eventid;
	var boxStatusInvitedHidden;
	
	jQuery.ajax( {
		type :"POST",
		url :"/FRONT/NISSAN_CUBE/include/action_selection.php",
		data :dataString,
		success : function(data) {
		
				if(data=="notPremium")
				{
					jQuery("#mesErrorNotPremium").show();//error
				}
				else
				if(data==1)
				{
					jQuery("#mesValid").show();
					boxStatusInvitedHidden = jQuery("#boxStatusInvitedHidden").html();
					jQuery("#article-"+ordre+" .grid_3").html(boxStatusInvitedHidden);
				}
				else
				if(data=="cuberide")
				{
					jQuery("#mesValidCuberide").show();
					boxStatusInvitedHidden = jQuery("#boxStatusInvitedHidden").html();
					jQuery("#article-"+ordre+" .grid_3").html(boxStatusInvitedHidden);
				}
				else
				{
					jQuery("#mesError").show();
				}	
		}				
	}); 
	
}


function CounterOpenEvent(eventid)
{
	
	ordre 		= 	$("#"+eventid).parent().attr("id");
	tableauEvt	=	ordre.split('-');
	ordre 		=	tableauEvt[1];
	
	var dataString = 'submit=valider&action=compteurOpenEvent&eventid='+eventid+'&ordre='+ordre;


	jQuery.ajax( {
		type :"POST",
		url :"/FRONT/NISSAN_CUBE/include/action_selection.php",
		data :dataString,
		success : function(data) {	
			jQuery("#article-"+ordre+" .grid_3").hide();
			jQuery("#boxOpen"+eventid).show();	
		}				
	});

}

jQuery(document).ready(function(event) {
	jQuery(".gallery li a, a.image-full, a.request, .product-list li a, a.offer").miniModal({	
		// ----------------------------
		// ! ///// ON COMPLETE AJAX CALLBACK - START//////////
		// ----------------------------
		onComplete : function () {
	           //alert("Cube-List - Content Loaded \n(onComplete - Ajax Callback)\n(Modal ready for new javascript features )");
			   /***************POPIN SOUS ARTICLE WEBZINE****************/
	           jQuery(".next").bind("click", handler);
	           jQuery(".previous").bind("click", handler);
	           var modaltype = jQuery("#modaltype").attr("value");
	           /***************POPIN SOUS ARTICLE WEBZINE****************/  
	           
	            // ----------------------------
				// ! ///// MODAL - SHOW-HIDE FORM INPUT - START //////////
				// ----------------------------
	           if(modaltype=='notif')
			   {
	        	  handlerVerifNotif();
			   }
	           if(modaltype=='invit')
			   {
					handlerInvitUser();
			   }
	           
	           jQuery("#show-request-mail").click(function(){
					handlerEnvoiInvit('email');
					return false;
				}); 
									
				jQuery("#show-request-sms").click(function(){
					//jQuery("#show-request-mail").hide();
					jQuery("#request-sms").show();   
					return false;  
				});
				
				jQuery("#request-sms-answer").click(function(){
					var mobile 		= 	$("#mobile").val();
					var optinYes 	=	$('#optin_yes').attr('checked')?1:0;
					var optinNo 	= 	$('#optin_no').attr('checked')?1:0;
			
					if(	!isNaN(mobile) && (optinYes || optinNo)	)
					{
						var optinEnvoi;
						if(optinYes) optinEnvoi = 1; else optinEnvoi = 0;
						handlerEnvoiInvit('sms',optinEnvoi, mobile);
					}
					else
					{
						if(isNaN(mobile) || !mobile)
						{	
							jQuery("#errorsmscheck").slideUp();
							jQuery("#errorsmscheck").slideDown();
						}else jQuery("#errorsmscheck").hide();
						
						if(!optinYes && !optinNo)
						{
							jQuery("#erroroptin").slideUp();
							jQuery("#erroroptin").slideDown();
						}else jQuery("#erroroptin").hide();
					}
					return false;  
				});
				
				jQuery(".offer-btn").click(function(){
					window.print();
					return false;
				});

			
			// ----------------------------
			// ! ///// MODAL - SHOW-HIDE FORM INPUT - END //////////
			// ----------------------------
	      }
	      // ----------------------------
		// ! ///// ON COMPLETE AJAX CALLBACK - END//////////
		// ----------------------------
	});
	
	// ----------------------------
	// ! ///// NAV SEARCH - START //////////
	// ----------------------------
	jQuery(".nav-search > li > a").toggle(
		function () {
			     jQuery(".nav-search > li > ul").fadeOut("fast");
				 jQuery(".nav-search > li").addClass("current");
		},
		function () {
			jQuery(".nav-search > li > ul").fadeIn("fast");
			jQuery(".nav-search > li").removeClass("current");  
		}
	);
	jQuery(".nav-search > li > a").trigger("click");
		
	jQuery(".articles h2").click(function(){
	     jQuery(this).parents(".container_16").find("a[id*=toggle-]").trigger("click")
	});	
   
	// ----------------------------
	// ! ///// NAV SEARCH - END //////////
	// ----------------------------

	jQuery("a.offer").click(function(){
		jQuery("body").addClass("offer-print");
	});	
	
});



jQuery(window).load(function(event) {
	// ! Log DGS Framework Object
	//jQuery.log(OT.browser);
	// ! MINI TOGGLE START
	onToggle();
});

function ouvrePopup(fichier) 
{
	ff=window.open(fichier,"Agenda","width=822,height=600,scrollbars=yes");
}
