/* Cufon remplacement sur css Classe font */
Cufon.replace('.font');

var pib = pib || {};
pib.swfInterface = {};

/* Check Js Ready */
var jsReady = false;
function isReady() {
	return jsReady;
}

/* Recupere l'instance SWF embed dynamique avec swfObject */
pib.swfInterface.getInstance = function(swfName){
	var instance = (navigator.appName.indexOf("Microsoft") != -1)? window[swfName] : document.getElementById(swfName);
	return (instance)? instance : false;
};

/* Editorial */
pib.Editorial = function(container, parent, options){
	this.options = {};
	$.extend(this.options, options);
	this.container = $('#' + container);
	this.parent = $('#' + parent);
	this.navigations = $('.navigation', this.parent);
	this.tabs = $('.tab li');
	this._date = $('.date');
	this.data = false;	
	this.inProcess = false;
	this.initialize();
};

pib.Editorial.prototype = {
	/* Initialise l'objet : navigation et tabs */
	initialize: function(){
		if(this.navigations.length){
			var that = this;
			this.navigations.bind('click', function(e){
				pib.tools.stopEvent(e);
				var url = $(this).attr('href');
				that._get(url);
				return false;
			});		
		}	
		
		if(this.tabs.length){
			this.tabs.each(function(i, elt){
				var $current = $(elt);
				var $link = $('a', $current);
				$link.data('parent', $current).bind('click', function(e){
					pib.tools.stopEvent(e);
					if(!$(this).data('parent').hasClass('active')) that.toogleWindow().toogleTabs();
					$(this).blur();
					return false;
				});
			});
		}
		return this;
	},
	
	/* Load le data d'un nouvelle edito : utilise l'url contenu dans les liens de navigation */
	_get: function(uri){
		var that = this;
		if(this.inProcess) return;
		this.inProcess = true;
		$.ajax({
			type: 'GET',
			url: uri,
			data: 'ajax=true', 
			dataType: 'html',
			success: function(response){
				var response = $(response);
				response.each(function(i, elt){
					var $elt = $(elt);
					if($elt.is('span') && $elt.hasClass('data')){
						var data = eval('(' + $.trim($elt.text()) + ')');
						$('.e_wrapper', that.container).html(response);
						if(data.type) that.refresh(data);
						that.inProcess = false;
					}					
				});				
			}
		});
	},
	
	/* Gestion des layouts edito */
	toogleWindow: function(){
		var $windows = $('.e_window', this.container);	
		$windows.each(function(i, elt){
			var $current = $(elt);
			$current.hasClass('active')? $current.removeClass('active') : $current.addClass('active');			
		});
		return this;
	},
	
	/* Gestion des tabs edito */
	toogleTabs: function(){
		this.tabs.each(function(i, elt){
			var $current = $(elt);
			$current.hasClass('active')? $current.removeClass('active') : $current.addClass('active');			
		});	
		return this;
	},
	
	/* Mise a jour HTML contenu hors du load Ajax */
	refresh: function(data){
		this.tabs.each(function(i, elt){ //Affichage des tabs
			(i == 0)? $(elt).addClass('active') : $(elt).removeClass('active')
		});
		
		if(data.type){
			var html = this._formatDate(data.date);
			this._date.html(html);
			this._refreshNavigation(data);
		}		
	}, 
	
	/* Gestion de l'affichage des liens de navigation en fonction du data Ajax */
	_refreshNavigation: function(data){
		this.navigations.each(function(i, elt){
			var $current = $(elt);
			var url = (i >= 1)? data.next : data.prev;
			if(url != "false")	$current.attr('href', url).css('visibility', 'visible');
			else $current.attr('href', 'javascript:;').css('visibility', 'hidden');				
		});
	},
	
	/* Affichage date dans "onglet date" edito */
	_formatDate: function(date){
		var dates = $.trim(date).split(' ');
		var day = (dates[0].length < dates[1].length)? dates[0] : dates[1];
		var month = (dates[0].length < dates[1].length)? dates[1] : dates[0];
		month = (month.length > 7)? month.substr(0, 3) + '.' : month;
		month = month.charAt(0).toUpperCase() + month.substring(1).toLowerCase();
		var html = (pib.lang != 'en')? '<em>' + day + '</em>' + month : '<em>' + month + '</em>' + day;
		return html;
	}
};

