// [di_core.js]

var currentVDA = null;

VDA = Class.create({
    /**
     * Initialize the VDA instance.
     * @param {String} divId Identifier of the <div> of the VDA.
     */
	initialize: function(divId) {
		this.divId = divId;
		currentVDA = this;
	}
});




// [di_commsmanager_cda.js]

VDA.addMethods({
	
	requestCallback : null,
	
	sendBasicRequest : function(parameters, callback) {
		var url = this.serverUrl + "?requestdate=" +new Date().getTime()+"&"+ this.toQueryString(parameters);
		this.requestCallback = callback;
		this.dhtmlLoadScript(url, "uploadScript", true);
	},
	
    dhtmlLoadScript : function(url, id, replaceOld) {
		var old = $(id);
		if (old != null) {
			if(replaceOld) {
				$(id).remove();
			} else {
				return false;
			}
		}
		$$("head")[0].insert({bottom: new Element('script', {"id":id,"type":"text/javascript","src":url})});
		return true;
	}
	

	
	
});

/** 
* The function called from the CALLBACK template/jsp. 
*
* This uses variable currentVDA, defined outside of VDA object, which makes it impossible to have more than one VCA on a site.
* Unfortunately this reference can not be removed, since the callback script does not know the name of the vda object.
* Todo: send name of VDA object as parameter to LP, and return it in response. That way the callbackscript can locate the caller. 
* To do this we need to create a VDAFactory which sets the name of the VDA object as a variable.
* 
  */
function vdaCallback(json) {
	if(typeof currentVDA.requestCallback == 'function') {
		currentVDA.requestCallback.defer(json);
	}
}





// [di_ui.js]

//add constants
VDA.addMethods({
	STATE_MAXIMIZED : "maximized",
	STATE_MINIMIZED : "minimized",
	INSERT_LOCATION_DIV : "div",
	INSERT_LOCATION_BODY : "body",
	TEXTELEMENT_TYPE_TEXTFIELD : "textfield",
	TEXTELEMENT_TYPE_TEXTAREA : "textarea",
	DEFAULT_CSS_PREFIX : "di_"
});
	
