// generic object to perform ajax operation
var httpRequest;
// variable to store postid to be deleted
var postid;
// this will used to redirect to previous page
var previoustrail = 0;
// initial css class of post rows, used to switch class
var cssclass = '';
// id of element holding posts
var main_post_table = document.getElementById('main_posts_table');
// this will used to store html element index of deleted post
var deleted_hash;
// store rows length  
var table_rows= main_post_table.rows.length;

/* 	Purpose: this function is used to confirm delete request
	@Parameters: msg_flag - msg_flag for which message to be displayed 
	Return: true or false.
	Call scope: Local, inside this script.	*/
function confirmDelete (msg_flag) {
	if(msg_flag){
		return confirm("Deleting the first post will cause the entire thread to be deleted.\n\nAre you sure you would like to continue?");
	}else{
		return confirm("Are you sure you would like to delete this post?");
	}
}		 
/* 	Purpose: this function is used to send delete request
	@Parameters: postid, msg_flag - postid of the post to be deleted ,msg_flag for which message to be displayed
	Return: None.
	Call scope: Global, outside this script.	*/
function delete_request(post_id,msg_flag){
	if(confirmDelete(msg_flag)){
		postid=post_id;	// set the postid used in html deletion of deleted post, global variable defined in post script
		
		// url used to process delete request and append a new post
		var url_delete = "/post/ajaxdeletePost?id="+id+"&trail="+trail+"&pid="+ postid +"&forum="+forum+"&ajax_request=1"+query;
		
		// create & set a response handler, global variable 
		httpRequest = CreateXmlHttpReq(_postdeleteHandler);

		// if response handler created successfully send the url 
		if (httpRequest) {
			XmlHttpGET(httpRequest, url_delete);
		}
	}
} // end function delete_request();

/* 	Purpose: this function is used to check the response of ajax request and process accordingly
	@Parameters: None.
	Return: None.
	Call scope: Local, inside this script.	*/
function _postdeleteHandler() {
		// if server is ready to process the request
		if (httpRequest.readyState == 4) {
			// if server response code is ok
            if (httpRequest.status == 200) {
				// if recieved response xml data from server
				if (httpRequest.responseXML) { 
					// get the post's xml response
					var responsedata = httpRequest.responseXML;
					
					// if response contains any error tag
					if (responsedata.getElementsByTagName("error")[0])
					{
						// if error tag contains any error string
						if (responsedata.getElementsByTagName("error")[0].firstChild.nodeValue)
						{
							// alert the error after stripping out any html tags 
							alert(responsedata.getElementsByTagName("error")[0].firstChild.nodeValue.replace(/<\S[^><]*>/g,''));
						}
						
						// if response contains any redirect url
						if (responsedata.getElementsByTagName("redirect_url")[0]) {
							// url redirection
							window.location = responsedata.getElementsByTagName("redirect_url")[0].firstChild.nodeValue;
						}
						return false;
					}
					//Fade affect when a post is deleted
					Effect.Fade('tr_'+postid);
					// call the function to delete the HTML code for deleted post
					_remove_post();

					// save the value to jump on previuos page, if all post on current page has deleted, global variables
					previoustrail = (trail - replies_perpage);

					var ajax_pagination_data = responsedata.getElementsByTagName("pagination")[0].firstChild.nodeValue;

					// if recieved pagination's HTML
					if (ajax_pagination_data) { 
						
						 // if recieved post id, create HTML to append the post
						if (responsedata.getElementsByTagName("postid")[0]) {
							// postid of the post to be appended, retrive from xml document
							 var ajax_post_id = responsedata.getElementsByTagName("postid")[0].firstChild.nodeValue;
							// retrive data of left td from xml response, this contains, owner of post etc
							var ajax_data_td_1 = responsedata.getElementsByTagName("data_td_1")[0].firstChild.nodeValue;
							// retrive data of right td from xml response, this contains, actual content of post woth delete,  edit links etc
							var ajax_data_td_2 = responsedata.getElementsByTagName("data_td_2")[0].firstChild.nodeValue;
							var td1_id = responsedata.getElementsByTagName("td1_id")[0].firstChild.nodeValue;
							// retrive data of right td from xml response, this contains, actual content of post woth delete,  edit links etc
							var td2_id = responsedata.getElementsByTagName("td2_id")[0].firstChild.nodeValue;
							// create a HTML TR element
							var _tr = document.createElement("tr");
							// set TR element's id as retrieved postid
							_tr.id = ajax_post_id;
							_tr.style.display ="none";
							// create HTML left TD element for post left content
							var _td1 = document.createElement("td");
							// set the inner HTML of left TD as post left content, retreived from xml response
							_td1.innerHTML = ajax_data_td_1;
							_td1.id=td1_id;
							_td1.setAttribute("valign","top");
							// set left TD width as 19%
							_td1.setAttribute("width","19%");
							
							// create HTML right TD element for post right content
							var _td2 = document.createElement("td");
							// set the inner HTML of right TD as post right content, retreived from xml response
							_td2.innerHTML = ajax_data_td_2;
							_td2.id=td2_id;
							_td2.setAttribute("valign","top");
							_td2.style.height='100%';
							
							// append the left TD with TR element
							_tr.appendChild(_td1);
							// append the right TD with TR element
							_tr.appendChild(_td2);
							// append the TR element with main HTML element containg post rows 
							main_post_table.appendChild(_tr);
							//alert('\n Response::\n\n ajax_post_id :'+ajax_post_id+'\n\n ajax_data_td_1: '+ajax_data_td_1+'\n\n : '+ajax_data_td_2);
							// call function _css_walk() css walk to keep consistency,  in post count as well as alternative classes of post rows
							_css_walk(); 
							//Appear effect when a new post is added at the bottom
							Effect.Appear(ajax_post_id, { duration: 2.0, from: 0.0, to: 2.0 });
						}
						

						// update pagination's HTML
						document.getElementById('div_pagination').innerHTML= ajax_pagination_data;
						
						// if all posts on current page has deleted, redirect to previous page
						if (table_rows < 1) {
							window.location = "/post?id="+id+"&trail="+previoustrail+query;
						} 
							
					} else {window.location="/?forum="+forum;}
				} 
			} else {
				// give alert that there is some problem occurred during ajax request process.
                alert('There was a problem with the request.');
				return false;
            }
        }

}