/* Accordeons */
pib.Accordeon = function(container, options){
	this.options = {btns: false, scrolling: false, caroussel: false, delay: 1000, height: false, cssClass: 'tmp'};
	$.extend(this.options, options);
	this.container = $(container);
	this.ul = $('ul.acc_container', this.container);
	this.initialize();	
};

pib.Accordeon.prototype = {
	initialize: function(){
		var $btn = (!this.options.btns)? $('h3 em', this.container) : $('h3 span.btns span', this.container);
		var that = this;
		$btn.bind('click', function(e){
			pib.tools.stopEvent(e);
			var $current = $(this);
			var $parent = $($current.parents('li').eq(0));
			if($parent.is('li')){
				if($parent.hasClass('active')) return false;
				that.closeAll($parent).animate($parent);		
			}		
			return false;			
		});
		
		$(window).bind('resize', function(e){
			if(that.options.caroussel){
				var $content = $('li.active', that.container);				
				var $scroller = $('.caroussel_wrapper', $content);
				if(!$scroller.is('div')){
					$('.' + that.options.cssClass, that.container).remove();
					that.showTypes($content, true);					
				}
				else {
					that.options.caroussel.hideTypes();
					that.options.caroussel.showTypes(true);	
				}
			}		
		});
		
		if(this.options.caroussel) this.showTypes($('li.active', this.ul));
		this.showTooltip($('li.active', this.ul));
		return this;
	},
	
	animate: function(container){
		var $content = $('.acc_content', container);
		var $prev = container.prev('li');
		if(this.options.caroussel) this.options.caroussel.hideTypes(this.container);
		
		if(this.options.scrolling){
			var height = (!this.options.height)? $content.height() : this.options.height;
			var that = this;
			this.hideTooltip(container);
			$wrapper = $('.animate_wrapper', $content);
			$content.css({display: 'block'});	
			$wrapper.css({position: 'relative', overflow: 'hidden', height: '0px'}).animate({height: height + 'px'}, this.options.delay, 'easeOutCubic', function(){
				if(that.options.caroussel){
					var $scroller = $('.caroussel_wrapper', $content);
					if(!$scroller.is('div')) that.showTypes(container);
					else that.options.caroussel.showTypes();
				}
				that.showTooltip(container);
			});
		} else {
			$content.css({display: 'block'});
			if(this.options.caroussel){
				var $scroller = $('.caroussel_wrapper', $content);
				if($scroller.is('div')) this.options.caroussel.showTypes();
				else this.options.caroussel.hideTypes();
			}
		}
		container.addClass('active');
		if($prev.is('li')) $prev.addClass('prev');	
		return this;		
	},
	
	closeAll: function(active){
		var $lis = $('li', this.ul);
		$lis.each(function(i, elt){
			var $current = $(elt);
			$current.removeClass('active');
			$('.acc_content', $current).css({display: 'none'});
			$current.removeClass('prev');
			if(i == $lis.length){
				active.addClass('active');	
			}
		});
		return this;
	}, 
	
	showTypes: function(container, isResize){
		var that = this;
		var isResize = isResize || false;
		var $snails = $('.c_snail', container);
		$snails.each(function(j, snail){
			var $type = $('.type', snail);
			var $media = $('.media', snail);
			var $clone = $type.clone();
			var $acc_content = $('.acc_content', container);
			$acc_content.before($clone);
			var posX = $media.offset().left - 67;
			var posY = $media.offset().top;
			/*if($.browser.msie && isResize ){
				var refTop = $(document).scrollTop();
				posY = (refTop > 0)? posY - refTop : posY;
				var refLeft = $(document).scrollLeft();
				posX = (refLeft > 0)? posX - refLeft : posX;
			}	*/
			$clone.addClass(that.options.cssClass).css({top: posY + 'px', left: posX + 'px'});			
		});	
		return this;
	}, 
	
	showTooltip: function(container){
		if(window['tooltips']){
			var $caracters = $('.over_tooltip', container);
			if($caracters.length == 1){
				$caracters.each(function(i , elt){
					var $caracter = $(elt);
					var tooltip = (window['tooltips'].length)? window['tooltips'][$caracter.attr('rel')] : false;
					var parent = $($caracter.parents('.media').eq(0));				
					tooltip.show($(this), $('.description:eq(0)', parent).text());
					tooltip.locked = true;
				});			
			}
		}
	}, 
	
	hideTooltip: function(container){
		if(window['tooltips']){
			for(var i = 0; i < window['tooltips'].length; i++){
				var tooltip = window['tooltips'][i];
				tooltip.locked = false;
				tooltip.hide();				
			}
		}
	}
};

