// JavaScript Document
$(document).ready(function(e){	
	/* Tooltip menu podcast */
	var headerItems = $('#menu li');
	$(headerItems).each(function(i, elt){
		if(i == 2){
			var eltLink = $('a', elt);
			var that = this;
			$(eltLink).click(function(e){
				WWA.utils.stopEvent(e);		
			}).bind('mouseover', function(e){
				var tooltip = $('.tooltip', that);
				var outerWidth = $(that).width();
				var innerWidth = $(tooltip).width();
				var position = Math.ceil((outerWidth - innerWidth) / 2);
				$(tooltip).css('left', position + 'px');
				$(tooltip).css('display', 'block');
			}).bind('mouseout', function(e){
				var tooltip = $('.tooltip', that);
				$(tooltip).css('display', 'none');
			});
		}														 
	});	
	
	$('.warning').each(function(i, warning){
		new WWATooltip(warning);												
	});
	
	var rightInputs = $('.content_right input.text, #sign_up_container input.text');
	$(rightInputs).each(function(i, elt){
		var value = $(elt).attr('value');
		elt.initiale = value;
		$(elt).focus(function(e){
			$(elt).attr('value', ''); 
		});
		
		$(elt).blur(function(e){
			if($(this).attr('value') == ''){
				$(this).attr('value', elt.initiale);
			}
			else elt.initiale = $(this).attr('value');
		});
	});
	
	/* Liste des messages systeme */
	var messages = $('.wwa_message');
	$(messages).each(function(i, message){
		WWA.Messages[i] = new WWAMessageBox(message);
	});
	
	/* Embed mosaic */
	var embedTagId = 'mosaic';
	if($('#' + embedTagId).is('div')){
		WWA.utils.embedFlash('mosaic', {'lang': whoweare.lang}, 990, 452, {'allowfullscreen': 'true', 'allowscriptaccess': 'always', 'wmode': 'window'});
		var interval = window.setInterval(function(){
			var mosaicSWF = swfobject.getObjectById('mosaic');
			if($(mosaicSWF).is('object') || $(mosaicSWF).is('embed')){
				if(interval) window.clearInterval(interval);			
 			}
		}, 100);
	}
});

/* Object WWA - Namespace pour le site */
var WWA = WWA || {};
WWA.Messages = [];

/* Tools Box pour tout le site */
WWA.utils = {};
WWA.utils.stopEvent = function(e){
	if(window.event){ //IE
		e = window.event;
		e.returnValue = false;
	}
	try {
		e.cancelBubble = true;
		if(e.preventDefault) e.preventDefault();
		if(e.stopPropagation) e.stopPropagation();
		if(e.stopped) e.stopped = true;
	}
	catch(e) {
		console.log(e.message);
	}		
	return e;
};

/* A deleter */
WWA.utils.embedFlash = function(target, flash_vars, width, height, params) {
  width = width > 0 ? width : 400;
  height = height > 0 ? height : 249;
	params = params || {};
  swfobject.embedSWF(
    '/static/swf/WWA.swf', 
    target, 
    width, 
    height, 
    "9.0.0", 
    null, 
    flash_vars,
		params
  );
}

WWA.utils.SWF = {};
WWA.utils.SWF.isFlashPlayer = function(){
	if(swfobject){
		var playerVersionInfo = swfobject.getFlashPlayerVersion();
		var version = (playerVersionInfo.major)? parseInt(playerVersionInfo.major): false;
		return (version >= 9)? true : false;
	}
	else return false;
};

WWA.utils.SWF.setFlashVars = function(flashVars, swfObjectUrl){
	if(typeof(flashVars) == 'object'){
		for(prop in flashVars){
			if(!flashVarsURI) var flashVarsURI = prop + '=' + flashVars[prop];
			else flashVarsURI += '&' + prop + '=' + flashVars[prop];
		}
		swfObjectUrl += (flashVarsURI)? '?' + flashVarsURI : '';
		return swfObjectUrl;
	}
	else throw 'Exception: flashVars argument must be an object';
};

