/* EMPECHE LE FLICKING DE TYPEKIT SIMPLEMENT ENLEVER LES COMMENTAIRES POUR ACTIVER */
(function(){
  // if firefox 3.5+, hide content till load (or 3 seconds) to prevent FOUT
  var d = document, e = d.documentElement, s = d.createElement('style');
  if (e.style.MozTransform === ''){ // gecko 1.9.1 inference
    s.textContent = 'body{visibility:hidden}';
    var r = document.getElementsByTagName('script')[0];
    r.parentNode.insertBefore(s, r);
    function f(){ s.parentNode && s.parentNode.removeChild(s); }
    addEventListener('load',f,false);
    setTimeout(f,3000); 
  }
})();




jQuery(function($) {
	/* METTRE TOUS LES SCRIPTS POUR LE SITE ICI PLUTOT QUE DIRECTEMENT DANS LA PAGE! */
	
	
    /* ***************************************************************
        OUVERTURE DES LIENS EXTERNE DANS UN NOUVEAU TAB / WINDOW 
        Note : ajouter class="in" si vous voulez qu'il s'ouvre 
               dans la même fenêtre.
    *************************************************************** */
	//jQuery('a[href^=http]:not(.in)').attr({'target':'_blank'});
	
	$('.subnav-link').click(function() { 
		var $ul = $(this).parent().find('> ul');//.slideToggle();
		if ($ul.hasClass('open')) $ul.removeClass('open').show();
		$ul.slideToggle();
		var myover = $(this).parent();
		if (myover.hasClass('active')) myover.removeClass('active');
		else myover.addClass('active');
		return false;
	});
	$('#sidebar-nav > li > a').click(function() { 
		$(this).parent().find('> ul').slideToggle();
		return false;
	});
	
	
	$('#topnav-drop > li').hover(function() { 
		$(this).stop().animate({top:'0px'},150);
	},function() {
		$(this).stop().animate({top:'-68px'},250);
	});
	
	$('#bt-sitemap').click(function() { 
		var height=220;
		if ($(this).hasClass('is-visible')) height=20;
		$(this).parent().parent().stop(false,true).animate({height:height+'px'},500);
		$(this).toggleClass('is-visible');
		return false;
	});
	
	$('.listing-horizon').click(function() { 
		/*var myover = $(this);
		if (myover.hasClass('active'))
		{
		$('#list-block').removeClass('horizontal');
		myover.removeClass('active');
		}
		else
		{ 
		myover.addClass('active');
		$('#list-block').addClass('horizontal');
		$('.listing-block').removeClass('active');
		}*/
		$('.listing-block').removeClass('active');
		$('.listing-horizon').addClass('active');
		$('#list-block').addClass('horizontal');
		$.cookie('list','horizontal');
		return false;
	});
	$('.listing-block').click(function() { 
		/*var myover = $(this);
		if (myover.hasClass('active'))
		{
		$('#list-block').addClass('horizontal');
		myover.removeClass('active');
		}
		else
		{ 
		myover.addClass('active');
		$('#list-block').removeClass('horizontal');
		$('.listing-horizon').removeClass('active');
		}*/
		$('.listing-block').addClass('active');
		$('.listing-horizon').removeClass('active');
		$('#list-block').removeClass('horizontal');
		$.cookie('list','');
		return false;
	});
	
	/*$('#showlist > a').click(function() { 
		var top=-320;
		if ($(this).parent().hasClass('is-visible')) top=-42;
		$(this).parent().stop(false,true).animate({top:top+'px'},500);
		$(this).parent().toggleClass('is-visible');
	});
	$('#bt-wish').click(function() { 
		$('body').removeClass('compareractive');
		$('body').addClass('wishactive');
		return false;
	});
	$('#bt-compare').click(function() { 
		$('body').addClass('compareractive');
		$('body').removeClass('wishactive');
		return false;
	});*/
	$('#bt-wish').click(function() { 
		
		if ($(this).parent().hasClass('is-visible') && $('body').hasClass('wishactive')) {
			$(this).parent().stop(false,true).animate({top:'-42px'},500);
			$(this).parent().removeClass('is-visible');
		}
		else if ($('body').hasClass('wishactive')) {
			$(this).parent().stop(false,true).animate({top:'-320px'},500);
			$(this).parent().addClass('is-visible');
			$(this).addClass('active');
			$('#bt-compare').removeClass('active');
		} else {
			$(this).parent().stop(false,true).animate({top:'-320px'},500);
			$(this).parent().addClass('is-visible');
			$(this).addClass('active');
			$('#bt-compare').removeClass('active');
			$('body').removeClass('compareractive');
			$('body').addClass('wishactive');
		}
		return false;
	});
	$('#bt-compare').click(function() { 
		
		if ($(this).parent().hasClass('is-visible') && $('body').hasClass('compareractive')) {
			$(this).parent().stop(false,true).animate({top:'-42px'},500);
			$(this).parent().removeClass('is-visible');
		}
		else if ($('body').hasClass('compareractive')) {
			$(this).parent().stop(false,true).animate({top:'-320px'},500);
			$(this).parent().addClass('is-visible');
			$(this).addClass('active');
			$('#bt-wish').removeClass('active');
		} else {
			$(this).parent().stop(false,true).animate({top:'-320px'},500);
			$(this).parent().addClass('is-visible');
			$(this).addClass('active');
			$('#bt-wish').removeClass('active');
			$('body').removeClass('wishactive');
			$('body').addClass('compareractive');
		}
		return false;
	});
	
	if ($('#comparer').length) {
		$('#comparer').width(($('#comparer>ul>li').length*252)+6);
	}
	
	
	// ! POPUPS ! ! !
	$('.box-popup').live('click',function() {
		$('<div id="overlay" class="loading" />').appendTo($('body')).load($(this).attr('href'),function() { $(this).removeClass(); });
		map = null;
		homemarker = null;
		markers = new Array();
		geocoder;
		return false;
	});
	$('#bg,#over-close').live('click',function() {
		$('#overlay').remove();
		return false;
	});
	$('.mail').click(function() {
		$('<div id="overlay" class="loading" />').appendTo($('body')).load('/share.php?url='+escape(location.href),function() { $(this).removeClass(); });
		return false;
	});
	
	
	// ! DEALER LOCATOR ! ! ! 
	var map = null,
	homemarker = null,
	markers = new Array(),
	geocoder,
	curInfoWindow=null;
	
	$('#dealer-locator').live('submit',function() {
		//console.log('test');
		$(this).find('input[type=image]').next().remove();
		var geocoderFunction = function() {
			if (map==null) {
				//$('#map').show();
				
			} else {
				cleanMap();
			}
			geocoder = new google.maps.Geocoder();
			geocoder.geocode( { 'address': $('#cp').val()}, function(results, status) {
			  if (status == google.maps.GeocoderStatus.OK) {
				
				
				if (!$('#dealer-locator').data('loaded')) {
					
					$('#dealer-locator').data('loaded',true);
					$('#map-content > div').hide();
					$('#map').show();
					$('#over-container').css({marginTop:'-300px'});
					$('#map-content').show().css({height:'400px'});
					map = new google.maps.Map(document.getElementById('map'), {zoom: 10,mapTypeId: google.maps.MapTypeId.ROADMAP});
					//$('#over-container').animate({marginTop:'-=200px'},500);
					//$('#map-content').show().height(0).animate({height:'400px'},500);
					
				}
				map = new google.maps.Map(document.getElementById('map'), {zoom: 10,mapTypeId: google.maps.MapTypeId.ROADMAP});
				map.setCenter(results[0].geometry.location);
				
				homemarker = new google.maps.Marker({
					map: map, 
					position: results[0].geometry.location
				});
				loadNearestUnimat(homemarker.getPosition());
			  } else {
				$('#dealer-locator input[type=image]').after('<span>Impossible de localiser ce code postal.</span>');
				//$('#over-container').animate({marginTop:'+=200px'},500);
				//$('#map-content').show().animate({height:'0'},500);
			  }
			});
		}
		geocoderFunction();
		/*if (!$(this).data('loaded')) {
			$(this).data('loaded',true);
			$('#map-content > div').hide();
			$('#over-container').animate({marginTop:'-=200px'},500,geocoderFunction);
			$('#map-content').show().height(0).animate({height:'400px'},500);
		} else {
			geocoderFunction();
		}*/
		
		return false;
	});
	
	var cleanMap = function() {
		if (homemarker != null) {
			homemarker = removeMarker(homemarker);
		}
		for(var i=0;i<markers.length;i++) removeMarker(markers[i]);
		markers = new Array();
		map=null;
		$('#map').html('');
	};
	
	var removeMarker = function(elm) {
		elm.setMap(null);
		return null;
	};
	
	var addMarker = function(options) {
		var marker = new google.maps.Marker({
			map: map, 
			position: new google.maps.LatLng(options.lat,options.lon),
			icon:'http://www.unimat.ca/images/icone_map.png'
		});
		var infowindow = new google.maps.InfoWindow({ content: getInfoHTML(options)});
		google.maps.event.addListener(marker, 'click', function() {
			if (curInfoWindow!= null) try {
				curInfoWindow.close();
			} catch(e) {}
			curInfoWindow = infowindow;
			infowindow.open(map,marker);
		});
		markers.push(marker);
	};
	
	var getInfoHTML = function(options) {
		var html = '<b>'+options.nom+'</b><br />';
		html += options.adresse+'<br />';
		html += options.ville+', '+options.code_postal+'<br />';
		html += options.telephone;
		return html;
	};
	
	var loadNearestUnimat = function(latlng) {
		$.getJSON('/dealer-locator.php?locate=1&lat='+latlng.lat()+'&lng='+latlng.lng()+'&inov='+$('#inov').val(),function(data) {
			$.each(data, function(key, val) {
				addMarker(val);
				//console.log(val);
			});
		});
	};
	
	// ! INSCRIPTION MAILING LIST ! ! !
	$('#frm-infoclic').live('submit',function() {
		// VALIDATE 
		$('#frm-infoclic input[type=image]').next().remove();
		if (!validMail($('#email').val())) {
			$('#frm-infoclic input[type=image]').after('<span>Le courriel entr&eacute; est invalide.</span>');
			return false;
		}
		$.post('/infolettre.php?subscribe=1',$('#frm-infoclic').serialize());
		$('#frm-infoclic input[type=image]').after('<span>Votre adresse a &eacute;t&eacute; ajout&eacute;e &agrave; l\'infoclic!</span>');
		setTimeout(function() { $('#bg').click(); },3000);
		return false;
	});
	
	var validMail = function(email) {
		var result = false
		var theStr = new String(email)
		var index = theStr.indexOf("@");
		if (index > 0) {
			var pindex = theStr.indexOf(".",index);
			if ((pindex > index+1) && (theStr.length > pindex+1)) result = true;
		}
		return result;
	}
	/*
	var tmBanner;
	var bannerSize = ($('#imageslider').hasClass('large')) ? 950 : 710;
	
	if ($('#slidernav').length) {
		$('#slidernav li a').click(function() {
			if ($(this).hasClass('active')) return false;
			$('#slidernav li a.active').removeClass('active');
			$(this).addClass('active');
			var left = $(this).parent().index()*-bannerSize;
			$('#sliderlist').stop().animate({left:left+'px'},500);
			try { clearTimeout(tmBanner); } catch(e) {}
			tmBanner = setTimeout(fnBanner,5000);
			return false;
		});
		var fnBanner = function() {
			var $next = ($('#slidernav li a.active').parent().next().length) ? $('#slidernav li a.active').parent().next().find('a') : $('#slidernav li:first a');
			$next.click();
		};
		tmBanner = setTimeout(fnBanner,5000);
	}
	*/
	
	// Banner anims..
	var tmBanner;
	//var bannerSize = ($('#imageslider').hasClass('large')) ? 950 : 710;
	var animTime = 800;
	if ($('#slidernav').length) {
		//alert('HELLO');
		$('#sliderlist li:not(:first)').hide();
		$('#slidernav li a').click(function() {
			if ($(this).hasClass('active')) return false;
			$('#slidernav li a.active').removeClass('active');
			$(this).addClass('active');
			/*var left = $(this).parent().index()*-bannerSize;
			$('#sliderlist').stop().animate({left:left+'px'},500);
			try { clearTimeout(tmBanner); } catch(e) {}
			tmBanner = setTimeout(fnBanner,5000);*/
			$('#sliderlist li:visible').fadeOut(animTime);
			var ident = $(this).parent().index();
			$('#sliderlist li:eq('+ident+')').fadeIn(animTime);
			try { clearTimeout(tmBanner); } catch(e) {}
			tmBanner = setTimeout(fnBanner,5000);
			return false;
		});
		var fnBanner = function() {
			var $next = ($('#slidernav li a.active').parent().next().length) ? $('#slidernav li a.active').parent().next().find('a') : $('#slidernav li:first a');
			$next.click();
		};
		tmBanner = setTimeout(fnBanner,5000);
	}
	
	// MARQUES POPULAIRES
	if ($('#popular-brands ul li').length) {
		// 
		var sens = -1;
		var animFunc = function() {
			if (sens == -1) $('#popular-brands ul').animate({left:(((totalWidth)-730)*sens)+'px'},50000,'linear',function() { animFunc(); });
			else $('#popular-brands ul').animate({left:'0px'},50000,'linear',function() { animFunc(); });
			sens = sens*-1;
		};
		var totalWidth = 0;
		$(window).load(function() {
			// Prend le width du UL...
			
			$('#popular-brands ul li').each(function() {
				totalWidth += $(this).outerWidth(true);
			});
			animFunc();
		});
	}
	
	// Wishlist / Comparer	
	var updateBodyClass = function() {
		var hasWishlist = false;
		var hasCompare = false;
		if ($('.wishcontent > ul > li').length) {
			hasWishlist = true;
		}
		if ($('.comparecontent > ul > li').length) {
			hasCompare = true;
		}
		$('body').removeClass('showboth').removeClass('wish').removeClass('compare');
		if (hasWishlist && hasCompare) $('body').addClass('showboth');
		else if (hasWishlist) $('body').addClass('wish');
		else if (hasCompare) $('body').addClass('compare');
		
		if (!hasWishlist && $('body').hasClass('wishactive')) $('body').removeClass('wishactive');
		if (!hasCompare && $('body').hasClass('compareractive')) $('body').removeClass('compareractive');
		if (hasWishlist) FB.XFBML.parse($(".wishcontent .fb-root").get(0));
	};
	$(window).load(function() {
		$('.wishcontent').load('/ajax/wishlist',updateBodyClass);
		$('.comparecontent').load('/ajax/compare',updateBodyClass);
	});
	
	// WISHLIST
	$('.add-item').click(function() {
		$('.wishcontent').load('/ajax/wishlist-add?id='+$(this).attr('rel'),updateBodyClass);
		return false;
	});
	$('.wl-delete').live('click',function() {
		$('.wishcontent').load('/ajax/wishlist-del?id='+$(this).attr('rel'),updateBodyClass);
		return false;
	});
	
	/*$('.share-wishlist').live('click',function() {
		
	});*/
	
	// COMPARE ITEMS
	$('.compare-item').click(function() {
		$('.comparecontent').load('/ajax/compare-add?id='+$(this).attr('rel'),updateBodyClass);
		return false;
	});
	$('.compare-delete').live('click',function() {
		$('.comparecontent').load('/ajax/compare-del?id='+$(this).attr('rel'),updateBodyClass);
		return false;
	});
	
	$('.compare-delete2').live('click',function() {
		$.get('/ajax/compare-del?type=url&id='+$(this).attr('rel'),function(data) { location.href=data; });
		return false;
	});
	
	// Show Compare popup...
	$('.compare-link').live('click',function() {
		window.open($(this).attr('href'),'compare',"width=1024,height=600,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no").focus();
		return false;
	});
	
	$('.imprimante').click(function() {
		window.print();
		return false;
	});
	
	$('#close-compare').click(function() {
		window.close();
		return false;
	});
	
	// ! INSCRIPTION MAILING LIST ! ! !
	$('#frm-contact').live('submit',function() {
		// VALIDATE 
		//$('#frm-contact input[type=image]').next().remove();
		if (!validMail($('#email').val())) {
			//$('#frm-infoclic input[type=image]').after('<span>Le courriel entr&eacute; est invalide.</span>');
			alert('Veuillez entrer un courriel valide');
			return false;
		}
		if ($('#txt-prenom').val()=='') {
			alert('Veuillez entrer votre prénom');
		}
		if ($('#txt-nom').val()=='') {
			alert('Veuillez entrer votre nom');
		}
		if ($('#txt-message').val()=='') {
			alert('Veuillez entrer votre message');
		}
		$.post('/contact/post',$('#frm-contact').serialize());
		$('#frm-contact input[type=image]').after('<span>Votre message a &eacute;t&eacute; envoy&eacute;!</span>');
		setTimeout(function() { $('#bg').click(); },3000);
		return false;
	});
	
	$('#frm-share').live('submit',function() {
		// VALIDATE 
		//$('#frm-contact input[type=image]').next().remove();
		if (!validMail($('#email').val())) {
			//$('#frm-infoclic input[type=image]').after('<span>Le courriel entr&eacute; est invalide.</span>');
			alert('Veuillez entrer un courriel valide');
			return false;
		}
		if ($('#txt-votrenom').val()=='') {
			alert('Veuillez entrer votre nom');
		}
		if ($('#txt-nom').val()=='') {
			alert('Veuillez entrer le nom de la personne.');
		}
		
		$.post('/sharing/post',$('#frm-share').serialize());
		$('#frm-share input[type=image]').after('<span>Votre message a &eacute;t&eacute; envoy&eacute;!</span>');
		setTimeout(function() { $('#bg').click(); },3000);
		return false;
	});
	
	if ($.fn.fancybox) { 
		$('.fb-tendances').fancybox({
			titlePosition:'inside',
			titleFormat:function(title) {
				return '<div id="barre-top"><h2>'+title+'</h2</div>';
			},
			overlayOpacity:.7,
			overlayColor:'#000'
		});
	}
	
	//alert('WTF');
	$('#convertisseur input').bind('keyup',function() {
		//console.log('triggered');
		var $elm = $(this);
		if (isNaN(parseFloat($(this).val()))) return;
		if ($(this).attr('id')=='base') {
			var baseval = $(this).val();
			$('#convertisseur input:not(#base)').each(function() {
				if ($(this) == $elm) return;
				var formule = $(this).data('formule');
				try {
					if (formule.indexOf('/') > -1) {
						formule = formule.replace('/','*');
					}
					else {
						formule = formule.replace('*','/');
					}
					console.log($(this).attr('id')+':'+'var laval = '+baseval+formule+';');
					eval('var laval = '+baseval+formule+';');
					$(this).val(round(laval,8));
				}
				catch(e) { }
			});
		}
		else { 
			var baseval;
			var formule = $(this).data('formule');
			try {
				eval('baseval = '+$(this).val()+formule+';');
				$('#base').val(baseval).keyup();
			} catch(e) { return; }
			
		}
	});
	

	/*$('#ml').change(function() {
		if ($(this).val() == 'biere') $(this).val('341').keyup();
		if ($(this).val() == 341) {
			//$('body').append('<audio autoplay="autoplay" controls="controls" src="/images/form/open.ogg"><source src="/images/form/open.mp3" /><source src="/images/form/open.ogg" /></audio>');
		}
	});*/
	try {
		$('.add-item').qtip({
		   content: 'Ajouter à ma liste de souhaits', // Set the tooltip content to the current corner
		   show: 'mouseover',
		   hide: 'mouseout',
		   style: {
			  border: {
				 width: 2,
				 radius: 3
			  },
			  width:160,
			  padding: 2, 
			  textAlign: 'center',
			  tip: true, // Give it a speech bubble tip with automatic corner detection
			  name: 'dark' // Style it according to the preset 'cream' style
		   },
			position: {
			  corner: {
				 target: 'bottomMiddle',
				 tooltip: 'topMiddle'
			  }
		   }
		});

		$('.compare-item').qtip({
		   content: 'Ajouter au comparateur', // Set the tooltip content to the current corner
		   show: 'mouseover',
		   hide: 'mouseout',
		   style: {
			  border: {
				 width: 2,
				 radius: 3
			  },
			  padding: 2, 
			  textAlign: 'center',
			  tip: true, // Give it a speech bubble tip with automatic corner detection
			  name: 'dark' // Style it according to the preset 'cream' style
		   },
			position: {
			  corner: {
				 target: 'bottomMiddle',
				 tooltip: 'topMiddle'
			  }
		   }
		});
	} catch(e) {  }
});


