var layout;
var bigger;
var pagination = false;
var user_id = null;
var comment_plugin = '';
var comments_open = false;
var old_center_height;
var minus_height;

function displayWait()
{
	$.blockUI({ 
		css: 
		{ 
			width:'200px', 
			border:0, 
			background:'transparent', 'text-align':'center'
		},
		overlayCSS: 
		{  
			backgroundColor: '#000',  
      opacity: '0'  
    },
		message: '<img src="http://www.cowblog.fr/img/site/loading.gif" alt="Patientez..." />' 
	});
}

function columnsToBottom()
{
	if($('#center').height() > $('#left').height() && $('#center').height() > $('#right').height())	{	
		$('#left').height($('#center').height() - 10);
		$('#right').height($('#center').height() - 10);
	}
	else {
		if($('#right').height() > $('#left').height()) {
			$('#left').height($('#right').height() - 10);
			$('#center').height($('#right').height() - 10);
		}
		else if($('#left').height() > $('#right').height()) {
			$('#right').height($('#left').height() - 10);
			$('#center').height($('#left').height() - 10);
		}
	}
}

function adjustColumns()
{
	var margin_bottom = $('.article').css('marginBottom');
	
	if(margin_bottom.indexOf('px') != -1) {
		margin_bottom = margin_bottom.substring(0,margin_bottom.indexOf('px'));
	}
	else {
		margin_bottom = 10;
	}
	
	var new_center_height = old_center_height + parseInt(margin_bottom)*2;
	
	if($('#comments').is('div')) {
		new_center_height = new_center_height + $('#comments').height() + parseInt(margin_bottom);
	}
	
	if($('#post').is('div')) {
		new_center_height = new_center_height + $('#post').height() + parseInt(margin_bottom);
	}
	
	if($('#trackbacks').is('div')) {
		new_center_height = new_center_height + $('#trackbacks').height() + parseInt(margin_bottom);
	}
	
	//if(new_center_height > $('#right').height() && new_center_height > $('#left').height()) {
	$('#center').height(new_center_height);
	//}
	
	minus_height = new_center_height - old_center_height;
	
	columnsToBottom();
}	