pib.HUBCaroussel = function(container, options){
  this.options = {inProcess: false, itemWidth: 610};
	$.extend(this.options, options);
	this.container = $(container);
	this.scroller = $('#scroll', this.container);
	this.bluff = $('#bluff', this.container);
	if($.cookie(this.options.cookieName))
	{
    var active = $.cookie(this.options.cookieName);
  }
  
	this.active = (active && active > 1)? active : null;
	this.next = $('.next a', this.container);
	this.prev = $('.prev a', this.container);
	return this.init();
}

$.extend(pib.HUBCaroussel.prototype, {
  init: function()
  {
    var length = $('.item', this.scroller).length;
    var width = length*this.options.itemWidth;
    this.scroller.css({width: width + 'px'});
    
    var that = this;
    this.next.bind('click', function(e){
      if(!that.options.inProcess) that.goNext();
    });
    
    this.prev.bind('click', function(e){
      if(!that.options.inProcess) that.goPrev();
    });
    
    if(this.active && this.active <= length)
    {
      this.jumpTo();
    }
    else this.active = $('.active', this.container).attr('rel');
    return this;
  }, 
  
  goNext: function()
  {
    if(this.options.inProcess) return;
    this.options.inProcess = true;
    
    var items = [$('.active', this.container)];
    for(var i = 0; i < 2; i++){
      items.push(items[i].next());
    }
    
    var that = this;
    $(items).each(function(i, elt){
      var clone = elt.clone(true);
      that.bluff.append(clone);
    });
    
    var left = -1*(3*this.options.itemWidth);
    $('.btn a', this.container).addClass('disabled');
    this.scroller.animate({left: left + 'px'}, {duration: 550, easing: 'easeInOutCirc', complete: function(){
      that.toggleViewers().updateScroll(2).toggleViewers(true);
      $('.pager span:eq(0)', that.container).text(that.active);
      that.bluff.css({display: 'none'});
      $('.item', that.bluff).remove();
      var timeout = window.setTimeout(function(){
        if(timeout) window.clearTimeout(timeout);
        that.options.inProcess = false;
        $('.btn a', that.container).removeClass('disabled');
        $.cookie(that.options.cookieName, that.active, that.cookieOptions);
        window.location.hash = 'rel';
      }, 50);
    }});
  },
  
  goPrev: function()
  {
    if(this.options.inProcess) return;
    this.options.inProcess = true;
    
    var items = [$('.active', this.container)];
    for(var i = 0; i < 2; i++){
      items.push(items[i].prev());
    }
    
    var that = this;
    $(items).each(function(i, elt){
      var clone = elt.clone(true);
      that.bluff.prepend(clone);
    });
    
    var left = -1*(1*this.options.itemWidth);
    $('.btn a', this.container).addClass('disabled');
    this.scroller.animate({left: left + 'px'}, {duration: 550, easing: 'easeInOutCirc', complete: function(){
      that.toggleViewers().updateScroll(2, true).toggleViewers(true);
      $('.pager span:eq(0)', that.container).text(that.active);
      that.bluff.css({display: 'none'});
      $('.item', that.bluff).remove();
      var timeout = window.setTimeout(function(){
        if(timeout) window.clearTimeout(timeout);
        that.options.inProcess = false;
        $('.btn a', that.container).removeClass('disabled');
        $.cookie(that.options.cookieName, that.active, that.cookieOptions);
        window.location.hash = 'rel';
      }, 50);
    }});
  }, 
  
  toggleViewers: function()
  {
    var scroll = arguments[0] || false;
    if(scroll)
    {
      this.scroller.css({display: 'block'});
      this.bluff.css({display: 'none'});
    }
    else
    {
      this.scroller.css({display: 'none'});
      this.bluff.css({display: 'block'});
    }
    return this;
  },
  
  updateScroll: function(j)
  {
    left = -1*(j*this.options.itemWidth);
    this.scroller.css({left: left + 'px'});
    if(!arguments[1]) this.scroller.append($('.item:first', this.scroller));
    else {
      this.scroller.prepend($('.item:last', this.scroller));
    }
    $('.active', this.scroller).removeClass('active');
    $('.item:eq(' + j + ')', this.scroller).addClass('active');
    this.active = $('.active', this.scroller).attr('rel');
    return this;
  }, 
  
  jumpTo: function()
  {
    this.options.inProcess = true;
    var items = $('.item', this.scoller);
    var list = new Array();
    if(this.active == items.length)
    {
       list = [parseInt(this.active)-1, parseInt(this.active), 1];
    }
    else
    {
      list = [parseInt(this.active)-1, parseInt(this.active), parseInt(this.active)+1];
    }
    
    for(var i = 0; i < list.length; i++)
    {
      var c = $('.item[rel=' + list[i] + ']', this.scroller);
      if(c.length)
      {
        var clone = c.clone(true);
        this.bluff.append(clone);
      }
    }
    this.toggleViewers();
    var length = items.length;
    var list = new Array();
    var active = parseInt(this.active);
    if(this.active == 2)
    {
      list = [items.length, 1, active];
    }
    else
    {
      list = [active - 2, active -1, active];
      if(active == length)
      {
        list.push(1);
        list.push(2);
      }
      else if(active == (length-1))
      {
        list.push(length);
        list.push(1);
      }
      else 
      {
        list.push(active+1);
        list.push(active+2);
      }
    }
    
    var limit = length - list.length;
    var w = list[list.length-1];
    for(var i = 1; i < limit+1; i++)
    {
      var index = w+i;
      if(index > length)
      {
        index = index - length;
      }
      list.push(index);
    }
    
    var items = [];
    for(var i = 0; i < list.length; i++)
    {
      var c = $('.item[rel=' + list[i] + ']', this.scroller);
      if(c.length)
      {
        items.push(c);
      }
    }
    var that = this;
    $(items).each(function(i, elt){
      that.scroller.append(elt); 
    });
    this.toggleViewers(true);
    $('.pager span:eq(0)', that.container).text(that.active);
    this.options.inProcess = false;
    return this;
  }
});

