//----------------------------------------------------------------------------------------

// Authors : Guillaume Quimper & Nadia Hadji, Influenza marketing http://www.influenza.ca
// Version 1.0
// Created: October 2010

//----------------------------------------------------------------------------------------


// *************************
// Main Navigation Drop Down
// *************************

$(function() {
	//Open submenu
	var toggle = function(direction, display) {
    return function() {
      var self = this;
      var ul = $("ul", this);
      if( ul.css("display") == display && !self["block" + direction] ) {
        self["block" + direction] = true;
        ul["slide" + direction]("normal", function() {
          self["block" + direction] = false;
        });
      }
    };
  }
  $("#mainNav li.parent").hover(toggle("Down", "none"), toggle("Up", "block"));
  $("#mainNav li.parent ul").hide();
  
  //Add class to active parent link
	$("#mainNav li.parent ul").hover(
		function(){
			$(this).prev("a").addClass("active");
		},
		function() {
			$(this).prev("a").removeClass("active");
		}
	);
});




// ****************************
// Cost & Accessibility Toolpip
// ****************************

$(function(){
	$("#content #splitContent #rightColumn div span").hover(
		function(){
			$(this).next("div").fadeIn("fast");
		},
		function() {
			$(this).next("div").fadeOut("fast");
		}
	);

});

// ************************
// Products Listing Styling
// ************************

$(function(){
	$("#productListing li:eq(0),#productListing li:eq(4),#productListing li:eq(8)").addClass("noBorder");
});

// **********************
// Life Cycles Hover Text
// **********************

$(function() {
	var tabContainers = $('#detailsCycle > div');
	
	$('ul#cycles li.on a').click(function () {
        tabContainers.hide().filter(this.hash).fadeIn('fast');
		$('ul#cycles li.on').removeClass('active');
        $(this).parent('li').addClass('active');
        return false;
    });
	$('#detailsCycle #start').show();
	$('ul#cycles li a').click(function () {
		return false;								   
	});
});


// *****************
// Product Info Tabs
// *****************

$(function() {
	var tabContainers = $('#detailsProduct > div');
	
	$('#tabSelector a').click(function () {
        tabContainers.hide().filter(this.hash).show();
        $('#tabSelector li').removeClass('active');
        $(this).parent('li').addClass('active');
        return false;
    })/*.filter('#tabSelector a:first').click()*/;
}); 

// ************************
// Postal Code modification
// ************************

$(function(){
	$("a.changeCode").click(function (){
		$(".viewPrice").hide();
		$("#postalForm1").fadeIn('fast');
	});
});


// ************************
// Font Replacement - Cufón
// ************************
Cufon.set('fontFamily', 'akzidenz');

Cufon.replace('#homeVideo a.play, #homeHighlight h3, #homeHighlight a, #content h1, #content #didYouKnow h5, #content a.discoverProducts, #content #productInfo #productPrice .viewPrice h4, #content #productInfo #productPrice .viewPrice h5 strong, input#buttonPostal, #content #productInfo #productPrice .buyProduct a.buyButton, #content #productInfo #lifeCycle #detailsCycle h5, #rightColumn h4, #cost div table caption, #accessibility div table caption, #cost div table td.definition, #accessibility div table td.definition, #content table.issues td.issue, #content table.issues td.action, #content table.leed th span, #content table.approach tbody th span, #content table.renovate tbody td.issue, #content table.renovate tbody td.action,#content table.heating tbody td.source, #content table.flooring tbody td.type, #adminContainer h1, #page404 h2, #page404 p, #newsletter h1, #newsletter h2, #newsletter div#newsletterContainer input.submit, #leftColumn #sideNav h3, #leftColumn #columnVideo h5');

Cufon.replace('#homeMessage p a', {hover: true});  

// **************
// HotSpot Images
// **************
$(function(){
	
	$("#hotSpot li").each(function (i) {
		i = i+1;
		$(this).prepend("<span class=\"smallNumber\">"+i+"</span>");
		Cufon.replace('span.smallNumber');
	});
	
	$("#hotSpot li a").each(function (i) {
		i = i+1;
		$(this).prepend("<span class=\"largeNumber\">"+i+"</span>");
		Cufon.replace('span.largeNumber');
	});
	
	if ($.browser.msie && $.browser.version < 9) { 
		$("#hotSpot li").hover(
			function(){
				$("a", this).show();
			},
			function() {
				$("a", this).hide();
			}
		);
	}
	else {
		$("#hotSpot li").hover(
			function(){
				$("a", this).fadeIn("fast");
			},
			function() {
				$("a", this).fadeOut("fast");
			}
		);
	}
});


