/*
 /*
 Copyright 2006 Adobe Systems Incorporated

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
 to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.


 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 */

var CTC_SERVER;

/*
 * The Bridge class, responsible for navigating AS instances
 */
function FABridge(target,bridgeName)
{
    this.target = target;
    this.remoteTypeCache = {};
    this.remoteInstanceCache = {};
    this.remoteFunctionCache = {};
    this.localFunctionCache = {};
    this.bridgeID = FABridge.nextBridgeID++;
    this.name = bridgeName;
    this.nextLocalFuncID = 0;
    FABridge.instances[this.name] = this;
    FABridge.idMap[this.bridgeID] = this;

    return this;
}

// type codes for packed values
FABridge.TYPE_ASINSTANCE =  1;
FABridge.TYPE_ASFUNCTION =  2;

FABridge.TYPE_JSFUNCTION =  3;
FABridge.TYPE_ANONYMOUS =   4;

FABridge.initCallbacks = {};
FABridge.userTypes = {};

FABridge.addToUserTypes = function()
{
    for (var i = 0; i < arguments.length; i++)
    {
        FABridge.userTypes[arguments[i]] = {
            'typeName': arguments[i],
            'enriched': false
        };
    }
}

FABridge.argsToArray = function(args)
{
    var result = [];
    for (var i = 0; i < args.length; i++)
    {
        result[i] = args[i];
    }
    return result;
}

function instanceFactory(objID)
{
    this.fb_instance_id = objID;
    return this;
}

function FABridge__invokeJSFunction(args)
{
    var funcID = args[0];
    var throughArgs = args.concat();//FABridge.argsToArray(arguments);
    throughArgs.shift();

    var bridge = FABridge.extractBridgeFromID(funcID);
    return bridge.invokeLocalFunction(funcID, throughArgs);
}

FABridge.addInitializationCallback = function(bridgeName, callback)
{
    var inst = FABridge.instances[bridgeName];
    if (inst != undefined)
    {
        callback.call(inst);
        return;
    }

    var callbackList = FABridge.initCallbacks[bridgeName];
    if(callbackList == null)
    {
        FABridge.initCallbacks[bridgeName] = callbackList = [];
    }

    callbackList.push(callback);
}

// updated for changes to SWFObject2
function FABridge__bridgeInitialized(bridgeName) {
    var objects = document.getElementsByTagName("object");
    var ol = objects.length;
    var activeObjects = [];
    if (ol > 0) {
        for (var i = 0; i < ol; i++) {
            if (typeof objects[i].SetVariable != "undefined") {
                activeObjects[activeObjects.length] = objects[i];
            }
        }
    }
    var embeds = document.getElementsByTagName("embed");
    var el = embeds.length;
    var activeEmbeds = [];
    if (el > 0) {
        for (var j = 0; j < el; j++) {
            if (typeof embeds[j].SetVariable != "undefined") {
                activeEmbeds[activeEmbeds.length] = embeds[j];
            }
        }
    }
    var aol = activeObjects.length;
    var ael = activeEmbeds.length;
    var searchStr = "bridgeName="+ bridgeName;
    if ((aol == 1 && !ael) || (aol == 1 && ael == 1)) {
        FABridge.attachBridge(activeObjects[0], bridgeName);
    }
    else if (ael == 1 && !aol) {
        FABridge.attachBridge(activeEmbeds[0], bridgeName);
    }
    else {
        var flash_found = false;
        if (aol > 1) {
            for (var k = 0; k < aol; k++) {
                var params = activeObjects[k].childNodes;
                for (var l = 0; l < params.length; l++) {
                    var param = params[l];
                    if (param.nodeType == 1 && param.tagName.toLowerCase() == "param" && param["name"].toLowerCase() == "flashvars" && param["value"].indexOf(searchStr) >= 0) {
                        FABridge.attachBridge(activeObjects[k], bridgeName);
                        flash_found = true;
                        break;
                    }
                }
                if (flash_found) {
                    break;
                }
            }
        }
        if (!flash_found && ael > 1) {
            for (var m = 0; m < ael; m++) {
                var flashVars = activeEmbeds[m].attributes.getNamedItem("flashVars").nodeValue;
                if (flashVars.indexOf(searchStr) >= 0) {
                    FABridge.attachBridge(activeEmbeds[m], bridgeName);
                    break;
                }
            }
        }
    }
    return true;
}

// used to track multiple bridge instances, since callbacks from AS are global across the page.

FABridge.nextBridgeID = 0;
FABridge.instances = {};
FABridge.idMap = {};
FABridge.refCount = 0;

FABridge.extractBridgeFromID = function(id)
{
    var bridgeID = (id >> 16);
    return FABridge.idMap[bridgeID];
}

FABridge.attachBridge = function(instance, bridgeName)
{
    var newBridgeInstance = new FABridge(instance, bridgeName);

    FABridge[bridgeName] = newBridgeInstance;

    /*  FABridge[bridgeName] = function() {
     return newBridgeInstance.root();
     }
     */
    var callbacks = FABridge.initCallbacks[bridgeName];
    if (callbacks == null)
    {
        return;
    }
    for (var i = 0; i < callbacks.length; i++)
    {
        callbacks[i].call(newBridgeInstance);
    }
    delete FABridge.initCallbacks[bridgeName]
}

// some methods can't be proxied.  You can use the explicit get,set, and call methods if necessary.

FABridge.blockedMethods =
{
    toString: true,
    get: true,
    set: true,
    call: true
};

