﻿// --- SmartChat, Simon Booth, Evangelyze Communications 2008.
//SmartChat_Main

/*
This module dynamically injects all nedded files and manages versioning & culture specific versions
*/
if (!__ecSmartChat.lazyLoad) window.status = "SmartChat loading modules"

var webAppPath = "";
var __ecScriptsToLoad = Object();
var __ecLaunchContainer;
var chatid = "";
var __ECUserInfo = Object();
var __ecFlashVer = "";
var __ecSkin = "";
var pageImprint;
var messageSequence;
var enableClientDebug;
var startupComplete = false;
var essentialScriptLoadComplete = false;


function loadSmartChat() {
    sEnc = "%20%C3%A8%20"
    sUnEnc=" è "
    if (decodeURIComponent(sEnc) != sUnEnc) {
        alert("There may be a problem with encoding on this page, some characters may not render as they were intended");
    }

    if (!document) {
        window.setTimeout(loadSmartChat, 150);
        return;
    }
    if (__ecSmartChat.chatOnLoad && typeof ec_openChatPopup != 'undefined') {
        ec_openChatPopup();
        return;
    }
    if (startupComplete) return;
    if (__ecSmartChat.displayname) {
        __ecSmartChat.displayName = __ecSmartChat.displayname;
    }


    if (__ecSmartChat.webcontext) {
        __ecSmartChat.WebContext = __ecSmartChat.webcontext;
    }
    //load balancer:
    if (__ecSmartChat.appServers) {
        var ran_unrounded = Math.random() * __ecSmartChat.appServers.length;
        var ran_number = Math.floor(ran_unrounded);
        webAppPath = __ecSmartChat.appServers[ran_number];
    }
    var needsLaunchContainer = !document.getElementById("__ecLaunchContainer");
    if (needsLaunchContainer || webAppPath.length == 0) {
        //find this script:
        var scriptTags = document.getElementsByTagName("script");
        for (var scriptCount = 0; scriptCount < scriptTags.length; scriptCount++) {
            var scStart = -1;
            if (scriptTags[scriptCount].src.indexOf("clicktochat.js") > 0)
                scStart = scriptTags[scriptCount].src.indexOf("clicktochat.js");
            else if (scriptTags[scriptCount].src.indexOf("ecSmartChat") > 0)
                scStart = scriptTags[scriptCount].src.indexOf("ecSmartChat")
            if (scStart > 0) {
                if(webAppPath.length==0){
                    if (scriptTags[scriptCount].src.indexOf("http://", 0) == 0 || scriptTags[scriptCount].src.indexOf("https://", 0) == 0) {
                        webAppPath = scriptTags[scriptCount].src.substring(0, scStart);
                    }
                    else if (scriptTags[scriptCount].src.indexOf("/", 0) == 0) {
                        var docURL = parseUri(document.URL);
                        webAppPath = docURL.protocol + "://" + docURL.authority + scriptTags[scriptCount].src.substring(0, scStart);
                    }
                }
                if (needsLaunchContainer) {
                    var thisTag = scriptTags[scriptCount];
                    __ecLaunchContainer = document.createElement('div');
                    __ecLaunchContainer.setAttribute("id", "__ecLaunchContainer");
                    thisTag.parentNode.insertBefore(__ecLaunchContainer, thisTag);
                }
                break;
            }
        }
    }

    pageImprint = generateGuid();
    messageSequence = 0;

    injectBootStrap(false);

    startupComplete = true;



}
function injectBootStrap(resetstate) {

    var fallbackPreferedLanguage = "";
    if (navigator.language) fallbackPreferedLanguage = navigator.language;
    else if (navigator.browserLanguage) fallbackPreferedLanguage = navigator.browserLanguage;
    else if (navigator.systemLanguage) fallbackPreferedLanguage = navigator.systemLanguage;
    else if (navigator.userLanguage) fallbackPreferedLanguage = navigator.userLanguage;
    else if (__ecSmartChat.defaultLanguage) fallbackPreferedLanguage = __ecSmartChat.defaultLanguage;

    var param_skin = "";
    if (__ecSmartChat.skin) {
        param_skin = "&__ecSmartChat.skin=" + __ecSmartChat.skin;
    }

    var param_streamingServer = "";
    if (__ecSmartChat.streamingServer) {
        param_streamingServer = "&__ecSmartChat.streamingServer=" + __ecSmartChat.streamingServer;
    }
    var param_reset = "";
    if (resetstate) {
        messageSequence ++;
        param_reset = "&resetstate=true";
    }
    var param_webimuser = "";
    if (__ecSmartChat.webimuser) {
        param_webimuser = "&__ecSmartChat.webimuser=" + __ecSmartChat.webimuser;
    }
    var param_webcontext = "";
    if (__ecSmartChat.WebContext) {
        param_webcontext = "&__ecSmartChat.WebContext=" + __ecSmartChat.WebContext;
    }
    var param_chatid = "";
    if (__ecSmartChat.chatid) {
        param_chatid = "&__ecSmartChat.chatid=" + __ecSmartChat.chatid;
    }
    var param_pageCharSet = "";
    if (document.charset) {
        param_pageCharSet = "&pageCharSet=" + document.charset;
    }
    var param_defaultLanguage = "";
    if (__ecSmartChat.defaultLanguage) {
        param_defaultLanguage = "&__ecSmartChat.defaultLanguage=" + __ecSmartChat.defaultLanguage;
    }
    
    injectScript(webAppPath + "visitor/DynamicJScript.aspx" +
                                        "?pageImprint=" + pageImprint +
                                         "&s=" + messageSequence +
                                         param_skin +
                                         param_streamingServer +
                                         param_webcontext +
                                         param_webimuser +
                                         param_chatid +
                                         param_pageCharSet +
                                         param_defaultLanguage +
                                         "&pageTitle=" + encodeURIComponent(document.title) +
                                         "&pageUrl=" + document.URL +
                                         param_reset +
                                         "&fallbackPreferedLanguage=" + fallbackPreferedLanguage);

}