// ***************************
// Stategy Numbering & Styling
// ***************************
$(function(){
	$(".strategy li").each(function (i) {
		i = i+1;
		$(this).prepend("<span class=\"mediumNumber\">"+i+"</span>");
		Cufon.replace('span.mediumNumber');
	});
	$(".strategy li a").append("&nbsp;<strong>&rarr;</strong>");
});

// ************************
// Recommandation Numbering
// ************************
$(function(){
	$("#recommandations li").not("#recommandations li li").each(function (i) {
		i = i+1;
		$(this).prepend("<span class=\"recommandationNumber\">"+i+"</span>");
		Cufon.replace('span.recommandationNumber');
	});
});

// ************************
// Newsletter Numbering
// ************************
$(function(){
	$("#newsletter li").not("#adminToolbar li").each(function (i) {
		i = i+1;
		$(this).prepend("<span class=\"reasonNumber\">"+i+"</span>");
		Cufon.replace('span.reasonNumber');
	});
});


// **********************************
// Li class last & class right header
// **********************************

$(function(){   
$(".projets ul li:first").addClass('first'); 
$(".projets ul li:last").addClass('last'); 
$("#allProjects li:odd").addClass('right');
$("#sideNav li li a.active").parent().parent().parent().children().addClass('active');
});

$(function(){ 
	$(".certification a").append("&nbsp;<strong>&rarr;</strong>");
});