FABridge.prototype =
{


    // bootstrapping

    root: function()
    {
        return this.deserialize(this.target.getRoot());
    },
    //clears all of the AS objects in the cache maps
    releaseASObjects: function()
    {
        return this.target.releaseASObjects();
    },
    //clears a specific object in AS from the type maps
    releaseNamedASObject: function(value)
    {
        if(typeof(value) != "object")
        {
            return false;
        }
        else
        {
            var ret =  this.target.releaseNamedASObject(value.fb_instance_id);
            return ret;
        }
    },
    //create a new AS Object
    create: function(className)
    {
        return this.deserialize(this.target.create(className));
    },


    // utilities

    makeID: function(token)
    {
        return (this.bridgeID << 16) + token;
    },


    // low level access to the flash object

    //get a named property from an AS object
    getPropertyFromAS: function(objRef, propName)
    {
        if (FABridge.refCount > 0)
        {
            throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
        }
        else
        {
            FABridge.refCount++;
            retVal = this.target.getPropFromAS(objRef, propName);
            retVal = this.handleError(retVal);
            FABridge.refCount--;
            return retVal;
        }
    },
    //set a named property on an AS object
    setPropertyInAS: function(objRef,propName, value)
    {
        if (FABridge.refCount > 0)
        {
            throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
        }
        else
        {
            FABridge.refCount++;
            retVal = this.target.setPropInAS(objRef,propName, this.serialize(value));
            retVal = this.handleError(retVal);
            FABridge.refCount--;
            return retVal;
        }
    },

    //call an AS function
    callASFunction: function(funcID, args)
    {
        if (FABridge.refCount > 0)
        {
            throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
        }
        else
        {
            FABridge.refCount++;
            retVal = this.target.invokeASFunction(funcID, this.serialize(args));
            retVal = this.handleError(retVal);
            FABridge.refCount--;
            return retVal;
        }
    },
    //call a method on an AS object
    callASMethod: function(objID, funcName, args)
    {
        if (FABridge.refCount > 0)
        {
            throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");
        }
        else
        {
            FABridge.refCount++;
            args = this.serialize(args);
            retVal = this.target.invokeASMethod(objID, funcName, args);
            retVal = this.handleError(retVal);
            FABridge.refCount--;
            return retVal;
        }
    },

    // responders to remote calls from flash

    //callback from flash that executes a local JS function
    //used mostly when setting js functions as callbacks on events
    invokeLocalFunction: function(funcID, args)
    {
        var result;
        var func = this.localFunctionCache[funcID];

        if(func != undefined)
        {
            result = this.serialize(func.apply(null, this.deserialize(args)));
        }

        return result;
    },

    // Object Types and Proxies

    // accepts an object reference, returns a type object matching the obj reference.
    getTypeFromName: function(objTypeName)
    {
        return this.remoteTypeCache[objTypeName];
    },
    //create an AS proxy for the given object ID and type
    createProxy: function(objID, typeName)
    {
        var objType = this.getTypeFromName(typeName);
        instanceFactory.prototype = objType;
        var instance = new instanceFactory(objID);
        this.remoteInstanceCache[objID] = instance;
        return instance;
    },
    //return the proxy associated with the given object ID
    getProxy: function(objID)
    {
        return this.remoteInstanceCache[objID];
    },

    // accepts a type structure, returns a constructed type
    addTypeDataToCache: function(typeData)
    {
        newType = new ASProxy(this, typeData.name);
        var accessors = typeData.accessors;
        for (var i = 0; i < accessors.length; i++)
        {
            this.addPropertyToType(newType, accessors[i]);
        }

        var methods = typeData.methods;
        for (var i = 0; i < methods.length; i++)
        {
            if (FABridge.blockedMethods[methods[i]] == undefined)
            {
                this.addMethodToType(newType, methods[i]);
            }
        }


        this.remoteTypeCache[newType.typeName] = newType;
        return newType;
    },

    //add a property to a typename; used to define the properties that can be called on an AS proxied object
    addPropertyToType: function(ty, propName)
    {
        var c = propName.charAt(0);
        var setterName;
        var getterName;
        if(c >= "a" && c <= "z")
        {
            getterName = "get" + c.toUpperCase() + propName.substr(1);
            setterName = "set" + c.toUpperCase() + propName.substr(1);
        }
        else
        {
            getterName = "get" + propName;
            setterName = "set" + propName;
        }
        ty[setterName] = function(val)
        {
            this.bridge.setPropertyInAS(this.fb_instance_id, propName, val);
        }
        ty[getterName] = function()
        {
            return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName));
        }
    },

    //add a method to a typename; used to define the methods that can be callefd on an AS proxied object
    addMethodToType: function(ty, methodName)
    {
        ty[methodName] = function()
        {
            return this.bridge.deserialize(this.bridge.callASMethod(this.fb_instance_id, methodName, FABridge.argsToArray(arguments)));
        }
    },

    // Function Proxies

    //returns the AS proxy for the specified function ID
    getFunctionProxy: function(funcID)
    {
        var bridge = this;
        if (this.remoteFunctionCache[funcID] == null)
        {
            this.remoteFunctionCache[funcID] = function()
            {
                bridge.callASFunction(funcID, FABridge.argsToArray(arguments));
            }
        }
        return this.remoteFunctionCache[funcID];
    },

    //reutrns the ID of the given function; if it doesnt exist it is created and added to the local cache
    getFunctionID: function(func)
    {
        if (func.__bridge_id__ == undefined)
        {
            func.__bridge_id__ = this.makeID(this.nextLocalFuncID++);
            this.localFunctionCache[func.__bridge_id__] = func;
        }
        return func.__bridge_id__;
    },

    // serialization / deserialization

    serialize: function(value)
    {
        var result = {};

        var t = typeof(value);
        //primitives are kept as such
        if (t == "number" || t == "string" || t == "boolean" || t == null || t == undefined)
        {
            result = value;
        }
        else if (value instanceof Array)
        {
            //arrays are serializesd recursively
            result = [];
            for (var i = 0; i < value.length; i++)
            {
                result[i] = this.serialize(value[i]);
            }
        }
        else if (t == "function")
        {
            //js functions are assigned an ID and stored in the local cache
            result.type = FABridge.TYPE_JSFUNCTION;
            result.value = this.getFunctionID(value);
        }
        else if (value instanceof ASProxy)
        {
            result.type = FABridge.TYPE_ASINSTANCE;
            result.value = value.fb_instance_id;
        }
        else
        {
            result.type = FABridge.TYPE_ANONYMOUS;
            result.value = value;
        }

        return result;
    },

    //on deserialization we always check the return for the specific error code that is used to marshall NPE's into JS errors
    // the unpacking is done by returning the value on each pachet for objects/arrays
    deserialize: function(packedValue)
    {

        var result;

        var t = typeof(packedValue);
        if (t == "number" || t == "string" || t == "boolean" || packedValue == null || packedValue == undefined)
        {
            result = this.handleError(packedValue);
        }
        else if (packedValue instanceof Array)
        {
            result = [];
            for (var i = 0; i < packedValue.length; i++)
            {
                result[i] = this.deserialize(packedValue[i]);
            }
        }
        else if (t == "object")
        {
            for(var i = 0; i < packedValue.newTypes.length; i++)
            {
                this.addTypeDataToCache(packedValue.newTypes[i]);
            }
            for (var aRefID in packedValue.newRefs)
            {
                this.createProxy(aRefID, packedValue.newRefs[aRefID]);
            }
            if (packedValue.type == FABridge.TYPE_PRIMITIVE)
            {
                result = packedValue.value;
            }
            else if (packedValue.type == FABridge.TYPE_ASFUNCTION)
            {
                result = this.getFunctionProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ASINSTANCE)
            {
                result = this.getProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ANONYMOUS)
            {
                result = packedValue.value;
            }
        }
        return result;
    },
    //increases the reference count for the given object
    addRef: function(obj)
    {
        this.target.incRef(obj.fb_instance_id);
    },
    //decrease the reference count for the given object and release it if needed
    release:function(obj)
    {
        this.target.releaseRef(obj.fb_instance_id);
    },

    // check the given value for the components of the hard-coded error code : __FLASHERROR
    // used to marshall NPE's into flash

    handleError: function(value)
    {
        if (typeof(value)=="string" && value.indexOf("__FLASHERROR")==0)
        {
            var myErrorMessage = value.split("||");
            if(FABridge.refCount > 0 )
            {
                FABridge.refCount--;
            }
            throw new Error(myErrorMessage[1]);
            return value;
        }
        else
        {
            return value;
        }
    }
};

