// these are all the main functions of the website

var user_img;
var add_comment_id;
var scroll_comments;
var delete_id;
var share_this_id;
var form_data;

$(document).ready(function()
{
	
	jQuery.preloadImages = function()
	{
		for(var i = 0; i<arguments.length; i++)
		{
			jQuery("<img>").attr("src", arguments[i]);
		}
	}
	$.preloadImages("/images/icons/ajax_loader.gif", "/images/icons/social_twitter_on.png", "/images/icons/social_facebook_on.png", "/images/icons/social_linkedin_on.png", "/images/icons/social_flickr_on.png",
					"/images/button_on.png", "/images/button_on_small.png");
	
	
	// check login status
	if(user_auth != null)
	{
		$('div#default_user').hide();
		$('div#logout_user').show();
		$('.anonymous').hide();
		if(user_auth < 5)
		{						
			// enable the admin stylesheet
			document.styleSheets[4].disabled = false;
			// draw the editor tools						
		}
	}
	else
	{
		$('.anonymous').show();
		// disable the admin stylesheet		
		document.styleSheets[4].disabled = true;
	}
	
	$('a[href*="#"]').click(function() 
	{
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
			 && location.hostname == this.hostname) 
		{
			 var $target = $(this.hash);
			 $target = $target.length && $target 
				|| $('[name=' + this.hash.slice(1) +']');
		
			 if ($target.length) 
			 {
				var targetOffset = $target.offset().top;
				$('html,body')
				   .animate({scrollTop: targetOffset}, 1000);
				return false;
			 }
		}
	});		
					
	$('button.button').live('click', function()
	{
		$(this).ajaxStart(function()
		{
		  
		  //when all page ajax functions start, do this:
		  if(jQuery("img", this).attr("src") != "/images/icons/ajax_loader.gif")
		  {
			jQuery("img", this).data('prev_img',jQuery("img", this).attr("src"));
		  }
		  jQuery("img", this).attr("src","/images/icons/ajax_loader.gif");
		  
		});
		$(this).ajaxComplete(function()
		{
		  //when all page ajax functions stop, do this:
		  jQuery("img", this).attr("src",jQuery("img", this).data('prev_img'));
		  $(this).unbind("ajaxStart");
		  $(this).unbind("ajaxComplete");
		});            
	});
	
	$('#submit_subscribe').click(function()
	{
		$(this).ajaxStart(function()
		{					  
		  //when all page ajax functions start, do this:
		  $(this).after('<img src="/images/icons/ajax_loader.gif" alt="" class="icon_subscribe" />');
		});
		$(this).ajaxComplete(function()
		{
		  //when all page ajax functions stop, do this:
		  $(this).next('img').remove();
		  $(this).unbind("ajaxStart");
		  $(this).unbind("ajaxComplete");
		}); 
	
	});
	
	$('div#user div form button.button_small').click(function()
	{
		$(this).ajaxStart(function()
		{
		  
		  //when all page ajax functions start, do this:
		  if(jQuery("img", 'a.cancel').attr("src") != "/images/icons/ajax_loader.gif")
		  {
			jQuery("img", 'a.cancel').data('prev_img',jQuery("img", 'a.cancel').attr("src"));
		  }
		  jQuery("img", 'a.cancel').attr("src","/images/icons/ajax_loader.gif");
		});
		$(this).ajaxComplete(function()
		{
		  //when all page ajax functions stop, do this:
		  jQuery("img", 'a.cancel').attr("src",jQuery("img", 'a.cancel').data('prev_img'));
		  $(this).unbind("ajaxStart");
		  $(this).unbind("ajaxComplete");
		}); 
	
	});
	
	$('a.social_comments').click(function()
	{
		var article_id = $(this).attr("rel");
		var tmp_this = this;				
		
		$(this).ajaxStart(function()
		{
		  
		  //when all page ajax functions start, do this:
		  if(jQuery("img", this).attr("src") != "/images/icons/ajax_loader.gif")
		  {
			jQuery("img", this).data('prev_img',jQuery("img", this).attr("src"));
		  }
		  jQuery("img", this).attr("src","/images/icons/ajax_loader.gif");
		  
		});
		$(this).ajaxComplete(function()
		{
		  //when all page ajax functions stop, do this:
		  jQuery("img", this).attr("src",jQuery("img", this).data('prev_img'));
		  $(this).unbind("ajaxStart");
		  $(this).unbind("ajaxComplete");
		});  	
		
		$.get("/index.php",{'do':'8','id':article_id},function(comments)
		{
			$(tmp_this).parent().siblings('div.social_results').children('div.comments').html(comments);
			$(tmp_this).hide();
			$(tmp_this).next().show();	
			if(scroll_comments == 1)
			{
				/*$(this).ajaxComplete(function()
				{
					$.scrollTo("#end_comments_"+article_id+"",1000, {offset:-10});
					$(this).unbind("ajaxComplete");
				});*/  /* Scroll to used for comments that appear at the bottom, ascending order. */
				scroll_comments = 0;
			}				
		});				
		clearInterval($(this).data('interval_id'));
		var tmp_id = setInterval(function() {
			$("a.social_comments[rel='"+article_id+"']").click();					
		}, 10000);					
		$(this).data('interval_id',tmp_id);
		
		
		
	});
	$('a.social_comments_hide').click(function()
	{
		clearInterval($(this).prev().data('interval_id'));	
		var article_id = $(this).attr("rel");
		$(this).parent().siblings('div.social_results').children('div.comments').html("");
		$(this).hide();
		$(this).prev().show();				
		
		$.get("/index.php",{'do':'11','id':article_id},function(count)
		{						
			$("a.social_comments[rel='"+article_id+"']").html("<img src=\"/images/icons/comments.png\" class=\"icon\" alt=\"\" />"+count+" comments");
		});
					
	});
	
	$('a.social_add_comment').click(function()
	{					
		add_comment_id = $(this).attr("rel");					
		$(this).parent().siblings('div.social_results').children('div.add_comment').toggle();
		$(this).toggle();
		$(this).next().toggle();
	});
	$('a.social_add_comment_cancel').click(function()
	{
		$(this).parent().siblings('div.social_results').children('div.add_comment').toggle();
		$(this).toggle();
		$(this).prev().toggle();
	});
	
	$('a.social_share').click(function()
	{							
		share_this_id = $(this).attr("rel");			
		$(this).parent().siblings('div.social_results').children('div.share_this').toggle();
		$(this).toggle();
		$(this).next().toggle();
	});
	$('a.social_share_cancel').click(function()
	{
		$(this).parent().siblings('div.social_results').children('div.share_this').toggle();
		$(this).toggle();
		$(this).prev().toggle();
	});
	
	$('a.delete_comment').live('click', function()
	{
		delete_id = $(this).attr("rel");
		$.get("/index.php",{'do':'12','id':delete_id},function(bool)
		{
			if(bool)
				$("div#comment_"+delete_id+"").fadeOut(900);
			else
				alert("Delete failed for an unknown reason.");
		});
	});	
	
	$('a.report_comment').live('click', function()
	{
		report_id = $(this).attr("rel");
		
		$(this).ajaxStart(function()
		{
		  
		  //when all page ajax functions start, do this:
		  if(jQuery("img", this).attr("src") != "/images/icons/ajax_loader.gif")
		  {
			jQuery("img", this).data('prev_img',jQuery("img", this).attr("src"));
		  }
		  jQuery("img", this).attr("src","/images/icons/ajax_loader.gif");
		  
		});
		$(this).ajaxComplete(function()
		{
		  $(this).unbind("ajaxStart");
		  $(this).unbind("ajaxComplete");
		});            
		if(user_auth != null)
		{
			$.get("/index.php",{'do':'13','id':report_id},function(bool)
			{
				if(bool)
				{
					$("div#comment_"+report_id+"").addClass("reported");
					$("div#comment_"+report_id+"").find('.report_comment').children('img').attr("src", "/images/icons/exclamation.png");;
				}
				else
					if($("div#comment_"+report_id+"").hasClass("reported"))
					{
						$("div#comment_"+report_id+"").removeClass("reported");		
						$("div#comment_"+report_id+"").find('.report_comment').children('img').attr("src", "/images/icons/exclamation_off.png");;
					}						
					else
						alert("Report failed for an unknown reason.");
			});
		}
		else
			alert("You must register or login to report a comment.");
	});	
	
	$('a.comment_reply').live('click', function()
	{
		reply_nick = $(this).parent().siblings('div.comment_content').children('h6').children('a.user_account').html();
		var parent_id = $(this).parent().parent().parent().parent().parent().attr('id');
		parent_id = parent_id.split("id_");	
		$('textarea#add_comment_content_'+parent_id[1]).html('@'+reply_nick+' ');						
		$(this).parent().parent().parent().siblings('div.add_comment').show();
		$('a.social_add_comment[rel="'+parent_id[1]+'"]').hide().next().show();				
	});	
	
	$('a.delete_comment').live('click', function()
	{
		delete_id = $(this).attr("rel");
		$.get("/index.php",{'do':'12','id':delete_id},function(bool)
		{
			if(bool)
				$("div#comment_"+delete_id+"").fadeOut(900);
			else
				alert("Delete failed for an unknown reason.");
		});
	});	
				
	$('a#logout').click(function()
	{
		$.get("/index.php",{'do':'5'});
		if(user_auth < 5)
		{
			
			$('.editor_recover').remove();
			// disable the admin stylesheet
			document.styleSheets[4].disabled = true;
		}
		user_auth = null;	
		$('.anonymous').show();					
		$(this).parent().fadeOut(300,function()
		{
			$('div#default_user').fadeIn(300);
		});	
		
		
	});
	
	$('a#login').click(function()
	{
		$('div#default_user').fadeOut(300,function()
		{
			$('div#login_form').fadeIn(300);						
		});
	});
	
	$('a#register').click(function()
	{
		$('div#default_user').fadeOut(300,function()
		{
			$('div#register_form').fadeIn(300);
		});
	});
	
	$('a#login_help_icon').click(function()
	{
		$('div#login_form').fadeOut(300,function()
		{
			$('div#login_help').fadeIn(300);
		});
	});
	
	$('a.cancel').click(function()
	{
		$(this).parent().parent().fadeOut(300,function()
		{
			$('div#default_user').fadeIn(300);
		});
	});
	
	clear_on_focus();
	change_to_pw();
	
	var facebox_link;
	$('.btn_facebox').click(function()
	{
		facebox_link = this;
	});	
	$(document).bind('loading.facebox', function()
	{
		if(jQuery("img", facebox_link).attr("src") != "/images/icons/ajax_loader.gif")
		{
			jQuery("img", facebox_link).data('prev_img',jQuery("img", facebox_link).attr("src"));
		}
		jQuery("img", facebox_link).attr("src","/images/icons/ajax_loader.gif");
	});	
	$(document).bind('afterReveal.facebox', function()
	{
		jQuery("img", facebox_link).attr("src",jQuery("img", facebox_link).data('prev_img'));
	});				
	jQuery('.btn_facebox').facebox();
			
	
	
	// bind 'form_contact' and provide a callback function 
	$('form#form_contact').ajaxForm({
	  target: '#contact_result', 
	  success: function()
	  {             			
	  }
	});
	// bind 'form_subscribe' and provide a callback function 
	$('form#form_subscribe').ajaxForm({
	  target: '#subscribe_result', 
	  success: function()
	  {        
	  	$('#subscribe_result').children('span').fadeIn(300).fadeOut(3000);		
	  }
	});	
	// bind 'form_share_this' and provide a callback function 
	$('form.form_share_this').ajaxForm({
	  success: function(responseText)
	  {           
	  	 $("#share_this_result_"+share_this_id).html(responseText).fadeIn(300).fadeOut(3000); 			
	  }
	});
	// bind 'form_add_comment' and provide a callback function 
	$('form.form_add_comment').ajaxForm({
	  success: function(responseText)
	  {        
		var string = $("a.social_comments[rel='"+add_comment_id+"']").html();
		var prev_count = string.match(/\d+/);
		
		$.get("/index.php",{'do':'11','id':add_comment_id},function(count)
		{
			
			$("a.social_comments[rel='"+add_comment_id+"']").html("<img src=\"/images/icons/comments.png\" class=\"icon\" alt=\"\" />"+count+" comments");
			if(prev_count != count)
			{						
				$("a.social_add_comment[rel='"+add_comment_id+"']").toggle();
				$("a.social_add_comment[rel='"+add_comment_id+"']").next().toggle();
				$("form.form_add_comment[name='"+add_comment_id+"']").parent().fadeOut(0,function()
				{
					scroll_comments = 1;
					$("a.social_comments[rel='"+add_comment_id+"']").click();			
																
				});
			}
			else
				$("#add_comment_result_"+add_comment_id).html(responseText).fadeIn(300).fadeOut(3000);
		});
		
		
	  }
	});	
	// bind 'form_login' and provide a callback function 
	$('form#form_login').ajaxForm({
	  target: '#login_result', 
	  success: function()
	  {        
		$('#login_result').fadeIn(300).fadeOut(3000);
		if(user_auth != null)
		{
			on_login();
			$('#login_form').fadeOut(900,function()
			{
				$('#logout_user').fadeIn(300);
			});
		}					
	  }
	});	
	// bind 'form_login_help' and provide a callback function 
	$('form#form_login_help').ajaxForm({
	  target: '#login_help_result', 
	  success: function()
	  {        
		$('#login_help_result').fadeIn(300);									
	  }
	});	
	// bind 'form_register' and provide a callback function 
	$('form#form_register').ajaxForm({
	  target: '#register_result', 
	  success: function()
	  {        
	  	$('#register_result').fadeIn(300).fadeOut(3000);
		if(user_auth != null)
		{
			on_login();
			$('#register_form').fadeOut(900,function()
			{
				$('#logout_user').fadeIn(300);
			});	
		}					
	  }
	});					
});	


