var lastCMT = '';

function UpdateFilter(val){
   fltthres = val;
   if (fltthres > 0 ) $('SliderFilter').innerHTML =	': ' + val;
   else $('SliderFilter').innerHTML =	': Off';
   DisplayComments();
 } 
 
 
function DisplayComments(){
     ajax = new Ajax.Updater('comments', '/comments/?code=VIEW&format=html&newsid='+nid+'&sort='+sort+'&filter='+fltthres, {
							method: 'get',
							onCreate: function() 	{if ( $('cmThr') ) $('cmThr').innerHTML = updIMG;},
							onComplete: function() 	{if ( $('cmThr') ) $('cmThr').innerHTML = '';}
							});
    PostBox();
}	


function ChangeSort(){
	sortTXT = '';
	if (sort == 'ASC') {
		sort = 'DESC';
		sortTXT = 'oldest first';
	}
	else{
		sort = 'ASC';
		sortTXT = 'newest first';
	}
	
	DisplayComments();
	$('sortCmnt').innerHTML =	sortTXT;
}


function PostBox(){
	var pstbx = '<form name="commadd" method = "POST" action="/comments/">' +
			'<fieldset id="fieldset-comments">' +
				'<label for="commenttext" id="addtitle">Add your Comment:</label>' +
				'<p><textarea id="input-comment" name="commenttext" cols="49" rows="5" onKeyDown="maxLength(this,1000);" onKeyUp="maxLength(this,1000);"></textarea></p>' +
				'<input type="hidden" name="status" value="new" /> ' +
				'<input type="hidden" name="cid" value="0" />' +
				'<input type="hidden" name="nid" value="" />' +
				'<p>' +
				'<span id="cmPrThr" class="float-right"></span>'+
				'<button id="comment-submit" name="commentsubmit" value="Add Comment" onClick="AddComment(); return false;" >Submit</button>' +	
				'<button value="Cancel" onClick="CommentReset(); return false;">Cancel</button>' + 
				'</p>' +
				'<ul><li><b><i>Brevity is the soul of wit</i>:</b> <span id="cmChCnt">1000</span> characters left.</li><li><b>Edit:</b> Your comment will be editable for 3 minutes.</li> <li><b>HTML tags:</b> HTML tags are not allowed.</li><li><b>Comments guidelines:</b> <a href="http://www.physorg.com/help/comments/" target="_blank">please read</a> before you post.</li> </ul>' +
				'Notify me via email of follow-up comments posted here ' +
				'<button id="comment-follow" name="commentfollow" value="Follow comment"  onClick="FollowComments(); return false;" >subscribe</button>' + 
			'</fieldset>' +
			'</form>';
	var lgbox = '<div id="fstlog">' +
				'<p>Please <a href="/profile/login.php?code=signup">register</a> or <a href="/profile/login.php?redirect=TRUE">sign in</a> to add a comment. ' +
				'Registration is free, and takes less than a minute. <a href="/help/physorg-account/">Read more</a></p>' +
				'<form name="fstlogin" id="fstlogin" method = "POST" action="" onSubmit="SignIn(this, SignInComments); return false;" >' +
				'<fieldset id="fieldset-logins">' +
					'<label for="email" id="email">Email</label>' +
					'<p><input type="text" name="email" id="email" size="10" maxlength="128"></p>' +
					'<label for="passwd" id="passwd">Password</label>' +
					'<p><input type="password" name="passwd" id="passwd" size="10" maxlength="128"></p>' +	
					'<input type="hidden" name="status" value="login" /> ' +
					'<p><span id="cmPrThr" class="float-right"></span>'+
					'<button type="submit" id="login-submit" name="loginsubmit" value="Sign in" onClick="" >Sign In</button></p>' +		
					'</fieldset>' +
				'</form>' +		
				'Forgot your password? <a href="http://www.physorg.com/profile/login.php?code=pwdreset">Click here</a> to reset it <br/>' +
				'Notify me via email of follow-up comments posted here ' +
				'<button id="comment-follow" name="commentfollow" disabled="disabled" >sign in first</button>' + 
			'</div> ';
	
	if (mid != '0') {
			document.getElementById('postbox').innerHTML =	pstbx;
			document.commadd.nid.value = nid;
			if (follow == 'on') { document.commadd.commentfollow.innerHTML = 'unsubscribe'; }
	}
	else {
		document.getElementById('postbox').innerHTML =	lgbox;
	}

}