WWA.utils.SWF.setFlashParams = function(params){
	var swfObjectParams = swfEmbedParams = '';
	if(typeof(params) == 'object'){
		for(prop in params){
			var value = params[prop];
			swfEmbedParams += ' ' + prop + '="' + value + '"';
			swfObjectParams += '<param name="' + prop + '" value="' + value + '"></param>';
		}
		return {params: swfObjectParams, attr: swfEmbedParams};
	}
	else throw 'Exception: params argument must be an object';
};

WWA.utils.SWF.embedFlash = function(swfUrl, htmlTarget, flashVars, sizes, params){
	if(!WWA.utils.SWF.isFlashPlayer()) return;
	var playerVersion = swfobject.getFlashPlayerVersion();
	var width = sizes.width || 400;
	var height = sizes.height || 250;
	var swfObjectUrl = swfUrl || '/static/swf/WWA.swf';
	if(flashVars) swfObjectUrl = WWA.utils.SWF.setFlashVars(flashVars, swfObjectUrl);	
	if(params) var swfParams = WWA.utils.SWF.setFlashParams(params);
	
	var html = '<object width="' + width + '" height="' + height + '" id="' + htmlTarget + '">';
	html += '<param name="movie" value="' + swfObjectUrl + '"></param>';
	html += (swfParams)? swfParams.params : '';
	html += '<embed src="' + swfObjectUrl + '" type="application/x-shockwave-flash"' + swfParams.attr + ' width="' + width + '" height="' + height + '"></embed>';
	html += '</object>';
	
	var targetHtmlElement = ($('#' + htmlTarget).is('div'))? $('#' + htmlTarget)[0] : false;
	if($(targetHtmlElement).is('div')){
		$(html).replaceAll(targetHtmlElement);
		var swfObjectElement = document.getElementById(htmlTarget);
		var embedElt = $('embed', swfObjectElement)[0];
		return embedElt;
		/* if(embedElt) return embedElt;
		else throw 'Exception: No embed tag in the custom embed'; */
	}
	else throw 'Exception: target HTML not found'; 	
};


/* Sharebox */
/* 
var WWASharebox = function(container){
	this.container = ($(container).is('div'))? $(container) : false;
	if(!this.container) return;
	this.btn = $('.btn_panel a', this.container)[0] || false;
	this.icone 
	this.panel = $('.panel', this.container)[0] || false;
	this.initialize();
};

WWASharebox.prototype.initialize = function(){
	$(this.panel).hide();
	var is_closed = $(this.panel).is(':hidden');
  $(this.btn).text(is_closed ? '+' : '-');
};

WWASharebox.prototype.setBtnActions = function(){
	
}; */


/* Message BOX */
var WWAMessageBox = function(container, message){
	this.container = $(container);
	if(!this.container.is('div')) return;
	this.btnClose = $('.close', this.container) || false;
	this.initialize(message);
};

WWAMessageBox.prototype.initialize = function(message){
  if (message) this.setMessage(message);
	if(this.btnClose) {
		var that = this;
		this.btnClose.click(function(e){
			WWA.utils.stopEvent(e);
      that.closeMessage();
		});	
	}	
};

WWAMessageBox.prototype.closeMessage = function(){
	this.container.fadeOut('slow');
};

WWAMessageBox.prototype.showMessage = function() {
  this.container.fadeIn('slow');
};

WWAMessageBox.prototype.setMessage = function(message) {
  var html = "";
  if (typeof(message) == 'object') {
    html += "<ul>";
    for (key in message) {
      html += "<li>" + whoweare.labels[message[key]] + "</li>";
    }
    html += "</ul>";
  } else if (typeof(message) == 'array') {
    //Array of messages
    html += "<ul>";
    for (var i=0; i < message.length; i++) html += "<li>" + message[i] + "</li>";
    html += "</ul>";
  } else {
    html += "<p>" + message + "</p>";
  }
  this.container.find(".content").html(html);
};

