// JavaScript Document

/* -------------------------------------------------------------- 
a17.ui.loader.js 
sustainable a17 js
Copyright 2010 Nobleskine @ AREA 17

Lightweight js preloader. 
- Use it to dynamically load "user interaction" oriented javascript at the bottom of the page.
- Don't use it for "css-fix" oriented javascript (to avoid any css jump)

This file relies :
- jquery.require.js
- jquery-1.4.2.min.js

Version 1.0.1 Alpha (01/02/2010) :
	
To minify :
java -jar yuicompressor-2.4.2.jar js/a17.flowplayer-1.0.2.js -o js/a17.flowplayer-1.0.2.min.js
	
-------------------------------------------------------------- */
/*
* jQuery.use - The jQuery plugin manager
* Copyright (c) 2009 Aaron Heckmann
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function(e,n){var B={},d={LOADED:3,LOADING:2,UNLOADED:1},x="1.0.0",C=false,v=false,o=false,E=document,t={},z=E.getElementsByTagName("head")[0]||E.documentElement,F=E.createElement("div"),j="*",w="ui-lightness",r=false,u=n.toString,A=function(H,M,K){if(e.use.lib_root===false){throw"jQuery.use.lib_root has not been set. Please set this to your libray's root before continuing."}if(e.use.service&&e.use.serviceURI===false){throw"jQuery.use.serviceURI has not been set."}D();var L=h(y(H)),G=0,p=function(){if(++G===2&&M){setTimeout(function(){if(!m(L.provides)){return setTimeout(arguments.callee,30)}M.call(K||window,jQuery);a(L.preload)},30)}};if(0===L.js.length+L.css.length){M&&M();return}function I(N){return N.isPkg&&(N.url.indexOf("http")==-1||N.url.indexOf(v)===0)}function J(W,U,O){var R=W.length,T,N,P="",X=[],V=e.use.service&&!O,S=f(),Q=100;if(R===0){p();return}T=W.splice(0,1)[0];N=c(T.url.toLowerCase(),I(T),!V);if(t.hasOwnProperty(N)){if(t[N].status===d.LOADING){t[N].queue.push(function(){J(W,U,O)})}else{J(W,U,O)}}else{while(V&&I(T)){P+="d"+(Q++)+"="+T.url+"&";N=c(T.url.toLowerCase(),true);t[N]={status:d.LOADING,queue:[]};X[X.length]=N;T=W.length&&I(W[0])&&W.splice(0,1)[0]}if(P.length>0){P=P.substring(0,P.length-1);U(S+P,function(){for(var Z=0,Y=X.length;Z<Y;Z++){b(X[Z])}J(W,U,O)})}else{U(N,function(){J(W,U,O)})}}}J(L.css,k,!e.use.combineCSS);J(L.js,l);return jQuery},a=function(p){if(p.length){setTimeout(function(){for(var I=0,H=p.length,G=e.use.lib_root;I<H;I++){(new Image()).src=G+p[I]}},1)}},m=function(M){var K=true,H=0,p=M.length,L,J,I,G;while(K&&H<p){L=M[H].split(".");J=L.length;I=window;G=0;for(;G<J;G++){if(!(L[G] in I)){K=false;break}I=I[L[G]]}H++}return K},k=function(H,p){t[H]={status:d.LOADING,queue:[]};var G=E.createElement("link");G.type="text/css";G.rel="stylesheet";G.href=H;G.media="screen";z.appendChild(G);b(H,p)},l=function(G,p){t[G]={status:d.LOADING,queue:[]};e.ajax({type:"GET",url:G,cache:true,dataType:"script",success:function(){b(G,p)}})},b=function(K,G){var I=t[K],J=I.queue,p=J.length,H=0;I.status=d.LOADED;G&&G();for(;H<p;H++){J[H]()}I.queue=[]},f=function(){var p=e.use.serviceURI||"";return p+(p.indexOf("?")>-1?"&":"?")},y=function(R,G){var Q,M,L=[],p=[],S=[],H=/\.css/i,K=0,T,J,O=[],P=[],N=!!G,I=e.use.uiTheme;if(u.call(R)==="[object Array]"){Q=R}else{if(B.hasOwnProperty(R)){Q=(B[R].requires||[]).concat(B[R].file||[]);P=B[R].provides||[];S=B[R].preload||[];N=true}else{Q=[R]}}for(M=Q.length;K<M;K++){J=Q[K];if(""===J){continue}if(B.hasOwnProperty(J)){T=y(J,N);p=p.concat(T.js);L=L.concat(T.css);P=P.concat(T.provides);S=S.concat(T.preload)}else{if(H.test(J)){L.push({url:J.replace("{THEME}",I),isPkg:N})}else{p.push({url:J,isPkg:N})}}}return{js:p,css:L,provides:P,preload:S}},h=function(p){p.js=q(p.js);p.css=q(p.css);p.preload=q(p.preload);return p},q=function(K){var J=0,p=K.length,G={},H=[],L,I;for(;J<p;J++){L=K[J];I=L.url?L.url:L;if(!G[I]){G[I]=1;H[H.length]=L}}return H},D=function(){var H=s(),G=H.length+1,p;while(--G){p=H[G-1].toLowerCase();if(!t.hasOwnProperty(p)){t[p]={status:d.LOADED}}}return t},c=function(G,H,p){if(H){return(p?e.use.lib_root:j)+G}F.innerHTML='<a href="'+G+'"></a>';return F.firstChild.href},s=function(){var G=new RegExp(f().replace("?","\\?"),"i"),p=function(H){var I=c,J=e.use.service;return function(){if(J&&G.test(this[H])){return(j+this[H].replace(G,"").split("&").join("&"+j)).split("&")}return I(this[H])}};return e("script[src]").map(p("src")).get().concat(e("link[href][type=text/css]").map(p("href")).get())},g=function(G,I){if(!G){return e}if(u.call(G)==="[object Array]"){for(var H=0,p=G.length;H<p;H++){g(G[H],I)}return e}if(B.hasOwnProperty(G.name)&&!I){throw"Package name already taken."}if(G.file){G.file=e.makeArray(G.file)}if(G.requires){G.requires=e.makeArray(G.requires)}if(G.provides){G.provides=e.makeArray(G.provides)}B[G.name]=G;delete B[G.name].name;return e},i=function(p){return p?B[p]:B};e.use=A;e.use.add=g;e.use.modules=i;e.use.VERSION=x;e.use.combineCSS=r;e.use.uiTheme=w;e.use.serviceURI=v;e.use.service=o;e.use.lib_root=C})(jQuery,Object.prototype);
$.use.lib_root = "";

var minify = false;

// Scripts variables
var script_path = '/assets/js';
var script_min = '';
// Minify if needed
if (minify) script_min = '.min';
var script_gallery = script_path + '/a17.ui.gallery' + script_min + '.js',
	script_jscroll = script_path + '/ext/jquery.jscroll' + script_min + '.js',
	script_flowplayer = script_path + '/vid/a17.flowplayer-1.0.2' + script_min + '.js',
	script_endless = script_path + '/jquery.endless-scroll-1.3' + '.js',
	script_autocolumn = script_path + '/ext/autocolumn' + '.js';
// Browser check
var isIE6 = false;
var categorySlug = "all";

var L = false;
var ID = 0;

/* -------------------------------------------------------------- 
ON DOM READY
-------------------------------------------------------------- */
$(document).ready(function(){
	
	runOnDOMready();
	
	
});