// *******************
// Custom Modal Window
// *******************
$(function() {    
	 
	 //select all the a tag with name equal to modal  
     $('a[rel="modal"]').click(function(e) {  
         //Cancel the link behavior  
         e.preventDefault();  
         //Get the A tag  
         var id = $(this).attr('href');  
       
         //Get the screen height and width  
         var maskHeight = $(document).height();  
         var maskWidth = $(window).width();  
       
         //Set height and width to mask to fill up the whole screen  
         $('#mask').css({'width':maskWidth,'height':maskHeight});  
           
         //transition effect       
         $('#mask').fadeIn(500);      
         $('#mask').fadeTo("fast",0.85);    
       
         //Get the window height and width  
         var winH = $(window).height();  
         var winW = $(window).width();  
                 
         //Set the popup window to center  
         $(id).css('top',  winH/4-$(id).height()/4);  
         $(id).css('left', winW/2-$(id).width()/2);  
       
     });
	 
	 //Set Flash Player For Older Browsers
	  if ($.browser.msie && $.browser.version < 9) { var browser = "unsupported"; } 
	  else if ($.browser.mozilla == true) { var browser = "unsupported"; }
	  else { var browser = "supported"; }
	  
	  //Write Flash if Unsupported Browser
	  if (browser == "unsupported" ) {
	 	
		// Build French Movie
		$("a.play.fr").click(function () {
			$('#videoContainer').empty();
			$('#videoContainer').flash({swf: '/video/player.swf',width: 960,height: 550,flashvars: {skin: '/video/skins/echo.swf',thumbnail: '/video/video-thumbnail-fr.jpg',video: '/video/video-cycle-fr.flv'}});
		});
		// Build English Movie
		$("a.play.en").click(function () {
			$('#videoContainer').empty();
			$('#videoContainer').flash({swf: '/video/player.swf',width: 960,height: 550,flashvars: {skin: '/video/skins/echo.swf',thumbnail: '/video/video-thumbnail-en.jpg',video: '/video/video-cycle-en.flv'}});
		});
		
	  }
	  
	  // Write French Movie
	  if(browser == "supported") {
		 
		// Build French Movie
		$("a.play.fr").click(function () {
			 $('#videoContainer').empty();
			 $('#videoContainer').append('<div class="video-js-box"><video id="example_video_1" class="video-js" width="952" height="540" controls="controls" preload="auto" poster="/video/video-thumbnail-fr.jpg"><source src="/video/video-cycle-fr.mp4" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' /></video></div>');
			 VideoJS.setupAllWhenReady();
		});
		
		// Build French Movie
		$("a.play.en").click(function () {
			 $('#videoContainer').empty();
			 $('#videoContainer').append('<div class="video-js-box"><video id="example_video_1" class="video-js" width="952" height="540" controls="controls" preload="auto" poster="/video/video-thumbnail-en.jpg"><source src="/video/video-cycle-en.mp4" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' /></video></div>');
			 VideoJS.setupAllWhenReady();
		});
		 
	  }
	 
	 //Adjust Mask on Window Resize
	 $(window).resize(function() {
		//Get the screen height and width  
         var maskHeight2 = $(document).height();  
         var maskWidth2 = $(window).width();
		$('#mask').css({'width':maskWidth2,'height':maskHeight2});   
	 });
	 
	
	// Stop Video on Closing - Depending on Browser Support
	if (browser == "unsupported" ) {
		$('.modalWindow .close,#mask').click(function () { 
			//Remove Flash
			$('#videoContainer').flash().remove();
		});  
	   	} else {
			// Stop Video on Close
			var $gVideo = $(".video-js-box video");
			var gPlay = function() {	
				$gVideo[0].pause();					
		};
		$('.modalWindow .close,#mask').click(function () {
			$('#videoContainer').empty();									   
		});
	}

	
     //if close button is clicked  
     $('.modalWindow .close, #infoTable .close, #newsletter .close, .modalContent .close').click(function () {  
         //e.preventDefault();  
         $('#mask').fadeOut();
		 $('.modalWindow, #infoTable, #newsletter, .modalContent').css ('left', -3000);
		 return false;
     });       
       
     //if mask is clicked  
     $('#mask').click(function () {  
         $(this).fadeOut();  
         $('.modalWindow, #infoTable, #newsletter, .modalContent').css ('left', -3000);
		 //$('video').pause();
     });           
       
});

// ************************
// Smooth Jump Menu
// ************************

$(function(){
	// Prepare fucntion
	var scrollContent = function() {
		var $contentDestination = $(this.hash);
		$('html, body').animate({
		scrollTop: $($contentDestination).offset().top
		}, 1000);
		return false;
	};
	// Set triggers
	$('#jumpmenu a, a.top').click(scrollContent);
});

// ******************
// Homepage Caroussel
// ******************


$(function(){
	$('#slideHome').cycle({ 
		slideExpr: 'div.slide',
		fx: 'scrollHorz',
		cleartypeNoBg: true,
		cleartype:  1,
		pager: '#slidePager',
		pause: true,
    	pauseOnPagerHover: true, 
		speed:   800, 
    	timeout: 7000
	});
});


// **********************
// Postal Code Validation
// **********************

$(function(){
//Add Regex for Postal Code
jQuery.validator.addMethod('postalCode', function (value) {
	return /^([ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]\d[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstwvxyz]\d)$/.test(value);
}, 'Veuillez entrer un code postal valide.');

	// Validate French
	var validator = $("#productPrice form.fr").bind("invalid-form.validate", function() {
		
	}).validate({
		rules: {
			code: {
				postalCode: true
			}
		},
		messages: {
			code: {
				required: "Veuillez entrer votre code postal",
				postalCode: "Veuillez entrer un code postal valide"
			}
   		}

	});
	
	//Validate English
	var validator = $("#productPrice form.en").bind("invalid-form.validate", function() {
		
	}).validate({
		rules: {
			code: {
				postalCode: true
			}
		},
		messages: {
			code: {
				required: "Please enter your postal code",
				postalCode: "Invalid postal code"
			}
   		}

	});
	
});

// *********************
// Login Form Validation
// *********************

$(function(){

	// Validate French
	var validator = $("#conn").bind("invalid-form.validate", function() {
		
	}).validate({ 
		messages: {
			login: "Veuillez saisir un nom d'utilisateur",
			mdp: "Veuillez saisir un mot de passe"
   		}

	});
	
});  


// ****************************
// Newsletter Form & Validation
// ****************************

$(function(){
		   
	$("#newsletter input.textInput").focus(function() {
		$(this).prev("label.watermark").fadeOut('fast');											  
	});
	
	
	$("#newsletter input.textInput").blur(function() {
		var inputValue  = $(this).val();
		if (inputValue == "") {
			$(this).prev("label.watermark").fadeIn('fast');
		}
	});

  $("input#yes_airmiles").click(function() {		   
			  $("#rep_airmiles").fadeIn("normal");
	});
	$("input#no_airmiles").click(function() {		   
			  $("#rep_airmiles").fadeOut("normal");
	});	


//Add Regex for Postal Code
jQuery.validator.addMethod('postalCode', function (value) {
	return /^([ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]\d[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZabceghjklmnprstwvxyz]\d)$/.test(value);
}, 'Veuillez entrer un code postal valide.');

	// Validate French
	var validator = $("#newsletter_FR").bind("invalid-form.validate", function() {
		
	}).validate({
	rules: {
			code: {
				postalCode: true
			},
			email:{ 
        required: true,
				email: true,      
        remote: {
        url: "/inc/email.php",
        type: "post",
        data: {
          username: function() {
            return $("#email").val();
          }
        }
      }
      }
		},
		messages: {
			prenom: "Erreur: Entrer un prénom",
			nom: "Erreur: Entrer un nom",
      email: {
                required: 'Erreur: Entrer un courriel',
                email: 'Adresse invalide',
                remote: function() {
                // $("#email") is the input field for the email address
                return $("#email").val()+' existe déjà';

                }

              },     
			code: {
				required: "Erreur: Entrer un code postal",
				postalCode: "Code postal invalide"
			}
   		},       
      submitHandler: function(form) {
              jQuery(form).ajaxSubmit({
              target: "#newsletter_FR",
                  success: function() {
                  $("#newsletter_FR").html("<div id=\"newsletterMessage\" class=\"fr\"></div>");
                  $("#newsletterMessage").html("<h1>Merci de prendre part au mouvement.</h1><h2>Vous avez des suggestions pour notre bulletin ? Écrivez-nous à l'adresse suivante <a href=\"mailto:info@rona-eco.ca\">info@rona-eco.ca</a></h2>")
                  
                  //.append("<p></p>")
                  .hide() 
                  .fadeIn(1500, function() { 
					  $("#newsletterMessage");
					  _gaq.push(['_setCustomVar',2,'newsletter-subscriber','FR',2]);
					  _gaq.push(['_trackPageview', "/goal/newsletter"]);
                  });
                  }
              });
              }
   		
	});
	
	
	// Validate English
	var validator = $("#newsletter_EN").bind("invalid-form.validate", function() {
		
	}).validate({
	rules: {
			code: {
				postalCode: true
			},
			email:{ 
        required: true,
				email: true,      
        remote: {
        url: "/inc/email.php",
        type: "post",
        data: {
          username: function() {
            return $("#email").val();
          }
        }
      }
      }
		},
		messages: {
			prenom: "Error: Enter your first name",
			nom: "Error: Enter your last name",
      		email: {
                required: 'Error: Enter your email address',
                email: 'Error: Invalid address',
                remote: function() {
                // $("#email") is the input field for the email address
                return $("#email").val()+' already exists';

                }

            },     
			code: {
				required: "Error: Enter your postal code",
				postalCode: "Error: Invalid postal code"
			}
   		},       
      submitHandler: function(form) {
              jQuery(form).ajaxSubmit({
              target: "#newsletter_EN",
                  success: function() {
                  $("#newsletter_EN").html("<div id=\"newsletterMessage\" class=\"en\"></div>");
                  $("#newsletterMessage").html("<h1>Thank you for taking part of the movement.</h1><h2>You'll be hearing from us soon. Do you have newsletter suggestions for us? Email us at <a href=\"mailto:info@rona-eco.ca\">info@rona-eco.ca</a></h2>")
                  //.append("<p></p>")
                  .hide()
                  .fadeIn(1500, function() {
                  	$("#newsletterMessage");
					_gaq.push(['_setCustomVar',2,'newsletter-subscriber','EN',2]);
					_gaq.push(['_trackPageview', "/goal/newsletter"]);
                  });
                  }
              });
              }
   		
	});


});  