pib.Caroussel = function(container, options){
	this.options = {currentPage: 1, display: 4, cssClass: 'tmp', cssActive: 'active', inProcess: false, type: false, height: false};
	$.extend(this.options, options);
	this.container = $(container);
	this.wrapper = $('.caroussel_wrapper', this.container);
	this.scroller = $('.caroussel_scroller', this.container);
	this.items = $('.page', this.scroller);
	this.btns = $('h3 .btns span', this.container);
	this.initialize();	
};

pib.Caroussel.prototype = {
	initialize: function(){
		var that = this;
		if(this.options.type) this.btns = $('#c_episode_btns .btns span', this.container);	
		
		this.btns.each(function(i, btn){
			var $btn = $(btn);
			$btn.bind('click', function(e){
				pib.tools.stopEvent(e);
				var $btn = $(this);
				if($btn.hasClass('first')) that.next();
				if($btn.hasClass('last')) that.prev();
				return false;
			});			
		});
		this.refreshBtns();
		return this;
	},
	
	next: function(){
		var next = this.options.currentPage+1;
		if(this.items.length >= next && !this.options.inProcess){
			this.options.inProcess = true;
			var that = this;
			var distance = (!this.options.type)? -700 : -454;
			if(this.options.height) distance = -1*this.options.height;
			this.hideTypes().disabledTootips();
			this.scroller.animate({top: distance*that.options.currentPage}, 1000, function(){
				that.options.currentPage = next;
				that.refreshBtns();
				var timer = window.setTimeout(function(){
					if(timer) window.clearTimeout(timer);
					that.showTypes().enabledTootips();
					that.options.inProcess = false;
				}, 250);
			});	
		}		
	},
	
	prev: function(){
		var prev = this.options.currentPage-1;
		if(prev != 0 && !this.options.inProcess){
			this.options.inProcess = true;
			var that = this;
			var distance = (!this.options.type)? 700 : 454;
			if(this.options.height) distance = this.options.height;			
			var position = parseInt(this.scroller.css('top').replace('px', ''));			
			position = position + distance;
			this.hideTypes().disabledTootips();
			this.scroller.animate({top: position}, 1000, function(){
				that.options.currentPage = prev;
				that.refreshBtns();
				var timer = window.setTimeout(function(){
					if(timer) window.clearTimeout(timer);
					that.showTypes().enabledTootips();
					that.options.inProcess = false;
				}, 250);
			});					
		}		
	},
	
	refreshBtns: function(){
		var $next = $prev = false;
		for(var i = 0; i < this.btns.length; i++){
			var $btn = $(this.btns[i]);
			if($btn.hasClass('first')) $next = $btn;
			else if($btn.hasClass('last')) $prev = $btn;
			else continue;
		}
		
		if(this.items.length < 2){
			if($prev) $prev.css({display: 'none'});
			if($next) $next.css({display: 'none'});
		}
		else {
			if(this.options.currentPage-1 != 0){
				if(this.options.currentPage != this.items.length){
					$prev.removeClass('disabled');
					$next.removeClass('disabled');
				}
				else{
					$prev.removeClass('disabled');
					$next.addClass('disabled');
				}				
			} else {
				$prev.addClass('disabled');
				$next.removeClass('disabled');
			}
		}
		return this;
	},
	
	hideTypes: function(){
		$('.' + this.options.cssClass, (arguments.length)? arguments[0] : this.container).remove();
		return this;
	}, 
	
	showTypes: function(isResize){
		var isResize = isResize || false;
		var $pages = $('.page', this.scroller);
		var that = this;
		for(var i = 0; i < $pages.length; i++){
			if(that.options.currentPage-1 != i) continue;
			var $page = $($pages[i]);
			var $snails = $('.c_snail', $page);
			$snails.each(function(j, snail){
				var $type = $('.type', snail);
				var $media = $('.media', snail);
				var $clone = $type.clone();
				var $acc_content = $('.acc_content', that.container);
				$acc_content.before($clone);
				var posX = $media.offset().left - 67;
				var posY = $media.offset().top;
				if($.browser.msie && isResize ){
					/*var refTop = $(document).scrollTop();
					posY = (refTop > 0)? posY - refTop : posY;
					var refLeft = $(document).scrollLeft();
					posX = (refLeft > 0)? posX - refLeft : posX;*/
				}				
				$clone.addClass(that.options.cssClass).css({top: posY + 'px', left: posX + 'px'});			
			});			
		}
		return this;
	},
	
	enabledTootips: function(){
		if(window['tooltips']){
			for(var i = 0; i < window['tooltips'].length; i++){
				var tooltip = window['tooltips'][i];
				if(!tooltip.enable) tooltip.enable = true;
			}
		}
		return this;
	},
	
	disabledTootips: function(){
		if(window['tooltips']){
			for(var i = 0; i < window['tooltips'].length; i++){
				var tooltip = window['tooltips'][i];
				if(tooltip.enable) tooltip.enable = false;
			}
		}
		return this;
	}
};

