
/* ***** ESRI RATINGS and COMMENTS (6/29/2005 b.garoutte) */

// set up some globals
	var req; // ratings
	var req2; //comments
	var req3; //ecas
	
	var theRating = 3; //default rating
	
	var ECASid;
	
	var dataItemType, dataItemId, commentsUrl, submitType, theActiveAlert;
	var theUser, theTitle, theComment, theCreationDate, theLastUpdate, theEditStat, theCommentId, theUserLogged, theActive;
	
// this is called by the ratings HTML - it makes sure we have the guid (theId) 
// stored as a global and starts up both the ratings and comments
	function init(theType, theId, ratings, comments, loggedIn){
		dataItemType = theType;
		dataItemId = theId;
		theUserLogged = loggedIn;
		if(ratings) getRating();
		if(comments) getComments();
	}

	function replaceText(theDiv, theText){
		var tmp = document.getElementById(theDiv);
		tmp.innerHTML = theText;
	}


/***** RATINGS FUNCTIONS *******/
	 
// displays the input section of the rating form
	function toggleRatingForm(){
		toggle("ratingForm");
		setDefaultRating();
	}
	
	function toggle(theDiv){
		var getDiv = document.getElementById(theDiv);
		getDiv.style.display == "block" ? getDiv.style.display = "none": getDiv.style.display = "block";
	}
	
	function setDefaultRating(){
		var theForm = document.getElementById("ratingForm");
		var theRadio = theForm.getElementsByTagName("input");
		
		// set the default choice to "good"
		document.ratings.theRating[2].checked = "true";
		showStars(3);
		showStarText(3);
	}

	function showStarText(num){
		var text = new Array;
		text[1] = "Poor";
		text[2] = "Average";
		text[3] = "Good";
		text[4] = "Very Good";
		text[5] = "Outstanding";
	
		replaceText("starDescription", text[num]);
	}
	
	function showRating(num){
		var theStars = document.getElementById("starfield");
		theStars.style.width = num * 12 + "px";
		theStars.setAttribute("title", num + " stars");
	}
	
	function showStars(num){
		var theStars = document.getElementById("starRating");
		theStars.style.width = num * 12 + "px";
		theStars.setAttribute("title", num + " star rating");
	}

	function updatePrompt(ratingCount){
		var text = "Be the first to rate this " + dataItemType + ".";
		if(ratingCount > 0) text = "Rating based on " + ratingCount + " responses.";
		if(ratingCount == 1) text = "Rating based on 1 response.";
		
		replaceText("prompt", text);
	}
	
	function selectRating(num){
		theRating = num;
		showStars(num);
		showStarText(num);
	}

	function submitRating(){
		ratingsPostUrl = "index.cfm?fa=ratings.postRating&ajaxOn=1&ratingsId=" + dataItemId + "&ratingtype=" + dataItemType + "&theRating=" + theRating;
		loadXMLDoc(ratingsPostUrl);
		
		replaceText("rateLink", "");
		replaceText("prompt", "Refreshing the rating results...");
		replaceText("ratingForm", "<p>Thank you for rating this " + dataItemType + ".</p>");
	}
		
	function getRating(){
		ratingsUrl = "index.cfm?fa=ratings.getRatings&ajaxOn=1&ratingsId=" + dataItemId;
		loadXMLDoc(ratingsUrl);
	}
	
	function showError(errMsg){
		replaceText("rateLink", "");
		replaceText("prompt", "Error encountered.");
		replaceText("ratingForm", errMsg);
	}
	
	function processRating(){
		var theCount = req.responseXML.getElementsByTagName('count')[0].firstChild.nodeValue; 
    var theAvg =  req.responseXML.getElementsByTagName('average')[0].firstChild.nodeValue;           
    
    	showRating(theAvg);
    	updatePrompt(theCount);
   	}
	
	// retrieve XML document (reusable generic function);
	// parameter is URL string (relative or complete) to
	// an .xml file whose Content-Type is a valid XML
	// type, such as text/xml; XML source must be from
	// same domain as HTML file
	function loadXMLDoc(url) {
	    // branch for native XMLHttpRequest object
	    if (window.XMLHttpRequest) {
	        req = new XMLHttpRequest();
	        req.onreadystatechange = processReqChange;
	        req.open("GET", url, true);
	        req.send(null);
	     // branch for IE/Windows ActiveX version
	    } else if (window.ActiveXObject) {
	        req = new ActiveXObject("Microsoft.XMLHTTP");
	        if (req) {
	            req.onreadystatechange = processReqChange;
	            req.open("GET", url, true);
	            req.send();
	        }
	    }
	}

	// handle onreadystatechange event of req object
	function processReqChange() {
	    // only if req shows "loaded"
	    if (req.readyState == 4) {
	        // only if "OK"
	        if (req.status == 200) {
            	processRating();
	         } else {
	            showError(req.statusText);
	         }
	    }
	}


