var flash_version = {major: 0, minor: 0, release: 0};
var IE6 = false;
var IE7 = false;
var IE8 = false;
var IE_CSS3 = false;
var debugging = true;
var tele_box_confirmation;
var CDNPATH = 'http://cdn1.horoscope.fr/';

$(document).ready(function() {
	IE6 = $.browser.msie && $.browser.version.indexOf('6.') != -1;
	IE7 = $.browser.msie && $.browser.version.indexOf('7.') != -1;
	IE8 = $.browser.msie && $.browser.version.indexOf('8.') != -1;

	if (typeof(swfobject) != 'undefined') flash_version = swfobject.getFlashPlayerVersion();

	IE_CSS3 = $.browser.msie && !(IE6 || IE7 || IE8);
});

var debug = function(string) {
	if (debugging && typeof console != 'undefined' && typeof console.log == 'function'){
		console.log(string);
	}
};
var warn = function(string) {
	if (debugging && typeof console != 'undefined' && typeof console.warn == 'function'){
		console.warn(string);
	}
};
var info = function(string) {
	if (debugging && typeof console != 'undefined' && typeof console.info == 'function'){
		console.info(string);
	}
};
var ccount = function() {
	if (debugging && typeof console != 'undefined' && typeof console.count == 'function'){
		console.count();
	}
};

var track_page = function(_page) {
	try {
		var pageTracker = _gat._getTracker(ga_ID);
		pageTracker._trackPageview(_page);
	} catch(err) {}
};