pib.Tabs = function(container, options){
	this.options = {callback: false};
	$.extend(this.options, options);
	this.container = $(container);
	this.tabs = $('.tabs ul li', this.container);
	this.layouts = $('.ui_tabs_contents .ui_tabs_content', this.container);
	this.initialize();
};

pib.Tabs.prototype = {
	initialize: function(){
		var that = this;
		this.tabs.each(function(i, tab){
			var $tab = $(tab);
			var $link = $('a', $tab);
			$link.data('index', i);
			$link.bind('click', function(e){
				pib.tools.stopEvent(e);
				var $current = $(this);
				if(!$tab.hasClass('active')) that.show($current.data('index'));
				return false;			
			});
		});		
		return this;
	}, 
	
	show: function(index){
		this.tabs.each(function(i, elt){
			var $elt = $(elt);
			(i == index)? $elt.addClass('active') : $elt.removeClass('active');
		});
		
		this.layouts.each(function(i, elt){
			var $elt = $(elt);
			if($elt.hasClass('active')){
				var $forms = $('form', $elt);
				$forms.each(function(i, form){
					var $form = $(form);
					var $upload = $('.upload');
					if(!$upload.is('div')) return;
					var $input = $('.upload .input input');
					if($input.is('input')) $input.val('');
					$upload.removeClass('error');
				});		
			}
			
			(i == index)? $elt.addClass('active') : $elt.removeClass('active');
		});
	}
};

