/** THIS FILE IS USED BOTH FOR SAVING COMMENTS AND VOTES ON RESUMES/JOBOFFERS (in overview and popup pages) **/

function editComment(whichLink,cancelLabel,saveLabel,theUrl)
{
	if (document.getElementById("commentForm"))
	{
		if(confirm("Do you want to cancel unsaved changes?"))
		{
			closeCommentForms();
		}
		else
		{
			return false;
		}
	}

	myTD = whichLink.parentNode;
	myTD.myComment = myTD.getElementsByTagName("p")[0].innerHTML;
	myTD.editButton = whichLink;
	commentID = myTD.id.substring(1);
	//alert(commentID);
	fieldID = "f" +myTD.id; // the field ID will be something like "fc1", because the TD's ID is "c1" ("c" + comment's ID).
	myTD.innerHTML = '<blockquote class="comment"><form id="commentForm" name="commentForm" action="#" method="post">'
		+ '<textarea name="' +fieldID+ '" id="' +fieldID+ '">' +myTD.myComment+ '</textarea>'
		+ '<br/><input type="button" value="' +saveLabel+ '" onclick="saveComment(this,\'' +theUrl+ '\');" class="buttons"/> <input type="button" value="' +cancelLabel+ '" onclick="cancelEditComment(this);" class="buttons"/>';
		+ '</form></blockquote>';
}

function cancelEditComment(whichInput)
{
	myTD = whichInput.parentNode.parentNode.parentNode; // form-->blockquote-->td
	myTD.innerHTML = '<p>' +myTD.myComment + '</p>';
	myTD.appendChild(myTD.editButton);
}

function closeCommentForms()
{
	openTextarea = document.getElementById("commentForm").getElementsByTagName("textarea")[0];
	cancelEditComment(openTextarea);
}

function saveComment(whichButton,whichURL)
{
	myTextarea = whichButton.parentNode.getElementsByTagName("textarea")[0];
	ajaxCommentProcess("edit",myTextarea,whichURL);
}

function saveVote(whichButton,whichURL)
{
	myResume = whichButton.name.substring(1); // the resume/job id is stored in the link name, after the letter "v"
	re = /(on )/;
	myClass = whichButton.className.replace(re, ''); // Delete 'on ' in case of class='on thumbUp' or class='on thumbDn'.
	myVote = (myClass=='thumbUp') ? 1 : -1;
	myURL = whichURL + '?target_id=' +myResume+ '&vote=' + myVote;
	ajaxCommentProcess("insert",whichButton,myURL);
}

/* This function is used ONLY to delete comment from POPUP window! In "favorites" page, standard "deleteItem()" function is used */
function deleteComment(whichButton,whichURL)
{
	if(confirm('Sure to delete this comment?')) 
	{
		myID = whichButton.name.substring(1); // the "select_id" is stored in the link name, after the letter "v"
		myURL = whichURL + '?id=' +myID;
		ajaxCommentProcess("delete",whichButton,myURL);
	}
}

/*** COMMUNICATE WITH SERVER ***/

function ajaxCommentProcess(mod,myObj,myURL)
{
	/** Arguments: 
	* mod		= 'insert' or 'edit' or 'delete'
	* myObj	= the HTML object to be altered upon server response
	* myUrl	= the URL of the server script
	*/

	showHideLoading(1);
	
	/** THIS e' l'Input Field **/
	myInputField = this;
	req = null;
	myString = (myObj.id) ? myObj.id+"="+myObj.value : ""; // This function is called BOTH to submit textarea changes AND to delete an item. In the 2nd case, there is no input field.

	//alert("Submit effettuato. Attendo feedback dal server...");

	if (window.XMLHttpRequest) // Mozilla, Safari, ...
	{
		req = new XMLHttpRequest();
		if (req.overrideMimeType) { req.overrideMimeType('text/xml'); }
	}
	else if (window.ActiveXObject) // IE
	{
		try { req = new ActiveXObject("Msxml2.XMLHTTP"); } // Vers. 5.5 o inferiore
		catch (e)
		{
			try { req = new ActiveXObject("Microsoft.XMLHTTP"); } // Vers. 5.5 o superiore
			catch (e) {}
		}
	}

	if (!req) {
	   alert('Giving up :( Cannot create an XMLHTTP instance');
	   return false;
	}

	req.open("POST", myURL, true); // 1) POST or GET;  2) URL of the script to execute;  3) true for asynchronous (false for synchronous).
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	req.send(myString); // POSTs data to the server.
	
	result = false;

	req.onreadystatechange = function()
	{
		/** Ora THIS e' questa funzione! **/
		if (req.readyState == 4) // The 4 state means for the response is ready and sent by the server.
		{
			if (req.status == 200) // This status means "OK", otherwise some error code is returned, 404 for example.
			{
				//alert("Pagina trovata... \nSubmit effettuata!");

				/*** Following are the actions to be performed with the server response ***/
				rispostaServer = req.responseXML;
				if (mod=="insert") {manageRespForInsert(myObj,rispostaServer);}
				else if (mod=="edit") {manageRespForEdit(myObj,rispostaServer);}
				else if (mod=="delete") {manageRespForDelete(myObj,rispostaServer);}
			}
			else
			{
				//alert("The page generating XML has not been found!");
				alert("An error occurred while submitting data to the server!\nCode: " + req.status + " " + req.statusText); // statusText è una proprietà dell'oggetto XMLHttpRequest che contiene il messaggio di errore.
				showHideLoading(2); //hide loading div
			}
		}
	}
}