/* Caroussel de news */
var WWACaroussel = function(elt, groupsToDisplay, nbItemsByGroup){
	this.elt = (elt)? $(elt) : false;
	if(!this.elt.is('div')) return;
	this.wrapper = $('.wrapper', this.elt)[0] || false;
	this.scroller = $('.scroller', this.elt)[0] || false;
	this.initialized, this.process = false;
	this.nextBtn, this.prevBtn = false;
	this.btns = $('.btn', this.elt);
	this.nbGroupsToDisplay = groupsToDisplay || 1;
	this.nbGroups = $('.page', this.elt).length || 0;
	this.currentGroup = 0;
	this.nbItemsByGroup = nbItemsByGroup || $('.page:first ul li').length;
	this.debugMode = true;
	this.activeSlug = $(this.elt).attr('title') || false;
	this.initialize();
};

/* Initialise le caroussel */
WWACaroussel.prototype.initialize = function(){
	this.setScrollerSize();
	this.initBtnsActions();
	this.initItemsActions();	
	this.initialized = true;
};

/* Mettre a jour les settings - load Ajax */
WWACaroussel.prototype.refreshSettings = function(){
	this.nbGroups = $('.page', this.elt).length || 0;
	this.setScrollerSize();	
	this.initItemsActions();
	this.process = false;
	this.move('next');
};

WWACaroussel.prototype.setScrollerSize = function(){
	if(this.nbGroups){
		var group = $('.page', this.elt)[0];
		var groupWidth = parseInt($(group).css('width').replace('px',''));
		var scrollerWidth = groupWidth * this.nbGroups;
		try {
			$(this.scroller).width(scrollerWidth + 10);
		} catch(e) {
			this.alertMessage('Pas de scroller trouve !!!');
		}	
	}
	return this;
};

WWACaroussel.prototype.initItemsActions = function(){
	var items = $('.page ul li', this.elt);
	var that = this;	
	$(items).click(function(e) {
    var aHref = $(this).find('a.more').attr('href');
    window.location.href = aHref;
  });
};


WWACaroussel.prototype.initBtnsActions = function(){
	if(this.btns.length > 1){
		for(var i = 0; i < this.btns.length; i++){
			if(this.nextBtn && this.prevBtn) break;
			var btn = this.btns[i];
			if($(btn).hasClass('prev')) this.prevBtn = btn;
			else if($(btn).hasClass('next')) this.nextBtn = btn;
			else continue;
		}
		
		if(this.nextBtn && this.prevBtn){
			var that = this;
	    $(this.prevBtn).click(function(e){
				if(!$(this).hasClass('disable') && that.canMove('prev')){
					that.move('prev');
	      }
	    });
			
			$(this.nextBtn).click(function(e){
				if(!$(this).hasClass('disable')){
	      	if(!that.canMove('next')){
						try{
							that.getNewData(that.currentGroup + 2);
						} catch(e){
							that.alertMessage('Fin du caroussel Loader des datas en Ajax');
						}											
					}
					else that.move('next');
	      }
	    });
		}		
	}
	return this;
};

WWACaroussel.prototype.canMove = function(direction){
	if(this.process) return false;
	if(direction == 'next'){
		return (this.currentGroup < this.nbGroups - 1)? true : false;
	}
	else {
		return (this.currentGroup > 0)? true : false;
	}
};

WWACaroussel.prototype.getNewData = function(p){
	if(p){
		var that = this;
		this.process = true;		
		whoweare.api.news.search(
			function(response){
    		if (response.type != whoweare.SUCCESS || !response.data.resultset.length){
					that.refreshSettings();
					return;
				}
				that.addGroups(response.data.resultset);
			}, null, {'pagesize' : 5, 'sort' : 'date_posted', 'page' : p}
		);
	}
};

