/*
 * iaapiajax.js
 * 
 * Library for the ajax based client side integration of an IA
 * - preconfigured for client side session persistence
 * 
 * Author:  Norbert Busch - norbert.busch@artificial-solutions.com
 * Version: 1.0.2
 * Date:    12.07.2007
 *
 * Changes: updateIaView()
 *          xmlrequest now without addional lib
 */

/* configurational constants */

var IA_RESTORE_FROM_SERVER = false;
var IA_LOCATION = "/_demos/cetelem/cgi-bin/cetelem.cgi";  // to be changed to the real value
var IA_COOKIE_NAME = "iadata";  // only used if IA_RESTORE_FROM_SERVER=false
var IA_NAVIGATION_KEY = "linkname";

/* global variables */

var iaSessionKeys = [];
iaSessionKeys.push("ident");
iaSessionKeys.push("userlogid");

var iaAdditionalPersistenceKeys = [];
iaAdditionalPersistenceKeys.push("botanswer");
iaAdditionalPersistenceKeys.push("image");

var iaAdditionalQueryKeys = [];
iaAdditionalQueryKeys.push("extradata");

var iaPropertyForUpdate = [];
iaPropertyForUpdate["image"] = "document.getElementById('iaimage').src";
iaPropertyForUpdate["botanswer"] = "document.getElementById('iaanswertextfield').innerHTML";

var iaData = [];

/* only used if IA_RESTORE_FROM_SERVER=false */

function setInitialIaData() {
	iaData["image"] = "/_demos/cetelem/htdocs/images/Friendly_2.gif";
	iaData["botanswer"] = "Hi,</br> can I help you?";
}

function storeIaData() {
	var persKeys = iaSessionKeys.concat(iaAdditionalPersistenceKeys);
	var ser = "";
	for (var i=0; i<persKeys.length; i++) {
		if (iaData[persKeys[i]]) {
			ser += escape(persKeys[i] + "=" + iaData[persKeys[i]]) + ";";		
		}	
	}
	document.cookie = IA_COOKIE_NAME + "=" + escape(ser) + "; path=/";
}

function restoreIaDataFromCookie() {
	var index = document.cookie.indexOf(IA_COOKIE_NAME + "=");
	if (index == -1) {
		setInitialIaData();
		return;
	}
	index = document.cookie.indexOf("=", index) + 1;
	var endstr = document.cookie.indexOf(";", index);
	if (endstr == -1) {
		endstr = document.cookie.length;
	}
	var keyValPairs = unescape(document.cookie.substring(index, endstr)).split(";");
	var key, value;
	for (var i=0; i<keyValPairs.length; i++) {
		keyValPairs[i] = unescape(keyValPairs[i]);
		if ((index = keyValPairs[i].indexOf("=")) > 0) {
			key = keyValPairs[i].substr(0, index);
			value = keyValPairs[i].slice(index + 1);
			if (key != "") {
				iaData[key] = value;
			}
		}
	}        
}
/* end - only used if IA_RESTORE_FROM_SERVER=false */

function initIa() {
	if (!IA_RESTORE_FROM_SERVER) {
		restoreIaDataFromCookie();
	}
	restoreIa();
}

function restoreIa() {
	if (!document.body) {
	  self.setTimeout("restoreIa()", 50);
	  return;
	}
	if (IA_RESTORE_FROM_SERVER) {
		receiveIaResponse();
	}
	else {
		updateIaView();
	}
}

function checkIaKeyEvent(e) {
	var keyChar;
	if (e.which) {
		keyChar = e.which;
	}
	else {
		keyChar = event.keyCode;
	}
	if (keyChar == 13) {
		reaktToIaAskEvent();
	}
}

function reaktToIaAskEvent() {
	var elem = document.getElementById('iaentryfield');
	receiveIaResponse(elem.value);
	elem.value = "";
	elem.focus();
}

