///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Anboto IntelligentChat Core v1.0 - 19/Ene/2011
// (c) Anboto Group SL - www.anbotogroup.com
// PR+IMQ
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////// INIT objImq ///////////////////////////////////////////////////////////////////////////////////
function objImq (lang, host, method) { 
   this.ref = "";
   this.lang = lang || 1;
   this.method = method || "ajax_json";
   this.host = host || "service.php";

   this.printResponse = function(text) {
      printResponse(text);
   }
   
   this.getResponse = function(params) {
	  switch(this.method) {
	    case "json":
		   this.getResponse_JSONP(params);
		   break;
		case "ajax_xml":
		   this.getResponse_AJAX_XML(params);
		   break;
		case "ajax_json":
		   this.getResponse_AJAX_JSON(params);
		   break;
		case "html5":
		   break;
		default:
		   this.getResponse_JSONP(params);
	  }
   }

   //Makes the JSONP call
   this.getResponse_JSONP = function(question) {   
      
   }
   
   //Makes the ajax call and loads the returned json
   this.getResponse_AJAX_JSON = function(question) {  
	  var thisobject = this;
	  var uri = this.host
	     +"?ref="+this.ref
	     +"&lang="+this.lang
	     +"&question="+encodeURIComponent(question)
	  var ajax = this.createAjax();
	  ajax.open('POST', uri, true);
	  //ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
     ajax.send(null);
	  ajax.onreadystatechange = function() {
	     if (ajax.readyState==1) {
		  //
	     } else if ((ajax.readyState==4) && (ajax.status==200)) {
			var json = eval('('+ ajax.responseText +')');
			thisobject.loadJSON(json); //aqui this se refiere al ajax
         }
	  }
	  
	  if (debug == 1) {
	     printDebugPetition(uri);
      }
   }
   
   //Create the AJAX object depending of the navigator
   this.createAjax = function() {
      var objectAjax = false;
      try {
        //Distinct to internet explorer
        objectAjax = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            //For explorer
            objectAjax = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (E) {
            objectAjax = false;
         }
      }
      if (!objectAjax && typeof XMLHttpRequest != 'undefined') {
         objectAjax = new XMLHttpRequest();
      }
      return objectAjax;
   }

   //Load the returned JSON values
   this.loadJSON = function (obj) {
      txtQuestion.disabled = "";
	  txtQuestion.focus();
	  if (debug == 1) {
		 printDebugXml(obj);
      }  
      if(!isSet(obj.response)) { //Invalid response
         return; 
      }
   
      if (isSet(obj.response.context)) {    
         var context = obj.response.context;
		 if (isSet(context.ref)) {
		    this.ref = context.ref;
          saveVar("ref", this.ref);
       }
		 if (isSet(context.responseType))
		    this.responseType = context.responseType;
	  }

      //if(isSet(obj.response.fields) && isSet(obj.response.fields.question)) { 
      if(isSet(obj.response.fields)) {
         var fields = obj.response.fields;
         this.loadFields(fields);
      }
   }
   
   //Load answers from server
   this.loadFields = function(fields) {
      var responseText = "";
	  
	  if (debug == 1) {
         printDebugFormImq(fields.form);
	  }
	  
	  if(isSet(fields.form) && this.responseType == 'FC') { //form
	     responseText += fields.form.text2add;
		  this.loadForm(fields.form);
        if (debug == 1) {
            printDebugFormImq(fields.form);
	     }		 
	  }
	  
	  if(isSet(fields.question)) {
         responseText += this.loadQuestions(fields.question);         
      }
		 
      if (responseText != '') {
	     this.printResponse(responseText);
      }
   }

   //Loads the form fields
   this.loadForm = function (form) {
      updateFormularioBuscador(form); //External function
   }
   
   //Return the answers from server
   this.loadQuestions = function (questions, separator2) {
      var sep = separator2 || "<br /><br />";
      var answer = "";
      if (isArray(questions)) { // 
   	     for (i=0;i<questions.length;i++) {
            answer += this.loadQuestion(questions[i]) + sep; 
         }
      } else { //there is only one question  : is not an array
         answer = this.loadQuestion(questions);
      }
      return answer;
   }
   
   //Return a response from server
   this.loadQuestion = function (question, separator1, separator2, link) {
      var answer = '';
      if (isSet(question.emotion))     
	      this.updateEmotion(question.emotion);
	   if (isSet(question.resp) && this.responseType != 'FC')        
         answer += question.resp;
      if (isSet(question.links) && this.responseType != 'FC') 
         answer += this.loadLinks(question.links);
      if (isSet(question.connections)) 
         answer += this.loadConnections(question.connections);	  
      return answer;
   }   
   
   this.loadLinks = function (links) {
      var html = ''; 
      if (links == "")
         return '';
         
      links = links.link;      
      if (!isArray(links)) { 
         var tempLink = links;
         var links = new Array();
         links.push(tempLink);
      }
	   for (var i=0;i<links.length;i++) {
         html += '<br />- <a href="#" onclick=\'openPopup(\"'+links[i].target+'\");\' >'+links[i].caption+'</a>'; 
      }      
      return html;
   }   
   
   //Returns added links to related topics
   this.loadConnections = function (connections, separator1, separator2, link) {
     var sep1 = separator1 || "<br />";
	  var sep2 = separator2 || "<br /><br />";
	  
	  var html = '';
	  if (isSet(connections.header) && connections.header != "") {
		 html = sep2 + connections.header;
	  }
	  if (isSet(connections.connection)) {
	     connections = connections.connection;
		 if (isArray(connections)) { // 
	        for (var i=0;i<connections.length;i++) {
               html += sep1 + this.loadConnection(connections[i]); 
            }
         } else { // solo hay una pregunta : no es un array
             html += sep1 + this.loadConnection(connections); 
         }
	  }
	  return html;
   }
   
   //Returns added shorcuts links to related topics
   this.loadConnection = function (connection, link) {
      var link = link || "- <a href=\"#\" class=\"ANB_link\" onclick=\"sendQuestion('%RELATEDQUESTION%'); return false\">%RELATEDQUESTION%</a>";
	  return link.replace(/%RELATEDQUESTION%/g, connection); 
   }
      
   this.updateEmotion = function (emotion) { 
      updateVideoEmotion(emotion); //External function
   }   
}
//////////// END objImq //////////////////////////////////////////////////////////////////////////////////////////////