$(document).bind('reveal.facebox', function() { 
	bind_form_account();
});


	
function on_login()
{
	$('.anonymous').hide();
	if($('a.social_comments:hidden'))
		$('a.social_comments:hidden').click();
	if(user_auth < 5)
	{
		// enable the admin stylesheet
		document.styleSheets[4].disabled = false;					
		$('#content_data').prepend('<div id="refreshing" class="message alert">Refreshing the blog listing now...</div>');
		$('#refreshing').fadeOut(3000,function()
		{
			$('#refreshing').remove();
		});
		refresh_blogs();														
	}
}	

// bind 'form_edit_title' and provide a callback function 
function bind_form_edit_title()
{
	$('form.form_edit_title').ajaxForm({
		success: function(responseText)
		{  
			var old_title = $('.edit_container').next().html();
			old_title = old_title.split("<img");
			var new_title = responseText + "<img" + old_title[1];
			$('.edit_container').next().html(new_title);
			$('.edit_container').next().toggle();  
			$('.edit_container').remove();						
			$('#edit_publish').attr("src", $('#edit_publish').data('prev_img'));						
		}
	});
}	

// bind 'form_edit_content' and provide a callback function 
function bind_form_edit_content()
{
	$('form.form_edit_content').ajaxForm({
		success: function(responseText)
		{  
			var old_content = $('.edit_container').next().html();
			old_content = old_content.split("<img");
			var new_content = responseText + "<img" + old_content[1];
			$('.edit_container').next().html(new_content);
			$('.edit_container').next().toggle();  
			$('.edit_container').remove();						
			$('#edit_publish').attr("src", $('#edit_publish').data('prev_img'));						
		}
	});
	$('form.form_edit_content').bind('form-pre-serialize', function(event, $form, options) {
	    tinyMCE.triggerSave();
	}); 
}