function runOnDOMready() {
	
	common();
	productsFilter() // used for products filter
	avh();
	//GALLERY DETECTION
	if ($('#gallery').length > 0) {
		
		if ($('#gallery').hasClass('gallery-feature')) $('#newsletter').addClass('active');
		
		
		
		if ($('#gallery-thumbnails')[0])  {
			if ($('#gallery-thumbnails').children('li').children('a.vid').length > 0)  {
				jQuery.use.add({
				    name: 'gallery-jscroll-flow',
				    file: [
				        script_gallery
				    ],
					requires: [script_jscroll, script_flowplayer]
				}).use('gallery-jscroll-flow', function ($) {
					//console.log('My gallery-jscroll-flow and all required dependencies are ready!');
				});
			} else {
				jQuery.use.add({
				    name: 'gallery-jscroll',
				    file: [
				        script_gallery
				    ],
					requires: [
						script_jscroll
					]
				}).use('gallery-jscroll', function ($) {
				    //console.log('My gallery-jscroll and all required dependencies are ready!');
				});
			}
		} else  {
			jQuery.use.add({
			    name: 'gallery',
			    file: [
			        script_gallery
			    ]
			}).use('gallery', function ($) {
			    //console.log('My gallery is ready!');
			});
		} 
		
		

	}
	
	// NEWS DETECTION
	if ($('.two-columns').length > 0) {
		jQuery.use.add({
		    name: 'autocolumn',
		    file: [
		        script_autocolumn
		    ]
		}).use('autocolumn', function ($) {
		    autocolumn();
		});

	}


    var endlessRunning = false;
    var productsAllLoaded = false;
	// PRODUCTS/ARCHITECTURE ITEMS DETECTION
	if ($('#products').length > 0) {
		var products = $('#products');
		
		var endlessLoader = $('<div/>').attr('id', 'endlessLoader');
		var endlessLoaderText = $('<span/>').text('loading');
		endlessLoader.append(endlessLoaderText);
		
		jQuery.use.add({
		    name: 'endless',
		    file: [
		    	script_endless
		    ]
		}).use('endless', function ($) {
			$('#newsletter, .footer').hide();
			products.endlessScroll({
		    	bottomPixels: 150,
		    	fireOnce: true,
				fireDelay: 10,
		    	callback: function(p){
		      		if (!endlessRunning && !productsAllLoaded) {
		        		if ($('#endlessLoader').length > 0) $('#endlessLoader').show();
						else $('.page').after(endlessLoader);
						endlessRunning = true;
		  		        var offset = products.children().size();
		  		        var pathname = window.location.pathname;
		  		        var url = pathname + "?offset=" + offset;
		    			if (categorySlug != "") url = url + "&category=" + categorySlug;
		    		    $.post(url,"", function (response){
		    				if (response.length > 33) { 
								products.append(response);
								imagesLoader();
								$('#endlessLoader').fadeOut();
							} else {
								$('#newsletter, .footer').show();
								productsAllLoaded = true;
								$('#endlessLoader').remove();
							}
		    		    	endlessRunning = false;
		    		    });
  		      		} else {
  		      		}
		      	}
		  	});
		});
	}
	
	if ($('.product')[0]) $('.page').addClass('page-detail');

}

