/**
 *
 * Author: Michael Kinkaid
 * Version 1
 * 
 * The following functions are used within publish.asp
 *
 **/

/**
 * Opens editProductDetails.asp so that the user can  
 * edit the name and title of this product
 */
 
var xmlHttpSetDetails;
var xmlHttpPostMessage;
var commentTitleSaved;
var commentTextSaved;
var productIDSaved;
var moveToLoginHttp;

function formatStringForHTML(rawString)
{
	rawString = rawString.replace(/</g,"&lt;");
	rawString = rawString.replace(/>/g,"&gt;");
	rawString = rawString.replace(/"/g,"&#34;");
	return rawString;
}
 
function openEditProperties(n_productID)
{
	//Save the productID for any future calls
	productIDSaved = n_productID
	
	//Open uploadImage.asp in pop-up window
	var theTop	= (screen.height/2)-(125);
	var theLeft	= (screen.width/2)-(225);
	var URL = "../../myAccount/editProductDetails.asp?productID=" + n_productID;
	var features = "height=250,width=450,top=" + theTop + ",left=" + theLeft + ",status=yes,toolbar=no,menubar=no,location=no";
	window.open(URL, "_blank", features);
}

function updateTitle(str_newTitle, str_newDescription)
{
	//Get objects
	var aboutTitleObj = document.getElementById("testTitle");
	var aboutDescriptionObj = document.getElementById("aboutDescriptionText");
	
	//Update values on page
	aboutTitleObj.innerHTML			= formatStringForHTML(str_newTitle) + " ";
	aboutDescriptionObj.innerHTML	= formatStringForHTML(str_newDescription);
	updateFlashTitle(formatStringForHTML(str_newTitle));
}

/**
 * Handles the creation of the XMLHTTP object for use with AJAX
 * communication between the client and the server.
 */
function GetXmlHttpObject() 
{
    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      var aVersions = [ "MSXML2.XMLHttp.5.0",
        "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
        "MSXML2.XMLHttp","Microsoft.XMLHttp"
      ];

      for (var i = 0; i < aVersions.length; i++) {
        try {
            var oXmlHttp = new ActiveXObject(aVersions[i]);
            return oXmlHttp;
        } catch (oError) {
            //Do nothing
        }
      }
    }
    throw new Error("XMLHttp object could be created.");
}

function commentLoginResponse()
{
	if (xmlHttpSetDetails.readyState==4 || xmlHttpSetDetails.readyState=="complete")
	{
		
		//Successful login
		var updateResponse = xmlHttpSetDetails.responseText;
		if(updateResponse == "Invalid username or password.")
		{
			var loginErrorMessage = document.getElementById("errorMessage");
			loginErrorMessage.innerHTML = "<img id='loginError' src='../../images/Comments/error.gif' width='16' height='16' />" + updateResponse;
		}
		else if(updateResponse == "Success")
		{
			var addCommentContainer = document.getElementById("addCommentContainer");
			addCommentContainer.innerHTML = "<div id='addCommentHeader'></div><div id='addCommentTitle'><img id='addCommentIcon' src='../../images/Comments/addCommentIcon.gif' width='18' height='18' />Add a comment</div><div id='addCommentForm'><span id='titleLabel'>Title:</span><br /><input type='text' id='commentTitle' name='commentTitleTextBox' /><br /><br /><span id='commentLabel'>Comment:</span><br /><textarea id='commentText' name='commentTextArea' rows='5'></textarea></div><span id='errorMessage'></span><div id='postCommentButton'><a id='sendPost' href='javaScript:;' onclick='postMessage()'></a></div><div id='addCommentFooter'></div>";
		}
		else
		{
			var loginErrorMessage = document.getElementById("errorMessage");
			loginErrorMessage.innerHTML = "<img id='loginError' src='../../images/Comments/error.gif' width='16' height='16' />We had a problem!  Please try again.";
		}
	}	
}

function postMessage()
{
	
	//Get objects
	var commentTitleObj	= document.getElementById("commentTitle");
	var commentTextObj	= document.getElementById("commentText");
 	var postErrorMessageObj = document.getElementById("errorMessage");
	
	//Perform Validation
	if(isEmpty(commentTitleObj, postErrorMessageObj))
	{
		if(isEmpty(commentTextObj, postErrorMessageObj))
		{
			//Validation successful
			var commentTitleVal	= encodeURI(commentTitleObj.value);
			var commentTextVal	= encodeURI(commentTextObj.value);	
			
			//Save values to display new comment
			commentTitleSaved	= commentTitleObj.value;
			commentTextSaved	= commentTextObj.value;
			commentTitleSaved	= formatStringForHTML(commentTitleSaved);
			commentTextSaved	= formatStringForHTML(commentTextSaved);

			var productID 		= getQueryVariable("productID");
			var parameters = "commentTitle=" + commentTitleVal + "&commentText=" + commentTextVal + "&productID=" + productID;
			
			//Create xmlHttp
			xmlHttpPostMessage = GetXmlHttpObject();
			if (xmlHttpPostMessage == null)
			{
				alert ("Browser does not support HTTP Request");
				return;
			}
			else
			{
				var loginErrorMessage = document.getElementById("errorMessage");
				loginErrorMessage.innerHTML = "<img id='loginError' src='../../images/Comments/database_save.gif' width='16' height='16' />Processing . . . ";			
			} 		
			
			//Send information to addCommenet.asp
			xmlHttpPostMessage.onreadystatechange = addCommentResponse;
			xmlHttpPostMessage.open('POST', "commentCreate.asp", true);
			xmlHttpPostMessage.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttpPostMessage.setRequestHeader("Content-length", parameters.length);
			xmlHttpPostMessage.setRequestHeader("Connection", "close");
			xmlHttpPostMessage.send(parameters);
		}
	}
}

