///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Virtual Assistant v1.0 - 24/Jan/2011
// (c) Anboto Group SL - www.anbotogroup.com
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

///Variables globales//////

//config
var debug = false;
var trace = true;
var saveMethod = "cookie";
var videoSyncro = false;

var anbFolder = '../Anboto_VirtualAssistant/';
var host = anbFolder+"service.php";
var search_page = "resultados_guia_medica.php";

var flashvars = {
   playlist: anbFolder+"player/playlist.xml",
   inactive: "60000",
   width: "385",
   height: "248",
   standbyTransitionMode: "normal",
   yoyoTransitionAlpha: ".5",
   // returnVideoCompleted: true   
   showIntro: "false",
   startVideo: ""
};
var params = {
   menu: false, 
   bgcolor: "#ffffff",
   // allowscriptaccess: "always",
   allowfullscreen: "false",
   quality: "high",
   wmode: "transparent"
};

if (!(window['console'] !== undefined && console && trace)) {
   trace = false;
}

activeObject = new objImq(langPack.dblang, host);
activeObject.intro = langPack.intro;

divChat = mapElement("ANB_chatwindow");
txtQuestion = mapElement("ANB_question");
divEmotion = mapElement("ANB_swf");
divPopup = mapElement("ANB_popup");
divPopupContent = mapElement("ANB_popup_content");


//try cookies as saving method
if (saveMethod == "cookie" && cookiesEnabled()) {
   saveMethod = "cookie";
} else {
   saveMethod = "session";
}

window.onload = function () {
   loadVisibility();
   //if (trace) console.log('flashvars.showIntro: ' + flashvars.showIntro);
   swfobject.embedSWF(anbFolder+"player/anboto_player.swf", "ANB_swf", "385", "248", "10", anbFolder+"player/expressInstall.swf", flashvars, params);

   if (debug) {
      activateDebugDivs();
   }
}

window.onunload = function () {
   if (mapElement('ANB_content').style.display == 'none') {
      saveVar("visibility", 0);
   } else {
      saveVar("visibility", 1);
   }
}

function clean(question) {
   if (question.value == langPack.type_) {
      question.value = "";
   }
}

function openPopup(url) {
   var ajax = activeObject.createAjax();
	ajax.open('GET', anbFolder+url, false);   
   ajax.send();
   divPopup.style.display = 'block';     
   if (ajax.responseText) {
      divPopupContent.innerHTML = ajax.responseText;             
   } else {
      divPopupContent.innerHTML = 'Error...';
   }    
}
function closePopup() {
   divPopup.style.display = 'none';   
   divPopupContent.innerHTML = ""; 
}

function clearChatWindow() {
   divChat.innerHTML = '<p>'+langPack.intro+'</p>';
   delVar("visibility");
}

//Pinta la pregunta del usuario
function printQuestion(question) {
   var html = "<h3>"+ ucfirst(question) +"</h3>";
   saveDialog(html);
   divChat.innerHTML += html;
   divChat.scrollTop = divChat.scrollHeight; //mueve el scroll abajo
   txtQuestion.value = ""; //limpia el campo de la pregunta
}

//Pinta la respuesta del servidor
function printResponse(answer) {
   if (videoSyncro) {
      answer = answer.replace(new RegExp('\\n','g'),'').replace(new RegExp('\\r','g'),'');
      setTimeout('printDelayedResponse("'+ answer +'")', delay*1000);
      delay = 0;
   } else {
      printDelayedResponse(answer);
   }
} //truco para sincronizar la repsuesta
function printDelayedResponse(answer) {
   var html = "<p>"+ answer +"</p>";
   saveDialog(html);
   divChat.innerHTML += html;
   divChat.scrollTop = divChat.scrollHeight; //mueve el scroll abajo
   if (divChat.childNodes[divChat.childNodes.length] > 1) {
      divChat.childNodes[divChat.childNodes.length-2].scrollIntoView(true);
   }
   if (txtQuestion) {
      txtQuestion.focus();
   }
}

//Envia una nueva pregunta. Para los enlaces relacionados
function sendQuestion(question) {
   if (question == "" || question == langPack.type_) {
	  txtQuestion.value = "";
     return false;
   }
   printQuestion(question);
   activeObject.getResponse(question);
   txtQuestion.disabled = "disabled";
   setTimeout('mapElement("ANB_question").disabled = "";', 10000);
}

function updateVideoEmotion(emotion) {
   sendVideoToAS(emotion.toLowerCase());
   if (trace) console.log("emotion: "+emotion.toLowerCase());
}

function updateFormularioBuscador(form) {
   //saveFormSession(form);
   loadFormPage(form);
}