WWACaroussel.prototype.addGroups = function(data){
	var html = '';
	html += '<div class="page">';
	html += '<ul>';
	for(var i = 0; i < data.length; i++){
		var isFirstItem = (i % this.nbItemsByGroup == 0)? true : false;
		var isLastItem = (i == data.length - 1)? true : false;
    var class_str = " class='";
    if (isFirstItem) class_str += " first";
    if (isLastItem) class_str += " last";
		if(data[i]._slug == this.activeSlug) class_str += " active";
		class_str += "'";
    html += '<li' + class_str + '><div><p>' + data[i].title.substr(0,40) + '</p><a href=' + data[i].url_page + ' class="more">&nbsp;</a></div></li>';
	}	
	html += '</ul>';
	html += '</div>';
	try {
		$(this.scroller).append(html);
	} catch(e){ this.alertMessage('Dernier element du caroussel non trouve !'); }
	this.refreshSettings();
};

WWACaroussel.prototype.updateClassToElements = function(className, toRemove){
	if(arguments.length < 3) return;
	for(var i = 2; i < arguments.length; i++){
		var elt = $(arguments[i]);
		(toRemove)? elt.remove(className): elt.addClass(className);
	}
};

WWACaroussel.prototype.move = function(direction){
	if(!this.canMove(direction)) return;
	var position = this.getPositionToMove(direction);
	this.process = true;
  var that = this;
  $(this.scroller).animate({'left': position}, 'fast', function(){
  	that.currentGroup = (direction == 'next')? that.currentGroup + 1 : that.currentGroup - 1;
		that.process = false;
  });		
};

WWACaroussel.prototype.getPositionToMove = function(direction){
	var group = $('.page:first', this.elt);	
	try {
		var groupWidth = parseInt($(group).css('width').replace('px',''));
		var position = parseInt($(this.scroller).css('left').replace('px',''));
		position = (direction == 'next')? 0 - (Math.abs(position) + groupWidth) : position + groupWidth;
	} catch(e) { this.alertMessage('Pb dans le calcul des valeurs de deplacement !'); }
	return (position)? position : 0;
};

WWACaroussel.prototype.alertMessage = function(message){
	if(this.debugMode){
		alert(message);
	}
};


/* Panel simple */
var WWASlidePanel = function(container){
	this.container = $(container) || false;
	if($(this.container).is('div')){
		this.btn = $('a.btn', this.container)[0] || false;
		this.panel = $('.related_content', this.container)[0] || false;
		if(!this.btn || !this.panel) return;
		this.isOpen = ($(this.panel).css('display') == 'none')? false : true;
		this.initialize();
	}
};
	
WWASlidePanel.prototype.initialize = function(){
	if(this.isOpen) $(this.btn).addClass('open');		
	var that = this;
	$(this.btn).click(function(){
		if(that.isOpen) $(that.panel).css('display', 'none');
		else $(that.panel).css('display', 'block');
		$(that.btn).toggleClass('open');
		that.isOpen = (that.isOpen)? false : true;
	});		
};

/* Preview */
var WWAPreviewer = function(formulaire, externalLinkInput){
	this.formulaire = $(formulaire);
	this.formulaire = ($(this.formulaire).is('form'))? this.formulaire : false;
	if(this.formulaire){
		this.container = $('.preview_window', formulaire)[0];
		this.btnPreview = $('input[rel="preview"]', this.formulaire);
		this.fields = $('input[rel="preview_data"], textarea[rel="preview_data"]');
		this.externalLinkInput = $(externalLinkInput);
		this.preloader = arguments[2] || false;
		this.initialize(false);	
	}	
};
		
WWAPreviewer.prototype.initialize = function(reinitilize){
	var that = this;
	if(!reinitilize){
		$(this.btnPreview).click(function(e){
			WWA.utils.stopEvent(e);
			this.blur();
			var externalUrl = $(that.externalLinkInput).attr('value');
			that.updateByAjax(externalUrl);
		});
	}
	
	if(reinitilize) {
		this.btnReset = $('a[rel="preview_reset"]', this.formulaire)[0];		
		if($(this.btnReset).is('a')){
			$(this.btnReset).click(function(e){
				WWA.utils.stopEvent(e);
				that.resetPreview();		
			});
		}
		else {
			$('.close',  this.formulaire).click(function(e){
				WWA.utils.stopEvent(e);
				var parent = $(this).parents('.wwa_message')[0];
				if($(parent).is('div')){
					$(parent).fadeOut('slow');	
				}			
			});
		}
	}
	
	$(this.externalLinkInput).attr('value', '');
};