/* -------------------------------------------------------------- 
ON PAGE READY
-------------------------------------------------------------- */
$(function($) {
	imagesLoader();
});


/* -------------------------------------------------------------- 
Sitewide functions
-------------------------------------------------------------- */

function common() {
	
	$('#breadcrumb').find('li:first-child').addClass('first');
	$('#breadcrumb').find('li:last-child').addClass('last');
	$('#news').find('.size804_170:first-child').addClass('first');
	$('.inactive > a').bind({
		click: function(e) {
			e.preventDefault();
		}
	});
	
	
	
	myselection();
	browserCheck();
	searchBar();
	searchBarL()
	newsletter();
	customDropDown();
	rollovers();
	news();
	ouiForm();
	login();
	searchResults();
}


/* Sitewide / browser check 
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function browserCheck() {
	var htmlbody = $('body');
	if (htmlbody.hasClass('ie6')) {
		isIE6 = true;
	}
}

/* Sitewide / images loading
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function imagesLoader(order) {
	if ($('.a17-ui-imgloader')[0]) {

		var imagesHolder = $('.a17-ui-imgloader').find('.imgHolder'),
			images = imagesHolder.children('img'),
			imagesNb = images.length;
		
		if (imagesNb == 0) return false;

		function loadImage(index, max) {
			if (index<max) {
				var _imageHolder = imagesHolder.eq(index),
					_image = _imageHolder.children('img'); 
				_imageHolder.addClass('a17-ui-imgloading');
				_image.onImagesLoaded(function(_this) {
					// show image
					$(_this).fadeIn(function() {
						$(_this).parent('.a17-ui-imgloading').removeClass('a17-ui-imgloading');
					});
					// show entry-title
					$(_this).parents('.entry').find('*').animate({
						opacity: 1
					}, 200);
					// load next image
					loadImage(index+1, max);
				});
			}
		}
		
		function loadImages() {
			images.onImagesLoaded(function(_this) {
				$(_this).parent('.imgHolder').addClass('a17-ui-imgloading');
				$(_this).fadeIn(function() {
					$(_this).parent('.a17-ui-imgloading').removeClass('a17-ui-imgloading');
				});
				$(_this).parents('.entry').find('*').animate({
					opacity: 1
				}, 500);
			});
		}
		
		switch (order) {
			case 'all':
				loadImages();
				break;
			default :
				loadImage(0, imagesNb);
				break;
		}
	}
}

/* Sitewide / myselection 
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function myselection() {
	

	if ($('#myselectionModule')[0]) {
		
		var wrapper = $('#myselectionModule'),
			info = wrapper.children('#myselection_info'),
			count = info.children('.myselection_count'),
			label = info.children('.myselection_label'),
			logout = info.children('.myselection_logout'),
			action = $('#myselection_action'),
			isExpanded = false;
			//threshold = action.offset().top;
		
		//label.hide();
		
		if (wrapper.hasClass('expanded')) isExpanded = true;
		if (wrapper.hasClass('loggedin')) L = true;
		
		
		
		function open(effect) {
			
			if (effect == 'animate') {
				info.stop().animate({
					width: '190px'
				}, 200, function() {
					info.addClass('expanded'); /* to avoid seeing the label broken in 2 lines on animation load */
					//label.show();
				});
				
			}

			else {
				info.addClass('fixed');
				info.stop().css('width', '190px');
			}
		}
		
		function close() {
			//label.hide();
			info.removeClass('expanded'); /* to avoid seeing the label broken in 2 lines on animation ending */
			info.stop().animate({
				width: '30px'
			}, 200);
		}
		
		info.bind({
			mouseenter: function() {
				if (!$('#myselection-products')[0])
				open('animate');
			},
			mouseleave: function() {
				if (!$('#myselection-products')[0])
				close();
			}
		});
		
		
		if ($('#myselection-products')[0]) {
			open('default');
		}
		
	}
	
	if ($('.entry-selection')[0]) {
		
		var entryselection = $('.entry-selection');
		
		entryselection.bind({
			click: function(e) {
				e.preventDefault();
				
				if (L) {
					// if the item has been already added, remove it
					if ($(this).hasClass('entry-selected')) {
						// UPDATE THE NUMBER OF MY SELECTIONS AFTER AJAX RESPONSE
						itemid = $(this).attr('rel');
	    				$.get("/myselection/removeitem/"+itemid, function(data){
	    			  		updateFolderCount(data);
	    				});
						// if we are in my selection page, remove it from the product list
						if ($('#myselection-products')[0]) {
							var parent = $(this).parent().parent();
							parent.animate({width:0}, 200, function() {
								$(this).remove();
							});
						} 
						// else remve the class entry-selected (in my selection page, we don't need to do it cos we actually remove it from the âge)
						else {
							$(this).removeClass('entry-selected');
						}

					}
					// else add it
					else {
						$(this).addClass('entry-selected');
						// UPDATE THE NUMBER OF MY SELECTIONS AFTER AJAX RESPONSE
						itemid = $(this).attr('rel');

	    			$.get("/myselection/additem/"+itemid, function(data){
	    			  updateFolderCount(data);
	    			});
					}
				} else {
					ID = $(this).attr('rel');
					$('#login').a17_ui_showhide('fade', 'fast');
					$('#login').a17_ui_loginResetForm();
				}
			}
		});
		
		$('#loginTrigger').bind({
			click: function(e) {
				e.preventDefault();
				$('#login').a17_ui_showhide('fade', 'fast');
				$('#login').a17_ui_loginResetForm();
			}
		});
	}

