/******************************************************************************
 Name:    Lifeyo
 Version: 1.0 Beta
 Author:  Wiwat Ruengmee
 Email:   wiwat@scapenetworks.com
 ******************************************************************************/
// Global namespace
var Lifeyo = {};
var divPost;
var postId;
var divComment = "wow";
var commentId;
Lifeyo.actions = {};

// Actions
Lifeyo.actions.getPostsByAuthorName = function getPostsByAuthorName(author){
    // Empty blog content
    $("div#blog-content").html('');
    $.getJSON("/ajax/get_posts_by_author_name/" + author + '/', function(json){
        var divPost;
        var postId;
        json = json.reverse();
        if (json.length == 0) {
            $("div#blog-content").append('<div class="error-msg"><p>Sorry. No blogs found.<p><div>');
        }
        for (var i = 0; i < json.length; i++) {
            divPost = '';
            postId = 'post_' + json[i].pk;
            divPost += '<div id="post_' + json[i].pk + '" class="hentry" onmouseover="return false">';
            
            divPost += '<div class="rbcRowMenu" style="right: 20px; top: 20px; visibility: hidden;">';
            divPost += '<div class="rowMenuInner">'
            divPost += '<a class="rowMenuEdit" onclick="Lifeyo.actions.editPost(\'' + postId + '\')"; return false;>';
            divPost += '<img onmouseout="this.src=\'/static/images/edit_post_reg.png\'" onmouseover="this.src=\'/static/images/edit_post_hov.png\'" title="Edit" src="/static/images/edit_post_reg.png"/>'
            divPost += '</a>'
            divPost += '<a class="rowMenuEdit" onclick="Lifeyo.actions.deletePost(\'' + postId + '\')"; return false;>';
            divPost += '<img onmouseout="this.src=\'/static/images/delete_reg.png\'" onmouseover="this.src=\'/static/images/delete_hov.png\'" title="Delete" src="/static/images/delete_reg.png"/>'
            divPost += '</a>'
            divPost += '</div>'
            divPost += '</div>'
            
            divPost += '<div class="entry-datetime">' + json[i].fields.pub_date.split(" ")[0].replace("-", ".").replace("-", ".") + '</div>';
            divPost += '<div class="title-date-container">' + '<h2 class="entry-title click-to-edit">' + json[i].fields.title + '</h2>' + '</div>';
            divPost += '<div class="entry-content">' + json[i].fields.body + '</div>';
            divPost += '<div class="entry-meta"> Posted by: <span>' + json[i].fields.author_fname + '</span></div>';
            divPost += '</div>';
            $("div#blog-content").append(divPost);
            
            var newPost = $('#blog-content > div:last-child');
        }
    });
}