WWAPreviewer.prototype.resetFieldsValue = function(){
	for(var i = 0; i < this.fields.length; i++){
		var field = this.fields[i];
		($(field).is('input'))? $(field).attr('value', '') : $(field).html('');
	}
};
	
WWAPreviewer.prototype.resetPreview = function(){
	this.resetFieldsValue();
	$(this.container).html('');
};
	
WWAPreviewer.prototype.updateByAjax = function(externalUrl){
  this.resetPreview();
  this.preloader.startTraveler();
	var that = this;
  whoweare.api.video.import_preview(function(response) {
    if (response.type == whoweare.SUCCESS) {
      var response = response.data;
			var xhtmlResponse = $(document.createElement('div')).html(response);
			var timer = setTimeout(function(){
				that.preloader.stopTraveler();
				$(that.container).html(response);
				that.setFieldsValue(xhtmlResponse);
				that.initialize(true);				
			}, 500);				
    } else {
      WWA.Messages[0].setMessage(response.msg);
      WWA.Messages[0].showMessage();
    }
  },externalUrl);
  
};
	
WWAPreviewer.prototype.setFieldsValue = function(content){
	var elts = $('*', content);		
	fieldsLoop: for(var i = 0; i < this.fields.length; i++){
		var field = this.fields[i];
		eltsLoop: for(var j = 0; j < elts.length; j++){
			var elt = $(elts[j]);
			if(elt.attr('rel') != $(field).attr('id')) continue eltsLoop;
			else {
				var value = elt.html();
				($(field).is('input'))? $(field).attr('value', value) : $(field).html(value);
				break eltsLoop;
			}				
		}		
	}	
};

/* Progress Bar */
WWAProgressBar = function(container){
	this.container = $(container);
	if(!$(this.container).is('div')) return;
	this.traveler = $('.traveler', this.container)[0];
	this.width = $(container).width();
}
	
WWAProgressBar.prototype.animateTraveler = function(){
	var that = this;
	var left = -parseInt(this.width) + "px";
	$(this.traveler).css('left', left).animate( {
     left: '0px'
  }, 7000, "linear", function() {
    that.animateTraveler();
  });
};
	
WWAProgressBar.prototype.startTraveler = function() {
  var that = this;
	that.animateTraveler();
	$(this.container).css({display: 'block'});    
};
  
WWAProgressBar.prototype.stopTraveler = function() {
  var that = this;
	$(this.container).css({display: 'none'});
	$(that.traveler).stop(true, false);
};	

/* ToolTips */
var WWATooltip = function(elt){
	this.container = $(elt);
	this.btn = $('.btn', this.container)[0];
	this.content = $('.warning_content span', this.container)[0];
	this.master = $('#master_warning')[0];
	this.timeout = false;
	this.initialize();	
};

WWATooltip.prototype.initialize = function(){
	if($(this.btn).is('a')){
		var that = this;
		$(this.btn).bind('mouseover', function(e){			
			that.show(this, true);			
		}).bind('click', function(e){
			return false;		
		});
		
		var masterBtn = $('.btn', this.master)[0];
		var masterContent = $('.warning_content', this.master)[0];		
		$(masterContent).bind('mouseenter', function(e){
			that.show(this);								 
		}).bind('mouseleave', function(e){
			that.timeout = window.setTimeout(function(){
				if(that.timeout) window.clearTimeout(that.timeout);
				that.hide();															
			}, 150);
		});	
		
		$(masterBtn).bind('mouseover', function(e){
			that.show(this);							 
		}).bind('mouseout', function(e){			
			that.timeout = window.setTimeout(function(){
				if(that.timeout) window.clearTimeout(that.timeout);
				that.hide();															
			}, 150);
		}).bind('click', function(e){
			return false;	
		});
	}	
};

