var req;
var deleteIfFollower = false;
var paramName = new Array();
var paramValue = new Array();
var paramTitle = new Array();
var paramRequired = new Array();
var paramChecker = new Array();
var paramType = new Array();
var tabIndex;
var urlParameters;
var processName;
var formNodesToRetrieve = ['input', 'select', 'textarea'];
var idResult;



// this function should more be called "sendData", but all the web pages would have to be changed to respect the name ...
// It will have to be done in the next future.
function sendFormData(thisId, _processName, _idResult) {
	
	// the formId must always starts with "form" when it is a form
	// when a form must be duplicated, the form model must have the id "form0"
	// when it is a Config sending, the id must always start with "Display", case important !

	// shows the loader if there is one
	displaySubLoader();
	displaySubLoaderCentered();
	
	var configValue = _processName;	
	
	if (thisId != null && thisId.length >= 7 && thisId.substring(0,7) == "Display"){
		sendConfigData(thisId, configValue);
	}
	else{
		// if it is a follower, asks the customer if the past results must be deleted or not
		if (_processName == "Follower" && followerSetupHasChanged == "true"){
			// reinit flag
			followerSetupHasChanged = false;
			// display message
			/*
			displayNodeMessage("idConfirmFollower" , "Vous êtes sur le point de changer les paramètres de recherche d'un de vos agents. Souhaitez-vous conserver " +
					"l'historique de vos résultats ? <br></br><br></br>" +
					"<a class=\"popupButton\" style=\"margin-left:3px;margin-right:3px;\" href=\"javascript:deleteIfFollower=false; javascript:sendFormContent('" + thisId + "','" +  _processName + "','" +  _idResult + "');hide('displayConfirm');displayConfirm();\">Conserver</a>" +
					"<a class=\"popupButton\" style=\"margin-left:3px;margin-right:3px;\" href=\"javascript:deleteIfFollower=true; javascript:sendFormContent('" + thisId + "','" +  _processName + "','" +  _idResult + "');hide('displayConfirm');displayConfirm();\">Effacer</a>" +
					"<a class=\"popupButton\" style=\"margin-left:3px;margin-right:3px;\" href=\"javascript:closePopup('idConfirmFollower');window.location.reload();\">Annuler</a>");*/
			
			displayNodeMessage("idConfirmFollower" , "Vous venez de changer votre agent de recherche. " +
					"Toutes vos anciens résultats seront remplacés par les résultats trouvés pour ce nouvel agent." +
					"<br /><br />" +
					"<a class=\"popupButton\" style=\"margin-left:60px;margin-right:3px;\" href=\"javascript:deleteIfFollower=true; javascript:sendFormContent('" + thisId + "','" +  _processName + "','" +  _idResult + "');hide('displayConfirm');displayConfirm();\">OK</a>" +
					"<a class=\"popupButton\" style=\"margin-left:10px;margin-right:3px;\" href=\"javascript:closePopup('idConfirmFollower');window.location.reload();\">Annuler</a>");
			
		}
		else{
			sendFormContent(thisId, _processName, _idResult);
		}
		
	}
	
}
function displayConfirm(){
 	displayMessage(
	"Merci. La mise à jour des résultats et des scores de réputation peut prendre plusieurs minutes. Merci de votre compréhension." +
		"<br></br><br></br><u><a href=\"./account\">Revenir à la page d'accueil</a></u>"  
	);
}


function sendConfigData(thisId, _configValue){
	
	   var url = "GetForm" + "?configId=" + thisId + "&configValue=" + _configValue + "&processName=SetConfig&sess=" + getCookie("JSESSIONID")
	   	+ "&activeFollowerId=" + activeFollowerId;
	   	   
	   send(url, callbackForm, "POST");
	
}