Lifeyo.actions.getAllPosts = function getAllPosts(show, start, one){
    // Empty blog content
    $("div#blog-content").html('');
    
    var startSpot=start;
	var showNum=show;
	var ajaxURL="/ajax/get_all_posts/"+showNum+"/"+startSpot+"/";
	
	if (one == 1){ajaxURL="/ajax/get_one_post/"+showNum+"/"; }
	
	
	$.getJSON(ajaxURL, function(json){
        var divPost;
        var postId;
        var divComment;
        var commentId;
        json = json.reverse();
        if (json.length == 0) {
            $("div#blog-content").append('<p>Sorry. No blogs found.<p>');
        }
        for (var i = 0; i < json.length; i++) {
            divPost = '';
            postId = 'post_' + json[i].pk;
            divPost += '<div id="post_' + json[i].pk + '" class="hentry" onmouseover="return false">';
            
            divPost += '<div class="rbcRowMenu" style="right: 20px; top: 20px; visibility: hidden;">';
            divPost += '<div class="rowMenuInner">'
            divPost += '<a class="rowMenuEdit" onclick="Lifeyo.actions.editPost(\'' + postId + '\')"; return false;>';
            divPost += '<img onmouseout="this.src=\'/static/images/edit_post_reg.png\'" onmouseover="this.src=\'/static/images/edit_post_hov.png\'" title="Edit" src="/static/images/edit_post_reg.png"/>'
            divPost += '</a>'
            divPost += '<a class="rowMenuEdit" onclick="Lifeyo.actions.deletePost(\'' + postId + '\')"; return false;>';
            divPost += '<img onmouseout="this.src=\'/static/images/delete_reg.png\'" onmouseover="this.src=\'/static/images/delete_hov.png\'" title="Delete" src="/static/images/delete_reg.png"/>'
            divPost += '</a>'
            divPost += '</div>'
            divPost += '</div>'
            
            divPost += '<div class="entry-datetime">' + json[i].fields.pub_date.split(" ")[0].replace("-", ".").replace("-", ".") + '</div>';
            divPost += '<div class="title-date-container">' + '<h2 class="blog-title">' + json[i].fields.title + '</h2>' + '</div>';
            divPost += '<div class="entry-content">' + json[i].fields.body + '</div>';
            divPost += '<div class="posted-by">Posted by: <span>' + json[i].fields.author_fname + '</span><div class="IconBox"><img src="/static/images/comments/' + json[i].fields.author_fname + '.png" /></div></div>';

			
            divPost += '<div class="entry-comment"><br><hr>';
			divPost += '<img src="/static/images/comments/comment_bubble.png">&nbsp;<span id="commentsAlready_' + postId + '" onclick="Lifeyo.actions.toggleCommentContainer(\'' + postId + '\')" class="commentsAlready">There are no comments yet.</span><br>';
			divPost +='<div class="PostCommentBtn"><a href="#" onclick="Lifeyo.actions.toggleCommentForm(\'' + postId + '\'); return false;" id="PostCommentBtn_' + postId + '">&nbsp;</a></div>';
			divPost +='<div class="ViewCommentsBtn"><a href="#" onclick="Lifeyo.actions.toggleCommentContainer(\'' + postId + '\'); return false;" id="ViewCommentsBtn_' + postId + '"></a></div>';
			divPost +='<div id="SharePostBtn_' + postId + '"  class="SharePostBtn"><a href="#" onclick="return false;"></a></div>';
			
			
			divPost += '</div><br><br><br>';
			
			

			//This is the div that shows and hides
			divPost += '<div id="comment_form_' + postId + '" style="display:none">';
			
			
			
			
			//adjustable dialog box container
			divPost+='<div class="dialog"><div class="content"><div class="t"></div>';
			
            divPost+='<div class="title-comment-container"><input name="name_' + postId + '" type="text" id="name_' + postId + '" value="Your name.." maxlength="10"/></div>';
			
			divPost+='<div class="body-comment-container"><textarea name="comment_' + postId + '" id="comment_' + postId + '" >Say something..</textarea></div>';
			
			
				divPost+='<div id="CommentBoxBtns">';
			divPost +='<div id="AddCommentBtn_' + postId + '" class="AddCommentBtn"><a href="#" onclick="Lifeyo.actions.addComment(\'' + postId + '\'); return false;">&nbsp;</a></div>';
			divPost +='<div id="CancelCommentBtn_' + postId + '" class="CancelCommentBtn"><a href="#" onclick="Lifeyo.actions.toggleCommentForm(\'' + postId + '\'); return false; "></a></div>'
			divPost+='</div><br>';
			//end adjustable dialog container
			divPost+='</div><div class="b"><div></div></div></div>';
			
		
			
			//end the show hide divComment Div
			divPost+='</div>';
            
            // Empty blog comments container that will be filled after.
			divPost += '<br><div id="comment_container_' + postId + '" style="display:none"></div><br><br>';
         
            //dow check and loop through any comments for this POST
            //move back one position, for the reason, I dont know.
            
            current = json[i].pk;
            //current = current - 1;
            
            //execute ajax call
            $.getJSON("/ajax/get_all_comments/" + current, function(json2){
            
            json2 = json2.reverse();
            
                
              
			   var postNum=json2.length;
			   
			   
			   if (postNum > 0) {
				   //find out where this is because the loops dont keep up.
				   var BlogLocation=json2[0].fields.entry;
			   }
			   
			   
			   
			   
				var textNow="#commentsAlready_post_"+ BlogLocation;
                 //change the sentance that displays how many comments are there.
				var sentance = "There ";
				if (postNum > 1){ sentance+="are ";}else{sentance+="is ";}
				sentance+="("+ postNum + ") comment";
				if (postNum > 1){ sentance+="s";}
				sentance+=" so far";
				
				$(textNow).text(sentance);
					
                
                for (var j = 0; j < json2.length; j++) {
					
					var AuthorName=json2[j].fields.author;
					var thumbImage;
					if (AuthorName=='Ryan May') {thumbImage="Ryan.png";}
					else if(AuthorName=="Codey May") {thumbImage="Codey.png";}
					else if(AuthorName=="Mike Kai") {thumbImage="Mike.png";}
					else if(AuthorName=="Wiwat") {thumbImage="Wiwat.png";}
					else if(AuthorName=="B Berg") {thumbImage="Betsy.png";}
					else{thumbImage="bolt.png";}
					
					divComment = '';
                    divComment += '<div id="comment_' + json2[j].pk + '" class="commentBlock">';
					
					//User Icon
					divComment+='<div class="CommentIcon"><img style="margin-top:5px" src="/static/images/comments/'+thumbImage+'"><br> '+ json2[j].fields.author + '</div>';
					
					
					//this is where the  dialog buble starts.
					divComment+='<div class="cloudContainer">';
					divComment+='<div class="commentBubble"><div class="content"><div class="t"></div>';
				
                    divComment += '<div class="commentParagraph">' + json2[j].fields.body + '</div>';
                    divComment += '<div class="commentDate">' + json2[j].fields.created_at.split(" ")[0].replace("-", ".").replace("-", ".") + '</div>';
                    
                    
					//dialog bubble ends
					divComment += '</div><div class="b"><div></div></div></div><br>';
					
					divComment += '</div><br><br>';
          			var spotNow="div#comment_container_post_"+json2[j].fields.entry;
					
                    $(spotNow).append(divComment);
            		//alert ("wow");
            		var newPost = $('#blog-content > div:last-child');
                   
				 
					
                }
				
				
				
                
            });
            
      
          
       
			
            divPost += '</div>';
            $("div#blog-content").append(divPost);
            //alert ("wow");
            var newPost = $('#blog-content > div:last-child');
			
			
        }
    });
};


