//----------------------------------------------------------------------------------------

// Author : Guillaume Quimper, Influenza marketing http://www.influenza.ca
// Version 1.0
// Created: December 2010

//----------------------------------------------------------------------------------------

// *************************
// Font Replacement
// *************************

            
Cufon.set('fontFamily', 'monolineMed');
Cufon.replace('#refundPolicy a, #myRonaSpace a', {hover: true});
Cufon.replace('.footerNav h4, #searchFilters label.mainLabel,#productListing div.item .productOptions a.viewDetails,#productInfo #rightInfo div.productCart a.addButton, #relatedRight div h4, .homeContent h3, .bananes a');
Cufon.replace('#CalDropDown a.trigger', {hover: true});

Cufon.set('fontFamily', 'monolineBold');
Cufon.replace('#mainNav  li a.trigger', {hover: true});
Cufon.replace('#CalDropDown li a.trigger', {hover: true});
Cufon.replace('#searchResults h2,h6#comparatorTitle,#compareTable h3,#productInfo #rightInfo h1,#suggestedProducts h3, #featuredProducts h3, #expertProfile h3,  #homeRight h4');


// *******************************
// Start document.ready
// *******************************

$(function() {
 

	// *******************************
	// Parallax Scrolling Backgrounds
	// *******************************

	// Set Function						
	function parallax(){
    	// Distance for the top of document
    	scrollTopCur = $(document).scrollTop();
    	$('#parallax1').css("background-position", "50% -" + Math.round(scrollTopCur * 1.5) + "px");
    	$('#parallax2').css("background-position", "50% -" + Math.round(scrollTopCur / 4) + "px");
	}

    parallax();                     
    $(window).scroll(parallax); 
    $(window).resize(parallax);
    
    
    // *******************************
	// Top Fixed Menu Background
	// *******************************
    
    $(window).scroll(function () {
   		if (scrollTopCur > 10) {
   			$('#fixedTop').addClass('visible');
   		} else {
   			$('#fixedTop').removeClass('visible');
   		}
   		
   	});
		   
	// *************************
	// Main Navigation Drop Down
	// *************************

	//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");
			Cufon.refresh();
		}
	);

