﻿/*  @Perfect World Entertainment
 *  @class BlogManager
 *  @requires document, page, jQuery
 *  @description
 *
 *  Controls the functionality of the blog
 */


BlogManager = {

	config: {SEARCH_TEXT: 'Search'},
	replyID: null,
	linkedSelected: false,

	init: function(){
		BlogManager.bindEvents();
	},

	bindEvents: function(){
		$('#txtPostSearch01').bind('click', BlogManager.searchToggle);
		$('#txtPostSearch01').bind('blur', BlogManager.searchOnBlur);
		$('.reply-btn').bind('click', BlogManager.showReply);			
		$('.postReply').bind('click', BlogManager.validateReply);
		$('.PostComment').bind('click', BlogManager.validateComment);
		$('#article').find('.check-login').bind('click', BlogManager.scrollToComment);
		$('.delete-btn').bind('click', BlogManager.deleteComment);
		$('.delete-reply-btn').bind('click', BlogManager.deleteReply);
	},

	searchToggle: function(){
		if ($(this).val() == BlogManager.config.SEARCH_TEXT) $(this).val('');;
	},

	searchOnBlur: function(){
		if ($(this).val() == '') $(this).val(BlogManager.config.SEARCH_TEXT);
	},

	scrollToComment: function(){
		if ($(this).hasClass('require-login')) return;

		var c;
		c = $.browser.safari ? $("body") : $("html");
		c.animate({ scrollTop: $('#comment-container').offset().top - 200 }, 450);		
	},

	removeInlineColor: function(html){

		var regx = /color\: rgb\(0\, 0\, 0\)\;|color\=\"\#000000\"/g;

		return html.replace(regx, '');

	},

	selectSublink: function(){

		if(BlogManager.linkSelected) return;

		var query = location.search.replace('?', '');
		var vars = query.split('&');
		var get = [];
		var regx = /^\w{1,3}(-| )|-/gi;

		for(var i = 0; i<vars.length; i++){

			var k = vars[i].split('=');
			
			get.push(k[1].replace(regx, ''));

		}	

		var sublinks = [];

		$('.sublink').find('li').each(function(){

			sublinks.push($(this).text().toLowerCase());

		});

		$('.tags').find('a').each(function(){
		
			get.push($(this).text().toLowerCase().replace(regx, ' '));

		});
		
		var regx = /^\s|\s$/gi;

		for(i = 0; i<get.length; i++){

			get[i] = get[i].replace(regx, '');	

			for(var t = 0; t<sublinks.length; t++){
	
				if(sublinks[t] == get[i]){
					$('.sublink').find('li').removeClass('selected');
					$('.sublink').find('li').eq(t).addClass('selected');
					BlogManager.linkSelected = true;
					return;
				}				

			}

		}
			
	},

	//slides the reply box down when the reply button is clicked

	showReply: function(){

		BlogManager.replyID = $(this).parent().attr("id").replace('b', '');
	
		var addReply = $('#r'+BlogManager.replyID).find('.addReply');	

		if(addReply.is(":visible") || addReply.hasClass('curReply')){

			 addReply.slideUp(350);
			 addReply.removeClass('curReply');

		}else{

			 $('.curReply').slideUp(350);
			 $('.curReply').removeClass('curReply');
			 addReply.slideDown(350);
			 addReply.addClass('curReply');
		}

	},

	//validates reply field then sends an ajax request with the data

	validateReply: function(){

		$('p.blog-error').hide();
		$('textarea.blog-error').removeClass('blog-error');

		var form = $(this).parent().parent();
		var textarea = form.find('textarea').eq(0);
	
		if(textarea.val() == ''){

			form.find('p.blog-error').show();
			textarea.addClass('blog-error');
			return;
		}
		
		$.ajax({

			url: '/blog/wp-comments-post.php',
			type: 'post',
			data: 'comment='+textarea.val()+'&comment_post_ID='+form.find('.postID').val()+'&comment_parent='+form.find('.commentParent').val(),
			
			success: function(data){

				var replyData = JSON.parse(data);
				
				if(replyData.status != 'successful'){ //if the data wasn't written to the DB

					textarea.after('<p class="blog-error">'+replyData.msg+'</p>');
					form.find('.blog-error').eq(0).show();
					return;

				};

				//mark up for sub list-item with the replied text

				var html = '<li class="sub01" style="display: none;"><h3><a href="http://core.perfectworld.com/u/'+replyData.data.comment_author+'">'+replyData.data.comment_author+'</a></h3><p>'+replyData.data.comment_content+'</p></li>';
				var sibling = form.parent(), target = null;

				while(true){ //gets last response so we can append it to the end of the responses

					target = sibling.next();
					if(target.attr('id').length > 0){
						
						sibling.after(html);
						break;

					}

					sibling = target;

				}	

				sibling.next().slideDown(500);
				form.find('.curReply').slideUp(350);
				textarea.val('');	
			},

			error: function(xhr, err){

				 textarea.after('<p class="blog-error">There was an error submitting your response.</p>');

			}

		});


	},

	//validates data for comments and sends an ajax request

	validateComment: function(){
		
		$('p.blog-error').hide();
        $('textarea.blog-error').removeClass('blog-error');

        var form = $(this).parent().parent();
        var textarea = form.find('textarea').eq(0);

        if(textarea.val() == ''){

            form.find('p.blog-error').show();
            textarea.addClass('blog-error');
            return;
        }
	
		$.ajax({

            url: '/blog/wp-comments-post.php',
            type: 'post',
            data: 'comment='+textarea.val()+'&comment_post_ID='+form.find('#comment_post_ID').val()+'&comment_parent=0"',

            success: function(data){
					
                var replyData = JSON.parse(data);				

                if(replyData.status != 'successful'){ //if the data was unable to be written to the DB

                    textarea.next().after('<p class="blog-error">'+replyData.msg+'</p>');
                    form.find('.blog-error').eq(1).show();
					return;

                };

				var commentsList = $('.commentsList');
				var cls = '';

				(commentsList.find('li').eq(0).attr('class') == 'odd')? cls = 'even' : cls = 'odd';				
				
				//mark up for adding an additional comment row

                var html = '<li class="'+cls+'" id="commentsID'+replyData.data.comment_ID+'" style="display: none;"><h3><a href="http://core.perfectworld.com/u/'+replyData.data.comment_author+'">'+replyData.data.comment_author+'</a><span class="timestamp">@ '+replyData.data.comment_date+'</span></h3><p>'+replyData.data.comment_content+'</p><a id="b'+replyData.data.comment_ID+'" class="btn"><span class="ico-arrow reply-btn">Reply</span></a>';

				var replyhtml = '<form id="r'+replyData.data.comment_ID+'" class="reply-form" method="post" action="/blog/wp-comments-post.php"><div class="addComments addReply"><p>Replying to <strong>'+replyData.data.comment_author+'</strong></p><textarea cols="" rows="" name="comment"></textarea><p class="blog-error" style="display: none;">Please write a reply</p><p id="s'+replyData.data.comment_ID+'" class="postReply">Post Reply</p></div><input type="hidden" class="postID" value="'+replyData.data.comment_post_ID+'" /><input type="hidden" class="commentParent" value="0" /></form>';

				if(location.search.indexOf('page') != -1){

					var notehtml = '<p> *note: This comment will appear on page 1 upon page refresh. </p>';

				}else{

					var notehtml = '';

				}

				var endinghtml = '</li>'

				//add comment to the list

				commentsList.prepend(html + replyhtml + notehtml + endinghtml);
				
				//add event listeners for the newly created elements

				commentsList.find('li').eq(0).find('.reply-btn').bind('click', BlogManager.showReply);
        		commentsList.find('li').eq(0).find('.postReply').bind('click', BlogManager.validateReply);
			
				if($.browser.safari){

					$('body').animate({ scrollTop: commentsList.offset().top - 250 }, 550);
			
				}else{
	
					$('html').animate({ scrollTop: commentsList.offset().top - 250 }, 550);
                
				}

				setTimeout("$('.commentsList').find('li').eq(0).slideDown(500)", 600);
                textarea.val('');
				
            },

            error: function(xhr, err){

                 textarea.after('<p class="blog-error">There was an error submitting your response.</p>');

            }

        });


	},

	deleteComment: function(){

		var c = confirm("Are you sure you want to delete this comment?");

		if(!c) return;

		var comment = $(this).parent();
		var id = comment.attr('id').replace('commentsId', '');

		$.ajax({

			url: 'deleteComment.php',
			type: 'post',
			data: 'id='+id,
			success: function(data){
				
				var replyData = JSON.parse(data);

				if(replyData.status == 'failed'){

					alert(replyData.msg);
					return;

				}

				comment.slideUp(350);
				setTimeout("comment.remove()", 375);
			},

			error: function(){

				alert("There was an error deleting this post.");

			}

		});			

	},

	deleteReply: function(){

		var c = confirm("Are you sure you want to delete this reply?");

		if(!c) return;

		var comment = $(this).parent();
        var id = comment.find('input[type=hidden]').eq(0).val();
        
		$.ajax({

            url: 'deleteComment.php',
            type: 'post',
            data: 'id='+id,
            success: function(data){

                var replyData = JSON.parse(data);

                if(replyData.status == 'failed'){

                    alert(replyData.msg);
                    return;

                }

                comment.slideUp(350);
                setTimeout("comment.remove()", 375);
            },

            error: function(){

                alert("There was an error deleting this post.");

            }

        });

	}

}

Page.queue(BlogManager.init);



