function strip_tags(str, allowed_tags){
	var key = '', allowed = false;
	var matches = [];
	var allowed_array = [];
	var allowed_tag = '';
	var i = 0;
	var k = '';
	var html = '';
	
	var replacer = function(search, replace, str){
		return str.split(search).join(replace);
	};
	
	// Build allowes tags associative array
	if (allowed_tags) {
		allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
	}
	
	str += '';
	
	// Match tags
	matches = str.match(/(<\/?[\S][^>]*>)/gi);
	
	// Go through all HTML tags
	for (key in matches) {
		if (isNaN(key)) {
			// IE7 Hack
			continue;
		}
		
		// Save HTML tag
		html = matches[key].toString();
		
		// Is tag not in allowed list? Remove from str!
		allowed = false;
		
		// Go through all allowed tags
		for (k in allowed_array) {
			// Init
			allowed_tag = allowed_array[k];
			i = -1;
			
			if (i != 0) {
				i = html.toLowerCase().indexOf('<' + allowed_tag + '>');
			}
			if (i != 0) {
				i = html.toLowerCase().indexOf('<' + allowed_tag + ' ');
			}
			if (i != 0) {
				i = html.toLowerCase().indexOf('</' + allowed_tag);
			}
			
			// Determine
			if (i == 0) {
				allowed = true;
				break;
			}
		}
		
		if (!allowed) {
			str = replacer(html, "", str); // Custom replace. No regexing
		}
	}
	
	return str;
}

/**
 * jQuery shuffle
 *
 * Copyright (c) 2008 Ca-Phun Ung <caphun at yelotofu dot com>
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://yelotofu.com/labs/jquery/snippets/shuffle/
 *
 * Shuffles an array or the children of a element container.
 * This uses the Fisher-Yates shuffle algorithm <http://jsfromhell.com/array/shuffle [v1.0]>
 */
(function($){

	$.fn.shuffle = function(){
		return this.each(function(){
			var items = $(this).children().clone(true);
			return (items.length) ? $(this).html($.shuffle(items)) : this;
		});
	}
	
	$.shuffle = function(arr){
		for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x) 
			;
		return arr;
	}
	
})(jQuery);

/**
 * jQuery template
 *
 */