function round (value, precision, mode) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Onno Marsman
    // +      input by: Greenseed
    // +    revised by: T.Wild
    // +      input by: meo
    // +      input by: William
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Josep Sanz (http://www.ws3.es/)
    // +    revised by: RafaÅ‚ Kukawski (http://blog.kukawski.pl/)
    // %        note 1: Great work. Ideas for improvement:
    // %        note 1:  - code more compliant with developer guidelines
    // %        note 1:  - for implementing PHP constant arguments look at
    // %        note 1:  the pathinfo() function, it offers the greatest
    // %        note 1:  flexibility & compatibility possible
    // *     example 1: round(1241757, -3);
    // *     returns 1: 1242000
    // *     example 2: round(3.6);
    // *     returns 2: 4
    // *     example 3: round(2.835, 2);
    // *     returns 3: 2.84
    // *     example 4: round(1.1749999999999, 2);
    // *     returns 4: 1.17
    // *     example 5: round(58551.799999999996, 2);
    // *     returns 5: 58551.8
    var m, f, isHalf, sgn; // helper variables
    precision |= 0; // making sure precision is integer
    m = Math.pow(10, precision);
    value *= m;
    sgn = (value > 0) | -(value < 0); // sign of the number
    isHalf = value % 1 === 0.5 * sgn;
    f = Math.floor(value);

    if (isHalf) {
        switch (mode) {
        case 'PHP_ROUND_HALF_DOWN':
            value = f + (sgn < 0); // rounds .5 toward zero
            break;
        case 'PHP_ROUND_HALF_EVEN':
            value = f + (f % 2 * sgn); // rouds .5 towards the next even integer
            break;
        case 'PHP_ROUND_HALF_ODD':
            value = f + !(f % 2); // rounds .5 towards the next odd integer
            break;
        default:
            value = f + (sgn > 0); // rounds .5 away from zero
        }
    }

    return (isHalf ? value : Math.round(value)) / m;
}
