/**
 *
 * 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;

function formatStringForHTML(rawString)
{
	rawString = rawString.replace(/</g,"&lt;");
	rawString = rawString.replace(/>/g,"&gt;");
	return rawString;
}

function showLoginBox()
{
	var addCommentContainer = document.getElementById("addCommentContainer");
	addCommentContainer.innerHTML = "<div id='addCommentHeader'><img src='../../images/gallery/CommentBox/header_grey.png' width='430' height='12'></div><div id='addCommentTitle'><img id='addCommentIcon' src='../../images/Comments/user_grey.gif' width='16' height='16' />Login Here&nbsp;<a id='newUserRegistration' href='../../loginAndRegistration.asp'>(sign-up here)</a></div><div id='addCommentForm'><span id='titleLabel'>User Name:</span><br /><input type='text' id='userName' name='userNameTextBox' /><br /><br /><span id='commentLabel'>Password:</span><br /><input type='password' id='password' name='passwordTextBox' /></div><div id='errorContainer'><span id='errorMessage'></span></div><div id='postCommentButton'><a id='sendlogin' href='javaScript:;' onclick='loginToAddComment()'></a></div><div id='addCommentFooter'><img src='../../images/gallery/CommentBox/footer_grey.png' width='430' height='12'></div>";
}


function showSendToAFriend()
{
	var theTop	= (screen.height/2)-(420/2);
	var theLeft	= (screen.width/2)-(400/2);
	var features = "height=420,width=400,top=" + theTop + ",left=" + theLeft + ",status=yes,toolbar=no,menubar=no,location=no,scrollbars=no";
	window.open("../../sendtoFriend.asp", "_blank", features);		
}

function contact(userName)
{
	var theTop	= (screen.height/2)-(400/2);
	var theLeft	= (screen.width/2)-(400/2);
	var url = "../../contact.asp?Designer=" + userName
	var features = "height=400,width=400,top=" + theTop + ",left=" + theLeft + ",status=yes,toolbar=no,menubar=no,location=no,scrollbars=no";
	window.open(url, "_blank", features);	
}

/**
 * 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 loginToAddComment()
{
	var userNameObj = document.getElementById("userName");
	var passwordObj = document.getElementById("password");
	var strUserName = encodeURI(userNameObj.value);
	var strPassword = encodeURI(passwordObj.value);

	xmlHttpSetDetails = GetXmlHttpObject();
	if (xmlHttpSetDetails == 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_grey.gif' width='16' height='16' />Processing . . . ";	
	} 
	
	var url = "../../flashTools/designLab/commentLogin.asp";
	url = url + "?userName=" + strUserName;
	url = url + "&password=" + strPassword;
	url = url + "&sid=" + Math.random();
	xmlHttpSetDetails.onreadystatechange = commentLoginResponse;
	xmlHttpSetDetails.open("GET", url, true);
	xmlHttpSetDetails.send(null);	
}
*/

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_grey.gif' width='16' height='16' />" + updateResponse;
		}
		else if(updateResponse == "Success")
		{
			var addCommentContainer = document.getElementById("addCommentContainer");
			addCommentContainer.innerHTML = "<div id='addCommentHeader'><img src='../../images/gallery/CommentBox/header_grey.png' width='430' height='12'></div><div id='addCommentTitle'><img id='addCommentIcon' src='../../images/Comments/addCommentIcon_grey.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><div id='errorContainer'><span id='errorMessage'></span></div><div id='postCommentButton'><a id='sendPost' href='javaScript:;' onclick='postMessage()'></a></div><div id='addCommentFooter'><img src='../../images/gallery/CommentBox/footer_grey.png' width='430' height='12'></div>";
		}
		else
		{
			var loginErrorMessage = document.getElementById("errorMessage");
			loginErrorMessage.innerHTML = "<img id='loginError' src='../../images/Comments/error_grey.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 designerIDObj 	= document.getElementById("designerID");
			var designerID		= designerIDObj.value;
			
			var parameters = "commentTitle=" + commentTitleVal + "&commentText=" + commentTextVal + "&designerID=" + designerID;
			
			//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")
	{		
		//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_grey.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'><div class='commentHeader'><img src='../../images/Comments/commentTop.png' width='361' height='25' /></div><div class='commentContent'><p class='userName'>New message<span class='commentDate'>(&nbsp;<a class='commentDesignerLink' href='../../Designer/" + strUserName + "/' title='Visit " + strUserName + "'s Monster Gallery!'>" + strUserName + "</a>,&nbsp;today&nbsp;)</span></p><p class='userComment'><em><i>Waiting to be approved...</i></em></p></div><div class='commentFooter'><img src='../../images/Comments/commentBottom.png' width='361' height='20' /></div></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'><div class='commentHeader'><img src='../../images/Comments/commentTop.png' width='361' height='25' /></div><div class='commentContent'><p class='userName'>New message<span class='commentDate'>(&nbsp;<a class='commentDesignerLink' href='../../Designer/" + strUserName + "/' title='Visit " + strUserName + "'s Monster Gallery!'>" + strUserName + "</a>,&nbsp;today&nbsp;)</span></p><p class='userComment'><em><i>Waiting to be approved...</i></em></p></div><div class='commentFooter'><img src='../../images/Comments/commentBottom.png' width='361' height='20' /></div></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	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_grey.gif' width='16' height='16' />Please complete every field.";
		obj_input.focus();
		return false;	
	}
}

//Opens the designBrowse applicatiion
function openProduct(nProductID)
{
	var openURL = "../../flashTools/designLab/designBrowse.asp?productID=" + nProductID;
	window.open(openURL, "_self");
}

//Validates the search entry
function validateSearch(strUserName)
{
	//get the value for the search element
	var searchObj = document.getElementById("searchBox");
	var searchString;
	
	if(searchObj.value.length != 0)
	{
		searchString = searchObj.value;
		var url = "../gallery.asp?Designer=" + strUserName + "&searchString=" + encodeURIComponent(searchString);
		window.open(url, "_self");
	}
	
	return false;
}

Window.addEvent('domready', function() {

	var productContainerArray = new Array();
	var productContainerArray = $$('.productContainer');
	
	productContainerArray.each(function(productContainer){
		
		productContainer.setStyles({
		   height: 188
		});
		
		var productLink = productContainer.getProperty('id');
			
		var productInfo = productContainer.getElement('.productInfo');
		
		productInfo.setStyles({
		   height: 50
		});	
		
		
		var fx = new Fx.Styles(productInfo, {wait: false, duration: 300, transition: Fx.Transitions.Quad.easeOut});
		var startPosition = 0;
		var finishPosition = -50;
		
				
		productContainer.addEvents({
			
			'mouseenter': function() {
				fx.start({
					'top': [startPosition, finishPosition]
				});
			},
			'mouseleave': function() {			
				fx.start({
					'top': [finishPosition, startPosition]
				});
			},		
			'click': function() {
				openProduct(productLink)
			}
		});	
		
	
	});
});