VDA.addMethods({	
	//default values
	title : "Virtual Chat Agent",
	youSaid : "<span class='you_said'>You said: </span>",
	yourQuestion : "Type your question here",
	minimizeIcon : "./img/icons/16-em-minus-grey.png",
	maximizeIcon : "./img/icons/16-em-plus-grey.png",
	closeIcon : "./img/icons/16-em-cross-grey.png",
	emotionPath : "./img/emotes/",
	initialEmotion : "Neutral",
	emotionExtension : ".png",
	fallbackEmotion : "Neutral",
	submitLabel : "Send question",
	initialState : VDA.prototype.STATE_MAXIMIZED,
	initialVisible : true, //typically true for integrated, and false for draggable VCAs
	isDraggable : true,

	insertLocation : VDA.prototype.INSERT_LOCATION_BODY , //body or div
	insertCoordinates : {"left":20,"top":30},
	insertDivId : "assistant",
	
	questionTextElementType : VDA.prototype.TEXTELEMENT_TYPE_TEXTFIELD, //textfield or textarea
	
	cssPrefix : VDA.prototype.DEFAULT_CSS_PREFIX,
	
	hasHeaderElement : true,
	hasToolbarElement : true,
	hasTitleElement : true,
	hasCloseButton : true,
	hasMinMaxButton : true,
	hasBodyElement : true,
	hasLastInputElement : true,
	hasAvatarElement : true,
	hasAnswerElement : true,
	hasQuestionElement : true,
	hasQuestionTextElement : true, //needed?
	hasQuestionSubmitElement : true,


    	


  /**
   * Initialize UI. It creates the components of the UI and assign the corresponding
   * behavior to each of these components.
   */

	initUI: function() {
		//this.draggableVdaDiv = null;
		this.initVdaDiv();
		if (typeof this.initSwfEmotion=="function") this.initSwfEmotion();
		this.displayVdaDiv();
		//if (!this.skipLastRequest) this.getLastRequest();
                if (this.sClickRequestOnInvisible!=null) this.sendClickRequest(this.sClickRequestOnInvisible);
                else this.getLastRequest();
		this.firstFocus = true;
		if (this.insertLocation==this.INSERT_LOCATION_BODY) $$("body")[0].insert(this.vdaDiv);
		else if (this.insertLocation==this.INSERT_LOCATION_DIV) $(this.insertDivId).insert(this.vdaDiv);

                if (this.sClickRequestOnInvisible!=null) this.openUI();
	},



	initVdaDiv : function(){
	 	this.vdaDiv = new Element('div').addClassName(this.cssPrefix+"vda");
		this.vdaDiv.vda = this;
		this.vdaDiv.writeAttribute('id', this.divId);
		if(this.hasHeaderElement)
			this.initHeaderDiv();
		if(this.hasBodyElement)
			this.initBodyDiv();
		if(this.isDraggable)
			this.initDraggable();
	},

	initHeaderDiv : function(){
		this.headerDiv = new Element('div').addClassName(this.cssPrefix+"header");
		this.vdaDiv.insert(this.headerDiv);
		if(this.hasToolbarElement)
			this.initToolbarDiv();
		if(this.hasTitleElement)
			this.initTitleDiv();
	},
	
	initToolbarDiv : function(){
		this.toolbarDiv = new Element('div').addClassName(this.cssPrefix+"toolbar");
		this.headerDiv.insert(this.toolbarDiv);
		 //insert right to left (float:right in CSS)
		if(this.hasCloseButton){
		   this.closeButton = new Element('img').addClassName(this.cssPrefix+"close");
		   this.toolbarDiv.insert(this.closeButton);
		   this.closeButton.writeAttribute("src", this.closeIcon);    
		   this.closeButton.observe('click', this.closeUI.bind(this));
		   }
		if(this.hasMinMaxButton){
			this.minimizeButton = new Element('img').addClassName(this.cssPrefix+"minimize");
			this.maximizeButton = new Element('img').addClassName(this.cssPrefix+"maximize");	
			this.toolbarDiv.insert(this.minimizeButton);
			this.toolbarDiv.insert(this.maximizeButton);	
			this.minimizeButton.writeAttribute("src", this.minimizeIcon);
			this.maximizeButton.writeAttribute("src", this.maximizeIcon);	
			this.minimizeButton.observe('click', this.minimizeUI.bind(this));
			this.maximizeButton.observe('click', this.maximizeUI.bind(this));
		}
		

	},
	
	initTitleDiv : function() {
		this.titleDiv = new Element('div').addClassName(this.cssPrefix+"title");
		this.headerDiv.insert(this.titleDiv);	
		this.titleDiv.update(this.title);
	},
	
	initBodyDiv : function() {
		this.bodyDiv = new Element('div').addClassName(this.cssPrefix+"body");
		this.vdaDiv.insert(this.bodyDiv);
		if(this.hasAvatarElement)
			this.initAvatarDiv();		
		if(this.hasLastInputElement)
			this.initLastInputDiv();
		if(this.hasAnswerElement)
			this.initAnswerDiv();
		if(this.hasQuestionElement)
			this.initQuestionDiv();
	},
	
	initAvatarDiv : function() {
		this.avatarDiv = new Element('div').addClassName(this.cssPrefix+"avatar");
		this.emotionImage = new Element('img', {"id":this.cssPrefix+"emotion"});
		this.bodyDiv.insert(this.avatarDiv);
		this.avatarDiv.insert(this.emotionImage);
	},
	
	initLastInputDiv : function() {
		this.lastInputDiv = new Element('div').addClassName(this.cssPrefix+"last_input");
		this.bodyDiv.insert(this.lastInputDiv);
	},
	
	initAnswerDiv : function(){
		this.answerDiv = new Element('div').addClassName(this.cssPrefix+"answer");	
		this.bodyDiv.insert(this.answerDiv);
	},
	
	initQuestionDiv : function(){
		this.questionDiv = new Element('div').addClassName(this.cssPrefix+"question");	
		this.bodyDiv.insert(this.questionDiv);
		this.questionForm = new Element('form', {"id":this.cssPrefix+"question_form", "action":"#"});
		this.questionDiv.insert(this.questionForm);
		
		var qt = this.questionTextElementType;
		if(qt == "textfield"){
			this.initQuestionTextField();
		}
		else if (qt == "textarea"){
			this.initQuestionTextArea();
		}
		
		if(this.hasQuestionSubmitElement){
			this.initQuestionSubmitElement();
		}
	},
	
	initQuestionTextField : function(){
		this.questionText = new Element('input', {"type":"text", "id":this.cssPrefix+"question_text"});
		this.questionForm.insert(this.questionText);
		this.questionText.writeAttribute("value", this.yourQuestion);
		this.questionText.observe('focus', this.respondToFocus.bind(this));
	},
	
	initQuestionTextArea : function(){

		//the following line makes IE8 crash in IE7 compability mode and quirks mode
		//(setAttribute crashes for type=text)
		this.questionText = new Element('textarea', {"type":"text","id":this.cssPrefix+"question_text"});

		this.questionForm.insert(this.questionText);
		
		this.questionText.writeAttribute("value", this.yourQuestion);
		this.questionText.observe('keypress', this.respondToKeyPress.bindAsEventListener(this));

	},
	
	initQuestionSubmitElement : function(){
		this.questionSubmit = new Element('input', {"type":"submit", "id":this.cssPrefix+"question_submit"});
		this.questionForm.insert(this.questionSubmit);
		this.questionSubmit.writeAttribute("value", this.submitLabel);
		this.questionForm.observe('submit', this.submitQuestion.bind(this));
		this.questionSubmit.observe('focus', this.respondToFocus.bind(this));	

	},

	/**
	 * Moves the avatar inside the viewport. This function should be used
	 * to move the avatar inside the current viewport in cases when it
	 * gets (or can get) out of it - when dragging it, maximizing it or
	 * resizing the window. --Added by ALPE.
	 */
	adjustPositionToViewport : function() {
                
		var vpW, vpH, x;
		if ((typeof window.innerWidth)!="undefined") {
			vpW = window.innerWidth;
			vpH = window.innerHeight;
		}
		else if ((typeof document.documentElement)!="undefined"&&
				(typeof (x = document.documentElement).clientWidth)!="undefined"&&
				(vpW = x.clientWidth)!=0) {
			vpH = x.clientHeight;
		}
		else {
			x = document.getElementsByTagName("body");
			if (x.length>0&&(x=x[0])!=null&&(typeof x.clientWidth)!="undefined") {
				vpW = x.clientWidth;
				vpH = x.clientHeight;
			}
			else {
				vpW = 0;
				vpH = 0;
			}
		}
		if (vpW==NaN||vpW<=0||vpH==NaN||vpH<=0) return;

		var scrollOffset = Element.cumulativeScrollOffset(this.vdaDiv);

		var left = this.vdaDiv.style.left;
		x = parseInt(left);
		if (x!=NaN) left = x;
		else {
			if ((x=left.length)<3) return;
			left = parseInt(left.substr(0,x-2));
			if ((typeof left)!="number"||left==NaN) return;
		}
		left -= scrollOffset.left;

		var top = this.vdaDiv.style.top;
		x = parseInt(top);
		if (x!=NaN) top = x;
		else {
			if ((x=top.length)<3) return;
			top = parseInt(top.substr(0,x-2));
			if ((typeof top)!="number"||top==NaN) return;
		}
		top -= scrollOffset.top;

		if (left<4) this.vdaDiv.style.left = (scrollOffset.left+4).toString()+"px";
		else {
			x = this.vdaDiv.getWidth()+32;
			if (left+x>vpW) this.vdaDiv.style.left = (scrollOffset.left+((left = vpW-x)>4 ? left : 4)).toString()+"px";
		}
                /* commented not to make VCA disappear when dragging it out of the windonw when "Event.observe(window, 'scroll', function()" (line 386) is commented
		if (top<4) this.vdaDiv.style.top = (scrollOffset.top+4).toString()+"px";
		else {
			x = this.vdaDiv.getHeight()+32;
			if (top+x>vpH) this.vdaDiv.style.top = (scrollOffset.top+((top = vpH-x)>4 ? top : 4)).toString()+"px";
		}
                */
        	x = this.vdaDiv.getHeight()+32;
		if (top+x>vpH) this.vdaDiv.style.top = (scrollOffset.top+((top = vpH-x)>4 ? top : 4)).toString()+"px";
		else if (top<4) this.vdaDiv.style.top = (scrollOffset.top+4).toString()+"px";
	},


	initDraggable : function(){	

			if(typeof Droppables=='undefined')
				throw("Draggable VDA requires including script.aculo.us' dragdrop.js library");	

			//We need to create our own Draggable subclass here to make textual areas behave as expected. 
			//We pass an array of class ids which should *not* be draggable to the constructor.
			//Also, onEnd event handling when dragging (saving position to cookie) is handled by this subclass
			var DIDraggable = Class.create(Draggable,{
				
				initialize: function($super,element, excludelist){
                                    var options = {
                                        endeffect: function(element) {
                                            new Effect.Opacity(element, { afterFinish: function(effect) {
                                                    effect.element.setStyle({ opacity: '1' });
                                                },
                                                from: 0.7, to: 1.0, duration: 0.2
                                            });
                                        },
                                        starteffect: function(element) {
                                            new Effect.Opacity(element, {from: 1, to: 0.7, duration: 0.2});
                                        }
                                  
                                    };
                                    $super(element, options);
                                    this.excludelist = excludelist;
                                },
			
				initDrag: function($super, event){					
					var src = Event.element(event);
					var drag = true;
					for(var i=0; i<this.excludelist.length; i++){
						if(src.hasClassName(this.excludelist[i]))
							drag=false;							
					}					
					if(drag)
						$super(event);
				},
				
				finishDrag: function($super, event, success){
					this.element.vda.adjustPositionToViewport();
					this.element.vda.storePosition();
                    try {
                        var questionText = this.element.vda.questionText;
                        if (questionText) questionText.focus();
                    }
                    catch(err) {}
					$super(event,success);
				}
		                
			});
			
			this.draggableVdaDiv = new DIDraggable( this.vdaDiv,[this.cssPrefix+"answer", this.cssPrefix+"last_input"]);
			var scrollOffset = Element.cumulativeScrollOffset(currentVDA.vdaDiv);
			currentVDA.leftScrollOffset = scrollOffset.left;
			currentVDA.topScrollOffset = scrollOffset.top;
			
			Event.observe(window, 'scroll', function() {
			
					//var visible = Element.visible(currentVDA.vdaDiv);
					//if(visible)	
					//	currentVDA.vdaDiv.hide();
					/*var scrollOffset = Element.cumulativeScrollOffset(currentVDA.vdaDiv);
					var leftdiff = scrollOffset.left - currentVDA.leftScrollOffset;
					var topdiff = scrollOffset.top - currentVDA.topScrollOffset;
					var l = currentVDA.vdaDiv.style.left;
					var t =currentVDA.vdaDiv.style.top;						
					l = l.substr(0,l.length-2);
					l = parseInt(l);
					l = l + leftdiff;					

					t = t.substr(0,t.length-2);
					t = parseInt(t);
					t = t + topdiff;
					
					if(typeof(t) == "number" && typeof(l) == "number"){
						currentVDA.vdaDiv.style.top = (t).toString()+"px"; 	
						currentVDA.vdaDiv.style.left = (l).toString()+"px"; 
					}

					currentVDA.leftScrollOffset = scrollOffset.left;
					currentVDA.topScrollOffset = scrollOffset.top;
					//now show it again
					//currentVDA.vdaDiv.show();	
					currentVDA.adjustPositionToViewport();
					//currentVDA.storePosition();
                                        */
			});

			Event.observe(window, 'resize', function() {
				currentVDA.adjustPositionToViewport();
			});
			
		},
	
		//position UI
	displayVdaDiv : function(){	
		if (this.isDraggable) {
			this.restorePosition();
			this.adjustPositionToViewport();
		}
		//show UI depending on settings
		if (this.firstInstance()){
			this.setMaximized(this.initialState==this.STATE_MAXIMIZED);
			this.setSessionOpen(this.initialVisible);
		}
		if (this.isMaximized()) this.maximizeUI();
		else this.minimizeUI();
		if (this.isSessionOpen()) this.openUI();
		else this.resetAndHideUI();
	},
	

    /**
     * Set the emotion to be displayed in avatar field. If argument is empty, set it to initial emotion.
     * @param {String} emotion Emotion to be displayed in the avatar.
     */
	setEmotion : function(emotion) {
		if(this.emotionImage){//make sure that there is an emotionImage
			if( emotion == ""){
				emotion = this.fallbackEmotion;
			}
			this.emotionImage.writeAttribute("src", this.emotionPath + emotion + this.emotionExtension);
		}
	},
    /**
     * Set the last input of the user in the field.
     * Text must be encoded with encodeURIComponent function.
     * @param text - Text to be displayed in last input field.
     */
	setLastInput: function(text) {
		if(this.lastInputDiv){ //make sure that there is a lastInputDiv
		    this.resetScrollbars.defer(this.lastInputDiv); /** IE HACK: defer **/
		    this.lastInputDiv.update(text ? this.youSaid + text : "");
		}
	},
	
    /**
     * Set the answer from the server in the text box.
     * Text must be encoded with encodeURIComponent function.
     * @param text - Text to be displayed in answer text box.
     */
	setAnswer : function(text) {
		if(this.answerDiv){ //make sure that there is an answerDiv
			this.resetScrollbars.defer(this.answerDiv); /** IE HACK: defer **/
			this.answerDiv.update(text);
			//this.answerDiv.innerHTML = text;
			var children = $$("#" + this.divId + " "+this.cssPrefix+" .kb_link");
			var vda = this;
			children.each(function(child) {
				child.observe('click', respondToClick);
			});
			
			function respondToClick(event) {
				var element = Event.element(event);
				Event.stop(event);
				vda.sendRequest(element.innerHTML);
			}

                       
                                                
		}
	},
	
	resetScrollbars : function(element) {
		element.scrollTop -= element.cumulativeScrollOffset().top;
		element.scrollLeft -= element.cumulativeScrollOffset().left;
	},
	
	clearQuestion : function() {
		if(this.questionText) //make sure questionText is defined
			this.questionText.value = "";
	},
	
        bAllowRequest : true,

	submitQuestion : function(event) {
		Event.stop(event);
		if (this.bAllowRequest) {
                    this.sendRequest(this.questionText.value);
                    this.bAllowRequest = false;
                    setTimeout((function(){this.bAllowRequest = true;}).bind(this),1000);
                }
	},

	focusQuestion : function() {
		if(this.questionForm) //make sure questionText is defined
			this.questionForm.focusFirstElement();
	},
  respondToFocus : function() {
      if (this.firstFocus) {
          this.clearQuestion();
          this.firstFocus = false;
      }
  },
  
  		
	respondToKeyPress : function(event){   
			if(event.keyCode == Event.KEY_RETURN)
				this.submitQuestion(event);
		},
  
   minimizeUI : function() {
		if(this.bodyDiv) //make sure bodyDiv is defined
			this.bodyDiv.hide();
		
		if(this.minimizeButton && this.maximizeButton){	//make sure buttons exist
			this.minimizeButton.hide();
			this.maximizeButton.show();
			this.setMaximized(false);
		}
               
    },
    maximizeUI : function() {

		if(this.bodyDiv) //make sure bodyDiv is defined
			this.bodyDiv.show();
		if(this.minimizeButton && this.maximizeButton){	//make sure buttons exist
			this.minimizeButton.show();
			this.maximizeButton.hide();
			this.setMaximized(true);
			if (this.isDraggable) this.adjustPositionToViewport();
		}
		//send init if there is no session and if initialState!=maximized
		var sessionId = this.getSession().getId();
		if( sessionId == "" && this.initialState != this.STATE_MAXIMIZED){
			this.sendInit();
		}	
	},

 closeUI : function() {
     // finish server session
    this.logout();
	
	this.resetAndHideUI();
	
	this.clearMaximized();
	this.clearLocation();

    // fire close event
   	this.vdaDiv.fire("vda:close");
  },
  
  /*
  closeUI : function() {
    // clear local info and cookies
    this.endSession();
    // finish server session
    this.logout();
    // hide the avatar
    this.vdaDiv.hide();
    // set the avatar status to close
    this.setSessionOpen(false);
    // reset UI components
    this.setAnswer(this.initialMessage);
    this.setEmotion(this.initialEmotion);
    this.setLastInput("");
    // fire close event
   	this.vdaDiv.fire("vda:close");
  },
  
  */

  //resets and hides UI
  resetAndHideUI : function(){
  	// hide the avatar
    this.vdaDiv.hide();
    // clear local info and cookies
	this.endSession();
	// set the avatar status to close
    this.setSessionOpen(false);
    // reset UI components
	this.clearMaximized();
    this.setAnswer(this.initialMessage);
    this.setEmotion(this.initialEmotion);
    this.setLastInput("");
  },
  
 
 
  openUI : function() {
	this.setSessionOpen(true);
        if (typeof this.vdaDiv=='undefined') return;
	this.vdaDiv.show();
	this.vdaDiv.fire("vda:open");
  
	//send init if there is no session and if initialVisible == false
	var sessionId = this.getSession().getId();
	//if (sessionId==""&&!this.initialVisible) this.sendInit();
        if (!sessionId) {
            this.extraParameters.ttsmode = false;
            this.ttsModeCheckbox.checked = false;
            if (!this.initialVisible) {
                this.sendInit();
            }
        }
	// repossition the UI to initial possition. FIX for CANALDIGITAL
	// Don't do it directly as the pos cookie is ignored in this case:
	// this.vdaDiv.style.left = this.insertCoordinates.left+"px";
	// this.vdaDiv.style.top = this.insertCoordinates.top+"px";
	// Use restorePosition() instead:

	this.restorePosition();
	this.adjustPositionToViewport();
	this.storePosition();
  },

	//saves DI position, relative to current scroll view
	storePosition: function(){
		var scrollOffset = Element.cumulativeScrollOffset(this.vdaDiv); 
		//var offset = Element.cumulativeOffset(this.vdaDiv); 
		//this.savePosition(offset.left-scrollOffset.left, offset.top-scrollOffset.top);
		var offsetLeftStr = this.vdaDiv.style.left;
		var offsetTopStr = this.vdaDiv.style.top;

		offsetLeftStr = offsetLeftStr.substr(0,offsetLeftStr.length-2);
		offsetTopStr = offsetTopStr.substr(0,offsetTopStr.length-2);
		var offsetLeft = parseInt(offsetLeftStr);
		var offsetTop = parseInt(offsetTopStr);
		if(typeof(offsetLeft)!="number")
			//offsetLeft = 0;
			return;
		if(typeof(offsetTop)!="number")
			//offsetTop = 0;
			return;
		var left = offsetLeft-scrollOffset.left;
		var top = offsetTop-scrollOffset.top;
		this.savePosition(left,top);
	},
	
	//restore DI position
	restorePosition: function() {
		var savedPos = this.loadPosition();
		var scrollOffset = Element.cumulativeScrollOffset(this.vdaDiv); 
		var l, t; 
		if (savedPos.left&&savedPos.top) {
			l = parseInt(savedPos.left)+scrollOffset.left;
			t = parseInt(savedPos.top)+scrollOffset.top;
		}
		else {
			l = this.insertCoordinates.left+scrollOffset.left;
			t = this.insertCoordinates.top+scrollOffset.top;
		}
		this.vdaDiv.style.left = l.toString()+"px";
		this.vdaDiv.style.top = t.toString()+"px";
	},
	
	
	
  
  getAnswerFor : function(text){
  	this.sendRequest(text);
  }
});