WWATooltip.prototype.show = function(btn, setPosition){
	if(this.timeout) window.clearTimeout(this.timeout);
	if(setPosition){
		var offSet = $(this.container).offset();
		var content = $('.warning_content span', this.container).html();
		$('.warning_content span', this.master).html(content);	
		$(this.master).css({left: offSet.left + 'px', top: offSet.top + 'px'});
	}
	$(this.master).css({display: 'block'});	
};

WWATooltip.prototype.hide = function(){
	$(this.master).css({left: '0px', top: '0px', display: 'none'});
};

/* Gestion des zones de passage */
var WWAArea_manager = function(button){
	this.button = $(button);	
	this.buttonContainer = $(button).parents('p')[0];
	this.areasContainer = $(this.buttonContainer).next('div.areas');
  this.listing = $('ul', this.areasContainer);
	if(this.areasContainer.length) this.initialize();	
};

WWAArea_manager.prototype.initialize = function(){
	var that = this;	  
  var init_children = $('li', this.listing);
  if (init_children.length > 0) {
    var cities_list = [];
    init_children.each(function(i, e) {
      cities_list[i] = $(this).text();
      $(this).remove();
    });
    for (var i=0; i<cities_list.length; i++) {
      that.addOneRow(cities_list[i]);
    }
  }
	$(this.button).click(function(e){
		that.addOneRow();
	});	
};

WWAArea_manager.prototype.addOneRow = function(init_value){
	var row = this.createRow(init_value);
	$(this.listing).append(row);
	this.initializeRow(row);
  $(this.areasContainer).css('display', 'block');
};

WWAArea_manager.prototype.createRow = function(init_value){
	var li = document.createElement('li');
	var p = document.createElement('p');	
	var input = document.createElement('input');
	var aBtn = document.createElement('a');
	$(aBtn).attr('href', 'javascript:;').html('[ X ]');
	var name = $(this.buttonContainer).attr('rel');
	$(input).attr('type', 'text').addClass('text');	
	$(input).attr('name', name + '[]').attr('id', name + '_' + $('input', this.areasContainer).length);
  if (init_value) $(input).attr('value', init_value);
	$(p).append(input);
	$(input).after(aBtn);
	return $(li).addClass('area').append(p);
};

WWAArea_manager.prototype.initializeRow = function(row){
	var btn = $('a', row)[0];
	var that = this;
  var autocomplete = new WWAAutocomplete($('input', row));
	$(btn).click(function(e){
		that.deleteRow(this);							
	});
};

WWAArea_manager.prototype.clear = function() {
  var that = this;
  $('li.area', this.areasContainer).each(function(i, e) {
    that.deleteRow($('a', this)[0]);
  });
}

WWAArea_manager.prototype.deleteRow = function(btn){
	var parent = $(btn).parents('li.area')[0];
	$(parent).remove();
	if($('li.area', this.areasContainer).length < 1){
		$(this.areasContainer).css('display', 'none');
	}	
};

/* Autocomplete */
var WWAAutocomplete = function (input_selector) {
  this.input = $(input_selector);
  this.initialize();
};

WWAAutocomplete.prototype.initialize = function() {
  var that = this;
  this.input.click(function(e) {
    //that.input.val('');
  }).autocomplete(
    whoweare.urlmap.api_json + '/location/autocomplete', 
    {
      minChars : 1, 
      autoFill : true, 
      mustMatch : true, 
      matchContains : false, 
      
      parse : that.parseServerData, 
      formatItem : that.formatItem
    }
  );
};

WWAAutocomplete.prototype.parseServerData = function(response) {
  var parsed = [];
  if (response.type != whoweare.SUCCESS) return parsed;
  var rows = response.data.resultset;
  for (var i=0; i < rows.length; i++) {
    var row = rows[i];
    var nice_value = row.city + "," + row.region + "," + row._country[0].name;
    parsed[parsed.length] = {
      data: row,
      value: nice_value,
      result: nice_value
    };
  }
  return parsed;
};