// The root ASProxy class that facades a flash object

ASProxy = function(bridge, typeName)
{
    this.bridge = bridge;
    this.typeName = typeName;
    return this;
};
//methods available on each ASProxy object
ASProxy.prototype =
{
    get: function(propName)
    {
        return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id, propName));
    },

    set: function(propName, value)
    {
        this.bridge.setPropertyInAS(this.fb_instance_id, propName, value);
    },

    call: function(funcName, args)
    {
        this.bridge.callASMethod(this.fb_instance_id, funcName, args);
    },

    addRef: function() {
        this.bridge.addRef(this);
    },

    release: function() {
        this.bridge.release(this);
    }
};

/**
 * tools.flashembed 1.0.4 - The future of Flash embedding.
 *
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/flash-embed.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : March 2008
 * Date: ${date}
 * Revision: ${revision}
 */
(function() {

    //{{{ utility functions

    var jQ = typeof jQuery == 'function';

    var options = {

        // very common opts
        width: '100%',
        height: '100%',

        // flashembed defaults
        allowfullscreen: true,
        allowscriptaccess: 'always',
        quality: 'high',

        // flashembed specific options
        version: null,
        onFail: null,
        expressInstall: null,
        w3c: false,
        cachebusting: false
    };

    if (jQ) {

        // tools version number
        jQuery.tools = jQuery.tools || {};

        jQuery.tools.flashembed = {
            version: '1.0.4',
            conf: options
        };
    }


    // from "Pro JavaScript techniques" by John Resig
    function isDomReady() {

        if (domReady.done)  { return false; }

        var d = document;
        if (d && d.getElementsByTagName && d.getElementById && d.body) {
            clearInterval(domReady.timer);
            domReady.timer = null;

            for (var i = 0; i < domReady.ready.length; i++) {
                domReady.ready[i].call();
            }

            domReady.ready = null;
            domReady.done = true;
        }
    }

    // if jQuery is present, use it's more effective domReady method
    var domReady = jQ ? jQuery : function(f) {

        if (domReady.done) {
            return f();
        }

        if (domReady.timer) {
            domReady.ready.push(f);

        } else {
            domReady.ready = [f];
            domReady.timer = setInterval(isDomReady, 13);
        }
    };


    // override extend opts function
    function extend(to, from) {
        if (from) {
            for (key in from) {
                if (from.hasOwnProperty(key)) {
                    to[key] = from[key];
                }
            }
        }

        return to;
    }


    // JSON.asString() function
    function asString(obj) {

        switch (typeOf(obj)){
            case 'string':
                obj = obj.replace(new RegExp('(["\\\\])', 'g'), '\\$1');

            // flash does not handle %- characters well. transforms "50%" to "50pct" (a dirty hack, I admit)
                obj = obj.replace(/^\s?(\d+)%/, "$1pct");
                return '"' +obj+ '"';

            case 'array':
                return '['+ map(obj, function(el) {
                    return asString(el);
                }).join(',') +']';

            case 'function':
                return '"function()"';

            case 'object':
                var str = [];
                for (var prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                        str.push('"'+prop+'":'+ asString(obj[prop]));
                    }
                }
                return '{'+str.join(',')+'}';
        }

        // replace ' --> "  and remove spaces
        return String(obj).replace(/\s/g, " ").replace(/\'/g, "\"");
    }


    // private functions
    function typeOf(obj) {
        if (obj === null || obj === undefined) { return false; }
        var type = typeof obj;
        return (type == 'object' && obj.push) ? 'array' : type;
    }


    // version 9 bugfix: (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
    if (window.attachEvent) {
        window.attachEvent("onbeforeunload", function() {
            __flash_unloadHandler = function() {};
            __flash_savedUnloadHandler = function() {};
        });
    }

    function map(arr, func) {
        var newArr = [];
        for (var i in arr) {
            if (arr.hasOwnProperty(i)) {
                newArr[i] = func(arr[i]);
            }
        }
        return newArr;
    }

    function getHTML(p, c) {

        var e = extend({}, p);
        var ie = document.all;
        var html = '<object width="' +e.width+ '" height="' +e.height+ '"';

        // force id for IE or Flash API cannot be returned
        if (ie && !e.id) {
            e.id = "_" + ("" + Math.random()).substring(9);
        }

        if (e.id) {
            html += ' id="' + e.id + '"';
        }

        // prevent possible caching problems
        if (e.cachebusting) {
            e.src += ((e.src.indexOf("?") != -1 ? "&" : "?") + Math.random());
        }

        if (e.w3c || !ie) {
            html += ' data="' +e.src+ '" type="application/x-shockwave-flash"';
        } else {
            html += ' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';
        }

        html += '>';

        if (e.w3c || ie) {
            html += '<param name="movie" value="' +e.src+ '" />';
        }

        // parameters
        e.width = e.height = e.id = e.w3c = e.src = null;

        for (var k in e) {
            if (e[k] !== null) {
                html += '<param name="'+ k +'" value="'+ e[k] +'" />';
            }
        }

        // flashvars
        var vars = "";

        if (c) {
            for (var key in c) {
                if (c[key] !== null) {
                    vars += key +'='+ (typeof c[key] == 'object' ? asString(c[key]) : c[key]) + '&';
                }
            }
            vars = vars.substring(0, vars.length -1);
            html += '<param name="flashvars" value=\'' + vars + '\' />';
        }

        html += "</object>";

        return html;

    }

    //}}}


    function Flash(root, opts, flashvars) {

        var version = flashembed.getVersion();

        // API methods for callback
        extend(this, {

            getContainer: function() {
                return root;
            },

            getConf: function() {
                return opts;
            },

            getVersion: function() {
                return version;
            },

            getFlashvars: function() {
                return flashvars;
            },

            getApi: function() {
                return root.firstChild;
            },

            getHTML: function() {
                return getHTML(opts, flashvars);
            }

        });

        // variables
        var required = opts.version;
        var express = opts.expressInstall;


        // everything ok -> generate OBJECT tag
        var ok = !required || flashembed.isSupported(required);

        if (ok) {
            opts.onFail = opts.version = opts.expressInstall = null;
            root.innerHTML = getHTML(opts, flashvars);

            // fail #1. express install
        } else if (required && express && flashembed.isSupported([6,65])) {

            extend(opts, {src: express});

            flashvars = {
                MMredirectURL: location.href,
                MMplayerType: 'PlugIn',
                MMdoctitle: document.title
            };

            root.innerHTML = getHTML(opts, flashvars);

            // fail #2.
        } else {

            // fail #2.1 custom content inside container
            if (root.innerHTML.replace(/\s/g, '') !== '') {
                // minor bug fixed here 08.04.2008 (thanks JRodman)

                // fail #2.2 default content
            } else {
                root.innerHTML =
                "<h2>Flash version " + required + " or greater is required</h2>" +
                "<h3>" +
                (version[0] > 0 ? "Your version is " + version : "You have no flash plugin installed") +
                "</h3>" +

                (root.tagName == 'A' ? "<p>Click here to download latest version</p>" :
                 "<p>Download latest version from <a href='http://www.adobe.com/go/getflashplayer' target='_blank'>here</a></p>");

                if (root.tagName == 'A') {
                    root.onclick = function() {
                        location.href= 'http://www.adobe.com/go/getflashplayer';
                    };
                }
            }
        }

        // onFail
        if (!ok && opts.onFail) {
            var ret = opts.onFail.call(this);
            if (typeof ret == 'string') { root.innerHTML = ret; }
        }

        // http://flowplayer.org/forum/8/18186#post-18593
        if (document.all) {
            window[opts.id] = document.getElementById(opts.id);
        }

    }

    window.flashembed = function(root, conf, flashvars) {

        //{{{ construction

        // root must be found / loaded
        if (typeof root == 'string') {
            var el = document.getElementById(root);
            if (el) {
                root = el;
            } else {
                domReady(function() {
                    flashembed(root, conf, flashvars);
                });
                return;
            }
        }

        // not found
        if (!root) { return; }

        if (typeof conf == 'string') {
            conf = {src: conf};
        }

        var opts = extend({}, options);
        extend(opts, conf);

        return new Flash(root, opts, flashvars);

        //}}}


    };


    //{{{ static methods

    extend(window.flashembed, {

        // returns arr[major, fix]
        getVersion: function() {

            var version = [0, 0];

            if (navigator.plugins && typeof navigator.plugins["Shockwave Flash"] == "object") {
                var _d = navigator.plugins["Shockwave Flash"].description;
                if (typeof _d != "undefined") {
                    _d = _d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
                    var _m = parseInt(_d.replace(/^(.*)\..*$/, "$1"), 10);
                    var _r = /r/.test(_d) ? parseInt(_d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
                    version = [_m, _r];
                }

            } else if (window.ActiveXObject) {

                try { // avoid fp 6 crashes
                    var _a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");

                } catch(e) {

                    try {
                        _a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
                        version = [6, 0];
                        _a.AllowScriptAccess = "always"; // throws if fp < 6.47

                    } catch(ee) {
                        if (version[0] == 6) { return version; }
                    }
                    try {
                        _a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
                    } catch(eee) {

                    }

                }

                if (typeof _a == "object") {
                    _d = _a.GetVariable("$version"); // bugs in fp 6.21 / 6.23
                    if (typeof _d != "undefined") {
                        _d = _d.replace(/^\S+\s+(.*)$/, "$1").split(",");
                        version = [parseInt(_d[0], 10), parseInt(_d[2], 10)];
                    }
                }
            }

            return version;
        },

        isSupported: function(version) {
            var now = flashembed.getVersion();
            var ret = (now[0] > version[0]) || (now[0] == version[0] && now[1] >= version[1]);
            return ret;
        },

        domReady: domReady,

        // returns a String representation from JSON object
        asString: asString,


        getHTML: getHTML

    });

    //}}}


    // setup jquery support
    if (jQ) {

        jQuery.fn.flashembed = function(conf, flashvars) {

            var el = null;

            this.each(function() {
                el = flashembed(this, conf, flashvars);
            });

            return conf.api === false ? this : el;
        };

    }

})();

// ITooLabs ctc part starts here
// Extend Array if need
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length;
        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0) from += len;
        for (; from < len; from++)  if (from in this && this[from] === elt) return from;
        return -1;
    };
}

