//initialisation de la fonction de lancement des scripts
function addEvent(el,eventName,fction,returnVal) {
	if (el.addEventListener){
		el.addEventListener(eventName,fction,false);
	} else if (el.attachEvent) {
		el.attachEvent('on'+eventName,fction);
	}
}

function clickButton(e, buttonid){
     var evt = e ? e : window.event;
     var bt = document.getElementById(buttonid);
     if (bt){
         if (evt.keyCode == 13){
             bt.click();
             
            return false;
         }
     }
 }


 var clv = {

 	popins: function popins() {

 		this.getCurrentYPos = function() {
 			if (document.body && document.body.scrollTop) {
 				return document.body.scrollTop * 1;
 			}
 			if (document.documentElement && document.documentElement.scrollTop) {
 				return document.documentElement.scrollTop * 1;
 			}
 			if (window.pageYOffset) {
 				return window.pageYOffset * 1;
 			}
 			return 0;
 		};

 		this.getWindowHeight = function() {

 			var windowHeight = 0;

 			if (typeof (window.innerHeight) == 'number') {
 				windowHeight = window.innerHeight;
 			}

 			else {

 				if (document.documentElement && document.documentElement.clientHeight) {
 					windowHeight = document.documentElement.clientHeight;
 				}

 				else {

 					if (document.body && document.body.clientHeight) {
 						windowHeight = document.body.clientHeight;

 					}

 				}

 			}

 			return windowHeight;

 		};

 		this.closeHandler = function() {

 			jQuery(".popin-coupon .close").bind("click", function(e) {
 				e.preventDefault();
 				jQuery(".popin-opacity, .popin-coupon").remove();
 				if (typeof document.body.style.maxHeight === "undefined") {
 					jQuery("#fond select").css("visibility", "visible");
 				}
 			});

 		}

 		this.init = function() {
 			var that = this;
            jQuery.noConflict();
 			jQuery(".open-coupon").bind("click", function(e) {

 				e.preventDefault();
 				var url = jQuery(this).attr("href");

 				jQuery("#genericPopin").remove();
 				jQuery.ajax({
 					type: "GET",
 					url: url,
 					success: function(msg) {
 						if (typeof document.body.style.maxHeight === "undefined") {
 							jQuery("#fond select").css("visibility", "hidden");
 						}
 						jQuery("#fond").after("<div class='popin-opacity'><!-- --></div>");
 						jQuery(".popin-opacity").css({
 							height: jQuery("body").height() + "px"
 						}).after(msg);

 						var windowHeight = that.getWindowHeight();
 						var scrollPos = that.getCurrentYPos();

 						var topPos = (windowHeight - jQuery(".popin-coupon").height()) / 2 + scrollPos;

 						jQuery(".popin-coupon").css("top", topPos + "px");
 						that.closeHandler();
 					}
 				});

 			});

 		};
 	},

 	coupons: function coupons() {
 	
 	  this.isListeBR = $("div.reduction-block.reduction-choice").length > 0;
        
 		this.calculate = function() {
 			var that = this; 
 			
 			var couponsTxt = "<p>Vous n’avez pas sélectionné de bon de réduction à imprimer</p>";
 			var couponsLength = 0;
 			if (that.isListeBR) {
 				couponsLength = $("li.coupon.selected-coupon").length;
 			}
 			else {
 			  couponsLength = jQuery("li.coupon").length;
 			}
 			if (couponsLength == 0) {
 				$("div.economy-block div.economy-print").hide();
 			}
 			else {
 				var txtPrint = "Voir et imprimer les " + couponsLength + " bons";
 				couponsTxt = "<p>Vous avec sélectionné<br><strong>" + couponsLength + " bons de réduction à imprimer</strong></p>";
 				if (couponsLength == 1) {
 					txtPrint = "Voir et imprimer le bon";
 					couponsTxt = "<p>Vous avec sélectionné<br><strong>1 bon de réduction à imprimer</strong></p>";
 				}
 				if (that.isListeBR) {
 					$("div.economy-block div.economy-print a").html(txtPrint);
 				}
 				$("div.economy-block div.economy-print").show();
 			}
 			
 			$("div.economy-block div.economy-text").html(couponsTxt);

 			var reductionValue = 0;
 			var selectedCoupons = [];
 			if (that.isListeBR) {
 				selectedCoupons = $("li.coupon.selected-coupon");
 			}
 			else {
 			  selectedCoupons = $("li.coupon");
 			}
 			selectedCoupons.each(function() {
                
 				reductionValue += parseFloat($("input.coupon-value", this).val(), 10);
 				reductionValue = Math.round(reductionValue*Math.pow(10,2))/Math.pow(10,2); 				

 			});

 			reductionValue = reductionValue.toString();
            
 			reductionValue = reductionValue.replace(/\./g, ',');

 			var comaLength = reductionValue.split(",");
 			
 			if (typeof comaLength[1] !== "undefined") {
 				if (comaLength[1].length == 1) {
 					reductionValue += "0";
 				}
 			}
            
 			$("div.economy-block div.economy span.economy-price").html(reductionValue);


 		};

 		this.init = function() {
            
            
 			var that = this; 

      jQuery.noConflict();      
      
 			$("div.print-block2 a.print-link").bind("click", function(e) {
 				$("div.print-infos, .coupon-print-buttons").hide();
 				$("div.coupon-print-progress").show();
 				e.preventDefault();
 				//var str_pdfLink = $(this).attr("href");
 				var urlPopin = jQuery(this).attr("linkpopin");
 				var urlWS = jQuery(this).attr("linkws");
 				
 				var winl = (screen.width - 200) / 2 -10; 
        var wint = (screen.height - 200) / 2 - 20; 
        window.meswebcoupons = window.open('', 'Impression','height=200,width=200,top='+wint+',left='+winl+',toolbar=0,location=0,scrollbars=0,directories=0,status=1,menubar=0,resizable=0');
        if (window.meswebcoupons != null && window.meswebcoupons != 'undefined')
        {
          window.meswebcoupons.location.href = urlPopin;
 				
 				  $.ajax({
 					  type: "GET",
 					  //url: str_pdfLink,
 					  url: urlWS,
 					  success: function(XMLHttpRequest) {
 						  //$("body").append(XMLHttpRequest);
 						  window.setTimeout(function() {
 							  $("div.coupon-print-progress").hide();
 							  $("div.coupon-confirmation").show();
 						  }, 3000);
 					  }
 				  });
 				}
 				else
 				  alert("Pour obtenir vos bons de réductions, vous devez autoriser l'affichage des fenêtres pop-up (fenêtre publicitaire) sur votre navigateur.");
 			});

 			if (that.isListeBR) {
 				$("li.coupon ul.buttons a.sendToFriend span").bind("click", function(e) {
                        
 				    $("#popinFriendDisplay").remove();
		            $("#corps").after('<div id="popinFriendDisplay"><div id="bgPopinFriend"></div></div>')
		            window.scrollTo(0,0);
		            $.ajax({
			            type:"GET",
			            url:jQuery(this).attr("link"),
			            success:function(msg) {
				            $("#bgPopinFriend").after(msg);
				            closePopinSend1();   
				            backgroundPopin1();
				            checkFormFriend();
			            }
		            });
 					return false;

 				});
 				
        $("li.coupon a.add").bind("click", function(e) {

 					e.preventDefault();
 					jQuery(this).siblings("input.coupon-checkbox").attr("checked", "checked");
 					jQuery(this).siblings("input.coupon-checkbox").change(); // launch the onChange event
 					jQuery(this).parents("li.coupon").addClass("selected-coupon");
 					that.calculate();
          return false;
 				});
 				
 				$("li.coupon a.remove").bind("click", function(e) {

 					e.preventDefault();
 					jQuery(this).parent().siblings("input.coupon-checkbox").removeAttr("checked");
 					jQuery(this).parent().siblings("input.coupon-checkbox").change(); // launch the onChange event
 					jQuery(this).parents("li.selected-coupon").removeClass("selected-coupon");
 					that.calculate();
 					return false;

 				});
 				
 				$("a.select-all-coupons").bind("click", function(e) {
 				  canLauchOmniture = false;
 					e.preventDefault();
 					$("li.coupon a.add:last").bind("click", function(e) {
 				    canLauchOmniture = true;
 				    jQuery(this).unbind("click", arguments.callee);
 				  });
 					$("li.coupon a.add").trigger("click");
 				});
 				
 				$("a.deselect-all-coupons").bind("click", function(e) {
 				  canLauchOmniture = false;
 					e.preventDefault();
 					$("li.coupon a.remove:last").bind("click", function(e) {
 				    canLauchOmniture = true;
 				    jQuery(this).unbind("click", arguments.callee);
 				  });
 					$("li.coupon a.remove").trigger("click");
 				});
 				
				$("div.economy-print").click(function() {
				  var idLink;						              
	        $("li.coupon").each(function(index) {
	          if($(this).find("input.coupon-checkbox").is(':checked') == true) {
	            if(typeof(idLink)=="undefined") {
                idLink = "id=" + $(this).find("input.coupon-checkbox").val();
              }
              else {
                idLink = idLink + "&id=" + $(this).find("input.coupon-checkbox").val();
              }    
	          }
          });
          if(typeof(idLink)!="undefined") {     
            window.location.href="/produits-et-marques-nestle/avantages/ListeBR_Selection.aspx?"+idLink; 
	          return false;
          }
          return false;
        });
 				
 				$.extend({
          getQueryString: function (name) {           
                  function parseParams() {
                      var params = {},
                          e,
                          a = /\+/g,  // Regex for replacing addition symbol with a space
                          r = /([^&=]+)=?([^&]*)/g,
                          d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                          q = window.location.search.substring(1);
                         
                      while (e = r.exec(q)) {
                          if(typeof(params[d(e[1])])=="undefined") {
                              params[d(e[1])] = d(e[2]);
                          }
                          else {
                              params[d(e[1])] = params[d(e[1])] + "," +d(e[2]);
                          }                    
                      }
                      return params;
                  }
                 
                  if (!this.queryStringParams)
                      this.queryStringParams = parseParams();                                         
                  
                  return this.queryStringParams[name];
              }
        });
                
        if (typeof($.getQueryString("id")) != "undefined") {
          /* Select id from query string */
	        
	        var couponIds = $.getQueryString("id").split(",");
	        var lastCouponIdx = couponIds.length - 1;
	        jQuery.each(couponIds, function(idx, el) {
	          if (idx == lastCouponIdx) {
	            $('#' + el).siblings("a.add").bind("click", function(e) {
	              canLauchOmniture = true;
	              jQuery(this).unbind("click", arguments.callee);
	            });
	          }
	        });
	        
          $("li.coupon").each(function(index) {
              if($.getQueryString("id").match($(this).find("input.coupon-checkbox").val())) {
                $(this).find("a.add").trigger('click');
              }
          });
        }
        else
        {
          /* No coupons pre-selected */
          that.calculate();
          canLauchOmniture = true;
        }        
 			}
 			else {

        that.calculate();

 				jQuery("li.coupon a.remove").bind("click", function(e) {

 					e.preventDefault();
 					jQuery(this).parents("li.coupon").remove();
 					that.calculate();

 				});
 				
 				jQuery("li.coupon ul.buttons a.sendToFriend span").bind("click", function(e) {
                        
 				    $("#popinFriendDisplay").remove();
		            $("#corps").after('<div id="popinFriendDisplay"><div id="bgPopinFriend"></div></div>')
		            window.scrollTo(0,0);
		            $.ajax({
			            type:"GET",
			            url:jQuery(this).attr("link"),
			            success:function(msg) {
				            $("#bgPopinFriend").after(msg);
				            closePopinSend1();   
				            backgroundPopin1();
				            checkFormFriend();
			            }
		            });
 					return false;

 				});
 				
		    jQuery("div.economy-print").click(function(){						        						    
			    var idLink;						              
	        $("li.coupon").each(function(index) {
            if(typeof(idLink)=="undefined"){
              idLink = "id=" + $(this).find("input.coupon-checkbox").val();
            }
            else {
              idLink = idLink + "&id=" +$(this).find("input.coupon-checkbox").val();
            }
          });
          if(typeof(idLink)!="undefined") {     
            window.location.href="/produits-et-marques-nestle/avantages/ListeBR-Impression.aspx?"+idLink; 
	          return false;
          }
          return false;                                                                     
			  });
			  
			  jQuery("a.bt-add-coupon").click(function(){						        						    
			    var idLink;						              
	        $("li.coupon").each(function(index) {
            if(typeof(idLink)=="undefined"){
              idLink = "id=" + $(this).find("input.coupon-checkbox").val();
            }
            else {
              idLink = idLink + "&id=" +$(this).find("input.coupon-checkbox").val();
            }
          });
          if(typeof(idLink)!="undefined") {     
            window.location.href="/produits-et-marques-nestle/avantages/ListeBR.aspx?"+idLink; 
	          return false;
          }
          return false;                                                                     
			  });

 			}

 		}

 	}

 }
        