Lifeyo.actions.addComment = function(postId){
    parts=postId.split("_");
	postId=parts[1];
	//conf = confirm("Are you sure you want to post this comment? to"+postId);
	commentID='#comment_post_'+postId;
	nameID='#name_post_'+postId;
	
	
	
	var comment = $(commentID).val();
	var author = $(nameID).val();
	
	$('#comment_form_post_'+postId).animate({opacity: "hide"}, "fast");
	//Going to chnage the status text to say accetpted
	 //change the button so its not pluged in anymore
	$('a#PostCommentBtn_post_'+postId).css("background-position", "");
	
	//change the view comments button to be pligged in
	$('a#PostCommentBtn_'+postId).css("background-position", "0 -45px");
	
	
	
	//Going to want to update the Field that displays how many posts have been made..
	//first get what is in there right now.
	var textAlready="#commentsAlready_post_"+ postId;
	var commentsSoFar=$(textAlready).text();
	var commentInt;
	//Check to see if it is nothing
	if (commentsSoFar=='There are no comments yet.'){
		commentInt=0;
	}else{
		var r = commentsSoFar.match(/[\d\.]+/g);
		commentInt=r[0];
	}
	
	//Now that we know how many comments there was, update the value by 1
	commentInt++;
	
	//Use the original codes to update the spot
	
	var sentance = "There ";
	if (commentInt > 1){ sentance+="are ";}else{sentance+="is ";}
	sentance+="("+ commentInt + ") comment";
	if (commentInt > 1){ sentance+="s";}
	sentance+=" so far";
	
	//Update the text to include this blog post in the amount.			
	$(textAlready).text(sentance);

	
	
	
    if (postId) {
        params = "body=" + comment;
		params += "&entry_id=" + postId;
		params += "&author=" + author;
        $.ajax({
            type: "POST",
            data: params,
            url: "/ajax/create_new_comment/",
            success: function(data){
                var comment_content=data;
                var commentDiv = document.createElement('div');
				$(commentDiv).addClass('commentBlock');
				$(commentDiv).html(comment_content);
				
				
				//figure out which icon to use
				
				var AuthorName=author;
				var thumbImage;
				if (AuthorName=='Ryan May') {thumbImage="Ryan.png";}
				else if(AuthorName=="Codey May") {thumbImage="Codey.png";}
				else if(AuthorName=="Mike Kai") {thumbImage="Mike.png";}
				else if(AuthorName=="Wiwat") {thumbImage="Wiwat.png";}
				else if(AuthorName=="B Berg") {thumbImage="Betsy.png";}
				else{thumbImage="bolt.png";}
				var imageDiv='<div class="CommentIcon"><img src="/static/images/comments/'+thumbImage+'" style="margin-top: 5px;"/><br>'+author+'</div>';
				//stick in icon before rest
				$(commentDiv).prepend(imageDiv);
				
				//slot it in the right spot
				var spotNow="div#comment_container_post_"+postId;
				$(spotNow).prepend(commentDiv);
            		//alert ("wow");
            	
				var newPost = $('#blog-content > div:first-child');
                
            },
            failure: function(data){
                alert(data);
            }
        });
    }
	
	$('#comment_container_post_'+postId).animate({opacity: "show"}, "slow");
    return false;
};