WWAAutocomplete.prototype.formatItem = function(row, i, max, filter) {
  return row.city + ", " + row.region + ", " + row._country[0].name;
};

var WWACommenter = function (comments_selector, video_slug, news_slug, blogentry_id) {
  this.CommentsSelector = comments_selector;
  this.VideoSlug = video_slug;
  this.NewsSlug = news_slug;
  this.BlogEntryId = blogentry_id;
	this.isProcess = false;
  this.initialize();
};

WWACommenter.prototype.initialize = function() {
  this.CommentsDiv = $(this.CommentsSelector);
  this.ReplyBox = this.CommentsDiv.find(".response_form");
  this.hide();
  var that = this;
  $(".add_comment a").unbind().click(function(e) {
    that.moveTo();
    that.show();
		that.openAddComment();
    return false;
  });
  this.CommentsDiv.find("a.reply_btn").unbind().click(function(e) {
    var comment_id = $(this).attr('rel');
    that.moveTo(comment_id);
    that.show();
		that.resetAddComment();
    return false;
  });
  this.ReplyBox.find('a.cancel').unbind().click(function(e) {
    that.hide();
		that.resetAddComment();
    return false;
  });
  this.ReplyBox.find('input#comment_submit').unbind().click(function(e) {
    if(!that.isProcess) that.post();
    return false;
  });
  this.CommentsDiv.find(".more").unbind().click(function(e) {
    var comment_id = $('a', this).attr('rel');
    that.modUp(comment_id);
    return false;
  });
  this.CommentsDiv.find(".less").unbind().click(function(e) {
		var comment_id = $('a', this).attr('rel');
    that.modDown(comment_id);
    return false;
  });
  this.CommentsDiv.find(".delete").unbind().click(function(e) {
    $(this).parent('.comment_action').find('.confirm_delete').show();
    return false;
  });
  this.CommentsDiv.find(".delete_yes").unbind().click(function(e) {
    var comment_id = $(this).attr('rel');
    that.erase(comment_id);
    return false;
  });
  this.CommentsDiv.find(".delete_no").unbind().click(function(e) {
    $(this).parent().parent('.confirm_delete').hide();
    return false;
  });
};

WWACommenter.prototype.resetAddComment= function(){
	var addComments = $('.header .add_comment');
	$(addComments).each(function(i, elt){
		$(elt).removeClass('open');														 
	});	
};

WWACommenter.prototype.openAddComment= function(){
	var addComments = $('.header .add_comment');
	$(addComments).each(function(i, elt){
		$(elt).addClass('open');														 
	});	
};

WWACommenter.prototype.hide = function() {
  this.ReplyBox.hide();
};

WWACommenter.prototype.show = function() {
  this.ReplyBox.show();
};

WWACommenter.prototype.moveTo = function(comment_id) {
  this.reset();
  var move_to = this.CommentsDiv;
  if (comment_id > 0) {
    move_to = $("div.reply_placeholder.comment_" + comment_id);
    this.SelectedId = comment_id;
  } else {
    this.SelectedId = 0;
  }
  
  move_to.prepend(this.ReplyBox);
};

WWACommenter.prototype.reset = function() {
  this.ReplyBox.find('textarea#comment').val('');
  this.ReplyBox.find('input#external_link_text').val('');
};