function updateFolderCount(response) {
	// TODO
	var mySplitResult = response.split(":");
	var code = mySplitResult[0];
	var count = mySplitResult[1];
	var text = $('.myselection_count');
	text.html(count);
	
	if ($('.countnb')[0]) {
		var isFR = false;
		if ($('body').hasClass('fr')) isFR = true;
		
		var myselection_count = $('.countnb');
		myselection_count.html(count);
		var myselection_text = $('.countlabel');

		var projects_label = 'projects';
		if (isFR) projects_label = 'projets';
		

		if (count == 0) {
			myselection_count.parents('ul').remove();
		}
		else if (count > 1) myselection_text.text(projects_label);
		else myselection_text.text(myselection_text.text().replace('s', ''));
		
		if (count == 1 && isFR) $('.count').text($('.count').text().replace('sélectionnés', 'sélectionné')); 

	}
}

}

/* Sitewide / rollovers 
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function rollovers() {
	
	if ($('.entry')[0]) {
		
		// .delegate() way (only with jQuery 1.4.2)
		var entry = '.entry > a';
		$('body').delegate(entry, 'mouseenter', function(){
			$(this).parent().addClass('entry-hover');
		});
		$('body').delegate(entry, 'mouseleave', function(){
			$(this).parent().removeClass('entry-hover');
		});
		
	}
	
}


/* Sitewide / autocolumn 
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function autocolumn() {
	var content = $('.two-columns');
	content.columnize({ width: 299}).animate({
		opacity: '1'
	}, 400);
}


/* Sitewide / about 
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function avh() {
	if ($('#aboutvisionhistory')[0]) {
		
		var avh = $('#aboutvisionhistory'),
			mask = avh.children('.line'),
			about = $('.trigger_about'),
			vision = $('.trigger_vision'),
			history = $('.trigger_history'),
			
			aboutL = 0,
			visionL = '-804px',
			historyL = '-1684px',
			
			aboutPanel = $('#panel_about'),
			visionPanel = $('#panel_vision'),
			historyPanel = $('#panel_history'),
			
			units = historyPanel.find('.unit'),
			visionLegend = visionPanel.children('.size170').children('.legend'),
			
			breadcrumb = $('#breadcrumb'),
			loc = window.location.href;
			currentPanel = loc.substring(loc.indexOf('#') + 1);

		/* History Panel */
		if (units.size() > 0) {
			for (var i=-1; ++i<units.size();) {
				if (units.eq(i).offset().left == historyPanel.offset().left) units.eq(i).removeClass('unitYear').addClass('unitBorder');
			}
		}
		var historyLegend = historyPanel.find('.unitBorder').find('.imgHolder').children('.legend');
		
		function slideTo(pos, animation, elem) {
			
			var klass = elem.replace('.trigger_', '');
			
			if (animation) {
				
				mask.animate({
					marginLeft: pos
				}, 350, function() {
					avh.attr('class', '').addClass(klass);
					if ($(window).scrollTop() > $('#breadcrumb').offset().top) {
						$('html, body').animate({
							scrollTop: 0
						}, 350);
					}
				});
				
				switch(klass) {
					case 'vision': 
						visionLegend.animate({
							opacity: 0
						}, 400);
						
						historyLegend.width(100);
						
						break;
					case 'about': 
						visionLegend.animate({
							opacity: 1
						}, 400);
						historyLegend.width('auto');
						break;
					case 'history': 
						visionLegend.animate({
							opacity: 0
						}, 400);
						historyLegend.width('auto');
						break;
				}
			}
			else {
				avh.attr('class', '').addClass(klass);
				mask.css('marginLeft', pos);
			}
		}
		
		function updateCurrent(elem) {
			breadcrumb.children('.current').removeClass('current');
			breadcrumb.find(elem).parent().addClass('current');
		}
		
		
		switch(currentPanel) {
			case 'about':
				updateCurrent('.trigger_about');
				slideTo(aboutL, false, '.trigger_about');
				break;
			case 'vision':
				updateCurrent('.trigger_vision');
				slideTo(visionL, false, '.trigger_vision');
				break;
			case 'history':
				updateCurrent('.trigger_history');
				slideTo(historyL, false, '.trigger_history');
				break;
		}
			
		about.bind({
			click: function(e) {
				updateCurrent('.trigger_about');
				slideTo(aboutL, true, '.trigger_about' );
			}
		});
		
		vision.bind({
			click: function(e) {
				updateCurrent('.trigger_vision');
				slideTo(visionL, true, '.trigger_vision');
			}
		});
		
		history.bind({
			click: function(e) {
				updateCurrent('.trigger_history');
				slideTo(historyL, true, '.trigger_history');
			}
		});
		
		/* Vision Panel */
		visionPanel.find('.imgHolder').delay(600).animate({
			opacity: 1
		}, 800);


		

	}
	
}