Lifeyo.actions.toggleCommentForm = function(postId){
	
			if ($('#comment_form_'+postId).is(':visible')){
				$('#comment_form_'+postId).animate({opacity: "hide"}, "slow");
				//Change the text to prompt the user to fill out the form.
				var textSpot="#commentSentance_"+ postId;
                //change the button so its not pluged in anymore
				$('a#PostCommentBtn_'+postId).css("background-position", "");
				
				
			}
			else
			{
				$('#comment_form_'+postId).animate({opacity: "show"}, "slow");
				var textSpot="#commentSentance_"+ postId;
                 //change the position of the button so it looks like its clicked
				 $('a#PostCommentBtn_'+postId).css("background-position", "0 -45px");
				
				
				//also set the cursor into the name field of that location
				$('#name_'+postId).focus();
			}

};
Lifeyo.actions.toggleCommentContainer = function(postId){
	
			if ($('#comment_container_'+postId).is(':visible')){
				$('#comment_container_'+postId).animate({opacity: "hide"}, "slow");
				  //change the button so its not pluged in anymore
				$('a#ViewCommentsBtn_'+postId).css("background-position", "");
			}
			else
			{
				$('#comment_container_'+postId).animate({opacity: "show"}, "slow");
				  //change the button so its not pluged in anymore
				  
				$('a#ViewCommentsBtn_'+postId).css("background-position", "0 -45px");
			}

};

Lifeyo.actions.convertDate = function (dateStamp){
	
	//get things about today
	var today = new Date();
	var todayYear = today.getYear();
	var todayMonth = today.getMonth();
	var todayDay = today.getDay();
	
	//Post date cut off back half
	var postDate=dateStamp.split(" ")[0];
	var postYear=dateStamp.split("-")[0];
	var postMonth=dateStamp.split("-")[1];
	var postDay=dateStamp.split("-")[2];
	
	//Figure out the difference between the 2.
	
	
	
	
	
	
};