pib.Tooltips = function(container, options){
	this.options = {top: false, left: false, ref: false, mousepos: false};
	$.extend(this.options, options);
	this.container = $(container);
	this.enable = true;
	this.locked = false;
	this.initialize();
}; 

pib.Tooltips.prototype = {
	initialize: function(){
		this.container.css({display: 'none'});
		this.options.ref = $('#' + this.container.attr('rel'));
		return this;
	},
	
	show: function(ref, txt, event){
		if(!this.enable) return;
		if(this.locked) return;
		$('p span', this.container).text(txt.length? txt : pib.tools.translate('no_description'));
    if(this.options.mousepos)
    {
      var offset_gap = 50;
      var offset_gap_top = 30;
      this.container.css({left: (event.pageX + offset_gap)+ 'px', top: (event.pageY - offset_gap_top)+ 'px',display: 'block'});
    }
    else
      this.container.css({top: this.getPosition(ref.offset().top) + 'px', display: 'block'});
		return this;
	}, 
	
	hide: function(){
		if(this.locked) return;
		this.container.css({display: 'none'});
		return this;
	}, 
	
	getPosition: function(y){
		var posY = 0;
		if(this.options.ref){
			var offSetTop = this.options.ref.offset().top;
			posY = (offSetTop < y)? y - offSetTop : 0;	
		}
		return posY;
	}, 
	
	disabled: function(){
		this.hide();
		this.enable = false;
		return this;
	}, 
	
	enabled: function(){
		this.enable = true;
		return this;
	}
};

pib.Episodes = function(container, options){
	this.options = {top: false, left: false, ref: false};
	$.extend(this.options, options);
	this.container = $(container);
	this.tabs = $('.tab li', this.container);
	this.initialize();
};

pib.Episodes.prototype = {
	initialize: function(){
		var that = this;		
		if(this.tabs.length){
			this.tabs.each(function(i, elt){
				var $current = $(elt);
				var $link = $('a', $current);
				$link.data('parent', $current).bind('click', function(e){
					pib.tools.stopEvent(e);
					if($(this).hasClass('disabled')) return;
					if(!$(this).data('parent').hasClass('active')) that.toogleWindow().toogleTabs();
					$(this).blur();
					return false;
				});
			});
		}	
	},
	
	/* Gestion des layouts edito */
	toogleWindow: function(){
		var $windows = $('.e_window', this.container);	
		$windows.each(function(i, elt){
			var $current = $(elt);
			$current.hasClass('active')? $current.removeClass('active') : $current.addClass('active');			
		});
		return this;
	},
	
	/* Gestion des tabs edito */
	toogleTabs: function(){
		this.tabs.each(function(i, elt){
			var $current = $(elt);
			$current.hasClass('active')? $current.removeClass('active') : $current.addClass('active');			
		});	
		return this;
	}	
};

pib.Validator = function(form, options){
	this.options = {matches: new Array(), requires: new Array(), callback: null, params: new Array(), fields: new Array(), prefix: null};
	$.extend(this.options, options); 
	this.container = $(form);
	this.params = {};
	this.timeout = false;
	this.initialize();
};