VDA.addMethods({

	init : function() {
        if (this.vdaDiv) return;
        var ieScrollCheck = function() {
            try {document.documentElement.doScroll('left');}
            catch(e) {return false;}
            return true;
        };
        var readyCheck = function() {
            return (!document.readyState||document.readyState=='complete'||document.readyState=='loaded'||ieScrollCheck());
        };
	    var vda = this;
	    var f = function() {
			vda.initUI();
			if (typeof vda.initSurvey=='function') vda.initSurvey();
			if (typeof vda.initHistory=='function') vda.initHistory();
			if (typeof vda.initHistoryBackUI=='function') vda.initHistoryBackUI();
			if (typeof vda.initExtendedView=='function') vda.initExtendedView();
			if (typeof vda.initTTS=='function') vda.initTTS();
			if (typeof vda.initWebcallback=='function') vda.initWebcallback();
                        vda.extraParameters['clienturllocation'] = document.location.href;
		};
		var sAvatarHolderId = this.insertLocation=='div' ? this.insertDivId : null, x;
		if (sAvatarHolderId) x = $(sAvatarHolderId);
		else x = ((x = $$("body")).length>0) ? x[0] : null;



		if (x&&readyCheck()) {
		    f();
		    return;
		}
		x = 0;
		var interval = null;
		interval = window.setInterval(function() {
			if (interval==null) return;
			var e;
			if (sAvatarHolderId) e = $(sAvatarHolderId);
			else e = ((e = $$("body")).length>0) ? e[0] : null;
			if (e&&readyCheck()) {
				window.clearInterval(interval);
				interval = null;
				f();
			}
            else if (++x>100) {
				window.clearInterval(interval);
				interval = null;
				throw("The ASOL Avatar could not be loaded because the DOM is taking too much time to construct.");
			}
		},200);
	}
});