/*** MANAGE SERVER RESPONSE ***/

function switchOnThumb(aObj,selectID)
{
	re = /(on )/;
	myClass = aObj.className.replace(re, ''); // Delete 'on ' in case of class='on thumbUp' or class='on thumbDn'.
	//alert(myClass);
	theOtherClass = (myClass=='thumbUp') ? 'thumbDn' : 'thumbUp';
	otherObj = document.getElementsByClassName(theOtherClass)[0];

	fdbackSpan = document.getElementById('fdback');
	if (fdbackSpan) {
		fdbackSpan.className = 'on';
		fdbackSpan.style.color = (myClass=='thumbUp') ? '#006600' : '#cc0000';
		theMsg = aObj.title;
		delButton = fdbackSpan.getElementsByTagName('img')[0];
		fdbackSpan.innerHTML = theMsg + ' &nbsp;';
		fdbackSpan.appendChild(delButton); // append the "delete" button at the end
		fdbackSpan.getElementsByTagName('img')[0].name = (selectID!='') ? 'd'+selectID : fdbackSpan.getElementsByTagName('img')[0].name;
	}

	aObj.className = 'on ' +myClass;
	otherObj.className = theOtherClass;
}

function manageRespForInsert(myLink,XMLresponse)
{
	myRoot = (XMLresponse.firstChild.nodeName == "xml") ? XMLresponse.childNodes[1] : XMLresponse.childNodes[0];  //alert("myRoot= "+myRoot.nodeName);
	if (myRoot.getAttribute("success")==1) { // If DB query was successful...
		switchOnThumb(myLink,myRoot.getAttribute("selectID"));
	}
	else if (myRoot.getAttribute("success")==2) {
		alert('Sorry. You have already left your vote!');
	}
	else {alert("An error occurred. Please refresh this page.");}
	showHideLoading(2); //hide loading div
}

function manageRespForEdit(myTextarea,XMLresponse)
{
	myRoot = (XMLresponse.firstChild.nodeName == "xml") ? XMLresponse.childNodes[1] : XMLresponse.childNodes[0];  //alert("myRoot= "+myRoot.nodeName);
	if (myRoot.getAttribute("success")==1) // If DB query was successful...
	{
		myTD = myTextarea.parentNode.parentNode.parentNode;
		myTD.innerHTML = '<p>' +myTextarea.value + '</p>';
		myTD.appendChild(myTD.editButton);	
	}
	else {alert("An error occurred. Please refresh this page.");}
	showHideLoading(2); //hide loading div
}

/* This function is used ONLY to delete comment from POPUP window! */
function manageRespForDelete(myButton,XMLresponse)
{
	myRoot = (XMLresponse.firstChild.nodeName == "xml") ? XMLresponse.childNodes[1] : XMLresponse.childNodes[0];  //alert("myRoot= "+myRoot.nodeName);
	if (myRoot.getAttribute("success")==1) // If DB query was successful...
	{
		//Hide text
		fdbackSpan = document.getElementById('fdback');
		fdbackSpan.className='off';
		//Switch off "thumb" buttons
		if (tUp = document.getElementsByClassName('on thumbUp')[0]) {tUp.className = 'thumbUp';}
		else if (tDn = document.getElementsByClassName('on thumbDn')[0]) {tDn.className = 'thumbDn';}
	}
	else {alert("An error occurred. Please refresh this page.");}
	showHideLoading(2); //hide loading div
}