//Impression generale//
//Marche a suivre : ajouter class="launchPrint" au lien declenchant l'impression

 $(document).ready(function() {
     $("a.launchPrint").click(function() {
         $(this).attr("href", "javascript:;");
         window.print();
     });

     // Rollover on image : initialisation
     rolloverTool.rollover.init();

     // Clear textbox and textarea first time you click into it
     jQuery(".jsClearText").bind("click", clearTextBox);

     // hover effect for ie6
     toggleHover();

     // pour la nav tour de main
     jQuery(".leftTDM .leftNav > li > a").click(toggleNav);

     //nav pour coup de coeur
     jQuery("#navCoupDeCoeur > ul > li > a").click(toggleNav);
     //intersticiel
     //initIntersticiel("/Common/templates/intersticiel.html", "300", "250", "/app_themes/common/swf/Visuelsrecettes.swf", "0.6", "#000");

     // newsletter previewing
     jQuery(".previewNL a").bind("click", openPreview);

     
     
     if ($.browser.msie && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9)
     {
        IECouponInitializer();
     }
     else
      (new clv.coupons()).init();
     
     (new clv.popins()).init();

 });

function IECouponInitializer() {
  if ($("div.economy-print").length == 2 || $("div.print-block2 a.print-link").length == 1)
    (new clv.coupons()).init();
  else
    setTimeout('IECouponInitializer();', 200);
}
      