function SignIn(formName, handler){
		var email = formName.email.value;
		if ( email.length == 0 ){ ShowAlert('Please enter your email!'); return }

		var passwd = formName.passwd.value;
		if ( passwd.length == 0 ){ ShowAlert('Please enter your password!'); return }		

		var queryString = 'email=' + escape(email) + '&passwd=' + passwd + '&status=login';
		ajax = new Ajax.Request('/comments/',{
								method: 'post',
								parameters: queryString,
								onCreate: function(){$('cmPrThr').innerHTML = updIMG;},
								onSuccess: handler
								});
} 

// comment handling
function AddComment(){
		var cmnt = document.commadd.commenttext.value;
		if ( cmnt.length == 0 ){ ShowAlert('Please enter your comment'); return }
		if ( cmnt.length > 1000 ){ ShowAlert('Comment text too long'); return }

		var nid = document.commadd.nid.value;
		var cid = document.commadd.cid.value;
		var status = document.commadd.status.value;	  
		lastCMT = cmnt;
		var queryString = 'commenttext=' + escape(cmnt) + '&nid=' + nid + '&status=' + status +'&cid=' + cid + '&sort=' + sort;
		submit = new Ajax.Request('/comments/', {
								method: 'post',
								parameters: queryString,
								onCreate: function(){
												document.commadd.commentsubmit.disabled = true;
												$('cmPrThr').innerHTML = updIMG;
										  },
								onSuccess: function(respXML){
											  	response  = respXML.responseXML.documentElement;
												if (response.getElementsByTagName('msg')[0].firstChild != null) ShowAlert(response.getElementsByTagName('msg')[0].firstChild.data);
												DisplayComments();
												// put back last text if there was an error
												if (response.getElementsByTagName('msg')[0].firstChild != null) {
													document.commadd.commenttext.value = lastCMT;
													lastCMT = '';
												}
												// jump to first
												else if (sort == 'DESC') new Effect.ScrollTo('comments', { duration: 1.0, offset: -160 });
											}									
										   
								});
}


// comment editing
function GetComment(cid){
	 ajax = new Ajax.Request('/comments/?code=COM&cid='+cid,
					{
					method: 'get',
					onCreate: function(){   $('cmPrThr').innerHTML = updIMG;
											new Effect.ScrollTo('postbox', { duration: 0.5 });
										},
					onComplete: function()  {$('cmPrThr').innerHTML = '';},
					onSuccess: function(xmlDoc){
											response  = xmlDoc.responseXML.documentElement;
											
											if (response.getElementsByTagName('code')[0].firstChild.data == '300') {
												   ShowAlert(response.getElementsByTagName('msg')[0].firstChild.data);
												   return ;
											}
										 	var commentTEXT = response.getElementsByTagName('comment')[0].getElementsByTagName("text")[0].firstChild.data;
											//document.getElementById('addtitle').innerHTML = 'Edit comment';
											$('addtitle').innerHTML = 'Edit comment';
											document.commadd.cid.value = cid;
											document.commadd.status.value ='edit';
											document.commadd.commentsubmit.value='Edit';
											document.commadd.commenttext.value = commentTEXT;
								}
					});
}

function CommentReset(cid){
   	$('addtitle').innerHTML = 'New comment';	
	document.commadd.commenttext.value = ''; 
    document.commadd.status.value ='New';
    document.commadd.cid.value = '0';
	document.commadd.commentsubmit.value='Add Comment';	
	document.commadd.reset;

}

function ShowComment(cid){
	   ajax = new Ajax.Request('/comments/?code=COM&format=html&cid='+cid, {
							method: 'get',
							onSuccess: function(xmlDoc){
										  response  = xmlDoc.responseXML.documentElement;
										  cmTXT = response.getElementsByTagName('comment')[0].getElementsByTagName("text")[0].firstChild.data;
										  if (cmTXT != ''){
										   	$('cm_'+cid).className  = '';
										   	$('cm_'+cid).innerHTML = cmTXT;
										  }
										}
							});
}

//comment quoting
function QuoteComment(cid){
	ajax = new Ajax.Request('/comments/?code=COM&cid='+cid, {
							method: 'get',
							onCreate: function() 	{$('cmPrThr').innerHTML = updIMG;},
							onComplete: function()  {$('cmPrThr').innerHTML = '';},
							onSuccess: function(xmlDoc){
									    response  = xmlDoc.responseXML.documentElement;
										cmTXT = response.getElementsByTagName('comment')[0].getElementsByTagName("text")[0].firstChild.data;
										if (cmTXT != '') {
											 document.commadd.commenttext.value = '[q]' + cmTXT + '[/q]\r\n' + document.commadd.commenttext.value;
											 new Effect.ScrollTo('postbox', { duration: 0.5 });
										}
									   }
							});
}
							
					
							