//'guid' gen (not really a guid) http://blog.shkedy.com/2007/01/createing-guids-with-client-side.html
function generateGuid() {
    var result, i, j;
    result = '';
    for (j = 0; j < 32; j++) {
        if (j == 8 || j == 12 || j == 16 || j == 20)
            result = result + '-';
        i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
        result = result + i;
    }
    return result;
}

function injectScript(scriptPath, scriptName, deferfunction, tagid) {
    if (scriptName) {
        window.status = "SmartChat loading " + scriptName + " from " + webAppPath;
    }
    else if (!scriptPath || scriptPath == "src='javascript:void(0)'") {
    window.status = "SmartChat waiting";

    if (scriptPath) {
        window.status = "SmartChat loading files from " + scriptPath + " from " + webAppPath;
    }
    else if (location.protocol == "https:") {
        scriptPath = "//0";
    }
    else {
        scriptPath = "//:";  //"javascript:void(0)";
    }
}
    var scriptContainer = document.getElementsByTagName("head")[0];
    var libNode;
    if (tagid) {
        var scripts = scriptContainer.getElementsByTagName("script");
        for (var scripttagcount = 0; scripttagcount < scripts.length; scripttagcount++) {
            var scripttag = scripts[scripttagcount];
            if (scripttag.ID == tagid) {
                libNode = scripttag;
                break;
            }
        }
    }
    if (libNode) {
        scriptContainer.removeChild(libNode);
    }
    libNode = document.createElement('script');
    libNode.setAttribute("type", "text/javascript");
    libNode.setAttribute("language", "javascript");
    if (scriptPath) {
        libNode.setAttribute("src", scriptPath);
    }

    if (scriptName) {
        __ecScriptsToLoad[scriptName] = Object();
    }
    
    if (tagid) {
        libNode.setAttribute("id", tagid);

    }
    scriptContainer.appendChild(libNode);
    return libNode;
}
function callWhenLoaded(scriptname, funcname, func) {
    __ecScriptsToLoad[scriptname][funcname] = func;
}
function loadComplete(scriptname) {
    for (var onloadfunc in __ecScriptsToLoad[scriptname]) {
        window.status = "SmartChat calling " + onloadfunc;
        __ecScriptsToLoad[scriptname][onloadfunc]();
    }
    window.status = "SmartChat loaded " + scriptname;
    __ecScriptsToLoad[scriptname] = false;
    for (var script in __ecScriptsToLoad) {
        if (__ecScriptsToLoad[script]) return;
    }
    if (essentialScriptLoadComplete) return;
    window.status = "SmartChat initializing";
    window.setTimeout(initSmartChat, 50);
    essentialScriptLoadComplete = true;

}


function injectCSS(stylePath) {
    var cssContainer = document.getElementsByTagName("head")[0];
    var cssNode = document.createElement('link');
    cssNode.type = 'text/css';
    cssNode.rel = 'stylesheet';
    cssNode.href = stylePath;
    cssNode.media = 'screen';

    cssContainer.appendChild(cssNode);
}

//This function has to be included right in here because its used to load all the modules
/*
parseUri 1.2.1
(c) 2007 Steven Levithan <stevenlevithan.com>
MIT License
*/

function parseUri(str) {
    var o = parseUri.options,
		m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
};

parseUri.options = {
    strictMode: false,
    key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
    q: {
        name: "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};


//This must be the last line of this file
if (!__ecSmartChat.lazyLoad) window.setTimeout(loadSmartChat, 50);