/***** COMMENTS FUNCTIONS *******/

	function loadXMLComments(url) {
	    if (window.XMLHttpRequest) {
	        req2 = new XMLHttpRequest();
	        req2.onreadystatechange = processReqComments;
	        req2.open("GET", url, true);
	        req2.send(null);
	    } else if (window.ActiveXObject) {
	        req2 = new ActiveXObject("Microsoft.XMLHTTP");
	        if (req2) {
	            req2.onreadystatechange = processReqComments;
	            req2.open("GET", url, true);
	            req2.send();
	        }
	    }
	}

	function processReqComments() {
	    if (req2.readyState == 4) {
	        if (req2.status == 200) {
		       	processComment();
	         } else {
	            showError2(req2.statusText);
	         }
	    }
	}

	function loadXMLAddComment(url) {
	    if (window.XMLHttpRequest) {
	        req2 = new XMLHttpRequest();
	        req2.onreadystatechange = processAddComments;
	        req2.open("GET", url, true);
	        req2.send(null);
	    } else if (window.ActiveXObject) {
	        req2 = new ActiveXObject("Microsoft.XMLHTTP");
	        if (req2) {
	            req2.onreadystatechange = processAddComments;
	            req2.open("GET", url, true);
	            req2.send();
	        }
	    }
	}

	function processAddComments() {
	    if (req2.readyState == 4) {
	        if (req2.status == 200) {
		       	showConfirmation();
	         } else {
	            showError2(req2.statusText);
	         }
	    }
	}

	function initFormAdd(){
		// sets up the form for adding a record
		replaceText("commentTab2","Add your comment");
		theTab = document.getElementById("commentTab2");
		theTab.setAttribute("onClick", "initFormAdd();tabBoxV3('commentTab','2','2');");
		if(document.getElementById("commentTitle")){ // make sure the form is in memory before we change it
			document.getElementById("commentTitle").value = "";
			document.getElementById("commentBox").value = "";
			document.getElementById("theActive").value = 1;
			document.getElementById("theActive").checked = true;
			document.getElementById("theConfirm").style.display = "none";
			document.getElementById("theForm").style.display = "block";
			submitType = "add";
			replaceText("validation","");
		}
	}
	
	function initFormEdit(){
		// sets up the form for editing a record
		replaceText("commentTab2","Edit your comment");
		theTab = document.getElementById("commentTab2");
		theTab.setAttribute("onClick", "initFormEdit();tabBoxV3('commentTab','2','2');");
		document.getElementById("theConfirm").style.display = "none";
		document.getElementById("theForm").style.display = "block";
		submitType = "update";
	}

	function getComments(){
		commentsUrl = "index.cfm?fa=comments.getComments&ajaxOn=1&guid=" + dataItemId;
		loadXMLComments(commentsUrl);
		initFormAdd();
	}
	
	function submitComment(){
		var errMsg = "Please complete ";
		var errCount = 0;
		
		theTitle = document.userInput.commentTitle.value;
		theComment = document.userInput.commentBox.value;
		if(document.userInput.theActive.checked == true){
			testActive = 1;
			} else {
			testActive = 0;
		}

		
		// a little validation for empty fields...
		if(regXtrim(theTitle).length < 1){
			errCount ++;
			errMsg += "comment title ";
		}
		
		theTitle = theTitle.replace( new RegExp( "&", "g" ), "_AMP_" );
		theTitle = theTitle.replace( new RegExp( "\n", "g" ), "_BR_" );
		
		if(regXtrim(theComment).length < 1){
			errCount ++;
			errCount > 1? errMsg += "and ": errMsg += "";
			errMsg += "comment text ";
		}
		errCount > 1? errMsg += "fields.": errMsg += "field.";

		// in order to support URLs and line feeds, you have to replace certain characters (by Josh and Bill, 7/11/07)
		theComment = theComment.replace( new RegExp( "&", "g" ), "_AMP_" );
		//theComment = theComment.replace( new RegExp( "\?", "g" ), "_Q_" );
		theComment = theComment.replace( new RegExp( "\n", "g" ), "_BR_" );
		
		if(errCount == 0){
			if(submitType == "add") commentsUrl = "index.cfm?fa=comments.postComments&ajaxOn=1&guid=" + dataItemId + "&title=" + theTitle + "&commentText=" + theComment + "&itemType=" + dataItemType + "&isActive=" + testActive + "&urlString=test";
			if(submitType == "update")commentsUrl = "index.cfm?fa=comments.updateComment&ajaxOn=1&guid=" + dataItemId + "&title=" + theTitle + "&commentText=" + theComment + "&id=" + theCommentId + "&isActive=" + testActive;
			replaceText("validation","");
			loadXMLAddComment(commentsUrl);
		}else{
			replaceText("validation",errMsg);
		}
	}

	function regXtrim(theText){
		// delete leading, then trailing, white-space
	    trimmed = theText.replace(/^\s+/,'');
        trimmed = trimmed.replace(/\s+$/,'');
		return trimmed;
	}
	
	function submitAlert(theId){
		theActiveAlert = theId;
		theAlertReason = document.getElementById("alertReason" + theId).value;
		commentsUrl = "index.cfm?fa=comments.alert&ajaxOn=1&guid=" + dataItemId + "&alertText=" + theAlertReason + "&commentId=" + theCommentId + "&url=" + escape(window.location);
		loadXMLAddComment(commentsUrl);
	}


	function showConfirmation(){
		document.getElementById("theForm").style.display = "none";
		document.getElementById("theConfirm").style.display = "block";
		tabBoxV3('commentTab','2','2');
		replaceText("confirmMsg", req2.responseText);
	}

	function getNodeVal(theNode, index){
		if(req2.responseXML.getElementsByTagName(theNode)[index].hasChildNodes()){
			return req2.responseXML.getElementsByTagName(theNode)[index].firstChild.nodeValue;
		}else{
			return ""
		}
	}

	function getContent(index){
		theUser = getNodeVal("ecasuser",index);
		theCreationdate = getNodeVal("creationdate", index);
		theLastUpdate = getNodeVal("lastupdated", index);
		theTitle = getNodeVal("title", index);
		theCommentText = getNodeVal("commenttext", index);
		
		//reverse the character encoding we had to do got the GET to work
		theTitle = theTitle.replace( new RegExp( "_AMP_", "g" ), "&" );
		theTitle = theTitle.replace( new RegExp( "_BR_", "g" ), "<br>" );
		
		theCommentText = theCommentText.replace( new RegExp( "_AMP_", "g" ), "&" );
		//theCommentText = theCommentText.replace( new RegExp( "_Q_", "g" ), "?" );
		theCommentText = theCommentText.replace( new RegExp( "_BR_", "g" ), "<br>" );
		
		theEditStat = getNodeVal("editable", index);
		theCommentId = getNodeVal("id", index);
		theActive = getNodeVal("theActive", index);
	}
	
	function processComment(){
		// clear any previous comments
		replaceText("commentList", "");
		
		theComments = document.getElementById("commentList");
		var items = req2.responseXML.getElementsByTagName("comment");
		if(items.length > 0){
			for(var i = 0; i < items.length; i++){
				// get the comment data for one record
				getContent(i);
				// build the comment				
				theDiv = document.createElement("div");
				theDiv.setAttribute("id","com" + i);
				// if it's an inActive comment, add note so admin knows
				if(theActive == 0){
					newH = document.createElement("h2");
					newSpan = document.createElement("span");
					newText = document.createTextNode("This post is not shown to users");
					newSpan.appendChild(newText);
					newH.appendChild(newText);
					theDiv.appendChild(newH);
				}
				//create the posted by line
				newP = document.createElement("p");
				newText = document.createTextNode(theTitle);
				newStrong = document.createElement("strong");
				newStrong.appendChild(newText);
				newP.appendChild(newStrong);
				var tmpText = " posted by: " + theUser + " on " + theCreationdate;
				newText = document.createTextNode(tmpText);
				newP.appendChild(newText);
				theDiv.appendChild(newP);
				// create the comment block
				newP = document.createElement("p");
				
				newP.innerHTML = theCommentText;
				//newText = document.createTextNode(theCommentText)
				
				newP.setAttribute("id", "commentText");
				//newP.appendChild(newText)
				theDiv.appendChild(newP);
				// create the alert and edit links
				newP = document.createElement("p");
				newP.className="right";
				// updated notice
				if(theLastUpdate != ""){
					newSpan = document.createElement("span");
					newText = document.createTextNode("This post was last edited on " + theLastUpdate);
					newSpan.appendChild(newText);
					newP.appendChild(newSpan);
				}
				// edit link
				if(theEditStat == "true"){
					newLink = document.createElement("a");
					newLink.setAttribute("href","javascript:editComment("+ i + ")");
					newText = document.createTextNode("Edit my comment");
					newLink.className = "commentUtil";
					newLink.appendChild(newText);
					newP.appendChild(newLink);
				}else{
					// alert moderator link if logged in
					if(theUserLogged == true){
						newLink = document.createElement("a");
						//newLink.setAttribute("href","index.cfm?fa=comments.moderator&commentId=" + theCommentId);
						newLink.setAttribute("href","javascript:alertComment("+ i + ")");
						newLink.setAttribute("id","alertMod"+i);
						newText = document.createTextNode("Alert Moderator");
						newLink.className = "commentUtil";
						newLink.appendChild(newText);
						newP.appendChild(newLink);
					}
				}
				theDiv.appendChild(newP);
				//append the div to the parent div
				theComments.appendChild(theDiv);
			}
		}else{
		// create the "be the first" statement...
			newP = document.createElement("p");
			newEm = document.createElement("em");
			newText = document.createTextNode("Be the first to comment on this " + dataItemType + ".");
			newEm.appendChild(newText);
			newP.appendChild(newEm);
			theComments.appendChild(newP);
		}
	}
	
	function alertComment(theId){
		// get the selected comment Info
		getContent(theId);
		// get the proper comment's div
		theSelectedDiv = document.getElementById("com" + theId);
		theSelectedBtn = document.getElementById("alertMod" + theId);
		// create the wrapper div
		newDiv = document.createElement("div");
		newDiv.setAttribute("id", "alertDiv" + theId);
		newDiv.className = "theAlert";
		// instructions
		newP = document.createElement("p");
		newText = document.createTextNode("Please tell us why you are notifying us about this comment.");
		newP.appendChild(newText);
		newDiv.appendChild(newP);
		// text area
		newForm = document.createElement("form");
		newForm.setAttribute("id", "alertForm");
		newTextBox = document.createElement("textarea");
		newTextBox.setAttribute("rows", "4");
		newTextBox.setAttribute("cols", "50");
		newTextBox.setAttribute("id", "alertReason" + theId);
		newForm.appendChild(newTextBox);
		newDiv.appendChild(newForm);
		
		// create the submit
		newLink = document.createElement("a");
		newLink.setAttribute("href","javascript:submitAlert("+ theId + ")");
		newText = document.createTextNode("Submit Alert");
		newLink.className = "commentUtil";
		newLink.appendChild(newText);
		newDiv.appendChild(newLink);
		
		// create the cancel
		newLink = document.createElement("a");
		newLink.setAttribute("href","javascript:cancelAlert("+ theId + ")");
		newText = document.createTextNode("Cancel");
		newLink.className = "commentUtil";
		newLink.appendChild(newText);
		newDiv.appendChild(newLink);
				
		// disable the alert moderator button
		theSelectedBtn.removeAttribute("href");
		theSelectedBtn.className = "commentDisabled";
		
		// put it all in the appropriate comment's div
		theSelectedDiv.appendChild(newDiv);
	}
	
	function cancelAlert(theId){
		theSelectedDiv = document.getElementById("com" + theId);
		theSelectedAlert = document.getElementById("alertDiv" + theId);
		theSelectedDiv.removeChild(theSelectedAlert);
		theSelectedBtn = document.getElementById("alertMod" + theId);
		theSelectedBtn.setAttribute("href","javascript:alertComment("+ theId + ")");
		theSelectedBtn.className = "commentUtil";
	}

	
	function editComment(theId){
		// get the record contents
		getContent(theId);
		//plug it into the edit form
		document.userInput.commentTitle.value = theTitle;
		document.userInput.commentBox.value = theCommentText;
		document.userInput.theActive.value = theActive;
		if(theActive == 1){
			document.userInput.theActive.checked = true;
			} else {
			document.userInput.theActive.checked = false;
		}
		
		initFormEdit();
		
		// switch the selected tab
		tabBoxV3('commentTab','2','2');
	}
	
	function showError2(errMsg){
		replaceText("theComments", "");
		replaceText("theComments", "Error encountered. <br/>" + errMsg);
	}
	