// Rank handling 
function RateComment(cid, rank){
	
	ajax = new Ajax.Request('/comments/?code=RATE&cid='+cid+'&rank='+rank, {
							method: 'get',
							onCreate: function(){$('rate-' + cid).hide();
												 $('rk-' + cid).innerHTML = updIMG;	
												},
							onSuccess: DisplayRank
												});
}  

function  DisplayRank(xmlDoc){

	response  = xmlDoc.responseXML.documentElement;			 
	if (response.getElementsByTagName('msg')[0].firstChild != null) {
		   ShowAlert(response.getElementsByTagName('msg')[0].firstChild.data);
		   return;
	}

	var cid =  response.getElementsByTagName('comment')[0].getElementsByTagName('cid')[0].firstChild.data;
	var rank=  response.getElementsByTagName('comment')[0].getElementsByTagName('rank')[0].firstChild.data;	
	var votes=  response.getElementsByTagName('comment')[0].getElementsByTagName('votes')[0].firstChild.data;	
	$('rk-' + cid).innerHTML =  FormatRank(rank, votes); 
	
}

// fstlog
function  SignInComments(xmlDoc){

	response  = xmlDoc.responseXML.documentElement;		
	
	if (response.getElementsByTagName('msg')[0].firstChild != null) {
		   ShowAlert(response.getElementsByTagName('msg')[0].firstChild.data);
		   return;
	}						  
	if (response.getElementsByTagName('mid')[0].firstChild != null) {
		 mid = 	 response.getElementsByTagName('mid')[0].firstChild.data;
	}	

	DisplayComments();						  
	PostBox();

}

// flag comment
function FlagComment(cid){
  var alertBox = 'Report this comment as spam, offensive or inappropriate?'+
  				 '<br/><br/>' +
				 '<button onClick="SendFlag('+cid+');">report</button>';
  ShowAlert(alertBox,'Thank you. Moderator will review your report and remove this post if inappropriate.'); 
}

function SendFlag(cid){
 ajax = new Ajax.Request('/comments/?code=FLAG&cid=' + cid, {
					method: 'get',
					onSuccess:  function(xmlDoc){
									response  = xmlDoc.responseXML.documentElement;			 
									if (response.getElementsByTagName('msg')[0].firstChild != null) {
											   ShowAlert(response.getElementsByTagName('msg')[0].firstChild.data);
									}
								}
					
					});
}

// follow comments
function FollowComments(){
	var queryString = 'status=follow' +'&nid=' + nid;
	ajax = new Ajax.Request(
				'/comments/', {
				method: 'post',
  				parameters: queryString,
				onCreate: function() 	{$('cmPrThr').innerHTML = updIMG;},
				onComplete: function()  {$('cmPrThr').innerHTML = '';},
				onSuccess : FollowAdd
				});
}

function FollowAdd(xmlDoc){

	response  = xmlDoc.responseXML.documentElement;			 
	
	if (response.getElementsByTagName('code')[0].firstChild.data == '200'){
		document.commadd.commentfollow.innerHTML = 'unsubscribe';
		 follow = 'on';
	}
	if (response.getElementsByTagName('code')[0].firstChild.data == '300'){
		 document.commadd.commentfollow.innerHTML = 'subscribe';
		 follow = '';
	}
	if (response.getElementsByTagName('code')[0].firstChild.data == '400') ShowAlert('Sorry, your request can\'t be processed');
}

// max comment length
function maxLength(textarea, maxLen){
	if (textarea.value.length > maxLen) textarea.value = textarea.value.substring(0,maxLen);
	document.getElementById('cmChCnt').innerHTML = (maxLen - textarea.value.length);
}


// supplemental
function FormatRank(rank, votes){
	if (rank == 0) return 'not rated yet';
	var txt = rank + '/5 after ' + votes;
	if 	( votes > 1 ) return  txt + ' votes';
	else return  txt + ' vote';

}

function hideVoting(divID) { 
	if (document.getElementById) { 
		document.getElementById(divID).style.visibility = 'hidden'; 
		} 
	else { 
		if (document.layers) { // Netscape 4 
		document.divID.visibility = 'hidden'; 
		} 
		else { // IE 4 
		document.all.divID.style.visibility = 'hidden'; 
		} 
	} 
}