function equalHeight(group) {
	tallest = 0;
	group.each(function() {
		thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
} 

function prependMsg(type,msg,container)
{
	switch(type)
	{
		case 'error': var title = 'Erreur'; break;
		case 'warning': var title = 'Avertissement'; break;
		case 'confirm': var title = 'Action réussie'; break;
	}
	
	var message_box = document.getElementById('message_box');
	
	var content = '<p id="message_hide"><a href="javascript:void(0);">'+
		'<img src="http://www.cowblog.fr/img/site/blank.gif" width="14" height="14"></a></p><strong>'+title+
		' :</strong><ul><li>'+msg+'</li></ul>';
	
	if(message_box)
	{
		message_box.className = type;
		message_box.innerHTML = content;
	}
	else
	{	
		$(container).prepend('<div id="message_box" class="'+type+'">'+content+'</div>');
	}
	
	$('.'+type).effect("pulsate", { times: 3, duration: 50 });
	
	$('#message_hide').click(function()
	{
		$('#message_box').fadeOut('slow');
	});
}

function dialog(d_id,d_title,d_content,d_width,d_height)
{
	if($('#dialog-'+d_id).is('div')) {
		$('#dialog-'+d_id).remove();
	}
	
	$('#container').prepend('<div id="dialog-'+d_id+'"></div>');
	$('#dialog-'+d_id).html(d_content);	
	
	$('#pub728x90').hide();
	
	$('#dialog-'+d_id).dialog(
	{
    width: d_width,
    height: d_height,
		modal: true, 
		overlay: {
			opacity: 0.5, 
			background: 'black'
		},
    resizable: false,
    title: d_title,
    show: 'slow'
	});
}

function dialog_close(d_id)
{
	$('#pub728x90').show();
	$('#dialog-'+d_id).dialog('close');
}

function bindComments()
{
	// Antispam
	$('#comment-post input[name="user_name"]').hide();
	
	// Ajout de commentaire
	$('#comment-post input[name="commentsub"]').click(function() 
	{
		displayWait();
		
		var post_id = $('#post_id').val();
		var user_id = $('#comment-post input[name="user_id"]').val();
		var user_site = $('#comment-post input[name="user_site"]').val();
		var user_email = $('#comment-post input[name="user_email"]').val();
		var user_pwd = $('#comment-post input[name="user_pwd"]').val();
		
		if(String(user_pwd) == "undefined") {
			user_pwd = '';
		}
		
		var hide_email = $('#comment-post input[name="hide_email"]').attr('checked') == true ? 1 : 0;
		var comment_follow = $('#comment-post input[name="comment_follow"]').attr('checked') == true ? 1 : 0;
		
		var comment_content = $('#comment_content').val();
			
		$.post(url,{ action:'comment', user_id:user_id, user_pwd:user_pwd, post_id:post_id, user_site:user_site, user_email:user_email, hide_email:hide_email, comment_follow:comment_follow, comment_content:comment_content, user_name:'c0wb0ys', comment_plugin:comment_plugin } ,function(data)
		{
			if(data == 'comment_wait')
			{
				prependMsg('confirm',"Votre commentaire a bien été ajouté, mais le propriétaire du blog doit d'abord le valider avant qu'il apparaisse sur le blog.",'#post .article-body');
			}
			else if(data == 'comment_spam')
			{
				prependMsg('warning',"Votre commentaire a été considéré comme du spam et devra être validé par le propriétaire du blog.",'#post .article-body');
				$('#comment_content').val('');
				$.scrollTo($('#blog').find('#post').get(0),800);
			}
			else if(data.indexOf('comment_') != -1)
			{
				$('#comment-last').remove();
				$('#comments .article-body').append(data);
				
				prependMsg('confirm',"Votre commentaire a bien été ajouté.",'#post .article-body');
				$('#comment_content').val('');
				$('.nocomment').hide();
				$.scrollTo($('#blog').find('#comment-last').get(0),800);
			}
			else
			{
				prependMsg('error',data,'#post .article-body');
				$.scrollTo($('#blog').find('#post').get(0),800);
			}
			
			columnsToBottom();
			//equalHeight($('.column'));
		});
		
		return false;
	});
	
	// Blog par défaut
	if($.cookie('cowblog_blog') != null) {
		$('#comment-post input[name="user_site"]').val($.cookie('cowblog_blog'));
	}
	
	// Commentaires - détection de session
	user_id = unescape($.cookie('cowblog_user'));
	
	if(user_id != '' && user_id != null && user_id != 'null') 
	{
		$('#auth-box').hide();
		$('#authed-box').html('Identifié : <b>'+user_id+'</b> '+
			'(<a id="user-change" href="javascript:void(0);">Changer</a>)<br /><br />'+
			'<input type="hidden" name="user_id" value="'+user_id+'" />');
			
		$('#user-change').click(function()
		{
			$('#authed-box').html('');
			$('#auth-box').show();
		});
	}	
	else {
		$('.favorites-add').hide();
	}
}

$(function()
{	
	$().ajaxStop($.unblockUI);
	
	bindComments();
	
	$('#searchsub').click(function() 
	{
		var q = $('#searchquery').val();
		
		if(q.length < 3) {
			prependMsg('error','Entrez au moins 3 caractères.','container');
		}
		
		$('#form-search').attr('action','/search.html');
		$('#form-search').submit();
		return false;
	});
	
	$('#researchsub').click(function() 
	{
		var q = $('#researchquery').val();
		
		if(q.length < 3) {
			prependMsg('error','Entrez au moins 3 caractères.','container');
		}
		
		$('#form-research').attr('action','/search.html');
		$('#form-research').submit();
		return false;
	});
	
	$('.protected-post input[type="submit"]').click(function()
	{
		var post_id = this.id.substring(4,this.id.length);
		
		$.post(url,{ action:'passwd', post_id:post_id, post_pwd:$('#pwd-'+post_id).val() } ,function(data)
		{
			if(data.indexOf("Cet article n'existe pas.") != -1) {
				prependMsg('error',data,'#form-'+post_id);
			}			
			else if(data.indexOf('Mot de passe incorrect !') != -1) {
				prependMsg('error',data,'#form-'+post_id);
			}
			else {
				$.cookie('post-'+post_id,$('#pwd-'+post_id).val(),{expires: 1});
				$('#post-'+post_id).html(data);
			}
		});
		
		return false;		
	});
	
	$('.protected-post').each(function()
	{
		var post_id = this.id.substring(5,this.id.length);
		
		if($.cookie('post-'+post_id) != null) {
			$('#pwd-'+post_id).val($.cookie('post-'+post_id));
			$('#sub-'+post_id).trigger('click');
		}
	});
	
	// Contact
	$('#contact-mail input[name="contactsub"]').click(function() 
	{
		$.post(url,{ action:'contact', 'user_email':$('#user_email').val(), 'email_content':$('#email_content').val() } ,function(data)
		{
			if(data == 'contact') {
				prependMsg('confirm',"L'email a bien été envoyé.",'#contact-mail');
				$('#contact-mail').reset();
			}
			else {
				prependMsg('error',data,'#contact-mail');
				$.scrollTo($('#container').get(0),800);
			}
		});
		return false;
	});
	
	// Ajouter aux favoris
	$('.favorites-add').click(function()
	{
		$.post(url,{ action:'favorites', 'blog_url':url, 'from-blog':1 } ,function(data)
		{
			if(data == 'favorites') {
				prependMsg('confirm',"Vous avez ajouté ce blog à vos favoris.",'#module-contact');
			}
			else {
				prependMsg('error',data,'#module-contact');
				$.scrollTo($('#module-contact').get(0),800);
			}
		});
	});
	
	$('#page-query').attr('class','textarea');
	$('#btn-pagination').attr('class','zeButton');
	
	$('.comment-link').click(function()
	{
		if(post_page == true) {
			$.scrollTo($('#blog').find('#comments').get(0),800);
			return false;
		}
		
		var post_id = this.href.substring(this.href.lastIndexOf('-')+1,this.href.lastIndexOf('.html'));
		
		$('#comments').remove();
		$('#post').remove();
		$('#trackbacks').remove();
			
		if(comments_open == post_id) {
			comments_open = false;
			$('#center').height(old_center_height).css({zIndex:"50"});
			$('#main').height(parseInt($('#main').height() - minus_height)).css({ });
		}
		else {
			displayWait();
			comments_open = post_id;
			old_center_height = $('#center').height();
			
			$.get(url+'/commentaires-'+post_id+'.html', function(data)
			{
				if(data.indexOf('comment_') != -1) 
				{
					$('#p_'+post_id).after(data);
					$('#comments').slideToggle();
					$('#post').slideToggle();
					$('#trackbacks').slideToggle();
					
					bindComments();
					$.scrollTo($('#blog').find('#comments').get(0),800);
				}
				else {
					prependMsg('error',data,'#p_'+post_id);
					$.scrollTo($('#blog').find('#p_'+post_id).get(0),800);					
				}		
				//columnsToBottom();				
				setTimeout("adjustColumns();",1000);
			});
		}
		return false;
	});
	
	$('.archive-link').click(function()
	{
		$(this).parent().find('ul').slideToggle();
	});
	
	$('.archive-li').each(function()
	{
		var archive_posts = 0;
		var has_posts = false;
		
		$(this).find('li').find('strong').each(function()
		{
			archive_posts += parseInt($(this).text());
			has_posts = true;
		});
		
		if(has_posts == true) {
			$(this).find('.archive-link').after(' (<strong>'+archive_posts+'</strong>)');
		}
	});
	
	$('#blog-page').change(function()
	{
		window.location = this.value+'.html';
	});
	
	if(nb_pages > 0) {
		$('#blog-page').removeOption('-'); 
	}
	
	for(i=1; i <= nb_pages; i++) {
		$('#blog-page').addOption(i, 'Page n°'+i+' sur '+nb_pages, (i == cur_page));
	}
		
	var _online_img = new Image(1,1);
  var _www = 'http://www.cowblog.fr/online.php?';
  _online_img.src = _www+Math.round(Math.random()*1000000000);
});

$(window).load(function()
{
	columnsToBottom();
	//equalHeight($('.column'));
});

$.fn.extend({ reset: function() {
	return this.each(function() { $(this).is('form') && this.reset(); });
	} 
});