

var wl_im_widget = 
{
    _base_url: 'http://apps.widgetlaboratory.com/',
    _script_tag: false,
    _head_tag: document.getElementsByTagName("head").item(0),
    _wl_app: {},
    _wl_profile: {},
    _last_msg: {},
    _current_msg: false,
    _users: {},
    _outgoing_msg: false,
    _data: [],
    _showing: false,
    _refresh_timeout: false,
    _showing_arr: [],
    _play_sound: false,
    _ignore_msg: false,
    _rcvsound: 'http://apps.widgetlaboratory.com/newIM.mp3',
    _ad_interval: '1000005',
    _msg_number: 0,
    _ad_click: 'http://widgetlaboratory.com',
    _ad_src: 'http://apps.widgetlaboratory.com/lab_ad.jpg',
    _last_update_time: 0,
    _debug: false,
    _max_msg_len: 250,
    _timeout: 1200,
    _timeout_count: 0,
    _widget_active: true,
    loadCss: function(stylesheet_url) {
        stylesheet = document.createElement("link");
        stylesheet.rel = "stylesheet";
        stylesheet.type = "text/css";
        stylesheet.href = stylesheet_url;
        stylesheet.media = "all";
        document.lastChild.firstChild.appendChild(stylesheet)
    },
    loadJs: function(params) {
        this._script_tag = document.createElement('script');
        this._script_tag.src = this._base_url + params + '&no_cache=' + (new Date()).getTime();

        this._head_tag.appendChild(this._script_tag)
    },
    monitorConnection: function() {
        if (wl_im_widget == 0) return;
        var t = new Date().getTime();
        if (t - wl_im_widget._last_update_time > 180000) {
            wl_im_widget.refresh()
        }
    },
    monitorActivity: function() {
        if (wl_im_widget._timeout_count < 1) {
            wl_im_widget._widget_active = false;
            wl_im_widget._timeout_count - 0
        } else {
            wl_im_widget._timeout_count--
        }
    },
    limitMessage: function(el) {
        if (el.value.length > wl_im_widget._max_msg_len) {
            el.value = el.value.substr(0, wl_im_widget._max_msg_len)
        }
    },
    callback: function() {
        var data = wl_im_widget._data;
        if (!data) return;
        wl_im_widget._users = data.d;
        if (wl_im_widget._script_tag) document.getElementsByTagName("head").item(0).removeChild(wl_im_widget._script_tag);
        var h = "";
        
        //for (var i in data.d) {
        data.d.each(function(item, index) {
            h += '<div class="im_avatar_div"><img src="' + item.t + '" style="width:40px;height:40px" alt="' + item.fn + '" title="' + item.fn + '" sid="' + item.sname + '" class="avatar" onclick="wl_im_widget.showSendMessage(\'' + item.sname + '\')"/><div class="wl_im_user_status im_status_';
            h += (item.igm == 1) ? 'offline': 'online';
            h += '"></div></div>'
        });
        
        $('wl_im_icons').innerHTML = h;
        wl_im_widget.showReceivedMessage();
        if (typeof data.ref_speed != 'undefined') {
            if (wl_im_widget._refresh_timeout) clearTimeout(wl_im_widget._refresh_timeout);
            wl_im_widget._refresh_timeout = setTimeout(wl_im_widget.refresh, data.ref_speed * 1000);
            wl_im_widget._last_update_time = new Date().getTime()
        }
    },
    showReceivedMessage: function() {
        if (wl_im_widget._ignore_msg) return;
        
        if (wl_im_widget._data.m) {
            if (wl_im_widget._data.m[0]) {
                var mm = wl_im_widget._data.m[0].shift();
                if (!mm) return;
                var t = [];
                
                wl_im_widget._showing_arr.each( function (n, i) {
                	
	               if (n == mm.id) t.push(n);
                	}
	            );
	            
                if (t.length == 0) {
                    wl_im_widget._showing_arr.push(mm.id);
                    var user = wl_im_widget.getUser(mm.from_id);
                    var md = document.getElementById('wl_im_message');
                    var _im = new Element('div', {'class':'wl_im_body', 'id':'wl_im_'+mm.id});
                    
                    var h = '<div class="wl_im_title"></div><div class="wl_im_msg_body"><h2>From: ' + wl_im_widget.chopName(mm.from_fn) + '</h2><img src="' + mm.image + '" style="width:40px;height:40px" class="wl_im_avatar" onclick="window.open(\'/members/profile/' + mm.from_id + '\',\'_parent\')"/>';
                    h += '<div class="wl_im_msg">' + mm.msg + '</div><textarea onKeyPress="wl_im_widget.limitMessage(this)" class="wl_im_ta" id="wl_im_ta_' + mm.id + '" style="display:none"></textarea></div><div class="wl_im_action wl_im_receive_action"><a href="JavaScript:wl_im_widget. closeReceivedMessage(\'' + mm.id + '\')" class="wl_im_close">Close</a>';
                    if (typeof user == "undefined") {
                        wl_im_widget.closeMessage(mm.id);
                        wl_im_widget.showReceivedMessage();
                        return
                    }
                    if (user.igm != 1) h += '<a href="JavaScript:wl_im_widget.reply(\'' + mm.from_id + '\',\'' + mm.id + '\', \'' + encodeURIComponent(wl_im_widget.chopName(mm.from_fn)).replace(/\'/g, '\\\'') + '\')" class="wl_im_send">Reply</a>';
                    h += '</div><div class="wl_im_action wl_im_send_action" style="display:none"><a href="JavaScript:wl_im_widget. closeMessage(\'' + mm.id + '\')" class="wl_im_close">Close</a>';
                    h += '<a href="JavaScript:wl_im_widget.sendMessage(\'' + mm.from_id + '\', \'' + mm.id + '\')" class="wl_im_send">Send Message</a></div>';
                    
                    if (wl_im_widget._play_sound) {
                    
                        if ($('wl_im_soundpixel').innerHTML == "") {
                            $('wl_im_soundpixel').innerHTML = '<embed type="application/x-shockwave-flash" width="1" height="1" allowscriptaccess="never" quality="best" src="http://apps.widgetlaboratory.com/soundpixel.swf?mp3=' + wl_im_widget._rcvsound + '" wmode="transparent" flashvars="playerMode=embedded" />';
                            setTimeout(function() {
                                document.getElementById('wl_im_soundpixel').innerHTML = ""
                            },
                            3000)
                        }
                    }
                    wl_im_widget._current_msg = mm;
                    _im.set('html', h);
                    _im.inject($('wl_im_message'));
                    
//                    $('wl_im_message').innerHTML += $('wl_im_message').innerHTML + h;
//                    $('wl_im_' + mm.id).fade('in');
                    wl_im_widget._msg_number++;
                    if (wl_im_widget._msg_number == wl_im_widget._ad_interval) {
                        wl_im_widget._msg_number = 0;
                        wl_im_widget.showAd()
                    }
                }
            }
        }
        if (typeof wl_im_widget._data.m == 'object') {
            var rest = wl_im_widget._data.m[0];
            if (rest.length > 0) {
                setTimeout(wl_im_widget.showReceivedMessage, 1000)
            }
        }
    },
    chopName: function(fn) {
        if (fn.length > 33) return fn.substr(0, 33);
        return fn
    },
    showAd: function() {
        var rand = (new Date()).getTime();
        var adimg = $("<img>");
        adimg.attr("src", wl_im_widget._ad_src + '&amp;cb=' + rand);
        var h = "<div class='wl_im_body wl_im_ad' id='wl_im_ad" + rand + "'><div class='wl_im_title'></div><div class='wl_im_msg_body'><h2>Sponsored Ad:</h2><center><a href='" + wl_im_widget._ad_click + "' target='_blank'><img src='" + wl_im_widget._ad_src + "' border='0' alt='' /></a></center></div><div class='wl_im_ad_btm'></div></div>";
        $('#wl_im_message').prepend(h);
        setTimeout(function() {
            $('#wl_im_ad' + rand).fadeIn('slow',
            function() {
                setTimeout(function() {
                    $('#wl_im_ad' + rand).fadeOut('slow',
                    function() {
                        $('#wl_im_ad' + rand).remove()
                    })
                },
                10000)
            })
        },
        2000)
    },
    reply: function(sn, mid, fn) {
        wl_im_widget.deleteMessage(mid);
        $('wl_im_ta_' + mid).setStyle('display', 'block');
        $$('#wl_im_ta_' + mid)[0].focus();
        $$('#wl_im_' + mid + ' div.wl_im_msg').setStyle('display', 'none');
        $$('#wl_im_' + mid + ' div.wl_im_receive_action').setStyle('display', 'none');
        $$('#wl_im_' + mid + ' div.wl_im_send_action').setStyle('display', 'block');
        $$('#wl_im_' + mid + ' h2').innerHTML = ('Reply to ' + fn);
        wl_im_widget._timeout_count = wl_im_widget._timeout
    },
    refresh: function() {
        if (wl_im_widget._widget_active) {
            var i = wl_im_widget._ignore_msg ? 1 : 0;
            wl_im_widget.loadJs('whoim.php?dom=&app=' + (wl_im_widget._wl_app) + '&lm=' + wl_im_widget._current_msg.id + '&p=' + (wl_im_widget._wl_profile) + '&im=' + i)
        } else {
            $('wl_instant_messanger').innerHTML = ('<center><img src="http://apps.widgetlaboratory.com/images/tubes.png" style="cursor:pointer; max-width:152px !important" onclick="wl_im_widget.restart()"/></center>')
        }
    },
    restart: function() {
        wl_im_widget._timeout_count = wl_im_widget._timeout;
        wl_im_widget._widget_active = true;
        document.getElementById('wl_instant_messanger').innerHTML = '<div id="wl_im_icons"><img src="http://apps.widgetlaboratory.com/images/ajax-loader.gif"/></div>';
        wl_im_widget.refresh()
    },
    showSendMessage: function(sn) {

        if (!snmWidget.uid) return;
        if (sn == snmWidget.uid) return wl_im_widget.showSettings();
        var user = wl_im_widget.getUser(sn);
        var mid = 'n' + (new Date()).getTime();
        
        var _el = new Element('div', {'class':'wl_im_body', 'id':'wl_im_' + mid});        
        var h = '<div class="wl_im_title"></div><div class="wl_im_msg_body"><h2>To: ' + wl_im_widget.chopName(user.fn) + '</h2><img src="' + user.t + '" style="width:40px;height:40px" class="wl_im_avatar" onclick="window.open(\'/members/profile/' + sn + '\',\'_parent\')"/>';
        if (user.igm == 1) {
            h += '<div class="wl_im_msg">Sorry but this user is ignoring all messages.</div>'
        } else {
            h += '<textarea id="wl_im_ta_' + mid + '" onKeyPress="wl_im_widget.limitMessage(this)" class="wl_im_ta"></textarea>'
        }
        h += '</div><div class="wl_im_action wl_im_send_action"><a href="JavaScript:wl_im_widget. closeMessage(\'' + mid + '\')" class="wl_im_close">Close</a>';
        if (user.igm != 1) h += '<a href="JavaScript:wl_im_widget.sendMessage(\'' + sn + '\', \'' + mid + '\')" class="wl_im_send">Send Message</a></div></div>';

		
        _el.set('html', h);
		_el.inject($('wl_im_message'));
//        var th = $('wl_im_message').innerHTML;
//        $('wl_im_message').innerHTML = h + th

//        $('wl_im_' + mid).fade('in');
        if (user.igm == 0) document.getElementById('wl_im_ta_' + mid).focus();
    },
    
    showSettings: function() 
    {
        //var user = ning.CurrentProfile;
        var saved = wl_im_widget.getSettings();
        
        var _settings = new Element('div', {'id':'wl_im_settings'});
		
		var h = '<div class="wl_im_body"><div class="wl_im_title"></div><div class="wl_im_msg_body"><h2>My Settings</h2>';
        h += '<input type="checkbox" id="wl_im_snd_box"';
        if (saved[0] == 'true') h += ' checked="checked"';
        h += '/> <label for="wl_im_snd_box">Enable Sound Notifications</label><br/>';
        h += '<input type="checkbox" id="wl_im_ignore_box"';
        if (saved[1] == 'true') h += ' checked="checked"';
        h += '/> <label for="wl_im_ignore_box">Ignore All Messages</label><br/>';
        h += '</div><div class="wl_im_action"><a href="JavaScript:wl_im_widget. closeSettings()" class="wl_im_close">Close</a><a href="JavaScript:wl_im_widget.saveSettings()" class="wl_im_save">Save</a></div></div>';        
        _settings.set('html', h);        
        _settings.injectInside($(document.body));        
//        $(document.body).innerHTML = $(document.body).innerHTML + h;
        //$('wl_im_settings').getElement('div.wl_im_body').fade('in');
        _settings.fade('in');

    },
    saveSettings: function() 
    {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + 30);
        var settings = $('wl_im_snd_box').checked + "," + $('wl_im_ignore_box').checked;
        document.cookie = "wl_im_widget_settings=" + escape(settings) + ";expires=" + exdate.toGMTString();
        this._play_sound = $('wl_im_snd_box').checked;
        this._ignore_msg = $('wl_im_ignore_box').checked;
        $('wl_im_settings').getElement('div.wl_im_body').fade('out');
        $('wl_im_settings').remove();
        wl_im_widget.refresh()
    },
    getSettings: function() {
        if (document.cookie.length > 0) {
            var cs = document.cookie.indexOf("wl_im_widget_settings=");
            if (cs != -1) {
                cs = cs + 'wl_im_widget_settings'.length + 1;
                ce = document.cookie.indexOf(";", cs);
                if (ce == -1) ce = document.cookie.length;
                var val = unescape(document.cookie.substring(cs, ce));
                val = val.split(",");
                return val
            }
        }
        return ['false', 'false']
    },
    closeSettings: function() {
        $('wl_im_settings').getElement('div.wl_im_body').fade('out');
        $('wl_im_settings').remove();
    },
    closeMessage: function(mid) {
        $('wl_im_' + mid).fade('out');
	$('wl_im_' + mid).remove();
    },
    closeReceivedMessage: function(mid) {
        wl_im_widget.deleteMessage(mid);
        $('wl_im_' + mid).fade('out');
        $('wl_im_' + mid).remove()
        
    },
    deleteMessage: function(mid) {
        wl_im_widget._timeout_count = wl_im_widget._timeout;
        if (wl_im_widget._outgoing_msg) wl_im_widget._head_tag.removeChild(wl_im_widget._outgoing_msg);
        var jq = document.createElement('script');
        wl_im_widget._last_msg = mid;
        jq.src = this._base_url + 'removemsg.php?dom=&from=' + snmWidget.uid + '&net=' + snmWidget.site_id + '&m=' + mid;
        wl_im_widget._head_tag.appendChild(jq);
        wl_im_widget._outgoing_msg = jq
    },
    sendMessage: function(sn, mid) {
        var tv = document.getElementById('wl_im_ta_' + mid).value;
        if (!tv.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) return;
        if (this._outgoing_msg) this._head_tag.removeChild(this._outgoing_msg);
        var jq = document.createElement('script');
        var i = wl_im_widget._ignore_msg ? 1 : 0;
        jq.src = this._base_url + 'sendmsg.php?dom=&from=' + snmWidget.uid + '&to=' + sn + '&net=' + snmWidget.site_id + '&i=' + i + '&m=' + encodeURIComponent(tv);
        this._head_tag.appendChild(jq);
        this._outgoing_msg = jq;
        $('wl_im_' + mid).fade('out');
        $('wl_im_' + mid).remove();
        wl_im_widget._msg_number++;
        if (wl_im_widget._msg_number == wl_im_widget._ad_interval) {
            wl_im_widget._msg_number = 0;
            wl_im_widget.showAd()
        }
    },
    getUser: function(sn) {
        for (var i in wl_im_widget._users) {
            if (wl_im_widget._users[i].sname == sn) return wl_im_widget._users[i]
        }
    },
    receiveMessage: function(data) {
        //alert('got the message')
    },
    avatarClick: function(sn) {
        wl_im_widget.showSendMessage(sn)
    },
    formatTime: function(ts) {
        var t = new Date(ts * 1000);
        var hour = t.getHours();
        var min = t.getMinutes();
        if (min < 10) min = '0' + min;
        var ampm = "am";
        if (hour == 0) hour = 12;
        if (hour > 11) ampm = "pm";
        if (hour > 12) hour -= 12;
        return (hour + ":" + min + ampm)
    },
    
    setupJq: function() 
    {
    	
//		$(document.body).inject('<div id="wl_im_message"></div>');
		var b = new Element('div', {'id':'wl_im_message'});
		b.injectInside($(document.body));
		wl_im_widget.refresh();
		window.setInterval(wl_im_widget.monitorActivity, 1000);
		window.setInterval(wl_im_widget.monitorConnection, 100000)
    },
    
    init: function() 
    {
    	
        if (!$('sb-user-account')) return;
        
        this.loadCss('http://apps.widgetlaboratory.com/sogowhoim.css');
        
        var _im = new Element('div', {'id':'wl_instant_messanger'});
        
        var h = '<h2>Who-Im</h2><div id="wl_im_icons"></div></div><div id="wl_im_soundpixel"></div><div style="clear:both"><img title="Viva Laboratoria!" style="cursor: pointer;" onclick="window.open(\'http://widgetlaboratory.com\', \'lab\')" src="http://apps.widgetlaboratory.com/images/powered-by-light.gif"/>';
        
        _im.set('html', h);        
        _im.injectInside($('sb-user-account'));   
        

        this._timeout_count = this._timeout;
        this._wl_app.id = snmWidget.site_id;
        this._wl_app.url = snmWidget.site_url;
        if (snmWidget.profile) {
            this._wl_profile.photoUrl = unescape(snmWidget.avatars.chatavatar);
            this._wl_profile.fullName = snmWidget.nickname;
            this._wl_profile.id = snmWidget.uid;
        }
        
        this._wl_app = JSON.encode(this._wl_app);
        this._wl_profile = JSON.encode(this._wl_profile);
                
        var saved = wl_im_widget.getSettings();
        this._play_sound = (saved[0] == 'true') ? true: false;
        this._ignore_msg = (saved[1] == 'true') ? true: false;

		this.setupJq();
    }                                                                                          
}
window.addEvent('domready', function() { 
   wl_im_widget.init()
});