// [di_session.js]


/**
 * vda_session 2.0.0 - VDA UI Javascript
 * Session is base class for representing user sessions.
 * @constructor
 */
Session = Class.create({
    /**
     * Initialize the Session.
     */
    initialize: function() {
        this.id = "";
        this.transaction = "";
    },
    /**
     * Get the id of the current session.
     * @returns Id for current session.
     */
    getId : function() {
        return this.id;
    },
    /**
     * Set the id of the current session.
     * @param {String} value Id for current session.
     */
    setId : function(value) {
        this.id = value;
    },
    /**
     * Get the transaction of the current session.
     * @returns Transaction for current session.
     */
    getTransaction : function() {
        return this.transaction;
    },
    /**
     * Set the transaction of the current session.
     * @param {String} value Transaction for current session.
     */
    setTransaction : function(value) {
        this.transaction = value;
    }

});

VDA.addMethods({
    session : new Session()
});





// [di_sessionmanager.js]

VDA.addMethods({
	COOKIE_SESSION_ID : 'vda_session_id',
	COOKIE_TRANSACTION_ID : 'vda_transaction_id',
	COOKIE_OPEN : 'vda_open',
	COOKIE_MAXIMIZED : 'vda_maximized',
	COOKIE_LOCATION : 'vda_location',
    COOKIE_TTS : "vda_tts",

	/** EXPIRY_TIME is defined in minutes. */
	EXPIRY_TIME : null,
	OUT_OF_TIME : -10
});