// bind 'form_edit_author' and provide a callback function 
function bind_form_edit_author()
{
	$('form.form_edit_author').ajaxForm({
		success: function(responseText)
		{  ;
			var old_author = $('.edit_container').next().html();
			old_author = old_author.split("<img");
			var new_author = responseText + "<img" + old_author[1];
			$('.edit_container').next().html(new_author);
			$('.edit_container').next().toggle();  
			$('.edit_container').remove();						
			$('#edit_publish').attr("src", $('#edit_publish').data('prev_img'));						
		}
	});
}

// bind 'form_add_post' and provide a callback function 
function bind_form_add_post()
{
	$('form.form_add_post').ajaxForm({
		success: function(responseText)
		{  
			$('#article_id_new').fadeOut(300,function()
			{
				$('#article_id_new').remove();
				$('#content_column').prepend(responseText);			
			});						
		}
	});
	$('form.form_add_post').bind('form-pre-serialize', function(event, $form, options) {
	    tinyMCE.triggerSave();
	}); 
}					

function refresh_blogs()
{				
	var html = document.location.href.match(".html");
	var blog = document.location.href.match("/blog/");
	
	if(html == null && blog !== null)
	{
		// blog listing refreshed
		$.get("/index.php",{'do':'20'},function(blog_data)
		{
			
			$('div#content_column').html(blog_data);						
			 		
		});					
		$(this).ajaxComplete(function()
		{
			//when all page ajax functions stop, do this:
			$(this).unbind("ajaxComplete");
		});				 			
	}				
}		