//VISIBILITY
function loadVisibility() {
   //if (trace) console.log('flashvars.showIntro: ' + flashvars.showIntro);
	var visibility = loadVar("visibility");   
   if (visibility == "1") {      
      changeVisibility();
      loadDialog();
      //loadForm();
   } else {
      changeVisibility("hide");//hide & reset
      activeObject.ref = "";
      delVar("dialog");
      delVar("form");
      delVar("visibility");
      delVar("ref");
      delVar("emotion");
      clearChatWindow();
   }
}


function changeVisibility(pre) {
   var divModule = mapElement('ANB_module');
   var divContent = mapElement('ANB_content');
   var divOnOffText = mapElement('ANB_onoff_text');
   //var divSwf = mapElement('ANB_swf');
   if (divContent.style.display == 'block' || pre == "hide") { //Hide
	   divContent.style.display = 'none';
	   //divSwf.style.display = 'none';	  
	   divOnOffText.innerHTML = langPack.show_+' (+)';
	   saveVar("visibility", 0);
   } else { //Show
	   divContent.style.display = 'block';
	   //divSwf.style.display = 'block';
	   divOnOffText.innerHTML = langPack.hide_+' (-)';
	   saveVar("visibility", 1);
      //txtQuestion.focus();
      //sendVideoToAS("in1");
      var page = String(document.location).split("/").pop().split("?").shift();
      activeObject.ref = loadVar("ref");
      if (!activeObject.ref > 0) { //primer acceso
         if (trace) console.log('init: ' + "saludo");
         //sendVideoToAS("saludo");
         flashvars.showIntro = "true";
         //saveVar("visibility", 1);
      } else if (page == search_page) {
         if (trace) console.log('init: ' + "contento");
         flashvars.startVideo = "contento";
         //sendVideoToAS("contento");
      } else { //standby
         if (trace) console.log('init: ' + "standby");
         //sendVideoToAS("standby");
      }      
   }
}

//DIALOG
function loadDialog() {
	var html = unescape(loadVar("dialog"));
	var pat = /<h3>/;//Si no hay ninguna pregunta no guarda el saludo
   if ((html == '' && divChat.innerHTML == '')) {// || !pat.test(html)) { //if is the first access
      //delVar("dialog");
      printResponse(activeObject.intro);
   } else {
      if (html != '')
         divChat.innerHTML = html;
      divChat.scrollTop = divChat.scrollHeight;
      if (divChat.childNodes[divChat.childNodes.length] > 1) {
         divChat.childNodes[divChat.childNodes.length-2].scrollIntoView(true);
      }
   }
}
function saveDialog(html) {
   if (html.substring(0,4) == "<h3>") { //resp
      delVar("dialog");
      var dialog = "";
   } else {
      var dialog = loadVar("dialog");
   }
   dialog += escape(html);
   saveVar("dialog", dialog);
}

function loadFormPage(json) {
   var frm = document.createElement("FORM");
   frm.method = "post";
   frm.action = search_page;//"http://www.imq.es/imq/es/resultados_guia_medica.php";
   frm.id = "ANB_search";

   na = document.createElement("INPUT");
   na.name = "nombre_gm";
   na.value = json.name;
   na.type = "hidden";
   frm.appendChild(na);
   
   sn = document.createElement("INPUT");
   sn.name = "apellidos_gm"; //or medical center
   sn.value = json.sn;
   sn.type = "hidden";
   if (json.sn == "")
      sn.value = json.center;
   frm.appendChild(sn);
   
   sp = document.createElement("INPUT");
   sp.name = "gcuadro";
   sp.value = json.speciality.split("|").shift();
   sp.type = "hidden";
   if (json.speciality.split("|").shift() == "")
      sp.value = "0"; //default
   //sp.value = keyArray(specialities, json.speciality);
   frm.appendChild(sp);
   
   ho = document.createElement("INPUT");
   ho.name = "rbHorario";
   ho.value = json.hours;
   ho.type = "hidden";
   if (json.hours == "")
      ho.value = "all"; //default
   frm.appendChild(ho);
   
   tw = document.createElement("INPUT");
   tw.name = "localidad";
   tw.value = json.town.toLowerCase();
   tw.type = "hidden";
   frm.appendChild(tw);
   
   pr = document.createElement("INPUT");
   pr.name = "gprovincia";
   pr.value = json.province.toUpperCase();
   if (json.province == "")
      pr.value = "0"; //default
   pr.type = "hidden";
   frm.appendChild(pr);
   
   si = document.createElement("INPUT");
   si.name = "cmbHorasDe";
   si.value = "";
   si.type = "hidden";
   frm.appendChild(si);
   
   un = document.createElement("INPUT");
   un.name = "cmbHorasA";
   un.value = "";
   un.type = "hidden";
   frm.appendChild(un);
   
   mu = document.createElement("INPUT");
   mu.name = "gpartmutua";
   if (json.isMutualUser == "1")
      mu.value = "mutua";
   else
      mu.value = "part";
   mu.type = "hidden";
   frm.appendChild(mu);
   
   document.body.appendChild(frm);
   document.forms['ANB_search'].submit();
}

