/*****************************************************************
Company: MediLexicon International Ltd.

Description: Performs the "rate this article" functionality 
asynchonously using AJAX technology, including updating and 
displaying the rating score in the form of star images and 
textual format.

Warning: This code cannot be copied, reused, distributed in any 
manner without written consent from MediLexicon International Ltd.

*******************************************************************/

var usertype;
var score;

// used to check for user double clicking on the stars
var infoAdded = false;

// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
var xmlHttpStars = createXmlHttpRequestObject();

/***************************************************************************************/
// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

/***************************************************************************************/
// called to read a file from the server
function rate(user,score)
{
  
  if(infoAdded) return;
  infoAdded = true;
  
  //hideSubmitButton();
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    {
		usertype = user;
		// this was the old method url (when there was radion buttons and dropdown menu)...
		//var url = "../raterserver.php?rating=" + getRatingsInfo() + "&usertype=" + getUserTypeInfo() + "&newsid=" + getNewsIdInfo() + "&categoryid=" + getCategoryIdInfo();
		
		// build the url with parameters: rating, usertype, newsid, categoryid - pass these to raterserver.php db(s)
		var url = "/rater/raterserver.php?rating=" + score + "&usertype=" + user + "&newsid=" + getNewsIdInfo() + "&categoryid=" + getCategoryIdInfo();
	
		// initiate reading the url file from the server	
		xmlHttp.open("GET", url, true);
		xmlHttp.onreadystatechange = handleRateRequestStateChange;
		xmlHttp.send(null);	
    }
    // display the error in case of failure
    catch (e) 
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

/***************************************************************************************/
// function that handles the HTTP response
function handleRateRequestStateChange() 
{
  // obtain a reference to the <div> element on the page
  var myDiv = document.getElementById("txtHint");
  var response = "";
  // when readyState is 4, we also read the server response
  if (xmlHttp.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      { 	  		
		// read the message from the server
        response = xmlHttp.responseText;

		// display the message (string received from server file - rateserver.php)
		myDiv.innerHTML = response;

		// hide the initial ratings score (displayed from the <?include raterscoreserver.php?>)
        hideRatingScoreDiv();
	
		// hide the rating form to stop users from rating more than once
		hideRateForm();	
		// if rating or visitor type hasn't been selected on the rating form
		if (document.getElementById("norating") || document.getElementById("novisitortype")){
			showRateForm();
			showSubmitButton();
		}		
		else {
			// showOpinionInfo();
		}

		// displays the appropriate star image that represents the rating score
		displayStars();
      }
      catch(e)
      {
        // display error message
        alert("Error reading the response: " + e.toString());
      }
    } 
    else
    {
      // display status message
      alert("There was a problem retrieving the data:\n" + 
            xmlHttp.statusText);
    }
  }
}