VDA.addMethods({
    getSession : function() {
    	if (this.session.getId() == "") {
            var sessionId = readCookie(this.divId + "_" + this.COOKIE_SESSION_ID);
            if (sessionId != null && typeof sessionId == "string") {
                this.session.setId(sessionId);
                var transactionId = readCookie(this.divId + "_" + this.COOKIE_TRANSACTION_ID);
                this.session.setTransaction(transactionId);
            }
    	}
    	return this.session;
    },
    setSession : function(id, transaction) {
    	this.session.setId(id);
    	this.session.setTransaction(transaction);
    	setCookie(this.divId + "_" + this.COOKIE_SESSION_ID, id, this.EXPIRY_TIME);
        setCookie(this.divId + "_" + this.COOKIE_TRANSACTION_ID, transaction, this.EXPIRY_TIME);
    },
    endSession : function() {
      this.session.setId("");
      this.session.setTransaction("");
      setCookie(this.divId + "_" + this.COOKIE_SESSION_ID, "", this.OUT_OF_TIME);
      setCookie(this.divId + "_" + this.COOKIE_TRANSACTION_ID, "", this.OUT_OF_TIME);
	  
    },
	
    isSessionOpen : function() {
      var value = readCookie(this.divId + "_" + this.COOKIE_OPEN);
      if (value == "true") return true;
      return false;
    },
	
    setSessionOpen : function(isOpen) {
      if (isOpen) setCookie(this.divId + "_" + this.COOKIE_OPEN, "true",null); // TODO set to never
      else setCookie(this.divId + "_" + this.COOKIE_OPEN, "false", null); 
    },
	
	isMaximized : function(){
		var value = readCookie(this.divId + "_" + this.COOKIE_MAXIMIZED);
	    if (value == "false") return false;
		return true;
	},
	
	
	
    setMaximized : function(isMaximized) {
      if (isMaximized) setCookie(this.divId + "_" + this.COOKIE_MAXIMIZED, "true",null); // TODO set to never
      else setCookie(this.divId + "_" + this.COOKIE_MAXIMIZED, "false", null); 
    },

	clearMaximized : function(){
		setCookie(this.divId + "_" + this.COOKIE_MAXIMIZED, "", this.OUT_OF_TIME);
	},
	
	
	// this function checks if the VCA has been created before 
	// this is done by checking if there is a COOKIE_OPEN cookie
	firstInstance : function(){
		var val = readCookie(this.divId + "_" + this.COOKIE_OPEN);
		if (val) return false;
		return true;

	},
	

	savePosition : function(left,top){
		return this.saveCurrentLocation(left,top);
	},
	
	saveCurrentLocation : function(left,top) {
		setCookie(this.divId + "_" + this.COOKIE_LOCATION, left+"AA"+top, null); 
	},

	loadPosition : function(){
		return this.loadCurrentLocation();
	},
	
	loadCurrentLocation : function(){
		var left = "";
		var top = "";
		var loc = readCookie(this.divId + "_" + this.COOKIE_LOCATION);
		if(loc){
			var locArray = loc.split('AA');
			var left = locArray[0];
			var top = locArray[1];
		}		
		return {"left":left,"top":top};
	},
	
	clearLocation : function(){
		setCookie(this.divId + "_" + this.COOKIE_LOCATION, "", this.OUT_OF_TIME);
	},

    isTTSOn : function(){
        var value = readCookie(this.divId + "_" + this.COOKIE_TTS);
        return (value == "true");
    },


    setTTS : function(b) {
        setCookie(this.divId + "_" + this.COOKIE_TTS, b ? "true":"false",null);
    }
	
});

	

function setCookie(name,value,minutes) {
    if (minutes) {
      var date = new Date();
      date.setTime(date.getTime()+(minutes*60000));
      document.cookie = name+"="+value+";expires="+date.toGMTString()+";path=/";
    } 
    else document.cookie = name+"="+value+";path=/";
}

function readCookie(name) {
   var needle = name + "=";
   var cookieArray = document.cookie.split(';');
   for(var i=0;i <cookieArray.length;i++) {
     var pair = cookieArray[i];
     while (pair.charAt(0)==' ') {
		pair = pair.substring(1, pair.length);
		}
     if (pair.indexOf(needle) == 0) {
		return pair.substring(needle.length, pair.length);
		}
   }
   return null;
}




// [di_uimanager.js]


VDA.addMethods( {

    processResource : function(data) {
        if (typeof data.link=="object"&&typeof data.link.href=="string"&&typeof data.link.target=="string") {
            var location = decodeURIComponent(data.link.href);
            if (location) {
                var target = decodeURIComponent(data.link.target);
                if (target=="") {
                    try {
                        if (!window.onunload) window.onunload = function() {};
                    }
                    catch (err) {}
                    self.location.href = location;
                    return false;
                }
                var x = window.open();
                x.opener = null;
                x.document.location = location;
            }
        }
        return true;
    },


    updateUI : function(data) {
            this.clearQuestion();
            this.focusQuestion();
            if (typeof data.emotion=="string") {
                this.setEmotion(decodeURIComponent(data.emotion));
            }
            if (typeof data.lastinput=="string") {
                this.setLastInput(decodeURIComponent(data.lastinput).unescapeHTML().stripScripts());
            }
            if (typeof data.answer=="string") {
                this.setAnswer(decodeURIComponent(data.answer));
            }
    }

});



// [commsmanager.js]

/**
* Constants
*/
VDA.addMethods({
	TEMPLATE_CALLBACK : "CALLBACK",
	TEMPLATE_JSON : "STANDARDJSON",
	CMD_REQUEST : "request",
	CMD_LASTREQUEST : "last_request",
	CMD_LOGOUT : "logout"
});

/**
* Default config values
*/
VDA.addMethods({
	serverUrl : "http://localhost:8080/libtest/", //url to WE/LP
	template : VDA.prototype.TEMPLATE_CALLBACK, //TEMPLATE_JSON or TEMPLATE_CALLBACK	
	initialMessage : "", //any string
	errorMessage : "Sorry, an unexpected error occurred.", 
	//initialEmotion : "plain",	
	extraParameters :{},     // key and value (value can be a 0-ary function as well) of the parameter 
	useWithLP : false,
	sendCurrentPageUrl : true
});

