// JavaScript Document

//handles the AJAX requests - this method is compatible with all versions of IE
var objcommentxml;

var totalComments;
var totalPages;

var cPage = 1;
var linkToNextPage;
var linkToPreviousPage;
var linkToFirstPage;
var linkToLastPage;
var showEachSide = 3;

var domainpath = '';
var URLPath = 1;

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  objcommentxml=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  objcommentxml=new ActiveXObject("Microsoft.XMLHTTP");
}


function sendRequest(section) {
	//alert(this);
	
	switch(section) {
	
		case("games"):
			//alert('games comments selected');
			objcommentxml.open("POST",""+domainpath+"/external/process_comment.php?section=games",true);
		break;
		
		case("retrospecs"):
			//alert('retrospecs comments selected');
			objcommentxml.open("POST",""+domainpath+"/external/process_comment.php?section=retrospecs",true);
		break;
		
		case("fanimations"):
			//alert('fanimations comments selected');
			objcommentxml.open("POST",""+domainpath+"/external/process_comment.php?section=fanimations",true);
		break;
		
		case("arcade-games"):
			//alert('arcade-games comments selected');
			objcommentxml.open("POST",""+domainpath+"/external/process_comment.php?section=arcadegames",true);
		break;
		
	}	
	
	objcommentxml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	var form = $('#comment_system');
	objcommentxml.send(form.serialize());
	objcommentxml.onreadystatechange=requestHandler;
}

//Handle all comment posts
requestHandler=function(data)
{
	if (objcommentxml.readyState==4 && objcommentxml.status==200)
	{
		if(objcommentxml.responseText == 'true'){
			
			$('.comment_status').html('*Comment successfully posted!');
			$('#comment_system #comment').val('');
			updateComments();
			$('.comment_status').fadeOut(3000, function () {
			  $(this).empty();
			  $(this).show();
			 });

			
		} else if(objcommentxml.responseText == 'false') {
			
			$('.comment_status').html('*A system error occured. Try again later.');	
			
		} else if(objcommentxml.responseText == 'empty'){
			
			$('.comment_status').html('*Please type in a comment');
			
		} else {
			//do nothing
		}
	}
}

//Reload the comments upon successfull post
function updateComments(){
	
	var path = window.location.pathname;
	var subpaths = path.split('/');
	var page = subpaths[URLPath];
	
	//reset the cPage count so the first page of comments is displayed upon a comment submission
	cPage = 1;
	
	switch(page){
	
		case("games"):
			//alert('games comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/get_comments.php?pg=game&pgNum=1",true);
		break;
		
		case("retrospecs"):
			//alert('retrospecs comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/get_comments.php?pg=retrospec&pgNum=1",true);
		break;
		
		case("fanimations"):
			//alert('fanimations comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/get_comments.php?pg=fanimation&pgNum=1",true);
		break;
		
		case("arcade-games"):
			//alert('arcade-games comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/get_comments.php?pg=arcadegame&pgNum=1",true);
		break;
		
	}
	
	objcommentxml.send();
	objcommentxml.onreadystatechange=commentHandler;
	
}

//Display all available comments or show message indicating otherwise
commentHandler=function(data) {
	if (objcommentxml.readyState==4 && objcommentxml.status==200) {
		
		var json = eval(objcommentxml.responseText);
		//$('#comments_container').html('');
		if(json == null){
		
			$('.comments_error').html('No comments were found. Be the first to post a comment.');
			
		} else {
			
			updatePageCount();
		
			//clear the comments_error div
			$('.comments_error').empty();
			$('.comments_box').empty();
			$.each(json, function(i) {
				
				if(json[i].user_avatar == "NA"){
					$('.comments_box').append('<div class="comments_box_user"><div class="comments_avatar"><img src="'+domainpath+'/images/default_avatar.jpg" width="83" height="83" /></div><ul><li><h1>Posted by: '+ json[i].username +'</h1></li><li><span>Date posted: '+ json[i].date_posted +'</span></li><li><p>' + json[i].comment + '</p></li></ul></div>');
				} else {
					$('.comments_box').append('<div class="comments_box_user"><div class="comments_avatar"><img src="'+domainpath+'/users/'+ json[i].user_dir +'/avatar/'+ json[i].user_avatar +'" width="83" height="83" /></div><ul><li><h1>Posted by: '+ json[i].username +'</h1></li><li><span>Date posted: '+ json[i].date_posted +'</span></li><li><p>' + json[i].comment + '</p></li></ul></div>');
				}
				
			
			});
			
		}
		
	}
}

function timeConverter(timestamp) {
    //function parses mysql datetime string and returns javascript Date object
    //input has to be in this format: 2007-06-05 15:26:02
    var t = timestamp.split(/[- :]/);

	// Apply each element to the Date function
	var date = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
	
	return date;

}

//UPDATE PAGE COUNT
function updatePageCount(){
	
	var path = window.location.pathname;
	var subpaths = path.split('/');
	var page = subpaths[URLPath];
	
	switch(page){
	
		case("games"):
			//alert('games comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/comments_count.php?pg=game",true);
		break;
		
		case("retrospecs"):
			//alert('retrospecs comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/comments_count.php?pg=retrospec",true);
		break;
		
		case("fanimations"):
			//alert('fanimations comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/comments_count.php?pg=fanimation",true);
		break;
		
		case("arcade-games"):
			//alert('arcade-games comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/comments_count.php?pg=arcadegame",true);
		break;
		
	}//end of switch
	
	objcommentxml.send();
	objcommentxml.onreadystatechange=pageHandler;
	
}

