
/* gettext library */

var catalog = new Array();

function pluralidx(count) { return (count == 1) ? 0 : 1; }
catalog[' est connect&eacute;'] = ' is connected';
catalog[' est d&eacute;connect&eacute;'] = ' is disconnected';
catalog['Aucun agent disponible actuellement'] = 'No contact available';
catalog['Aucun agent disponible...'] = 'No contact available';
catalog['Des questions ? <a style=\'text-decoration:underline;color:white\'>Posez les en direct en cliquant ici</a>'] = 'Questions ? <a style=\'text-decoration:underline;color:white\'>Ask now clicking here</a>';
catalog['L\'utilisateur a ferme la webcam'] = 'Visitor closed the webcam';
catalog['L\'utilisateur a ferme le chat'] = 'Visitor closed the chat window';
catalog['L\'utilisateur a ferme le viewer'] = 'User closed the document viewer';
catalog['Les champs sont obligatoires'] = 'Fields are mandatory';
catalog['Navigateur'] = 'Browser';
catalog['Nous envoyer un message'] = 'Send us a message';
catalog['Saisissez votre message puis pressez ENTREE pour envoyer'] = 'Enter your message then press ENTER to send';
catalog['Votre correspondant est deconnect&eacute;...'] = 'Your contact is disconnected...';
catalog['Votre message a &eacute;t&eacute; envoy&eacute;'] = 'Your message has been sent successfully';
catalog['connexion en cours...'] = 'please, hold on...';
catalog['envoyer'] = 'send';
catalog['ouvrir le chat'] = 'open chat';
catalog['recommencer'] = 'try again';


function gettext(msgid) {
  var value = catalog[msgid];
  if (typeof(value) == 'undefined') {
    return msgid;
  } else {
    return (typeof(value) == 'string') ? value : value[0];
  }
}

function ngettext(singular, plural, count) {
  value = catalog[singular];
  if (typeof(value) == 'undefined') {
    return (count == 1) ? singular : plural;
  } else {
    return value[pluralidx(count)];
  }
}

function gettext_noop(msgid) { return msgid; }


function interpolate(fmt, obj, named) {
  if (named) {
    return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
  } else {
    return fmt.replace(/%s/g, function(match){return String(obj.shift())});
  }
}

/* formatting library */

var formats = new Array();

formats['DATETIME_FORMAT'] = 'N j, Y, P';
formats['DATE_FORMAT'] = 'N j, Y';
formats['DECIMAL_SEPARATOR'] = '.';
formats['MONTH_DAY_FORMAT'] = 'F j';
formats['NUMBER_GROUPING'] = '0';
formats['TIME_FORMAT'] = 'P';
formats['FIRST_DAY_OF_WEEK'] = '0';
formats['TIME_INPUT_FORMATS'] = ['%H:%M:%S', '%H:%M'];
formats['THOUSAND_SEPARATOR'] = ',';
formats['DATE_INPUT_FORMATS'] = ['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B %Y', '%d %B, %Y'];
formats['YEAR_MONTH_FORMAT'] = 'F Y';
formats['SHORT_DATE_FORMAT'] = 'm/d/Y';
formats['SHORT_DATETIME_FORMAT'] = 'm/d/Y P';
formats['DATETIME_INPUT_FORMATS'] = ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y'];

function get_format(format_type) {
    var value = formats[format_type];
    if (typeof(value) == 'undefined') {
      return msgid;
    } else {
      return value;
    }
}

 
var jsocketBridgeDomain = 'http://santeo.edemo.fr/apps/whiteboard/static/js/jsocketBridge.swf?'+Math.random() ;
var userIP ='38.107.179.211';
var userGEOIP = {'country': 'US', 'city': 'Washington'};
var jsocketConfig = {};
 
var QuickPrez_requirements = [
      'http://api.jsocket.com/prod/jsocket-min.js'
     ,'http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js'
     ,'http://santeo.edemo.fr/apps/widget/static/js/QuickPrezViewer.js'
     ,'http://santeo.edemo.fr/apps/widget/static/js/seadragon-min.js'
     ,'http://santeo.edemo.fr/apps/widget/static/js/SeaDragonManager.js'
     ,'http://santeo.edemo.fr/apps/widget/static/css/seadragon.css'
]


QUICKPREZ_DEFAULT_TOOLBAR_TEXT = gettext("Des questions ? <a style='text-decoration:underline;color:white'>Posez les en direct en cliquant ici</a>");
QUICKPREZ_OFFLINE_TOOLBAR_TEXT = gettext("Aucun agent disponible actuellement");

/* LOADER */

Loader={version:'0.1',files:{},appName:'',callback:function(){},loadedElements:0,totalElements:0,showMask:true,addApplication:function(appName,files){this.files[appName]=files;for(var file in files){if(typeof files[file]!='string')continue;if(this.getFileExtension(files[file])=='Js'){this.totalElements+=1;}}
return(true);},start:function(appName,callback){this.appName=appName||this.appName;this.callback=callback||function(){};if(this.showMask)document.body.innerHTML+=('<div id="loading-mask"></div>'+'<div id="loading">'+'<span id="loading-message">Loading '+this.appName+'. Please wait...</span>'+'</div>');return(this.load());},createElement:function(config){var e=document.createElement(config.element);for(var i in config){if(i!='element'&&i!='appendTo'){e[i]=config[i];}}
var root=document.getElementsByTagName(config.appendTo)[0];return(typeof root.appendChild(e)=='object');},load:function(){var date=new Date();var timestamp=date.getTime();for(var app in this.files){if(this.showMask){this.createElement({element:'script',type:'text/javascript',innerHTML:'document.getElementById("loading-message").innerHTML = "Loading '+this.appName+'/'+app+'...";',appendTo:'body'});}
for(var file in this.files[app]){if(typeof this.files[app][file]=='function')continue;var extension=this.getFileExtension(this.files[app][file]);if(typeof this['load'+extension]=='function'){var url=this.files[app][file];if(url.indexOf('?')==-1){url+='?ts='+timestamp;}
else{url+='&ts='+timestamp;}
this['load'+extension](url);}}}},getFileExtension:function(url){if(url.indexOf('/jsapi')>-1)return'Js';var i=(url+'').lastIndexOf('.');var extension=url.substr(i+1);extension=(extension.substr(0,1).toUpperCase()+extension.substr(1));if(extension=='Css')return'Css';else return'Js';},loadCss:function(url){var result=this.createElement({element:'link',rel:'stylesheet',type:'text/css',href:url,appendTo:'head'});return(result);},loadJs:function(url){var result=this.createElement({element:'script',type:'text/javascript',onload:this.elementLoaded,onreadystatechange:this.elementReadyStateChanged,src:url,appendTo:'head'});return(result);},elementLoaded:function(){Loader.loadedElements+=1;if(Loader.loadedElements==Loader.totalElements){Loader.finish();}},elementReadyStateChanged:function(){if(this.readyState=='loaded'||this.readyState=='complete')Loader.elementLoaded();},finish:function(){if(this.showMask&&typeof(Ext)=='object'){var loadingMask=Ext.get('loading-mask');var loading=Ext.get('loading');loading.fadeOut({duration:0.2,remove:true});loadingMask.setOpacity(0.9);loadingMask.shift({xy:loading.getXY(),width:loading.getWidth(),height:loading.getHeight(),remove:true,duration:1,opacity:0.1,easing:'bounceOut'});}
Loader.callback();},reset:function(){Loader.files={}
Loader.loadedElements=0;Loader.totalElements=0;Loader.appName='';}};