/* Sitewide / news 
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function news() {
	if ($('.imgHolder').length > 0) {
		var imgH = $('.imgHolder'),
			parentW = imgH.parents().width();
		for (var i=-1; ++i<imgH.length;) {
			var img = imgH.eq(i).children('img'),
				imgW = img.width(),
				legend = imgH.eq(i).children('.legend'),
				legendW = legend.width();
			if ( (imgW * 100 / parentW) >= (100 / 3 * 2) ) imgH.eq(i).removeClass('fL');
			else if (legendW > imgW) legend.width(imgW);
			//console.log(parentW + ' - ' + imgW + '-' + (imgW * 100 / parentW));
			
		}
	}
	if ($('.size170').children('.legend_current').length > 0) {
		var legends = $('.size170').children('.legend_current');
		if (legends.size() > 0) {
			legends.each(function(i) {
				if ($(this).text() != '') $(this).css('display', 'block');
			})
		}
	}
}

/* Sitewide / newsletter 
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function newsletter() {
	
	if ($('#newsletter')[0]) {
	
		var newsletter = $('#newsletter');
		var newsletterForm = newsletter.find('form');
		var newsletterInput = $('#subscribe_email');
		var newsletterSubmit = $('#subscribe_submit');
		var newsletterTextDefault = $('#subscribe_email').val(); 
		
		function isNewsletterEmpty() {
			if (newsletterInput.val() == '' || newsletterInput.val() == newsletterTextDefault) { return true; } else {return false; } 
		}

		if (newsletterInput.val() != newsletterTextDefault) newsletterForm.addClass('searchFor');
		
		newsletterInput.bind({
			focus: function(e) {
				if ($(e.target).val() == newsletterTextDefault) {
					$(e.target).val('');
					newsletterForm.addClass('searchFor');
				}
			},
			blur: function(e) {
				if ($(e.target).val() == '') {
					$(e.target).val(newsletterTextDefault);
					newsletterForm.removeClass('searchFor error');
				}
			}
		});
		
		newsletterForm.a17_validate_subscribe(newsletterTextDefault);
	
	}
}


/* Sitewide / ouiForms 
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function ouiForm() {
	if ($('.ouiForm')[0]) {
		var form = $('.ouiForm'),
			inputs = form.find('input[type="text"], textarea'),
			input1 = inputs.eq(0);
			submit = form.find('input[type="submit"]');
		
		inputs.bind({
			focus: function(e) {
				$(this).parent('.input_holder').addClass('input_focus');
			},
			blur: function(e) {
				$(this).parent('.input_holder').removeClass('input_focus');
			}
		});
		
		submit.bind({
			mouseenter :function() { $(this).addClass('btn-hover'); },
			mouseleave: function() { $(this).removeClass('btn-hover'); }
		})
		
		if (input1.val() == '') input1.focus();
	}
}


/* Sitewide / searchBar 
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function searchBar() {
	
	if ($('#searchBar')[0]) {
		
		var searchBar = $('#searchBar');
		var searchForm = searchBar.children('form');
		var searchInput = $('#search');
		var searchSubmit = $('#search-btn');
		var searchText = $('#search').val();
		
		function isSearchEmpty() {
			if (searchInput.val() == '' || searchInput.val() == searchText) { return true; } else {return false; } 
		}
		
		if (searchInput.val() != searchText) searchForm.addClass('searchFor');
		
		// on page load, expand the search if there's a search pattern. 
		// Ideally, this should be handled from the BE to prevent jumping on page load
		// if (!isSearchEmpty()) {
		// 	searchBar.addClass('cSB-expanded cSB-expanded-css');
		// }
		if (!isSearchEmpty()) {
			searchInput.val(''); // autoreset all the time
		}
		
		/* just in case we don't apply autohide by default */
		if (!searchBar.hasClass('cSB-autohide')) {
			searchBar.addClass('cSB-expanded cSB-expanded-css');
		}
		
		searchInput.bind({
			focus: function(e) {
				if ($(e.target).val() == searchText) {
					$(e.target).val('');
					searchForm.addClass('searchFor');
				}
			},
			blur: function(e) {
				if ($(e.target).val() == '') {
					$(e.target).val(searchText);
					searchForm.removeClass('searchFor');
				}
			}
		});
		

		searchSubmit.bind({
			mouseenter: function() {
				$(this).addClass('submit-hover');
			},
			mouseleave: function() {
				$(this).removeClass('submit-hover');
			},
			click: function(e) {
				/* expand the search bar */
				if (!searchBar.hasClass('cSB-expanded')) {
					e.preventDefault();
					
					searchBar.addClass('cSB-expanded');
					searchInput.focus();
					
					if (!isIE6) {
						/* animates the expand */
						searchInput.animate({
							width: '213px',
							paddingLeft: '9px',
							paddingRight: '26px',
							marginLeft: '6px'
						}, 200);
					} else {
						searchInput.addClass('cSB-expanded-css');
					}

				} 
				/* once expanded, launch search */
				else {
					if (isSearchEmpty()) {
						/* Dont't submit the form */
						e.preventDefault();
						//console.log('already expanded but search is empty');
					} else {
						$(this).addClass('submitted');
						//console.log('already expanded. Search not empty. Launching search');
					}
					
				}
			}
		});
		
		/* autohide */
		if (searchBar.hasClass('cSB-autohide')) {

		}
		
	}
}