// Classes
(function($) {
	// TeleBox - ModalBox
	TeleBox = function(options){
		return this.init(options);
	};

	TeleBox.prototype = {
		IE: $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
		sizes: {mask: {width: '100%', height: '100%'}, box: {}},
		mask_parent: null,
		box_parent: null,
		mask: null,
		box: null,
		cross: null,
		loadURL: false,
		hasMask: true,
		hasCross: true,
		name: '',
		box_border: 8,
		data: {},
		multi: false,
		visible: false,
		doClose: true,
		hasScroll: {'left': false, 'top': false},
		open_slide: false,
		loaded: false,
		
		init: function(opt) {
			options = opt;

			this.settings   = {delay: 0, margin: 10, width: 'auto', mask_id: 'tele_box_parent', box_id: 'tele_box', close_id: 'tele_box_close', cross_txt: '<strong>Fermer</strong>', box_class: 'ui-corner-all ui-telelab-shadow-black', mask_class: '', loader_class: 'loading', content: '', cross_img: '/images/icons/close.png', onInit: function(){}, onLoad: function(){}, onAppend: function() {}, onBeforeOpen: function() {}, onOpen: function() {}, onClose: function() {}, onAfterClose: function() {}, onPosition: function() {}};
			this.mask_css   = {'position': 'fixed', 'left': '0px', 'top': '0px', 'background-color': '#222222', 'opacity': 0.80, 'display': 'none', 'z-index': 10};
			this.box_css    = {'position': 'fixed', 'left': '0px', 'top': '0px', 'border': 'solid 4px transparent', 'background-color': '#F7F4EF', 'padding': '10px', 'opacity': 1.0, 'font-size': '12px', 'display': 'none', 'z-index': 20};
			this.cross_css  = {'position': 'fixed', 'display': 'none', 'padding': '6px 7px', 'z-index': 30};

			this.loadURL    = false;
			this.hasMask    = true;
			this.hasCross   = true;
			this.isCrossImg = false;
			
			this.mask_parent = null;
			this.box_parent  = null;
			
			this.parent = null;
			
			this.hasScroll.left = ($(document).width() > $(window).width());
			this.hasScroll.top  = ($(document).height() > $(window).height());
			
			this.options = $.extend(this.settings, options);
			this.options.mask_css  = $.extend(this.mask_css, this.options.mask_css || {});
			this.options.box_css   = $.extend(this.box_css, this.options.box_css || {});
			this.options.cross_css = $.extend(this.cross_css, this.options.cross_css || {});

			//console.log(this.options.mask_css);
			if (this.options.loadURL != undefined) this.loadURL = this.options.loadURL;
			if (this.options.hasCross != undefined) this.hasCross = this.options.hasCross;
			if (this.options.hasMask != undefined) this.hasMask = this.options.hasMask;
			if (this.options.isCrossImg != undefined) this.isCrossImg = this.options.isCrossImg;
			if (this.options.content != undefined) this.content = this.options.content;
			if (this.options.name != undefined) this.name = '_' + this.options.name;
			if (this.options.data != undefined) this.data = this.options.data;
			if (this.options.multi != undefined) this.multi = this.options.multi;
			if (this.options.doClose != undefined) this.doClose = this.options.doClose;
			if (this.options.box_border != undefined) this.box_border = this.options.box_border;
			if (this.options.open_slide != undefined) this.open_slide = this.options.open_slide;
			
			this.mask_parent = document.body;			

			if (this.hasMask)
				mask  = '<div id="' + this.options.mask_id + this.name + '" class="' + this.options.mask_class + '"></div>';

			box     = '<div id="' + this.options.box_id + this.name + '" class="' + this.options.box_class + '"><div class="tele_content" style="position: relative;"></div></div>';
			
			if (this.hasCross) {
				if (this.isCrossImg)
					cross = '<img class="button hover" id="' + this.options.close_id + this.name + '" src="' + this.options.cross_img + '">';
				else	
					cross = '<a class="button hover secondary ui-telelab-corner-all" id="' + this.options.close_id + this.name + '">' + this.options.cross_txt + '</a>';
			}

			if (this.options.box_parent) {
				this.box_parent = $(this.options.box_parent);
				//this.options.mask_css.width  = this.mask_parent.width();
				//this.options.mask_css.height = this.mask_parent.height();
				this.options.onInit();
			}
			
			//if (this.options.mask_parent) {
			//	this.mask_parent = $(this.mask_parent);
				//this.options.mask_css.width  = this.mask_parent.width();
				//this.options.mask_css.height = this.mask_parent.height();
			//}

			this.box_parent = $(this.options.box_parent || document.body);

			if (this.hasMask) {
				this.mask  = $(mask).css(this.options.mask_css).appendTo(this.mask_parent);
				this.mask.queue('fx');
				this.mask.css({'width': this.sizes.mask.width, 'height': this.sizes.mask.height});
			} else
				this.mask = $('body');

			this.box    = $(box).css(this.options.box_css).appendTo(this.box_parent).css({'position': 'fixed'});
			if (this.hasCross) this.cross  = $(cross).css(this.options.cross_css).appendTo(this.box_parent);
			
			if (this.hasMask) this.mask.queue('fx');
			this.box.queue('fx');
		},
		
		exec: function(elt) {
			if (this.hasMask) this.mask.addClass(this.options.loader_class).fadeIn('fast');
			
			elt = elt || this.content;
			current = this;

			var _content = $('.tele_content', this.box);
			_content.html('');
			
			this.box.css({'width': (this.box.width() || 'auto'), 'height': (this.box.height() || 'auto')});
			if (elt) {
				if (this.loadURL) {
					$.get(
						elt.href || elt, 
						{}, 
						function(data, textStatus) {
							if (textStatus == 'success') { 
								current.content = data;
								_content.html(data);
								current.options.onAppend(current);
								current._show();
							}
						}
						, 'html'
					);
				} else {
					is_img = false;
					is_embed = false;
					if ($(elt).attr('tagName') == 'A' && $(elt).children('img').length == 1) {
						img = $(elt).children('img').get(0);
						is_img = true;
					}		

					if ($(elt).attr('tagName') == 'IMG') {
						img = elt;
						is_img = true;
					}
					
					if ($(elt).attr('tagName') == 'DIV' && $(elt).children('embed').length == 1) {
						embed = $(elt).children('embed').get(0);
						is_embed = true;
					}				

					if (is_img) {
						if (this.hasMask) this.mask.css({'opacity': 0.5});
					  this.box.css({'background-color': 'transparent', 'border': 'none', 'padding': 0});
						$(img).attr('id', 'tele_img').bind('load', this, this.appear);
						this.content = $(elt);
						//this._show();
						$(elt).appendTo($('.tele_content', this.box));
						this.options.onAppend(this);
					} else {
						this.parent = $(elt).parent();
						elt = $(elt).detach().css({'display': 'block'});

						this.content = elt;
						$('.tele_content', this.box).append(elt);
						if (is_embed) {
							if ($('[src]', embed).length) {
								var so = new SWFObject($(embed).attr('src'), $(elt).attr('id'), '900', '450', '8', 'transparent');
								so.addParam('allowScriptAccess', 'always');
								so.addParam('menu', 'false');
								so.addParam('wmode', 'transparent');
								loadFlash(so, $(elt).attr('id'));
							}
						}
						this.options.onAppend(this);
						this._show();
					}
				}

				this.options.onLoad(this);

				return this;
			}
		},
		
		option: function(options) {
			$.extend(true, this.options, options);
		},
		
		appear: function(event) {
			if (event && event.data) {
				current = event.data;
			} else {
				return;
			}

			current._show();
			
			return this;
		},
			
		disappear: function(event) {
			if (event && event.data) {
				current = event.data;
			} else {
				return;
			}
			
			current._hide();
			
			return this;
		},
		
		update: function(animate, opts) {
			var opts = opts || {};

			if (this.hasMask) this.mask.css({'width': this.sizes.mask.width, 'height': this.sizes.mask.height});

			if (IE6 || IE7) {
				_h = 0;
				this.box.children('*').children('*').each(function() { _h += $(this).height(); });
				width  = opts.width || this.box.width() || this.box.children().width() || this.box.children().outerWidth();
				height = opts.height || _h;
			} else {
				width  = opts.width || this.box.width() || this.box.outerWidth();
				height = opts.height || this.box.height() || this.box.outerHeight();
			}

			if (this.hasCross) {
				c_width  = this.cross.outerWidth(); 
				c_height = this.cross.outerHeight();
			}
			
			_margin = this.options.margin * 2;

			_margin_w = 0; _margin_h = 0;
			//if (this.box_parent.get(0).tagName == 'body' && this.box_parent
			var min_height = (this.box_parent.outerWidth() - _margin);										
			if (width > min_height && (this.box_parent.get(0).tagName != 'BODY' || (this.box_parent.get(0).tagName == 'BODY' && this.box_parent.outerWidth() >= $(window).width()))) {
				width = this.box_parent.outerWidth() - _margin;
				_margin_w = _margin;
			}
			
			var min_height = (this.box_parent.outerHeight() - _margin);
			if (height > min_height && (this.box_parent.get(0).tagName != 'BODY' || (this.box_parent.get(0).tagName == 'BODY' && this.box_parent.outerHeight() >= $(window).height()))) {
				height = this.box_parent.outerHeight() - _margin;
				_margin_h = _margin;
			}

			var left = (this.box_parent.outerWidth() + _margin_w - width) / 2;
			
			/*
			if (left < this.options.margin) {
			  left = this.options.margin;
				width = this.mask.width() - (this.options.margin * 2);
			}
			*/
			
			var top  = ((this.mask.height() + _margin_h - height) / 2);
			//debug(this.mask.height() + ' + ' + _margin_h + ' - ' +  height);
			pos = $(this.box_parent).attr('id') == 'body' && this.box_css.position != 'absolute' ? 'fixed' : 'absolute';

			if (pos == 'absolute') 
				top += $(window).scrollTop();
		
			//top = c_height + 2 + margin;
			/*
			if (top < this.options.margin) {
			  top = this.options.margin;
				height = this.mask.height() - (this.options.margin * 2);
			}
			*/
			var c_right = c_top = 0;
			if (this.hasCross) {
				c_right = this.cross_css.left || (left - this.box_border);
				c_top   = this.cross_css.top || (top - c_height - (this.box_border || 10));

				if (c_top < 0) {
					t_diff = 10 + Math.abs(c_top);
					c_top = 10;
					top += t_diff;
				}
			}
			
			var ease_w = ease_h = 10;

			if (animate) {
				var opts = $.extend({'left': left, 'top': top, 'width': width}, opts);
				if (!IE7 && !IE8)
					opts = $.extend({'height': 'auto'}, opts);
				this.box.animate(opts);
			} else {
				var opts = $.extend({'position': pos, 'left': left, 'top': top, 'width': width, 'height': 'auto'}, opts);
				this.box.css(opts);
			}
			// alert(top);
			if (this.hasCross) {
				// Handling window ScrollLeft and ScrollTop
				//debug((this.box.height() + top) + ' > ' + $(window).height());
				if (this.hasScroll.top == false && ((this.box.height() + top) > $(window).height()))
					c_right -= 16;
			}
			
			//this.box.animate({'left': (left - (ease_w / 2)) + 'px', 'top': (top - (ease_w / 2)) + 'px', 'width': (width + ease_w) + 'px', 'height': (this.box.height() + ease_h)}, 'fast');
			//this.box.delay('fast').animate({'position': pos, 'left': left + 'px', 'top': top + 'px', 'width': width + 'px', 'height': 'auto'}, 'fast');
			if (this.hasCross) {
				this.cross.css({'position': pos});
				if (animate)
					this.cross.animate({'right': c_right + 'px', 'top': c_top + 'px'});
				else
					this.cross.css({'right': c_right + 'px', 'top': c_top + 'px'});
			}
			//console.log('window_width : ' + this.mask.width() + ' - box_width : ' + width + ' - left : ' + this.box.css('left'));
			

			this.options.onPosition(this, left, top, c_right, c_top);

			return this;
		},
		
		_show: function(update, opts) {
			var opts = opts || {};
			var tb = this;
			
			if (update == undefined)
				update = true;
			//this.loader.fadeOut('fast');
			
			this.options.onBeforeOpen(this);
			
			if (update) {
				if (IE7 || IE8) {
					//this.update();
					//this._fireShow();
					
					var _fireShow = tb._fireShow;
					var _update = tb.update;
					
					result = setTimeout(function() { tb._fireShow(); tb.update(false, opts); }, 100, tb);
				}
					
				else {

					//result = this._fireShow().update();
					result = setTimeout(function() { tb.update(false, opts); tb._fireShow(); }, 100, tb);
				}
			} else {
				this._fireShow();
			}
		},
		
		_fireShow: function() {
			this.visible = true;
		
			if (this.hasMask) {
				if (this.doClose)
					this.mask.bind('click', this, this.disappear);
					
				this.mask.removeClass(this.options.loader_class).delay(110).fadeIn(100);
			}
				
			if (this.hasCross && this.doClose) this.cross.bind('click', this, this.disappear);
			
			var widget = this;
			var onOpen = function() { widget.settings.onOpen(widget); };
			
			if ($.browser.msie) {
				if(this.open_slide){
					var widget = this;
					setTimeout(function(){
						_t = widget.box.css('top').replace('px','');
						_h = widget.box.css('height').replace('px','');
						widget.box.css({'opacity': 'none', 'display': 'block','top':'-'+_h+'px'}).stop().animate({'top':_t+'px'},500,onOpen);
					}, 300);
				} else {
					this.box.css({'opacity': 'none', 'display': 'block'});
					// this.settings.onOpen(widget);
					setTimeout(onOpen, 200);			
				}
			} else {
				if(this.open_slide){
					this.box.show(); // patch ff sur mac ( top pas detecté si display none)
					_t = this.box.css('display','block').css('top').replace('px','');
					this.box.hide(); // suite patch ff sur mac
					_h = this.box.css('height').replace('px','');
					this.box.css({'opacity': 'none', 'display': 'block','top':'-'+_h+'px'}).stop().animate({'top':_t+'px'},500,onOpen);
				} else 
					this.box.fadeIn('fast', onOpen);
			}
			
			if (this.hasCross) this.cross.delay(30).fadeIn('fast');

			return this;
		},
		
		_hide: function() {		
			var tb = this;
			
			if (this.hasMask) this.mask.unbind('click').fadeOut('fast');			
			
			if ($.browser.msie) {
				if(this.open_slide){
					_h = this.box.css('height').replace('px','');
					_widget = this;
					this.box.stop().animate({'top':'-'+parseInt(_h+100)+'px'},500,function(){
						_widget.box.hide();
						if (_widget.hasCross) _widget.cross.hide();
						_widget.afterHide(tb);
					});
				} else {
					this.box.css({'opacity': 'none', 'display': 'none'});
					if (this.hasCross) this.cross.css({'opacity': 'none', 'display': 'none'});
					this.afterHide(tb);
				}
			} else {
				if(this.open_slide){
					_h = this.box.css('height').replace('px','');
					_widget = this;
					this.box.stop().animate({'top':'-'+parseInt(_h+100)+'px'},500,function(){
						_widget.box.hide();
						_widget.afterHide(tb);
						if (_widget.hasCross) _widget.cross.fadeOut('fast');
					});
				} else {
					this.box.fadeOut('fast');
					var _afterHide = tb.afterHide;
					result = setTimeout(function() { _afterHide(tb); }, 100, tb);
					if (this.hasCross) this.cross.fadeOut('fast');
				}
			}
			this.options.onClose(this);
		},
		
		afterHide: function(tb) {		
			if (tb && typeof(tb) == 'object' && tb.multi != 'undefined') {
				if (tb.multi == true && tb.parent != null)
					tb.content.css({'display': 'none'}).detach().appendTo(tb.parent);
				tb.visible = false;

				tb.options.onAfterClose(tb);
			}
		},
		
		_getTop: function(){
		
			var opts = opts || {};
			if (this.hasMask) this.mask.css({'width': this.sizes.mask.width, 'height': this.sizes.mask.height});
			if (IE6 || IE7) {
				_h = 0;
				this.box.children('*').children('*').each(function(){ _h+=$(this).height();});
				width  = opts.width || this.box.width() || this.box.children().width() || this.box.children().outerWidth();
				height = opts.height || _h;
			} else {
				width  = opts.width || this.box.width() || this.box.outerWidth();
				height = opts.height || this.box.height() || this.box.outerHeight();
			}

			if (this.hasCross) {
				c_width  = this.cross.outerWidth(); 
				c_height = this.cross.outerHeight();
			}
			
			_margin = this.options.margin * 2;

			_margin_w = 0; _margin_h = 0;
			if (width > (this.box_parent.outerWidth() - _margin)) {
				width = this.box_parent.outerWidth() - _margin;
				_margin_w = _margin;
			}

			if (height > (this.box_parent.outerHeight() - _margin)) {
				height = this.box_parent.outerHeight() - _margin;
				_margin_h = _margin;
			}
			
			var left = (this.box_parent.outerWidth() + _margin_w - width) / 2;
			var top  = ((this.mask.height() + _margin_h - height) / 2);
			pos = $(this.box_parent).attr('id') == 'body' && this.box_css.position != 'absolute' ? 'fixed' : 'absolute';

			if (pos == 'absolute') 
				top += $(window).scrollTop();
				
			var c_right = c_top = 0;
			if (this.hasCross) {
				c_right = this.cross_css.left || (left - this.box_border);
				c_top   = this.cross_css.top || (top - c_height - (this.box_border || 10));

				if (c_top < 0) {
					t_diff = 10 + Math.abs(c_top);
					c_top = 10;
					top += t_diff;
				}
			}
			return top;
		},
		
		_change: function(new_content,time,type) {
			if(typeof type=="undefined") type = 1;
			var widget = this;
			var onOpen = function() { widget.settings.onOpen(widget); };
			var _box = this.box;
			var _boxparent = this.box_parent;
			var _content = $('.tele_content', this.box);
			_w = this.box.outerWidth(); _h = this.box.outerHeight();
			_t = _boxparent.outerHeight()/2; _l = _boxparent.outerWidth()/2;
			// debug('width : '+_w);			debug('height : '+_h);			debug('left : '+_l);			debug('top : '+_t);
			if(type==1){
				this.box.css('overflow','hidden').animate({'width':'0px', 'height':'0px', 'left':_l, 'top':_t },time,function(){
					$.get(new_content,{},function(data, textStatus) {
															if (textStatus == 'success') { 
																current.content = data;
																_content.html(data);
																current.options.onAppend(current);
																current._show();
																_w = $('div:eq(0)',_content).outerWidth(); _h = $('div:eq(0)',_content).outerHeight();
																_t = widget._getTop(); _l = (_boxparent.outerWidth() - _w)/2;
																_box.animate({'width':_w+'px', 'height':_h+'px', 'left':_l, 'top':_t },time,function(){_box.css('overflow','visible'); onOpen();});
															}
														}, 'html');
				});
			} else if(type==2){
				this.box.css('overflow','hidden').animate({'height':'0px'},time,function(){
					$.get(new_content,{},function(data, textStatus) {
															if (textStatus == 'success') { 
																current.content = data;
																_content.html(data);
																current.options.onAppend(current);
																current._show();
																_w = $('div:eq(0)',_content).outerWidth(); _h = $('div:eq(0)',_content).outerHeight();
																_t = widget._getTop(); _l = (_boxparent.outerWidth() - _w)/2;
																_box.css({'width':_w+'px', 'left':_l}).animate({'height':_h+'px', 'top':_t },time,function(){_box.css('overflow','visible'); onOpen();});
															}
														}, 'html');
				});
			} else if(type==3){ 
				this.box.stop().animate({'top':'-'+_h+'px'},time,function(){ 
					$(this).hide();
					if(typeof(new_content)!='object'){
						$.get(new_content,{},function(data, textStatus) {
																if (textStatus == 'success') { 
																	current.content = data;
																	_content.html(data);
																	current.options.onAppend(current);
																	// current._show();
																	_w = $('div:eq(0)',_content).outerWidth(); _h = $('div:eq(0)',_content).outerHeight();
																	_t = widget._getTop(); _l = (_boxparent.outerWidth() - _w)/2; 
																	
																	
				

																	_box.css({'width':_w+'px', 'left':_l,'display':'block'}).animate({'top':_t+'px'},(time*2),function(){ onOpen();});
																}
															}, 'html');
					} else {
						$('.tele_content', this.box).append(new_content);
						current.options.onAppend(current);
						current._show();
						_w = $('div:eq(0)',_content).outerWidth(); _h = $('div:eq(0)',_content).outerHeight();
						_t = widget._getTop(); _l = (_boxparent.outerWidth() - _w)/2;
						_box.css({'width':_w+'px', 'left':_l}).animate({'height':_h+'px', 'top':_t },time,function(){_box.css('overflow','visible'); onOpen();});
					}
				});
			}
		},
		
		_destroy: function() {
			this.box.remove();
			if (this.hasCross) this.cross.remove();
			if (this.hasMask) this.mask.remove();
		}
	}

})(jQuery);