// Static vars
var XIMSSEvent = {
    CONNECTED: "CONNECTED",
    DISCONNECTED: "DISCONNECTED",
    LOGIN_FAILED: "LOGIN_FAILED",
    CONN_FAILED: "CONN_FAILED"
};
var CallEvent = {
    CALL_DISCONNECTED: "CALL_DISCONNECTED",
    CALL_PROVISIONED: "CALL_PROVISIONED",
    CALL_CONNECTED: "CALL_CONNECTED",
    CALL_INCOMING: "CALL_INCOMING",
    CALL_UPDATED: "CALL_UPDATED"
};
var ITL_CTC_DIALPAD = 1;
var ITL_CTC_POPUP = 2;
var ITL_CTC_AUTO_CALL = 4;

var ITL_CTC_POPWIN; 

function getCtcScriptBase(def) {
    var srv;
    if (def != null) {
        srv = def;
    } else {
        var head = document.getElementsByTagName("head")[0];
        var r = /^(https?:\/\/[^\/]+\/.*\/?)?ctc\.js$/;
        for (var node = head.firstChild; node != null; node = node.nextSibling) {
            if (node.nodeName == "SCRIPT") {
                var a = r.exec(node.getAttribute("src"));
                if (a) {
                    srv = a[1] || '';
                    break;
                }
            }
        }
    }
    if (srv == null) {
    	srv =  (document.location.href.substring(0, 5) == 'https')?'https':'http';
        srv += '://ctc.ru.itoolabs.net/';
    }
    return srv;
}

function getCtcFlashServerURI() {
    if (CTC_SERVER != null) {
    	return 'http://' + CTC_SERVER + '/';
    } else {
    	var base = getCtcScriptBase();
    	if (base == '') base = document.location.href;
    	a = /^https?:\/\/([^\/]+\/)/.exec(base);
    	if (a) {
    		return 'http://' + a[1];
    	} else {
    		return 'http://ctc.ru.itoolabs.net/';
    	}
    }
}

function itl_add_ctc_css() {
      var headID = document.getElementsByTagName("head")[0];         
      var cssNode = document.createElement('link');
      cssNode.type = 'text/css';
      cssNode.rel = 'stylesheet';
      cssNode.href = getCtcScriptBase()+'ctc.css';
      cssNode.media = 'screen';
      headID.appendChild(cssNode);
}