/* Suppression du texte présent dans la textbox */
function clearTextBox(e) {
	if(!this.clearOneTime) {
		this.clearOneTime = true;
		$(this).val("");
	}
} 

  
addEvent(window,'load',clickButton,false);

// toggling tours de main navigation
function toggleNav() {
	//jQuery(".leftTDM .leftNav > li").removeClass("selected");	
	jQuery(this).parent().parent().find("li").removeClass("selected");
	jQuery(this).parent().addClass("selected");	
	jQuery(this).blur();
	return false;
}


// ie6 hover effect (quiz)
function toggleHover() {
//    alert(Query(".quiz #quiz .validation input"));
//	if((jQuery.browser.msie) && jQuery(".quiz #quiz .validation input").length > 0) {
//            jQuery(".quiz #quiz .validation input").hover(function(){
//            jQuery(this).addClass("activate");
//            },function(){
//            jQuery(this).removeClass("activate");
//            });
//    }
}


function initIntersticiel(popinURL,objWidth, objHeight, objURL, objAlpha, objBgColor, targetUrl) {
	openPopinLayer(popinURL, "interstitiel");
	$("#corps").ajaxComplete(function(request, settings){
									  
									  
		var bodyHeightInter = (document.documentElement.clientHeight)/2;
		
		var blockMargin = bodyHeightInter - objHeight/2;
		
		var cssLayer = {
			backgroundColor: objBgColor,
			opacity: objAlpha
		}
		var cssBlock = {
			width: objWidth + "px",
			height: objHeight + "px",
			top: blockMargin
		}
		jQuery("#bgPopinLayer").css(cssLayer);
		jQuery("#innerIntersticiel").css(cssBlock);
		var swfIntersticiel = new SWFObject(objURL, "interFlash", objWidth, objHeight, "8", "#FFFFFF");
		swfIntersticiel.useExpressInstall('/app_themes/common/swf/expressinstall.swf');
		swfIntersticiel.addParam("wmode","transparent");
		swfIntersticiel.addVariable("Target_link", targetUrl);
		
		if(jQuery("#innerIntersticiel").length > 0){
		   swfIntersticiel.write("innerIntersticiel"); 
		}
		
		
	});
}


