// Inspired by base2 and Prototype
(function () {
    var initializing = false,
        fnTest = /xyz/.test(function () {
            xyz;
        }) ? /\b_super\b/ : /.*/;

    // The base Class implementation (does nothing)
    this.Class = function () {};

    // Create a new Class that inherits from this class
    Class.extend = function (prop) {
        var _super = this.prototype;

        // Instantiate a base class (but only create the instance,
        // don't run the init constructor)
        initializing = true;
        var prototype = new this();
        initializing = false;

        // Copy the properties over onto the new prototype
        for (var name in prop) {
            // Check if we're overwriting an existing function
            prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function (name, fn) {
                return function () {
                    var tmp = this._super;

                    // Add a new ._super() method that is the same method
                    // but on the super-class
                    this._super = _super[name];

                    // The method only need to be bound temporarily, so we
                    // remove it when we're done executing
                    var ret = fn.apply(this, arguments);
                    this._super = tmp;

                    return ret;
                };
            })(name, prop[name]) : prop[name];
        }

        // The dummy class constructor
        function Class() {
            // All construction is actually done in the init method
            if (!initializing && this.init) this.init.apply(this, arguments);
        }

        // Populate our constructed prototype object
        Class.prototype = prototype;

        // Enforce the constructor to be what we expect
        Class.constructor = Class;

        // And make this class extendable
        Class.extend = arguments.callee;

        return Class;
    };
})();