/* Sitewide / searchBarL 
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function searchBarL() {
	
	if ($('#searchBarL')[0]) {
		
		var searchBar = $('#searchBarL');
		var searchForm = searchBar.children('form');
		var searchInput = $('#searchL');
		var searchSubmit = $('#searchL-btn');
		var searchText = $('#searchL').val();
		
		function isSearchEmpty() {
			if (searchInput.val() == '' || searchInput.val() == searchText) { return true; } else {return false; } 
		}
		
		if (searchInput.val() != searchText) searchForm.addClass('searchFor');
		
		searchInput.bind({
			focus: function(e) {
				if ($(e.target).val() == searchText) {
					$(e.target).val('');
					searchForm.addClass('searchFor');
				}
			},
			blur: function(e) {
				if ($(e.target).val() == '') {
					$(e.target).val(searchText);
					searchForm.removeClass('searchFor');
				}
			}
		});
		

		searchSubmit.bind({
			mouseenter: function() {
				$(this).addClass('sb-hover');
			},
			mouseleave: function() {
				$(this).removeClass('sb-hover');
			},
			click: function(e) {
				if (isSearchEmpty()) {
					/* Dont't submit the form */
					e.preventDefault();
					//console.log('already expanded but search is empty');
				} else {
					$(this).addClass('submitted');
					//console.log('already expanded. Search not empty. Launching search');
				}
				
			}
		});
		
	}
}

/* Sitewide / customDropDown
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function customDropDown() {
	
	function hideAll() {
		$('.customDropDown').removeClass('dd-open');
		
	}
	
	$("div.customDropDown").each(function (i) {
		
		/* container */
		var self = $(this);
		self.bind({
			mouseenter: function() {
				self.addClass('dd-hover');
			}, 
			mouseleave: function() {
				self.removeClass('dd-hover');
			}
		});
		
		/* container input and container options */
		var ddInput = $(this).children()[0];
		var ddDiv = $(this).children()[1];
		ddInput = $(ddInput);
		ddDiv = $(ddDiv);
		
		ddDiv.children('ul').children('li:last-child').addClass('last');
		
		/* Just to make sure it's hidden on page load */
		ddDiv.hide();
		
		/* Bind events */
		ddInput.bind({
			click: function() {	
				toggleDD();
			}
		});
		
		/* Show/Hide the options */
		function toggleDD() {
			if (self.hasClass('dd-open')) {
				self.removeClass('dd-open');
			} else {
				hideAll(); // making sure to hide possible other existing customDropDown modules 
				self.addClass('dd-open');
			}
			
		}

		/* Click anywhere else on the page closes the customDropDown */
		$(document).click(
			function (e) {
				if(!$(e.target).parents().hasClass('customDropDown')) {
					ddDiv.hide();
					self.removeClass('dd-open');
				}
			}
		);
		
	});
}


/* Sitewide / products filter
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function productsFilter() {
	if ($('#categoriesToolbar')[0] && $('.products')[0]) {
		
		var filterBar = $('#categoriesToolbar');
		var filterLink = filterBar.children('li').children('a');
		
		function updateCurrent(elem) {
			filterBar.children('li.current').removeClass('current');
			elem.parent('li').addClass('current');
		}
		
		filterLink.bind({
			click: function(e) {
	   			e.preventDefault(); 
	
				updateCurrent($(this));
	
				if (categorySlug != "all") {
					$("#category-"+categorySlug).removeClass('current');
					// remove the last item from the breadcrumb
					$("#breadcrumb").children().last().remove();
				}

				categorySlug = $(this).parent().addClass('current');
				categorySlug = $(this).attr('href');

				var offset = 0;
	      		var pathname = window.location.pathname;
	      		var url = pathname + "?offset=" + offset;
	      		url = url + "&category=" + categorySlug;

				$.post(url,"",
	            	function (response){
		           		$('#products').empty();
		            	$('#products').append(response);
		            } 
			    );
				
				$("#breadcrumb").append('<li><span>'+$(this).attr('title')+'</span></li>');
				
				$('#breadcrumb').find('li').removeClass('first last');
				$('#breadcrumb').find('li:first-child').addClass('first');
				$('#breadcrumb').find('li:last-child').addClass('last');
				
			    
			}
		});
		
	}
}

/* Sitewide / searchresults
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function searchResults() {
	if ($('#searchresults')[0]) {
		$('.products_collection').find('.unit:last-child').addClass('last');
	}
}

/* Sitewide / login
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
var errorLoginText = 'Your email address is not valid.';
var loginText = $('.login_instructions').text();

function login() {
	
	if ($('body').hasClass('fr')) {
		errorLoginText = 'Adresse email invalide.'
	}
	
	/* Turn #login into a lightbox */
	$('#login').a17_ui_lightbox('fade', 200);
	/* Turn xx into the lightbox trigger */
	$('#login_form').a17_validate_login(loginText);
	
}