WWACommenter.prototype.post = function() {
  this.isProcess = true;
	var body = this.ReplyBox.find('textarea#comment').val();
  var link = this.ReplyBox.find('input#external_link_text').val();
  var parent_id = null;
  var gotopage1 = true;
  if (this.SelectedId > 0) {
    parent_id = this.SelectedId;
    gotopage1 = false;
  }
  var that = this;
  
  whoweare.api.comment.post(function(response) {
		that.isProcess = false;
		if (response.type != whoweare.SUCCESS) {
      var msg = response.code;
      if (response.data) {
        msg = (response.data.body ? response.data.body : response.data.external_link);
        that.error(whoweare.labels[msg]);
      } else {
        location.href = whoweare.urlmap.app_signup;
      }
      return;
    }
    that.hide();
    
    //Update comment count
    var cmt_count = $(".comment_ajax_update").text();
    var cmt_count = parseInt(cmt_count.substr(1)) + 1;
    $(".comment_ajax_update").text('('+cmt_count+')');
    
    if (pager) {
      pager.searchOptions.cache_off = true;
      if (gotopage1 && pager.searchOptions.page > 1) pager.pageChange(1); else pager.reload();
      delete pager.searchOptions.cache_off;
    } else
      location.reload();
  }, this.VideoSlug, this.NewsSlug, this.BlogEntryId, body, link, parent_id);
};

WWACommenter.prototype.modUp = function(comment_id) {
  var that = this;
  whoweare.api.comment.mod_up(function(response) {
    if (response.type != whoweare.SUCCESS) {
      that.error(response.msg, comment_id);
      return;
    }
    that.updateRates(comment_id, 1);
    that.success(response.msg, comment_id);
  }, comment_id);
};

WWACommenter.prototype.modDown = function(comment_id) {
  var that = this;
  whoweare.api.comment.mod_down(function(response) {
    if (response.type != whoweare.SUCCESS) {
      that.error(response.msg, comment_id);
      return;
    }
    that.updateRates(comment_id, -1);
    that.success(response.msg, comment_id);
  }, comment_id);
};

WWACommenter.prototype.updateRates = function(comment_id, offset) {
  var rates = $("#comment_" + comment_id + " span.rates");
  var points = parseInt(rates.text()) + offset;
  if (points > 0) {
    points = "+" + points;
    rates.removeClass("error").addClass("succes");
  } else if (points < 0) {
    rates.removeClass("succes").addClass("error");
  } else {
    rates.removeClass("succes").removeClass("error");
  }
  rates.text(points);
};

WWACommenter.prototype.erase = function(comment_id) {
  var that = this;
  whoweare.api.comment.erase(function(response) {
    if (response.type != whoweare.SUCCESS) {
      that.error(response.msg, comment_id);
    }
    if (pager) {
      pager.searchOptions.cache_off = true;
      pager.reload();
      delete pager.searchOptions.cache_off;
    } else
      location.reload();
  }, comment_id);
};

WWACommenter.prototype.success = function(message, comment_id) {
  var msgspan = $("#comment_" + comment_id + " span.message");
  /* if (this.messageTimeout) clearInterval(this.messageTimeout);
  msgspan.hide();
  message = "<em class=\"icone\">[!]</em>" + message;
  msgspan.addClass("succes").removeClass("error").html(message).fadeIn('fast');
  this.messageTimeout = setTimeout(function() { msgspan.fadeOut('fast'); }, 2000); */
	msgspan.hide();
	message = "<em class=\"icone\">[!]</em>" + message;
  msgspan.addClass("succes").removeClass("error").html(message).fadeIn('fast');
	var timer = setTimeout(function(){
		if(timer) clearInterval(timer);
		msgspan.fadeOut('fast');
	}, 2000);	
};

WWACommenter.prototype.error = function(message, comment_id) {
  var msgspan = null;
  if (comment_id) {
    msgspan = $("#comment_" + comment_id + " span.message");
  } else {
    msgspan = this.ReplyBox.find("p.error");
  }
  /* if (this.messageTimeout) clearInterval(this.messageTimeout);
  msgspan.hide();
  message = "<em class=\"icone\">[!]</em>" + message;
  msgspan.addClass("error").removeClass("succes").html(message).fadeIn('fast');
  this.messageTimeout = setTimeout(function() { msgspan.fadeOut('fast'); }, 2000); */
	msgspan.hide();
  message = "<em class=\"icone\">[!]</em>" + message;
  msgspan.addClass("error").removeClass("succes").html(message).fadeIn('fast');
  var timer = setTimeout(function(){
		if(timer) clearTimeout(timer);
		msgspan.fadeOut('fast');
	}, 2000);
};