// bind 'form_account' and provide a callback function 
function bind_form_account()
{
	$('form#form_account').ajaxForm({
		target: '#account_result', 
		success: function()
		{  
			$('#account_result').children().fadeIn(300).fadeOut(3000); 
			user_img = $('div#account_result').find('span.positive').attr("rel"); 
			if(user_img)
			{
				$('img#user_tn').attr("src", "/images/user/" + user_img);
			}   		
		}
	});
}			

function clear_on_focus()
{
  //clear input elements on focus
  $("input[type='text']").focus(function() {
	if( this.value == this.defaultValue && !$(this).hasClass('change_to_pw') && !$(this).hasClass('current_edit')) {
	  this.value = "";
	}
  }).blur(function() {
	if( !this.value.length ) {
	  this.value = this.defaultValue;
	}
  });
  //clear textarea elements on focus
  //$("textarea").focus(function() {
  //	if( this.value == this.defaultValue && !$(this).hasClass('current_edit') ) {
  //	  this.value = "";
  //	}
  //}).blur(function() {
  //	if( !this.value.length ) {
  //	  this.value = this.defaultValue;
  //	}
  //});	
}

function change_to_pw()
{
  $("input[type='text'].change_to_pw").focus(function()
  {
	$(this).hide();
	$(this).next().show().focus().blur(function(){if(this.value == this.defaultValue){$(this).hide();$(this).prev().show();}});
  });      
}