pib.Validator.prototype = {
	initialize: function(){
		var that = this;
		$(this.options.params).each(function(i, elt){ //api Params
			var label = (that.options.prefix)? that.options.prefix + that.options.fields[i] : that.options.fields[i];
			var $field = $('#' + label);
			that.params[elt] = $field.val();		
		});
		
		if(this.container.is('form')){
			this.container.bind('submit', function(e){
				pib.tools.stopEvent(e);
				for(var i = 0; i < that.options.fields.length; i++){
					var key = that.options.fields[i];
					var label = (that.options.prefix)? that.options.prefix + key : key;
					var $field = $('#' + label);
					var value = $field.val();					
					if($.inArray(key, that.options.requires) >= 0){
						if($field.attr('rel')) value = ($field.attr('rel') == $.trim(value))? null : value;					
					}
					
					if($field.attr('type') == 'checkbox'){
						value = ($field.is(':checked'))? 1 : 0;	
					}					
					that.params[that.options.params[i]] = value;					
				}
				that.apiCall();
				return false;
			});			
		}		
		return this;
	}, 
	
	apiCall: function(){
		var that = this;
		if(this.options.type == 'stf'){
			pib.api.share.sendToFriend(function(r){
				that.callback(r);																							
			}, this.params);
		}
		else if(this.options.type == 'follow'){
			pib.api.share.follow(function(r){
				that.callback(r);																							
			}, this.params);
		}
		else {
			heap.api.reactions.create(function(r){
				that.callback(r);
			}, this.params);
		}
	},
	
	callback: function(response){
		var $msg = $('.callback_msg', this.container);
		$('.error', this.container).removeClass('error');		
		if(response.type == heap.SUCCESS){
		  var dictionary;
		  if (this.options.type == 'stf')
		    dictionary = {data:{success: "stf_send"}};
		  else if (this.options.type == 'follow')
		    dictionary = {data:{success: "follow_send"}};
		  else
			  dictionary = {data:{success: "reaction_send"}};
			this.reset().showMsg($msg, dictionary, true);	
		}
		else {
			this.showMsg($msg, response, false);			
			for(var i = 0; i < this.options.matches.length; i++){
				var token = this.options.matches[i];
				if(response.data && response.data[token]){
					var label = (this.options.prefix)? this.options.prefix + this.options.requires[i] : this.options.requires[i];
					var $field = $('#' + label);
					var $fieldset = $($field.parents('.fieldset:eq(0)'));
					if($fieldset.is('p') || $fieldset.is('span')) $fieldset.addClass('error');	
				}	
			}
			
			if(response.code && response.code == "FOLLOW_THEME_ALREADY_SUBSCRIBED"){
				for(var i = 0; i < this.options.fields.length; i++){
					var $input = $('#' + this.options.fields[i], this.container);
					if($input.attr('type') != 'text') continue;
					$input.val('');
				}				
			}			
		}
		
		if(this.options.callback) this.options.callback();
		return this;
	}, 
	
	reset: function(){
		for(var i = 0; i < this.options.requires.length; i++){
			var label = (this.options.prefix)? this.options.prefix + this.options.requires[i] : this.options.requires[i];
			var $field = $('#' + label);
			$field.val($field.attr('rel')? $field.attr('rel') : '');		
		}
		return this;
	}, 
	
	showMsg: function(msg, response, success){
		$(msg).css({display: 'none'});
		var cssClass = (success)? 'msg_success' : 'msg_error';
		$(msg).removeClass('msg_success msg_error');
		var html = '';
		for(var prop in response.data){
			html += "<li>" + pib.tools.translate(prop + '_' +  response.data[prop]) + "</li>";
		}
		if (html == '')
		  html += "<li>" + response.msg + "</li>";
		$('.msg_content ul', $(msg)).html(html);
		$(msg).addClass(cssClass).css({display: 'block'});
		if(this.timeout) window.clearTimeout(this.timeout);
		var that = this;
		this.timeout = window.setTimeout(function(){
			if(that.timeout) window.clearTimeout(that.timeout);		
			$(msg).css({display: 'none'});
		}, 3000);			
	}	
};

pib.Media_Validator = function(form, options){
	this.options = {callback: null, prefix: null, fields: new Array('email', 'name'), server: new Array('__email', '__name')};
	$.extend(this.options, options); 
	this.container = $(form);
	this.timeout = false;
	this.initialize();
};