if (!window.XMLHttpRequest && window.ActiveXObject) {
	window.XMLHttpRequest = function() {
	var versions = ['MSXML2.XMLHTTP.7.0', 'MSXML2.XMLHTTP.6.0',
		'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0',
		'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP',
		'Microsoft.XMLHTTP'];
	for (var i = 0; i < versions.length; i++) {
		try {
			return new ActiveXObject(versions[i]);
		} catch(e) {}
	}
		return undefined;
	}
}

function receiveIaResponse(question) {
 try {
  var buildQuery = function (quest) {
        var query = "";
        for (var i=0; i<iaSessionKeys.length; i++) {
         query += "&" + iaSessionKeys[i] + "=" + (iaData[iaSessionKeys[i]] ? escape(iaData[iaSessionKeys[i]]) : "");
        }
        if (quest) {
         var patSpace = /["\\#\$<>\[\]\^`\{\}\|~]/;
         var patDot = /!/;
         while (patSpace.test(question)) {
           question = question.replace(patSpace, " ");
         }
         while (patDot.test(question)) {
           question = question.replace(patDot, ".");
         }
         query += "&entry=" + escape(question);        
        }
        for (var i=0; i<iaAdditionalQueryKeys.length; i++) {
         query += "&" + iaAdditionalQueryKeys[i] + "=" + (iaData[iaAdditionalQueryKeys[i]] ? escape(iaData[iaAdditionalQueryKeys[i]]) : "");
        }
        if (query.length > 0) {
         query = "?" + query.slice(1);
        }
        return query;
       }
  var com = new XMLHttpRequest();
  com.open("GET", IA_LOCATION + buildQuery(question), true);
  com.onreadystatechange = function() {
         if(com.readyState == 4) {
             if (com.status == 200) {
              parseIaResponse(com.responseText);
           storeIaData();
           if (iaData[IA_NAVIGATION_KEY] && iaData[IA_NAVIGATION_KEY] != "") {
            navigateByIa(iaData[IA_NAVIGATION_KEY]);
            iaData[IA_NAVIGATION_KEY] = "";
           }
              updateIaView();
             }
             else {
                 alert("Problems getting an answer:\n" + com.statusText);
             }
         }
        };
  com.send(null);
 } catch(ex) {
 }
}



function parseIaResponse(response) {
	var trimLeadingWS = function (str) {
							var ws = /\s/;
						    while (ws.test(str.charAt(0))) {
						    	str = str.slice(1);
						    }
							return str;
						}	
	var unescapeIa = function (str) {
						var pat = /\\u003B/;
						while (pat.test(str)) {
							str = str.replace(pat, ";");
						}
						return str;
					}
	var keyValPairs = response.split(";");
	var index, key, value;
	for (var i=0; i<keyValPairs.length; i++) {
    	if ((index = keyValPairs[i].indexOf("=")) > 0) {
    		key = keyValPairs[i].substr(0, index);
    		key = trimLeadingWS(key);
    		value = keyValPairs[i].slice(index + 1);
    		if (key != "") {
    			iaData[key] = unescapeIa(value);
    		}
    	}
    }        
}

function updateIaView() {
	var escapeIa = function (str) {
						var pat = /'/;
						while (pat.test(str)) {
							str = str.replace(pat, "&#039;");
						}
						return str;
					}
	for (var key in iaData) {
		if (iaPropertyForUpdate[key]) {
			try {
				eval(iaPropertyForUpdate[key] + "='" + escapeIa(iaData[key]) + "'");
			} catch(e) {}
		}
	}        
}


function navigateByIa(linkName) {
	if (linkName != "") {
		var url = "";
		switch (linkName) {
		case "example1":
			url = "/this/that.htm";
			break;
		case "example2":
			url = "/that/this.htm";
			break;
		}
		if (url != "") {
			self.location.href = url;		
		}
	}
}

initIa();


// form integration api

function sendEventToIa(sender, event, value) {
	var formName = (sender.form ? sender.form.name : sender.name);
	var entry = '_send_event ' + formName;
	if (formName != sender.name) {
		entry += ' ' + sender.name;
	}    
	entry += ' ' + event.type;
	if (value) {
		entry += ' ' + value;
	}
	receiveIaResponse(entry);
}