var displayConfirmationCloseFunction = function() { tele_box_confirmation._hide(); };
var displayConfirmationFlagFunction  = function() { $(this).addClass('data-clicked'); }

var displayNotification = function(e) {
	tele_box_confirmation = null;
	e.data = $.extend(true, {'name': 'message', 'icon': null, 'content': '<div id="confirmation_box" class="content-box ui-telelab-corner-all" style="display: none; margin: 0;"><div class="content-box-header"><h3>' + e.data.title + '</h3></div><div class="question content-box-content"></div><div class="clear"></div><' + (IE7 ? 'div' : 'span') + ' class="answer"><button class="primary_button button action primary ui-telelab-corner-all"><h3>Oui</h3></button><button class="secondary_button button action primary ui-telelab-corner-all"><h3>Non</h3></button></' + (IE7 ? 'div' : 'span') + '></div>', 'hide': {'primary': true, 'secondary': true}, 'loader_class': 'loading circular', 'tele_box': {'mask_parent': e.data.tele_box && e.data.tele_box.mask_parent || document.body, 'box_parent': e.data.tele_box && e.data.tele_box.box_parent || document.body, 'box_class': 'telelab-corner-all-inner ui-telelab-shadow-darkgrey', 'box_css': {'position': 'absolute', 'padding': '0px', 'border': '0 none', 'overflow': 'auto', 'background-color': 'transparent', 'overflow': 'none'}, 'mask_css': {'z-index': 10, 'position': 'fixed', 'width': '100%'}}}, e.data);

	displayConfirmation(e);
}