//UPDATE PAGING
pageHandler=function(data) {
	if (objcommentxml.readyState==4 && objcommentxml.status==200) {
		
		var json = eval(objcommentxml.responseText);
		//$('#comments_container').html('');
		if(json == null){
			//do nothing
		} else {
			
			//calculate the total number of pages
			totalComments = json;
			
			$('#comments_count').html(' ' + json);
			$('#comments_count1').html(' (' + json + ') ');
			
			
			//alert('The total number of comments for this arcade game is: ' + totalComments);
			totalPages_divided = totalComments / 10; /*10 reflects the comments_per_page variable*/
			totalPages = Math.ceil(totalPages_divided);
			//alert( totalPages );
			
			buildPaging();
			
		}//end of if
		
	}
}

//BUILD PAGING LINKS
function buildPaging(){

	$('.comments_paging_container').empty();

	//Builds the paging links
	if( totalPages > 1 ){
		
		$('.comments_page_indicator').html('Displaying page: <strong>'+ cPage +'</strong> of '+ totalPages +' ');
		
		
		//Build the first page Link
		if( cPage > 1 ){
			linkToFirstPage = 1;
			$('.comments_paging_container').append(' <span id='+ linkToFirstPage +'><a href=""> << </a></span> ');
		}
		
		//Build the Previous Link
		if( cPage > 1 ){
			linkToPreviousPage = parseInt(cPage) - 1;
			$('.comments_paging_container').append(' <span id='+ linkToPreviousPage +'><a href=""> < </a></span> ');
		}
		
		if( cPage > showEachSide ){
			$('.comments_paging_container').append('...');
		}
		
		
		//Build the pages links
		for (var i = 1; i <= totalPages; i++){
			
			//Might have to use the correct radix value with parseInt. ex. parseInt(cPage, 10)
			if ( (i > (cPage - showEachSide)) && (i < (parseInt(cPage) + parseInt(showEachSide))) ){
				$('.comments_paging_container').append(' <span id='+ i +'><a href="">'+ i +'</a></span> ');
			}
			
		}
		
		if( parseInt(cPage) + parseInt(showEachSide) < totalPages ){
			$('.comments_paging_container').append('...');
		}
		
		//Build the Next Link
		if( cPage < totalPages ){
			
			linkToNextPage = ++cPage;
			$('.comments_paging_container').append(' <span id='+ linkToNextPage +'><a href=""> > </a></span> ');
			
			linkToLastPage = totalPages;
			$('.comments_paging_container').append(' <span id='+ linkToLastPage +'><a href=""> >> </a></span> ');
			
		}
		
		$('.comments_paging_container span').each(function(i) {
					
			$(this).click(function(e) {
				e.preventDefault();
				var id = $(this).attr("id");
				cPage = id;
				pageThroughComments(id);
			});
				
			$(this).mouseout(function(){ 
				
			});
				
			$(this).mouseover(function(){ 
				
				$(this).css("cursor", "pointer");
			});
				
		});
		
		
	}//end of totalPages if
	
}

//PAGE THROUGH COMMENT SETS
function pageThroughComments(p){
	
	var path = window.location.pathname;
	var subpaths = path.split('/');
	var page = subpaths[URLPath];
		
	switch(page){
	
		case("games"):
			//alert('games comments selected');
			objcommentxml.open("GET",''+domainpath+'/external/get_comments.php?pg=game&pgNum='+ p +'',true);
		break;
		
		case("retrospecs"):
			//alert('retrospecs comments selected');
			objcommentxml.open("GET",''+domainpath+'/external/get_comments.php?pg=retrospec&pgNum='+ p +'',true);
		break;
		
		case("fanimations"):
			//alert('fanimations comments selected');
			objcommentxml.open("GET",''+domainpath+'/external/get_comments.php?pg=fanimation&pgNum='+ p +'',true);
		break;
		
		case("arcade-games"):
			//alert('arcade-games comments selected');
			objcommentxml.open("GET",''+domainpath+'/external/get_comments.php?pg=arcadegame&pgNum='+ p +'',true);
		break;
		
	}
	
	objcommentxml.send();
	objcommentxml.onreadystatechange=commentHandler;
	
}


//Get the comments on page load
function startupComments(pageType){
	
	var currPage = pageType;
	
	switch(currPage){
	
		case("games"):
			//alert('games comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/get_comments.php?getAll&pg=game&pgNum=1",true);
		break;
		
		case("retrospecs"):
			//alert('retrospecs comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/get_comments.php?getAll&pg=retrospec&pgNum=1",true);
		break;
		
		case("fanimations"):
			//alert('fanimations comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/get_comments.php?getAll&pg=fanimation&pgNum=1",true);
		break;
		
		case("arcade-games"):
			//alert('arcade-games comments selected');
			objcommentxml.open("GET",""+domainpath+"/external/get_comments.php?getAll&pg=arcadegame&pgNum=1",true);
		break;
		
	}
	
	objcommentxml.send();
	objcommentxml.onreadystatechange=commentHandler;
	
}

//sendRequest(objcommentxml);

$(document).ready(function() {
	
	//alert('comment js working');
    
	$('#comment_system').submit(function() {
		
		var path = window.location.pathname;
		var subpaths = path.split('/');
		var page = subpaths[URLPath];
		
		sendRequest(page);
		
	});
	
	
	if(totalComments == undefined){
		
		$('#comments_count').html(' 0 ');
		$('#comments_count1').html('(0) ');
		
	} 
	
	
	//startupComments("arcadegame");
	
	//Startup call to load any comments that may already exist in the database
	//objcommentxml.open("GET","get_comments.php?getAll",true);
	//objcommentxml.send();
	//objcommentxml.onreadystatechange=commentHandler;

	
});		