/* External/homemade plugins
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
jQuery.fn.onImagesLoaded = function(_cb) { 
  return this.each(function() {
 
    var $imgs = (this.tagName.toLowerCase()==='img')?$(this):$('img',this),
        _cont = this,
            i = 0,
    _done=function() {
      if( typeof _cb === 'function' ) _cb(_cont);
    };
 
    if( $imgs.length ) {
      $imgs.each(function() {
        var _img = this,
        _checki=function(e) {
          if((_img.complete) || (_img.readyState=='complete'&&e.type=='readystatechange') )
          {
            if( ++i===$imgs.length ) _done();
          }
          else if( _img.readyState === undefined ) // dont for IE
          {
            $(_img).attr('src',$(_img).attr('src')); // re-fire load event
          }
        }; // _checki \\
 
        $(_img).bind('load readystatechange', function(e){_checki(e);});
        _checki({type:'readystatechange'}); // bind to 'load' event...
      });
    } else _done();
  });
};

jQuery.fn.vAlign = function() {
	return this.each(function(i){
		var h = $(this).height();
		var oh = $(this).outerHeight();
		var mt = (h + (oh - h)) / 2;	
		$(this).css({'margin-top': '-' + mt + 'px', 'top': '50%', 'position': 'absolute'});
	});	
};


jQuery.fn.hAlign = function() {
	return this.each(function(i){
		var w = $(this).width();
		var ow = $(this).outerWidth();	
		var ml = (w + (ow - w)) / 2;
		$(this).css({'margin-left': '-' + ml + 'px', 'left': '50%', 'position': 'absolute'});
	});
};


jQuery.fn.vhAlign = function() {
	return this.each(function(i){
		/* horizontal alignment */
		var w = $(this).width();
		var ow = $(this).outerWidth();	
		var ml = (w + (ow - w)) / 2;
		
		/* vertical alignment */
		var h = $(window).height();
		var h2 = parseFloat($(this).height());
		var windowTopOffset = $(window).scrollTop();
		if (h < h2) {
			windowTopOffset = windowTopOffset;
		} else {
			windowTopOffset = windowTopOffset + ((h-h2)/2);
		}
			
		$(this).css({'top': windowTopOffset+'px', 'position': 'absolute', 'margin-left': '-' + ml + 'px', 'left': '50%'});
	});	
};


/* LIGHTBOX HOMEMADE
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
jQuery.fn.a17_ui_lightbox = function(_effect, _speed) {
	return this.each(function(i) {
		var self = $(this);
		var lbCloseButton = self.find('.lb_close'); /* Assuming the close button has the standard .lb-close class applied */
		lbCloseButton.bind({
			click: function(e) {
				e.preventDefault();
				self.a17_ui_showhide(_effect, _speed);
			}
		});
	});
};
jQuery.fn.a17_ui_loginResetForm = function() {
	return this.each(function(i) {
		var self = $(this);
		function resetForm() {
			self.vhAlign();
			self.find('.login_instructions').html(loginText);
			self.find('.error').removeClass('error');
			self.find('input:text')[0].focus(); /* Auto focus the first input text field found */
		}
		resetForm();
	});
};
jQuery.fn.a17_ui_lightbox_trigger = function(_target) {
	return this.each(function(i) {
		if (_target.length == 0) 
			return;
		var self = $(this);
		var lb = $(_target);
		self.bind({
			click: function(e) {
				e.preventDefault();
				lb.a17_ui_showhide('fade', 'fast');
				lb.a17_ui_loginResetForm();
			}
		});
	});
};

// LOGIN VALIDATE
jQuery.fn.a17_validate_login = function() {
	return this.each(function(i) {
		
		var self = $(this);
		var container = self.parent();
		var emailField = self.find('input:text');
		var instructionsField = self.find('.login_instructions');
		
		var submitBtn = self.find('input.submit');
		var cancelBtn = self.find('input.cancel');
		
		// if ($('html').hasClass('ie6')){
		// 	var successContainerBg = successContainer.children('.lb_background');
		// 	successContainerBg.css({'width': successContainer.outerWidth() + 'px','height': successContainer.outerHeight() + 'px'});
		// }
		
		self.submit(function() {
			
			var emailField = $(this).find('input:text');
			var emailVal = $(this).find('input:text').val();
			
			if (emailVal.length > 0 && isValidEmail(emailVal)) {
				
				instructionsField.html(loginText);
				self.removeClass('error');
				container.delay(400).a17_ui_showhide('fade', 'normal');
				
				//$('#logout').vhAlign();
				//$('#logout').delay(500).a17_ui_showhide('fade', 'fast');// .delay(2000).fadeOut('slow');

				if (ID != null && ID > 0) window.location = '/' + emailVal + '?add_on_login_id=' + ID;
				else window.location = '/' + emailVal;
				return false;
			} else {
				instructionsField.html(errorLoginText);
				self.addClass('error');
				emailField.focus();
				return false;
			}
		});
		
		cancelBtn.bind({
			click: function() {
				instructionsField.html(loginText);
				self.removeClass('error');
				emailField.focus();
			},
			mouseenter: function() {
				if (emailField.val().length == 0) cancelBtn.addClass('btn_alt_inactive');
				else cancelBtn.removeClass('btn_alt_inactive');
			}
		});
		
		submitBtn.bind({
			mouseenter: function() {
				if (emailField.val().length == 0) submitBtn.addClass('btn_inactive');
				else submitBtn.removeClass('btn_inactive');
			}
		})
		
	});
};