var ITooLabs = (function() {
    var ua = navigator.userAgent.toLowerCase(),
            isOpera = ua.indexOf("opera") > -1,
            isSafari = (/webkit|khtml/).test(ua),
            isIE = !isOpera && ua.indexOf("msie") > -1,
            isIE7 = !isOpera && ua.indexOf("msie 7") > -1,
            isGecko = !isSafari && ua.indexOf("gecko") > -1,
            isFun = function(fun) {
                return typeof(fun) == 'function';
            },

        /* ***************************************************************************************
         * onDocumentReady related things
         */
            onReadyListener = [],
            readyBound = false,
            readyFlag = false,
            ready = function() {
                if(readyFlag) return;
                for(var i = 0; i < onReadyListener.length; i++)
                    onReadyListener[i].c.apply(onReadyListener[i].s, onReadyListener[i].p);
                onReadyListener = [];
                readyFlag = true;
            },
            bindReady = function() {
                if(readyBound) return;
                readyBound = true;
                /* Mozilla, Opera (see further below for it) and webkit nightlies currently support this event */
                if(document.addEventListener && !isOpera)
                /* Use the handy event callback */
                    document.addEventListener("DOMContentLoaded", ready, false);
                /* If IE is used and is not in a frame
                 Continually check to see if the document is ready */
                if(isIE && window == top) (function() {
                    try {
                        /* If IE is used, use the trick by Diego Perini
                         http://javascript.nwbox.com/IEContentLoaded/ */
                        document.documentElement.doScroll("left");
                    } catch(error) {
                        setTimeout(arguments.callee, 0);
                        return;
                    }
                    /* and execute any waiting functions */
                    ready();
                })();

                if(isOpera)
                    document.addEventListener("DOMContentLoaded", function () {
                        /* and execute any waiting functions */
                        ready();
                    }, false);

                if(isSafari) {
                    (function() {
                        if(document.readyState != "loaded" && document.readyState != "complete") {
                            setTimeout(arguments.callee, 0);
                            return;
                        }
                        /* and execute any waiting functions */
                        ready();
                    })();
                }

                /* A fallback to window.onload, that will always work */
                if(document.addEventListener) document.addEventListener("load", ready, false);
                if(document.attachEvent) document.attachEvent("onload", ready);
            },
            onReady = function(callback, scope /*, args... */) {
                if (!isFun(callback)) throw new TypeError();
                if (readyFlag) callback.apply(scope, Array.prototype.slice.call(arguments, 2));
                else onReadyListener.push({c: callback, s: scope, p: Array.prototype.slice.call(arguments, 2)});
            };

    bindReady();

    return {
        onReady: onReady
    }
})();

ITooLabs.dom = function() {
    var
            _addClass = function(el, clazz) {
                var elClazz = (el.className||"").split(" ");
                clazz = (clazz||"").replace(/\s+/gi,' ');
                clazz = (clazz||"").split(" ");
                for (var i=0; i<clazz.length; i++) {
                    var idx = elClazz.indexOf(clazz[i]);
                    if (idx<0) elClazz.push(clazz[i]);
                }
                el.className = elClazz.join(" ");
            },
            _removeClass = function(el, clazz) {
                var elClazz = (el.className||"").split(" ");
                clazz = (clazz||"").replace(/\s+/gi,' ');
                clazz = (clazz||"").split(" ");
                for (var i=0; i<clazz.length; i++) {
                    var idx = elClazz.indexOf(clazz[i]);
                    if (idx>=0) elClazz.splice(idx, 1);
                }
                el.className = elClazz.join(" ");
            },
            _setClass = function(el, clazz) {
                clazz = (clazz||"").replace(/\s+/gi,' ');
                el.className = clazz;
            },
            _resize = function(el, size) {
                if (size && size.w) el.style.width = size.w;
                if (size && size.h) el.style.height = size.h;
            },
            _moveTo = function(el, pos) {
                if (pos && pos.x) el.style.left = pos.x;
                if (pos && pos.y) el.style.top = pos.y;
            },
            _setText = function(el, text) {
                el.innerHTML = (text||"").replace(/</gi, "&lt;");
            },
            _setHTML = function(el, html) {
                el.innerHTML = html;
            },
            _bind = function(el, type, fn) {
                if (el) {
                    if (el.addEventListener) el.addEventListener(type, fn, false);
                    else if (el.attachEvent) {el.attachEvent("on"+type, fn)}
                }
            },
            _unbind = function(el, type, fn) {
                if (el) {
                    if (el.removeEventListener) el.removeEventListener(type, fn, false);
                    else if (el.detachEvent) {el.detachEvent("on"+type, fn)}
                }
            },
            _position = function(oElement, scroll) {
                if (scroll) {
                    if (typeof(oElement.offsetParent) != 'undefined') {
                        var originalElement = oElement;
                        for (var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) {
                            posX += oElement.offsetLeft;
                            posY += oElement.offsetTop;
                            if (oElement != originalElement && oElement != document.body && oElement != document.documentElement) {
                                posX -= oElement.scrollLeft;
                                posY -= oElement.scrollTop;
                            }
                        }
                        return {x: posX, y: posY};
                    } else {
                        return {x: oElement.x, y:oElement.y};
                    }
                } else {
                    if (typeof( oElement.offsetParent ) != 'undefined') {
                        for (var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) {
                            posX += oElement.offsetLeft;
                            posY += oElement.offsetTop;
                        }
                        return {x: posX, y:posY};
                    } else {
                        return {x: oElement.x, y: oElement.y};
                    }
                }
            },
            _formatDuration = function(t) {
                var h = Math.floor(t / 3600),
                        m = Math.floor(t / 60 % 60),
                        s = t % 60;
                var r = "";
                if (h > 0) r += h+":";
                if (m > 0) {
                    r += m>9?m:("0"+m);
                    r += ":";
                } else {
                    r += "00:";
                }
                if (s > 0) {
                    r += s>9?s:("0"+s);
                } else {
                    r += "00";
                }
                return r;
            },
            _tick = function(el, t) {
                if (el) {
                    var ct = new Date().getTime();
                    el.innerHTML = _formatDuration(Math.floor((ct-t)/1000));
                }
            },
            _startTick = function(el) {
                if (el) {
                    var t = new Date().getTime();
                    return setInterval(function() {
                        _tick(el, t);
                    }, 1000);
                }
            },
            _stopTick = function(inter) {
                return clearInterval(inter)
            },
            _wSize = function()  {
                var myWidth = 0, myHeight = 0;
                if( typeof( window.innerWidth ) == 'number' ) {
                    //Non-IE
                    myWidth = window.innerWidth;
                    myHeight = window.innerHeight;
                } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
                    //IE 6+ in 'standards compliant mode'
                    myWidth = document.documentElement.clientWidth;
                    myHeight = document.documentElement.clientHeight;
                } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                    //IE 4 compatible
                    myWidth = document.body.clientWidth;
                    myHeight = document.body.clientHeight;
                }
                return {w: myWidth, h: myHeight}
            },
            _getDimensions = function(element) {
                var display = element.style.display;
                if (display != 'none' && display != null) // Safari bug
                    return {w: element.offsetWidth, h: element.offsetHeight};

                // All *Width and *Height properties give 0 on elements with display none,
                // so enable the element temporarily
                var els = element.style;
                var originalVisibility = els.visibility;
                var originalPosition = els.position;
                var originalDisplay = els.display;
                els.visibility = 'hidden';
                els.position = 'absolute';
                els.display = 'block';
                var originalWidth = element.clientWidth;
                var originalHeight = element.clientHeight;
                els.display = originalDisplay;
                els.position = originalPosition;
                els.visibility = originalVisibility;
                return {w: originalWidth, h: originalHeight};
            }

    return {
        addClass: _addClass,
        removeClass: _removeClass,
        setClass: _setClass,
        resize: _resize,
        wSize: _wSize,
        getDimensions: _getDimensions,
        moveTo: _moveTo,
        setText: _setText,
        setHTML: _setHTML,
        bind: _bind,
        unbind: _unbind,
        position: _position,
        startTick: _startTick,
        stopTick: _stopTick
    }
}();

