$(function(){
	$("#login_form").submit(function()
	{
		$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
		//check the username exists or not from ajax
		var username = $("#txtUsername").val();
		var password = $("#txtPass").val();
		var rndnum = Math.random(); //Spoof the Cache
		
		$.post("../../processors/login.php",{ username:username, password:password ,rand:rndnum } ,function(data)
        {
		  if(data=='yes') //if correct login detail
		  {
		  	$("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1,
              function()
			  { 
			  	 //redirect to secure page
				 document.location='../userpanel/index.php';
			  });
			  
			});
		  }
		  else 
		  {
		  	$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $(this).html('Login Failed...').addClass('messageboxerror').fadeTo(900,1);
			});		
          }
				
        });
 		return false; //not to post the  form physically
	});
	//now call the ajax also focus move from 
	$("#txtPass").blur(function()
	{
		$("#login_form").trigger('submit');
	});
	
	$('a#forgotpass').facebox({        	loadingImage : '../../css/facebox/loading.gif',        	closeImage   : '../../css/facebox/closelabel.gif'
    });	
	$('#frmforgotpass').livequery("submit", function(){
		var emailAddress = $('#txtEmail').val();
		$.facebox(function(){
			$.post("../../processors/forgotpass.php", {emailAddress:emailAddress}, function(data){
				$.facebox(data);
			});
		});
		return false;
	});
	
	//	Hide Comments
	$(".blogComments").livequery(function(){
		$(this).hide();
	});
	
	//	Create Category Links
	$(".categoryList a").livequery(function(){
		$(this).attr({"href":"getPosts.php?categoryId=" + $(this).attr("name")});
	});
	
	//	Create Archive Links
	$(".archiveList a").livequery(function(){
		$(this).attr({"href":"getPosts.php?archiveDate=" + $(this).attr("name")});
	});
	
	//	Create Blogger Links
	$(".bloggerList a").livequery(function(){
		$(this).attr({"href":"getPosts.php?bloggerId=" + $(this).attr("name")});
	});
	
	//	Show Comments
	$(".showComment a").livequery('click', function(){
		$(this).parent().parent().parent().next().slideToggle("slow");
		return false;
	});
	
	//	Retrieve New Post Form
	$("#addPost").click(function(){
		$.facebox(function(){
			$.post('getNewPostFrm.php', function(data){
				$.facebox(data);
				tinyMCE.init({
					// General options
					mode : "exact",
					elements: "blog_entry_text",
					theme : "advanced",
					convert_urls : false,
					plugins : "safari,pagebreak,style,layer,table,advhr,advimage,advlink,emotions,iespell,insertdatetime,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,inlinepopups",
					theme_advanced_buttons1: "bold, underline, strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontsizeselect,|,cut,copy,paste,pastetext,pasteword,|,search,replace"
				});
				$("#facebox .body").css("width", "500px");
			});
		});
		return false;
	});
	
	// Submit New or Update Post
	$('#frmBlogEntry').livequery('submit', function(){
		var title = $("#blog_entry_title").val();
		var content = tinyMCE.get('blog_entry_text').getContent()
		var tags = $("#blog_entry_tags").val();
		var category = $("#blog_category_id").val();
		var entryId = $("#blog_entry_id").val();
		var errorMsg = '';
		if(title == ''){
			errorMsg = errorMsg + ' Please enter a title.';
		}
		if(content == ''){
			errorMsg = errorMsg + ' Please enter content.';
		}
		if(errorMsg != ''){
			alert(errorMsg);
			return false;
		}
		tinyMCE.execCommand('mceFocus', false, 'blog_entry_text');                    
		tinyMCE.execCommand('mceRemoveControl', false, 'blog_entry_text');
		$.facebox(function(){
			if(entryId != 'undefined' && entryId != ''){
				//	Update Post
				$.post('saveBlogEntry.php', {entryId:entryId, title:title, content:content, tags:tags, category:category}, function(data){
					$.facebox(data + '<br/><a href="#" class="refreshWindow">Click to Refresh.</a>');
				});
			}
			else{
				//	Add New Post
				$.post('saveBlogEntry.php', {title:title, content:content, tags:tags, category:category}, function(data){
					$.facebox(data + '<br/><a href="#" class="refreshWindow">Click to Refresh.</a>');
				});
			}
		});
		return false;
	});
	
	//	Update Entry
	$(".entryEdit a").livequery("click", function(){
		var id = $(this).attr("name");
		$.facebox(function(){
			$.post('getEditPostFrm.php',{id:id}, function(data){
				$.facebox(data);
				tinyMCE.init({
					// General options
					mode : "exact",
					elements: "blog_entry_text",
					theme : "advanced",
					convert_urls : false,
					plugins : "safari,pagebreak,style,layer,table,advhr,advimage,advlink,emotions,iespell,insertdatetime,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,inlinepopups",
					theme_advanced_buttons1: "bold, underline, strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontsizeselect,|,cut,copy,paste,pastetext,pasteword,|,search,replace"
				});
				$("#facebox .body").css("width", "500px");
			});
		});
		return false;
	});
				
	//	Remove Entry
	$(".entryRemove a").livequery("click", function(){
		var id = $(this).attr("name");
		$.facebox(function(){
			$.post("removeBlogEntry.php", {id:id}, function(data){
				$.facebox(data + '<br/><a href="#" class="refreshWindow">Click to Refresh.</a>');
			});
		});
		return false;
	});
	
	//	Get New Comment Form
	$(".postComment a").livequery("click", function(){
		var entryId = $(this).attr("name");
		$.facebox(function(){
			$.post('getNewCommentFrm.php', {entryId:entryId}, function(data){
				$.facebox(data);
				tinyMCE.init({
					// General options
					mode : "exact",
					elements: "blog_comment_text",
					theme : "simple",
					theme_advanced_buttons1: "bold, underline, strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontsizeselect"
				});
				$("#facebox .body").css("width", "500px");
			});
		});
		return false;
	});

	//	Update or Add Comment
	$('#frmBlogComment').livequery('submit', function(){
		var content = tinyMCE.get('blog_comment_text').getContent();
		var commentId = $("#blog_comment_id").val();
		var entryId = $("#blog_entry_id").val();
		var authorName = $("#blog_comment_author").val();
		var authorEmail = $("#blog_comment_author_email").val();
		var authorURL = $("#blog_comment_author_url").val();
		var errorMsg = '';
		if(content == ''){
			errorMsg = errorMsg + 'Please enter content.\n';
		}
		if(entryId == ''){
			errorMsg = errorMsg + 'Error: Please try again.\n';
		}
		if(authorName == ''){
			errorMsg = errorMsg + 'Please enter your name.\n';
		}
		if(authorEmail == ''){
			errorMsg = errorMsg + 'Please enter your email address.\n';
		}
		if(errorMsg != ''){
			alert(errorMsg);
			return false;
		}
		tinyMCE.execCommand('mceFocus', false, 'blog_comment_text');                    
		tinyMCE.execCommand('mceRemoveControl', false, 'blog_comment_text');
		$.facebox(function(){
			/*if(commentId != 'undefined' && commentId != ''){
				//	Update Post
				$.post('saveBlogComment.php', {entryId:entryId, commentId:commentId, content:content}, function(data){
					$.facebox(data + '<br/><a href="#" class="refreshWindow">Click to Refresh.</a>');
				});
			}
			else{*/
				//	Add New Comment
				$.post('saveBlogComment.php', {authorName:authorName, authorEmail:authorEmail, authorURL:authorURL, content:content, entryId:entryId}, function(data){
					$.facebox(data + '<br/><a href="#" class="refreshWindow">Click to Refresh.</a>');
				});
			/*}*/
		});
		return false;
	});
	
	//Zebra Stripe Comments
	$(".blogCommentWrapper").livequery(function(){
		$(".blogCommentWrapper:even").css({'background-color':'#CBC49C'});
		$(".blogCommentWrapper:odd").css({'background-color':'#E4DFBE'});
	});
	
	//Refresh Window
	$(".refreshWindow").livequery("click", function(){
		location.reload(true);
		return false;
	});
	
	//	Resize all images in the blog post.
	var targetWidth = 500; // The max width.
	$(".content img").livequery(function(){
		$(".content img").each(function(){
			var currentWidth = $(this).width();
			var currentHeight = $(this).height();
			if(currentWidth <= targetWidth){
			}
			else{
				var newWidth = targetWidth;
				var newHeight = null;
				newHeight = (currentHeight * newWidth) / currentWidth;
				$(this).css({"width":newWidth+"px", "height":newHeight+"px"});
				/*$(this).width(newWidth);
				$(this).height(newHeight);*/
			}
		});
	});
});