
/**
 * Ajax.js
 *
 * Collection of Scripts to allow in page communication from browser to (struts) server
 * ie can reload part instead of full page
 *
 * How to use
 * ==========
 * 1) Call retrieveURL from the relevant event on the HTML page (e.g. onclick)
 * 2) Pass the url to contact (e.g. Struts Action) and the name of the HTML form to post
 * 3) When the server responds ...
 *		 - the script loops through the response , looking for <span id="name">newContent</span>
 * 		 - each <span> tag in the *existing* document will be replaced with newContent
 *
 * NOTE: <span id="name"> is case sensitive. Name *must* follow the first quote mark and end in a quote
 *		 Everything after the first '>' mark until </span> is considered content.
 *		 Empty Sections should be in the format <span id="name"></span>
 * CHANGES:
 * 	08/09/06 (albert) to get the actual state of checkboxes, some extra treatment has to be done in getFormAsString
 */


//global variables
var req;
var which;
/**
   * Get the contents of the URL via an Ajax call
   * url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1) 
   * nodeToOverWrite - when callback is made
   * nameOfFormToPost - which form values will be posted up to the server as part 
   *					of the request (can be null)
   */
function retrieveURL(url, nameOfFormToPost) 
{    
    //get the (form based) params to push up as part of the get request
    url = url + getFormAsString(nameOfFormToPost);    
    makeAjaxCall(url); 
}

/**
  * gets the contents of the form as a URL encoded String
  * suitable for appending to a url
  * @param formName to encode
  * @return string with encoded form values , beings with &
  */
function getFormAsString(formName) {
 	
 	//Setup the return String
    returnString = "";
 	
  	//Get the form values
    formElements = document.forms[formName].elements;
 	//loop through the array , building up the url
 	//in the form /strutsaction.do&name=value
    for (var i = formElements.length - 1; i >= 0; i = i -1) {
 		//we escape (encode) each value
 		fElVal = formElements[i].value;
 		if (formElements[i].type == "checkbox")
 		{
 			fElVal = formElements[i].checked; 			
 		}

        returnString = returnString + "&" + escape(formElements[i].name) + "=" + escape(fElVal);
    }
 	
 	//return the values
    return returnString;
}

/**
* just make the ajax call if the onkeypressed-event contains 13 (enter) as key
*/
function ajaxEnter(event, url)
{
	if (event.keyCode == 13)
	{
		makeAjaxCall(url);
	}
}

function test()
{
	alert('test');
}

function deleteMultipleAnswers(id){
	inputs = document.getElementById("deleteIndividualAnswers").getElementsByTagName("input");
	var string = "";
	for (i=0;i< inputs.length;i++) {
		var input = inputs[i];
		if (input.checked)
		{
			string += input.value+",";
		}
	}
	for (i=0;i< inputs.length;i++) {
		var input = inputs[i];
		input.checked = false;
	}
	url = "archiveanwsers.qsys?questId=" + id + "&deleteAnswerType=INDIVIDUAL&elementIds=" + string;
	makeAjaxCall(url);
}


/**
	* Do the Ajax call
*/
function makeAjaxCall(url)
{
	url += "&ajax=true";  
	resetDiv();
	//alert(url);
    if (window.XMLHttpRequest) { // Non-IE browsers
        req = new XMLHttpRequest();
        req.onreadystatechange = processStateChange;
        try {
            req.open("POST", url, true); //was get
        }
        catch (e) {
            alert("Problem Communicating with Server\n" + e);
        }
        req.send(null);
    } else {
        if (window.ActiveXObject) { // IE
            req = new ActiveXObject("Microsoft.XMLHTTP");
            if (req) {
                req.onreadystatechange = processStateChange;
                req.open("POST", url, true);
                req.send();
            }
        }       
    }   
}

/*
   * Set as the callback method for when XmlHttpRequest State Changes 
   * used by retrieveUrl
  */