(function($){

	$.fn.template = function(data){
		return $(this).clone().each(function(){
			return $(this).html($.template($(this).html(), data));
		});
	}
	
	$.template = function(template, data){
		template = data ? {
			template: template,
			data: typeof template == 'object' && template.data ? $.extend(template.data, data) : data
		} : template;
		$.each(template.data, function(key, value){
			template.template = template.template.replace(new RegExp('(\\{|%7B)' + key + '(\\}|%7D)', 'g'), value);
		});
		return template.template.replace(/source=\"/g, 'src="');
	}
	
})(jQuery);

(function($){
	$.fn.chain = function(f){
		return $(this).each(function(){
			f.apply(this)
			return this;
		});
	};
})(jQuery);

/**
 * jQuery Coaching Make Up
 *
 */
(function($){

	var CMU = function(){
		this.init();
	};
	
	//===================================================================
	//	COACHING MAKE UP
	//===================================================================
	
	var History = [];
	
	CMU.prototype = {
	
		config: {},
		xml: {},
		template: {},
		layout: {},
		
		init: function(){
			this.layout.context = this;
                        $.address.tracker(null)
		},
		
		load: function(){
			this.template.load(this.config.base + 'NOS_CONSEILS/Coaching_Make_Up/' + this.config.files.template);
			this.xml.load(this.config.base + 'NOS_CONSEILS/Coaching_Make_Up/' + this.config.files.pages);
			this.loadListener();
		},
		
		loadListener: function(){
			var _this = this;
			var interval = setInterval(function(){
				if (_this.xml.loaded && _this.template.loaded) {
					clearInterval(interval);
					_this.success();
					_this.URL();
					_this.hashURL();
					$('#b-cmu-navigation a').click($.proxy(function(event){
						event.preventDefault();
						this.historyBack();
					}, _this)).hide();
					$.address.internalChange(function(event){
						$('#b-cmu-navigation a').show();
					}).externalChange(function(event){
						var url = event.value.substr(1);
						if (url) 
							_this.hashURL(url);
						else 
							_this.hashURL(History[0]);
					});
				}
			}, 250);
		},
		
		success: function(){
		},
		
		URL: function(url){
			var staticUrl = url ? url : location.pathname.substr(location.pathname.lastIndexOf("/") + 1);
			var page = this.xml.getPage('[url="' + staticUrl + '"]');
			
			History.push(staticUrl);
			switch (page.attr('type')) {
				case 'section':
					this.layout.fromSection(page.attr('section'));
					break;
				case 'video':
					this.layout.fromVideo(page.attr('url'), page.attr('section'));
					break;
				default:
					this.layout.fromIndex();
					break;
			}
		},
		hashURL: function(url){
			var xhrUrl = url ? url : $.address.value().substr(1);
			if (xhrUrl) {
				var page = this.xml.getPage('[url="' + xhrUrl + '"]');
				switch (page.attr('type')) {
					case 'section':
						this.layout.triggerCategorySelect(page.attr('section'));
						break;
					case 'video':
						this.layout.triggerVideoSelect(page.attr('url'));
						break;
					default:
						this.layout.pageSection();
						break;
				}
			}
		},
		
		historyBack: function(){
			var url = '';
			if (History.length > 1) {
				url = History[History.length - 2];
				History = History.slice(0, -1);
			}
			if (url) {
				$.address.value(url);
				this.hashURL(url);
			}
			if (History.length == 1) {
				$('#b-cmu-navigation a').hide();
			}
		}
	};
	
	//===================================================================
	//	YOUTUBE API
	//===================================================================
	
	CMU.prototype.ytapi = {
		currentStep: 1,
		steps: [],
		_interval: 0,
		_current: 0,
		_api: {},
		init: function(){
			this._api = document.getElementById('myytplayer');
			this._interval = setInterval($.proxy(function(){
				if (this._api) {
					try{
						this._current = parseInt(this._api.getCurrentTime());
						this.update();
						this._api.addEventListener("onStateChange", "onYTStateChange");
						this._api.addEventListener("onPlaybackQualityChange", "onYTPlaybackQualityChange");
					} catch (ex) {}
				} else {
					clearInterval(this._interval);
				}
			}, this), 1000);
			this.ready();
		},
		seek: function(time){
			if (this._api) 
				this._api.seekTo(time, true);
		},
		time: function(){
			return this._current;
		},
		clear: function(){
			if (this._interval) 
				clearInterval(this._interval);
			this.steps = [];
			this.currentStep = 1;
			this._interval = this._current = 0;
			this._api = {};
		},
		ready: function(){
		},
		update: function(){
		}
	};
	
	//===================================================================
	//	CONFIG
	//===================================================================
	
	CMU.prototype.config = {
		base: '',
		files: {
			pages: '',
			template: ''
		}
	};
	
	//===================================================================
	//	TEMPLATE
	//===================================================================
	
	CMU.prototype.template = {
	
		section: {
			global: '',
			categorySelector: '',
			videoSelector: '',
			spotlightVideoSelector: ''
		},
		
		video: {
			global: '',
			header: '',
			player: '',
			step: '',
			stepText: '',
			stepProduct: '',
			panel: '',
			carousel: '',
			carouselItem: ''
		},
		
		loaded: false,
		
		load: function(url){
			$.ajax({
				type: 'GET',
				url: url,
				dataType: 'html',
				script: false,
				success: $.proxy(function(data){
					data = data.replace(/src=\"({.+})\"/g, 'source="$1"');
					this.section = {
						global: $(data).find('#cmu-template-section').html(),
						categorySelector: $(data).find('#b-cmu-rgt-categories').html(),
						videoSelector: $(data).find('#b-cmu-rgt-list-videos').html(),
						spotlightVideoSelector: $(data).find('#b-cmu-rgt-list-spotlight').html()
					};
					
					this.video = {
						global: $(data).find('#cmu-template-video').html(),
						header: $(data).find('#cmu-template-video').find('#b-cmu-rgt-header').html(),
						player: $(data).find('#b-cmu-rgt-video-player').html(),
						step: $(data).find('#b-cmu-rgt-video-steps').html(),
						stepText: $(data).find('#b-cmu-rgt-video-text').html(),
						stepProduct: $(data).find('#b-cmu-rgt-video-products').html(),
						stepProductList: $(data).find('#b-cmu-rgt-video-products-list').html(),
						panel: $(data).find('#b-cmu-rgt-video-user-panel').html(),
						carousel: $(data).find('#b-cmu-rgt-videos').html(),
						carouselItem: $(data).find('#b-cmu-rgt-videos-carousel-items').html(),
						popin: $(data).find('#cmu-template-popin').html()
					};
					
					this.loaded = true;
				}, this)
			});
		}
	};
	
	//===================================================================
	//	XML
	//===================================================================
	
	CMU.prototype.xml = {
	
		data: {},
		
		loaded: false,
		
		load: function(url){
			$.ajax({
				type: 'GET',
				url: url,
				dataType: 'xml',
				success: $.proxy(function(data){
					this.data = $(data);
					this.loaded = true;
				}, this)
			});
		},
		
		getPages: function(selector, filters){
			if (typeof selector == 'object' || typeof selector == 'array') {
				filters = selector;
				selector = '';
			}
			return this.data.find('pages > page' + selector).filter(function(){
				for (index in filters) {
					if (!$(this).find(filters[index]).size()) {
						return false;
					}
				}
				return true;
			});
		},
		
		getPage: function(selector, filters){
			return this.getPages(selector, filters).first();
		}
	};
	
	//===================================================================
	//	LAYOUT
	//===================================================================

	var productTimer = null;
	
	CMU.prototype.layout = {
	
		current: '',
		context: {},
		
		//-----------------------------------------------------------
		//	Context Builders
		//-----------------------------------------------------------
		
		fromIndex: function(){
			this.current = 'section';
			this.parseMenu();
			this.parseCategorySelector();
			this.parseSpotlightVideoSelector();
			$('#b-cmu-rgt-categories').after($('<ul id="b-cmu-rgt-list-videos"></ul>').css('display', 'none'));
			this.buildSpotlightVideoSelector();
		},
		
		fromSection: function(section){
			this.current = 'section';
			this.parseMenu();
			this.parseCategorySelector();
			this.parseSpotlightVideoSelector();
			this.pageSection(section);
		},
		
		fromVideo: function(url, section){
			this.current = 'video';
			this.parseMenu();
			this.buildVideoPlayer(url);
			this.parseVideoStepProducts(url, 1);
			this.parseVideoCarousel();
			this.triggerVideoYTAPI(url);
		},
		
		//-----------------------------------------------------------
		//	Layout Parsers
		//-----------------------------------------------------------
		
		parseMenu: function(){
			var _this = this;
			$('#b-cmu-lft-menu-selector li').each(function(){
				$(this).find('h3 a').bind('click', {
					section: $(this).find('div').attr('class')
				}, $.proxy(_this.handlerCategorySelect, _this)).end().find('li a').bind('click', $.proxy(_this.handlerVideoSelect, _this)).end()
			});
		},
		
		parseCategorySelector: function(){
			var _this = this;
			$('#b-cmu-rgt-categories li').each(function(){
				$(this).find('a').bind('click', {
					section: $(this).find('div').attr('class')
				}, $.proxy(_this.handlerCategorySelect, _this));
			});
		},
		
		parseSpotlightVideoSelector: function(){
			var _this = this;
			$('#b-cmu-rgt-list-spotlight li div a').bind('click', $.proxy(_this.handlerVideoSelect, _this));
			$('#b-cmu-rgt-list-spotlight li > a').bind('click', function(event){
				/*$.proxy(_this.handlerVideoSelect, _this)*/
			});
		},
		
		//-----------------------------------------------------------
		//	Pages Builders
		//-----------------------------------------------------------
		
		pageSection: function(section){
			var _this = this;
			this.current = 'section';
			this.context.ytapi.clear();
			$('#c-cmu-rgt').empty().hide().html(this.context.template.section.global).chain(function(){
				_this.buildSectionHeader();
				_this.buildCategorySelector();
				_this.buildVideoSelector(section);
				_this.buildSpotlightVideoSelector(section);
				if (section) {
					_this.triggerCategorySelect(section);
					$('#b-cmu-rgt-list-videos').show();
				} else 
					$('#b-cmu-rgt-list-videos').hide();
			}).show();
			$('#b-cmu-rgt-header img').attr('src', _this.makeUrl('NOS_CONSEILS/Coaching_Make_Up/img/img_cmu_title.gif'));
		},
		
		pageVideo: function(url){
			var _this = this;
			this.current = 'video';
			$('#c-cmu-rgt').empty().hide().html(this.context.template.video.global).chain(function(){
				$(this).attr('class', _this.context.xml.getPage('[url="' + url + '"][type="video"]').attr('section'));
				_this.buildVideoHeader(url);
				_this.buildVideoPlayer(url);
				_this.buildVideoSteps(url);
				_this.buildVideoStep(url, 1);
				_this.buildVideoStepProducts(url, 1);
				_this.buildVideoPanel(url);
				_this.buildVideoCarousel(url);
				_this.triggerVideoYTAPI(url);
				_this.buildTrackers(url);
				$('#b-cmu-lft-menu-selector > li').removeClass('selected');
				$('#b-cmu-lft-menu-selector li li a').each(function(){
					$(this).parents('li:first').removeClass('selected');
					if ($(this).attr('href').substr($(this).attr('href').lastIndexOf("/") + 1) == url) {
						$(this).parents('li').addClass('selected');
					}
				});
			}).show();
			$('#b-cmu-rgt-header img').attr('src', _this.makeUrl('NOS_CONSEILS/Coaching_Make_Up/img/img_cmu_title.gif'));
		},
		
		//-----------------------------------------------------------
		//	Layout Builders
		//-----------------------------------------------------------
		
		buildSectionHeader: function(url){
			var _this = this;
			$('#b-cmu-rgt-header p').html(function(){
				return _this.context.xml.getPage('[type="home"]').find('> intro').text();
			});
		},
		
		buildCategorySelector: function(){
			var _this = this;
			var container = $('#b-cmu-rgt-categories').empty();
			var xml = this.context.xml;
			var pattern = this.context.template.section.categorySelector;
			xml.getPages('[type="section"]').each(function(){
				var data = {
					'section.name': $(this).attr('section'),
					'section.title': $(this).find('title').text(),
					'section.url': $(this).attr('url'),
					'video.count': $(xml.getPages('[type="video"][section="' + $(this).attr('section') + '"]')).size()
				}
				container.append($($.template(pattern, data)).find('a').bind('click', {
					section: $(data).attr('section.name')
				}, $.proxy(_this.handlerCategorySelect, _this)).end());
			});
		},
		
		buildVideoSelector: function(section){
			var _this = this;
			var container = $('#b-cmu-rgt-list-videos').empty().css('display', 'block').attr('class', section);
			var xml = this.context.xml;
			var pattern = this.context.template.section.videoSelector;
			xml.getPages('[type="video"][section="' + section + '"]').each(function(){
				var data = {
					'video.title': $(this).find('> name').text(),
					'video.title.strip': $(this).find('> name').text().replace(/<[^>]+>/g, ''),
					'video.url': _this.getUrl($(this)),
					'video.image': _this.getImagesUrl() + $(this).find('> smallImage').text()
				};
				var template = $($.template(pattern, data));
				
				template.find('a').attr('href', $(data).attr('video.url')).bind('click', $.proxy(_this.handlerVideoSelect, _this));
				template.find('a').attr('title', $(this).find('> name').text().replace(/<[^>]+>/g, ''));
				container.append(template).end();
			});
		},
		
		buildSpotlightVideoSelector: function(section){
			var _this = this;
			var container = $('#b-cmu-rgt-list-spotlight').empty();
			var xml = this.context.xml;
			var pattern = this.context.template.section.spotlightVideoSelector;
			$.shuffle(xml.getPages('[type="video"]' + (section ? '[section=' + section + ']' : ''))).slice(0, 2).each(function(){
				var section = xml.getPage('[type="section"][section="' + $(this).attr('section') + '"]');
				var data = {
					'video.section': $(this).attr('section'),
					'video.title': $(this).find('> name').text(),
					'video.title.strip': $(this).find('> name').text().replace(/<[^>]+>/g, ''),
					'video.url': _this.getUrl($(this)),
					'video.image': _this.getImagesUrl() + $(this).find('> mediumImage').text(),
					'section.name': $(section).attr('section'),
					'section.title': $(section).find('title').text(),
					'section.url': $(section).attr('url')
				}
				var template = $($.template(pattern, data));
				
				template.find('div a').bind('click', {
					section: $(data).attr('video.section')
				}, $.proxy(_this.handlerCategorySelect, _this)).end();
				template.find('> a').attr('href', $(data).attr('video.url')).bind('click', $.proxy(_this.handlerVideoSelect, _this)).end();
				template.find('> a').attr('title', $(this).find('> name').text().replace(/<[^>]+>/g, ''));
				container.append(template);
			});
			if (section) {
				window.gaCMUPage('/NOS_CONSEILS/Coaching_Make_Up/'+section.charAt(0).toUpperCase() + section.substr(1) + '.aspx');
			}
		},
		
		buildVideoHeader: function(url){
			var _this = this;
			$('#b-cmu-rgt-header h2').html(function(){
				return '<span class="alt">' + _this.context.xml.getPage('[url="' + url + '"][type="video"]').find('> name').text().replace(/<[^>]+>/g, '') + '</span>';
			});
		},
		
		buildVideoPlayer: function(url){
			var videoElement = this.context.xml.getPage('[url="' + url + '"][type="video"]');
			var video = this.context.xml.getPage('[url="' + url + '"][type="video"]').find('> video').text();
			var params = {
				allowScriptAccess: "always",
				allowfullscreen: "true",
				wmode: 'transparent'
			};
			var atts = {
				id: "myytplayer"
			};
			window.YTUrl = url;
			swfobject.embedSWF("http://www.youtube.com/v/" + video + "?enablejsapi=1&playerapiid=ytplayer&autoplay=0&hl=fr_FR&fs=1&rel=0&hd=0&showinfo=0", "b-cmu-rgt-video-player", "610", "372", "8", null, null, params, atts);
			window.gaCMUPage('/NOS_CONSEILS/Coaching_Make_Up/' + videoElement.attr('section').charAt(0).toUpperCase() + videoElement.attr('section').substr(1) + '/' + url);
		},
		
		buildVideoSteps: function(url){
			var _this = this;
			var container = $('#b-cmu-rgt-video-steps').empty();
			var pattern = this.context.template.video.step;
			this.context.xml.getPage('[url="' + url + '"][type="video"]').find('steps step').each(function(i){
				var data = {
					'video.step.number': i + 1,
					'video.step.name': $(this).find('> name').text()
				};
				container.append($($.template(pattern, data)).chain(function(){
					if (!i) 
						$(this).addClass('selected');
				}));
			});
		},
		
		buildVideoStep: function(url, step){
			var _this = this;
			var container = $('#b-cmu-rgt-video-text').empty();
			var pattern = this.context.template.video.stepText;
			this.context.xml.getPage('[url="' + url + '"][type="video"]').find('steps step:eq(' + (step - 1) + ')').first().chain(function(){
				var data = {
					'video.step.number': step,
					'video.step.name': $(this).find('> name').text(),
					'video.step.description': $(this).find('> description').text()
				};
				container.html($.template(pattern, data));
			});
		},
		
		buildVideoStepProducts: function(url, step){
			var _this = this;
			var container = {
				global: $('#b-cmu-rgt-video-products').empty(),
				list: $('#b-cmu-rgt-video-products-list').empty()
			};
			var pattern = {
				global: this.context.template.video.stepProduct,
				list: this.context.template.video.stepProductList
			};
			var current_id = 0;
			var productTempo = 5000;
			this.context.xml.getPage('[url="' + url + '"][type="video"]').find('steps step:eq(' + (step - 1) + ') products product').each(function(i){
				
				if ($(this).find('> urlBuy').text() == "") {
					$('#b-cmu-rgt-video-products a#url-current-image').removeAttr('href');
					$('#b-cmu-rgt-video-products-navigation div').removeClass().addClass('title_fitme');
					$('#b-cmu-rgt-video-products-navigation a').removeAttr('href');
				}
				
				var data = {
					'video.step.product.name': $(this).find('> name').text(),
					'video.step.product.name.strip': $(this).find('> name').text().replace(/<[^>]+>/g, ''),
					'video.step.product.description': $(this).find('> description').text(),
					//'video.step.product.url': _this.context.config.base + $(this).find('> urlProduct').text(),
					'video.step.product.url': _this.makeUrl($(this).find('> urlProduct').text()),
					//'video.step.product.urlBuy': _this.context.config.base + $(this).find('> urlBuy').text(),
					'video.step.product.urlBuy': _this.makeUrl($(this).find('> urlBuy').text()),
					'video.step.product.smallImage': _this.getImagesUrl() + $(this).find('> smallImage').text(),
					'video.step.product.image': _this.getImagesUrl() + $(this).find('> bigImage').text(),
					'current.id': current_id
				};
				current_id++;
				if (!i) {
					container.list = container.global.html($.template(pattern.global, data)).find('#b-cmu-rgt-video-products-list').empty();
				}
				container.list.append($.template(pattern.list, data));
			});
			var productCount = $('#b-cmu-rgt-video-products-list li').length;
			var rotate = function(){
					$('.prod-selected').removeClass('prod-selected');
					$('#slideshow_' + current_id).addClass('prod-selected');
					
			if(productCount == current_id)
					current_id = 0;
				setTimeout(rotate, productTempo);
			};
			//rotate();
			this.parseVideoStepProducts(url, step);
			
		},

		buildTwitterUrl: function(elem){
			var url = 'http://twitter.com/home?status=';
			var status = "J'ai suivi les conseils maquillage Coaching Make Up  - " +
			elem.find('> name').text().replace(/<[^>]+>/g, '') +
			' - ' +
			elem.find('> bitly').text();
			
			url += encodeURIComponent(status);
			url = url.replace(/(%20)+/g, "+");
			return (url);
		},
		
		getUrl: function(elem){
			var url;
			
			if (this.isHttpUrl(elem) == false) {
				url = this.context.config.base +
				'NOS_CONSEILS/Coaching_Make_Up.aspx#/' +
				elem.attr('url');
			} else {
				url = elem;
			}
			return (url);
		},
		
		isHttpUrl: function(elem){
			var regexp = /^(http|https):\/\/?/;
			return regexp.test(elem);
		},
		
		makeUrl: function(elem){
			var url;
			
			if (this.isHttpUrl(elem) == false) {
				url = this.context.config.base + elem;
			} else {
				url = elem;
			}
			return url;
		},
		
		makeExternalUrl: function(elem){
			var url;
			
			if (this.isHttpUrl(elem) == false) {
				url = 'http://' + window.document.location.host + elem;
			} else {
				url = elem;
			}
			return url;
		},
		
		makeYoutubeUrl: function(elem){
			var url;
			
			if (this.isHttpUrl(elem) == false) {
				url = 'http://www.youtube.com/user/GemeyMaybellineFR#p/a/u/0/' + elem;
			} else {
				url = elem;
			}
			return url;
		},
		
		makePrintUrl: function(elem){
			var url;
			
			if (this.isHttpUrl(elem) == false) {
				url = this.context.config.base +
					  'NOS_CONSEILS/Coaching_Make_Up/print/' + 
					  elem;
			} else {
				url = elem;
			}
			return url;
		},
		
		getImagesUrl: function(){
			var url;
			
			url = this.context.config.base +
			'NOS_CONSEILS/Coaching_Make_Up/' +
			'img/';
			return (url);
		},

		buildVideoPanel: function(url){
			var _this = this;
			
			this.context.xml.getPage('[url="' + url + '"][type="video"]').chain(function(){
				var elem = $(this);
				var facebookIt = function(event){
					event.preventDefault();
					var message = "a suivi les conseils maquillage Coaching Make Up - " + strip_tags(elem.find('> name').text());
					var attachment = {
						'name': "Coaching Make Up : " + elem.find('> name').text(),
						'href': _this.makeExternalUrl(_this.getUrl(elem)),
						'caption': '{*actor*} vient de regarder la vidéo conseil maquillage - ' + elem.find('> name').text(),
						'description': "Suivez toutes les astuces des professionnels !",
						'media': [{
							'type': 'image',
							'src': _this.makeExternalUrl(_this.getImagesUrl() + elem.find('> mediumImage').text()),
							'href': _this.makeExternalUrl(_this.getUrl(elem))
						}]
					};
					var action_links = [{
						'text': "Voir les vidéos Coaching Make Up",
						'href': _this.makeExternalUrl(_this.makeUrl('/NOS_CONSEILS/Coaching_Make_Up.Aspx'))
						
					}];
					window.gaCMUEvent('share', 'facebook', elem.attr('url'));
					FB.Connect.streamPublish(message, attachment, action_links);
				};
				var printIt = function(event){
					event.preventDefault();
					var printUrl;
					
					url = _this.makePrintUrl(elem.attr('url').replace(/(.*)\.aspx/, '$1.html'));
					window.gaCMUEvent('share', 'print', elem.attr('url'));
					window.open(url, 'CoachingMakeUpPrint', "directories=no,location=no,menubar=no,resizable=no,status=no,scrollbars=yes,width=1024height=768");
				};
				var copyIt = function(event) {
					$.copy($(this).attr('value'));
					window.gaCMUEvent('share', 'copyUrl', elem.attr('url'));
					$(this).select();
				};
				
				/* youtube */
				$('#b-cmu-rgt-video-user-panel-youtube').attr('href', _this.makeYoutubeUrl($(this).find('video').text())).click(function(event) {
					window.gaCMUEvent('share', 'youtube', $(this).attr('url'));
				});
				/* facebook */
				$('#b-cmu-rgt-video-user-panel-facebook').click(facebookIt);

				/* twitter */
				$('#b-cmu-rgt-video-user-panel-twitter').attr('href', _this.buildTwitterUrl($(this))).click(function(event) {
					window.gaCMUEvent('share', 'twitter', elem.attr('url'));
				});
				/* copy/paste */
				$('#b-cmu-rgt-video-user-panel input').focus(copyIt);
				$('#b-cmu-rgt-video-user-panel input').attr('value', _this.makeExternalUrl(_this.getUrl($(this))));

				/* print */
				$('#b-cmu-rgt-video-user-panel-print').click(printIt);
				
				/* popin share to */
				$('#c-cmu-rgt').append(_this.context.template.video.popin);
				$('#cmu-popin-sendto .header a').bind('click', function(event){
					event.preventDefault();
					$('#cmu-popin-layer').find('input[type="image"]:first').attr('src', _this.makeUrl('NOS_CONSEILS/Coaching_Make_Up/img/btn_popin_sendto.gif'));
					$('#cmu-popin-layer').fadeOut(function(){
						$('#cmu-popin-layout').fadeOut();
					});
				});
				$('#b-cmu-rgt-video-user-panel-share').bind('click', function(event){
					event.preventDefault();
					window.gaCMUEvent('share', 'openSharePopin', elem.attr('url'));
					if ($.browser.msie && $.browser.version.substr(0, 1) == 6) {
						$('#cmu-popin-layer').css({
							'position': 'absolute',
							'top': $(this).offset().top - 500,
							'margin-top': '0px',
							'height': '500px'
						});
						$('#cmu-popin-layout').css({
							'position': 'absolute',
							'height': document.body.offsetHeight,
							'opacity': '0.75'
						});
					}
					$('#cmu-popin-layout').css('opacity', 0).animate({
						'opacity': 0.75
					}, 400, function(){
						$(this).css('display', 'block');
						$('#cmu-popin-layer').fadeIn();
					});
					$('#cmu-popin-layer form').submit(function(event){
						event.preventDefault();
						$.each(['fromFirstname', 'friendFirstname', 'friendEmail', 'message'], function(i, name){
							var item = $('#cmu-popin-layer form [name="' + name + '"]');
							
							if (item === null || item.length < 1 || item.val() === '') {
								alert('Merci de remplir tous les champs.');
								return (false);
							}
						});
						var soapBody = new SOAPObject("web:EmailThis");
						var urlParam = new SOAPObject("web:url");
						var competCodeParam = new SOAPObject("web:competCode");
						var ecardParam = new SOAPObject("web:ecardName");
						var fromEmailParam = new SOAPObject("web:fromEmail");
						var fromFirstnameParam = new SOAPObject("web:fromFirstname");
						var friendEmailParam = new SOAPObject("web:friendEmail");
						var friendFirstnameParam = new SOAPObject("web:friendFirstname");
						var messageParam = new SOAPObject("web:message");
						var sr;
						
						urlParam.val($('#b-cmu-rgt-video-user-panel input').val()); //('/' + $('#b-cmu-rgt-video-user-panel input').val().replace(_this.context.config.base, ''));
						competCodeParam.val('0905_coachingmakeup');
						ecardParam.val('emailthis');
						fromEmailParam.val('noreply@coachingmakeup.com');
						fromFirstnameParam.val($('#cmu-popin-layer form [name="fromFirstname"]').val());
						friendEmailParam.val($('#cmu-popin-layer form [name="friendEmail"]').val());
						friendFirstnameParam.val($('#cmu-popin-layer form [name="friendFirstname"]').val());
						messageParam.val($('#cmu-popin-layer form [name="message"]').val());
						
						soapBody.appendChild(urlParam);
						soapBody.appendChild(competCodeParam);
						soapBody.appendChild(ecardParam);
						soapBody.appendChild(fromEmailParam);
						soapBody.appendChild(fromFirstnameParam);
						soapBody.appendChild(friendEmailParam);
						soapBody.appendChild(friendFirstnameParam);
						soapBody.appendChild(messageParam);
						sr = new SOAPRequest("http://www.gemey-maybelline.com/Webservices/EmailThis", soapBody);
						sr.addNamespace("web", "http://www.gemey-maybelline.com/Webservices");
						sr.addNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
						SOAPClient.Proxy = _this.makeUrl("webservicesV4/mnyuserservices.asmx");
						SOAPClient.SendRequest(sr, null);
						$('#cmu-popin-sendto .header a').click();
						window.gaCMUEvent('share', 'sendSharePopin', elem.attr('url'));
					});
				});
			});
		},
		
		buildVideoCarousel: function(url){
			var _this = this;
			var container = {
				global: $('#b-cmu-rgt-videos').empty(),
				item: $('#b-cmu-rgt-videos-carousel-items').empty()
			};
			var pattern = {
				global: this.context.template.video.carousel,
				item: this.context.template.video.carouselItem
			};
			section = this.context.xml.getPage('[url="' + url + '"][type="video"]').attr('section');
			this.context.xml.getPage('[type="section"][section="' + section + '"]').chain(function(){
				var data = {
					'section.name': section,
					'section.title': $(this).find('> title').text(),
					'video.name': '',
					'video.url': '',
					'video.image': ''
				};
				container.item = container.global.html($.template(pattern.global, data)).find('#b-cmu-rgt-videos-carousel-items').empty();
			});
			this.context.xml.getPages('[type="video"][section="' + section + '"]').each(function(){
				var data = {
					'video.name': $(this).find('> name').text().replace(/<[^>]+>/g, ''),
					'video.url': _this.getUrl($(this)),
					'video.image': _this.getImagesUrl() + $(this).find('> mediumImage').text()
				};
				container.item.append($.template(pattern.item, data));
			});
			this.parseVideoCarousel();
		},
		
		parseVideoCarousel: function(){
		
			var ref = $('#b-cmu-rgt-videos-carousel ul li:first-child');
			//var ref_width = ref.width();
			var ref_width = 91;
			var nb_elem = $("#b-cmu-rgt-videos-carousel ul li").length;
			var nb_elem_vis = 6;
			var nb_elem_dis = nb_elem - nb_elem_vis;
			var cpt = 0;
			
			$('#b-cmu-rgt-videos-carousel ul').wrap('<div class="b-cmu-rgt-videos-carousel-conteneur" style="float:left;height:48px;width:552px;overflow:hidden;position:relative;"></div>').width(ref_width * nb_elem);
			
			$("#b-cmu-rgt-videos-carousel a.next").click(function(){
				if (cpt < nb_elem_dis) {
					cpt++;
					$('#b-cmu-rgt-videos-carousel ul').animate({
						marginLeft: -(ref_width * cpt - 6)
					});
				}
				return false;
			});
			
			$('#b-cmu-rgt-videos-carousel a.previous').click(function(){
				if (cpt > 0) {
					cpt--;
					$('#b-cmu-rgt-videos-carousel ul').animate({
						marginLeft: -(ref_width * cpt - 6)
					});
				}
				return false;
			});
			
			$("#b-cmu-rgt-videos-carousel-items a").bind('click', $.proxy(this.handlerVideoSelect, this));
			
			
			
		},

		parseVideoStepProducts: function(url, step){
			var _this = this;
			
			if (productTimer != null) 
				clearTimeout(productTimer);
			if ($('#b-cmu-rgt-video-products-list li').length == 0) 
				return;
			
			var productCount = $('#b-cmu-rgt-video-products-list li').length;
			var productTempo = 5000;
			productIndex = 0;
			
			
			$('#b-cmu-rgt-video-products-list li').each(function(i, el){
				$(this).click($.proxy(function(event){
					event.preventDefault();
					changeProduct(i, _this);
					productIndex = i;
				}, _this));
				
			});
			$('#b-cmu-rgt-video-products-list li:first').addClass('prod-selected');
			$('#b-cmu-rgt-video-products-list li').click(function(){
				$('#b-cmu-rgt-video-products-list li').removeClass("prod-selected");
				$(this).addClass("prod-selected");
			});
			$('#b-cmu-rgt-video-products-list').click(function(){
			$('#b-cmu-rgt-video-products-list li').animate({
				opacity: 0.4}, 100);
				});
				$('#b-cmu-rgt-video-products-list').click(function(){
			$('#b-cmu-rgt-video-products-list li.prod-selected').animate({
				opacity: 1}, 100);
				});
				$('#b-cmu-rgt-video-products-list').trigger('click');
				
			function changeProduct(index, _this){
				clearTimeout(productTimer);
				if (!$('#b-cmu-rgt-video-products-current-image')) 
					return;

				_this.context.xml.getPage('[url="' + url + '"][type="video"]').find('steps step:eq(' + (step - 1) + ') products product:eq(' + index + ')').chain(function(){
				
					var data = {
						'video.step.product.name': $(this).find('> name').text(),
						'video.step.product.name.strip': $(this).find('> name').text().replace(/<[^>]+>/g, ''),
						'video.step.product.description': $(this).find('> description').text(),
						//'video.step.product.url': _this.context.config.base + $(this).find('> urlProduct').text(),
						'video.step.product.url': _this.makeUrl($(this).find('> urlProduct').text()),
						//'video.step.product.urlBuy': _this.context.config.base + $(this).find('> urlBuy').text(),
						'video.step.product.urlBuy': _this.makeUrl($(this).find('> urlBuy').text()),
						'video.step.product.image': _this.getImagesUrl() + $(this).find('> bigImage').text()
					};
					
					//ici
					
					$('#b-cmu-rgt-video-products-current-image').attr('src', $(data).attr('video.step.product.image'));
					$('#b-cmu-rgt-video-products-actions .more').attr('href', $(data).attr('video.step.product.url'));
					
					if ($(this).find('> urlBuy').text() == "") {
						$('#b-cmu-rgt-video-products a#url-current-image').removeAttr('href');
						$('#b-cmu-rgt-video-products-navigation div').removeClass().addClass('title_fitme');
						$('#b-cmu-rgt-video-products-navigation a').removeAttr('href');
						$('#b-cmu-rgt-video-products-navigation .title_fitme .product').html($(data).attr('video.step.product.name'));
						$('#b-cmu-rgt-video-products-navigation .title_fitme .description').html($(data).attr('video.step.product.description'));
					} else {
						$('#b-cmu-rgt-video-products-current-image').parent().attr('href', $(data).attr('video.step.product.urlBuy'));
						$('#b-cmu-rgt-video-products-navigation a').attr('href', $(data).attr('video.step.product.urlBuy'));
						/*$('#b-cmu-rgt-video-products-actions .buy').attr('href', $(data).attr('video.step.product.urlBuy'));*/
						$('#b-cmu-rgt-video-products-navigation .title .product').html($(data).attr('video.step.product.name'));
						$('#b-cmu-rgt-video-products-navigation .title .description').html($(data).attr('video.step.product.description'));
					}
				});
				productTimer = setTimeout($.proxy(timerProduct, _this), productTempo);
			}
			function timerProduct(){
				
				if (productIndex >= (productCount - 1)) 
					productIndex = 0;
				else 
					productIndex++;				
				changeProduct(productIndex, this);
					$('.prod-selected').removeClass('prod-selected');
				$('#slideshow_' + (productIndex)).addClass('prod-selected');
					$('#b-cmu-rgt-video-products-list li').animate({
						opacity: 0.4}, 0);
					$('#b-cmu-rgt-video-products-list li.prod-selected').animate({
						opacity: 1}, 0);
			}
			productTimer = setTimeout($.proxy(timerProduct, this), productTempo);
			$('#b-cmu-rgt-video-products-navigation a.next').click($.proxy(function(event){
				event.preventDefault();
				if (productIndex < (productCount - 1)) {
					changeProduct(++productIndex, this);
				}
			}, this));
			$('#b-cmu-rgt-video-products-navigation a.previous').click($.proxy(function(event){
				event.preventDefault();
				if (productIndex > 0) {
					changeProduct(--productIndex, this);
				}
			}, this));
			
		},
		
		buildTrackers: function(url){
			var _this = this;
			var pattern = this.context.template.video.step;
			this.context.xml.getPage('[url="' + url + '"][type="video"]').find('trackers tracker').each(function(i){
				$('#b-cmu-rgt-trackers').append('<img src="'+$(this).text()+'" border="0" width="1" height="1" alt="" />');
			});
		},
		
		//-----------------------------------------------------------
		//	Layout Handlers
		//-----------------------------------------------------------
		
		handlerCategorySelect: function(event){
			event.preventDefault();
			var url = $(event.currentTarget).attr('href');
			var match = url.match(/.*\/([^\.]+\.aspx)/);
			
			if (match) {
				url = match[1];
			}
			$.address.value(url);
			History.push(url);
			$.proxy(this.triggerCategorySelect(event.data.section), this);
		},
		
		handlerVideoSelect: function(event){
			event.preventDefault();
			event.stopPropagation();
			var url = $(event.currentTarget).attr('href');
			var match = url.match(/.*\/([^\.]+\.aspx)/);
			
			if (match) {
				url = match[1];
			}
			$.address.value(url);
			History.push(url);
			$.proxy(this.triggerVideoSelect(url), this);
		},
		
		triggerVideoYTAPI: function(url){
			var _this = this;
			var steps = [];
			this.context.xml.getPages('[type="video"][url="' + url + '"]').find('steps step timestamp').each(function(i){
				if (i < 4) 
					steps.push($(this).text());
			})
			this.context.ytapi.steps = steps;
			this.context.ytapi.currentStep = 1;
			this.context.ytapi.update = function(){
				t = this.time();
				for (i = 0; i < this.steps.length; i++) {
					if (this.currentStep - 1 != i && t >= this.steps[i] && (i == this.steps.length - 1 || t < this.steps[i + 1])) {
						this.currentStep = i + 1;
						$('#b-cmu-rgt-video-steps li').each(function(j){
							$(this).removeClass('selected');
							if (j == i) 
								$(this).addClass('selected');
						});
						_this.buildVideoStep(url, i + 1);
						_this.buildVideoStepProducts(url, i + 1);
					}
					
				};
							};
			
			$('#b-cmu-rgt-video-steps a').each(function(i){
				$(this).bind('click', {
					step: i + 1
				}, $.proxy(_this.handlerVideoStep, _this));
			});
		},
		
		handlerVideoStep: function(event){
			event.preventDefault();
			$.proxy(this.triggerVideoStep(event.data.step), this);
		},
		
		triggerVideoStep: function(step){
			var ytapi = this.context.ytapi;
			ytapi.seek(ytapi.steps[step - 1]);
			/*
			 if (ytapi.time() < ytapi.steps[ step-1 ] || ytapi.steps.length == step || ytapi.time() > ytapi.steps[ step ]) {
			 ytapi.seek(this.context.ytapi.steps[ step-1 ]);
			 }
			 */
		},
		
		//-----------------------------------------------------------
		// Layout Triggers
		//-----------------------------------------------------------
		
		triggerVideoSelect: function(url){
			this.pageVideo(url);
		},
		
		triggerCategorySelect: function(section){
			if (this.current != 'section') 
				this.pageSection();
			if (section) {
				$('#b-cmu-lft-menu-selector li').each(function(){
					if ($(this).find('div').hasClass(section)) 
						$(this).addClass('selected');
					else 
						$(this).removeClass('selected');
				});
				$('#b-cmu-rgt-categories li').each(function(){
					if ($(this).find('div').hasClass(section)) 
						$(this).attr('class', 'selected');
					else 
						$(this).attr('class', 'unselected');
				});
				this.buildVideoSelector(section);
				this.buildSpotlightVideoSelector(section);
			}
		}
	};
	
	//===================================================================
	
	// to global
	window.CoachingMakeUP = new CMU();
	window.onYouTubePlayerReady = function(){
		window.CoachingMakeUP.ytapi.init();
	}	
	/**
	 * Track a page view, but not the first one
	 */
	window.gaCMUPage = function(pageID){
		if (typeof window.trackedFirstPage !== 'undefined') {
			try {
                            pageTracker._trackPageview(pageID);
			} catch (ex) {
			}
		} else {
			window.trackedFirstPage = true;
		}
	};
	/**
	 * Track an event
	 */
	window.gaCMUEvent = function(category, action, opt_label, opt_value){
		category = (typeof category === "string") ? category : 'undefined';
		action = (typeof action === "string") ? action : 'click';
		opt_label = (typeof opt_label === "string") ? opt_label : 'click';
		opt_value = (isNaN(parseInt(opt_value))) ? undefined : parseInt(opt_value);
		try {
			pageTracker._trackEvent(category, action, opt_label, opt_value);
		} catch (ex) {}
	};
	/**
	 * Track YT event
	 */
	window.onYTStateChange = function(state) {
		var		event = undefined;

		window.lastYTState = (typeof window.lastYTState !== "undefined") ? window.lastYTState : undefined;
		switch(state) {
			case	0 :
				event = "ended";
				break;
			case	1 :
				event = "play";
				break;
			case	2 :
				event = "pause";
				break;
			default :
				break;
		}
		if (typeof event === "undefined") {
			return;
		}
		if (event !== window.lastYTState) {
			window.gaCMUEvent('player', event, window.YTUrl);
			window.lastYTState = event;
		}
	};
	window.onYTPlaybackQualityChange = function(quality) {
		if (typeof quality === "undefined") {
			return;
		}
		window.lastYTQuality = (typeof window.lastYTQuality !== "undefined") ? window.lastYTQuality : undefined;
		if (quality !== window.lastYTQuality) {
			window.gaCMUEvent('playerQuality', quality, window.YTUrl);
			window.lastYTQuality = quality;
		}
	};
	var productCount = $('#b-cmu-rgt-video-products-list li').length;
	var prodtimer
			
})(jQuery);

if ($('#p-cmu')) {
	$().ready(function(){
		CoachingMakeUP.config.base = '/';
		//CoachingMakeUP.config.base = 'http://www.gemeylocal.com/';
		CoachingMakeUP.config.files.pages = 'pages.xml';
		CoachingMakeUP.config.files.template = 'template.html';
		CoachingMakeUP.load();
	});
}