function sendFormContent(formId, _processName, _idResult){
	
	
	processName = _processName;
	idResult = _idResult;
	tabIndex = 0;

	if (formId != null){
		
		formNr = parseInt(formId.substring(formId.indexOf("m") + 1 , formId.length));	

		for (var j = 0 ; j < formNodesToRetrieve.length ; j++) {
			 
			var myForm = document.getElementById(formId);
			var nodesToCheck = myForm.getElementsByTagName(formNodesToRetrieve[j]);
			
			for (var i = 0 ; i < nodesToCheck.length ; i++){											
				
				if ( ! (nodesToCheck[i].id == null || nodesToCheck[i].id == "")) {
					paramName[tabIndex] = nodesToCheck[i].id ;	
			
					if (isNumber(formNr) == true){
						paramValue[tabIndex] = document.getElementsByName(paramName[tabIndex])[formNr].value;
					}
					else {
						paramValue[tabIndex] = document.getElementById(paramName[tabIndex]).value;
					}
					
					
					paramTitle[tabIndex] = nodesToCheck[i].getAttribute("title");
					paramRequired[tabIndex] = nodesToCheck[i].getAttribute("required");
					paramChecker[tabIndex] = nodesToCheck[i].getAttribute("checker");
					paramType[tabIndex] = nodesToCheck[i].getAttribute("type");
					//if (paramRequired[tabIndex] == null) paramRequired[tabIndex] = "false";
					if (paramRequired[tabIndex] == null) paramRequired[tabIndex] = "0";
					
					// checks if it is a checkbox
					if (paramType[tabIndex] != null && paramType[tabIndex].toString().toLowerCase() == "checkbox"){
						if (nodesToCheck[i].checked == true){						
							//paramValue[tabIndex]=true;
							paramValue[tabIndex]="1";
						}
						else{						
							//paramValue[tabIndex]=false;
							paramValue[tabIndex]="0";
						}
					};
				
	
					// manages the case for input fields that are hidden
					// if it is hidden, it is not required
					if ( document.getElementById(paramName[tabIndex]).style.display == "none"){
						//paramRequired[tabIndex] = "false"; 
						paramRequired[tabIndex] = "0";
					}
					
					
					// checks if it is radio
					if (paramType[tabIndex] != null && paramType[tabIndex].toString().toLowerCase() == "radio"){
						if (nodesToCheck[i].checked == true){						
							paramName[tabIndex] = nodesToCheck[i].name;
							paramValue[tabIndex] = nodesToCheck[i].value;
						}
					};
	
				tabIndex ++ ;
				}
				
			}
		
		}
	}
	
	
	// checks if there is a customer cookie with his login
	var userLogin = getCookie("JSESSIONID");
   
   
   // sets the url arguments with the required fields   
   urlParameters = "";
   if (activeFollowerId == undefined || activeFollowerId == null) activeFollowerId="";
   
   for (var i = 0; i < paramValue.length ; i++){
	   
	   // replaces null values by "", to limit space used
	   if (paramValue[i] == "null" || paramValue[i] == null) paramValue[i] = "";
	   if (paramRequired[i] == "null" || paramRequired[i] == null) paramRequired[i] = "";
	   if (paramTitle[i] == "null" || paramTitle[i] == null) paramTitle[i] = "";
	   if (paramChecker[i] == "null" || paramChecker[i] == null) paramChecker[i] = "";
	   
	   // replaces true values by 1, to limit space used
	   if (paramValue[i] == "true" || paramValue[i] == true) paramValue[i] = "1";
	   if (paramRequired[i] == "true" || paramRequired[i] == true) paramRequired[i] = "1";
	   if (paramTitle[i] == "true" || paramTitle[i] == true ) paramTitle[i] = "1";
	   if (paramChecker[i] == "true" || paramChecker[i] == true) paramChecker[i] = "1";
	   
	   // replaces false values by 0, to limit space used
	   if (paramValue[i] == "false" || paramValue[i] == false) paramValue[i] = "0";
	   if (paramRequired[i] == "false" || paramRequired[i] == false) paramRequired[i] = "0";
	   if (paramTitle[i] == "false" || paramTitle[i] == false ) paramTitle[i] = "0";
	   if (paramChecker[i] == "false" || paramChecker[i] == false) paramChecker[i] = "0";
	   
	   
	   urlParameters = urlParameters + "&" + paramName[i] + "=" +  escape(paramValue[i]) + "&rrr" + paramName[i] + "="
	   	+ encodeURIComponent(paramRequired[i]) + "&ttt" + paramName[i] + "=" + encodeURIComponent(paramTitle[i])
	   	+ "&ccc" + paramName[i] + "=" + encodeURIComponent(paramChecker[i]) ;
	   
	   //if (i < paramValue.length -1) urlParameters = urlParameters + "&";		   
   }
   
   // adds unique values
   urlParameters = urlParameters + "&activeFollowerId=" + activeFollowerId + "&rrractiveFollowerId=0&formId=" + formId; 
   
   
   // sends the url
   var url = "GetForm" + "?" + urlParameters + "&processName=" + processName + "&rrrprocessName=0&rrruserLogin=0&userLogin=" + getCookie("JSESSIONID") + "&idResult=" + idResult + "&deleteIfFollower=" + deleteIfFollower;
   
   send(url, callbackForm, "POST");
   
}
   /*
 function sendit(_url, _callbackForm, _method){  
   
   if (typeof XMLHttpRequest != "undefined") {
       it_req = new XMLHttpRequest();       
   } 
   else if (window.ActiveXObject) {
      // req = new ActiveXObject("Microsoft.XMLHTTP");
	   
	   
	   if (window.ActiveXObject) { // C'est Internet explorer < IE7
			try { it_req = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e) {
				try {
					it_req = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(e) {
					it_req = null;
				}
			}
		}

	   if (it_req == null) alert ("req is null !");
	   
	   
   }
   
   alert(_url.length);
   
   it_req.open("POST", _url, true);
   it_req.setRequestHeader("Content-Type", "text/plain;charset=ISO-8859-1");
   it_req.onreadystatechange = _callbackForm;
   it_req.send(null);

}
*/