ITooLabs.ctcFactory = function() {
    var inst = [],
            _getInstance = function(target, lang, params, obj) {
                var ctcObj = ITooLabs.ctc(inst.length, target, lang, params, obj);
                inst.push(ctcObj);
                return ctcObj;
            },
            _init = function() {
                for (var i=0; i<inst.length; i++) {
                    inst[i].init();
                }
            }
    return {
        getInstance: _getInstance,
        init: _init
    }
}();

ITooLabs.ctc = function(id, target, lang, params, obj) {
    var _id = id,
            _target = target,
            _BRIDGE_NAME = "ctcBridge"+_id,
            _flexApp,
            _ximssConn,
            _leg,
            _flashDivHTML = obj==null?"<em id='ctcBtn"+_id+"' class='ctc_button'></em>":null,
            _flashDiv,_infoDiv,_arrDiv,
            _button,
            _flashRendered = false,
            _inter = null,
            _lang = lang||"en",
            _params =  params,
            _obj = obj,
            _win = null,

            _init = function() {
                _button = obj==null?(document.getElementById("ctcBtn"+_id)):(typeof obj == "string"?(document.getElementById(obj)):obj);
                if (_params&ITL_CTC_POPUP) {
                    ITooLabs.dom.bind(_button, "click", _initPopup);
                } else {
                    var c = document.createElement("DIV");
                    c.innerHTML = "<em id='ctcFlashDiv"+id+"' class='ctc_flash'></em>"+(ITL_CTC_POPWIN?"":"<em id='ctcArrDiv"+_id+"' class='ctc_arr'></em>")+"<em id='ctcInfoDiv"+_id+"' class='ctc_info'></em>";
                    var n= c.childNodes;
                    for (var i=0; n.length>0; i++) {
                        _button.parentNode.insertBefore(n[0], _button);
                    }
                    _flashDiv = document.getElementById("ctcFlashDiv"+_id);
                    _infoDiv = document.getElementById("ctcInfoDiv"+_id);
                    _arrDiv = document.getElementById("ctcArrDiv"+_id);
                    if (_params&ITL_CTC_AUTO_CALL)
                        _initFlash();
                    else
                        ITooLabs.dom.bind(_button, "click", _initFlash);
                }
            },
            _initPopup = function() {
                _win = window.open(getCtcScriptBase()+"ctc_popup.html#"+_target+"|"+_lang+"|"+(_params&(255^ITL_CTC_POPUP)), "", "width=230,height=190,toolbar=0,location=0");
            },
            _initFlash = function() {
                if (_flashRendered) return;
                _flashRendered = true;

                flashembed(_flashDiv,
                    { src: getCtcFlashServerURI()+"cgp_proxy/clicktocall_0.1.swf", version:[10, 0], width: 215, height: 138, wmode: "transparent", allowScriptAccess: 'always', onFail: _flashFailed},
                    { update: true, bridgeName: _BRIDGE_NAME }
                );
                if (_flashRendered)
                    FABridge.addInitializationCallback(_BRIDGE_NAME, function() {
                        _flexApp = FABridge[_BRIDGE_NAME].root();
                        _flexApp.addEventListener("MIC_READY", _onMicReady);
                        _flexApp.addEventListener("MIC_FAILED", _onMicFailed);
                        _fireUp();
                    });

            },
            _renderDialpad = function() {
                var html ="";
                html += '<em class="dpad" id="dpad_'+_id+'">';
                html += '<em class="dpad_row"><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>1</em></em><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>2</em></em><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>3</em></em></em>';
                html += '<em class="dpad_row"><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>4</em></em><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>5</em></em><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>6</em></em></em>';
                html += '<em class="dpad_row"><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>7</em></em><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>8</em></em><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>9</em></em></em>';
                html += '<em class="dpad_row"><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>*</em></em><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>0</em></em><em class="dpad_btn" onmouseover="ITooLabs.dom.addClass(this, \'hover\');" onmouseout="ITooLabs.dom.removeClass(this, \'hover\');"><em>#</em></em></em>';
                html += '</em>';

                return html;
            },
            _bindDialpad = function() {
                var dpad = document.getElementById("dpad_"+_id);
                if (dpad) {
                    ITooLabs.dom.bind(dpad, "click", function(e) {
                        var target = null
                        if (e.target) target = e.target;
                        else if (e.srcElement) target = e.srcElement;
                        if (target && target.parentNode && target.parentNode.className && target.parentNode.className.indexOf("dpad_btn") >=0 ) {
                            var c = target.innerHTML;
                            if (c && _leg) _leg.sendDTMF(c);
                        }
                    });
                }
            },
            _hideSettings = function() {
                ITooLabs.dom.resize(_flashDiv, {w: "1px", h: "1px"});
            },
            _showInfo = function(mode, size, ahtml) {
                if (size) ITooLabs.dom.resize(_infoDiv, size);
                else  ITooLabs.dom.resize(_infoDiv, {h:"auto", w:"auto"});

                var html = "<em class='status'>"+(mode=="error"?ITooLabs.ctc.mc[_lang]["error"]:(ITooLabs.ctc.mc[_lang]["status"]+": "+ITooLabs.ctc.mc[_lang]["status_"+mode]))+"</em><em class='top'></em><em class='info'>";
                if (mode == "dialing" || mode == "ringing" || mode == "settings") {
                    html += "<h1 id='ctcInfoH1"+_id+"' class=''>"+ITooLabs.ctc.mc[_lang]["calling"]+"</h1><h2 class='calling'><u id='ctcCancel"+_id+"'>"+ITooLabs.ctc.mc[_lang]["cancel"]+"</u></h2>"
                } else if (mode == "connected") {
                    html += "<h1 id='ctcInfoH1"+_id+"' class=''>"+((_params&&(_params&ITL_CTC_DIALPAD))?_renderDialpad():"")+"<em id='ctcInfoTime"+_id+"'>00:00</em></h1><h2 class='connected'><u id='ctcHangup"+_id+"'>"+ITooLabs.ctc.mc[_lang]["hangup"]+"</u></h2>"
                } else if (mode == "error") {
                    if (ahtml) {
                        html += ahtml;
                        html += "<h2 class='error'><u id='ctcClose"+_id+"'>"+ITooLabs.ctc.mc[_lang]["close"]+"</u></h2>"
                    } else {
                        html += "<h1 id='ctcInfoH1"+_id+"' class=''>404</h1><h2 class='error'><u id='ctcClose"+_id+"'>"+ITooLabs.ctc.mc[_lang]["close"]+"</u></h2>"
                    }
                } else if (mode == "micfailed") {
                    html += "<h1 id='ctcInfoH1"+_id+"' class=''>"+ITooLabs.ctc.mc[_lang]["status_"+mode]+"</h1>";
                    html += "<p>"+ITooLabs.ctc.mc[_lang]["onmicfailed"]+"</p>";
                    html += "<h2 class='error'><u id='ctcOk"+_id+"'>"+ITooLabs.ctc.mc[_lang]["ok"]+"</u>&nbsp;<u id='ctcCancel"+_id+"'>"+ITooLabs.ctc.mc[_lang]["cancel1"]+"</u></h2>"
                }
                html += "</em><em class='bottom'></em>";
                ITooLabs.dom.setHTML(_infoDiv, html);
                if (_arrDiv) {
                    var pos = ITooLabs.dom.position(_button, true);
                    var dsize = ITooLabs.dom.getDimensions(_infoDiv);
                    var wsize = ITooLabs.dom.wSize();
                    var xd = 0, xdd = 0;
                    var yd = 0, ydd = 0;
                    var clazz = "";
                    if (pos.x > wsize.w/2) {
                        xd = 66;
                        xdd = 203;
                        clazz = "right";
                    } else {
                        xd = 0;
                        xdd = 0;
                        clazz = "left";
                    }
                    if (pos.y > wsize.h/2) {
                        yd = 37+16;
                        ydd = dsize.h-1+37+16;
                        clazz += "bottom"
                    } else {
                        yd = 0;
                        ydd = -36;
                        clazz += "top"
                    }
                    ITooLabs.dom.setClass(_arrDiv, "ctc_arr "+clazz)
                    ITooLabs.dom.moveTo(_arrDiv, {x: pos.x+16-xd+"px", y: pos.y+16-yd+"px"});
                    ITooLabs.dom.moveTo(_infoDiv, {x: pos.x+16-xdd+"px", y: pos.y+16-ydd+"px"});
                }
                if (_params&&(_params&ITL_CTC_DIALPAD)) {
                    _bindDialpad();
                }
                if (mode == "settings") {
                    ITooLabs.dom.resize(_flashDiv, {w: "213px", h: "136px"});
                    if (_arrDiv) {
                        dsize = ITooLabs.dom.getDimensions(_flashDiv);
                        xd = 0; xdd = 0;
                        yd = 0; ydd = 0;
                        clazz = "";
                        if (pos.x > wsize.w/2) {
                            xd = 66;
                            xdd = 203;
                            clazz = "right";
                        } else {
                            xd = 0;
                            xdd = 0;
                            clazz = "left";
                        }
                        if (pos.y > wsize.h/2) {
                            yd = 37+16;
                            ydd = dsize.h-1+37+16;
                            clazz += "bottom"
                        } else {
                            yd = 0;
                            ydd = -36;
                            clazz += "top"
                        }
                        ITooLabs.dom.moveTo(_flashDiv, {x: pos.x+16-xdd+"px", y: pos.y+16-ydd+"px"});
                        _arrDiv.style.visibility = "visible";
                    }    
                }
                _infoDiv.style.visibility = "visible";
            },
            _hideInfo = function() {
                ITooLabs.dom.resize(_flashDiv, {w: "1px", h: "1px"});
                if(_arrDiv) _arrDiv.style.visibility = "hidden";
                _infoDiv.style.visibility = "hidden";
                _infoDiv.innerHTML = "";
            },
            _fireUp = function() {
                if (_flexApp) {
                    _flexApp.fireUp()
                    _showInfo("settings");
                 }
            },
            _flashFailed = function() {
                _flashRendered = false;
                var v = flashembed.getVersion();
                _showInfo('error', null, ITooLabs.ctc.mc[_lang]["flashVersion"].replace("^0", v.join(".")));
                ITooLabs.dom.bind(document.getElementById("ctcClose"+_id), "click", function() {_hideInfo(); if(ITL_CTC_POPWIN) self.close();});
            },
            _onMicReady = function () {
                _hideSettings();
                _ximssConn = _flexApp.newXIMSSConnection();
                _ximssConn.addEventListener(XIMSSEvent.CONNECTED, _onConnected);
                _ximssConn.addEventListener(XIMSSEvent.DISCONNECTED, _onDisconnected);
                _ximssConn.addEventListener(XIMSSEvent.CONN_FAILED, _onFailed);
                _ximssConn.addEventListener(XIMSSEvent.LOGIN_FAILED, _onFailed);
                _ximssConn.connect_ctc();
            },
            _onMicFailed = function () {
                _hideSettings();
                _showInfo("micfailed");
                ITooLabs.dom.bind(document.getElementById("ctcOk"+_id), "click", _fireUp);
                ITooLabs.dom.bind(document.getElementById("ctcCancel"+_id), "click", function() {
                    ITooLabs.dom.unbind(_button, "click", _initFlash);
                    ITooLabs.dom.unbind(_button, "click", _hangup);
                    ITooLabs.dom.unbind(_button, "click", _makeCall);
                    ITooLabs.dom.unbind(_button, "click", _fireUp);
                    ITooLabs.dom.bind(_button, "click", _fireUp);
                    _hideInfo();
                    if(ITL_CTC_POPWIN) self.close();
                });
            },
            _onFailed = function(evt) {
                if (_inter) {ITooLabs.dom.stopTick(_inter); _inter = null;};
                var err = evt.getMsg&&evt.getMsg();
                if (err) {
                    _showInfo("error", null, '<h1>'+err+'</h1>');
                    ITooLabs.dom.bind(document.getElementById("ctcClose"+_id), "click", function() {_hideInfo(); if(ITL_CTC_POPWIN) self.close();});
                } else {
                    if (ITL_CTC_POPWIN) self.close();
                }
            },
            _onDisconnected = function(evt) {
                if (_inter) {ITooLabs.dom.stopTick(_inter); _inter = null;};
                _leg = null;
                _ximssConn = null;
                ITooLabs.dom.unbind(_button, "click", _initFlash);
                ITooLabs.dom.unbind(_button, "click", _hangup);
                ITooLabs.dom.unbind(_button, "click", _makeCall);
                ITooLabs.dom.unbind(_button, "click", _fireUp);
                ITooLabs.dom.bind(_button, "click", _onMicReady);
                var err = evt.getMsg&&evt.getMsg();
                if (err) {
                    _showInfo("error", null, '<h1>'+err+'</h1>');
                    ITooLabs.dom.bind(document.getElementById("ctcClose"+_id), "click", function() {_hideInfo(); if(ITL_CTC_POPWIN) self.close();});
                } else {
                    if(ITL_CTC_POPWIN) self.close();
                }
            },
            _onConnected = function() {
                if (_inter) {ITooLabs.dom.stopTick(_inter); _inter = null;};
                var callManager = _ximssConn.getCallManager();
                callManager.addEventListener(CallEvent.CALL_DISCONNECTED, _onCallDisconnected);
                callManager.addEventListener(CallEvent.CALL_CONNECTED, _onCallConnected);
                callManager.addEventListener(CallEvent.CALL_PROVISIONED, _onCallProvisioned);
                _makeCall();
            },
            _onCallProvisioned = function(evt) {
                if (_inter) {ITooLabs.dom.stopTick(_inter); _inter = null;};
                ITooLabs.dom.removeClass(_button, "dialing connected");
                ITooLabs.dom.addClass(_button, "ringing");
                var err = evt.getMsg&&evt.getMsg();
                if (err) {
                    _showInfo("error", null, '<h1>'+err+'</h1>');
                    ITooLabs.dom.bind(document.getElementById("ctcClose"+_id), "click", function() {_hideInfo(); if(ITL_CTC_POPWIN) self.close();});
                } else {
                    _showInfo("ringing");
                    setTimeout(function() {
                        ITooLabs.dom.bind(document.getElementById("ctcCancel"+_id), "click", _hangup)
                    }, 200);
                }
            },
            _onCallConnected = function(evt) {
                if (_inter) {ITooLabs.dom.stopTick(_inter); _inter = null;};
                ITooLabs.dom.removeClass(_button, "dialing ringing");
                ITooLabs.dom.addClass(_button, "connected");
                var err = evt.getMsg&&evt.getMsg();
                if (err) {
                    _showInfo("error", null, '<h1>'+err+'</h1>');
                    ITooLabs.dom.bind(document.getElementById("ctcClose"+_id), "click", function() {_hideInfo(); if(ITL_CTC_POPWIN) self.close();});
                } else {
                    _showInfo("connected");
                    _inter = ITooLabs.dom.startTick(document.getElementById("ctcInfoTime"+_id));
                    setTimeout(function() {
                        ITooLabs.dom.bind(document.getElementById("ctcHangup"+_id), "click", _hangup)
                        ITooLabs.dom.bind(document, "keydown", _dtmf);
                    }, 200);
                }
            },
            _onCallDisconnected = function(evt) {
                if (_inter) {ITooLabs.dom.stopTick(_inter); _inter = null;};
                _hangup(true);
                var err = evt.getMsg&&evt.getMsg();
                if (err) {
                    _showInfo("error", null, '<h1>'+err+'</h1>');
                    ITooLabs.dom.bind(document.getElementById("ctcClose"+_id), "click", function() {_hideInfo(); if(ITL_CTC_POPWIN) self.close();});
                } else {
                    if(ITL_CTC_POPWIN) self.close();
                }
            },
            _makeCall = function() {
                if (_inter) {ITooLabs.dom.stopTick(_inter); _inter = null;};
                _leg = _ximssConn.getCallManager().createLeg();
                _leg.makeCall(_target);
                ITooLabs.dom.removeClass(_button, "ringing connected");
                ITooLabs.dom.addClass(_button, "dialing");
                ITooLabs.dom.unbind(_button, "click", _initFlash);
                ITooLabs.dom.unbind(_button, "click", _makeCall);
                ITooLabs.dom.unbind(_button, "click", _onMicReady);
                ITooLabs.dom.unbind(_button, "click", _fireUp);
                ITooLabs.dom.bind(_button, "click", _hangup);
                _showInfo("dialing");
                setTimeout(function() {
                    ITooLabs.dom.bind(document.getElementById("ctcCancel"+_id), "click", _hangup)
                }, 200);

            },
            _hangup = function(doNotClose) {
                if (_inter) {ITooLabs.dom.stopTick(_inter); _inter = null;};
                if (_leg) _leg.destroy();
                _leg = null;
                _hideInfo();
                if (doNotClose != true && ITL_CTC_POPWIN) self.close();
                else {
                    ITooLabs.dom.removeClass(_button, "dialing ringing connected");
                    ITooLabs.dom.unbind(document, "keydown", _dtmf);
                    ITooLabs.dom.unbind(_button, "click", _initFlash);
                    ITooLabs.dom.unbind(_button, "click", _onMicReady);
                    ITooLabs.dom.unbind(_button, "click", _hangup);
                    ITooLabs.dom.unbind(_button, "click", _fireUp);
                    ITooLabs.dom.bind(_button, "click", _makeCall);
                }
            },
            _dtmf = function(e) {
                var c = null;
                if (e.shiftKey) {
                    switch(e.keyCode) {
                        case 51: c = "#"; break;
                        case 56: c = "*"; break;
                    }
                } else {
                    switch(e.keyCode) {
                        case 48: c = "0"; break;
                        case 49: c = "1"; break;
                        case 50: c = "2"; break;
                        case 51: c = "3"; break;
                        case 52: c = "4"; break;
                        case 53: c = "5"; break;
                        case 54: c = "6"; break;
                        case 55: c = "7"; break;
                        case 56: c = "8"; break;
                        case 57: c = "9"; break;
                        case 106: c = "*"; break;
                        case 107: c = "#"; break;
                    }
                }
                if (c && _leg) {
                    _leg.sendDTMF(c);
                }
            }
    return {
        init: _init,
        getId: function() {return _id},
        getFlashDivHTML: function() {return _flashDivHTML}
    }
}