///////////////////////////////////////////////////////
// SESSION VARS
///////////////////////////////////////////////////////
   function loadVar (name, method) {	
      method = method || saveMethod;
      var value;
      if (method == "session") {
         var file = 'Anboto_VirtualAssistant/session'+ ucFirst(name) +'.php';
         value = loadSession(name, file);
      } else { //cookie
         value = loadCookie(name);
      }
      if (trace) console.log("Loaded ("+method+"): "+name+" = "+value);
      return value;
   }
   function saveVar (name, value, method) {
      method = method || saveMethod;
      if (method == "session") {
         var file = 'Anboto_VirtualAssistant/session'+ ucFirst(name) +'.php';
         saveSession(name, value, file);
      } else { //cookie
         saveCookie(name, value);
      }
      if (trace) console.log("Saved ("+method+"): "+name+" = "+value);
   }
   function delVar (name, method) {
      method = method || saveMethod;
      if (method == "session") {
         var file = 'Anboto_VirtualAssistant/session'+ ucFirst(name) +'.php?reset=1';
         delSession(name, file);
      } else { //cookie
         delCookie(name);
      }
      if (trace) console.warn("Deleted ("+method+"): "+name);
   }
   //By session
   function loadSession (name, file) {   
      var ajax = createAjax();
      ajax.open('GET', file, false);//SYNC
      ajax.send();
      return eval('('+ ajax.responseText +')');
   }
   function saveSession (name, value, file) {
      var ajax = createAjax();
      ajax.open('GET', file +'?v='+ value , true);
      ajax.send();  
   }
    function delSession (name, file) {
      var ajax = createAjax();
      ajax.open('GET', file +'?r=1', true);
      ajax.send();  
   }
   //By cookie
   function loadCookie (name) {
      var i,x,y;
      var ARRcookies = document.cookie.split(";");
      for (i=0;i<ARRcookies.length;i++) {
         x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
         y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
         x = x.replace(/^\s+|\s+$/g,"");
         if (x == "ANB_" + name) {
            return unescape(y);
         }
      }
      return "";
   }
   function saveCookie (name, value) {
      delCookie(name);
      document.cookie = "ANB_" + name + "=" + escape(value) + ";";
   }
   function delCookie (name) {
      document.cookie = " ANB_" + name + "=;expires=Thu, 01-Jan-70 00:00:01 GMT;";
   }

/////////////////////////////////////////////////////////////////////////////////////////////////////
// System functions
/////////////////////////////////////////////////////////////////////////////////////////////////////
function cookiesEnabled() {
	var cookieEnabled = (navigator.cookieEnabled) ? true : false;
	if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
	{ 
		document.cookie = "testcookie";
		cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
	}
	return (cookieEnabled);
}

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

function inArray(array, elemento) {
   for(var i=0;i<array.length;i++) {
      if (array[i] == elemento)
         return true;
   }
   return false;
}

function keyArray(array, element) {
   for(i in array) {
      if (array[i].toUpperCase() == element.toUpperCase())
         return i;
   }
  //return -1;
  return 0;
}

function isObject(obj) {
   return obj && typeof obj == "object";
}

function isSet(obj) {
   if (typeof obj == "undefined") 
	   return false;
   else
	   return true;
}

String.prototype.ucFirst = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

function ucfirst (str) {
   var f = str.charAt(0).toUpperCase();
   return f + str.substr(1);
}

function clone(obj){
   if(obj == null || typeof(obj) != 'object')
      return obj;

   var temp = obj.constructor(); // changed

   for(var key in obj)
      temp[key] = clone(obj[key]);
   return temp;
}


function mapElement(id) {
   return document.getElementById(id);
}

//Flash player functions
function getFlashMovie(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  return (isIE) ? window[movieName] : document[movieName];
}

function sendVideoToAS(id) {//alert("a");
   try {
      getFlashMovie("ANB_swf").jsChargeVideo(id);
      if (trace) console.log('videoid: ' + id);
   } catch(e) {
      if (trace) console.log('lag');
      setTimeout("sendVideoToAS('"+id+"')" , 500);
   }
}

function videoCompleted(type) {
  if (trace) console.log('videoCompleted::type: ' + type);
}