function callbackForm() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            parseJsonMessage();
        }
    }
}


function parseJsonMessage() {		
	
	var responseHeader = req.getResponseHeader("Content-Type");
	if (responseHeader != "application/csv") {
	
		myJson = req.responseText;
		
		if (myJson != "" && myJson != "{}" && myJson != "undefined" && myJson != undefined) {
			myJsonObj = jsonParse(myJson);	
			
			//checks if it is a redirection
			if (isRedirection(myJsonObj)) redirect(myJsonObj);
			// can also be a chart generation
			else if (myJsonObj.positivemessage.substring(0, 15) == "chartsgenerated") {
				reloadCharts(activeFollowerId);
				myJsonObj.positivemessage = myJsonObj.positivemessage.substring(16, myJsonObj.positivemessage.length);
				if (myJsonObj.positivemessage.length > 3) 
					//displayMessage(myJsonObj.positivemessage);
					displayAvertCenter(myJsonObj.positivemessage);
			}
			else if (myJsonObj.positivemessage.substring(0, 8) == "tonality") {
				var tableau = myJsonObj.positivemessage.split(":");
				var tonalityValue =  tableau[2];											
				removeAllChilds("testAnimation");
				// get jauge
				getJaugeHtml(tonalityValue,'indexjauge', true);
				// displays customed part of the help
				openCustomedJaugeHelp(tonalityValue);
				//
				commentTonality(tableau);
				//
				displayIndexComments(myJsonObj.listOfPositive, myJsonObj.listOfNegative, tonalityValue, myJsonObj.browserRequest);
			}
			else if (myJsonObj.positivemessage.substring(0, 18) == "maxTonalityReached") {
				maxTestsReached = true;		
				var tableauTon = myJsonObj.positivemessage.split(":");
				//displayMessage(tableauTon[1]);
				displayAvertCenter(tableauTon[1]);
			}			
			// can also be a basic message
			else if (myJsonObj.positivemessage != null && myJsonObj.positivemessage != undefined && myJsonObj.positivemessage.length > 3){			
					if ( myJsonObj.positivemessage.substring(0, 28) == "Votre message a correctement"){
						displayMsgCenter(myJsonObj.positivemessage);
						fadeForm();
					}
					else{
						//displayMessage(myJsonObj.positivemessage);
						//displayAvertCenter(myJsonObj.positivemessage);;
						displayMsgCenter(myJsonObj.positivemessage);
					}
			//}
			
			// if it is not, manages fields missing		
			//else {
				displayTitlesMissing(myJsonObj);	
				colorFieldsMissing(myJsonObj);
				//displayOtherMessage(myJsonObj);
			}
		}
		
		if (needToUpdateCorrectResults != undefined && needToUpdateCorrectResults == true){
			
			updateResults('correctResults','1');
			needToUpdateCorrectResults = false;
		}
		if (needToUpdateIncorrectResults != undefined && needToUpdateIncorrectResults == true){
			updateResults('incorrectResults','1');
			needToUpdateIncorrectResults = false;
		}
		if (needToUpdateDeletionList != undefined && needToUpdateDeletionList == true){
			displayUserList('deletionList', currentActiveList);	;
			needToUpdateDeletionList = false;
		}
		if (needToUpdateRegularList != undefined && needToUpdateRegularList == true){
			displayUserList('regularList', currentActiveList);	;
			needToUpdateRegularList = false;
		}
		if (needToReloadListPage != undefined && needToReloadListPage == true){
			reloadPage();
			needToReloadListPage = false;
		}		
	
	}
	
}