/**
* Functions
*/
VDA.addMethods({	


	/**
	 * Fix until version 1.6.1 of prototype that will include encoding parameter to Object.toQueryString(). 
	 * We can't use Object.toQueryString(parameters); because it uses encodeURIComponent not suitable for Lingubot 
	 * Only useful for simple objects!!
	 */	
    toQueryString: function(parameters) {
		var results = new Array(); 
		// LP accepts UTF8, produced by encodeURIComponent
		// WE wants windows 1252. we can not get that but latin1, produced by escape is close enough
		var di_encode_uri = ( this.useWithLP ? encodeURIComponent : escape );
		for(var key in parameters){
			var values = parameters[key];
			if (Object.isUndefined(values)) 
			//	results.push(encodeURIComponent(key));
				results.push(di_encode_uri(key));
			else
			//	results.push(encodeURIComponent(key) + '=' +encodeURIComponent(String.interpret(values)));
				results.push(di_encode_uri(key) + '=' +di_encode_uri(String.interpret(values)));
		}
		return results.join('&');
	},





   sendRequestCallback : function(parameters, json) {

       
      
        if (typeof json == "object") {
			if(typeof json.responseStatus == "number" && json.responseStatus == 200 ){ //need to check in different browssers

			
				if (typeof json.responseSession == 'object') {
					 if (typeof json.responseSession.id == 'string' && typeof json.responseSession.transaction == 'string') {
						 this.setSession(json.responseSession.id, json.responseSession.transaction);
					 }
				}
				if (typeof json.responseData == "object") {
					 if(this.processResource(json.responseData)) {
                                            this.updateUI(json.responseData);
					    this.vdaDiv.fire("vda:response", {"response" : Object.clone(json), "parameters" : Object.clone(parameters)});
                                            this.updateContactWebFormFieldsValues(json.responseData.contactformfieldsvalues);
					 }
				}
			}
			else{
				//return code not 200 (e.g. 404, 503), show error message and set session vars to "" (end session)
				this.setSession("", "");
				var errorData = Object.clone(json.responseData);
				errorData.link = {"href":"","target":""};
				errorData.emotion = this.initialEmotion;
				errorData.lastinput = "";
				errorData.answer = this.errorMessage;
				if(this.processResource(errorData)) {
                    this.updateUI(errorData);
				    this.vdaDiv.fire("vda:response", {"response" : Object.clone(errorData), "parameters" : Object.clone(parameters)});
			    }
			}
        }
    },



    sendClickRequest : function(request) {
    
	var epcg;    
    
    	if(this.extraParameters['clickedquestion']===undefined){
    		epcq = null;
    	}else{
    		epcq = this.extraParameters['clickedquestion'];
    	}
    	
    	this.extraParameters['clickedquestion'] = true;
    	this.sendRequest(request);
    	
    	if(epcq === null){
    		delete this.extraParameters.clickedquestion;
    	}
    	if(epcq === false){
    		this.extraParameters['clickedquestion'] = false;
    	}
    
    },

    sendRequest : function(request) {    
    
    	var session = this.getSession();
        var sessionId = session.getId();
        var transactionId = session.getTransaction();
        
	var parameters = this.useWithLP ?
	{
	    "ARTISOLCMD_TEMPLATE" : this.template,
	    "viewtype"		  : this.template,
	    "sessionid"           : sessionId,
	    "userinput"           : request,
	    "command"             : this.CMD_REQUEST
	} :
	{
	    "ARTISOLCMD_TEMPLATE" : this.template,
	    "ident"               : sessionId,
	    "userlogid"           : transactionId,
	    "entry"               : request,
	    "command"             : this.CMD_REQUEST
	} ;

        if (this.useWithLP && transactionId && transactionId!="") {
            parameters.transactionid = transactionId;
        }
		
		if( this.sendCurrentPageUrl ){
			parameters = Object.extend(parameters,{"currentPageUrl":window.location});
		}
        
     for(var key in this.extraParameters){
	  var value = this.extraParameters[key];
	  if( typeof(value) == 'function' ){
	    this.extraParameters[key]=value.call(null);
	  }
        }
        	
        parameters = Object.extend(parameters,this.extraParameters);
    	this.sendBasicRequest(parameters, this.sendRequestCallback.bind(this, parameters));
        this.vdaDiv.fire("vda:input", {
            "input" : Object.clone(parameters)
        });
    },
    
    getLastRequestCallback : function(parameters, json) {
        if (typeof json == "object") {
            if (typeof json.responseData == "object") {
                this.updateUI(json.responseData);
         
                                                            
            }
            //this.setTTS(false);
            this.vdaDiv.fire("vda:getlast", {"response" : Object.clone(json), "parameters" : Object.clone(parameters)});
            
        }
       
    },
    
    getLastRequest : function() {
        var session = this.getSession();
        if (session.getId() != "") {
          this.vdaDiv.show();
          var sessionId = session.getId();
          var transactionId = session.getTransaction();
          
		var parameters = this.useWithLP ?
		{
		    "ARTISOLCMD_TEMPLATE" : this.template,
		    "viewtype"		  : this.template,
		    "sessionid"           : sessionId,
		    "userinput"           : this.CMD_LASTREQUEST,
		    "command"             : this.CMD_LASTREQUEST
		} :
		{
		    "ARTISOLCMD_TEMPLATE" : this.template,
		    "ident"               : sessionId,
		    "userlogid"           : transactionId,
		    "entry"               : this.CMD_LASTREQUEST,
		    "command"             : this.CMD_LASTREQUEST
		} ;
	
          if (this.useWithLP && transactionId && transactionId!="") {
              parameters.transactionid = transactionId;
          }
          this.sendBasicRequest(parameters, this.getLastRequestCallback.bind(this, parameters));
        } 
        else {
            this.setAnswer(this.initialMessage);
            this.setEmotion(this.initialEmotion);
        }
    },
    
    
    logout : function(clearPrevious) {
		
	
    	if (typeof clearPrevious == "undefined") clearPrevious = false;
    	var session = this.getSession();
        var sessionId = session.getId();
        var transactionId = session.getTransaction();
		//do not send anything if we are not in a session:
		if( transactionId == "" || sessionId == ""){
			return;
		}
        var userinput = clearPrevious ? "clear" : "logout";
    	var parameters = this.useWithLP ? {
            "ARTISOLCMD_TEMPLATE" : this.template,
			"viewtype"			  : this.template,
            "sessionid"           : sessionId,
            "userinput"           : userinput,
            "command"             : this.CMD_LOGOUT
        } :
        {
            "ARTISOLCMD_TEMPLATE" : this.template,
            "ident"               : sessionId,
            "userlogid"           : transactionId,
            "entry"               : userinput,
            "command"             : this.CMD_LOGOUT
        } ;
        if (this.useWithLP && transactionId && transactionId!="") {
            parameters.transactionid=transactionId;
        }
    	this.sendBasicRequest(parameters);
        this.initialVisible = false;
    },
	
	sendInit : function(){
		var userinput = "";
    	var parameters = this.useWithLP ? {
            "ARTISOLCMD_TEMPLATE" : this.template,
	     "viewtype"		  : this.template,
            "userinput"           : userinput,
            "command"             : this.CMD_REQUEST
        } :
        {
            "ARTISOLCMD_TEMPLATE" : this.template,
            "entry"               : userinput,
            "command"             : this.CMD_REQUEST
        } ;

		for(var key in this.extraParameters){
			var value = this.extraParameters[key];
			if( typeof(value) == 'function' ){
				this.extraParameters[key]=value.call(null);
			}
        }
        parameters = Object.extend(parameters,this.extraParameters);
		this.sendBasicRequest(parameters, this.sendRequestCallback.bind(this, parameters));
        this.vdaDiv.fire("vda:input", {
            "input" : Object.clone(parameters)
        });

	}

});






// [di_swfemotion.js]

VDA.addMethods({
	SWF_EXTENSION : ".swf",
	SWF_EMOTION_FLASH_VERSION : "8.0.0",
	SWF_ALTERNATE_CONTENT : null,
	SWF_ALTERNATE_EXTENSION : null,
	SWF_EXPRESS_INSTALL : false, // minimum size required 310x137px
	SWF_FLASHVARS : {},
	SWF_PARAMETERS : {"wmode":"transparent", "allowScriptAccess":"always"},
	SWF_ATTRIBUTES : {"id":VDA.prototype.cssPrefix+"emotionSwf"},
	SWF_FLASH_FILE :  "",

	SWF_EMOTION_READY : "SWF_EMOTION_READY"
});