/***************************************************************************************/
// displays the appropriate star image that represents the rating score
// won't work if the file <? include raterstarserver.php?> hasn't been included
function displayStars(){
	
	if (usertype == "hcp"){	
		// get the average HCP rating from the server and then convert into a float
		var avgHcpServer = document.getElementById("avghcprating");
		avgHcpServer = avgHcpServer.innerHTML;
		var avghcp = parseResponseIntoFloat(avgHcpServer);
		
		if (document.getElementById("hcpnotyetrated") != null){
			var hcpNotYetRatedImage = document.getElementById("hcpnotyetrated");
			var newHcpNotYetRatedImage = document.createElement("img");
       		newHcpNotYetRatedImage.setAttribute("id", "hcpstars");
			newHcpNotYetRatedImage = convertToStars(avghcp,newHcpNotYetRatedImage);					
			
			// replace old star image with the newly created image node
			var hcpNotYetRatedImageParent = hcpNotYetRatedImage.parentNode;
			hcpNotYetRatedImageParent.insertBefore(newHcpNotYetRatedImage, hcpNotYetRatedImage);
			hcpNotYetRatedImageParent.removeChild(hcpNotYetRatedImage);	
			
			var hcpStarRaterVotes = document.getElementById("avghcprating_raterstarserver");
			var newHcpStarRaterVotes = document.createElement("p");
			newHcpStarRaterVotes.setAttribute("style", "font-size:10px");
			newHcpStarRaterVotes.style.fontSize = "10px";				
       		newHcpStarRaterVotes.setAttribute("id", "avghcprating_raterstarserver");
			var txt = document.createTextNode(avgHcpServer);
			newHcpStarRaterVotes.appendChild(txt);
			
			var hcpStarRaterVotesParent = hcpStarRaterVotes.parentNode;
			hcpStarRaterVotesParent.insertBefore(newHcpStarRaterVotes, hcpStarRaterVotes);
			hcpStarRaterVotesParent.removeChild(hcpStarRaterVotes);
		}
		
		// create a new image node and set appropriate attributes
		else if (document.getElementById("hcpstars") != null){
			var hcpStarImage = document.getElementById("hcpstars");
			var newHcpStarImage = document.createElement("img");
       		newHcpStarImage.setAttribute("id", "hcpstars");
			newHcpStarImage = convertToStars(avghcp,newHcpStarImage);			
			
			// replace old star image with the newly created image node
			var hcpStarImageParent = hcpStarImage.parentNode;
			hcpStarImageParent.insertBefore(newHcpStarImage, hcpStarImage);
			hcpStarImageParent.removeChild(hcpStarImage);
			
			
			// replace written number vote in raterstarserver with newly updated written number vote
			var hcpStarRaterVotes = document.getElementById("avghcprating_raterstarserver");
			var newHcpStarRaterVotes = document.createElement("p");
			newHcpStarRaterVotes.setAttribute("style", "font-size:10px");
			newHcpStarRaterVotes.style.fontSize = "10px";				
       		newHcpStarRaterVotes.setAttribute("id", "avghcprating_raterstarserver");
			var txt = document.createTextNode(avgHcpServer);
			newHcpStarRaterVotes.appendChild(txt);
			
			var hcpStarRaterVotesParent = hcpStarRaterVotes.parentNode;
			hcpStarRaterVotesParent.insertBefore(newHcpStarRaterVotes, hcpStarRaterVotes);
			hcpStarRaterVotesParent.removeChild(hcpStarRaterVotes);
			
		}
	}
		
	else if (usertype == "public"){
		// get the average Public rating from the server and then convert into a float
		var avgPublicServer = document.getElementById("avgpublicrating");
		avgPublicServer = avgPublicServer.innerHTML;
		var avgpublic = parseResponseIntoFloat(avgPublicServer);

		if (document.getElementById("publicnotyetrated") != null){
			var publicNotYetRatedImage = document.getElementById("publicnotyetrated");
			var newPublicNotYetRatedImage = document.createElement("img");
       		newPublicNotYetRatedImage.setAttribute("id", "publicstars");
			newPublicNotYetRatedImage = convertToStars(avgpublic,newPublicNotYetRatedImage);					
			
			// replace old star image with the newly created image node
			var publicNotYetRatedImageParent = publicNotYetRatedImage.parentNode;
			publicNotYetRatedImageParent.insertBefore(newPublicNotYetRatedImage, publicNotYetRatedImage);
			publicNotYetRatedImageParent.removeChild(publicNotYetRatedImage);
			
			// adds written votes number for the first time
			var publicStarRaterVotes = document.getElementById("avgpublicrating_raterstarserver");
			var newPublicStarRaterVotes = document.createElement("p");
			newPublicStarRaterVotes.setAttribute("style", "font-size:10px");
			newPublicStarRaterVotes.style.fontSize = "10px";	
       		newPublicStarRaterVotes.setAttribute("id", "avgpublicrating_raterstarserver");
			var txt = document.createTextNode(avgPublicServer);
			newPublicStarRaterVotes.appendChild(txt);
			// need to insert it into place
			
			var publicStarRaterVotesParent = publicStarRaterVotes.parentNode;
			publicStarRaterVotesParent.insertBefore(newPublicStarRaterVotes, publicStarRaterVotes);
			publicStarRaterVotesParent.removeChild(publicStarRaterVotes);
			
		}

		// create a new image node and set appropriate attributes
		else if (document.getElementById("publicstars") != null){
			var publicStarImage = document.getElementById("publicstars");					
			var newPublicStarImage = document.createElement("img");
       		newPublicStarImage.setAttribute("id", "publicstars");
			newPublicStarImage = convertToStars(avgpublic,newPublicStarImage);
			
			// replace old star image with the newly created node			
			var publicStarImageParent = publicStarImage.parentNode;
			publicStarImageParent.insertBefore(newPublicStarImage, publicStarImage);
			publicStarImageParent.removeChild(publicStarImage);
			
			// replace written number vote in raterstarserver with newly updated written number vote
			var publicStarRaterVotes = document.getElementById("avgpublicrating_raterstarserver");
			var newPublicStarRaterVotes = document.createElement("p");
			newPublicStarRaterVotes.setAttribute("style", "font-size:10px");
			newPublicStarRaterVotes.style.fontSize = "10px";	
       		newPublicStarRaterVotes.setAttribute("id", "avgpublicrating_raterstarserver");
			var txt = document.createTextNode(avgPublicServer);
			newPublicStarRaterVotes.appendChild(txt);
			
			var publicStarRaterVotesParent = publicStarRaterVotes.parentNode;
			publicStarRaterVotesParent.insertBefore(newPublicStarRaterVotes, publicStarRaterVotes);
			publicStarRaterVotesParent.removeChild(publicStarRaterVotes);
		}
	}
}

