﻿window.init = window.LoadRunRemoveScriptOnce = function(id, debug){
    try{
        // make sure this only runs once
        if(window.ApexChat && window.ApexChat.compat){
            return;
        }
        window.ApexChat = window.ApexChat || {};
        window.ApexChat.compat = true;
        
        var myId = id || window.id,
            head = document.getElementsByTagName('head')[0] || document.documentElement,
	        script = document.createElement('script'),
	        allScripts = document.getElementsByTagName('script'),
	        domain = 'http://www.apexchat.com/';

	    for(var i = 0; i < allScripts.length; i++){
	        var s = allScripts[i];
	        if(s.src.indexOf('dyns.js') > -1){
	            domain = s.src.replace(/dyns\.js.*/,'');
	            break;
	        }
	    }
	    if(domain.lastIndexOf('/') != (domain.length - 1)){
	        domain += '/';
	    }
	    script.src = domain + 'invitation.ashx?company=' + myId + '&originalReferrer=' + encodeURIComponent(document.referrer).substring(0,500);
	    if(debug === true){
	        script.src += '&debug=true';
	    }
        head.insertBefore(script, head.firstChild);

        // wait for the invitation to be ready to show
        var ready = function(){
            if(window.ApexChat && ApexChat.Invitation && ApexChat.Invitation.ready){
		        ApexChat.Invitation.ready();
            }else{
                window.setTimeout(ready,50);
            }
        };
        ready();
    }catch(e){
        window.ApexChat.compat = false;
        window.setTimeout(function(){
            window.init(id, debug);
        },1000);
    }
};