Loader.showMask = false;

String.prototype.trim = function() { return this.replace(/^\s*([\S\s]*)\b\s*$/g, '$1'); };

/* BrowserDetect  */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('b G={r:k(){6.B=6.h(6.w)||"N l B";6.A=6.g(3.8)||6.g(3.M)||"y l A";6.H=6.h(6.C)||"y l H"},h:k(7){L(b i=0;i<7.v;i++){b 9=7[i].4;b J=7[i].s;6.p=7[i].a||7[i].2;c(9){c(9.F(7[i].5)!=-1)d 7[i].2}K c(J)d 7[i].2}},g:k(9){b m=9.F(6.p);c(m==-1)d;d V(9.Y(m+6.p.v+1))},w:[{4:3.8,5:"u",2:"u"},{4:3.8,5:"f",a:"f/",2:"f"},{4:3.e,5:"Z",2:"12",a:"O"},{s:11.W,2:"Q"},{4:3.e,5:"x",2:"x"},{4:3.e,5:"P",2:"R"},{4:3.8,5:"I",2:"I"},{4:3.e,5:"D",2:"D"},{4:3.8,5:"o",2:"o"},{4:3.8,5:"z",2:"S",a:"z"},{4:3.8,5:"U",2:"n",a:"T"},{4:3.8,5:"n",2:"o",a:"n"}],C:[{4:3.j,5:"13",2:"10"},{4:3.j,5:"E",2:"E"},{4:3.8,5:"q",2:"q/X"},{4:3.j,5:"t",2:"t"}]};G.r();',62,66,'||identity|navigator|string|subString|this|data|userAgent|dataString|versionSearch|var|if|return|vendor|OmniWeb|searchVersion|searchString||platform|function|unknown|index|Mozilla|Netscape|versionSearchString|iPhone|init|prop|Linux|Chrome|length|dataBrowser|iCab|an|MSIE|version|browser|dataOS|Camino|Mac|indexOf|BrowserDetect|OS|Firefox|dataProp|else|for|appVersion|An|Version|KDE|Opera|Konqueror|Explorer|rv|Gecko|parseFloat|opera|iPod|substring|Apple|Windows|window|Safari|Win'.split('|'),0,{}))