function openPreview() {
	var myURL = jQuery(this).attr("href");
	//openPopinLayer("/coin_perso/popinPreview.html");
	$("#popinLayerDisplay").remove();
	$("#corps").after('<div id="popinLayerDisplay"><div id="bgPopinLayer"></div></div>');
	$.ajax({
		type:"GET",
		url:"/coin_perso/popinPreview.html",
		success:function(msg) {
			$("#bgPopinLayer").after(msg);
			closePopinLayer();
			backgroundPopin();
			jQuery("#innerPreview").empty();
			jQuery("#innerPreview").append("<img src=\""+ myURL +"\" alt=\"\">");
		},
		complete:function(){
			jQuery("#bgPopinLayer").css("background-color", "#999");
			window.scrollTo(0,0);
			/*var bodyHeight = document.documentElement.clientHeight;
			var elmHeight = jQuery("#previewNL").height();
			var blockMargin = bodyHeight - (elmHeight/2);
			var cssBlock = {
				top: blockMargin
			}
			console.log(elmHeight);
			jQuery("#previewNL").css(cssBlock);*/
		}
	});
	
	
	
	jQuery(this).blur();
	return false;
}




// Ouverture de Popin //
function openPopinAdobe(popinUrl){

		$("#genericPopin").remove();
		
		$.ajax({
			type:"GET",
			url:popinUrl,
			beforeSend:function() {
			// Loader 
			
			$("#corps").after('<div id="genericPopin"><div id="bgGenericPopin"></div><img id="imgLoader" src="/common/Images/ajax-loader.gif" alt="loading..." /></div>')
			backgroundPopin2();
			
			},
			complete:function() {
				$("#imgLoader").remove();
				$("#popinBrSemain").show();
			},
			success:function(msg) {
				$("#bgGenericPopin").after(msg);
				closePopinAdobe();
				validAdobe();
				
			}
		});
}
function closePopinAdobe(){
	$(".mClose a").click(function() {	
		$("#genericPopin").remove();
		if (typeof document.body.style.maxHeight === "undefined") { 
			$("select").show();
		}
		return false; 
	});
}
/////////////////////// pour la popin des BR pour l'impression avec l'installation de PDF
function validAdobe()
{
   $("a.print_br").click(function(){
        var vars = "?";							
		$("#blocBonReduction .droite .imprimer input").each(function(i){
				
				if($(this).attr("checked") == true){
					if(i!=0) vars+="&";
						vars+="id="+$(this).attr("id");
						      					
					}
			  
		});
		window.location="/coin_perso/mes_avantages/Recapitulatif-des-bons-de-reduction-a-imprimer.aspx"+vars; 
		return false;
		});
}

function openPopinBr(idScanCampaign)
{
  openPopinLayer("/produits-et-marques-nestle/avantages/PopinBR.aspx?IdScanCampaign=" + idScanCampaign, "popinBr");
  $("#corps").ajaxComplete(function(request, settings){
    window.scrollTo(0,0);
  });
}


/////////////////////// Rollover
var rolloverTool = {};
rolloverTool.rollover =
{
   init: function() {
      this.preload();
     
      $(".jsRollover").hover(
         function () { $(this).attr( 'src', rolloverTool.rollover.newimage($(this).attr('src')) ); },
         function () { $(this).attr( 'src', rolloverTool.rollover.oldimage($(this).attr('src')) ); }
      );
   },

   preload: function() {
      $(window).bind('load', function() {
         $('.jsRollover').each( function( key, elm ) { $('<img>').attr( 'src', rolloverTool.rollover.newimage( $(this).attr('src') ) ); });
      });
   },
   
   newimage: function( src ) {
      return src.replace(/([-_])off\./, '$1on.');
   },

   oldimage: function( src ) {
      return src.replace(/([-_])on\./, '$1off.');
   }
};

						   