function addCommentResponse()
{
	if (xmlHttpPostMessage.readyState==4 || xmlHttpPostMessage.readyState=="complete")
	{
		/*
		if(updateResponse == "loginError")
		{
			var loginErrorMessage = document.getElementById("errorMessage");
			loginErrorMessage.innerHTML = "<img id='loginError' src='../../images/Comments/error.gif' width='16' height='16' />" + updateResponse;
		}
		*/
		
		//Get reference to the add comment boxes and clear
		var commentTextObj		= document.getElementById("commentText");
		var commentTitleObj		= document.getElementById("commentTitle");
		commentTextObj.value	= "";
		commentTitleObj.value	= "";
		
		//Show successful update in addCommentContainer
		var errorMessage = document.getElementById("errorMessage");
		errorMessage.innerHTML = "<img id='loginError' src='../../images/Comments/commentSuccess.gif' width='16' height='16' /> Comment added (see below).";
				

		//Get reference to commentListNode
		var commentListObj		= document.getElementById("commentList");
		var currentHTML			= commentListObj.innerHTML;
		
		//Attempt JSON script
		var myJSONString		= xmlHttpPostMessage.responseText;
		var JSON_Response		= eval("(" + myJSONString + ")");
		var strUserName			= JSON_Response.userName;
		var strImageURL			= JSON_Response.imageURL;
		var nImageWidth			= JSON_Response.imageWidth;
		var nImageHeight		= JSON_Response.imageHeight;

		if(strImageURL != "No Image")
		{
			commentListObj.innerHTML = "<div class='userCommentContainer'><div class='imgContainer'><img class='profileImage' src='../../userResources/thumbNails/" + strImageURL + "' width='" + nImageWidth + "' height='" + nImageHeight + "' /></div><div class='commentContainer'><p class='userName'>New message<span class='commentDate'>(&nbsp;" + strUserName + ",&nbsp;today&nbsp;)</span></p><p class='userComment'><em><i>Waiting to be approved...</i></em></p></div></div>" + currentHTML;			
		}
		else
		{
			commentListObj.innerHTML = "<div class='userCommentContainer'><div class='imgContainer'><img class='profileImage' src='../../images/accountImages/noImageWee.gif' width='50' height='50' /></div><div class='commentContainer'><p class='userName'>New message<span class='commentDate'>(&nbsp;" + strUserName + ",&nbsp;today&nbsp;)</span></p><p class='userComment'><em><i>Waiting to be approved...</i></em></p></div></div>" + currentHTML;	
		}
	}
}


/**
 * Checks to see if a string entered by the user is empty
 *
 * @param	obj_input				Form element that we are checking 
 * @param	str_helperMessage		Message displayed on error
 * @param	str_hint				Message displayed to discribe validation
 * @param	obj_errorMsg			Form element to display all messages 
 *
 */
function isEmpty(obj_input, obj_errorMsg)
{
	if(obj_input.value.length != 0)
	{
		obj_errorMsg.innerHTML = "";
		return true;
	}
	else
	{
		obj_errorMsg.innerHTML = "<img id='loginError' src='../../images/Comments/error.gif' width='16' height='16' />Please complete every field.";
		obj_input.focus();
		return false;	
	}
}

function getQueryVariable(variable) 
{
  var query	= window.location.search.substring(1);
  if(query != "")
  {
	  var vars	= query.split("&");
	  for (var i=0;i<vars.length;i++)
	  {
	    var pair = vars[i].split("=");
	    if (pair[0] == variable) 
	    {
	      return pair[1];
	    }
	  }  
  }
  
  return null;
}

function moveToLogin(){
	var productURL = window.location.href;
		
	moveToLoginHttp= GetXmlHttpObject();
	if (moveToLoginHttp== null)
	{
		alert ("Browser does not support HTTP Request.  Please upgrade your browser.");
		return;
	} 
	
	var url = "saveURL.asp";
	url = url + "?url=" + encodeURIComponent(productURL);
	url = url + "&sid=" + Math.random();
	moveToLoginHttp.onreadystatechange = moveToLoginResponse;
	moveToLoginHttp.open("GET", url, true);
	moveToLoginHttp.send(null);	
}

function moveToLoginResponse(){
	if(moveToLoginHttp.readyState==4 || moveToLoginHttp.readyState=="complete")
	{
		if(moveToLoginHttp.status == 200)
		{
			var updateResponse = moveToLoginHttp.responseText;
			window.open("../../loginAndRegistration.asp", "_self");		
		}	
	}
}

function updateVoteScore(){
	var votesForProductObj	= document.getElementById("votesForProduct");
	var totalVotesObj		= document.getElementById("totalVotes");
	var percentageVotesObj	= document.getElementById("percentageVotes");

	var votesForProduct	= parseInt(votesForProductObj.innerHTML);
	var totalVotes		= parseInt(totalVotesObj.innerHTML);
	var percentageVotes = parseInt(percentageVotesObj.innerHTML);
	
	var newVotesForProduct	= votesForProduct + 1;
	var newTotalVotes		= totalVotes + 1;
	
	votesForProductObj.innerHTML	= newVotesForProduct + ""; 
	totalVotesObj.innerHTML			= newTotalVotes + "";
	percentageVotesObj.innerHTML	= Math.round((newVotesForProduct / newTotalVotes) * 100) + "%";
}