var ObjectSize = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function loadScript(url, callback) {
    var script = document.createElement("script")
    script.type = "text/javascript";
    if (script.readyState){  //IE
        script.onreadystatechange = function() {
            if (script.readyState == "loaded" ||
                    script.readyState == "complete") {
                script.onreadystatechange = null;
                if (callback) callback();
                this.parentNode.removeChild(this);
            }
        };
    } else {  //Others
        script.onload = function(){
            if (callback) callback();
            this.parentNode.removeChild(this);
        };
    }
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

window.size = function()
{
	var w = 0;
	var h = 0;

	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}


function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function setOpacity(target, opacity) {
    target.style.opacity = opacity / 100;
    target.style.MozOpacity = opacity / 100;
    target.style.filter = 'alpha(opacity='+opacity+ ')';
}
 

function serialize(_obj)
{

   // Let Gecko browsers do this the easy way
   if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined')
   {
      return _obj.toSource();
   }
   // Other browsers must do it the hard way
   switch (typeof _obj)
   {
      // numbers, booleans, and functions are trivial:
      // just return the object itself since its default .toString()
      // gives us exactly what we want
      case 'number':
      case 'boolean':
      case 'function':
         return _obj;
         break;

      // for JSON format, strings need to be wrapped in quotes
      case 'string':
         return '\'' + _obj + '\'';
         break;

      case 'object':
         var str;
         if (_obj.constructor === Array || typeof _obj.callee !== 'undefined')
         {
            str = '[';
            var i, len = _obj.length;
            for (i = 0; i < len-1; i++) { str += serialize(_obj[i]) + ','; }
            str += serialize(_obj[i]) + ']';
         }
         else
         {
            str = '{';
            var key;
            for (key in _obj) { str += key + ':' + serialize(_obj[key]) + ','; }
            str = str.replace(/\,$/, '') + '}';
         }
         return str;
         break;

      default:
         return 'UNKNOWN';
         break;
   }
}
 
/* END JS ADDONS */


 
var ChatWidget = {
    
    open:false
    ,height:null
    ,width:270
    ,opacity:0
    ,maxOpacity:95
    ,targetDiv:null
    ,inputHeight:70
 
    ,title:"eDemo Chat"
    ,gravatarId:null
    ,nickName:'invit&eacute;'
     
    ,editorInitialMessage:gettext('Saisissez votre message puis pressez ENTREE pour envoyer')
    ,waitingHTML:"<div style='text-align:center'><br><br><br><img style='vertical-align:middle' src='http://santeo.edemo.fr/apps/widget/static/img/ajax_loader_64.gif'/><br><br>" + gettext("connexion en cours...") + "<br><br><br><br></div  >"
    ,unavailableHTML:"<div style='text-align:center'><br><br><img style='vertical-align:middle' src='http://santeo.edemo.fr/apps/widget/static/img/unavailable_64.png'/><br><br>" + gettext("Aucun agent disponible...") + "<br><br><img  style='vertical-align:middle' src='http://santeo.edemo.fr/apps/widget/static/img/arrow-circle-double.png'/>&nbsp;<a href='#' onclick='ChatWidget.__searchAgent()'>" + gettext('recommencer') + "</a><br><br><div id='ChatWidget-noresponse-form'><br><b>" + gettext("Nous envoyer un message") +" : </b><br><br><textarea id='ChatWidget-noresponse-message'></textarea><br>Votre adresse email : <br><input type='text' id='ChatWidget-noresponse-email'/><br><br><a class='QuickPrez-awesome' onclick='ChatWidget.__sendEmail();'>"+ gettext('envoyer') +"</a><br></div><br><div id='ChatWidget-noresponse-result'></div><br></div  >"
    ,hangupHTML:"<div style='text-align:center'><br><br><br><img style='vertical-align:middle' src='http://santeo.edemo.fr/apps/widget/static/img/unavailable_64.png'/><br><br>" + gettext("Votre correspondant est deconnect&eacute;...") + "<br><br><br><br><a href='#' onclick='ChatWidget.__searchAgent()'>" + gettext('recommencer') + "</a></div  >"
    ,loaded:false
    ,connectRetries:0
    
    ,__sendEmail:function() {
        // sends a message from the no response form
        var e = document.getElementById('ChatWidget-noresponse-email').value;
        var m = document.getElementById('ChatWidget-noresponse-message').value;
        if (e.indexOf('@')>0 && e.length>5 && m.length>10) {
            // send message
            var url = 'http://santeo.edemo.fr/widget/message/'+QuickPrezWidget.config['WidgetTarget'];
            url += '?m='+escape(m);
            url += '&ajax=1';
            url += '&e='+escape(e);
            loadScript(url);
            document.getElementById('ChatWidget-noresponse-form').style.display='none';
            document.getElementById('ChatWidget-noresponse-result').innerHTML="<img src='http://santeo.edemo.fr/apps/widget/static/img/tick-circle.png' style='vertical-align:bottom'/>&nbsp;<span style='color:green;font-weight:bold'>" + gettext("Votre message a &eacute;t&eacute; envoy&eacute;") + '</span>';
        }
        else {
            document.getElementById('ChatWidget-noresponse-form').style.display='block';
            document.getElementById('ChatWidget-noresponse-result').innerHTML="<img src='http://santeo.edemo.fr/apps/widget/static/img/exclamation.png' style='vertical-align:bottom'/>&nbsp;<span style='color:red;font-weight:bold'>" + gettext("Les champs sont obligatoires") + '</span>';
        }
        
    }   
    ,__randomId:null
    ,__lastSenderId:null
    
    ,__getMaxHeight:function( chatWidget ) {
        var available = parseInt(window.size().height);
        var height = available;

        var height = (height - 40);
        var offsety = (document.all)?5:20;
        height -= offsety;
        //console.log(height);
        return height;
    }
    ,init:function() {
           // auto height
           ChatWidget.height = ChatWidget.__getMaxHeight( true );
           if (!ChatWidget.loaded)  {
               // load libs
               ChatWidget.__loadReqs();
               // display widget now
               //if (!ChatWidget.loaded) return;
               ChatWidget.__randomId = Math.random();
               var div = document.createElement('DIV');
               div.setAttribute('id', 'QuickPrezChat');
               div.setAttribute('class', "qp-" + QuickPrezWidget.config.theme);
               div.setAttribute('style', 'width:' +  ChatWidget.width + 'px' );
               div.innerHTML = ChatWidget.getHtml();          
               document.body.appendChild( div );
               ChatWidget.targetDiv = document.getElementById('QuickPrezChat');
               
               }
           else {
               ChatWidget.__onReqsReady();
           }
           ChatWidget.__setToolbarHTML();
           ChatWidget.show();
           QuickPrezWidget.__hideBar();
           ChatWidget.__enableTextArea( true );
           
            
           // wait for an agent
          // ChatWidget.__startWaitTimeout(true);
    }
    ,__webcam:null
    ,__webcamCallback:function( data ) {
         if (data.indexOf('(')>0) {
            // send to remote
            var fwd = "if(chat.webcam) {chat.webcam."+data+"}";
            jsocket.api.message(jsocketConfig.APP_NAME, jsocketConfig.ROOM, [fwd , [ 'master' ]] );
        }
    }
    ,__webcamCloseCallback:function(  ) {
        ChatWidget.__sendMessage(gettext("L'utilisateur a ferme la webcam"), true);
        ChatWidget.disableWebcam();
    }
    ,enableWebcam:function( audio, video) {
        document.getElementById('QuickPrezChat-Webcam-wrap').style.display = 'block';
        
        flashvars = {
            mode:'client'
            ,cb:'ChatWidget.__webcamCallback'
            ,closecb:'ChatWidget.__webcamCloseCallback'
            ,a: audio && 1 || 0
            ,v: video && 1 || 0
            //,debug:1
        }
        params = {
              menu: "false"
              ,allowscriptaccess: 'always'
        }
        var attributes = {
          id: 'QuickPrezChat-Webcam',
          name: 'QuickPrezChat-Webcam',
          allowscriptaccess: 'always'
        };
        swfobject.embedSWF('http://santeo.edemo.fr/apps/widget/static/FlexStratusWidget.swf?r='+Math.random(), 'QuickPrezChat-Webcam', ChatWidget.width, (ChatWidget.width * 3 / 4), '10', '', flashvars, params, attributes, function() { ChatWidget.__webcam = document.getElementById('QuickPrezChat-Webcam'); } );
        ChatWidget.__resize();
    }
    ,disableWebcam:function() {
        // replace SWF with a blank div
        ChatWidget.__webcam = null;
        var tgt = document.getElementById('QuickPrezChat-Webcam');
        var parent = tgt.parentNode;
        parent.removeChild(tgt);
        
        var div = document.createElement('DIV');
        div.setAttribute('id', 'QuickPrezChat-Webcam')
        parent.appendChild(div);
        
        // hide the tr
        document.getElementById('QuickPrezChat-Webcam-wrap').style.display = 'none';
      //  document.getElementById('QuickPrezChat-Webcam-wrap').height = '0px';
        ChatWidget.__resize();
    }
    ,__setHangUp:function() {
            var tgt = document.getElementById('QuickPrezChat_messageslist');
            tgt.innerHTML = ChatWidget.hangupHTML;
            ChatWidget.__enableTextArea( false );
    }
    ,__setNoResponse:function() {
            ChatWidget.__messagesReceived = 0;
            var tgt = document.getElementById('QuickPrezChat_messageslist');
            tgt.innerHTML = ChatWidget.unavailableHTML;
            ChatWidget.__hideInputHelp();
            ChatWidget.__enableTextArea( false );
    }
    ,__enableTextArea:function( enable ) {
        var tgt = document.getElementById('QuickPrezChat_txtarea');
        if (tgt.value == '') tgt.value = ChatWidget.editorInitialMessage;
        tgt.disabled = !enable;
        tgt.style.color = enable && 'black' || 'silver';
    }
    ,__hideInputHelp:function() {
        var tgt = document.getElementById('QuickPrezChat_messageslist');
        if (tgt) tgt.style.background = 'white';
    }
    ,__setWaiting:function() {
            ChatWidget.__messagesReceived = 0;
            var tgt = document.getElementById('QuickPrezChat_messageslist');
            tgt.innerHTML = '';
            tgt.innerHTML = ChatWidget.waitingHTML;
    }
    ,__setConnectedToRemote:function() {
            var tgt = document.getElementById('QuickPrezChat_messageslist');
            tgt.innerHTML = "";
    }
    ,__onReqsReady:function() {
        // if existing session
        if ( ChatWidget.__checkExistingSession() ) {    
           // alert('existing');
             ChatWidget.__initJsocket();  
             ChatWidget.__setWaiting();
            try {
                eval("var history = " + getCookie('QuickPrez-chatHistory', '/') );
                }
            catch(e) {
                var history = [];
            }
            for (i in history) {
                if (typeof(history[i])  != 'object') continue;
                ChatWidget.addMessage( history[i], true );
            }
          }
          else {
                // load first item on first load
                if ( QuickPrezWidget.config['waitHtml'] ) {
                    QuickPrezViewer.openItem('html', null, QuickPrezWidget.config['waitHtml']);
               }
                ChatWidget.__searchAgent();
                ChatWidget.__enableTextArea( true  );
          }
    
    }
    ,__loadReqs:function() {
        if (ChatWidget.loaded)  {
            // second load
           ChatWidget.__onReqsReady();
            return;
            
            }
        
        Loader.reset();
        Loader.addApplication('QuickPrez', QuickPrez_requirements);
        Loader.start('QuickPrez', function() {
              if (typeof(Seadragon)=='undefined') {
                setTimeout(Loader.callback, 250);
                return;
              }
              Seadragon.Config.imgPath = 'http://santeo.edemo.fr/apps/widget/static/img/seadragon';
              ChatWidget.__onReqsReady();
          });
         ChatWidget.loaded = true;
     }
     ,__searchAgent:function() {
        //ChatWidget.connectRetries = 0;
        ChatWidget.__startWaitTimeout( true );
        ChatWidget.__newRequest();
        
        //ChatWidget.__setWaiting();
     }
     ,__newRequest:function() {
        // search a new agent
        if (typeof(initialJsocketConfig) == 'object') {
           // alert('__newRequest');
             ChatWidget.__cancelWaitTimeout();
             ChatWidget.__initJsocket();   
        }
        else {
            deleteCookie('jsocketConfig', '/');
            var url = 'http://santeo.edemo.fr/widget/incoming/'+QuickPrezWidget.config['WidgetTarget']+'?ajax=1&'+Math.random();
            loadScript(url);
            }
     }
 
     ,__prevJsocketConfig:{
        ROOM:null
     }
     ,__incomingRequestResponse:function( response ) {  
        // receive new params from server
        // wait some time to try again
       //console.log('__incomingRequestResponse', response);
       
        ChatWidget.__cancelWaitTimeout();
        this.__prevJsocketConfig = {}
        for (a in  jsocketConfig ) {
            this.__prevJsocketConfig[a] = jsocketConfig[a]; 
        }
        ChatWidget.__messagesReceived = 0;
        
        if (typeof(response) == 'object') {
            // receive a valid config
            deleteCookie('QuickPrez-chatHistory', '/');    
            jsocketConfig = response['jsocketConfig'];     
            ChatWidget.__initJsocket();   
        }
        else {
            // try again
            ChatWidget.__startWaitTimeout(true);
        }
    }
    ,deleteSession:function() {
        deleteCookie('QuickPrez-chatHistory', '/');   
        deleteCookie('jsocketConfig', '/');   
        //initialJsocketConfig = null;
    }
    ,__checkExistingSession:function() {
        // check if initial config or fresh cookie
        var c = getCookie('jsocketConfig');
        if (typeof(initialJsocketConfig) == 'object') {
            jsocketConfig = initialJsocketConfig;
            return true;
        }
        else if (c) {
            eval("jsocketConfig="+c);
            return true;
        }
        return false;
    }
    ,__clientList:{}
    ,__remoteStatusChanged:function( info ) {
        if (info.name == ChatWidget.nickName) return;
        if (info.key == jsocket.api.uid) return;
        
        // user known 
        if (typeof(ChatWidget.__clientList[ info.key ]) != 'undefined') {
            // status not changed
            if (ChatWidget.__clientList[ info.key ].status == info.status) return;
            }
        
        ChatWidget.__clientList[ info.key ] = info;
        
        // remote connected
        ChatWidget.__cancelWaitTimeout();
        
        
        var now = new Date();
        minutes = now.getMinutes();
        
        if (minutes < 10)  minutes = "0" + minutes;
        var ntime = now.getHours() + ':' + minutes;
        // skip my status :/
        
        var msgt = info.name + gettext(' est connect&eacute;');
        if (info.status == 'offline') {
            msgt = info.name + gettext(' est d&eacute;connect&eacute;');
            delete ChatWidget.__clientList[ info.key ]
            // if (ObjectSize(ChatWidget.__clientList) == 0) {
                
            // }
            }
        var msgdata = {
            from:"system", 
            msg:msgt,
            time:ntime
        }
        
        ChatWidget.addMessage(msgdata, true);
        if (info.status == 'offline') {
            ChatWidget.__setHangUp();
            
        }
        else {
            ChatWidget.__enableTextArea( true );
            if (ChatWidget.__messagesReceived == 0) tgt.innerHTML ='';
            for (var i=0; i < ChatWidget.__waitingMessages.length; i++) {
                var jmsg = ChatWidget.__waitingMessages[i];
                jsocket.api.message('whiteboard', jsocketConfig.ROOM, [ "chat.addMessage({time:'" + jmsg.time + "', senderId:'" + jmsg.senderId +" ', from:'" + jmsg.from +" ', msg:'"+jmsg.msg.replace(/\'/g,"\\\'")+"'})", [ 'master' ]] );
                }

            // send some metas
          //  if (typeof(initialJsocketConfig) == 'object') return;
            var loc = document.location.toString();
            var url = (loc.length>35)?loc.substring(0,35)+"...":loc;
            var infos = '<b>' + gettext("Navigateur") + ':</b> ' + BrowserDetect.browser + ' ' + BrowserDetect.version + ' ( ' + BrowserDetect.OS + ' )';
            var userLang = (navigator.language) ? navigator.language : navigator.userLanguage; 
            infos += '<br><b>Language: </b>'
            if (userLang == 'fr' || userLang == 'en' ) {
                infos += ' <img src=http://santeo.edemo.fr/apps/main/static/img/flags/' + userLang +'.png  />';
            }
            infos += " " + userLang;
            infos += '<br><b>City: </b>' + userGEOIP.city + ' (' + userGEOIP.country + ') ';
            infos += '<br><b>Network: </b>' + userIP ;
            
            //console.log(infos);
            
            var userMeta = QuickPrezWidget.config.userMeta;
            if (userMeta!='') {
                userMeta = userMeta.replace(/"/gi, ' ');
                infos += '<hr><br>' + userMeta;
            }
            var text = '<img src="http://santeo.edemo.fr/apps/widget/static/img/information.png" ext:qtip="'+infos+'" style="cursor:pointer;vertical-align:bottom"/>&nbsp;Page actuelle : <a title="'+loc+'" href="'+loc+'">'+url+'</a>';
            jsocket.api.message('whiteboard', jsocketConfig.ROOM, [ "chat.addMessage({time:'" + ntime + "', senderId:'system', from:'"+jsocketConfig.NICK+"', msg:'"+text+"'})", [ 'master' ]] );
            ChatWidget.__waitingMessages = [];
        }
    }
    ,MAX_WAIT:10000
    ,__startWaitTimer:null
    ,__startWaitTimeout:function(showLoader) {
        ChatWidget.__cancelWaitTimeout();
        if (showLoader) {
            ChatWidget.__setWaiting();
            }       
        ChatWidget.__startWaitTimer = window.setTimeout( ChatWidget.__waitTimeout, ChatWidget.MAX_WAIT);
    }
    ,__cancelWaitTimeout:function() {
        ChatWidget.__startWaitTimer = window.clearInterval( ChatWidget.__startWaitTimer );
        ChatWidget.__startWaitTimer = null;
    }
    ,__waitTimeout:function() {
        if (!ChatWidget.__startWaitTimer) return;
        ChatWidget.__cancelWaitTimeout();
        if (typeof(initialJsocketConfig) == 'object') {
            return;
        }
        //if (ChatWidget.connectRetries >= 0) {
            initialJsocketConfig = '';
            ChatWidget.__setNoResponse();
            //setTimeout("alert('" + gettext("Aucun agent disponible") + "')", 100);
            return;
            
        //}
       // ChatWidget.connectRetries += 1;
       // ChatWidget.__newRequest();
    }
    ,__jsocketReady:false
    ,__initJsocket:function() {
        //console.log('__initJsocket');
          if ( ChatWidget.__jsocketReady ) {
            if ( jsocket.api.uid ) {
                jsocket.api.part( jsocketConfig.APP_NAME,  ChatWidget.__prevJsocketConfig.ROOM );
                jsocket.api.join( jsocketConfig.APP_NAME , jsocketConfig.ROOM, jsocketConfig.ROOM_PWD );
                return;
                }
            else {
                
            }
          }
          else {
            
            
             var conf = {
                tcp: {
                  host: jsocketConfig.SERVER,
                  port: jsocketConfig.SERVER_PORT
                },
                http: {
                  url: jsocketConfig.URL_FAILOVER
                },
                websocket: {
                  host: jsocketConfig.SERVER,
                  port: jsocketConfig.SERVER_WEBSOCKET_PORT
                },
                vhost: jsocketConfig.VHOST
              };
           
            jsocket.api.configure( conf );
            
            
              jsocket.api.register( jsocketConfig.APP_NAME );
              
              jsocket.api.app[ jsocketConfig.APP_NAME ].onForward = function(response) {
                  chat = ChatWidget;
                  if (response.value != false && response.value != true && response.value[1]) {
                      eval(response.value[1]);
                  }
              }
              
              jsocket.api.app[ jsocketConfig.APP_NAME ].onMessage = function(response) {
                  chat = ChatWidget;
                  if (response.value != false && response.value != true && response.value[1]) {
                      eval(response.value[1]);
                  }
              }

              jsocket.api.app[ jsocketConfig.APP_NAME ].onStatus = function(response) {
                 //console.log('onStatus', arguments);
                ChatWidget.__remoteStatusChanged( response.value );
             }
               jsocket.api.app[ jsocketConfig.APP_NAME ].onDisconnect = function(response) {
                    //console.log('onDisconnect', response);
                   ChatWidget.__setNoResponse();
              }
              
              jsocket.api.app[ jsocketConfig.APP_NAME ].onJoin = function (info) {
                     // wait for a remote contact to join
                     //console.log('onJoin', arguments);
                     ChatWidget.__startWaitTimeout();
                       
                     if (info.value == false) {
                          return;
                      } else {
                        // ask list of contacts
                        jsocket.api.list(jsocketConfig.APP_NAME, jsocketConfig.ROOM);
                      }
               } 
               
               jsocket.api.app[ jsocketConfig.APP_NAME ].onList = function(info) {
                //console.log('onList', info);
                    //hatWidget.__clientList={};
                    for (var i=0; i<info.value.length;i++)  {
                        if (typeof(info.value[i]) == 'object') {
                            ChatWidget.__remoteStatusChanged(info.value[i]);
                            }
                    }
                }
               
               jsocket.api.app[ jsocketConfig.APP_NAME ].onPart = function (info) {
                  //console.log('onPart', arguments);
               }
               
               jsocket.api.app[ jsocketConfig.APP_NAME ].onConnect = function(response) {
                  //console.log('onConnect', response);
                  jsocket.api.nick( jsocketConfig.APP_NAME , jsocketConfig.ROOM, jsocketConfig.NICK);
                  jsocket.api.join( jsocketConfig.APP_NAME , jsocketConfig.ROOM, jsocketConfig.ROOM_PWD);
              }
          ChatWidget.__jsocketReady = true;
          }
          

        
        jsocket.api.connect();
        //jsocket.api.debug(true);
        

    
    }
        
    ,close:function() {       
        // cancel close if in room client. (nothing to see)
        ChatWidget.disableWebcam()
        if (typeof(initialJsocketConfig) == 'object') {
            return;
         }
        
        ChatWidget.__sendMessage(gettext("L'utilisateur a ferme le chat"), true);
        ChatWidget.__clientList={};
        jsocket.api.part( jsocketConfig.APP_NAME,  jsocketConfig.ROOM );
        jsocket.api.disconnect();
        ChatWidget.__cancelWaitTimeout();
        ChatWidget.hide();
       // show bar
        setTimeout("QuickPrezWidget.__showBar();", 500);
        ChatWidget.deleteSession();
    
    }
    ,hide:function() {
        ChatWidget.__fadeOut();
        QuickPrezViewer.close();
        
        setTimeout("document.getElementById('QuickPrezChat').style.display='none';", 1000);
        
    
    }
    ,show:function() {
        document.getElementById('QuickPrezChat').style.display='block';
        ChatWidget.__fadeIn();
    }
    ,__messagesReceived:0
    ,addMessage:function(data, noHistory) {
        var tgt = document.getElementById('QuickPrezChat_messageslist');
        if (ChatWidget.__messagesReceived == 0) {
            tgt.innerHTML ='';
            // record config in cookie for later user
            setCookie( 'jsocketConfig', serialize(jsocketConfig), 1, '/');
        }
        if (typeof(data.time) == 'undefined' || data.time=='') {
            data.time = ChatWidget.getNewMsgDate();
        }
        if (typeof(data.senderId) == 'undefined' || data.senderId=='') {
            data.senderId=data.from;
        }
        var alternate = (data.senderId == ChatWidget.__randomId)?'self':'remote';
        var expChanged = (ChatWidget.__lastSenderId && data.senderId != ChatWidget.__lastSenderId)?'x-message-sender-changed':'';
        ChatWidget.__lastSenderId = data.senderId;
        var ahtml = '<div class="QuickPrezChat-message-'+alternate+' '+expChanged+'">';
        if (data.from == 'system' ){
            ahtml += "<img src='http://santeo.edemo.fr/apps/widget/static/img/information.png' style='vertical-align:bottom'/>&nbsp;";
        }
        ahtml += '<b>' + data.from + '</b>&nbsp;';
        ahtml += '<span class="QuickPrezChat-message-date">' + data.time + '</span><br>'
        ahtml += data.msg;
        ahtml += '</div>';
        tgt.innerHTML += ahtml;
        tgt.scrollTop = tgt.scrollHeight;
        ChatWidget.__messagesReceived += 1;
        if (!noHistory) {
            try {
                    eval("var history = " + getCookie('QuickPrez-chatHistory', '/') || [] );
                    }
                catch(e) {
                    var history = [];
                }
            if (!history) history = [];
            history.push( data ) 
            if ( history && history.length > 0 ) setCookie('QuickPrez-chatHistory', serialize( history ), 1, '/');
        }
    }
    ,getNewMsgDate:function() {
            var d = '';
            var n = new Date();
            d = n.getHours();
            var mins = parseInt(n.getMinutes());
            if (mins<10) mins = '0'+mins;
            d +=':' + mins;
            return d;
    }
    ,__htmlEncode:function(value) {
        return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;"); 
    }
    ,__linkifyString:function( inString ) {
        var re = new RegExp("(https?://[^\f\n\r\t\v ]+)", "gi");
        var linkified = inString.replace(re,'<a href="$1" target="_blank" >$1</a>' );
        return linkified;
    }
    ,__waitingMessages:[]
    ,__sendMessage:function( msg, remoteOnly) {
        // remove image helper
        ChatWidget.__hideInputHelp();
        msg = ChatWidget.__htmlEncode(msg);
        while (msg.indexOf('\n')>-1) msg = msg.replace('\n','<br>');
        while (msg.indexOf('\r')>-1) msg = msg.replace('\r','');
        msg = ChatWidget.__linkifyString(msg);
        
        if (msg=='') return;
        
        var jmsg = {
            time:ChatWidget.getNewMsgDate()
            ,from:ChatWidget.nickName
            ,msg:msg.trim()
            ,senderId:ChatWidget.__randomId
        }
        if (!remoteOnly) ChatWidget.addMessage( jmsg );            
        
        
        if (ObjectSize(ChatWidget.__clientList) == 0) {
            // buffer message
            ChatWidget.__waitingMessages.push( jmsg );
        }
        // TODO COMPATIBILITY for old version
        else {
            jsocket.api.message('whiteboard', jsocketConfig.ROOM, [ "chat.addMessage({time:'" + jmsg.time + "', senderId:'" + jmsg.senderId +" ', from:'" + jmsg.from +" ', msg:'"+jmsg.msg.replace(/\'/g,"\\\'")+"'})", [ 'master' ]] );
            }
    }
    ,__txtareaClick:function(obj) {
         if (obj.value.trim() == ChatWidget.editorInitialMessage) {obj.value='';obj.style.color='black'}
    }
    ,__txtareaFocus:function(obj) {
         //if (obj.value.trim() == ChatWidget.editorInitialMessage) {obj.value='';}
    }
    ,__txtareaBlur:function(obj) {
        // if (obj.value.trim() == '') {obj.value='';}
    }
    ,__resize:function() {
        ChatWidget.maximize();
    }
    ,minimized:false
    ,minimize:function() {
        ChatWidget.minimized = true;
        ChatWidget.__setToolbarHTML();
        document.getElementById('QuickPrezChat_messages').style.display='none';
        document.getElementById('QuickPrezChat_tools').style.display='none';
        document.getElementById('QuickPrezChat_table').style.height='40px';
        QuickPrezViewer.close();
    }
    ,maximize:function() {
        if (!ChatWidget.loaded) return;
        ChatWidget.minimized = false;
        document.getElementById('QuickPrezChat').style.display='block';
        ChatWidget.__setToolbarHTML();
        document.getElementById('QuickPrezChat_messages').style.display='block';
        document.getElementById('QuickPrezChat_tools').style.display='block';
        var height = ChatWidget.__getMaxHeight( true );
        var list_height = (height - 20 - ChatWidget.inputHeight);
        if (ChatWidget.__webcam) {
             list_height -= (ChatWidget.width * 3 / 4);
        }
        var tgt = document.getElementById('QuickPrezChat_messageslist');
        tgt.scrollTop = tgt.scrollHeight;
        document.getElementById('QuickPrezChat_table').style.height=height+'px';
        tgt.style.height =  list_height+ 'px';
        tgt.style.width =  ChatWidget.width+ 'px';
      
    }
    ,__setToolbarHTML:function() {
        if (ChatWidget.minimized) {
            document.getElementById('QuickPrezChat_toolbar').innerHTML="<div class='QuickPrezChat-closed' onclick='ChatWidget.maximize()'><img style='vertical-align:top' src='http://santeo.edemo.fr/apps/widget/static/img/comments.png'/> " + gettext('ouvrir le chat') + "</div>"
        }
        else {
          var tbhtml = "<table cellpadding='0' cellspacing='0' width='100%'><tr><td width='80%' class='QuickPrezChat-title' valign='middle'>";
          tbhtml += "<a href='http://www.eDemo.fr' target='_blank'><img border='0'  src='http://santeo.edemo.fr/apps/main/static/img/favicon-edemo.png' style='vertical-align:middle;margin-top:-2px'/>&nbsp;" + ChatWidget.title + "</a>";
          tbhtml += "</td><td width='16' align='right'>";
          // dont add close button for room client
          if (typeof(initialJsocketConfig) != 'object') tbhtml += " <span  class='QuickPrezChat-closebtn' onclick='ChatWidget.close()'>&nbsp;</span>";
          tbhtml += '</td></tr></table>';
          document.getElementById('QuickPrezChat_toolbar').innerHTML=tbhtml;
          
         
        }
    }
    ,__fadeIn:function() {
        if (ChatWidget.opacity <= ChatWidget.maxOpacity) {
            ChatWidget.opacity += 20;
            if (ChatWidget.opacity > ChatWidget.maxOpacity) ChatWidget.opacity  = ChatWidget.maxOpacity;
            setOpacity(ChatWidget.targetDiv, ChatWidget.opacity);
            if (ChatWidget.opacity != ChatWidget.maxOpacity) {
                window.setTimeout(ChatWidget.__fadeIn, 50);
                }
        }   
    }
    ,__fadeOut:function() {
        if (ChatWidget.opacity >= 0) {
            ChatWidget.opacity -= 20;
            if (ChatWidget.opacity<0) ChatWidget.opacity  = 0;
            setOpacity(ChatWidget.targetDiv, ChatWidget.opacity);
            if (ChatWidget.opacity != 0) {
                window.setTimeout(ChatWidget.__fadeOut, 50);
                }
        }   
    }
    ,getHtml:function() {
        var html = '<table id="QuickPrezChat_table" height="' + (ChatWidget.height) +'" width="' + ((ChatWidget.width)) +'" border="0" align="center" cellpadding="0" cellspacing="0">';
        html += '<tr height="20" ><td id="QuickPrezChat_toolbar" height="20"  align="right">&nbsp;</td></tr>';
        html += '<tr id="QuickPrezChat-Webcam-wrap" style="display:none" height="'+(ChatWidget.width * 3 / 4)+'" ><td><div id="QuickPrezChat-Webcam"></div></td></tr>';
        html += '<tr id="QuickPrezChat_messages" height="auto"><td   valign="top" >';
        html += '<div style="width:'+ChatWidget.width+'px;height: '+(ChatWidget.height - 20 - ChatWidget.inputHeight )+'px" \
                id="QuickPrezChat_messageslist" \
                onmousewheel="var event = (typeof(event)!=\'undefined\') ? event : window.event;if(event.stopPropagation) {event.stopPropagation();};    if (event.cancelBubble) {event.cancelBubble();};  return true; " \
                ></div></td></tr>';
        html += '<tr  id="QuickPrezChat_tools" height="' +  ChatWidget.inputHeight + '"><td valign="top" width="' + (ChatWidget.width) +'" align="center">';
        html += '<textarea style="color:#AAAAAA" id="QuickPrezChat_txtarea"  \
                onclick="ChatWidget.__txtareaClick(this)" \
                onfocus="ChatWidget.__txtareaFocus(this)" \
                onblur="ChatWidget.__txtareaBlur(this)" \
                onKeyDown="if (this.value.trim() == ChatWidget.editorInitialMessage) {this.value=\'\';this.style.color=\'black\';}" \
                onKeyUp="if (this.value.trim() == ChatWidget.editorInitialMessage) {this.value=\'\';this.style.color=\'black\';} else if ((event.keyCode || event.charCode) == 13) {ChatWidget.__sendMessage(this.value);this.value=\'\'}" >';

        html += ChatWidget.editorInitialMessage + '</textarea>';
        html += '</textarea>';
        html += '</td></tr>';
        html += '</table>';
        return html;
    }

}

var isDebug = (document.location.hash == '#debug');

var QuickPrezWidget = {
    config:null
    ,loaded:false               // when this loaded
    ,teamOnline:false           // if remote team is available
    ,sessionInProgress:false    // if user asked support
    ,status:''                  // current display status : online or offline
    ,targetDiv:null             // holds ref to existing or created DIV 
    
    ,init:function() {
        // wait for document to be fully loaded
        if (top.document != document) {
            return;
        }
        if (!document.readyState == 'complete' || !document.body) {
            window.setTimeout(QuickPrezWidget.init, 250);
            return;
        }
      
        //load default CSS
        Loader.reset();
        var css =  ['http://santeo.edemo.fr/apps/widget/static/css/widget.css'];
        if (document.all) { 
                var isOld = (window.navigator.appVersion.indexOf('MSIE 6.')>0 || window.navigator.appVersion.indexOf('MSIE 7.')>0); 
                if (isOld) css.push('http://santeo.edemo.fr/apps/widget/static/css/widget-ie.css');
                else  css.push('http://santeo.edemo.fr/apps/widget/static/css/widget-ie8.css');
                // image quality fix
                css.push('http://santeo.edemo.fr/apps/widget/static/css/seadragon-ie.css');
                 }
        Loader.addApplication('Css',css);
        Loader.start('Css');

        // load the widget
        QuickPrezWidget.loaded = true;
        QuickPrezWidget.__initConfig();
        QuickPrezWidget.__initTarget();
        

        // display team or user status
        QuickPrezWidget.__checkStatus();        
        
    }
    ,onClick:function() {
        // open a chat window or redirect to a full page
        if (!QuickPrezWidget.teamOnline) {
             if (typeof(initialJsocketConfig) == 'object') {
               
            }
            else {
                
            }
            //todo : envoyer un message
        }
        QuickPrezWidget.sessionInProgress = true;
        ChatWidget.nickName = jsocketConfig.NICK || 'invité';
        ChatWidget.init();
        if (QuickPrezBulle) QuickPrezBulle.stop();
    }
    ,close:function() {
         
    }
    ,__hideBar:function() {
        //QuickPrezWidget.__fadeIn();
        QuickPrezWidget.targetDiv.style.display='none';
        QuickPrezWidget.opacity = 0;
        setOpacity(QuickPrezWidget.targetDiv, QuickPrezWidget.opacity);
        if (QuickPrezBulle) QuickPrezBulle.stop();
    }
    ,__showBar:function() {
      
        QuickPrezWidget.targetDiv.style.display='block';
        QuickPrezWidget.__fadeIn();
        QuickPrezWidget.sessionInProgress = false;  
        
        QuickPrezWidget.__clearStatusTimeout();
        QuickPrezWidget.__checkStatus();
        
        if (QuickPrezBulle) QuickPrezBulle.start();
        //else if (this.config.bulleParams) 
        else {
            if (!QuickPrezWidget.config.bulleParams)  QuickPrezWidget.config.bulleParams = {};
            if (!QuickPrezWidget.config.bulleParams.theme)  QuickPrezWidget.config.bulleParams.theme = QuickPrezWidget.config.theme;
            loadBulle( QuickPrezWidget.config.bulleParams );
        }
    }
    ,__initTarget:function() {
        if (QuickPrezWidget.config.target==null || QuickPrezWidget.config.target=='bottom right' || QuickPrezWidget.config.target=='bottom left' || QuickPrezWidget.config.target=='bottom' ) {
           if (QuickPrezWidget.config.target==null ) QuickPrezWidget.config.target='bottom';
           var div = document.createElement('DIV');
           div.setAttribute('id', 'QuickPrezWidget');
           div.setAttribute('class', 'position-'+QuickPrezWidget.config.target.replace(' ','-') );
           document.body.appendChild( div );
           var wrap = document.createElement('DIV');
           wrap.setAttribute('id', 'QuickPrezWidget_wrap');
           wrap.setAttribute('class', "QuickPrezWidget_wrap_qp-"+QuickPrezWidget.config.theme);
           wrap.setAttribute('style', 'display:none');
           div.appendChild( wrap );
           
           QuickPrezWidget.targetDiv = document.getElementById( 'QuickPrezWidget_wrap' );
 
        }

        else {
            QuickPrezWidget.targetDiv = document.getElementById( QuickPrezWidget.config.target );
        }       
    }
    ,__initConfig:function() {
        // default config
        QuickPrezWidget.config = {
            target:null                                                             // widget position : 'bottom right',  'bottom left',  'bottom' or any ID. only 'bottom' for IE :/
            ,onImage:'http://santeo.edemo.fr/apps/widget/static/img/button-online.gif'          // image to display when online
            ,offImage:'http://santeo.edemo.fr/apps/widget/static/img/button-offline.gif'        // image to display when offline
            ,onHtml:QUICKPREZ_DEFAULT_TOOLBAR_TEXT                                                            // html to display when online 
            ,offHtml:QUICKPREZ_OFFLINE_TOOLBAR_TEXT                                                             // html to display when offline
            ,ownUrl:false                                                           // force redirection to full page onwidgetclick
            ,hideIfOffline:true                                                    // hide widget if team offline
            ,waitHtml:null                                                          // html to display in the viewer while waiting remote
            ,firstItem:null                                                         // first item to display in the room when remote connected
            ,offUrl:'http://santeo.edemo.fr/unavailable'                                        // redirect onclick when team offline (if hideIfOffline==false)
            ,onUrl:'http://santeo.edemo.fr/incoming'                                            // redirect onclick when team online (if ownUrl==true)
            ,host:'http://santeo.edemo.fr'                                                      // team quickprez hostname
            ,branding:true                                                          // display ad
            ,theme:'darkblue'
            ,userMeta:''
            ,bannerUrl:''
            ,bannerHeight:180
        }
        // override config if any
        if (typeof(QuickPrezWidget_config) == 'object') {
            for (a in QuickPrezWidget_config) {
                QuickPrezWidget.config[a] = QuickPrezWidget_config[a]
            }
        }
        else {
            QuickPrezWidget_config = {};
        }
        // apply chat config
        if (QuickPrezWidget_config.chatWidth) ChatWidget.width = QuickPrezWidget_config.chatWidth;
        if (QuickPrezWidget_config.chatHeight) ChatWidget.height = QuickPrezWidget_config.chatHeight;
        
        
        QuickPrezWidget.config['WidgetTarget'] = "ee04a785e8298c5447db0ce634540a03";
        
    }
    ,__statusTimer:null
    ,__clearStatusTimeout:function() {
        window.clearTimeout(QuickPrezWidget.__statusTimer);
        QuickPrezWidget.__statusTimer = null;
    }
    ,__checkStatus:function() {
        
        if (QuickPrezWidget.sessionInProgress) return;
        if (ChatWidget.__checkExistingSession()) {
            // autolaunch             
            QuickPrezWidget.onClick();
            return;
        }
        // ask new status to server (polling)
        var url = QuickPrezWidget.config.host + '/widget/status/'+QuickPrezWidget.config['WidgetTarget'];

        url += "?cb=QuickPrezWidget.__receiveStatus&r=" + Math.random();
        loadScript(url);
        QuickPrezWidget.__statusTimer = window.setTimeout(QuickPrezWidget.__checkStatus, 3000);
    }

    ,__receiveStatus:function(online) {
        // callback from __checkStatus
        if (!QuickPrezWidget.teamOnline) {
            // team status changed
            if (online && QuickPrezWidget.status != 'online') {
                QuickPrezWidget.__onOnline();
            }
            else {
                if (!QuickPrezWidget.sessionInProgress && QuickPrezWidget.status != 'offline') QuickPrezWidget.__onOffline();
            }
            QuickPrezWidget.teamOnline = online;
        }
        else {
            if ( !online ) {
                QuickPrezWidget.teamOnline = false;
                if (!QuickPrezWidget.sessionInProgress  && QuickPrezWidget.status != 'offline' ) QuickPrezWidget.__onOffline();
            }
        }
    }
    ,__getToolbarHtml:function( html, isText) {
        if (isText) {
        
            // icon + wrapper div if text
            html = '<div class="QuickPrezToolbar-text" >&nbsp;&nbsp;<img src="http://santeo.edemo.fr/apps/widget/static/img/icon-chat-anim.gif" style="vertical-align:middle"/>&nbsp;&nbsp; ' + html + ' </div>';
        }
        html = "<div  id='QuickPrezWidget_contents'  style='cursor:pointer' onclick='QuickPrezWidget.onClick();' >" + html+ "</div>";
        html ="<table width='100%' height='95%'><tr><td valign='top'>" + html + "</td>";
        // add logo
        if (QuickPrezWidget.config.branding) html += "<td width='84' align='right'><div id='QuickPrezWidget_logo' style='cursor:pointer' onclick='window.open(\"http://www.eDemo.fr\");'></div></td>";
        html += "</tr></table>";
 
        return html;
    }
    ,__onOnline:function() {
        // set remote team online
        QuickPrezWidget.status = 'online';
        if (QuickPrezWidget.config.onHtml) {
            QuickPrezWidget.__setHtml( QuickPrezWidget.__getToolbarHtml( QuickPrezWidget.config.onHtml, true ) );
        }
        else {
            QuickPrezWidget.__setImage( QuickPrezWidget.config.onImage );
            }
            
        QuickPrezWidget.__showBar();
            
            
       // QuickPrezWidget.targetDiv.style.display = 'block';
       // QuickPrezWidget.__fadeIn();
        //targetDiv.style.display = 'block';
 
    }
    ,opacity:0
    ,maxOpacity:100
    ,__fadeIn:function() {
        //console.log('__fadeIn');
        if (QuickPrezWidget.opacity <= QuickPrezWidget.maxOpacity) {
            QuickPrezWidget.opacity += 10;
            if (QuickPrezWidget.opacity > QuickPrezWidget.maxOpacity) QuickPrezWidget.opacity  = QuickPrezWidget.maxOpacity;
            setOpacity(QuickPrezWidget.targetDiv, QuickPrezWidget.opacity);
            if (QuickPrezWidget.opacity != QuickPrezWidget.maxOpacity) {
                window.setTimeout(QuickPrezWidget.__fadeIn, 50);
                }
        }   
    }

    ,__onOffline:function() {
        // set remote team offline
        QuickPrezWidget.__hideBar();
        
        QuickPrezWidget.status = 'offline';
        if (QuickPrezWidget.config.offHtml) {
            QuickPrezWidget.__setHtml( QuickPrezWidget.__getToolbarHtml( QuickPrezWidget.config.offHtml, true ) );
        }
        else {
            QuickPrezWidget.__setImage( QuickPrezWidget.config.offImage );
            }
        QuickPrezWidget.targetDiv.style.display = (QuickPrezWidget.config.hideIfOffline)?'none':'block';
        if (QuickPrezBulle) QuickPrezBulle.stop();
        
    }
    ,__setHtml:function( html ) {
        // set widget HTML
        QuickPrezWidget.targetDiv.innerHTML = html;
    }
    ,__setImage:function( url ) {
        // set widget image
        QuickPrezWidget.__setHtml( QuickPrezWidget.__getToolbarHtml( "<img  id='QuickPrezWidget_contents' src='" + url  + "' style='cursor:pointer' onclick='QuickPrezWidget.onClick();' />")  );
    }
    
    ,__initChat:function() {
        // launch chat with existing session or create a new one
    }
    ,__resize:function() {
        if (!QuickPrezWidget.sessionInProgress) {
            // TODO
        }
    }
}
QuickPrezWidget.init();
 
 
var QuickPrezBulle = null;

function loadBulle(config) {
        Loader.reset();
        Loader.addApplication('ExtCore', ['https://ajax.googleapis.com/ajax/libs/ext-core/3.1.0/ext-core.js']);
        Loader.start('ExtCore', function() {
                 Loader.reset();
                 Loader.addApplication('ExtCore2', ['http://santeo.edemo.fr/apps/widget/static/css/bulle.css', 'http://santeo.edemo.fr/apps/widget/static/js/bulle.js']);
                 Loader.start('ExtCore2', function() {
                      // load bulle
                        QuickPrezBulle = new Ext.ux.TimedBubble(config);
                         
                        Ext.fly(QuickPrezBulle.el).on('click', function(e,t) {
                            QuickPrezWidget.onClick();
                        });
                        
                        QuickPrezBulle.start(  );
 
                  });
          });
}
 
function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}

addEvent(window, 'resize', function(e) {
    ChatWidget.__resize();
    QuickPrezWidget.__resize();
    if (typeof(QuickPrezViewer)!='undefined') QuickPrezViewer.__resize();
}, true);

 
 