VDA.addMethods({
	swfExtension : VDA.prototype.SWF_EXTENSION,
	swfEmotionMinFlashVersion : VDA.prototype.SWF_EMOTION_FLASH_VERSION, 
	swfAlternateContent : VDA.prototype.SWF_ALTERNATE_CONTENT,
	swfAlternateExtension : VDA.prototype.SWF_ALTERNATE_EXTENSION,
	swfExpressInstall : VDA.prototype.SWF_EXPRESS_INSTALL,
	swfFlashvars : VDA.prototype.SWF_FLASHVARS,
	swfParameters : VDA.prototype.SWF_PARAMETERS,
	swfAttributes : VDA.prototype.SWF_ATTRIBUTES,
	swfFlashFile : VDA.prototype.SWF_FLASH_FILE,
	swfEmotionQueue : null,
	swfemotionLoadingDiv : new Element('div').addClassName("loading"),
	
	initSwfEmotion : function(){
		this.swfAttributes.id = this.cssPrefix+"emotionSwf";
		//this.emotionExtension = ".swf";
	},
	
	setEmotion : function(emotion) {
		if(emotion == ''){
			emotion = this.fallbackEmotion;
		}
		this.swfemotionUpdate.bind(this).defer(emotion);
	},
	
	swfemotionEmbedFlash : function(emotionSrc, emotionId) {		
		swfobject.embedSWF(emotionSrc, emotionId, "100%", "100%", this.swfEmotionMinFlashVersion, this.swfExpressInstall, this.swfFlashvars, this.swfParameters, this.swfAttributes);
	},
	
	swfemotionGetSrc : function () {
		var swfObjectElement = $(this.swfAttributes.id);
		var swfObjectParams = swfObjectElement.childElements();
		for (var index = 0; index < swfObjectParams.length; ++index) {
			if(swfObjectParams[index].readAttribute("name") == "movie")
				return swfObjectParams[index].readAttribute("value");
		}
		return swfObjectElement.readAttribute("data");			
	},
	
	swfemotionSwitch  : function(emotion) {
		if(typeof $(this.swfAttributes.id).switchEmotion == 'function')
			$(this.swfAttributes.id).switchEmotion(emotion);
	},
	
	swfemotionEndLoading : function() {
		this.swfemotionLoadingDiv.hide();
	},
	
	swfemotionStartLoading : function() {
		this.avatarDiv.insert({top: this.swfemotionLoadingDiv});
	},
	
	swfemotionUpdate  : function(emotion) {
		var emotionSrc = this.emotionPath;
		
	//	if(this.swfFlashFile != "" && this.emotionExtension == ".swf") {
		if(this.swfFlashFile != "") {
			emotionSrc = emotionSrc + this.swfFlashFile + this.swfExtension;
		} else {
			emotionSrc = emotionSrc + emotion + this.swfExtension;
		}
		

		if($(this.swfAttributes.id) == null) {
			this.swfemotionEmbedFlash(emotionSrc, this.cssPrefix+"emotion");
			if($(this.swfAttributes.id) != null)
				this.swfemotionStartLoading();
		}
		
		if($(this.swfAttributes.id) != null && (this.swfFlashFile != "" || this.swfemotionGetSrc() != emotionSrc)) {
			if(this.swfFlashFile == "") {
				this.swfemotionEmbedFlash(emotionSrc, this.swfAttributes.id);
			} else {
				if(this.swfEmotionQueue == this.SWF_EMOTION_READY) {
					this.swfemotionSwitch(emotion);
				} else {
					this.swfEmotionQueue = emotion;
				}
			}
		}		    

                //alert("1:"+$(this.swfAttributes.id));
		if($(this.swfAttributes.id) == null) {
                    //alert("2:"+this.swfAlternateContent);
			if(this.swfAlternateContent == null) {
                                //alert("3:"+this.swfAlternateExtension);
				if(this.swfAlternateExtension == null)
					this.emotionImage.writeAttribute("alt", emotion);
				else {
                                    //alert(this.emotionPath + emotion + this.swfAlternateExtension);
                                    this.emotionImage.writeAttribute("src", this.emotionPath + emotion + this.swfAlternateExtension);
                                }
					
			} else {
				this.avatarDiv.update(this.swfAlternateContent);
			}
		}

		}
});

// SWFEmotion delayed switch
function swfemotionReady() {
	currentVDA.swfemotionEndLoading.bind(currentVDA).defer();
	if(typeof currentVDA.swfEmotionQueue == 'string')
		currentVDA.swfemotionSwitch.defer(currentVDA.swfEmotionQueue);
	currentVDA.swfEmotionQueue = currentVDA.SWF_EMOTION_READY;
}





// [di_tts.js]


//add constants
VDA.addMethods({
    VDA_TTS_LABEL : "Turn Sound On",
    VDA_INITIAL_TTSMODE : false,
    VDA_TTS_ALTERNATE_CONTENT : 'TTSPlayer could not be loaded!',
    VDA_TTS_PLAYER_PATH : './mods/tts/swf/'
});