function displayTitlesMissing(_myJsonObj) {
    
	var titlesMissing = new Array();
	titlesMissing = _myJsonObj.titlesMissing;	
	
	if (titlesMissing != undefined && titlesMissing.length > 0){

		//var formResultNode = document.getElementById("formResult");
		idResult = "idAnyMessage";
		var formResultNode = document.getElementById(idResult);
		removeAllChildNodes(formResultNode);
		
		var titleText = document.createTextNode("Les champs suivants sont obligatoires:");
		formResultNode.appendChild(titleText);
	
	
		var tableElement = document.createElement('table');
		tableElement.setAttribute("border", "1");
		var ulElement = document.createElement('ul');
		tableElement.appendChild(ulElement);
	
		for (var i = 0 ; i < titlesMissing.length ; i++){
					
			var liElement = document.createElement('li');
			var liText = document.createTextNode(titlesMissing[i]);
			
			liElement.appendChild(liText);		
			ulElement.appendChild(liElement);
			
		}		

		formResultNode.appendChild(ulElement);
	}
	
}


function colorFieldsMissing(_myJsonObj){
	
	var idsMissing = new Array();
	idsMissing = _myJsonObj.idsMissing;
	
	
	if (idsMissing != undefined && idsMissing.length > 0 ){
		for (var i = 0 ; i < idsMissing.length ; i++){

			if (document.getElementById(idsMissing[i]) != null){
				
		    	var currentClass = document.getElementById(idsMissing[i]).className;
		    	
		    	if (currentClass.substring(currentClass.length, currentClass.length - 6) == "Person"){
		    		document.getElementById(idsMissing[i]).className = "wrongPerson";
		    	}
		    	else if (currentClass.substring(currentClass.length, currentClass.length - 7) == "Company"){
		    		document.getElementById(idsMissing[i]).className = "wrongCompany";
		    	} 
		    	else{
		    		document.getElementById(idsMissing[i]).className = "wrong";
		    	}
			}
			
		}
	}
	
}


function displayOtherMessage(_myJsonObj) {
		
	idResult = "idAnyMessage";
	
	if (_myJsonObj.positivemessage){

		//var formResultNode = document.getElementById("formResult");
		var formResultNode = document.getElementById(idResult);
		
		var thisText = document.createTextNode(_myJsonObj.positivemessage);							
		formResultNode.appendChild(thisText);
			
	}		
		
}
	