function processStateChange() 
{
	//alert("processStateChange");
    if (req.readyState == 4) 
    { // Complete
        if (req.status == 200) 
        { // OK response  
        	var resStr = req.responseText;
        	//alert (resStr);
        	err = getError(resStr);
        	if (err != null && err != '')
        	{
        		addXError(err);
        	}
        	msg = getMessage(resStr)
        	//alert("msg:" + msg);
        	if (msg != null && msg != '')
        	{
        		addMessage(msg);
        	}
        	processResponseMsg(resStr); 
        	/*            
        	
        	try 
        	{
        		
        	} catch (e) {}      
        	var messages = readTagClassStringMsg(resStr);
       		addMessage(messages);
       		alert("msgs:" + messages);
       		var errors = readTagClassStringErr(resStr);
       		addErrors(errors);       		
        	alert("err:" + errors);
        	*/
        } 
        	else 
        {
            alert("Problem with server response:\n " + req.statusText);
        }
    }
}

function processResponseMsg(resStr)
{
	var ajaxMsg = getAjaxMessage(resStr);
	if (ajaxMsg == 'logo_deleted')
	{
		var logoImg = document.getElementById("logo");
		logoImg.src = "images/spacer_trans.gif";
		logoImg.width=1;
		//TODO: also hide the delete button
		var message = getFirstTagContent(resStr, "message");
		addMessage(message);
	}
}

function getError(resStr)
{
	return getFirstTagContent(resStr, "error");
}

function getMessage(resStr)
{
	return getFirstTagContent(resStr, "message");
}

function getAjaxMessage(resStr)
{
    return getFirstTagContent(resStr, "ajax_message");
}

function getFirstTagContent(resStr, tagName)
{
    tokens = resStr.split(startTag(tagName));
    if (tokens.length < 2) return "";
    msg = tokens[1];
    tokens = msg.split(endTag(tagName));
    return tokens[0];
}


function startTag(tagName)
{
	return "<" + tagName + ">";
}

function endTag(tagName)
{
	return "</" + tagName + ">";
}
/*
Read the text between the tag <i> tagName</i>
*/
function readTagClassString(textToSplit, cl)
{
	//Split the document
    returnElements = textToSplit.split("<td class=\"" + cl + "\">");
    returnElement = returnElements[1];
    //alert(returnElement);	
    var msg = returnElement.split("</td>")[0];
    //alert(msg);	
    return msg;   
}

function readTagClassStringErr(textToSplit)
{
	return  readTagClassString(textToSplit,'message_text'); 
}

function readTagClassStringMsg(textToSplit)
{
	return  readTagClassString(textToSplit,'error_text'); 
}


/*
Add an error string entry to the error div box
*/
function addXError(errorMsg)
{
	var errorDiv = document.getElementById("error_wrap");	
	var error = '<div id="errors" class="errors"><img src="images/error.png"/>&#160;<span class="error_text">' + errorMsg +  '</span></div>';		
	errorDiv.style.display = "block";
	errorDiv.innerHTML = error;	
	var msgDiv = document.getElementById("message_wrap");
	msgDiv.style.display = "none";
}

/*
Add an error string entry to the error div box
*/
function addMessage(msg)
{	
	var msgDiv = document.getElementById("message_wrap");
	var msgHtml = '<div id="messages" class="messages"><img src="images/ok.png"/>&#160;<span class="message_text">' + msg +  '</span></div>';		
	msgDiv.style.display = "block";
	msgDiv.innerHTML = msgHtml;
}

/*
Clear the message div
*/
function resetDiv()
{
	feedBackDivInv();
	var msgDiv = document.getElementById("message_wrap");
	msgDiv.innerHTML = '<span class="hidden_text"><img src="images/reminder.png"/>&#160;<font color="yellow">...sende Anfrage</font></span>';
	msgDiv.style.display = "block";	
	
}

function feedBackDivInv()
{
	var msgDiv = document.getElementById("message_wrap");
	msgDiv.style.display = "none";
	var errorDiv = document.getElementById("error_wrap");	
	errorDiv.style.display = "none";
}