VDA.addMethods({	
	ttsLabel : VDA.prototype.VDA_TTS_LABEL,
	ttsInitialMode : VDA.prototype.VDA_INITIAL_TTSMODE,
	ttsAlternateContent: VDA.prototype.VDA_TTS_ALTERNATE_CONTENT,
	ttsPlayerPath: VDA.prototype.VDA_TTS_PLAYER_PATH,
	
	ttsDiv : new Element('div').addClassName("tts"),
	ttsPlayerDiv : new Element('div', {"id":"ttsplayer"}),
	ttsModeCheckbox : new Element('input', {"type":"checkbox", "id":"ttsmode"}),
	ttsModeLabel : new Element('label', {"for":"ttsmode"}).addClassName("tts_mode_text"),
	ttsPlayerCallback : null,
	
	initTTS : function() {
	    this.lastInputDiv.insert({after: this.ttsDiv});
	    this.ttsDiv.insert(this.ttsModeCheckbox);
	    this.ttsDiv.insert(this.ttsModeLabel.update(this.ttsLabel));
	    this.ttsDiv.insert(this.ttsPlayerDiv.update(this.ttsAlternateContent).hide());
			
		this.extraParameters.ttsmode = this.ttsInitialMode; // Starts deactivated
		this.ttsModeCheckbox.checked = this.ttsInitialMode; // Needed for compatibility with IE7 and IE6, can't use attribute checked:true

		this.ttsModeCheckbox.observe('click', this.ttsModeToggleHandler.bind(this));		
		
		//this.vdaDiv.observe("vda:minimize", this.ttsMinimizeHandler.bindAsEventListener(this));
		//this.vdaDiv.observe("vda:maximize", this.ttsMaximizeHandler.bindAsEventListener(this));
                this.vdaDiv.observe("vda:close", this.ttsCloseHandler.bindAsEventListener(this));
		
        this.vdaDiv.observe("vda:input", this.ttsInputHandler.bindAsEventListener(this));
        this.vdaDiv.observe("vda:response", this.ttsResponseHandler.bindAsEventListener(this));
		this.vdaDiv.observe("vda:getlast", this.ttsResponseHandler.bindAsEventListener(this));
	},

        ttsCloseHandler : function() {
		if($("ttsPlayerSwf") != null) $("ttsPlayerSwf").stopStream();
		//this.ttsDiv.hide();
	},
	
	ttsMinimizeHandler : function() {
                if($("ttsPlayerSwf") != null) $("ttsPlayerSwf").stopStream();
                this.ttsDiv.hide();
	},
	
	ttsMaximizeHandler : function() {
		this.ttsDiv.show();
	},
	
	ttsModeToggleHandler : function(event) {
		if(Event.element(event).checked) {
			this.extraParameters.ttsmode = true;
		} else {			
			this.extraParameters.ttsmode = false;
			if($("ttsPlayerSwf") != null)
				$("ttsPlayerSwf").stopStream();
		}
	},
    
    ttsInputHandler : function (event) {
        var ttsmode = event.memo.input.ttsmode;
        this.setTTS (ttsmode);
    },

	
	 ttsResponseHandler : function(event) {
        if(typeof event.memo.response.responseTTS == "object") {
            var ttsResponseMode = event.memo.response.responseTTS.mode;
            var ttsResponseURI = decodeURIComponent(event.memo.response.responseTTS.uri);

            var b = this.stringToBoolean(ttsResponseMode);
            if(b) {
                this.extraParameters.ttsmode = true;
                this.ttsModeCheckbox.checked = true;
                if (event.memo.response.responseData.ttsallowed=='true') {
                    if($("ttsPlayerSwf") == null && this.isTTSOn()){
                        this.ttsPlayerDiv.show();
                        // TTSPlayer.swf will do a callback to ttsPlayerReady when prepared
                        this.ttsPlayerCallback = this.ttsDelayedPlay.curry(ttsResponseURI);
                        swfobject.embedSWF(this.ttsPlayerPath + "TTSPlayer.swf","ttsplayer","1px", "1px","8.0.0",false,{},{
                            "allowScriptAccess":"always"
                        },{
                            "id":"ttsPlayerSwf"
                        });
                    } else if (this.isTTSOn()){
                        $("ttsPlayerSwf").stopStream();
                        $("ttsPlayerSwf").playStream(ttsResponseURI);
                        //this.setTTS(false);
                    }
                }
            } else {
                this.extraParameters.ttsmode = false;
                if($("ttsPlayerSwf") != null)
                    $("ttsPlayerSwf").stopStream();
            }
        } else {
            this.extraParameters.ttsmode = false;
            if($("ttsPlayerSwf") != null)
                $("ttsPlayerSwf").stopStream();
        }
    },
	
    ttsDelayedPlay : function(uri) {
        $("ttsPlayerSwf").stopStream();
        $("ttsPlayerSwf").playStream(uri);        
        this.ttsPlayerCallback = null;
        
    },

	
	 stringToBoolean: function(string){
        switch(string.toLowerCase()){
            case "true":return true;
            case "false": case null:return false;
            default:return Boolean(string);
        }
    },

         updateContactWebFormFieldsValues: function(text){
            //if (text.startsWith("contactform")) {

            if (text!="") {
                var fieldvalues = text.split("*");
                var firstName = fieldvalues[0];
                var lastName = fieldvalues[1];
                var organization = fieldvalues[2];
                var email = fieldvalues[3];
                var phone = fieldvalues[4];
                var message = fieldvalues[5];
                document.getElementById("firstName").setAttribute("value", decodeURIComponent(firstName));
                document.getElementById("lastName").setAttribute("value", decodeURIComponent(lastName));
                document.getElementById("organization").setAttribute("value", decodeURIComponent(organization));
                document.getElementById("email").setAttribute("value", decodeURIComponent(email));
                document.getElementById("phone").setAttribute("value", decodeURIComponent(phone));
                document.getElementById("Message").value=decodeURIComponent(message);

            }
                
            //}
        }

 	
});

// TTSPlayer.swf callback functions //
function ttsPlayerReady() {
    if((typeof newVda.ttsPlayerCallback == 'function') && (newVda.isTTSOn())){
        newVda.ttsPlayerCallback.defer();
        //newVda.setTTS(false);
    } 
}

function ttsPlayerException(message) {
	alert(message);
}




// [di_config.js]

var newVda = new VDA("vda");

newVda.serverUrl = location.protocol+"//sol.csovca.artificial-solutions.com/sol/";

(function(){
    var x = location.href.toLowerCase();
    newVda.hostUrl = (x.indexOf('artificial-solutions')>=0&&x.indexOf('htdocs')<0) ? location.protocol+"//"+location.host : ".";
})();

newVda.title = "Sol";
//newVda.emotionExtension = ".swf";
newVda.emotionExtension = ".gif";

newVda.emotionPath = newVda.hostUrl+"/vdafiles/img/emotes/";
newVda.minimizeIcon = newVda.hostUrl+"/vdafiles/img/icons/16-em-minus-grey.png";
newVda.maximizeIcon = newVda.hostUrl+"/vdafiles/img/icons/16-em-plus-grey.png";
newVda.closeIcon = newVda.hostUrl+"/vdafiles/img/icons/16-em-cross-grey.png";
//newVda.initialVisible = false;

//newVda.initialVisible = true;

newVda.yourQuestion = "";
newVda.initialMessage = "";
newVda.errorMessage = "The VCA is currently unavailable. Please try again later.";
newVda.initialEmotion = "neutral";
newVda.fallbackEmotion = "neutral";

newVda.hasLastInputElement = true;

//newVda.swfAlternateContent = "<img src='"+newVda.hostUrl+"/vdafiles/img/emotes/Neutral.gif' />";
newVda.swfAlternateExtension = ".jpg";

newVda.historyBackStatic = true;

newVda.isDraggable = true;
//newVda.isDraggable = false;
newVda.submitLabel = "Send";
newVda.useWithLP = true;
//newVda.sendCurrentPageUrl = false;

newVda.insertLocation = "body"; //body or div
//newVda.insertDivId = "cd"; //the id for the main div
newVda.insertCoordinates = {"left":700,"top":100};

newVda.initialState = "maximized";

newVda.ttsPlayerPath = newVda.hostUrl+"/vdafiles/mods/tts/swf/";

//newVda.skipLastRequest = false;

if (typeof sClickRequestOnInvisible=='string') {
    newVda.sClickRequestOnInvisible = sClickRequestOnInvisible;
    newVda.initialVisible = true;
    if (newVda.isTTSOn()) {
        newVda.extraParameters.ttsmode = true;
        newVda.ttsModeCheckbox.checked = true;
    }
}
else {
    newVda.sClickRequestOnInvisible = null;
    newVda.initialVisible = false;
}
newVda.init();

VDA.loaderChecker = {"di_all" : true};