function itl_ctc(target, lang, params) {
    var inst = ITooLabs.ctcFactory.getInstance(target, lang, params);
    document.write(inst.getFlashDivHTML());
}
function itl_ctc_obj(obj, target, lang, params) {
    var inst = ITooLabs.ctcFactory.getInstance(target, lang, params, obj);
}

ITooLabs.ctc.mc = {
    "en":{
        flashVersion : '<h3>Flash version 10 or greater is required</h3><h3>Your version is ^0</h3><p>Download latest version from <a target="_blank" href="http://www.adobe.com/go/getflashplayer">here</a></p>',
        error : 'Error',
        status : 'Call status',
        status_dialing : 'Calling',
        status_ringing : 'Calling',
        status_connected : 'Talking',
        status_settings : 'Settings',
        status_micfailed : 'Microphone blocked',
        calling : 'Calling...',
        cancel : 'Cancel',
        close : 'Close',
        ok : 'Ok',
        cancel1 : 'Cancel',
        hangup : 'Hangup',
        onmicfailed: 'You must allow access to the microphone in order to make the call. Check "Allow", and press "Close".'
    },
    "ru":{
        flashVersion : '<h3>Необходим Flash версии 10 или выше</h3><h3>Ваша версия ^0</h3><p>Загрузить последнюю версию можно <a target="_blank" href="http://www.adobe.com/go/getflashplayer">здесь</a></p>',
        error : 'Ошибка',
        status : 'Статус звонка',
        status_dialing : 'Звоним',
        status_ringing : 'Звоним',
        status_connected : 'Говорим',
        status_settings : 'Настройки',
        status_micfailed : 'Микрофон не доступен',
        calling : 'Звоним...',
        cancel : 'Завершить',
        close : 'Закрыть',
        ok : 'Ок',
        cancel1 : 'Отмена',
        hangup : 'Положить трубку',
        onmicfailed: 'Для совершения звонка необходимо разрешить использование микрофона. Поставьте галочку напротив "разрешить" и нажмите "закрыть"'
    }
}
ITooLabs.onReady(function() {
    ITooLabs.ctcFactory.init();
});