/* 	Purpose: this function is used to switch css class alternatively for alternative post rows
	@Parameters: None, use the global cssclass variable
	Return: cssclass, for post row
	Call scope: Local, inside this script.	*/
function _switchclass(){
	// if cssclass is postrow_color change this with alt_postrow_color else set cssclass as postrow_color
	cssclass = (cssclass == 'postrow_color') ? 'alt_postrow_color' : 'postrow_color' ;
	// return this new set class
	return cssclass;
}
/* 	Purpose: this function is used to delete a particular row from main table
	@Parameters: None
	Call scope: Local, inside this script.	*/
function remove_row() {
	var row = document.getElementById('tr_'+postid);
	main_post_table.removeChild(row);
}
/* 	Purpose: this function is used to remove HTML of post that deleted via ajax request
	@Parameters: None, use the global postid variable
	Return: None
	Call scope: Local, inside this script only.	*/
function _remove_post() {
	// post row to be deleted
	var row = document.getElementById('tr_'+postid);

	// get hash(#) or index value of post row to be deleted, this will save in deleted_hash[1]
	deleted_hash   = row.getElementsByTagName('td')[0].id.split('_');
	// decrement by one in rows length 
	table_rows--;
	// Remove post's HTML after fade affect 
	setTimeout("remove_row()",2000);
	cssclass="";
	// initialize the childs as 0, this will be the count of posts rows available in HTML element containing post rows
	var childs=0;
	// number of tr elements located inside main post's container
	childs = main_post_table.rows.length;
		// get the first post count
	var i = (trail - replies_perpage) + 1  ;
	// add the count for rows on the page
	childs = parseInt(childs) + parseInt(i);
	// ids to blank of deleted hash row
	document.getElementById('td1_'+deleted_hash[1]).id='';
	document.getElementById('td2_'+deleted_hash[1]).id='';
	document.getElementById('postcount_'+deleted_hash[1]).id='';
	
	// iterate through each post row, to keep post count and alternate class consistency
	for (i;i<=childs;i++) {		
		// always keep consistency in post row classes

		if(document.getElementById('td1_' + i)){
			var changed_class = _switchclass();
			document.getElementById('td1_' + i).className=changed_class;
			document.getElementById('td2_' + i).className=changed_class;
			// set hash(#) or index value of current post, saved in current_hash[1]
			var current_hash = new Array(2) 
				current_hash[0] = 'postcount';
				current_hash[1] = parseInt(i);
			var current_row = document.getElementById('postcount_'+ current_hash[1]);

			if(current_row){
				// if deleted hash value is less than current post hash value
				if (parseInt(deleted_hash[1])<parseInt(current_hash[1])) {
					// decrement the current hash value by 1
					// update the id postcount_{current_hash - 1} of anchor element 
					current_row.id = current_hash[0]+'_'+(parseInt(current_hash[1])-1);
					var td1_id =document.getElementById('td1_' + current_hash[1]);
					var td2_id =document.getElementById('td2_' + current_hash[1]);
					td1_id.id = 'td1_'+(parseInt(current_hash[1])-1);
					td2_id.id = 'td2_'+(parseInt(current_hash[1])-1);
					// update the containing value #{current_hash - 1} of anchor element 
					document.getElementById(current_hash[0]+'_'+(parseInt(current_hash[1])-1)).firstChild.data = '#'+(parseInt(current_hash[1])-1);
					// get the postid by splitting tr_{postid}, a unique id for each row 
					// var tr_id = main_post_table.getElementsByTagName('tr')[i].id.split("_");

					// update the href attribute of anchor element (with updated postcount = {current_hash - 1} value)
					var post_href=document.getElementById(current_hash[0]+'_'+(parseInt(current_hash[1])-1)).getAttribute('href').split('postcount=');
					
					document.getElementById(current_hash[0]+'_'+(parseInt(current_hash[1])-1)).setAttribute("href", post_href[0]+"postcount="+(parseInt(current_hash[1])-1));

				} // end if
			}
		}
	} // end for
	
} // end function _remove_post

/* 	Purpose: this function is used to keep consistency in css class for alternative post rows
	@Parameters: None
	Return: None
	Call scope: Local, inside this script only.	*/
function _css_walk(){
	// initialize the childs as 0, this will be the count of posts rows available in HTML element containing post rows
	var childs=0;
	cssclass="";
	// number of tr elements located inside main post's container
	childs = main_post_table.rows.length;
	// get the first post count
	var i = (trail - replies_perpage) + 1  ;
	
	// add the count for rows on the page
	childs = parseInt(childs) + parseInt(i);
	for (i;i<childs ;i++) {
			// always keep consistency in post row classes
			if(document.getElementById('td1_' + i)){
				var changed_class = _switchclass();
				document.getElementById('td1_' + i).className=changed_class;
				document.getElementById('td2_' + i).className=changed_class;
			}
	} // end for
} // end function _css_walk