var Tweetedia = Class.extend({

    baseUri: 'http://api.tweetology.com',
    imagesUri: 'http://www.tweetology.com/images/widget',

    ident: null,
    isiPad: false,
    //Tweetedia vars
    counter: 0,
    tweetAction: 'update',
    version: null,
    feedId: null,
    tdiaPostUri: null,
    lastTweetId: null,
    oALoggedIn: false,
    //config
    configUri: null,
    config: null,
    skin: null,
    tweetFormat: null,
    feed: null,
    //Google Analytics
    gaCat: null,
    gaQueue: null,
    gaIsLoaded: false,
    gat: null,

    params: {},

    //TISM vars
    tismApi: 'http://www.tism.com/api/',
    s3Url: 'http://s3.amazonaws.com/tism/',

    apiKey: null,
    widgetId: null,

    scriptFound: false,

    scriptNode: null,

    aferLogin: null,

    checkinRunning: false,
    leaderboardTimeout: null,

    chiefPictureId: null,

    //Facebook vars
    fbCounter: 0,
    initialFbItems: 5,
    fbFeed: null,

    jqueryLoaded: false,

    twttrLoaded: false,

    init: function (args) {
        this.version = args.version || 'v3';
        this.params = args.params || {};
        this.ident = args.ident;
        this.container = (args.container != null) ? jCue('#' + args.container) : null;
        this.isiPad = (navigator.userAgent.match(/iPad/i) != null);

        this._manageTwitterText();

        //Google Analytics
        this.gaQueue = new Array();
        (function () {
            var ga = document.createElement('script');
            ga.type = 'text/javascript';
            ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(ga, s);
        })();

        if (args.ident.length > 8) {
            var self = this;
            this.feedId = args.ident.substring(8);
            this.gaCat = 'Feed_' + this.feedId;
            this.configUri = this.baseUri + '/' + this.version + '/config-jsonp/id/' + this.feedId;

            this._manageJquery();

            var bootstrapInterval = setInterval(function () {
                if (self.jqueryLoaded == true) {
                    clearInterval(bootstrapInterval);

                    try {
                        if (typeof(jCue) != 'object' && typeof(jCue) != 'function') {
                            throw new Error('jQuery could not be loaded/assigned to jCue');
                        }

                        self._postJquery();
                    } catch (e) {
                        self._log(e);

                        return false;
                    }
                }
            }, 150);
        } else {
            this._log('Invalid ident: parameter');
            return false;
        }
    },

    _manageJquery: function () {
        var self = this;

        if (typeof(jQuery) != 'object' && typeof(jQuery) != 'function') {
            self._lazyLoad.js('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js', function () {
                window.jCue = jQuery;

                self.jqueryLoaded = true;
            });
        } else {
            var jQueryVersion = self._parseVersionString(jQuery.fn.jquery);

            if (jQueryVersion.minor < 4) {
                self._lazyLoad.js('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js', function () {

                    window.jCue = jQuery.noConflict(true);

                    self.jqueryLoaded = true;
                });
            } else {
                window.jCue = jQuery;

                self.jqueryLoaded = true;
            }
        }
    },

    _parseVersionString: function (ver) {
        if (typeof(ver) != 'string') {
            return false;
        }

        var x = ver.split('.');
        // parse from string or default to 0 if can't parse
        var maj = parseInt(x[0]) || 0;
        var min = parseInt(x[1]) || 0;
        var pat = parseInt(x[2]) || 0;
        return {
            major: maj,
            minor: min,
            patch: pat
        }
    },

    _lazyLoad: {
        d: document,
        head: null,
        pending: {},
        queue: {
            css: [],
            js: []
        },
        ua: null,

        createNode: function (name, attrs) {
            var node = this.d.createElement(name),
                attr;

            for (attr in attrs) {
                if (attrs.hasOwnProperty(attr)) {
                    node.setAttribute(attr, attrs[attr]);
                }
            }

            return node;
        },

        finish: function (type) {
            var p = this.pending[type];

            if (!p) {
                return;
            }

            var callback = p.callback,
                urls = p.urls;

            urls.shift();

            // If this is the last of the pending URLs, execute the callback and
            // start the next request in the queue (if any).
            if (!urls.length) {
                if (callback) {
                    callback.call(p.scope || window, p.obj);
                }

                this.pending[type] = null;

                if (this.queue[type].length) {
                    this.load(type);
                }
            }
        },

        getUserAgent: function () {
            // No need to run again if ua is already populated.
            if (this.ua) {
                return;
            }

            var nua = navigator.userAgent,
                pF = parseFloat,
                m;

            this.ua = {
                gecko: 0,
                ie: 0,
                opera: 0,
                webkit: 0
            };

            m = nua.match(/AppleWebKit\/(\S*)/);

            if (m && m[1]) {
                this.ua.webkit = pF(m[1]);
            } else {
                m = nua.match(/MSIE\s([^;]*)/);

                if (m && m[1]) {
                    this.ua.ie = pF(m[1]);
                } else if ((/Gecko\/(\S*)/).test(nua)) {
                    this.ua.gecko = 1;

                    m = nua.match(/rv:([^\s\)]*)/);

                    if (m && m[1]) {
                        this.ua.gecko = pF(m[1]);
                    }
                } else if (m = nua.match(/Opera\/(\S*)/)) {
                    this.ua.opera = pF(m[1]);
                }
            }
        },

        load: function (type, urls, callback, obj, scope) {
            var self = this;

            var i, len, node, p, url;

            // Determine browser type and version.
            this.getUserAgent();

            if (urls) {
                // Cast urls to an Array.
                urls = urls.constructor === Array ? urls : [urls];

                // Create a request object for each URL. If multiple URLs are specified,
                // the callback will only be executed after all URLs have been loaded.
                //
                // Sadly, Firefox and Opera are the only browsers capable of loading
                // scripts in parallel while preserving execution order. In all other
                // browsers, scripts must be loaded sequentially.
                //
                // All browsers respect CSS specificity based on the order of the link
                // elements in the DOM, regardless of the order in which the stylesheets
                // are actually downloaded.
                if (type === 'css' || this.ua.gecko || this.ua.opera) {
                    this.queue[type].push({
                        urls: [].concat(urls),
                        // concat ensures copy by value
                        callback: callback,
                        obj: obj,
                        scope: scope
                    });
                } else {
                    for (i = 0, len = urls.length; i < len; ++i) {
                        this.queue[type].push({
                            urls: [urls[i]],
                            callback: i === len - 1 ? callback : null,
                            // callback is only added to the last URL
                            obj: obj,
                            scope: scope
                        });
                    }
                }
            }

            // If a previous load request of this type is currently in progress, we'll
            // wait our turn. Otherwise, grab the next item in the queue.
            if (this.pending[type] || !(p = this.pending[type] = this.queue[type].shift())) {
                return;
            }

            var head = this.head || this.d.getElementsByTagName('head')[0];
            urls = p.urls;

            for (i = 0, len = urls.length; i < len; ++i) {
                url = urls[i];

                if (type === 'css') {
                    node = createNode('link', {
                        href: url,
                        rel: 'stylesheet',
                        type: 'text/css'
                    });
                } else {
                    node = this.createNode('script', {
                        src: url
                    });
                }

                if (this.ua.ie) {
                    node.onreadystatechange = function () {
                        var readyState = this.readyState;

                        if (readyState === 'loaded' || readyState === 'complete') {
                            this.onreadystatechange = null;
                            self.finish(type);
                        }
                    };
                } else if (type === 'css' && (ua.gecko || ua.webkit)) {
                    // Gecko and WebKit don't support the onload event on link nodes, so we
                    // just have to finish after a brief delay and hope for the best.
                    setTimeout(function () {
                        self.finish(type);
                    }, 50 * len);
                } else {
                    node.onload = node.onerror = function () {
                        self.finish(type);
                    };
                }

                head.appendChild(node);
            }
        },

        css: function (urls, callback, obj, scope) {
            this.load('css', urls, callback, obj, scope);
        },

        js: function (urls, callback, obj, scope) {
            this.load('js', urls, callback, obj, scope);
        }
    },

    _postJquery: function () {
        var self = this;

        this._findScript();

        if (this.scriptFound != true) {
            this._log('Tweetedia container not found in DOM tree');

            return false;
        }

        if(typeof(SHARETHIS) == 'undefined') {
            jCue('head').prepend('<script type="text/javascript" src="http://w.sharethis.com/button/sharethis.js#publisher=8c503049-6fab-4b5d-9d5f-788e3c4c8f31&amp;type=website&amp;buttonText=&amp;post_services=email%2Ctwitter%2Cfacebook%2Cmyspace%2Creddit%2Cdigg&amp;button=false&onmouseover=false"></script>');
        }

        self._loadPlugins();

        jCue.ajax({
            url: this.configUri,
            dataType: 'jsonp',
            cache: false,
            jsonpCallback: 'getConfig',
            success: function (response) {
                if (response.status == 1) {
                    self.config = response;
                    //validate API key
                    if (self.configMode == false) {
                        var titleStart = self.config['titleFormat'].indexOf('<b>');
                        var titleEnd = self.config['titleFormat'].search('</b>');
                        var apiKey = hex_md5(self.config['titleFormat'].substring(parseInt(titleStart) + 3, parseInt(titleEnd)));
                        if (self.ident.substring(0, 8) != apiKey.substring(0, 8)) {
                            self._log('Invalid API key');
                            return false;
                        }

                    }
                    self._getFeed();
                }
            }
        });
    },

    _loadPlugins: function () {
        jCue.event.special.mousewheel = {
            setup: function () {
                var handler = jCue.event.special.mousewheel.handler;

                // Fix pageX, pageY, clientX and clientY for mozilla
                if (jCue.browser.mozilla) jCue(this).bind('mousemove.mousewheel', function (event) {
                    jCue.data(this, 'mwcursorposdata', {
                        pageX: event.pageX,
                        pageY: event.pageY,
                        clientX: event.clientX,
                        clientY: event.clientY
                    });
                });

                if (this.addEventListener) this.addEventListener((jCue.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
                else this.onmousewheel = handler;
            },

            teardown: function () {
                var handler = jCue.event.special.mousewheel.handler;

                jCue(this).unbind('mousemove.mousewheel');

                if (this.removeEventListener) this.removeEventListener((jCue.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
                else this.onmousewheel = function () {};

                jCue.removeData(this, 'mwcursorposdata');
            },

            handler: function (event) {
                var args = Array.prototype.slice.call(arguments, 1);

                event = jCue.event.fix(event || window.event);
                // Get correct pageX, pageY, clientX and clientY for mozilla
                jCue.extend(event, jCue.data(this, 'mwcursorposdata') || {});
                var delta = 0,
                    returnValue = true;

                if (event.wheelDelta) delta = event.wheelDelta / 120;
                if (event.detail) delta = -event.detail / 3;
                //		if ( jCue.browser.opera  ) delta = -event.wheelDelta;
                event.data = event.data || {};
                event.type = "mousewheel";

                // Add delta to the front of the arguments
                args.unshift(delta);
                // Add event to the front of the arguments
                args.unshift(event);

                return jCue.event.handle.apply(this, args);
            }
        };

        jCue.fn.extend({
            mousewheel: function (fn) {
                return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
            },

            unmousewheel: function (fn) {
                return this.unbind("mousewheel", fn);
            }
        });

        jCue.fn.tinyTips = function (b) {
            var c = '<div class="tinyTip"><div class="tiptext"></div></div>';
            var d = 200;
            var e;
            var f;
            jCue(this).hover(function () {
                jCue(this).parent().append(c);
                e = jCue("div.tinyTip");
                e.hide();
                if (b === "title") {
                    var g = jCue(this).attr("title")
                } else {
                    if (b !== "title") {
                        var g = b
                    }
                }
                jCue(".tinyTip .tiptext").html(g);
                f = jCue(this).attr("title");
                jCue(this).attr("title", "");
                var j = (((e.height() - 10) / 2)) - (jCue(this).height() / 2);
                var h = -23;
                var k = jCue(this).position();
                var i = k;
                i.top = k.top - j;
                i.left = k.left - h;
                e.css("position", "absolute").css("z-index", "1000");
                e.css(i).fadeIn(d)
            }, function () {
                jCue(this).attr("title", f);
                jCue("div.tinyTip").fadeOut(d, function () {
                    jCue(this).remove()
                })
            })
        }

        /*
         * jqModal - Minimalist Modaling with jQuery
         *   (http://dev.iceburg.net/jquery/jqModal/)
         *
         * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
         * Dual licensed under the MIT and GPL licenses:
         *   http://www.opensource.org/licenses/mit-license.php
         *   http://www.gnu.org/licenses/gpl.html
         *
         * $Version: 03/01/2009 +r14
         */
        jCue.fn.jqm=function(o){
            var p={
                overlay: 50,
                overlayClass: 'jqmOverlay',
                closeClass: 'jqmClose',
                trigger: '.jqModal',
                ajax: F,
                ajaxText: '',
                target: F,
                modal: F,
                toTop: F,
                onShow: F,
                onHide: F,
                onLoad: F
            };
            return this.each(function(){if(this._jqm)return H[this._jqm].c=jCue.extend({},H[this._jqm].c,o);s++;this._jqm=s;
            H[s]={c:jCue.extend(p,jCue.jqm.params,o),a:F,w:jCue(this).addClass('jqmID'+s),s:s};
            if(p.trigger)jCue(this).jqmAddTrigger(p.trigger);
            });};

            jCue.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
            jCue.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
            jCue.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;jCue.jqm.open(this._jqm,t);});};
            jCue.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;jCue.jqm.close(this._jqm,t)});};

            jCue.jqm = {
            hash:{},
            open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=jCue('<div></div>').css({height:'100%',width:'100%',position:'absolute',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
             if(c.modal) {if(!A[0])L('bind');A.push(s);}
             else if(c.overlay > 0)h.w.jqmAddClose(o);
             else o=F;

             h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
             if(ie6){jCue('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

             if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?jCue(r,h.w):jCue(r),u=(u.substr(0,1) == '@')?jCue(t).attr(u.substring(1)):u;
              r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose(jCue(cc,h.w));e(h);});}
             else if(cc)h.w.jqmAddClose(jCue(cc,h.w));

             if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);
             (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
            },
            close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
             if(A[0]){A.pop();if(!A[0])L('unbind');}
             if(h.c.toTop&&h.o)jCue('#jqmP'+h.w[0]._jqm).after(h.w).remove();
             if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
            },
            params:{}};
            var s=0,H=jCue.jqm.hash,A=[],ie6=jCue.browser.msie&&(jCue.browser.version == "6.0"),F=false,
            i=jCue('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
            e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!jCue('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
            f=function(h){try{jCue(':input:visible',h.w)[0].focus();}catch(_){}},
            L=function(t){jCue()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
            m=function(e){var h=H[A[A.length-1]],r=(!jCue(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
            hs=function(w,t,c){return w.each(function(){var s=this._jqm;jCue(t).each(function() {
             if(!this[c]){this[c]=[];jCue(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});
        };
    },

    _getFeed: function () {
        var self = this;
        jCue.ajax({
            url: this.config['feed'],
            dataType: 'jsonp',
            cache: false,
            jsonpCallback: 'getTdiaFeed',
            success: function (response) {
                self.feed = response;
                self._addEvent('Tweet Feed Loaded');
                self._postInit();
            }
        });
    },

    _postInit: function () {
        var self = this;
        this.skin = this.config['skin'];
        this.tweetFormat = this.skin['tweetFormat'];
        if (this.feed['tweet'] != null && this.feed['tweet'] != 'undefined') this.counter = this.feed['tweet'].length;
		if(typeof(this.config['maxItems']) == 'undefined') this.config['maxItems'] = 50;

        var siteDoctype = this._getDoctype();
        xhtml = siteDoctype.xhtml;
        if(siteDoctype.version == '4.01' && siteDoctype.importance == 'Transitional') {
            xhtml = 'XHTML';
        }

        //fb config
        if (this.config['hasFB']) {
            //this.fbFeed = this._getUri(this.baseUri + '/v3/TwitterOAuth.php?fbtwit=Facebook');
            //if (this.fbFeed['status'] != 0) this.fbCounter = this.fbFeed['feed'].length;
        }

        this._buildWidget();
        if (this.isiPad) {
            jCue('#tdia .content-wrapper').append('<div class="ipad ipad-down"><span></span></div><div class="ipad ipad-up"><span></span></div>');
        }
        this._attachEvents();
        this._log('Widget Placed in DOM');
        this._addEvent('Initialized');
        if (this.isiPad) this._addEvent('iPad');

        //set view
        jCue('#tdia .content, #tdia .content-messages').hide();
        if (this.config['ad']['show'] == 1 && this.config['type'] == 1) {
            jCue('#tdia .content-ad').show();
            jCue('#tdia .content-ad').css({
                'background': '#cccccc'
            });
        }
        jCue('#tdia input:password').hide();
        //set widget styles and defaults
        jCue('#tdia').css({
            'height': this.config['height'],
            'width': this.config['width']
        });
        jCue('#tdia .tdiawidget').css({
            'background-color': this.skin['background'],
            'border-color': this.skin['backgroundBorder'],
            'height': this.config['height'],
            'width': this.config['width'] - 6
        });
	if(self._isIE()) { jCue('#tdia .tdiawidget').css('width', this.config['width']); }
	if(self._isIE()) { jCue('#tdia .content-wrapper').css({'overflow':'hidden','width':this.config['width']-6}); jCue('#tdia .content-tweets').css('width', this.config['width'] - 6); }
        if (typeof(this.skin['customLogo']) != 'undefined' && this.skin['customLogo'] == 'top' && typeof(this.skin['customLogoUri']) != 'undefined') {
            var custImage = new Image();
            custImage.onload = function () {
                jCue('#tdia .head').prepend('<img src="' + self.skin['customLogoUri'] + '" style="margin-top:3px;" />');
                var heightTimer = setInterval(function() {
                    if(jCue('#tdia .head img:first').height() > 0) {
                        clearInterval(heightTimer);
                        var heightDiff = (typeof(self.skin['showTitle']) != 'undefined' && self.skin['showTitle'] == 0) ? (0-33) : 4;
                        jCue('#tdia').height(jCue('#tdia').height()+jCue('#tdia .head img:first').height()+heightDiff);
                        jCue('#tdia .tdiawidget').height(jCue('#tdia .tdiawidget').height()+jCue('#tdia .head img:first').height()+heightDiff);
                        jCue('#tdia .head').height(jCue('#tdia .head').height()+jCue('#tdia .head img:first').height()+heightDiff);
                    }
                }, 500);
            }
            custImage.src = self.skin['customLogoUri'];
        }
        jCue('#tdia .head').css({
            'background': this.skin['background']
        });
        var IEtitle = (self._isIE()) ? 5 : 0;
        var titleWidth = parseInt(jCue('#tdia .tdiawidget').width()) - 4 - IEtitle;
        jCue('#tdia .head li img').each(function () {
            titleWidth -= jCue(this).width();
        });
        jCue('#tdia .head li.title-text').html(this.config['titleFormat']).width(titleWidth);
        jCue('#tdia .view-share').width(this.config['width'] - 6);
        jCue('#tdia .jtc-message').val(this.skin['tweetInputPrompt']);
        var IEfix = 0;
        var IEFixOuter = 0;
        if (self._isIE()) {
            IEfix = 10;
            IEFixOuter = 10;
            if (xhtml == "XHTML") {
                IEFixOuter = 0;
            }
        }

        jCue('#tdia .content-wrapper, #tdia .content-tweets').css({
            'height': this.config['height'] - 100 + IEFixOuter
        });
        jCue('#tdia .content').css({
            'height': this.config['height'] - 100 + IEFixOuter
        });
        jCue('#tdia .tweets').css({
            'height': this.config['height'] - 100 - IEfix,
            'width' : this.config['width'] - 6
        });
        if (this.isiPad) {
            jCue('#tdia .content-tweets').css({
                'height': this.config['height'] - 140,
                'overflow': 'hidden',
                'top': '0px'
            });
        }

        //show ad
        if (this.config['ad']['show'] == 1) {
            var size = this.config['ad']['sz'].split('x');
            var adFrame = '<iframe width="' + size[0] + '" scrolling="no" height="' + size[1] + '" frameborder="0" src="' + this.config['ad']['target'].replace('http => ', 'http:') + '" marginwidth="0" marginheight="0" ';
            if (this.config['type'] == 1) {
                adFrame += 'style="margin-left:-3px;" ';
            }
            adFrame += '/>';

            var light = (this.skin['sponsorTextColor'] == 'light') ? '-light' : '';
            switch (this.config['type']) {
            case 1:
                jCue('#tdia .footer .sponsor-text').html('Sponsor Info <img src="' + this.imagesUri + '/sponsor-arrow-down' + light + '.png" style="vertical-align:middle; padding-bottom:2px;" />').css({
                    'cursor': 'pointer'
                });
                jCue('#tdia .content-ad .ad-image').html(adFrame);
                var adTimer = setTimeout(function () {
                    jCue('#tdia .sponsor-text').html('Sponsor Info <img src="' + self.imagesUri + '/sponsor-arrow' + light + '.png" style="vertical-align:middle; padding-bottom:2px;" />');
                    jCue('#tdia .content-ad').slideUp(500);
                }, 6000);
                break;
            case 2:
                jCue('#tdia .footer .sponsor-text').hide();
                jCue('#tdia').append(adFrame);
                if (self._isIE()) {
                    jCue('#tdia').height(parseInt(parseInt(jCue('#tdia').height()) + parseInt(size[1])) + 'px');
                }
                break;
            }
        }
        if (this.config['ad']['show'] == 0 || this.config['type'] == 2) {
            jCue('#tdia .content-ad').hide();
            jCue('#tdia .footer .sponsor-text').hide();
            jCue('#tdia .footer a.powered-by').css({
                'margin': '20px 5px 0 0'
            });
        }

        //show tweet list
        var tempInitial = (typeof(this.config['initialItems']) != 'undefined') ? this.config['initialItems'] : 8;

        this.initialTweets = this.counter - tempInitial;

        if(this.initialTweets < 0) {
        	this.initialTweets = 0;
        }

	if(typeof(console) == 'object') {
		console.log('Tweets available: ' + this.counter + ' :: Initial Tweets: ' + this.initialTweets);
	}

        for (this.counter; this.counter > this.initialTweets; this.counter--) {
        	if (this._getNextTweet(this.counter) !== null) {
                this._addItem('#tdia .tweets .makescroll', this._getNextTweet(this.counter));
                jCue('#tdia .tweet .btns:first li').tinyTips('title');
            }
        }

        //add modal dialog box for system messages
        jCue('#tdia .content-messages').jqm({modal:true, overlay:25});

        if (!this.isiPad) this._loadScrollpane();
        this._showTweets();
    },

    _getDoctype: function() {
        function versionInfo()
        {
            this.xhtml="";
            this.version="";
            this.importance="";
        }

        function detectDoctype(){
            var re=/\s+(X?HTML)\s+([\d\.]+)\s*([^\/]+)*\//gi;
            var myversionInfo=new versionInfo();
            if(typeof document.namespaces != "undefined"){
                if(document.all[0].nodeType==8)
                    re.exec(document.all[0].nodeValue);
                else
                    return null;
            }else{
                if(document.doctype != null)
                    re.exec(document.doctype.publicId);
                else
                    return null;
            }
            myversionInfo.xhtml=RegExp.$1;
            myversionInfo.version=RegExp.$2;
            myversionInfo.importance=RegExp.$3;
            return myversionInfo;
        }

        var myversionInfo=detectDoctype();

        if(myversionInfo == null) {
            return false;
        }

        return myversionInfo;
  	},

    _findScript: function () {
        var self = this;

        jCue('script').each(function () {
            if ((typeof(jCue(this).attr('defer')) == 'undefined' || jCue(this).attr('defer') == false) && jCue(this).html().search(/new Tweetedia\(/) != -1) {
                self.scriptFound = true;

                self.scriptNode = jCue(this);

                jCue(this).attr('defer', true);

                return true;
            }
        });

        return false;
    },

    _loadScrollpane: function () {
        var self = this;
        (function (A) {
            A.jScrollPane = {
                active: []
            };
            A.fn.jScrollPane = function (C) {
                C = A.extend({}, A.fn.jScrollPane.defaults, C);
                var B = function () {
                    return false
                };
                return this.each(function () {
                    var O = A(this);
                    O.css("overflow", "hidden");
                    var X = this;
                    if (A(this).parent().is(".jScrollPaneContainer")) {
                        var Ac = C.maintainPosition ? O.position().top : 0;
                        var L = A(this).parent();
                        var d = L.innerWidth();
                        var Ad = L.outerHeight();
                        var M = Ad;A(">.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown", L).remove();O.css({
                            top: 0
                        })
                    } else {
                        var Ac = 0;
                        this.originalPadding = O.css("paddingTop") + " " + O.css("paddingRight") + " " + O.css("paddingBottom") + " " + O.css("paddingLeft");
                        this.originalSidePaddingTotal = (parseInt(O.css("paddingLeft")) || 0) + (parseInt(O.css("paddingRight")) || 0);
                        var d = O.innerWidth();
                        var Ad = O.innerHeight();
                        var M = Ad;
			if(self._isIE()) {
				Ad = parseInt(Ad + 10);
				M = Ad;
			}
                        O.wrap(A("<div></div>").attr({
                            className: "jScrollPaneContainer"
                        }).css({
                            height: Ad + "px",
                            width: d + "px"
                        }));
                        A(document).bind("emchange", function (Ae, Af, p) {
                            O.jScrollPane(C)
                        })
                    }
                    if (C.reinitialiseOnImageLoad) {
                        var N = A.data(X, "jScrollPaneImagesToLoad") || A("img", O);
                        var G = [];
                        if (N.length) {
                            N.each(function (p, Ae) {
                                A(this).bind("load", function () {
                                    if (A.inArray(p, G) == -1) {
                                        G.push(Ae);
                                        N = A.grep(N, function (Ag, Af) {
                                            return Ag != Ae
                                        });
                                        A.data(X, "jScrollPaneImagesToLoad", N);
                                        C.reinitialiseOnImageLoad = false;
                                        O.jScrollPane(C)
                                    }
                                }).each(function (Af, Ag) {
                                    if (this.complete || this.complete === undefined) {
                                        this.src = this.src
                                    }
                                })
                            })
                        }
                    }
                    var o = this.originalSidePaddingTotal;
                    var l = {
                        height: "auto",
                        width: d - C.scrollbarWidth - C.scrollbarMargin - o + "px"
                    };
                    if (C.scrollbarOnLeft) {
                        l.paddingLeft = C.scrollbarMargin + C.scrollbarWidth + "px"
                    } else {
                        l.paddingRight = C.scrollbarMargin + "px"
                    }
                    O.css(l);
                    var m = O.outerHeight();
                    var i = Ad / m;
                    if (i < 0.99) {
                        var H = O.parent();
                        H.append(A("<div></div>").attr({
                            className: "jScrollPaneTrack"
                        }).css({
                            width: C.scrollbarWidth + "px"
                        }).append(A('<div></div>').attr({
                            className: "jScrollPaneDrag"
                        }).css({
                            width: C.scrollbarWidth + "px"
                        }).append(A("<div></div>").attr({
                            className: "jScrollPaneDragTop"
                        }).css({
                            width: C.scrollbarWidth + "px"
                        }), A("<div></div>").attr({
                            className: "jScrollPaneDragBottom"
                        }).css({
                            width: C.scrollbarWidth + "px"
                        }))));
                        var z = A(">.jScrollPaneTrack", H);
                        var P = A(">.jScrollPaneTrack .jScrollPaneDrag", H);
                        if (C.showArrows) {
                            var g;
                            var Ab;
                            var S;
                            var r;
                            var j = function () {
                                if (r > 4 || r % 4 == 0) {
                                    y(u + Ab * b)
                                }
                                r++
                            };
                            var K = function (p) {
                                A("html").unbind("mouseup", K);
                                g.removeClass("jScrollActiveArrowButton");
                                clearInterval(S)
                            };
                            var Z = function () {
                                A("html").bind("mouseup", K);
                                g.addClass("jScrollActiveArrowButton");
                                r = 0;
                                j();
                                S = setInterval(j, 100)
                            };
                            H.append(A("<a></a>").attr({
                                href: "javascript:;",
                                className: "jScrollArrowUp"
                            }).css({
                                width: C.scrollbarWidth + "px"
                            }).html("").bind("mousedown", function () {
                                g = A(this);
                                Ab = -1;
                                Z();
                                this.blur();
                                return false
                            }).bind("click", B), A("<a></a>").attr({
                                href: "javascript:;",
                                className: "jScrollArrowDown"
                            }).css({
                                width: C.scrollbarWidth + "px"
                            }).html("").bind("mousedown", function () {
                                g = A(this);
                                Ab = 1;
                                Z();
                                this.blur();
                                return false
                            }).bind("click", B));
                            var Q = A(">.jScrollArrowUp", H);
                            var J = A(">.jScrollArrowDown", H);
                            if (C.arrowSize) {
                                M = Ad - C.arrowSize - C.arrowSize;
                                z.css({
                                    height: M + "px",
                                    top: C.arrowSize + "px"
                                })
                            } else {
                                var s = Q.height();
                                C.arrowSize = s;
                                M = Ad - s - J.height();
                                z.css({
                                    height: M + "px",
                                    top: s + "px"
                                })
                            }
                        }
                        var w = A(this).css({
                            position: "absolute",
                            overflow: "visible"
                        });
                        var D;
                        var Y;
                        var b;
                        var u = 0;
                        var V = i * Ad / 2;
                        var a = function (Ae, Ag) {
                            var Af = Ag == "X" ? "Left" : "Top";
                            return Ae["page" + Ag] || (Ae["client" + Ag] + (document.documentElement["scroll" + Af] || document.body["scroll" + Af])) || 0
                        };
                        var f = function () {
                            return false
                        };
                        var v = function () {
                            n();
                            D = P.offset(false);
                            D.top -= u;
                            Y = M - P[0].offsetHeight;
                            b = 2 * C.wheelSpeed * Y / m
                        };
                        var E = function (p) {
                            v();
                            V = a(p, "Y") - u - D.top;
                            A("html").bind("mouseup", T).bind("mousemove", h);
                            if (A.browser.msie) {
                                A("html").bind("dragstart", f).bind("selectstart", f)
                            }
                            return false
                        };
                        var T = function () {
                            A("html").unbind("mouseup", T).unbind("mousemove", h);
                            V = i * Ad / 2;
                            if (A.browser.msie) {
                                A("html").unbind("dragstart", f).unbind("selectstart", f)
                            }
                        };
                        var y = function (Ae) {
                            Ae = Ae < 0 ? 0 : (Ae > Y ? Y : Ae);u = Ae;P.css({
                                top: Ae + "px"
                            });
                            var Af = Ae / Y;w.css({
                                top: ((Ad - m) * Af) + "px"
                            });O.trigger("scroll");
                            if (C.showArrows) {
                                Q[Ae == 0 ? "addClass" : "removeClass"]("disabled");
                                J[Ae == Y ? "addClass" : "removeClass"]("disabled")
                            }
                        };
                        var h = function (p) {
                            y(a(p, "Y") - D.top - V)
                        };
                        var q = Math.max(Math.min(i * (Ad - C.arrowSize * 2), C.dragMaxHeight), C.dragMinHeight);
                        P.css({
                            height: q + "px"
                        }).bind("mousedown", E);
                        var k;
                        var R;
                        var I;
                        var t = function () {
                            if (R > 8 || R % 4 == 0) {
                                y((u - ((u - I) / 2)))
                            }
                            R++
                        };
                        var Aa = function () {
                            clearInterval(k);
                            A("html").unbind("mouseup", Aa).unbind("mousemove", e)
                        };
                        var e = function (p) {
                            I = a(p, "Y") - D.top - V
                        };
                        var U = function (p) {
                            v();
                            e(p);
                            R = 0;
                            A("html").bind("mouseup", Aa).bind("mousemove", e);
                            k = setInterval(t, 100);
                            t()
                        };
                        z.bind("mousedown", U);
                        H.bind("mousewheel", function (Ae, Ag) {
                            v();
                            n();
                            var Af = u;
                            y(u - Ag * b);
                            var p = Af != u;
                            return !p
                        });
                        var F;
                        var W;

                        function c() {
                            var p = (F - u) / C.animateStep;
                            if (p > 1 || p < -1) {
                                y(u + p)
                            } else {
                                y(F);
                                n()
                            }
                        }
                        var n = function () {
                            if (W) {
                                clearInterval(W);
                                delete F
                            }
                        };
                        var x = function (Af, p) {
                            if (typeof Af == "string") {
                                $e = A(Af, O);
                                if (!$e.length) {
                                    return
                                }
                                Af = $e.offset().top - O.offset().top
                            }
                            H.scrollTop(0);
                            n();
                            var Ae = -Af / (Ad - m) * Y;
                            if (p || !C.animateTo) {
                                y(Ae)
                            } else {
                                F = Ae;
                                W = setInterval(c, C.animateInterval)
                            }
                        };
                        O[0].scrollTo = x;
                        O[0].scrollBy = function (Ae) {
                            var p = -parseInt(w.css("top")) || 0;
                            x(p + Ae)
                        };
                        v();
                        x(-Ac, true);
                        A("*", this).bind("focus", function (Ah) {
                            var Ag = A(this);
                            var Aj = 0;
                            while (Ag[0] != O[0]) {
                                Aj += Ag.position().top;
                                Ag = Ag.offsetParent()
                            }
                            var p = -parseInt(w.css("top")) || 0;
                            var Ai = p + Ad;
                            var Af = Aj > p && Aj < Ai;
                            if (!Af) {
                                var Ae = Aj - C.scrollbarMargin;
                                if (Aj > p) {
                                    Ae += A(this).height() + 15 + C.scrollbarMargin - Ad
                                }
                                x(Ae)
                            }
                        });
                        if (location.hash) {
                            x(location.hash)
                        }
                        A(document).bind("click", function (Ae) {
                            $target = A(Ae.target);
                            if ($target.is("a")) {
                                var p = $target.attr("href");
                                if (typeof(p) != 'undefined' && p.substr(0, 1) == "#") {
                                    x(p)
                                }
                            }
                        });
                        A.jScrollPane.active.push(O[0])
                    } else {
                        O.css({
                            height: Ad + "px",
                            width: d - this.originalSidePaddingTotal + "px",
                            padding: this.originalPadding
                        });
                        O.parent().unbind("mousewheel")
                    }
                })
            };
            A.fn.jScrollPane.defaults = {
                scrollbarWidth: 13,
                scrollbarMargin: 5,
                wheelSpeed: 18,
                showArrows: false,
                arrowSize: 0,
                animateTo: false,
                dragMinHeight: 1,
                dragMaxHeight: 99999,
                animateInterval: 100,
                animateStep: 3,
                maintainPosition: true,
                scrollbarOnLeft: false,
                reinitialiseOnImageLoad: false
            };
            A(window).bind("unload", function () {
                var C = A.jScrollPane.active;
                for (var B = 0; B < C.length; B++) {
                    C[B].scrollTo = C[B].scrollBy = null
                }
            })
        })(jCue);
    },

    _addEvent: function (event) {
        if (this.gaIsLoaded) {
            this.gat._trackEvent(this.gaCat, event);
        } else {
            this.gaQueue.push(event);
            if (typeof(_gat) != 'undefined') {
                this.gat = _gat._getTracker('UA-11924326-2');
                this.gat._setDomainName('none');
                this.gat._trackPageview();
                for (var i in this.gaQueue) {
                    this.gat._trackEvent(this.gaCat, this.gaQueue[i]);
                }
                this.gaIsLoaded = true;
            }
        }
    },

    _buildStyles: function () {
        var scrollColorFlag = false;
        var scrollColor = this.skin['scrollButtonDetail'];
        scrollColor = scrollColor.substr(1);
        var tester = new Image();
        tester.onLoad = function () {
            scrollColorFlag = true;
        };
        tester.src = this.imagesUri + '/scrollbar-top-' + scrollColor + '.png';

        if(typeof(this.skin['scrollbarDetailColor']) != 'undefined') {
        	scrollColor = this.skin['scrollbarDetailColor'].replace("#","");
        } else {
        	scrollColor = "ffffff";
        }

		sponsorTextColor = '#000000';
        if (typeof (this.skin['sponsorTextColor']) != 'undefined') {
			if (this.skin['sponsorTextColor'] == 'light') {
				sponsorTextColor = '#ffffff';
			} else {
				sponsorTextColor = '#000000';
			}
		}

        var pbColor = (this.skin['poweredByStyle'] == 'light') ? '#ffffff' : '#000000';

        var styles = '<style type="text/css"> \
        #tdia * {font-family: Verdana; margin: 0; padding: 0; border:none;} \
        #tdia {min-height: 350px; position:relative;} \
        #tdia a img {border:none;} \
        #tdia .clear {clear: both;} \
        #tdia .tdiawidget {background: #000; min-height: 350px; padding: 0 3px} \
        #tdia .keyword {font-weight: bold;} \
        #tdia .head {background:transparent; clear:both; font-size: 12px; font-weight: bold; text-align: center; height: 33px;} \
        #tdia .head ul {list-style-type:none; line-height: 25px; margin: 0 !important; padding:5px 2px 0px;} \
        #tdia .head ul li {display:inline; float:left; height:25px; border:none !important; margin:0 !important; padding: 0 !important;} \
        #tdia .head li.title-text {background:url(' + this.imagesUri + '/title-bkgnd.png) top left repeat-x; color:#000000;} \
	    #tdia .head li.title-text p {line-height:25px; text-align:center;}\
        #tdia .head ul li img {margin:0; padding:0; height:26px;} \
        #tdia .view-share {height:17px; color:'+pbColor+'; font-size:11px; margin:0 0 2px; padding:0; overflow:hidden;}\
        #tdia .view-share span img {cursor:pointer; height:15px; width:15px; vertical-align:top; margin-right:3px;}\
        #tdia .content-wrapper, #tdia .content {background: ' + this.skin['tweetListBackground'] + '; min-height: 240px; overflow: hidden; width: 100%;} \
        #tdia .content-wrapper {-moz-border-radius: 5px; -webkit-border-radius: 5px; position: relative; border:' + this.skin['tweetListBorder'] + ' solid; border-width:5px 0;} \
        #tdia .content .back {background:url(' + this.imagesUri + '/footer-bkgnd.png) top right repeat-x; cursor:pointer; font-size: 9px; height: 16px; line-height: 16px; margin: 0; padding-left: 10px; text-align: left; width: 100%;} \
        #tdia .content-messages {position: absolute; z-index: 99; background:#efefef; padding:10px 5px; border:2px solid #888; text-align:center; font-size:12px; width:250px; left:18px; top:50px;} \
        #tdia .messages-ok {clear:both; cursor: pointer; margin: 20px 0 0;} \
        #tdia .tinyTip {background:#ddd; border:#aaa solid 1px; padding:1px 3px; display: block; width:90px;} \
        #tdia .tinyTip .tiptext {background:transparent; border:none; color: #010101; font-size: 10px; font-family: "Verdana";} \
        #tdia .content-ad {text-align:center;}\
        #tdia .content form {margin: 0 auto; width:280px;} \
        #tdia .content form p {color: #666; margin-left: 5px;} \
        #tdia .content input {border: #000 solid 1px; color: #666; float: left; font-size: 11px; font-style: italic; height: 21px; width: 130px;} \
        #tdia .login-left {float: left; margin-left: 5px; width:130px;} \
        #tdia .login-right {float: right; margin-right: 5px; text-align: left; width:130px;} \
        #tdia .jtc-state {padding: 10px 5px 5px;} \
        #tdia .content-jtc p.wh {clear: both; font-size: 14px; font-weight: bold;} \
        #tdia .content-jtc .chars {font-size: 11px; font-weight: bold; line-height: 24px;} \
        #tdia .content-jtc textarea {border:#000 solid 1px; color: #666; font-size: 12px; font-style: italic; height:125px; max-height: 125px; margin: 5px; width:270px; max-width: 270px;} \
        #tdia .content-jtc .sbmtbtn {border:none; clear: right; float: right; margin-right: 7px; height:20px; width:65px;} \
        #tdia .content-jtc p.tacct {color: #666; font-size: 10px; margin: 8px 0; text-align: center;} \
        #tdia .content-jtc p.tacct a, #tdia .content-jtc p.tacct a:visited {color:#00f;} \
        #tdia .content-tism {text-align: center;} \
        #tdia .tism-state {padding: 10px 5px 5px;} \
        #tdia .content-tism a, #tdia .content-tism a:visited {color:#ef5f00;} \
        #tdia .content-tism .fp {font-size: 10px;} \
        #tdia .tism-state-login input[type=image] {clear: both; margin: 20px;} \
        #tdia .tism-state-login div.ca {color: #666; font-size: 12px;} \
        #tdia .fbFeed {overflow: scroll; overflow-x:hidden;} \
        #tdia .content-share p {font-size:11px; font-weight:bold; color:#333333; margin:9px 10px;}\
        #tdia .content-share #chicklets, #tdia .content-share #tdiaHtml {background:#f0f0f0; border:#cccccc solid 1px; margin:0 20px; padding:0;}\
        #tdia .content-share #chicklets td {width:132px; margin:0; padding:4px; font-size:12px;}\
        #tdia .content-share #chicklets td img {margin-right:4px; vertical-align:text-top;}\
        #tdia .content-share #chicklets .chicklet {color:#333333; text-decoration:none;}\
        #tdia .content-share #tdiaHtml {font-size:9px; word-wrap:break-word;}\
        #tdia .tweets {position:relative; left: 0; width: 294px; clear:both;} \
        #tdia .tweet {text-align: left; position:relative; border-bottom: #eaece9 solid 1px; border-top: #ededed solid 1px; padding:5px 4px 7px;} \
        #tdia .tweet span {padding-right: 3px;} \
        #tdia .tweet span.fullname {float:left;} \
        #tdia .tweet span.twttr-user {float:left; margin-top:2px; color:#999999; white-space: nowrap;} \
        #tdia .tweet span.mesg-content {display:block; float:left; width:97%} \
        #tdia .tweet ul.twttr-links {display: block; font-size: 9px; margin: -25px 0 0 65px; padding: 0; width: 100%;} \
        #tdia .tweet ul.twttr-links li {cursor: pointer; display: inline-block; font-family: Helvetica Neue,Arial,Helvetica; font-size: 10px; height: 14px; margin-top:5px; padding-top: 3px; width: auto;} \
        #tdia .tweet ul.twttr-links li.btn-st {padding-left:16px; background:url("'+this.imagesUri+'/bird_16_blue.png") no-repeat scroll 0 2px transparent;} \
        #tdia .tweet ul.twttr-links li.btn-at {padding-left:15px; background:url("'+this.imagesUri+'/reply.png") no-repeat scroll 0 2px transparent;} \
        #tdia .tweet ul.twttr-links li.btn-rt {padding-left:15px; background:url("'+this.imagesUri+'/retweet.png") no-repeat scroll 0 3px transparent;} \
        #tdia .tweet ul.twttr-links li.btn-fv {padding-left:15px; background:url("'+this.imagesUri+'/favorite.png") no-repeat scroll 0 2px transparent;} \
        #tdia .tweet div.twttr-botom-links {clear: both; width: 100%; float: left; margin-top: 2px;} \
        #tdia .tweet ul.twttr-links span img {display:block; float:left; } \
        #tdia .tweet .twttr-links.btns {background-color: ' + this.skin['tweetListBackground'] + ';} \
        #tdia .tweet .twttr-links.btns li {width:auto; display:inline-block; float:left;} \
        #tdia .tweet ul.twttr-links {background-color: ' + this.skin['tweetListBackground'] + ';} \
        #tdia .tweet span a {color:#4bc4d7; font-size: 14px; font-weight: bold; text-decoration: none;} \
        #tdia .text {font-size: 12px; margin:0 0 5px 62px;} \
        #tdia .text a {text-decoration: none;} \
        #tdia .text a:hover {text-decoration: underline;} \
        #tdia .time {margin-left: 50px; margin: 0 0 0 3px;} \
        #tdia .content-tweets {position: relative;} \
        #tdia .time, #tdia .time a {color: #a4d700; font-size: 12px; font-weight: bold; text-decoration: none;} \
        #tdia ul.btns {background:url('+this.imagesUri+'/btns-bkgnd.png) top left repeat; padding:4px 0 0 3px; float:left; margin:0;} \
        #tdia ul.btns li {cursor: pointer; display: inline; height:20px; padding:1px; width:20px;} \
        #tdia ul.btns .tw-links {font-size: 9px; left: -3px; margin-right: 0; padding-right: 0; position: relative; top: -5px; } \
        #tdia .tabs {list-style-type: none; margin: 0 auto; width:100%;} \
        #tdia .tab {background: transparent; color: #ffffff; cursor: pointer; display: inline; float: left; font-size: 12px; text-align: center;} \
        #tdia .footer {margin: 0; padding: 0; border:none;}\
        #tdia .footer img.jtc {cursor: pointer; height:31px; width:124px; float:left; margin:7px 0 0; padding:0;} \
        #tdia .via_icon {left:-1px; position: relative; top: 4px;} \
        #tdia .username {font-weight:bold;} \
        #tdia .footer .sponsor-text {background:' + this.skin['tweetListBorder'] + '; -moz-border-radius-bottomleft: 5px; -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomright: 5px; -webkit-border-bottom-right-radius: 5px; color:' + sponsorTextColor + '; cursor:pointer; float:right; font-size:8px; height:14px; line-height:13px; margin-right:22px; padding:0 3px 1px; text-align:center; text-transform:uppercase;} \
        #tdia .footer .powered-by {clear:right; margin:4px 5px 0 0; float:right;} \
        #tdia .jScrollPaneDrag img {width:' + this.skin['scrollWidth'] + 'px;}\
        #tdia .jScrollPaneDragTop {background:url(' + this.imagesUri + '/scrollbar-top-' + scrollColor + '.png) top center no-repeat; position: absolute; top: 0; left: 0; height:10px; overflow: hidden; } \
        #tdia .jScrollPaneDragBottom {background:url(' + this.imagesUri + '/scrollbar-bottom-' + scrollColor + '.png) bottom center no-repeat; position: absolute; bottom: 0; left: 0; height:20px; overflow: hidden;}';
        if(typeof(this.skin['scrollbarDetailColor']) != 'undefined') {
        	dark = this.skin['scrollbarDetailColor'].replace("#","-");
        } else {
        	dark = "-ffffff";
        }
        if (this.skin['scrollButtonStyle'] == 'shiny') {
            styles += '#tdia .jScrollPaneContainer {position: relative; overflow: hidden; z-index: 1;} \
            #tdia .jScrollPaneTrack {position: absolute; cursor: pointer; right: 0; top: 0; background:' + this.skin['scrollBackground'] + ' url(' + this.imagesUri + '/scroll-bkgnd.png) top center repeat-y; border:' + this.skin['scrollButtonBorder'] + ' solid 1px; border-top:none; border-bottom:none; height: 100%;} \
            #tdia .jScrollPaneDrag {background:' + this.skin['scrollButtonBackground'] + '; position: absolute; cursor: pointer; overflow: hidden;} \
            #tdia a.jScrollArrowUp {background:' + this.skin['scrollButtonBackground'] + ' url(' + this.imagesUri + '/scroll-uparrow' + dark + '.png) top center no-repeat; border:' + this.skin['scrollButtonBorder'] + ' solid 1px; border-bottom:none; border-top:none; display: block; position: absolute; z-index: 1; top: 0; right: 0; text-indent: -2000px; overflow: hidden; height: 14px;} \
            #tdia a.jScrollArrowDown {background:' + this.skin['scrollButtonBackground'] + ' url(' + this.imagesUri + '/scroll-downarrow' + dark + '.png) top center no-repeat; border:' + this.skin['scrollButtonBorder'] + ' solid 1px; border-bottom:none; border-top:none; display: block; position: absolute; z-index: 1; bottom: 0; right: 0; text-indent: -2000px; overflow: hidden; height: 14px;}';
        } else {
            styles += '#tdia .jScrollPaneContainer {position: relative; overflow: hidden; z-index: 1;} \
            #tdia .jScrollPaneTrack {position: absolute; cursor: pointer; right: 0; top: 0; background:' + this.skin['scrollBackground'] + '; border:' + this.skin['scrollButtonBorder'] + ' solid 1px; border-top:none; border-bottom:none; height: 100%;} \
            #tdia .jScrollPaneDrag {background:' + this.skin['scrollButtonBackground'] + '; position: absolute; cursor: pointer; overflow: hidden;} \
            #tdia a.jScrollArrowUp {background:' + this.skin['scrollButtonBackground'] + ' url(' + this.imagesUri + '/scroll-uparrow' + dark + '-matte.png) top center no-repeat; border:' + this.skin['scrollButtonBorder'] + ' solid 1px; border-bottom:none; border-top:none; display: block; position: absolute; z-index: 1; top: 0; right: 0; text-indent: -2000px; overflow: hidden; height: 14px;} \
            #tdia a.jScrollArrowDown {background:' + this.skin['scrollButtonBackground'] + ' url(' + this.imagesUri + '/scroll-downarrow' + dark + '-matte.png) top center no-repeat; border:' + this.skin['scrollButtonBorder'] + ' solid 1px; border-bottom:none; border-top:none; display: block; position: absolute; z-index: 1; bottom: 0; right: 0; text-indent: -2000px; overflow: hidden; height: 14px;}';
        }
        if (this.isiPad) {
            styles += '#tdia .content-wrapper .ipad {background:' + this.skin['scrollButtonBackground'] + ' url(' + this.imagesUri + '/ipad/btn-gradient.png) top left repeat-x; height:32px; width:50%; padding-top:11px; text-align:center;} \
            #tdia .content-wrapper .ipad-down {float:left;} \
            #tdia .content-wrapper .ipad-down span {background:url(' + this.imagesUri + '/ipad/down-arrow.png) center center no-repeat; height:25px; padding:13px 25px;} \
            #tdia .content-wrapper .ipad-up {float:right;} \
            #tdia .content-wrapper .ipad-up span {background:url(' + this.imagesUri + '/ipad/up-arrow.png) center center no-repeat; height:25px; padding:13px 25px;}';
        }

    	if (this._isIE()) {
    		styles += '#tdia .jScrollPaneDrag { left: 0; }</style>';
        } else {
            styles += '</style>';
        }

        jCue('head').append(styles);
    },

    _buildWidget: function () {
        this._buildStyles();

        jtcButtonUri = this.imagesUri + '/button-jtc.png';
        if(typeof(this.skin['customJtcImg']) != 'undefined') {
            jtcButtonUri = this.skin['customJtcImg'];
        }

        var html = '<div id="tdia"> \
        <div class="tdiawidget"> \
        <div class="head">';
        if (typeof(this.skin['showTitle']) == 'undefined' || this.skin['showTitle'] != 0) {
            html += '<ul><li><a href="http://www.tweetedia.com" target="_blank"><img src="'+this.imagesUri+'/tdia-icon.png" style="width:24px;" /></a></li><li><img src="' + this.imagesUri + '/title-left.png" style="width:10px;" /></li><li class="title-text"></li><li><img src="' + this.imagesUri + '/title-right.png" style="width:8px;" /></li></ul>';
        }
        html += '</div> \
        <div class="view-share">\
        <a style="float:right; text-decoration:none; margin-right:5px;" class="tab share">Share</a>\
        </div>\
        <div class="content-wrapper"> \
        <div class="content-messages"></div> \
        <div class="content content-ad"> \
        <div class="ad-image"></div> \
        </div> \
        <div class="content content-jtc"> \
        <div class="back">&lt; Back</div> \
        <div class="jtc-state jtc-state-login"> \
        <form method="post" name="jtcform" class="jtc-form" onSubmit="return false"> \
        <p class="wh">What\'s Happening?</p> \
        <textarea class="jtc-message" name="jtcmessage"></textarea> \
        <input type="image" class="sbmtbtn" src="http://www.tweetedia.com/images/button-send.png" alt="Send" /> \
        <p class="chars">Characters remaining <span>140</span></p> \
        </form> \
        <p class="tacct">You must have a <a href="https://twitter.com/signup" target="_blank">Twitter account</a> to participate</p> \
        </div> \
        </div> \
        <div class="content content-tism"> \
        <div class="back">&lt; Back</div> \
        <div class="tism-state tism-state-login"> \
        <form method="post" onsubmit="tismSubmit()"> \
        <div class="login-left"><input type="text" name="tismuser" value="Email/Username" /></div> \
        <div class="login-right"><input type="text" name="tismpasslabel" value="Password" /><input type="password" name="tismpass" /><a class="fp">forgot your password?</a></div> \
        <div class="clear"></div> \
        <input type="image" src="http://www.tweetedia.com/images/button-login.png" alt="Login" /> \
        <div class="ca">Not a member? Get in the game!<br /><a href="">Create Account</a></div> \
        </form> \
        </div> \
        </div> \
        <div class="content content-crowdreel"> \
        <div class="back">&lt; Back</div> \
        <div class="pics"></div> \
        </div> \
        <div class="content content-facebook"> \
        <div class="back">&lt; Back</div> \
        <div class="fbFeed"></div> \
        </div> \
        <div class="content content-share"> \
        <div class="back">&lt; Back</div> \
        <p>Share this page with friends...</p>\
        <table id="chicklets"> \
        <tr>\
        <td><a id="ck_facebook" class="chicklet" href="javascript:void(0);"><img src="http://w.sharethis.com/chicklets/facebook.gif" />Facebook</a></td> \
        <td><a id="ck_yahoo_buzz" class="chicklet" href="javascript:void(0);"><img src="http://w.sharethis.com/chicklets/ybuzz.gif" />Yahoo! Buzz</a></td> \
        </tr><tr>\
        <td><a id="ck_twitter" class="chicklet" href="javascript:void(0);"><img src="http://w.sharethis.com/chicklets/twitter.gif" />Twitter</a></td> \
        <td><a id="ck_digg" class="chicklet" href="javascript:void(0);"><img src="http://w.sharethis.com/chicklets/digg.gif" />Digg</a></td> \
        </tr>\
          </table> \
        <script type="text/javascript"> \
          var shared_object = SHARETHIS.addEntry({\
          title: document.title,\
          url: document.location.href\
        }, {button:false});\
         \
        shared_object.attachChicklet("twitter", document.getElementById("ck_twitter"));\
        shared_object.attachChicklet("facebook", document.getElementById("ck_facebook"));\
        shared_object.attachChicklet("digg", document.getElementById("ck_digg"));\
        shared_object.attachChicklet("yahoo_buzz", document.getElementById("ck_yahoo_buzz"));\
        </script>\
         <p>or paste the widget code to your website.</p>';
        if(this._isIE()) {
            html+= '<a href="javascript:;" id="tdiaCopyCode" style="clear:both; margin-left:100px; margin-top:10px;"><img src="'+this.imagesUri+'/button-copy-code.png" alt="Copy Code" /></a>';
        }
        html+='<div id="tdiaHtml"';
        if(this._isIE()) {
            html += ' style="display:none;"';
        }
        html += '>&lt;script type="text/javascript" src="http://api.tweetedia.com/v3/tweetedia.js"&gt;&lt;/script&gt;<br>&lt;script type="text/javascript"&gt;new Tweetedia({&nbsp;ident: '+this.ident+',&nbsp;params: {}});&lt;/script&gt;</div>\
        </div> \
        <div class="content-tweets"> \
        <div class="tweets"><div class="makescroll"></div></div> \
        </div> \
        </div> \
        <div class="footer">';
        if (typeof(this.config['hasJtc']) == 'undefined' || this.config['hasJtc'] == 1) {
            html += '<img src="' + jtcButtonUri +'" class="tab jtc" />';
        }
        if (typeof(this.skin['customLogo']) != 'undefined' && this.skin['customLogo'] == 'bottom' && typeof(this.skin['customLogoUri']) != 'undefined') {
            html += '<div style="position:relative; top:7px; right:0; height:30px; width:45px; background: transparent; display: inline; float: left; text-align:right;"><img src="' + this.skin['customLogoUri'] + '" /></div>';
        }
        var light = (this.skin['poweredByStyle'] == 'dark') ? '-dark' : '';
        html += '<div class="sponsor-text"></div> \
        <a class="powered-by" href="' + this.skin['poweredByTarget'] + '" target="_blank"><img src="' + this.imagesUri + '/powered-by' + light + '.png" alt="" /></a> \
    	</div> \
        <div class="clear"></div>\
        </div> \
        </div>';
        jCue(this.scriptNode).after(html);
    },

    _attachEvents: function () {
        var self = this;

        //Join the Conversation Stuff
        jCue('#tdia .jtc-message').focus(function () {
            if (jCue('#tdia .jtc-message').val() == self.skin['tweetInputPrompt'] || jCue('#tdia .jtc-message').val() == 'Type your message here... ') jCue('#tdia .jtc-message').val('');
        });
        jCue('#tdia .jtc-message').blur(function () {
            jCue('#tdia .content-jtc .login-left input').focus().select();
            if (jCue('#tdia .jtc-message').val() == '') jCue('#tdia .jtc-message').val(self.skin['tweetInputPrompt']);
        });
        jCue('#tdia .jtc-message').keyup(function () {
            var numChars = jCue('#tdia .jtc-message').val().length;
            if (numChars > 140) {
                jCue('#tdia .jtc-message').val(jCue('#tdia .jtc-message').val().substring(0, 140));
                numChars = 140;
            }
            jCue('#tdia .chars span').html(140 - numChars);
        });
        jCue("#tdia form[name=jtcform]").submit(function () {
            //check for empty fields
            if (jCue('#tdia .jtc-message').val() == '' || jCue('#tdia .jtc-message').val() == self.skin['tweetInputPrompt'] || jCue('#tdia .jtc-message').val() == 'Type your message here...') {
                self._showMessage('Please enter some text to tweet');
                return false;
            }
            if (self.tweetAction == 'directmessage') {
                var userid = jCue('#tdia p.wh').html();
                userid = userid.substr(15);
                userid = userid.replace(/:/, '');
                self.tweetAction += '&user=' + userid;
            }
            var hash = hex_md5(jCue('#tdia .jtc-message').val() + self.tweetAction);
            var jtcUri = self.baseUri + '/v3/TwitterOAuth.php?message=' + encodeURIComponent(jCue('#tdia .jtc-message').val()) + '&action=' + self.tweetAction + '&hash=' + hash;
            jCue.ajax({
                url: jtcUri,
                dataType: 'jsonp',
                cache: false,
                jsonpCallback: 'sendJtc',
                success: function (response) {
                    if (response.status == 1) {
                        self.feed['tweet'].splice(0, 0, response.tweet);
                        self.counter++;
                        self._showTweetsDelay(2000);

                        jCue('#tdia .content-jtc').slideUp(200).delay(200);
                        jCue('#tdia p.wh').html("What's Happening?");
                        jCue('#tdia .jtc-message').val(self.skin['tweetInputPrompt']);
                        jCue('#tdia p.chars span').html('140');
                        self.tweetAction = 'update';
                        self._showMessage('Your tweet has been sent');
                        self._addEvent('Update');
                    } else {
                        if (response.status == 0) {
                            self._showMessage('Error: ' + response.message);
                        }
                    }
                }
            });

            return false;
        });

        //share the widget "Copy Code" button
        jCue('#tdiaCopyCode').click(function(e) {
            if (window.clipboardData) { //IE
        		if (window.clipboardData.setData('Text',jCue('#tdiaHtml').text().replace(/						/g, '')) != false) {
                    self._showMessage('Your code has been copied to the clipboard');
        		}
            } else if(jCue.browser.webkit) { //Safari, Chrome

        	} else { //FF

            }
        });

        //Tism Stuff


        //Pictures Stuff


        //Tab, Back, and iPad button functions
        if (self.config['type'] != 2) {
            jCue('#tdia .sponsor-text').click(function () {
            	var light = (self.skin['sponsorTextColor'] == 'light') ? '-light' : '';
                if (jCue('#tdia .content-ad').is(':hidden')) {
                    if (jCue('#tdia .content').is(':visible')) jCue('#tdia .content').slideUp(200).delay(300);
                    jCue('#tdia .content-ad').slideDown(300);
                    jCue('#tdia .sponsor-text').html('Sponsor Info <img src="' + self.imagesUri + '/sponsor-arrow-down' + light + '.png" style="vertical-align:middle; padding-bottom:2px;" />');
                } else {
                    jCue('#tdia .content-ad').slideUp(200);
                    jCue('#tdia .sponsor-text').html('Sponsor Info <img src="' + self.imagesUri + '/sponsor-arrow' + light + '.png" style="vertical-align:middle; padding-bottom:2px;" />');
                }
            });
        }
        jCue('#tdia .tab').click(function() {
            var clickedTab = jCue(this).attr('class').split(" ");
            if(jCue('#tdia .content-' + clickedTab[1]).is(':hidden')) {
                if(clickedTab[1] == 'jtc') {
                    jCue('#tdia .jtc-state-login p.not-you').remove();
                    jCue.ajax({
            			url: self.baseUri + '/v3/TwitterOAuth.php',
            			dataType: 'jsonp',
            			cache: false,
            			jsonpCallback: 'getAuth',
            			success: function(response) {
                            if(response.status == 0) {
                                self._showMessage(response.message);
                            } else if (response.status == 1) {
                                //show Jtc Area
                                jCue('#tdia .content').slideUp(200);
                                if(jCue('#tdia .content').is(':visible')) jCue('#tdia .content').delay(300);
                                jCue('#tdia .content-jtc').slideDown(300);
                                //show message box asking to authorize
                                jCue('#tdia .content-messages').empty().html('<span>Please authorize Twitter to Join In</span><br /><img class="messages-ok doAuth" src="'+self.imagesUri+'/btn-ok.gif" alt="OK" /><br /><br /><a href="javascript:;" style="margin-top:10px;" onclick="jCue(\'#tdia .content-messages\').jqmHide(); jCue(\'#tdia .jtc\').trigger(\'click\');">Cancel</a>');
                                jCue('#tdia .doAuth').click(function() {
                                    self.popup({'url':self.baseUri+'/v3/TwitterOAuth.php?callback=doAuth','width':'800','height':'400','popupId':'authPop'});
                                });
                                jCue('#tdia .content-messages').jqmShow().css({'height':'auto'}).animate({'opacity':1},200);
                            } else if (response.status == 2) {
                                if(response.username != null) {
                                    jCue('#tdia .jtc-state-login').prepend('<p class="not-you" style="font-size: 12px; margin-bottom:7px;">Hey there '+response.username+'!<a href="javascript:;" style="margin-left:5px; font-size:10px; text-decoration:none;">not you?</a></p>');
                                } else {
                                    jCue('#tdia .jtc-state-login').prepend('<p class="not-you" style="font-size: 12px; margin-bottom:7px;">You are logged in.<a href="javascript:;" style="margin-left:5px; font-size:10px; text-decoration:none;">Log Out</a></p>');
                                }
                                jCue('#tdia .jtc-state-login p.not-you').click(function() {
                                    jCue.ajax({
                            			url: self.baseUri + '/v3/TwitterOAuth.php',
                            			dataType: 'jsonp',
                            			cache: false,
                            			jsonpCallback: 'logOut',
                            			success: function(response) {
                                            if(response.status = 1)
                                                self._showMessage('You have been logged out');
                                            else
                                                self._showMessage('You could not be logged out.  Please restart your browser and try again.');

                                            jCue('#tdia .content-jtc').slideUp(200);
                            			}
                                    });
                                });
                                //show Jtc Area
                                jCue('#tdia .content').slideUp(200);
                                if(jCue('#tdia .content').is(':visible')) jCue('#tdia .content').delay(300);
                                jCue('#tdia .content-jtc').slideDown(300);
                            }
            			}
            		});
                    self._addEvent('Join the conversation');
                } else {
                    jCue('#tdia .content').slideUp(200);
                    if(jCue('#tdia .content').is(':visible')) jCue('#tdia .content').delay(300);
                    jCue('#tdia .content-' + clickedTab[1]).slideDown(300);
                }
            } else {
                jCue('#tdia .content-' + clickedTab[1]).slideUp(200);
                if(clickedTab[1] == 'jtc') {
                    self.tweetAction = 'update';
                    jCue('#tdia p.wh').delay(500).html("What's Happening?");
                    jCue('#tdia .jtc-message').val(self.skin['tweetInputPrompt']);
                }
            }
            var light = (self.skin['sponsorTextColor'] == 'light') ? '-light' : '';
            jCue('#tdia .sponsor-text').html('Sponsor Info <img src="'+self.imagesUri+'/sponsor-arrow'+light+'.png" style="vertical-align:middle; padding-bottom:2px;" />');

        });
        jCue('#tdia .content .back').click(function () {
            var tabName = jCue(this).parent().attr('class').split("-");
            jCue('#tdia .content-' + tabName[1]).slideUp(200).delay(200);
            if (tabName[1] == 'jtc') {
                jCue('#tdia p.wh').delay(200).html("What's Happening?");
                jCue('#tdia .jtc-message').val(self.skin['tweetInputPrompt']);
                jCue('#tdia p.chars span').html('140');
                self.tweetAction = 'update';
            }
            self._addEvent('Back');
        });

        //iPad buttons
        jCue('#tdia .ipad-down').mousedown(function () {
            //if the tweets aren't outside the tweet area
            if (jCue('#tdia .tweets').css('top') == 'auto') jCue('#tdia .tweets').css({
                'top': 0
            });
            if ((parseInt(jCue('#tdia .tweets').css('top')) - 40) > (jCue('#tdia .content-tweets').height() - jCue('#tdia .tweets .makescroll').height())) {
                jCue('#tdia .tweets').css({
                    'top': parseInt(jCue('#tdia .tweets').css('top')) - 40
                });
            } else {
                jCue('#tdia .tweets').css({
                    'top': (jCue('#tdia .content-tweets').height() - jCue('#tdia .tweets .makescroll').height())
                });
            }
            self.downTimer = setTimeout(function () {
                jCue('#tdia .ipad-down').trigger('mousedown')
            }, 100)
        }).mouseup(function () {
            clearTimeout(self.downTimer);
        });
        jCue('#tdia .ipad-up').mousedown(function () {
            //if the tweets aren't outside the tweet area
            if (jCue('#tdia .tweets').css('top') == 'auto') jCue('#tdia .tweets').css({
                'top': 0
            });
            if ((parseInt(jCue('#tdia .tweets').css('top')) + 40) < 0) {
                jCue('#tdia .tweets').css({
                    'top': parseInt(jCue('#tdia .tweets').css('top')) + 40
                });
            } else {
                jCue('#tdia .tweets').css({
                    'top': 0
                });
            }
            self.upTimer = setTimeout(function () {
                jCue('#tdia .ipad-up').trigger('mousedown')
            }, 100)
        }).mouseup(function () {
            clearTimeout(self.upTimer);
        });

        //Google Analytics stuff
        jCue('#tdia').mouseleave(function () {
            self._addEvent('Mouse Leave');
        });
        jCue('#tdia .powered-by').click(function () {
            self._addEvent('Logo');
            return true;
        });
    },

    _manageTwitterText: function () {
        var self = this;

        if (typeof(twttr) != 'object' && typeof(twttr) != 'function') {
            self._lazyLoad.js(this.baseUri + '/' + this.version + '/twitter-text.js', function () {
                window.twttr = twttr;

                self.twttrLoaded = true;
            });
        } else {
            window.twttr = twttr;

            self.twttrLoaded = true;
        }
    },

    //system stuff
    dialogs: [],
    monitor: null,
    monitorStarted: false,

    popup: function(opts) {
        var self = this;

        var screenX = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft;
        var screenY = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop;
        var outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.body.clientWidth;
        var outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.body.clientHeight - 22);

        var width = opts.width;
        var height = opts.height;
        var left = parseInt(screenX + ((outerWidth - width) / 2), 10);
        var top = parseInt(screenY + ((outerHeight - height) / 2.5), 10);

        var features = (
            'width=' + width +
            ',height=' + height +
            ',left=' + left +
            ',top=' + top +
            ',menubar=0' +
            ',resizeable=0' +
            ',location=0' +
            ',scrollbars=1'
        );

        var popupId = opts.popupId || 'tdia' + self.parent.Util.randomString(14);

        var call = {
            id: popupId,
            cb: opts.cb || function() {}
        };

        if(self.monitorStarted == false) {
            self.startMonitor();
        }

        call.url = opts.url || self.parent.apiBase + 'index/' + self.parent.Net.buildUrl({
            reqId: call.id
        });

        call.window = window.open(call.url, call.id, features);

        self.dialogs.push(call);
    },

    startMonitor: function() {
        var self = this;

        self.monitorStarted = true;

        self.monitor = setInterval(function() {
            for(var i in self.dialogs) {
                var dialog = self.dialogs[i];

                try {
                    if (dialog.window.closed) {
                        jCue.ajax({
                			url: self.baseUri + '/v3/TwitterOAuth.php',
                			dataType: 'jsonp',
                			cache: false,
                			jsonpCallback: 'isAuthed',
                			success: function(response) {
                                if (response.status == 1) {
                                    jCue('#tdia .content-messages').jqmHide();
                                } else {
                                    jCue('#tdia .content-messages').jqmHide();
                                    jCue('#tdia .content-jtc').slideUp(200);
                                    self._showMessage('Authorization revoked. Please try again.');
                                }
                			}
                		});

                        self.dialogs.splice(i, 1);

                        if(self.dialogs.length == 0) {
                            self.monitorStarted = false;

                            clearInterval(self.monitor);
                        }
                    }
                } catch (y) {
                    // probably a permission error
                }
            }
        }, 100);
    },

    _showMessage: function (messageText) {
        jCue('#tdia .content-messages').empty().html('<span>'+messageText+'</span><br /><img class="messages-ok" src="'+this.imagesUri+'/btn-ok.gif" alt="OK" />');
        jCue('#tdia .content-messages').jqmAddClose('#tdia .messages-ok');
        return jCue('#tdia .content-messages').jqmShow().css({'height':'auto'}).animate({'opacity':1},200);
    },

    _addItem: function (listName, listItemHTML) {
        jCue(listItemHTML)
            .hide()
            .css({'opacity' : 0.0})
            .prependTo(listName)
            .slideDown(200)
            .delay(100)
            .animate({opacity: 1.0})
            .show();

		//limit maximum tweets to 50
		if(jCue(listName).children('div').size() > this.config['maxItems']) {
			jCue(listName).children('div').last().remove();
		}
    },

    _setStyles: function () {
        jCue('#tdia .tweet').css({
            'border-top-color': this.skin['tweetSeparatorTop'],
            'border-bottom-color': this.skin['tweetSeparatorBottom']
        });
        var textWidthDiff = (this._isIE()) ? 45 : 35;
        jCue('#tdia .text').css({
            'width': this.config['width'] - textWidthDiff - this.skin['avatarWidth'],
            'word-wrap': 'break-word'
        });
        jCue('#tdia .text, #tdia .text a, #tdia .mesg .fullname, #tdia .mesg .twttr-user, #tdia .mesg .mesg-content').css({
            'color': this.skin['textColor'],
            'font-size': this.skin['textSize'],
            'font-family': this.skin['textFont']
        });
        jCue('#tdia .tweet span a').css({
            'color':this.skin['twitterNameColor'],
            'font-family':this.skin['twitterNameFont']
        });
        jCue('#tdia .tweet span.fullname a').css({
            'font-size':this.skin['twitterNameSize']
        });
        jCue('#tdia .time, #tdia .time a').css({
            'color': this.skin['timestampColor'],
            'font-size': this.skin['timestampSize'],
            'font-family': this.skin['timestampFont']
        });

        if(this._isIE()) {
            jCue('#tdia p.text').css({'width':'auto'});
        }

        jCue('.mesg a').live('click', function() {
            window.open(this.href);
            return false;
        });
    },

    //Tweetedia Stuff
    _getNextTweet: function (childId) {
        if (typeof(this.feed['tweet']) == 'undefined' || typeof(this.feed['tweet'][childId]) == 'undefined' || this.feed['tweet'][childId] == null) return null;

        var authorImg = this.feed['tweet'][childId].author.image;
        var authorUri = this.feed['tweet'][childId].author.uri;
        var username = this.feed['tweet'][childId].author.twitter_name;
        var authorname = this.feed['tweet'][childId].author.name;
        var fnamePatt=/\([^()<>]*\)/gi;
        var fullname;
        if (authorname.match(fnamePatt) == null) {
            fullname = authorname;
        } else {
            var fname = authorname.match(fnamePatt)[0];
            fullname = fname.substring(1, fname.length-1);
        }

        var ttContent = twttr.txt.autoLink(twttr.txt.htmlEscape(this.feed['tweet'][childId].message.title));

        var t = this.feed['tweet'][childId].pubdate.split(/[- :]/);
        var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
        var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
        var twPubDate = d.getDate() + " " + monthNames[d.getMonth()];
        var avatarHeight = parseInt(this.skin['avatarHeight']) + 10;
        var avatarWidth = parseInt(this.skin['avatarWidth']) + 10;

        var avatarWidthCon = parseInt(this.skin['avatarWidth']);
        if(this._isIE()) {
            var avatarWidthCon = parseInt(this.skin['avatarWidth']) + 10;
        }

        this.lastTweetId = this.feed['tweet'][childId].id;
        var time_ago = this.feed['tweet'][childId].time_since;
        time_ago = time_ago.replace(' ago', '');
        var formattedTweet = '<div class="tweet"><div style="float:left; width:'+(avatarWidthCon+4)+'px;"><a href="'+authorUri+'"><img class="avatar" src="' +authorImg+ '" alt="'+username+'" height="'+avatarHeight+'px" width="'+avatarWidth+'px" /></a>';
        formattedTweet += '</div>';
        if (typeof(this.skin['useTweetFormat']) == "undefined" || this.skin['useTweetFormat'] == 0) {
            formattedTweet += '<p class="text"><span class="mesg"><span class="fullname"><a href="'+authorUri+'">'+fullname+'</a></span><span class="twttr-user">'+username+'</span><span class="mesg-content">'+ttContent+'</span></span><!-- mesg --></p>'+
'<div class="twttr-botom-links"> \
    <iframe allowtransparency="true" frameborder="0" scrolling="no" \
        src="http://platform.twitter.com/widgets/follow_button.html?screen_name='+username+'&show_count=false&show_screen_name=false" \
        style="width:61px; height:20px; float:left; margin-top:3px;"> \
    </iframe> \
    <ul class="twttr-links btns"> \
        <li class="btn-st clickable" id="'+this.feed['tweet'][childId].id+' st" title="View Status on Twitter"> \
            '+twPubDate+' \
        </li><li class="btn-at clickable" title="Reply"> \
            Reply \
        </li><li class="btn-rt clickable" title="Retweet"> \
            Retweet \
        </li><li class="btn-fv clickable" id="'+this.feed['tweet'][childId].id+' fv" title="Favorite"> \
            Favorite \
        </li> \
    </ul> \
</div>';

        } else {
            formattedTweet += this.skin['tweetFormat'].replace('<!--uri-->', this.feed['tweet'][childId].author.uri);
            formattedTweet = formattedTweet.replace('<!--twitter_name-->', this.feed['tweet'][childId].author.twitter_name);
            formattedTweet = formattedTweet.replace('<!--message-->', ttContent);
            formattedTweet = formattedTweet.replace('<!--time-->', time_ago);
            formattedTweet = formattedTweet.replace('<!--source-->', this.feed['tweet'][childId].source);
        }
        formattedTweet += '<div style="clear:both;"></div></div>';

        return formattedTweet;
    },

    _showTweetsDelay: function (milliseconds) {
        var self = this;
        if (this._getNextTweet(this.counter) !== null) var timer = setTimeout(function () {
            self._showTweets();
        }, milliseconds);
    },

    _showTweets: function () {
        var self = this;
        this._addItem('#tdia .tweets .makescroll', this._getNextTweet(this.counter));
        this._setStyles();
        //bind retweet, info, reply, and direct message buttons

        jCue('#tdia li.clickable').unbind('click').click(function () {
            self._tweetBtn(this, self);
        });
        jCue('#tdia .tdiawidget ul.btns:first li').tinyTips('title');
        jCue('#tdia .tdiawidget ul.btns').show();

        //bind avatar hover to show buttons
        jCue('#tdia img.avatar').unbind('mouseenter').mouseenter(function () {
            jCue('#tdia .tdiawidget ul.btns').show();
            jCue(this).parent().children('ul.btns').show();
        });
        jCue('#tdia ul.btns').unbind('mouseleave').mouseleave(function () {
            jCue('#tdia .tdiawidget ul.btns').show();
        });
        if (!this.isiPad) {
            var scrolltimer = setTimeout(function () {
                jCue('#tdia .tweets').jScrollPane({
                    showArrows: true,
                    scrollbarWidth: 13
                });
                if (self.skin['scrollButtonStyle'] == 'shiny') {
                    jCue('#tdia .jScrollPaneDrag').append('<img src="' + self.imagesUri + '/scroll-face.png" />');
                    jCue('#tdia .jScrollPaneDrag img').height(jCue('#tdia .jScrollPaneDrag').height());
                }
            }, 200);
        }
//        jCue('#tdia .tweets .makescroll div:first p.text').style.removeAttribute('filter');
        //Google Analytics for outbound links
        jCue('a').each(function () {
            var $a = jCue(this);
            var href = $a.attr('href');
            if (typeof(href) != 'undefined' && href.match(/^http/) && (!href.match(document.domain))) {
                $a.unbind('click').click(function () {
                    self._addEvent('Link')
                });
            }
        });

        //bind hover to twttr-links
        //status
        jCue('#tdia .btn-st').unbind('mouseenter').mouseenter(function() {
            jCue(this).css('background-image', 'url('+self.imagesUri+'/bird_16_blue.png)');
        });
        jCue('#tdia .btn-st').unbind('mouseleave').mouseleave(function() {
            jCue(this).css('background-image', 'url('+self.imagesUri+'/bird_16_blue.png)');
        });

        //reply
        jCue('#tdia .btn-at').unbind('mouseenter').mouseenter(function() {
            jCue(this).css('background-image', 'url('+self.imagesUri+'/reply_hover.png)');
        });
        jCue('#tdia .btn-at').unbind('mouseleave').mouseleave(function() {
            jCue(this).css('background-image', 'url('+self.imagesUri+'/reply.png)');
        });

        //retweet
        jCue('#tdia .btn-rt').unbind('mouseenter').mouseenter(function() {
            jCue(this).css('background-image', 'url('+self.imagesUri+'/retweet_hover.png)');
        });
        jCue('#tdia .btn-rt').unbind('mouseleave').mouseleave(function() {
            jCue(this).css('background-image', 'url('+self.imagesUri+'/retweet.png)');
        });

        //favorite
        jCue('#tdia .btn-fv').unbind('mouseenter').mouseenter(function() {
            if (jCue(this).css('background-image') != 'url("'+ self.imagesUri +'/favorite_on.png")') {
                jCue(this).css('background-image', 'url('+self.imagesUri+'/favorite_hover.png)');
            }
        });
        jCue('#tdia .btn-fv').unbind('mouseleave').mouseleave(function() {
            if (jCue(this).css('background-image') != 'url("'+ self.imagesUri +'/favorite_on.png")') {
                jCue(this).css('background-image', 'url('+self.imagesUri+'/favorite.png)');
            }
        });

        if(typeof(console) == 'object') {
		console.log('Show Tweets - Tweet Counter: ' + this.counter);
	}

        //continually check for new tweets
        if (this.counter == 0 && this.lastTweetId != null) self._checkForNewTweets(self.lastTweetId);

        //set delay between tweets
        var variation = this.config['loadTime']['max'] - this.config['loadTime']['min'];
        var millisecDelay = Math.floor(Math.random() * variation) + 1;
        millisecDelay = (millisecDelay + this.config['loadTime']['min']) * 1000;
        this.counter--;
        self._showTweetsDelay(millisecDelay);
    },

    _checkNewTweetsDelay: function () {
        var self = this;

	if(typeof(console) == 'object') {
		console.log('New Tweets Delay - Tweets Counter: ' + this.counter);
	}

        if (this.counter <= 0) var newTweetTimer = setTimeout(function () {
            self._checkForNewTweets(self.lastTweetId);
        }, 60000);
    },

    _checkForNewTweets: function (lastTweet) {
        var self = this;
        var newTweetsUri = this.baseUri + '/feed/json-v3/id/' + this.feedId + '/since/' + lastTweet;
        jCue.ajax({
            url: newTweetsUri,
            dataType: 'jsonp',
            cache: false,
            jsonpCallback: 'getTweets' + lastTweet,
            success: function (response) {
                if (typeof(response['tweet']) != 'undefined' && response['tweet'] != null) {
                    self._parseNewTweets(response['tweet']);
                } else {
                    self._checkNewTweetsDelay();
                }
            }
        });
    },

    _parseNewTweets: function (newTweets) {
        this.feed['tweet'] = [];
        for (var i in newTweets) {
            this.feed['tweet'][i] = newTweets[i];
        }

        this.counter = this.feed['tweet'].length - 1;

        //TODO: flash the icon glow

        this._showTweets();
    },

    //TISM Stuff
    //Crowdreel Stuff
    _getNextCrItem: function (childId) {
        if (this.fbFeed['feed'][childId] == null || typeof(this.fbFeed['feed'][childId]) == 'undefined') return null;
        var feed = this.fbFeed['feed'][childId];
        var formattedUpdate = '<div class="tweet"><img src="https://graph.facebook.com/' + feed['from']['id'] + '/picture" alt="' + feed['from']['name'] + '" align="left" height="48px" width="48px" /><p class="text"><span><a href="http://www.facebook.com/' + feed['from']['id'] + '" target="_blank">' + feed['from']['name'] + '</a></span>' + feed['message'] + '</p><p class="time">' + feed['created_time'] + ' via Facebook</p><ul class="btns"><li class="btn-comment">Comment</li><li class="btn-like">Like</li></ul><div style="clear:both;"></div></div>';
        return formattedUpdate;
    },

    _showCrFeedDelay: function (milliseconds) {
        var self = this;
        if (this._getNextFbItem(this.fbCounter) !== null) var timer = setTimeout("self._showFbFeed()", milliseconds);
    },

    _showCrFeed: function () {
        var self = this;
        this._addItem('.fbFeed', this._getNextFbItem(this.fbCounter));
        this._setStyles();
        //bind retweet, info, reply, and direct message buttons
        jCue('#tdia .tweet .btns li').unbind('click').click(function () {
            self._tweetBtn(this);
        });
        //set delay between updates
        var variation = this.config['loadTime']['max'] - this.config['loadTime']['min'];
        var millisecDelay = Math.floor(Math.random() * variation) + 1;
        millisecDelay = (millisecDelay + this.config['loadTime']['min']) * 1000;
        this.fbCounter--;
        self._showFbFeedDelay(millisecDelay);
    },

    //Facebook Stuff
    _getNextFbItem: function (childId) {
        if (this.fbFeed['feed'][childId] == null || typeof(this.fbFeed['feed'][childId]) == 'undefined') return null;
        var feed = this.fbFeed['feed'][childId];
        var formattedUpdate = '<div class="tweet"><img src="https://graph.facebook.com/' + feed['from']['id'] + '/picture" alt="' + feed['from']['name'] + '" align="left" height="48px" width="48px" /><p class="text"><span><a href="http://www.facebook.com/' + feed['from']['id'] + '" target="_blank">' + feed['from']['name'] + '</a></span>' + feed['message'] + '</p><p class="time">' + feed['created_time'] + ' via Facebook</p><ul class="btns"><li class="btn-comment">Comment</li><li class="btn-like">Like</li></ul><div style="clear:both;"></div></div>';
        return formattedUpdate;
    },

    _showFbFeedDelay: function (milliseconds) {
        var self = this;
        if (this._getNextFbItem(this.fbCounter) !== null) var timer = setTimeout("self._showFbFeed()", milliseconds);
    },

    _showFbFeed: function () {
        var self = this;
        this._addItem('.fbFeed', this._getNextFbItem(this.fbCounter));
        this._setStyles();
        //bind retweet, info, reply, and direct message buttons
        jCue('#tdia .tweet .btns li').unbind('click').click(function () {
            self._tweetBtn(this);
        });
        //set delay between updates
        var variation = this.config['loadTime']['max'] - this.config['loadTime']['min'];
        var millisecDelay = Math.floor(Math.random() * variation) + 1;
        millisecDelay = (millisecDelay + this.config['loadTime']['min']) * 1000;
        this.fbCounter--;
        self._showFbFeedDelay(millisecDelay);
    },
    //Advertisement Stuff
    //RT buttons
    _tweetBtn: function (button, self) {
        var btnName = jCue(button).attr('class');
        var prefix = '';
        var messagePrefix = '';
        var username = jCue(button).parent().parent().parent().children('.text').children('.mesg').children('.twttr-user').text();

        switch (btnName) {
        case 'btn-rt clickable':
            prefix = 'Retweet ';
            var tweetText = jCue(button).parent().parent().parent().children('.text').children('.mesg').text();
            var fullname = jCue(button).parent().parent().parent().children('.text').children('.mesg').children('.fullname').text();
            var needle = new RegExp(fullname + username);
            tweetText = tweetText.replace(needle, ': ');
            messagePrefix = 'RT @' + username + " " + tweetText;
            this.tweetAction = 'retweet';
            this._addEvent('Avatar Retweet Button');
            break;
        case 'btn-at clickable':
            prefix = 'Reply to ';
            messagePrefix = '@' + username;
            this.tweetAction = 'reply';
            this._addEvent('Avatar Reply Button');
            break;
        case 'btn-st clickable':
            window.open('http://twitter.com/'+username + '/status/' + jCue(button)[0].id.replace(' st', ''));
            this._addEvent('Avatar Status Button');
            return false;
            break;
        case 'btn-fv clickable':
            this.tweetAction = 'favorite';
            var statusId = jCue(button)[0].id.replace(' fv', '');

            prefix = 'Favorite ';
            messagePrefix = '@' + username;

            var hash = hex_md5(jCue('#tdia .jtc-message').val() + this.tweetAction);
            var jtcUri = this.baseUri + '/v3/TwitterOAuth.php?message=' + encodeURIComponent(jCue('#tdia .jtc-message').val()) + '&action=' + this.tweetAction + '&hash=' + hash +'&status_id=' + statusId;

            jCue.ajax({
                url: this.baseUri + '/v3/TwitterOAuth.php',
                dataType: 'jsonp',
                cache: false,
                jsonpCallback: 'getAuth',
                success: function(response) {
                    if(response.status == 0) {
                        self._showMessage(response.message);
                    } else if (response.status == 1) { // no authorized
                        //show message box asking to authorize
                        jCue('#tdia .content-messages').empty().html('<span>Please authorize Twitter</span><br /><img class="messages-ok doAuth" src="'+self.imagesUri+'/btn-ok.gif" alt="OK" /><br /><br /><a href="javascript:;" style="margin-top:10px;" onclick="jCue(\'#tdia .content-messages\').jqmHide();">Cancel</a>');
                        jCue('#tdia .doAuth').click(function(resp) {
                            self.popup({'url':self.baseUri+'/v3/TwitterOAuth.php?callback=doAuth','width':'800','height':'400','popupId':'authPop'});
                        });
                        jCue('#tdia .content-messages').jqmShow().css({'height':'auto'}).animate({'opacity':1},200);
                    } else if (response.status == 2) { //authorized

                        jCue(button).css('background-image', 'url('+self.imagesUri+'/favorite_on.png)');

                        this.tweetAction = 'update';

                        jCue.ajax({
                            url: jtcUri,
                            dataType: 'jsonp',
                            cache: false,
                            jsonpCallback: 'sendJtc',
                            success: function(response) {
                                if (response.status == 1) {
                                    // move favorite_on here when toggle is implemented
                                }
                            }
                        });
                    }
                }
            });

            this._addEvent('Avatar Favorite Button');
            return false;
            break;
        };

        jCue('#tdia p.wh').html(prefix + username + ':');
        jCue('#tdia .jtc-message').val(messagePrefix + ' ');
        jCue('#tdia .jtc').trigger('click');
        jCue('#tdia .jtc-message').trigger('keyup');
    },

    //Other Stuff
    _isIE: function () {
        return (((navigator.appVersion.indexOf("MSie") != -1) || navigator.appVersion.indexOf("MSIE") != -1) && !window.opera) ? true : false;
    },

    _log: function (message) {
        if (typeof(console) == 'object' && typeof(console.log) == 'function') {
            console.log(message);
        }
    }
});

/*
MD5
*/
var hexcase = 0;

function hex_md5(a) {
    return rstr2hex(rstr_md5(str2rstr_utf8(a)))
}
function hex_hmac_md5(a, b) {
    return rstr2hex(rstr_hmac_md5(str2rstr_utf8(a), str2rstr_utf8(b)))
}
function md5_vm_test() {
    return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72"
}
function rstr_md5(a) {
    return binl2rstr(binl_md5(rstr2binl(a), a.length * 8))
}
function rstr_hmac_md5(c, f) {
    var e = rstr2binl(c);
    if (e.length > 16) {
        e = binl_md5(e, c.length * 8)
    }
    var a = Array(16),
        d = Array(16);
    for (var b = 0; b < 16; b++) {
        a[b] = e[b] ^ 909522486;
        d[b] = e[b] ^ 1549556828
    }
    var g = binl_md5(a.concat(rstr2binl(f)), 512 + f.length * 8);
    return binl2rstr(binl_md5(d.concat(g), 512 + 128))
}
function rstr2hex(c) {
    try {
        hexcase
    } catch (g) {
        hexcase = 0
    }
    var f = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
    var b = "";
    var a;
    for (var d = 0; d < c.length; d++) {
        a = c.charCodeAt(d);
        b += f.charAt((a >>> 4) & 15) + f.charAt(a & 15)
    }
    return b
}
function str2rstr_utf8(c) {
    var b = "";
    var d = -1;
    var a, e;
    while (++d < c.length) {
        a = c.charCodeAt(d);
        e = d + 1 < c.length ? c.charCodeAt(d + 1) : 0;
        if (55296 <= a && a <= 56319 && 56320 <= e && e <= 57343) {
            a = 65536 + ((a & 1023) << 10) + (e & 1023);
            d++
        }
        if (a <= 127) {
            b += String.fromCharCode(a)
        } else {
            if (a <= 2047) {
                b += String.fromCharCode(192 | ((a >>> 6) & 31), 128 | (a & 63))
            } else {
                if (a <= 65535) {
                    b += String.fromCharCode(224 | ((a >>> 12) & 15), 128 | ((a >>> 6) & 63), 128 | (a & 63))
                } else {
                    if (a <= 2097151) {
                        b += String.fromCharCode(240 | ((a >>> 18) & 7), 128 | ((a >>> 12) & 63), 128 | ((a >>> 6) & 63), 128 | (a & 63))
                    }
                }
            }
        }
    }
    return b
}
function rstr2binl(b) {
    var a = Array(b.length >> 2);
    for (var c = 0; c < a.length; c++) {
        a[c] = 0
    }
    for (var c = 0; c < b.length * 8; c += 8) {
        a[c >> 5] |= (b.charCodeAt(c / 8) & 255) << (c % 32)
    }
    return a
}
function binl2rstr(b) {
    var a = "";
    for (var c = 0; c < b.length * 32; c += 8) {
        a += String.fromCharCode((b[c >> 5] >>> (c % 32)) & 255)
    }
    return a
}
function binl_md5(p, k) {
    p[k >> 5] |= 128 << ((k) % 32);
    p[(((k + 64) >>> 9) << 4) + 14] = k;
    var o = 1732584193;
    var n = -271733879;
    var m = -1732584194;
    var l = 271733878;
    for (var g = 0; g < p.length; g += 16) {
        var j = o;
        var h = n;
        var f = m;
        var e = l;
        o = md5_ff(o, n, m, l, p[g + 0], 7, -680876936);
        l = md5_ff(l, o, n, m, p[g + 1], 12, -389564586);
        m = md5_ff(m, l, o, n, p[g + 2], 17, 606105819);
        n = md5_ff(n, m, l, o, p[g + 3], 22, -1044525330);
        o = md5_ff(o, n, m, l, p[g + 4], 7, -176418897);
        l = md5_ff(l, o, n, m, p[g + 5], 12, 1200080426);
        m = md5_ff(m, l, o, n, p[g + 6], 17, -1473231341);
        n = md5_ff(n, m, l, o, p[g + 7], 22, -45705983);
        o = md5_ff(o, n, m, l, p[g + 8], 7, 1770035416);
        l = md5_ff(l, o, n, m, p[g + 9], 12, -1958414417);
        m = md5_ff(m, l, o, n, p[g + 10], 17, -42063);
        n = md5_ff(n, m, l, o, p[g + 11], 22, -1990404162);
        o = md5_ff(o, n, m, l, p[g + 12], 7, 1804603682);
        l = md5_ff(l, o, n, m, p[g + 13], 12, -40341101);
        m = md5_ff(m, l, o, n, p[g + 14], 17, -1502002290);
        n = md5_ff(n, m, l, o, p[g + 15], 22, 1236535329);
        o = md5_gg(o, n, m, l, p[g + 1], 5, -165796510);
        l = md5_gg(l, o, n, m, p[g + 6], 9, -1069501632);
        m = md5_gg(m, l, o, n, p[g + 11], 14, 643717713);
        n = md5_gg(n, m, l, o, p[g + 0], 20, -373897302);
        o = md5_gg(o, n, m, l, p[g + 5], 5, -701558691);
        l = md5_gg(l, o, n, m, p[g + 10], 9, 38016083);
        m = md5_gg(m, l, o, n, p[g + 15], 14, -660478335);
        n = md5_gg(n, m, l, o, p[g + 4], 20, -405537848);
        o = md5_gg(o, n, m, l, p[g + 9], 5, 568446438);
        l = md5_gg(l, o, n, m, p[g + 14], 9, -1019803690);
        m = md5_gg(m, l, o, n, p[g + 3], 14, -187363961);
        n = md5_gg(n, m, l, o, p[g + 8], 20, 1163531501);
        o = md5_gg(o, n, m, l, p[g + 13], 5, -1444681467);
        l = md5_gg(l, o, n, m, p[g + 2], 9, -51403784);
        m = md5_gg(m, l, o, n, p[g + 7], 14, 1735328473);
        n = md5_gg(n, m, l, o, p[g + 12], 20, -1926607734);
        o = md5_hh(o, n, m, l, p[g + 5], 4, -378558);
        l = md5_hh(l, o, n, m, p[g + 8], 11, -2022574463);
        m = md5_hh(m, l, o, n, p[g + 11], 16, 1839030562);
        n = md5_hh(n, m, l, o, p[g + 14], 23, -35309556);
        o = md5_hh(o, n, m, l, p[g + 1], 4, -1530992060);
        l = md5_hh(l, o, n, m, p[g + 4], 11, 1272893353);
        m = md5_hh(m, l, o, n, p[g + 7], 16, -155497632);
        n = md5_hh(n, m, l, o, p[g + 10], 23, -1094730640);
        o = md5_hh(o, n, m, l, p[g + 13], 4, 681279174);
        l = md5_hh(l, o, n, m, p[g + 0], 11, -358537222);
        m = md5_hh(m, l, o, n, p[g + 3], 16, -722521979);
        n = md5_hh(n, m, l, o, p[g + 6], 23, 76029189);
        o = md5_hh(o, n, m, l, p[g + 9], 4, -640364487);
        l = md5_hh(l, o, n, m, p[g + 12], 11, -421815835);
        m = md5_hh(m, l, o, n, p[g + 15], 16, 530742520);
        n = md5_hh(n, m, l, o, p[g + 2], 23, -995338651);
        o = md5_ii(o, n, m, l, p[g + 0], 6, -198630844);
        l = md5_ii(l, o, n, m, p[g + 7], 10, 1126891415);
        m = md5_ii(m, l, o, n, p[g + 14], 15, -1416354905);
        n = md5_ii(n, m, l, o, p[g + 5], 21, -57434055);
        o = md5_ii(o, n, m, l, p[g + 12], 6, 1700485571);
        l = md5_ii(l, o, n, m, p[g + 3], 10, -1894986606);
        m = md5_ii(m, l, o, n, p[g + 10], 15, -1051523);
        n = md5_ii(n, m, l, o, p[g + 1], 21, -2054922799);
        o = md5_ii(o, n, m, l, p[g + 8], 6, 1873313359);
        l = md5_ii(l, o, n, m, p[g + 15], 10, -30611744);
        m = md5_ii(m, l, o, n, p[g + 6], 15, -1560198380);
        n = md5_ii(n, m, l, o, p[g + 13], 21, 1309151649);
        o = md5_ii(o, n, m, l, p[g + 4], 6, -145523070);
        l = md5_ii(l, o, n, m, p[g + 11], 10, -1120210379);
        m = md5_ii(m, l, o, n, p[g + 2], 15, 718787259);
        n = md5_ii(n, m, l, o, p[g + 9], 21, -343485551);
        o = safe_add(o, j);
        n = safe_add(n, h);
        m = safe_add(m, f);
        l = safe_add(l, e)
    }
    return Array(o, n, m, l)
}
function md5_cmn(h, e, d, c, g, f) {
    return safe_add(bit_rol(safe_add(safe_add(e, h), safe_add(c, f)), g), d)
}
function md5_ff(g, f, k, j, e, i, h) {
    return md5_cmn((f & k) | ((~f) & j), g, f, e, i, h)
}
function md5_gg(g, f, k, j, e, i, h) {
    return md5_cmn((f & j) | (k & (~j)), g, f, e, i, h)
}
function md5_hh(g, f, k, j, e, i, h) {
    return md5_cmn(f ^ k ^ j, g, f, e, i, h)
}
function md5_ii(g, f, k, j, e, i, h) {
    return md5_cmn(k ^ (f | (~j)), g, f, e, i, h)
}
function safe_add(a, d) {
    var c = (a & 65535) + (d & 65535);
    var b = (a >> 16) + (d >> 16) + (c >> 16);
    return (b << 16) | (c & 65535)
}
function bit_rol(a, b) {
    return (a << b) | (a >>> (32 - b))
};