// NEWSLETTER SUBSCRIPTIOn VALIDATE
jQuery.fn.a17_validate_subscribe = function(defaultText) {
	return this.each(function(i) {
		
		var self = $(this);
		var container = self.parent();
		var emailField = self.find('input:text');
		var subscribeFeedback = self.find('.subscribe_feedback');
		var onValidErrorMessage = subscribeFeedback.text();
		var onSubmitFailMessage = 'Sorry an error occured, please try again';

	  if ($('body').hasClass('fr')) {
  		var onSubmitSuccessMessage = 'Inscription à notre newsletter réussie';
  		var onSubmitDupeMessage = 'Vous êtes déjà inscrit à notre newsletter';
    } else {
  		var onSubmitSuccessMessage = 'You are now subscribed to our newsletter';
  		var onSubmitDupeMessage = 'You have already subscribed to our newsletter';
	  }
		
		var submitBtn = self.find('input.submit');
		var cancelBtn = self.find('input.cancel');
		
		var isSubmitting = false;
		
		// if ($('html').hasClass('ie6')){
		// 	var successContainerBg = successContainer.children('.lb_background');
		// 	successContainerBg.css({'width': successContainer.outerWidth() + 'px','height': successContainer.outerHeight() + 'px'});
		// }
		
		self.submit(function() {
			
			var emailField = $(this).find('input:text');
			var emailVal = $(this).find('input:text').val();
			
			function onSubmitSuccess() {
				self.removeClass('submitting').addClass('submitted');
				subscribeFeedback.html(onSubmitSuccessMessage);
				isSubmitting = false;		
			}
			function onSubmitFailed() {
				self.removeClass('submitting').addClass('error');
				subscribeFeedback.html(onSubmitFailMessage);
				isSubmitting = false;		
			}
			function onSubmitDupe() {
				self.removeClass('submitting').addClass('error');
				subscribeFeedback.html(onSubmitDupeMessage);
				isSubmitting = false;
			}
			function onValidError() {
				self.removeClass('submitting').addClass('error');
				subscribeFeedback.html(onValidErrorMessage);
				emailField.focus();
				isSubmitting = false;
			}
			
			if (emailVal.length > 0 && isValidEmail(emailVal) && !isSubmitting) {
				isSubmitting = true;
				subscribeFeedback.html('&nbsp;');
				self.removeClass('error submitted').addClass('submitting');
				$('#subscribe_email').blur();
				$.ajax({
					type: "POST",
					url: "/subscribers/create",
					data: "email="+ emailVal,
					success: function(msg){
						switch(msg) {
							case 'SUCCESS: OK':
								setTimeout(onSubmitSuccess, 1300);
								self.a17_ui_subscribeResetForm(defaultText, 5500);
								return false;
							case 'ERROR: FAILED':
								setTimeout(onSubmitFailed, 1300);
								return false;
							case 'ERROR: DUPE':
								setTimeout(onSubmitDupe, 1300);
								self.a17_ui_subscribeResetForm(defaultText, 5500);
								return false;
							default :
								setTimeout(onSubmitFailed, 1300);
								return false;
						}
					},
					error: function(msg) {
						setTimeout(onSubmitFailed, 1000);
						return false;
					}
				});	
	
				return false;
			} else {
				if (!isSubmitting) onValidError();
				return false;
			}
		});
		
		
	});
};
jQuery.fn.a17_ui_subscribeResetForm = function(defaultText, delay) {
	return this.each(function(i) {
		var self = $(this);
		function resetForm() {
			// self.find('.subscribe_feedback').fadeOut('slow', function() {
			// 	self.removeClass('error');
			// });
			self.removeClass('error searchFor submitting submitted');
			self.find('input:text').val(defaultText);
		}
		if (delay) setTimeout(resetForm, delay);
		else resetForm();
	});
};


jQuery.fn.a17_ui_showhide = function(_effect, _speed) {
	return this.each(function(i) {
		var self = $(this);
		if (self.is(':visible')){
			switch(_effect) {
				case 'fade': self.fadeOut(_speed);
				case 'side': self.slideUp(_speed);
				default: self.hide(_speed);	
			}
		} else {
			switch(_effect) {
				case 'fade': self.fadeIn(_speed);
				case 'side': self.slideDown(_speed);
				default: self.show(_speed);	
			}
		}
	});
}

function isValidEmail(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}