var displayConfirmation = function(e) {
	data = $.extend(true, {'name': 'confirmation', 'tele_box': {'hasCross': false, 'isCrossImg': false, 'loadURL': false, 'cross_css': {'z-index': 70}, 'box_css': {'position': 'fixed', 'border': '0 none', 'background-color': '#FFFFFF', 'padding': '10px', 'opacity': 1.0, 'font-size': '12px', 'display': 'none', 'z-index': 60}, 'mask_css': {'z-index': 50, 'opacity': 0.90}, 'box_class': 'ui-telelab-corner-all ui-telelab-shadow-strong'}, 'icon': '/images/icons/opinion.png', 'message': 'Confirmez-vous votre choix ?', 'button': {'primary': 'Oui', 'secondary': null}, 'confirmFunction': $.noop, 'declineFunction': $.noop, 'hide': {'primary': false, 'secondary': true}, 'classes': {'primary': null, 'secondary': null}, 'delay': {'close': 0}, 'loader_class': '', 'content': '<div id="confirmation_box"><h2 class="question"></h2><span class="additional"></span><br class="clear" /><' + (IE7 ? 'div' : 'span') + ' class="answer"><button class="primary_button button action primary ui-telelab-corner-all"><h3>Oui</h3></button><button class="secondary_button button action primary ui-telelab-corner-all"><h3>Non</h3></button></' + (IE7 ? 'div' : 'span') + '></div>'}, e.data);

	if (data.doClose != 'undefined')
		doClose = data.doClose;
		
	box_css = $.extend({'position': 'fixed', 'border': '0 none', 'background-color': '#FFFFFF', 'padding': '10px', 'opacity': 1.0, 'font-size': '12px', 'display': 'none', 'z-index': 60}, data.tele_box && data.tele_box.box_css || {});


	if (tele_box_confirmation == null) {
		tele_box_confirmation = new TeleBox({
			/*name: 'confirmation',
			//isCrossImg: true,
			hasCross: false,
			data: data,
			cross_img: '/images/121/subscription/close.png',
			content: '<div id="confirmation_box"><h2 class="question"></h2><span class="additional"></span><br class="clear" /><' + (IE7 ? 'div' : 'span') + ' class="answer"><button class="primary_button button action primary ui-telelab-corner-all">Oui</button><button class="secondary_button button action primary ui-telelab-corner-all">Non</button></' + (IE7 ? 'div' : 'span') + '></div>',
			box_class: data.tele_box && data.tele_box.box_class,
			mask_css: {'z-index': 50, 'opacity': 0.90},
			box_css: box_css,
			doClose: doClose,
			cross_css: {'z-index': 70},*/
			
			name: data.name,
			isCrossImg: data.tele_box && data.tele_box.isCrossImg == true || false,
			hasCross: data.tele_box && data.tele_box.hasCross == true || false,
			data: data,
			cross_img: '/images/121/subscription/close.png',
			content: data.content,
			mask_parent: data.tele_box && data.tele_box.mask_parent || document.body,
			box_parent: data.tele_box && data.tele_box.box_parent || document.body,
			box_class: data.tele_box && data.tele_box.box_class,
			mask_css: data.tele_box && data.tele_box.mask_css,
			box_css: data.tele_box && data.tele_box.box_css,
			cross_css: data.tele_box && data.tele_box.cross_css,
			doClose: doClose,
			loader_class: data.loader_class,
			loadURL: data.tele_box && data.tele_box.loadURL || false,
			
			onAppend: function(tb) {
				data = tb.data;

				if (data.tele_box && data.tele_box.onAppend)
					data.tele_box.onAppend(tb);
			},
			onPosition: function(tb) {
				data = tb.data;
				
				if (data.tele_box && data.tele_box.onPosition)
					data.tele_box.onPosition(tb);
			},
			onBeforeOpen: function(tb) {
				data = tb.data;
				//debug(tb);
				if (data.tele_box && data.tele_box.onBeforeOpen)
					data.tele_box.onBeforeOpen(tb);
				
				if (data.icon) {
					var _icon = data.icon || '/images/icons/opinion.png';

					$('<img width="80" src="' + _icon + '" class="imgtofix icon_information_box" />').appendTo(tb.box);
				}
				
				$('#confirmation_box .question').removeAttr('style');
				if (typeof(data.message) == 'object' && data.message)
					data.message.detach().appendTo($('#confirmation_box .question')).fadeIn();
				else if (data.message)
					$('#confirmation_box .question').html(data.message);
				else
					$('#confirmation_box .question').css({'padding': '6px 0px'});
				
				if (data.message == '')	$('#confirmation_box .question').css({'display': 'none'});
				else if ($('#confirmation_box .question').not(':visible')) $('#confirmation_box .question').css({'display': 'block'});
				//alert(data.confirmFunction);
				if (data.button.primary) {
					$('#confirmation_box .primary_button').css({'display': 'inline'}).unbind('click').click(data.confirmFunction).click(displayConfirmationFlagFunction).children('h3').html(data.button.primary);
					if (data.classes.primary) $('#confirmation_box .primary_button').addClass(data.classes.primary);
				} else {
					$('#confirmation_box .primary_button').css({'display': 'none'});
				}

				if (data.hide.primary == true)
					$('#confirmation_box .primary_button').click(displayConfirmationCloseFunction);
					
				if (data.button.secondary) {
					$('#confirmation_box .secondary_button').css({'display': 'inline'}).unbind('click').click(data.declineFunction).click(displayConfirmationFlagFunction).children('h3').html(data.button.secondary);
					if (data.classes.secondary) $('#confirmation_box .secondary_button').addClass(data.classes.secondary);
				} else
					$('#confirmation_box .secondary_button').css({'display': 'none'});
				
				if (IE7 && data.button.secondary) {
					var buttons_width = $('#confirmation_box .primary_button').outerWidth(true) || 0 + $('#confirmation_box .secondary_button').outerWidth(true);
					var _left = ($('#confirmation_box .answer').outerWidth(true) - buttons_width) / 2;
					if (data.button.primary) $('#confirmation_box .primary_button').css({'margin-left': '+=' + _left});
				}
				
				if (data.hide.secondary == true)
					$('#confirmation_box .secondary_button').click(displayConfirmationCloseFunction);



						
			 	if (data.additional) {
					if (typeof(data.additional) == 'object')
						data.additional.detach().appendTo($('#confirmation_box .additional')).fadeIn();
					else
						$('#confirmation_box .additional').html(data.additional);
				}
			},
			onOpen: function(tb) {
				data = tb.data;

				if (data.tele_box && data.tele_box.onOpen)
					data.tele_box.onOpen(tb);
					
				if (data.delay && data.delay.close > 0)
					data.tele_box.timer_delay_close = setTimeout(function() { tele_box_confirmation._hide(); }, data.delay.close);
				//$('#confirmation_box .answer').center();
			},
			onClose: function(tb) {
				data = tb.data;

				if (data.tele_box && data.tele_box.onClose)
					data.tele_box.onClose(tb);

				if (data.declineFunction && $('#confirmation_box .button.data-clicked').size() == 0)
					data.declineFunction();
					
				if (typeof(data.tele_box.timer_delay_close) != 'undefined')
					clearTimeout(data.tele_box.timer_delay_close);
			},
			onAfterClose: function(tb) {
				data = tb.data;

				if (data.tele_box && data.tele_box.onAfterClose)
					data.tele_box.onAfterClose(tb);

				//debug($('#confirmation_box .additional').children());
					
				if (data.additional) {
					if (typeof(data.additional) == 'object')
						$('#confirmation_box .additional').children().css({'display': 'none'}).detach().appendTo(document.body);
					else
						$('#confirmation_box .additional').css({'display': 'none'}).html('');
				}
			}
		});
		tele_box_confirmation.exec();
	} else {
		tele_box_confirmation.data = data;
		//tele_box_confirmation.box.css({'width': 'auto', 'height': 'auto'});
		tele_box_confirmation._show(true, {'width': box_css.width || null, 'height': box_css.height || null});
	}

};

