var ie = (typeof window.ActiveXObject != 'undefined');

function initxmlhttp() {
	var xmlhttp ;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try {
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
	} catch (e) {
		try {
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
		} catch (E) {
			xmlhttp=false
		}
	}
	@else
	xmlhttp=false
	@end @*/
	if ( !xmlhttp && typeof XMLHttpRequest!='undefined' ) {
		try {
			xmlhttp = new XMLHttpRequest() ;
		}
		catch (e) {
			xmlhttp = false ;
		}
	} 
	return xmlhttp ;
}

function trim(str) {
	trimmed = str.replace(/^\s+/,'').replace(/\s+$/,'');
	return trimmed;
}



function rcsComment() {
	rcsFeedback('comment');
}

function rcsRate(rating) {
	rcsFeedback('rate',rating);
}

function rcsSubmitChanges(commentId) {
	rcsFeedback('comment edit',commentId);
}


function rcsFeedback(type, extra1) {

	var ajaxOb = initxmlhttp() ;
	var fullURL = location.href;
	var incQueryStr = document.getElementById("rcs_include_query_str").innerHTML;
	var rcsType = document.getElementById("rcs_type").innerHTML;
	
	var url = document.getElementById("rcs_update_file_location").innerHTML; // URL to which the feedback will be posted
	if (incQueryStr==1) {
		urlToEncode = fullURL;
		//alert('using query str');
	} else {
		
		queryStrStart = fullURL.indexOf(location.search);
		urlToEncode = fullURL.substring(0,queryStrStart);
		//alert('NOT using query str');
	}

	var postData = "u="+encodeURIComponent(urlToEncode)+"&t="+rcsType;
	
	ajaxOb.open( "POST", url, true ) ;
	ajaxOb.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	
	if (type=='rate') {
		postData += "&r="+encodeURIComponent(extra1); // shouldn't really have to encode it...
	} else if (type=='comment') {
	
		maxChars = document.getElementById('rcs_max_comment_length').innerHTML;
		postData += "&m="+encodeURIComponent(maxChars);
	
		commenterName = trim(document.getElementById("rcs_commenter_name").value);
		if (commenterName.length==0) {
			alert('Please enter your name');
			return;
		} 
		
		commentText = trim(document.getElementById('rcs_comment_textarea').value);
		commentText = commentText.substring(0,maxChars);
		
		if (commentText.length==0) {
			alert('Please enter your comment');
			return;
		} 
		
		document.getElementById('rcs_comment_textarea').disabled = true;
		postData += "&c="+encodeURIComponent(commentText)+"&n="+encodeURIComponent(commenterName);
		document.getElementById('rcs_comment_status').innerHTML = 'Saving comment...';
		
	} else if (type=='comment edit') {
	
		maxChars = document.getElementById('rcs_max_comment_length').innerHTML;
		postData += "&m="+encodeURIComponent(maxChars);
	
		newCommentText = trim(document.getElementById('rcs_edit_textarea_'+extra1).value);
		newCommentText = newCommentText.substring(0,maxChars);
		
		if (newCommentText.length==0) {
			alert('Comment cannot be empty.');
			return;
		} 
		
		document.getElementById('rcs_edit_textarea_'+extra1).disabled = true;
		postData += "&c="+encodeURIComponent(newCommentText)+"&id="+encodeURIComponent(extra1);
		document.getElementById('rcs_edit_comment_status_'+extra1).innerHTML = 'Updating comment...';
		
	} else {
		alert('invalid feedback');
		return;	
	}
	
	ajaxOb.send(postData);

	
	var changed = 0;

	ajaxOb.onreadystatechange=function() {

		if (ajaxOb.readyState==4) {
		
			var response = ajaxOb.responseXML;
			var responseText = ajaxOb.responseText;
			//prompt ("response",response); 
			//alert(responseText); 
			
			// error message
			var messageElement = response.getElementsByTagName("message");
			var message = messageElement[0].firstChild.nodeValue;
			
			if (type=='rate') {
				
				if (message=='-') { // no error
					//total votes
					var votesElement = response.getElementsByTagName("total_votes");
					var votes = votesElement[0].firstChild.nodeValue;
					document.getElementById("rcs_total_votes").innerHTML = votes;
					
					//average
					var averageElement = response.getElementsByTagName("avg_rating");
					var average = averageElement[0].firstChild.nodeValue;
					document.getElementById("rcs_avg_rating").innerHTML = average;
					document.getElementById("rcs_rating_title").innerHTML = document.getElementById("rcs_rating_thank_you").innerHTML;
					
					if (document.getElementById('rcs_comments')) { // if we're showing comments, update any ratings belonging to this rater's comments
						var existingCommentsElement = response.getElementsByTagName("existing_comments");
						var existingComments = existingCommentsElement[0].firstChild.nodeValue;

						var commenterRatingElement = response.getElementsByTagName("commenter_rating");
						var commenterRating = commenterRatingElement[0].firstChild.nodeValue; 

						if (existingComments!='-') {
							var ratingsToUpdate = existingComments.split(','); 
							//alert('comments to update: '+(ratingsToUpdate.length));
							for (var i = 0; i< ratingsToUpdate.length; i++) { // update the rating displayed by this person's other comments
								document.getElementById("rcs_commenter_rating_"+ratingsToUpdate[i]).innerHTML = commenterRating;
							}
						}
					}
					
				} else {
					document.getElementById("rcs_rating_title").innerHTML = message;
				}
			
			} else if (type=='comment') { // comment
				
				if (message=='-') { // no error	
					var dateElement = response.getElementsByTagName("comment_date");
					var commentDate = dateElement[0].firstChild.nodeValue;  
					
					var commentIdElement = response.getElementsByTagName("comment_id");
					var commentId = commentIdElement[0].firstChild.nodeValue; 
					
					var commenterRatingElement = response.getElementsByTagName("commenter_rating");
					var commenterRating = commenterRatingElement[0].firstChild.nodeValue; 
					
					var commenterNameElement = response.getElementsByTagName("commenter_name");
					var commenterName = commenterNameElement[0].firstChild.nodeValue; 
					
					document.getElementById('rcs_comment_submission').innerHTML = '';
					
					// get existing comments
					rcsComments = document.getElementById('rcs_existing_comments').innerHTML;  
					
					commentText = commentText.replace(/\n/g,'<br />');
					commentsTemplate = document.getElementById('rcs_comments_template').innerHTML;
					
					newCommentDiv = "<div class=\"rcs_comment\" id=\"rcs_comment_"+commentId+"\">\n"+commentsTemplate+"</div>\n"; // use the comment template to create a new comment div
					
					newCommentDiv = newCommentDiv.replace(/%name%/g,"<span class=\"rcs_commenter_name\" id=\"rcs_commenter_name_"+commentId+"\">"+commenterName+"</span>");
					newCommentDiv = newCommentDiv.replace(/%rating%/g,"<span class=\"rcs_commenter_rating\" id=\"rcs_commenter_rating_"+commentId+"\">"+commenterRating+"</span>");
					newCommentDiv = newCommentDiv.replace(/%date%/g,"<span class=\"rcs_comment_date\" id=\"rcs_comment_date_"+commentId+"\">"+commentDate+"</span>");
					newCommentDiv = newCommentDiv.replace(/%edit_link%/g,"<span class=\"rcs_edit_comment\" id=\"rcs_edit_comment_"+commentId+"\"> <a href=\"javascript:rcsEditComment("+commentId+");\">EDIT</a></span>");
					newCommentDiv = newCommentDiv.replace(/%comment%/g,"<div class=\"rcs_comment_text\" id=\"rcs_comment_text_"+commentId+"\">"+commentText+"</div>");
					
					if (document.getElementById('rcs_new_comments_top').innerHTML=='1') {
						finalCommentsDivContents = newCommentDiv+"\n\n"+rcsComments+"\n\n";
					} else {
						finalCommentsDivContents = rcsComments+"\n\n"+newCommentDiv+"\n\n";
					} 
					document.getElementById('rcs_existing_comments').innerHTML = finalCommentsDivContents;
					
					rcsCommentCount = document.getElementById('rcs_comment_count').innerHTML;  
					document.getElementById('rcs_comment_count').innerHTML = parseInt(rcsCommentCount)+1; 
				} else {
					alert(message);	
				}
				
			} else if (type=='comment edit') { // comment edit
				
				if (message=='-') { // no error	
					var dateElement = response.getElementsByTagName("comment_date");
					var commentDate = dateElement[0].firstChild.nodeValue;  
					
					var commentIdElement = response.getElementsByTagName("comment_id");
					var commentId = commentIdElement[0].firstChild.nodeValue; 
					
					var commenterRatingElement = response.getElementsByTagName("commenter_rating");
					var commenterRating = commenterRatingElement[0].firstChild.nodeValue; 
					
					var newCommentElement = response.getElementsByTagName("comment");
					var newComment = newCommentElement[0].firstChild.nodeValue; 
	  
					document.getElementById("rcs_comment_text_"+commentId).innerHTML = newComment.replace(/\n/g,'<br />');
					document.getElementById("rcs_edit_comment_"+commentId).style.display = 'inline';
	
				} else {
					alert(message);	
				}
			}
		}
	}
	try {
		ajaxOb.send(null);
	} catch (e) {
	
	}

} 


function rcsEditComment(id) {
	commentText = document.getElementById("rcs_comment_text_"+id).innerHTML;
	commentText = commentText.replace(/<br>/gi,'\n');
	commentText = commentText.replace(/<br \/>/g,'\n');
	document.getElementById("rcs_edit_comment_"+id).style.display = 'none';
	document.getElementById("rcs_comment_text_"+id).innerHTML = "<textarea id=\"rcs_edit_textarea_"+id+"\" class=\"rcs_edit_textarea\" >"+commentText+"</textarea><br /><input type=\"button\" onclick=\"rcsSubmitChanges("+id+")\" value=\"submit changes\" /> <span id=\"rcs_edit_comment_status_"+id+"\"></span>";
}

function limitInput(el_id, max) {
	el = document.getElementById(el_id);
	el.value = el.value.substring(0,max);
}