/***************************************************************************************/
// get rating value (radio buttons) for the users choice ---- NO LONGER IN USE!
function getRatingsInfo(){	
	for (i=1;i<6;i++){
		var radio = document.getElementById("radio" + i);		
			if (radio.checked == true){
				var rating = radio.value;
				return rating;
			}
	}

	// "" is used in raterserver.php and rater.js as a test for no rating radio being checked 
	return "";
}

/***************************************************************************************/
// get type of user (professional or member of public - dropdown menu) for the 
// users choice ---- NO LONGER IN USE!
function getUserTypeInfo(){
	var usertype = document.getElementById("ratings_select");
	usertype = usertype.options[usertype.options.selectedIndex].value;
	return usertype;
}
	
/***************************************************************************************/	
// get the articles newsid - e.g. 77866
function getNewsIdInfo(){
	var newsid = document.getElementById("newsid");
	var newsidvalue = newsid.getAttribute("value");
	return newsidvalue;
}	

/***************************************************************************************/
// get the articles categoryid - e.g. 74
function getCategoryIdInfo(){
	var categoryid = document.getElementById("categoryid");
	var categoryidvalue = categoryid.getAttribute("value");
	return categoryidvalue;
}	

/***************************************************************************************/
// parses the response from the server (avgString) and returns the appropriate part as a float
function parseResponseIntoFloat(avgString){
	whiteSpace = " ";
	start = 0;
	firstSpace = 0;
	searchThis = 0;
	avghcp = 0;

	// parse the response received from the server in order to pull out the avergage rate result and convert into a float		
	for (i=0 ; i<avgString.length ; i++){
    	// finds the index of white space and returns that position
		searchThis = avgString.indexOf(whiteSpace, start);			
		// if a white space has been found
		if(searchThis != 0){
			firstSpace += 1;
		}
		// if it is the first instance of a white space being found
		if (firstSpace == 1){
			var firstPart = "";
			// concat into a string - from start of servers response string upto the first white space
			for (i=0 ; i<searchThis ; i++){
				firstPart = firstPart + avgString.charAt(i);						
			}
			// convert the concat string into a float
			avghcp = parseFloat(firstPart);
			break;
    	}
    	else{
       		start = searchThis + 1;
    	}
	}
	return avghcp;
}