/*if ($.widget) {*/
	$.widget('ui.tooltip', {
		// default options
		options: {position: {selector: null}, events: {tooltip: true, hover: true, fixed: false}, direction: null, text: '', align: 'center', left: 0, top: 0, valign: 'bottom', onCreate: function(){}, onClick: function(){}},
		z_index: 50,
		timer: null,
		direction: null,
		fadeInTime: 50,
		fadeOutTime: 350,
		tooltip: null,
		block: false,
		
		_create: function() {},
		
		_init: function() {		
			var widget = this;

			element = this.element;
			
			this.direction = this.options.direction || this.options.align;
			this.z_index   = this.options['z-index'] || this.z_index;

			var fade_in  = this._fadeIn;
			var fade_out = this._fadeOut;
			var redraw   = this.redraw;
	
			if (this.options.events.tooltip == false)
				this.fadeOutTime = 50;
	
			if (element.attr('id')) {
				var id = element.attr('id');
			} else {
				if (element.parent().attr('id'))
					var id = element.parent().attr('id') + '_' + element.get(0).tagName.toLowerCase();
				else
					var id = $(element.parents('[id]').get(0)).attr('id') + '_' + element.get(0).tagName.toLowerCase();
			}

			if (typeof(this.options.text) == 'function')
				var text = this.options.text(element);
			else
				var text = this.options.text;
	
			if (!text || text == '' || (typeof(text) == 'object' && text.length == 0))
				return;

			element.attr('id', id).data('widget', widget);

			var fadeIn = function(e) { if (widget.block == true) return null; $('#tooltip_' + $(this).attr('id')).data('hover', true); clearTimeout(widget.timer); widget.timer = setTimeout(function() { widget._fadeIn(id); /*fade_in(id);*/ }, widget.fadeInTime); redraw(id, widget); };
			var fadeOut = function(e) { $('#tooltip_' + $(this).attr('id')).data('hover', false); clearTimeout(widget.timer); widget.timer = setTimeout(function() { fade_out(id); }, widget.fadeOutTime); };
			
			if (this.options.events.hover == true) {
				element.hover(
					fadeIn,
					fadeOut
				);
			}
			
			this.fadeIn = fadeIn;
			this.fadeOut = fadeOut;
			
			var t = $('<div id="tooltip_' + id + '" class="telelab-tooltip ui-telelab-corner-all ui-telelab-widget"><div class="telelab-tooltip-pointer-' + this.direction + '"><div class="telelab-tooltip-pointer-' + this.direction + '-inner"></div></div></div>');
			
			widget.tooltip = t;
	
			t.appendTo(document.body).css({'z-index': this.z_index}).hide().prepend(text);
	
			this.options.onCreate(t);
	
			this.drawBorder(t);
			
			/*if (this.direction == 'top' || this.direction == 'bottom') {
				var b_width = p.css('borderBottomWidth');
				var b_color = t.css('backgroundColor');
				p.css('border-bottom', b_width + ' solid ' + b_color);
			} else if (this.direction == 'left' || this.direction == 'right') {
				var b_width = p.css('border' + _direction + 'Width');
				var b_color = t.css('backgroundColor');
				p.css('border-' + this.direction, b_width + ' solid ' + b_color);
			}*/
	
			t.data('hover', false).data('position', false).data('align', this.options.align).data('valign', this.options.valign)/*.data('ui', this)*/;
			
			if (this.options.events.tooltip == true) {
				t.hover(
					function(e) { $(this).data('hover', true); },
					function(e) { $(this).data('hover', false); widget.timer = setTimeout(function() { fade_out(id); }, widget.fadeOutTime, $(this).attr('id').replace(/tooltip_/, '')); }
				);
			}
				
			if (this.options.events.fixed == true) {
				this.redraw(id, widget);
				this._fadeIn(id);
			}

			t.click(widget.options.onClick);
			
			//$(this).data('tooltip', t);
			//delete(p); delete(t); delete(b_width); delete(b_color);
			return this;
		},
	
		_fadeIn:  function(id) { t = $('#tooltip_' + id).css({'opacity': 1}); t.stop().fadeIn('fast').siblings('.telelab-tooltip').hide(); },
		_fadeOut: function(id) { t = $('#tooltip_' + id).css({'opacity': 1}); if (t.data('hover') == false) t.stop().fadeOut('fast'); },
		
		drawBorder: function(t) {
			var p = t.children(':last').children().removeAttr('style');
			var _direction = this.direction.substr(0, 1).toUpperCase() + this.direction.substr(1, this.direction.length - 1).toLowerCase();
			var b_width = p.css('border' + _direction + 'Width');
			var b_color = t.css('backgroundColor');
			p.css('border-' + this.direction, b_width + ' solid ' + b_color);
			
			return this;
		},
		
		redraw: function(id, widget) {
			t = $('#tooltip_' + id).css({left: 0, top: 0}); elt = $('#' + id);

			if (t.data('position') == false) {
				at_align = t.data('align');
				if (t.data('align') == 'left')
					at_align = 'right';
				else if (t.data('align') == 'right')
					at_align = 'left';
					
				at_valign = t.data('valign');
				if (t.data('align') == 'center') {
					if (t.data('valign') == 'bottom')
						at_valign = 'top';
					if (t.data('valign') == 'top')
						at_valign = 'bottom';
				}

				offset = {l: '' + widget.options.left, t: '' + widget.options.top};
	
				if (offset.l.indexOf('px') != -1)
					offset.l = offset.l.replace(/px/, '');
				if (offset.t.indexOf('px') != -1)
					offset.t = offset.t.replace(/px/, '');

				obj = $('#' + id);

				if (widget.options.position.selector != null) {
					if ($('#' + id).find(widget.options.position.selector).length)
						obj = $('#' + id).find(widget.options.position.selector);
					else
						obj = $('#' + widget.options.position.selector);

					if (obj.attr('id')) {
						id = obj.attr('id');
					} else {
						id = 'tooltip_selector_' + (obj.parent().attr('id') || obj.parent().parent().attr('id')) + '_' + obj.get(0).tagName.toLowerCase();
						obj.attr('id', id);
					}
				}
				
				// offset.l = $(window).scrollLeft() + parseInt(offset.l);
				// offset.t = $(window).scrollTop() + parseInt(offset.t);

				t.position({
					of: obj,
					my: at_align + ' ' + at_valign,
					at: t.data('align') + ' ' + t.data('valign'),
					offset: offset.l + ' ' + offset.t,
					collision: 'fit fit',
					using:function(r){
						_top = r.top+$(window).scrollTop();
						_left = r.left+$(window).scrollLeft();
						$(this).css({'top':_top+'px', 'left':_left+'px'});
					}
				});
			}
		},
		
		destroy: function() {
			$.Widget.prototype.destroy.apply(this, arguments); // default destroy
			// now do other stuff particular to this widget
			
			$('#tooltip_' + this.element.attr('id')).each(deleteElementProps).remove();
		}
	});
	
	$.extend($.ui.tooltip, {
		version: "@VERSION"
	});
	
	$.widget('ui.drawing', {
		// default options
		options: {onInit: function(){}, onClose: function(){}, onSelectCard: function(){}},
		cards: [],
		interpretations: [],
		cards_settings: {total: null, width: null, height: null, decal: null, max_top: 0, min_top: 0, clicked: 0, selectable: 0, path: null, ext:null, back_path: null},
		cards_selected: '',
		cards: [],
		cards_class: 'card',
		shuffle: false,
		shuffle_text: 'Mélanger avant de tirer vos cartes',
		shuffle_text_bis: 'Mélanger',
		tooltip_width: false,
		drawn: false,
		support: 'marseille',
		shuffling: false,
		selecting: false,
		no_interpretation: false,
		has_card_name: false,
		callback: false,
		icon_alert: true,
		time_exit: 2500,
		
		// Initialization
		_init: function() {
			var widget = this;
	
			element = this.element;
	
			jqflip = {};
			jqflip.s = document.createElement('script');
			jqflip.s.src = '/js/jquery.flip.min.js';
			document.getElementsByTagName('head')[0].appendChild(jqflip.s);
	
			jqpath = {};
			jqpath.s = document.createElement('script');
			jqpath.s.src = '/js/jquery.path.js';
			document.getElementsByTagName('head')[0].appendChild(jqpath.s);
			
			this.support = this.options.data && this.options.data.support && this.options.data.support || this.support;
			this.no_interpretation = this.options.data && this.options.data.no_interpretation && this.options.data.no_interpretation || this.no_interpretation;
			this.has_card_name = this.options.data && this.options.data.has_card_name && this.options.data.has_card_name || this.has_card_name;
			this.callback = this.options.data && this.options.data.callback && this.options.data.callback || this.callback;
			this.shuffle_text = this.options.data && this.options.data.shuffle_text && this.options.data.shuffle_text || this.shuffle_text;
			this.shuffle_text_bis = this.options.data && this.options.data.shuffle_text_bis && this.options.data.shuffle_text_bis || this.shuffle_text_bis;
			this.tooltip_width = this.options.data && this.options.data.tooltip_width && this.options.data.tooltip_width || this.tooltip_width;
			if(this.options.data.icon_alert==false) this.icon_alert=false;
			
			//this.direction = this.options.direction || this.options.align;		
			this.cards_settings.path = this.options.path || 'http://chat.internet.telemaque.fr/images/' + this.support;
			
			var tarot_id = 0;
			var img_dos  = 'dos.gif';
			var field    = 'description';
			this.cards_settings.decal = 22;
			this.cards_settings.total = 22;
			this.cards_settings.selectable = 5;
			this.cards_settings.ext = 'jpg';
			this.cards_settings.back_path = '/images/121/cards/dos-carte-' + this.support + '.jpg';
			
			this.cards_settings.width  = 52;
			this.cards_settings.height = 100;
			
			if (this.support == 'ge') {
				//this.cards_settings.decal = 40.2;
				//this.cards_settings.total = 57;
			} else if (this.support == 'belline') {
				var img_dos  = 'dos.jpg';
				var field    = 'recap';
				//this.cards_settings.total = 52;
				//this.cards_settings.decal = 39;
			} else if (this.support == 'esmeralda') {
				this.cards_settings.decal = 30;
				this.cards_settings.total = 22;
				this.cards_settings.width  = 72;
				this.cards_settings.height = 150;
				this.cards_settings.selectable = 8;
				this.cards_settings.ext = 'png';
				tarot_id = 66;
				this.cards_settings.back_path = this.cards_settings.path + 'dos.png';
				this.time_exit = 3500;
			}

			if (!this.no_interpretation) this.getInfosTarot({'field':field, 'table':this.support, 'actions':'get_interpretation'});
			else if (this.has_card_name) this.getInfosTarot({'id':tarot_id, 'actions':'get_tarot'});
					
			this.cards_selector = '.' + this.cards_class;
							
			this.placeCards();

			this.cards_settings.max_top = parseInt(card.css('margin-top').replace(/px/, ''));
			
			var _width  = (this.cards_settings.total * this.cards_settings.width) - ((this.cards_settings.total - 1) * (this.cards_settings.width - this.cards_settings.decal));
			var _height = this.cards_settings.height + this.cards_settings.max_top;
			element.css({'width': _width, 'height': _height});
			
			shuffle_event = this.shuffleCards;
			
			button = $('<button id="drawing_shuffle_button" class="button primary ui-telelab-corner-all"><h3>' + this.shuffle_text + '</h3></button>').insertAfter(element).bind('click', widget, shuffle_event);
	
			var selected_width = (Math.round(this.cards_settings.width * 1.5) * this.cards_settings.selectable) + 40;
			selected = $('<div id="drawing_selected" />').insertAfter(button).css({width: selected_width, height: Math.round(this.cards_settings.height * 1.5), 'left': (_width - selected_width)/ 2/*, 'margin-right': this.cards_settings.width / 2*/});
			
			if(selected_width>_width && !IE7){
				element.css({'left': ((selected_width-_width)/2)});
			}
			
			interpretation = $('<div id="drawing_interpretation" class="ui-telelab-corner-all ui-telelab-shadow-inner ui-telelab-background"><div class="contents" /></div>').insertAfter(selected).css({width: _width - 80});
			
			$('<button id="drawing_close_button" class="button primary ui-telelab-corner-all"><h3>Fermer le tirage</h3></button>').insertAfter(interpretation).bind('click', this.options.onClose);
			
			this.options.onInit(this, element);
		},
		
		// Shuffle cards
		shuffleCards: function(e) {
			widget = e.data;
			widget.shuffling = true;
			
			if (!widget.shuffle) {
				widget.shuffle = true;
				click_event = widget._selectCard;
				
				widget.element.children(widget.cards_selector).bind('click', widget, click_event).hover(function() {
						if (!$(this).hasClass('selected') && widget.selecting == false && $('.selected', widget.element).length < widget.cards_settings.selectable) $(this).animate({'top': '-10px'}, 100);															
					}, function() {
						if (!$(this).hasClass('selected') && widget.selecting == false && $('.selected', widget.element).length < widget.cards_settings.selectable) $(this).animate({'top': '0px'}, 45);
					}
				);
			}
	
			_max_delay = 0;
			$.shuffle(widget.element.children(widget.cards_selector)).each(function(i2) {
				card = $(this);
				_delay = $.random(20, 2000);
				
				if (_delay > _max_delay) _max_delay = _delay;
				
				card.delay(_delay).queue(function() {
					card = $(this);
					i1 = card.data('i');										 
												 
					_left_1 = i1 * widget.cards_settings.decal;
					_left_2 = i2 * widget.cards_settings.decal;
	
					if (_left_2 > _left_1)
						_left = _left_1 + (_left_2 - _left_1) / 2;
					else
						_left = _left_2 + (_left_1 - _left_2) / 2;
					
					zIndex = 41 + i2;
					_margin_top = $.random(0, 1) == 0 ? 0 : 200;
	
					/*var path = $.path.bezier({
						start: {x: _left_1, y: 0, angle: 20, length: 0.3},
						end:   {x: _left_2, y: 0, angle: -20, length: 0.2}
					});
					
					$(this).animate({'path': path});*/

					$(this).animate({'top': -50, 'margin-top': _margin_top, 'left': _left}, 400, 'plus');
					$(this).animate({'top': 0, 'margin-top': widget.calculateTop(i2, widget.cards_settings.total - 1), 'left': i2 * widget.cards_settings.decal}, 400, 'minus').data('i', i2).css({'z-index': zIndex});

					$(this).dequeue();
				});
			});
			
			setTimeout(function() {
				$('#drawing_shuffle_button').addClass('short').children('h3').html(widget.shuffle_text_bis);
				//widget.element.tooltip({direction: 'top', events: {tooltip: false, hover: false, fixed: true}, top: -30, align: 'center', valign: 'bottom', 'z-index': 11, text: function(obj) { return $('<h3 id="drawing_tooltip_indication">Choisissez ' + widget.cards_settings.selectable + ' cartes</h3>').css({'padding': '4px 6px'}); }});
				
				if(widget.tooltip_width!=false){
					$('<div style="width:'+widget.tooltip_width+'px;"><h3 style="text-align:center">Choisissez <span>' + widget.cards_settings.selectable + ' cartes</span></h3><div><div></div></div></div>').attr('id', 'drawing_tooltip_indication').appendTo($('#drawing')).addClass('telelab-tooltip ui-telelab-corner-all ui-telelab-widget disp_none').children('h3').css({'padding': '4px 6px'}).next().addClass('telelab-tooltip-pointer-top').children().addClass('telelab-tooltip-pointer-top-inner').css({'border-bottom': '10px solid rgb(255, 255, 255)'});
				} else {
					$('<div><h3>Choisissez <span>' + widget.cards_settings.selectable + ' cartes</span></h3><div><div></div></div></div>').attr('id', 'drawing_tooltip_indication').appendTo($('#drawing')).addClass('telelab-tooltip ui-telelab-corner-all ui-telelab-widget disp_none').children('h3').css({'padding': '4px 6px'}).next().addClass('telelab-tooltip-pointer-top').children().addClass('telelab-tooltip-pointer-top-inner').css({'border-bottom': '10px solid rgb(255, 255, 255)'});
				}
				
				$('#drawing_tooltip_indication').centerFix({'vertical': false}).css({'bottom': 8}).fadeIn();
				
				widget.shuffling = false;
			}, _max_delay + 200);
		},
		
		
		reorderCards: function() {
			//debug(this); return;
			this.element.children(this.cards_selector).sort(sortingCards).prependTo(widget.element);
		},
		
		orderCards: function() {
			this.element.children(this.cards_selector).each(function(i) { $(this).data('i', i); }).sort(sortingCards).prependTo(this.element);
		},
		
		placeCards: function() {
			if (this.element.children(this.cards_selector).length > 0)
				this.element.empty();
			
			zIndex = 41;
			
			for(i = 0; i < this.cards_settings.total; i++) {
				zIndex += 1;
				card = $('<a href="#" class="card"><img src="' + this.cards_settings.back_path + '" width="' + this.cards_settings.width + '" height="' + this.cards_settings.height + '" style="background-color:transparent;"/></a>').appendTo(this.element)
					.attr('id', 'card_' + i).data('i', i).data('id', i)
					.css({'z-index': zIndex, 'margin-top': this.calculateTop(i, this.cards_settings.total - 1), 'left': (i * this.cards_settings.decal)});
			}
		},
		
		rePlaceCards: function(index, _total) {
			widget = this;
	
			widget.element.children(widget.cards_selector).not('.selected').each(function() {
				_index = $(this).data('i');
				if (_index > index) {
					if (_total % 2 != 0) return;

					i = _index - 1;
					//decal = -(widget.cards_settings.decal / 2);
				} else if (_index < index) {
					if (_total % 2 == 0) return;
					
					i = _index + 1;
					//decal = (widget.cards_settings.decal / 2);
				}
				
				total = widget.cards_settings.total - 1;
				if (widget.cards_settings.clicked == widget.cards_settings.selectable && (widget.cards_settings.total % 2) != 0)
					total = widget.cards_settings.total;
					
				$(this).data('i', i).animate({'margin-top': widget.calculateTop(i, total), 'left': (i * widget.cards_settings.decal)/* + decal*/});
			});
		},
		
		// Select cards
		_selectCard: function(e) {
			e.preventDefault();
			
			widget = e.data;

			if (widget.selecting == true || widget.shuffling == true) {
				return;
			}
				
			if (widget.cards_settings.clicked < widget.cards_settings.selectable) widget.selecting = true;
			
			card   = $(this);
			
			if ($('#drawing_shuffle_button').is(':visible')) {
				//widget.reorderCards();
				$('#drawing_shuffle_button').fadeOut('normal', function() { widget.selectCard(card); });
			} else {
				widget.selectCard(card);
			}
		},
		
		selectCard: function(card) {
			widget = this;
	
			//_selected = $('.selected', widget.element).length;
			if (!card.hasClass('selected') && !card.hasClass('disabled')) {
								
				//if ($('#redraw').is(':visible'))
				//	$('.tirage .redraw').fadeOut();
				if (widget.cards_settings.clicked == widget.cards_settings.selectable) {
					//alert('Le tirage est effectué');
					if(widget.icon_alert==true)
						displayConfirmation({'data': {'message': 'Votre tirage est effectué.', 'button': {'primary': 'Ok', 'secondary': null}, 'hide': {'primary': true}, 'delay': {'close': 5000}}});
					else
						displayConfirmation({'data': {'icon': false, 'message': 'Votre tirage est effectué.', 'button': {'primary': 'Ok', 'secondary': null}, 'hide': {'primary': true}, 'delay': {'close': 5000}}})
					return false;
				}
				
				widget.cards_settings.clicked++;
				index = card.data('i');
				id = card.data('id') + 1;
								
				this.options.onSelectCard(widget.cards_settings.clicked - 1, id, widget.support);
	
				//x = jeu_cards[id - 1];
				url = widget.cards_settings.path + '/' + id + '.' + this.cards_settings.ext;
				
				zIndex = 80;
				card.css({'z-index': zIndex}).addClass('selected')/*.animate({'top': '24px'}).children()*/;
				//_selected++;
				
				_total = widget.cards_settings.total - widget.cards_settings.clicked;
				
				positions = $('#drawing_selected').position();
				
				//debug(positions);
				_width      = Math.round(widget.cards_settings.width * 1.5);
				_height     = Math.round(widget.cards_settings.height * 1.5);
	
				_margin_top = positions.top;
				_left       = positions.left + ((widget.cards_settings.clicked - 1) * (_width + 10));

				//debug(widget.cards_settings.clicked);
				_center = (widget.element.outerWidth() - _width) / 2;
	
				card.animate({'top': 0, 'margin-top': (_margin_top / 2), 'left': _center}).children().animate({'width': _width, 'height': _height}, 'normal', function() {
					$(this).flip({'color': '#000000', 'direction': 'lr', 'speed': 250, 'onEnd': function() {
						card.addClass('ui-telelab-shadow-black').animate({'top': 0, 'margin-top': _margin_top, 'left': _left}, 'fast', function() { widget.rePlaceCards(index, _total); widget.selecting = false; }).children().attr('src', url).css('background-color','transparent'); }
					}); 
				});
				
				//card.addClass('selected ui-telelab-shadow-black').animate({'top': 0, 'margin-top': _margin_top, 'left': _left}).children().attr('src', url);/*.animate({'width': _width, 'height': _height})*/
				if (!this.no_interpretation) widget.cards_selected += widget.interpretations[id].name + '[' + id + ']';
				this.cards.push(id);
		
				if (widget.has_card_name) widget.displayInfoTarot(id);
				
				if (widget.cards_settings.clicked == widget.cards_settings.selectable) {
					widget.drawn = true;
	
					$('#drawing_tooltip_indication').fadeOut('normal', function() { $(this).remove(); });
	
					$('#drawing_close_button').fadeIn().css({'display': 'block'});
					$('.selected', widget.element).bind('mouseover', widget, function(e) {
							widget = e.data;																	
							id = $(this).data('id') + 1;
							if (!widget.no_interpretation) widget.displayInfoTarot(id);
		
							zIndex += 50;
							$('.selected', widget.element).removeClass('hover ui-telelab-corner-all');
							$(this).css({'z-index': zIndex}).addClass('hover ui-telelab-corner-all');
						}
					).bind('mouseout', function() {
							// Out
							zIndex -= 50;
							$(this).css({'z-index': zIndex});
						}
					);

					if (!this.no_interpretation) widget.displayInfoTarot(0);
					if (typeof this.callback =='function' ) {
						callback = this.callback;
						window.setTimeout('callback()',widget.time_exit);
					} 
					
				} else {
					widget.cards_selected += ', ';
					var _left_cards = (widget.cards_settings.selectable - widget.cards_settings.clicked);
					$('#drawing_tooltip_indication h3 span').html(_left_cards + ' carte' + (_left_cards > 1 ? 's' : ''));
				}
			}
		},
		
		getInfosTarot: function(options) {
			widget = this;
			
			$.ajax({
				// url:  '/lab/_interpretation', 
				url:  '../common/drawing/_interpretation', 
				type: 'post',
				data: options,
				dataType: 'json',
				success: function(data) {
					if(options.actions=='get_interpretation'){
						widget.interpretations = data;
						widget.interpretations.unshift({'name': 'Aide', 'description': '<blink>Passez votre souris au-dessus d\'une carte tirée pour en lire l\'interprétation</blink>'});
					} else {
						widget.interpretations = data;			
					}
				}
			});
			
			return this; 
		},
		
		displayInfoTarot: function(id) {
			if (!this.no_interpretation){
				if (!$('#drawing_interpretation').is(':visible'))
					$('#drawing_interpretation').slideDown();
				
				var info = this.interpretations[id];
				$('#drawing_interpretation').find('.contents').html('<strong>' + info.name + '</strong> : ' + info.description.replace(/"/, "'"));
			}
			else if (widget.has_card_name) {
				var name = this.interpretations.stack[id].name;
				if($('#card_'+(id-1)).find('.card_name').length>0){
					$('#card_'+(id-1)).find('.card_name').html(name);
				} else {
					var img_width = Math.round(widget.cards_settings.width * 1.5);
					$('#card_'+(id-1)).width(img_width);
					window.setTimeout("$('#card_"+(id-1)+"').append(\"<span class='card_name' style='width:"+img_width+"px;'>"+name+"</span>\");",1000);	
				}
			}
				
		},
		
		calculateTop: function(index, total){ 
			return (1 - $.mirror((index / total) * .7 + .15, 'easeOutCircBis')) * 250; 
		},
		
		refresh: function() {
			this.cards = [];
			this.shuffle = false;
			this.drawn = false;
			this.cards_selected = '';
			this.cards_settings.clicked = 0;
			this.selecting = false;
			this.element.children(this.cards_selector).unbind('mouseenter mouseleave');
			this.placeCards();
			$('#drawing_shuffle_button').removeClass('short').children('h3').html(this.shuffle_text);
			$('#drawing_close_button').add($('#drawing_interpretation')).add($('#drawing_shuffle_button')).removeAttr('style');
		}
	});
/*}*/

$.widget('ui.scroll', {
	// default options
	options: {'top': 0, 'height': 0, 'selector': null, 'cols': 1, 'onInit': $.noop, 'parents': []},
	container: null,
	arrow_up: null,
	arrow_down: null,

	_create: function() {
		return this;
	},
	
	_init: function() {
		var widget = this;

		var element = this.element;

		this.cols = this.options.cols || this.cols;

		this.container = $('<div class="tele_scroll_container"></div>');

		this.arrow_up   = $('<div class="tele_scroll_up tele_scroll_arrow" style="display: none;" data-direction="top"></div>');
		this.arrow_down = $('<div class="tele_scroll_down tele_scroll_arrow" style="display: none;" data-direction="bottom"></div>');

		this.container.insertAfter(element).wrapInner(element.detach()).prepend(this.arrow_up).append(this.arrow_down);
		//element.addClass('tele_scroll_content').wrap(this.container).before(this.arrow_up).after(this.arrow_down);
		
		this.container.addClass('ui-telelab-corner-bottom').css({'position': 'relative', 'overflow': 'hidden'});

		this.arrow_up.addClass('ui-telelab-corner-top').css({'background': 'url("http://cdn1.horoscope.fr/1/ScrollNice/up_arrow.png") no-repeat scroll center center #FCF9F5', 'border-bottom': '1px solid #CCCCCC', 'top': 0});
		this.arrow_down.addClass('ui-telelab-corner-bottom').css({'background': 'url("http://cdn1.horoscope.fr/1/ScrollNice/down_arrow.png") no-repeat scroll center center #FCF9F5', 'border-top': '1px solid #CCCCCC', 'bottom': 0});
		
		this.arrow_up.add(this.arrow_down).css({'position': 'absolute', 'width': '100%', 'height': '20px', 'cursor': 'pointer', 'z-index': 1}).hover(
			function(e) {
				var t = Math.floor(element.height() - widget.container.height());

				var animate_time = Math.floor(Math.abs(t) * (element.height() * 3) / t);

				var direction = $(this).attr('data-direction');
				if (direction == 'top') {
					element.animate({'top': 0}, animate_time, 'swing');
				} else {
					element.animate({'top': -t}, animate_time, 'swing');
				}
			},
			function(e) {
				element.stop();
			}
		);

		this.options.onInit(widget);
	},
	
	update: function(settings) {
		var element = this.element;
		var widget = this;
		var _h = 0;
		
		var _children = this.options.selector && element.find(this.options.selector) || element.children();

		if (_children.parent().size() != element.find(this.options.parents).size()) {
			element.find(this.options.parents).each(function() {
				if ($(widget.options.selector, this).size() == 0) {
					_h += 39;
				}
			});
		}

		var nb_elts = _children.size();
		if (this.cols == 2)
			nb_elts = nb_elts % 2 == 0 && nb_elts || nb_elts + 1;

		_h = ((nb_elts / this.cols) - $(':animated', _children).size()) * _children.first().outerHeight() + this.options.height + _h;

		element.css({'height': _h});
		
		//debug(element.height() +' > '+ settings.height);
		if (element.height() > settings.height) {
			this.container.css({'height': settings.height, 'padding': '20px 0'});
			this.arrow_up.add(this.arrow_down).fadeIn('fast');
			
			var t = Math.floor(element.height() - this.container.height());
			
			if (Math.abs(element.position().top) > t) {
				var animate_time = Math.floor(Math.abs(element.position().top) * element.height() / t);
				element.animate({'top': -t}, animate_time, 'swing');
			}
		} else {
			element.animate({'top': 0}, 'fast');
			this.container.css({'height': 'auto', 'padding': '0'});
			this.arrow_up.add(this.arrow_down).fadeOut('fast');
		}
	}
});

$.fn.centerFix = function(params) {
	var options = {
		vertical: true,
		horizontal: true
	}

	options = $.extend(options, params);
	this.each(function(){
		
		//initializing variables
		var elt = $(this);
		//get the dimensions using dimensions plugin
		var _width = elt.width();
		var _height = elt.height();

		//get the paddings
		var paddingTop = parseInt(elt.css('padding-top')) || 0;
		var paddingBottom = parseInt(elt.css('padding-bottom')) || 0;
		//get the borders
		var borderTop = parseInt(elt.css('border-top-width')) || 0;
		var borderBottom = parseInt(elt.css('border-bottom-width')) || 0;
		//get the media of padding and borders
		var mediaBorder = (borderTop+borderBottom)/2;
		var mediaPadding = (paddingTop+paddingBottom)/2;
		//get the type of positioning
		var positionType = elt.parent().css('position');
		// get the half minus of width and height
		var halfWidth = (_width/2)*(-1);
		var halfHeight = ((_height/2)*(-1))-mediaPadding-mediaBorder;
		// initializing the css properties
		var cssProp = {'position': 'absolute'};

		if(options.vertical) {
			cssAff = {'top': '50%', 'margin-top': halfHeight};
			if (_height)
				cssAff = $.extend(cssAff, {'height': _height});
			cssProp = $.extend(cssProp, cssAff);
		}
			
		if(options.horizontal) {
			cssAff = {'left': '50%', 'margin-left': halfWidth};
			if (_width)
				cssAff = $.extend(cssAff, {'width': _width});
			cssProp = $.extend(cssProp, cssAff);
		}

		//check the current position
		if(positionType == 'static') {
			elt.parent().css('position', 'relative');
		}

		//aplying the css
		elt.css(cssProp);
	});
	
	return this;
};

$.fn.center = function() {
	return this.css({top: 0, left: 0}).position({
		my: 'center center',
		at: 'center center',
		of: this.parent(),
		using: function(pos) {
			var topOffset = $(this).css(pos).offset().top;
				if (topOffset < 0) {
					$(this).css('top', pos.top - topOffset);					
			}
		}
	});
}

$.fn.shoutbox = function(opts) {
	opts = opts || {};
	options = $.extend({delay: 5000}, opts);
	this.each(function(i) {
		if (!$(this).next() ||$(this).next().length == 0)
			return;
		$(this).delay(options.delay).fadeOut('normal', function() {	 
			next = $(this).next();
			$(this).remove();
			next.fadeIn('normal', function() {
				$(this).shoutbox();
			});
		});
	});
	
	return this;
}

$.fn.highlight = function(opts) {
	opts = opts || {};
	options = $.extend({'opacity': true, 'shadow': false, 'opacityOut': 0.4, 'opacityIn': 1.0, 'shadowOut': '0 0 0px #44F44D', 'shadowIn': '0 0 4px #44F44F', 'delay': 'normal'}, opts);

	this.queue(function() {
		$(this).animate({'opacity': options.opacityOut}, options.delay);
		$(this).animate({'opacity': options.opacityIn}, options.delay);
		$(this).highlight();
		$(this).dequeue();								
	});
	
	return this;
}

// EASING
/*$.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;
}*/

var get_window_sizes = function() {
	return {width: $(window).width(), height: $(window).height()};		
};

var sortingCards = function(a, b) {
	ret = parseInt($(a).data('i')) > parseInt($(b).data('i'));
	return ret;
}

$.mirror = function(pos, transition) {
	transition = transition || 'swing';
	ease = $.easing[transition];

	if(pos<0.5)
		return ease(pos*2);
	else
		return ease(1-(pos-0.5)*2);
}

$.easing.easeOutCircBis = function(pos) {
	return Math.sqrt(1 - Math.pow((pos-1), 2));
}

$.easing.swingFromTo = function(pos) {
	var s = 1.70158;
	return ((pos/=0.5) < 1) ? 0.5*(pos*pos*(((s*=(1.525))+1)*pos - s)) :
		0.5*((pos-=2)*pos*(((s*=(1.525))+1)*pos + s) + 2);
}

$.easing.minus = function(pos) {
  return Math.pow(pos, 3);
}

$.easing.plus = function (pos) {
	return Math.pow(pos - 1, 3) + 1;
}

// TOOLS
// custom easing called "custom" 
$.easing.custom = function (x, t, b, c, d) { 
	var s = 0.80158;  
	if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
	return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; 
}

$.fn.sort = function() {
	return this.pushStack($.makeArray([].sort.apply(this, arguments)));
};

$.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;
}

$.random = function(minVal, maxVal, floatVal) {
	floatVal = 0 || floatVal;
  var randVal = minVal + (Math.random() * (maxVal - minVal));
  return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);
}

function deleteElementProps() {
	elt = $(this);
	for(prop in elt) {
		elt[prop] = null;
	}
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
	 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function trim_string(s) {
	return s.replace(/^\s+/g,'').replace(/\s+$/g,'');
} 

function shuffle(o){
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
}

var strip_tags = function(input, allowed) {
	allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
	var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
	return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
		return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
	});
};

var basename = function(path, suffix) {
	var b = path.replace(/^.*[\/\\]/g, '');
		if (typeof(suffix) == 'string' && b.substr(b.length - suffix.length) == suffix) {
		b = b.substr(0, b.length - suffix.length);
	}
	
	return b;
};