pib.Media_Validator.prototype = {
	initialize: function(){
		var that = this;		
		return this;
	}, 
	
	callback: function(response){
		//Check response
		if((typeof(response.type) == "undefined") || response.type != '') this.showSuccess();
		else this.displayErrorField(response).showError(response);			
		if(this.options.callback) this.options.callback();
		return this;
	}, 
	
	reset: function(){
		var $fields = $('input, textarea', this.container);
		$fields.each(function(i, elt){
			var $field = $(elt);
			if($field.hasClass('clean')){
				$field.val($field.attr('rel'));
			}
			else {
				if($field.is('input')){
					var type = $field.attr('type');
					if(type != 'submit' && type != 'hidden'){
						$field.val('');
					}					
				}	
			}
		});
		return this;
	}, 
	
	showSuccess: function(){
		var html = "<li>" + pib.tools.translate('success_reaction_send') + "</li>";
		var that = this;
		if($('.loading', this.container).is('div')){
			pib.Loading.hide($('.loading', this.container), function(){
				that.showProcess(html, true).reset();																													 
			});		
		}
		else that.showProcess(html, true).reset();
		return this;
	},
	
	showProcess: function(){
		var $container = $('.callback_msg', this.container);
		$container.removeClass('msg_error').addClass('msg_success');
		var html = arguments[0] || '';
		if(!html.length) html = "<li>" + pib.tools.translate('waiting_message') + "</li>";
		$('.msg_content ul', $container).html(html);
		$container.css({display: 'block'});
		var timer = arguments[1] || false;
		if(timer){
			var that = this;
			if(this.timeout) window.clearTimeout(this.timeout);
			this.timeout = window.setTimeout(function(){
				if(that.timeout) window.clearTimeout(that.timeout);		
				$container.css({display: 'none'});
				$('.submit', this.container).css({visibility: 'visible'});	
			}, 3000);		
		}		
		return this;
	},
	
	displayErrorField: function(response){
		$('.error', this.container).removeClass('error');
		for(var prop in response.data){
			if($.inArray(prop, this.options.server) >= 0){
				prop = this.options.fields[$.inArray(prop, this.options.server)];
			}				
			var $field = $('#' + this.options.prefix + '_' + prop, this.container);
			var $fieldset = $($field.parents('.fieldset:eq(0)'));
			if($fieldset.is('p') || $fieldset.is('span')) $fieldset.addClass('error');	
		}	
		return this;
	},
	
	checkUploadFile: function(){
		var $input = $('.upload .input input', this.container);
		if($input.is('input') && !$.trim($input.val()).length){
			var $fieldset = $($input.parents('.upload:eq(0)'));
			if($fieldset.is('div')) $fieldset.addClass('error');
			var html = "<li>" + pib.tools.translate('upload_file_error_no_file_selected') + "</li>";
			this.showStaticError(html);
			return false;
		}
		else return true;
	},
	
	showError: function(response){
		var html = '';
		for(var prop in response.data) html += "<li>" + pib.tools.translate(prop + '_' +  response.data[prop]) + "</li>";
		if (html == '') html += "<li>" + response.msg + "</li>";
		this.showStaticError(html);
		return this;
	}, 
	
	showStaticError: function(html){
		var $container = $('.callback_msg', this.container);
		$container.removeClass('msg_success').addClass('msg_error');
		$('.msg_content ul', $container).html(html);
		if(html.length) $container.css({display: 'block'});
		
		var that = this;
		if(this.timeout) window.clearTimeout(this.timeout);
		this.timeout = window.setTimeout(function(){
			if(that.timeout) window.clearTimeout(that.timeout);		
			$container.css({display: 'none'});
		}, 3000);	
		return this;
	}
};

pib.Loading = {};
pib.Loading.show = function(elt){
	var $elt = $(elt);
	if(!$elt.hasClass('loading')) return;
	if($.browser.msie){
		$elt.css({display: 'block'});
		$('.l_container', $elt).animate({width: '240px'}, 'slow');
	}
	else {
		$elt.fadeIn('slow', function(){
			$('.l_container', $elt).animate({width: '240px'}, 'slow');
		});
	}	
};

pib.Loading.hide = function(elt, callback){
	var $elt = $(elt);
	var fn = callback || false;
	if(!$elt.hasClass('loading')) return;
	$('.l_container', $elt).stop(true, true).animate({width: '1px'}, 'slow', function(){
		if(!$.browser.msie) $elt.fadeOut('slow');
		else $elt.css({display: 'none'});
		if(fn) fn();
	});
};

pib.Tbox = {};
pib.Tbox.tb_show = function(url){
	tb_show(null, url);
	return;
};

pib.Tbox.tb_show = function(url){
	tb_show(null, url, null, true);
	return;
};

pib.Tbox.tb_remove = function(){
	tb_remove();
	return;
};

pib.api = {};
pib.api.share = {};
heap.api.setup({
  object: pib.api.share,
  'api_class':'share',
  url: pib.urlmap.api_json,
  methods: ['sendToFriend', 'follow', 'validate_reaction']
});