// *************************
// Calculatrice Navigation Drop Down
// *************************

	//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;
				});
			}
		};
	}
	$("#CalDropDown li.parent").hover(toggle("Down", "none"), toggle("Up", "block"));
	$("#CalDropDown li.parent ul").hide();
  	//Add class to active parent link
	$("#CalDropDown li.parent ul").hover(
		function(){
			$(this).prev("a").addClass("active");
		},
		function() {
			$(this).prev("a").removeClass("active");
		}
	);

	// ****************************
	// Search Form Watermark
	// ****************************

	// Fade out label on focus
	$("#searchForm input.textInput").focus(function() {
		$(this).prev("label.watermark").fadeOut('fast');											  
	});
	// If input is left blank fade in label
	$("#searchForm input.textInput").blur(function() {
		var inputValue  = $(this).val();
		if (inputValue == "") {
			$(this).prev("label.watermark").fadeIn('fast');
		}
	});

	// *************************
	// Homepage Caroussel
	// *************************

	$('#slides').cycle({ 
		slideExpr: 'div.slide',
		fx: 'scrollUp',
		cleartypeNoBg: true,
		cleartype:  1,
		pager: '#slidePager',
		pause: true,
    	pauseOnPagerHover: true, 
		speed: 300, 
    	timeout: 8000,
    	before: onBefore, 
    	after: onAfter,
    	//Build Pager
    	pagerAnchorBuilder: function(idx, slide) { 
        	return '<a href="#"><span class="number">'+ (idx+1) +'</span></a>'; 
    	}

	});
	// Remove Timer
	function onBefore() { 
    	$('span.timer').flash().remove();
    	$('span.timer').remove();
	}
	// Add Timer 
	function onAfter() { 
    	$('span.timer').flash().remove();
    	$('#slidePager a.activeSlide').append('<span class="timer"></span>');
    	$('.timer').flash({swf: '/v2/_object/carousel-timer-animation.swf',width: 24,height: 24,wmode: 'transparent'});
	}
	// Add Timer on load
	$('#slidePager a.activeSlide').append('<span class="timer"></span>');
	$('.timer').flash({swf: '/v2/_object/carousel-timer-animation.swf',width: 24,height: 24,wmode: 'transparent'});

	// Some Styling
	$('#slidePager a:last').addClass('last');
	Cufon.set('fontFamily', 'monolineBold');
	Cufon.replace('#slidePager a', {hover: true});

	// *************************
	// Homepage Styling
	// *************************

	// Add Class to last post entry
	$('.homeContent:last').addClass('last');
	
	// Make all .homeContent DIV clickables
	$(".homeContent").click(function(){
	  window.location=$(this).find("a").attr("href"); 
	  return false;
	});
	
	// Wrap .homeContent h6 in <span>
	$('.homeContent h6').wrapInner('<span />');
	
	// .homeContent Hover Effect
	$(".homeContent").hover(function() {
		$("a",this).addClass('boxHover');
		$("img", this).stop().fadeTo("normal", 0.8);
	}, function() {
		$("a",this).removeClass('boxHover');
		$("img", this).stop().fadeTo("normal", 1);
	});
	
	// Make all #suggestedProducts DIV clickables
	$(".relatedItem").click(function(){
	  window.location=$(this).find("a").attr("href"); 
	  return false;
	});
	
	// #suggestedProducts DIV Hover Effect
	$(".relatedItem").hover(function() {
		$("a",this).addClass('boxHover');
		$("img", this).stop().fadeTo("normal", 0.8);
	}, function() {
		$("a",this).removeClass('boxHover');
		$("img", this).stop().fadeTo("normal", 1);
	});
	
	// Wrap Customize Links in <span>
	$('#customizeHomepage ul li a').wrapInner('<span />');
	
	// Customize Link Actions
    $("#customizeHomepage a").click(function(){  
        $('#customizeHomepage ul li').removeClass('active'); 
        $(this).parent('li').addClass('active');
        return false; 
    });

	// *************************
	// Split UL into columns
	// *************************

	// Split Column
	$('#productTypes ul').easyListSplitter({ 
		colNumber: 4
	});


	// *************************
	// Item Listing Styling
	// *************************

	// Adjust item padding on left and right edges of listing
	$("#productListing div.item:eq(0),#productListing div.item:eq(4),#productListing div.item:eq(8)").addClass("leftEdge");
	// Reduce Price padding if a rebate is active
	$("span.rebate ~ span.price").css("padding-top", "5px");
	// Set Variables for Comparator
	itemTotalComparator = 0;
	// Comparator Checkboxes
    $("#productListing :checkbox").change(function(){  
        if (itemTotalComparator < 5) {
        	if($(this).is(":checked")){  
           	$(this).next("label").addClass("active");
           	$(this).parents('div.item').find('div.compareSelected').fadeIn('fast');
           	
           	if (itemTotalComparator < 4) {
           		itemTotalComparator++;
           	}
           	
           	if (itemTotalComparator == 4) { 
           		$("#productListing :checkbox").attr('disabled', true);
           		alert('Vous avez placé le nombre maximum (4) de produits dans le comparateur'); 
           		$('#productListing span.compare label.active').click(function(){
    				if (itemTotalComparator == 4) {
    					$("#productListing :checkbox").removeAttr('disabled');
    				}
    				
    			});
           	}
        } else {  
           	if (itemTotalComparator <= 4) {
           		$(this).next("label").removeClass("active");
           		$(this).parents('div.item').find('div.compareSelected').hide();
           		itemTotalComparator--;
           	};
        }
        // Show/Hide Compare Link
        if(itemTotalComparator < 2){
    		$('div.compareSelected a').hide();
    	} else {
    		$('div.compareSelected a').fadeIn('fast');
    	}
    	}
    });
	
    // Enlarge Item Hover Delay
	function activateItem(){ $(this).addClass("activeOptions");}
	function desactivatedItem(){ $(this).removeClass("activeOptions");}
	$("#productListing div.item").hoverIntent( activateItem, desactivatedItem );
	// Trigger Select Styling Plugin
	$('#productListing div.item .productOptions select').selectbox();



	// *************************
	// Search Filters Styling
	// *************************

	// Trigger Select Styling Plugin
	$('#searchFilters select').selectbox();
	// Add <span> to Main Label
	$('.selectBrands label:first-child, .selectPrice label').append('<span class="arrow"></span>');
	// Wrap Labels in <span>
	$('#searchFilters ul li label').wrapInner('<span class="text" />');
	$('#searchFilters ul li label').prepend('<span class="checkmarks"></span>');
	// Custom Styled Checkboxes
    $("#searchFilters :checkbox").change(function(){  
        if($(this).is(":checked")){  
           $(this).next("label").addClass("active");  
         }else{  
             $(this).next("label").removeClass("active");  
        }  
    });
	// Reset checboxes label
	$("#resetFilters").click(function() {
		$('#searchFilters ul li label').removeClass("active");											  
	});
	// Add <span> to link
	$('#searchFilters a.moreBrands').append('<span></span>');

	//**************************
	// Product Page
	//**************************

    // Trigger jCarousel
	$('#otherProducts').jcarousel();
	// Prepare Comparator
	$('#comparator').addClass('closed');
	// Open Comparator
	$('#openComparator').click(function() {
		$('#comparator').slideDown('fast');
		$('#comparator').removeClass('closed');
		$(this).fadeOut('fast');
		return false;
	});
	// Close Comparator
	$('#closeComparator').click(function() {
		$('#comparator').slideUp('fast');
		$('#comparator').addClass('closed');
		$('#openComparator').fadeIn('fast');
		return false;
	});
	
	// Draggable Items
	$('.dragItem').draggable({
		opacity: 0.7,
		scope: 'addToComparator',
		revert: 'invalid',
		appendTo: "body",
		helper: "clone",
		cursorAt: { cursor: 'move', top: 38, left: 38 },
		refreshPositions: true
	});
	// Open Comparator if Closed
	$('.dragItem').bind( 'drag', function(event, ui) {
		$('#comparator.closed').slideDown('fast');
		$('#openComparator').fadeOut('fast');
	});
	
	// Set Variables for Comparator
	var itemTotalComparator = 0;
	var itemTotalComparatorReset = itemTotalComparator;
	var initDiv = $('#comProduct1').html();
	
	// Empty Drop Zones
	$('#emptyComparator').click(function() {
		$('.dropZone').empty();
		$('.dropZone').append(initDiv);
		$('#otherProducts a:not("a.dragItem")').addClass('dragItem');
		$('#otherProducts a:not("a.dragItem")').addClass('ui-draggable');
		itemTotalComparator = itemTotalComparatorReset;
		return false;
	});
	
	
	
	// Drop Zones
	$(".dropZone").droppable({
		greedy: false,
		hoverClass: 'drophover',
		accept: '.dragItem',
		scope: 'addToComparator',
		tolerance: 'pointer',
		drop: function(event, ui) {
			var thisDiv = $(this);
			var thisDivID = $(this).attr('id');
			var dropElemID = ui.draggable.attr('id');
			$(this).find('span').remove();
			if(thisDiv.contents().length == 0){
				var dropElem = ui.draggable.html();
				thisDiv.append(dropElem);
				thisDiv.append('<input type="hidden" name="'+ thisDivID +'" value="'+ dropElemID +'" />');
				thisDiv.append('<a href="#" class="removeItem">Retirer le produit</a>');
				$('a#'+dropElemID+'').removeClass('dragItem');
				$('a#'+dropElemID+'').removeClass('ui-draggable');
        		var sizelien = $('a.removeItem').size();
				itemTotalComparator = sizelien;
				
				//alert(sizelien);
				
				// RemoveItem
				$('.removeItem').click(function () {
					$('a#'+dropElemID+'').addClass('dragItem');
					$('a#'+dropElemID+'').addClass('ui-draggable');
					$(this).parents('.dropZone').empty().append(initDiv);
					return false; 
				});
			
			}
			
		}
	});
	
	// Trigger Select Styling Plugin
	$('#productInfo #rightInfo div.productCart div.option select').selectbox();
	$('#productInfo #rightInfo div.productCart div.addToCart select').selectbox();
	// Trigger Select Styling Plugin
	$('#relatedProducts div.item select').selectbox();
	// Related Info Tabs
	var tabContainers = $('#panel > div');
	$('#tabSelector a').click(function () {
        tabContainers.hide().filter(this.hash).show();
        $('#tabSelector li').removeClass('active');
        $(this).parent('li').addClass('active');
        return false;
    });
	// Adjust item padding on left and right edges of listing
	$("div.relatedItem:nth-child(4n+1)").addClass("rightEdge");
	$("div.relatedItem:nth-child(2)").addClass("leftEdge");
	
	// *******************
	// Custom Modal Window
	// *******************
  
	//select all the a tag with name equal to modal  
	$('a[rel="modal"]').click(function(e) { 
	    var dropZoneElement = document.getElementById("compareProducts");
      if (dropZoneElement != null)
      {
       var sizelink2 = $('.dropZone a.removeItem').size();
            if(sizelink2 < 2){
            alert('Vous devez sélectionner au moins 2 produits');	
            return false; 
            }
      }
 
		// Make sure there's at least 2 items selected
	 	if(itemTotalComparator >= 2){
			// 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});  
			
			// Mask 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);
			
			// FadeIn Content
			$(id).fadeIn(500);
		 }
		 else {
			alert('Vous devez sélectionner au moins 2 produits');	 
		 }
		     
	});
	// 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});   
	}); 	
	// If close button is clicked  
	$('.modalWindow .close').click(function () {  
		$('#mask').fadeOut();
		$('.modalWindow').fadeOut (300);
		return false;
	});
	// If mask is clicked  
	$('#mask').click(function () {  
		$(this).fadeOut();  
		$('.modalWindow').fadeOut (300);
	});
	

	// *******************
	// Comparaison Table
	// *******************

	// Remove Border for last item on the right
	$('#compareTable table tr td:last-child').addClass('rightEdge')
	// Trigger Select Styling Plugin
	$('#compareTable table select').selectbox();
	
	
	// *******************
	// Footer Styling
	// *******************
	$('.footerNav a').wrapInner('<span />');
	
	//******************************************************************************************************************
	// Disable some default browser behavior on imgages and links -  e.g. alt & title attributes from showing
	// Should be kept at the very end to avoid conflict with other functions that might use those attributes
	//******************************************************************************************************************

	$(function() {
		$('img, a').removeAttr('title');
		$('img').removeAttr('alt');
	});
	
// End of document.ready
});