/***************************************************************************************/
// takes a float value and sets corresponding attributes on an image node
function convertToStars(avgFloat,newStarImage){
		if (avgFloat <= 1){
			newStarImage.setAttribute("src", "../images/rater/1stars.gif");
			newStarImage.setAttribute("alt", "1 star");
		}
		else if(avgFloat >1 && avgFloat <= 1.5){
			newStarImage.setAttribute("src", "../images/rater/1_5stars.gif");
			newStarImage.setAttribute("alt", "1 and a half stars");
		}	
		else if(avgFloat >1.5 && avgFloat <= 2){
			newStarImage.setAttribute("src", "../images/rater/2stars.gif");
			newStarImage.setAttribute("alt", "2 stars");
		}						
		else if(avgFloat >2 && avgFloat <= 2.5){
			newStarImage.setAttribute("src", "../images/rater/2_5stars.gif");
			newStarImage.setAttribute("alt", "2 and a half stars");
		}			
		else if(avgFloat >2.5 && avgFloat <= 3){
			newStarImage.setAttribute("src", "../images/rater/3stars.gif");
			newStarImage.setAttribute("alt", "3 stars");
		}				
		else if(avgFloat >3 && avgFloat <= 3.5){
			newStarImage.setAttribute("src", "../images/rater/3_5stars.gif");
			newStarImage.setAttribute("alt", "3 and a half stars");
		}			
		else if(avgFloat >3.5 && avgFloat <= 4){
			newStarImage.setAttribute("src", "../images/rater/4stars.gif");
			newStarImage.setAttribute("alt", "4 stars");
		}			
		else if(avgFloat >4 && avgFloat <= 4.5){
			newStarImage.setAttribute("src", "../images/rater/4_5stars.gif");
			newStarImage.setAttribute("alt", "4 and a half stars");
		}
		else if(avgFloat >4.5 && avgFloat <= 5){
			newStarImage.setAttribute("src", "../images/rater/5stars.gif");
			newStarImage.setAttribute("alt", "5 stars");
		}	
	
	return newStarImage;	
}

/***************************************************************************************/
// hides the rate area to stop multiple ratings 
function hideRateForm(){
	var ratingForm = document.getElementById("ratings_form");
	ratingForm.style.display = "none";
}

/***************************************************************************************/
// shows the rate area 
function showRateForm(){
	var ratingForm = document.getElementById("ratings_form");
	ratingForm.style.display = '';
}

/***************************************************************************************/
// hide submit button 
function hideSubmitButton(){
	var buttonSubmit = document.getElementById("button_submit");
	buttonSubmit.style.display = "none";
}

/***************************************************************************************/
// show submit button 
function showSubmitButton(){
	var buttonSubmit = document.getElementById("button_submit");
	buttonSubmit.style.display = '';
}

/***************************************************************************************/
// hides the average score area displayed from raterscoreserver.php  
// doesn't hide the score area from raterserver.php
function hideRatingScoreDiv(){
	if (document.getElementById("rating_score_div") != null){
		var ratingScoreDiv = document.getElementById("rating_score_div");
		ratingScoreDiv.style.display = "none";
	}
}

/***************************************************************************************/
// shows the link for users to write their opinions on the current article
function showOpinionInfo(){
	var opinionArea = document.getElementById("opinion_area");
	if (opinionArea.childNodes.length == 0){
		var opinionLink = document.createElement("a");
    	opinionLink.setAttribute("id", "opinionlink");
    	opinionLink.setAttribute("href", "../voiceyouropinion.php?associatednewsid=" + getNewsIdInfo());	

		opinionArea.appendChild(opinionLink);
	
		opinionText=document.createTextNode(">> Add your opinion on this article");
		opinionLink.appendChild(opinionText);
	}
}
