var wl_im_widget = 
{
    _base_url: 'http://lab1.ningina.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://ningina.com/newIM.mp3',
    _ad_interval: '5',
    _msg_number: 0,
    _ad_click: 'http://widgetlaboratory.com',
    _ad_src: 'http://ningina.com/lab_ad.jpg',
    _last_update_time: 0,
    _debug: false,
    _max_msg_len: 250,
    _timeout: 600,
    _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) {
            h += '<div class="im_avatar_div"><img src="' + data.d[i].t + '?crop=1%3A1&width=40&height=40" alt="' + data.d[i].fn + '" title="' + data.d[i].fn + '" sid="' + data.d[i].sname + '" class="avatar" onclick="wl_im_widget.showSendMessage(\'' + data.d[i].sname + '\')"/><div class="wl_im_user_status im_status_';
            h += (data.d[i].igm == 1) ? 'offline': 'online';
            h += '"></div></div>'
        }
        jQuery('#wl_im_icons').html(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;
        jQuery('#xn_bar').css('z-index', '0');
        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 = jQuery.grep(wl_im_widget._showing_arr,
                function(i) {
                    return i == mm.id
                });
                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 h = '<div class="wl_im_body" id="wl_im_' + mm.id + '"><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 + '?width=40&height=40&crop=1%3A1" class="wl_im_avatar" onclick="window.open(\'/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></div>';
                    
                    if (wl_im_widget._play_sound) {
                    
                        if (jQuery('#wl_im_soundpixel').html() == "") {
                            jQuery('#wl_im_soundpixel').html('<embed type="application/x-shockwave-flash" width="1" height="1" allowscriptaccess="never" quality="best" src="http://ningina.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;
                    jQuery('#wl_im_message').append(h);
                    jQuery('#wl_im_' + mm.id).fadeIn('slow');
                    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 = jQuery("<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>";
        jQuery('#wl_im_message').prepend(h);
        setTimeout(function() {
            jQuery('#wl_im_ad' + rand).fadeIn('slow',
            function() {
                setTimeout(function() {
                    jQuery('#wl_im_ad' + rand).fadeOut('slow',
                    function() {
                        jQuery('#wl_im_ad' + rand).remove()
                    })
                },
                10000)
            })
        },
        2000)
    },
    reply: function(sn, mid, fn) {
        wl_im_widget.deleteMessage(mid);
        jQuery('#wl_im_ta_' + mid).css('display', 'block');
        jQuery('#wl_im_ta_' + mid)[0].focus();
        jQuery('#wl_im_' + mid + ' div.wl_im_msg').css('display', 'none');
        jQuery('#wl_im_' + mid + ' div.wl_im_receive_action').css('display', 'none');
        jQuery('#wl_im_' + mid + ' div.wl_im_send_action').css('display', 'block');
        jQuery('#wl_im_' + mid + ' h2').html('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?app=' + (wl_im_widget._wl_app) + '&lm=' + wl_im_widget._current_msg.id + '&p=' + (wl_im_widget._wl_profile) + '&im=' + i)
        } else {
            jQuery('#wl_instant_messanger').html('<center><img src="http://ningina.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;
        jQuery('#wl_instant_messanger').html('<div id="wl_im_icons"><img src="http://ningina.com/images/ajax-loader.gif"/></div>');
        wl_im_widget.refresh()
    },
    showSendMessage: function(sn) {
        if (!ning.CurrentProfile) return;
        if (sn == ning.CurrentProfile.id) return wl_im_widget.showSettings();
        var user = wl_im_widget.getUser(sn);
        var mid = 'n' + (new Date()).getTime();
        var h = '<div class="wl_im_body" id="wl_im_' + mid + '"><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 + '?width=40&height=40&crop=1%3A1" class="wl_im_avatar" onclick="window.open(\'/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></div>';
        if (jQuery.browser.msie) {
            var th = jQuery('#wl_im_message')[0].innerHTML;
            jQuery('#wl_im_message')[0].innerHTML = h + th
        } else {
            jQuery('#wl_im_message').prepend(h)
        }
        jQuery('#wl_im_' + mid).fadeIn('slow',
        function() {
            if (user.igm == 0) document.getElementById('wl_im_ta_' + mid).focus()
        })
    },
    showSettings: function() {
        var user = ning.CurrentProfile;
        var saved = wl_im_widget.getSettings();
        var h = '<div id="wl_im_settings"><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></div>';
        jQuery('body').append(h);
        jQuery('#wl_im_settings div.wl_im_body').fadeIn('slow')
    },
    saveSettings: function() {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + 30);
        var settings = jQuery('#wl_im_snd_box')[0].checked + "," + jQuery('#wl_im_ignore_box')[0].checked;
        document.cookie = "wl_im_widget_settings=" + escape(settings) + ";expires=" + exdate.toGMTString();
        this._play_sound = jQuery('#wl_im_snd_box')[0].checked;
        this._ignore_msg = jQuery('#wl_im_ignore_box')[0].checked;
        jQuery('#wl_im_settings div.wl_im_body').fadeOut('slow',
        function() {
            jQuery('#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() {
        jQuery('#wl_im_settings div.wl_im_body').fadeOut('slow',
        function() {
            jQuery('#wl_im_settings').remove()
        })
    },
    closeMessage: function(mid) {
        jQuery('#wl_im_' + mid).fadeOut('slow',
        function() {
            jQuery(this).remove()
        })
    },
    closeReceivedMessage: function(mid) {
        wl_im_widget.deleteMessage(mid);
        jQuery('#wl_im_' + mid).fadeOut('slow',
        function() {
            jQuery(this).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?from=' + ning.CurrentProfile.id + '&net=' + ning.CurrentApp.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?from=' + ning.CurrentProfile.id + '&to=' + sn + '&net=' + ning.CurrentApp.id + '&i=' + i + '&m=' + encodeURIComponent(tv);
        this._head_tag.appendChild(jq);
        this._outgoing_msg = jq;
        jQuery('#wl_im_' + mid).fadeOut('slow',
        function() {
            jQuery('#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() {
    	        	
        	wl_im_widget._wl_app = (encodeURIComponent(jQuery.toJSON(wl_im_widget._wl_app)));
	        wl_im_widget._wl_profile = (encodeURIComponent(jQuery.toJSON(wl_im_widget._wl_profile)));
            if (jQuery.browser.msie) wl_im_widget.loadCss('http://ningina.com/css/im_ie.css');
            jQuery('body').append('<div id="wl_im_message"></div>');
            
            wl_im_widget.refresh();

            window.setInterval(wl_im_widget.monitorActivity, 1000);
            window.setInterval(wl_im_widget.monitorConnection, 100000)

    },
    
    init: function() {
    
        this.loadCss('http://ningina.com/whoim.css');
        if (typeof jQuery != "function") {
            var jq = document.createElement('script');
            jq.src = 'http://ningina.com/js/jquery.js';
            this._head_tag.appendChild(jq)
        }
        this._timeout_count = this._timeout;
        this._wl_app.domains = ning.CurrentApp.domains;
        this._wl_app.id = ning.CurrentApp.id;
        this._wl_app.url = ning.CurrentApp.url;
        if (ning.CurrentProfile) {
            this._wl_profile.photoUrl = ning.CurrentProfile.photoUrl;
            this._wl_profile.fullName = ning.CurrentProfile.fullName;
            this._wl_profile.id = ning.CurrentProfile.id
        }
        var saved = wl_im_widget.getSettings();
        this._play_sound = (saved[0] == 'true') ? true: false;
        this._ignore_msg = (saved[1] == 'true') ? true: false;
        	
        this.setupJq()
    }                                                                                          
}
document.write('<div id="wl_instant_messanger"><div id="wl_im_icons"></div></div>');
document.write('<div id="wl_im_soundpixel"></div>');
document.write('<div style="clear:both"><img title="Viva Laboratoria!" style="cursor: pointer;" onclick="window.open(\'http://widgetlaboratory.com\', \'lab\')" src="http://ningina.com/powered-by-light.gif"/></div>');

if (typeof wl_onload_event != "function") 
{
    function wl_onload_event(fnc){
      if ( typeof window.addEventListener != "undefined" )
        window.addEventListener( "load", fnc, false );
      else if ( typeof window.attachEvent != "undefined" ) {
        window.attachEvent( "onload", fnc );
      }
      else {
        if ( window.onload != null ) {
          var oldOnload = window.onload;
          window.onload = function ( e ) {
            oldOnload( e );
            window[fnc]();
          };
        }
        else
          window.onload = fnc;
      }
    }
}

wl_onload_event(function() {
	wl_im_widget.init()
});
