﻿function popup(url, height, width)
{
    window.open(url,null, 'directories=no,height=' + height +',resizable=yes,scrollbars=yes,location=no,menubar=no,status=no,toolbar=no,width=' + width);
}

function showHide(element)
{
    var e = $('#' + element).toggle();
    if (e.is(':visible')) {
        window.scrollBy(0, 80);
    }
}

function confirmDelete()
{
    return window.confirm(LushResource.Delete_Record);
}

function toggleEmbellish()
{
    var embellish = document.getElementById('EmbellishSection');
    if (embellish.style.display == 'none')
    {
        embellish.style.display = 'block';
        document.getElementById('ShowLabel').innerHTML = LushResource.Hide_Details;
        document.getElementById('ShowImage').src = '/images/collapse.jpg';
    }
    else
    {
        embellish.style.display = 'none';
        document.getElementById('ShowLabel').innerHTML = LushResource.Show_Details;
        document.getElementById('ShowImage').src = '/images/expand.jpg';
    }   
}

function add_bookmark() {
	var ver = navigator.appName;
	var num = parseInt(navigator.appVersion);
	if ((ver == "Microsoft Internet Explorer")&&(num >= 4)) {
	    window.external.AddFavorite(LushResource.Site_Url, LushResource.Site_Name);
	}else{
	    alert(LushResource.Browser_Not_Supported);
	} 
}

Function.createDelegate = function(instance,method){return function(){method.apply(instance,arguments);}}

// vertical scroll
var speed=6; // scroll speed (bigger = faster)
var dR=false; // reverse direction
// Vertical Scroller Javascript
// copyright 24th September 2005, by Stephen Chapman
// permission to use this Javascript on your web page is granted
// provided that all of the code below (as well as these
// comments) is used without any alteration
var step = 2; function objWidth(obj) {if(obj.offsetWidth) return obj.offsetWidth; if (obj.clip) return obj.clip.width; return 0;} function objHeight(obj) {if(obj.offsetHeight) return obj.offsetHeight; if (obj.clip) return obj.clip.height; return 0;} function scrF(i,sH,eH){var x=parseInt(i.top)+(dR? step: -step); if(dR && x>sH)x=-eH;else if(x<2-eH)x=sH;i.top = x+'px';} function startScroll(sN,txt){var scr=document.getElementById(sN); var sW = objWidth(scr)-6; var sH = objHeight(scr); scr.innerHTML = '<div id="'+sN+'in" style="position:absolute; left:3px; width:'+sW+';">'+txt+'<\/div>'; var sTxt=document.getElementById(sN+'in'); var eH=objHeight(sTxt); sTxt.style.top=(dR? -eH : sH)+'px'; sTxt.style.clip='rect(0,'+sW+'px,'+eH+'px,0)'; setInterval(function() {scrF(sTxt.style,sH,eH);},1000/speed);}

var ActiveUsers = function(args) {
    this._args = args;
    $('#' + args.Selector).bind('click', this, function(e) {
        var menu=null;
        $.ajax({
            type: "POST",
            url: "/services/memberservice.asmx/GetLoggedOnMembers",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: Function.createDelegate(this, 
                function(results) {
                  var buffer='';
                  var ctx = e.data;
                  $.each(results.d, function() {
                    buffer += ' <a href="/' + encodeURI(this) + '">' + this + '</a> ';
                  });
                  $('#activeusers img').hide();
                  $('#activeusers p').html(buffer);
                  if (menu != null) {
                    menu.Clear();
                  }
                  menu = new MemberContextMenu({Scope: '#activeusers p a'});
                }
            )
          });
        
        $('#activeusers').css({top: e.pageY+'px', left: e.pageX+'px'}).slideDown();
        e.stopPropagation();
        var timerId = null;
        
        var flashAds = $('#adspot');
        if (flashAds.length > 0) {
            flashAds.css('visibility','hidden');
        }
        
        $('body, #close-tag a').click(function(e) {
            if (menu != null) {
                menu.Clear();
            }
            $('#activeusers').slideUp(); 
            if (flashAds.length > 0) {
                flashAds.css('visibility','visible');
            }
            $('body, #close-tag a').unbind('click');
        });    
    });
}

function closeGrowl(ctx) {
    var me = $(ctx);
    var container = me.closest('div.jGrowl-notification').find('div.close');
    if (container.length !== 0) {
        container.trigger('click.jGrowl');
    }
}

function openChatWindow(member, usernameKey, id) {
    var qs = usernameKey+'='+member;
    if (typeof id != 'undefined') {
         qs += '&id='+id;
     }
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    var win = window.open(encodeURI('/membership/chat.aspx?' + qs), member + 'chat', 'width=680,height=370,directories=0,location=0,menubar=0,scrollbars=0,status=0,toolbar=0,resizable=1');
    if (!win || win == null || typeof win == undefined || (is_chrome && id != undefined)) {
        var link = "javascript:openChatWindow('" + encodeURIComponent(member) + "', '" + usernameKey + "', '" + encodeURIComponent(id) + "');";
        var flashAds = $('#adspot');
        $.jGrowl(member + ' ' + LushResource.Chat_Request_Pre + ' <a onclick="closeGrowl(this)" href="' + link + '">' + LushResource.Chat_Request_Post + '</a>?<br/><br/>' + LushResource.Allow_Popus, 
            {header: LushResource.Chat_Growl_Header,
            sticky: true,
            beforeOpen: function(e,m,o) {
                if (flashAds.length > 0) {
                    flashAds.css('visibility','hidden');
                }    
            },
            beforeClose: function(e,m,p) {
                if (flashAds.length > 0) {
                    flashAds.css('visibility','visible');
                }
            }
            });        
        if (confirm(LushResource.Chat_Blocked_Pre + ' ' + member + LushResource.Chat_Blocked_Post)) {
            window.location = '/allow-popups.aspx';
        }
        return;
    }
    win.focus();
}

var MemberContextMenu = function(args) {
    this._args = args;
    this._selector = (this._args != null && this._args.Scope != null ? this._args.Scope : '.author-link');
    this._baseMenu;
    this._init();
}

MemberContextMenu.prototype = {
    _init: function () {
        this._baseMenu = $('#idAuthorMenu');

        $(this._selector).bind('mouseover', this, function (e) {
            var ctx = e.data;

            e.preventDefault();
            e.stopPropagation();

            if (!$(this).hasClass('delete-friend')) {
                $('li.delete-friend', ctx._baseMenu).hide();
            }
            if (!$(this).hasClass('block-friend')) {
                $('li.block-friend', ctx._baseMenu).hide();
            }
            if (!$(this).hasClass('friend')) {
                $('li.poke', ctx._baseMenu).hide();
            } else {
                $('li.addfriend', ctx._baseMenu).hide();
            }
            
            var author = $.trim($(this).text());

            if (ctx._baseMenu.is(':visible') && author === $('li>span', ctx._baseMenu).html()) return;

            var t = $(e.target);
            var tPos = t.offset();

            var top = tPos.top + t.height();
            var left = tPos.left;

            ctx._baseMenu.css({ top: top + 'px', left: left + 'px' }).slideDown();

            $.each($('a', ctx._baseMenu), function () {
                var me = $(this);
                this.href = me.attr('template').replace(/\[author\]/g, author);
                me.click(function (e) {
                    countdown(0);
                });
            });
            $('li>span', ctx._baseMenu).html(author);

            var timerId = null;

            var countdown = function (timeout) {
                timerId = setTimeout(function () {
                    ctx._baseMenu.unbind('mouseout,mouseover');
                    ctx._baseMenu.slideUp();
                }, timeout);
            };
            countdown(2000);

            ctx._baseMenu.mouseout(function (event) {
                countdown(1000);
            });

            ctx._baseMenu.mouseover(function (e) {
                if (timerId !== null) {
                    clearTimeout(timerId);
                    timerId = null;
                }
            });
        });
    },
    Clear: function () {
        $(this._selector).unbind('mouseover');
        this._baseMenu.unbind('mouseout,mouseover');
        this._baseMenu.slideUp();
    }
}

var ChatService = function(args) {
    this._args = args;
    this._xhr = null;
    this._cTimestamp = '';
    this._mTimestamp = '';
    this._init();
}

ChatService.prototype = {
    _init: function() {
        setInterval(Function.createDelegate(this, this._checkNewMessages), this._args.PingTime * 1000);
    },
    _checkNewMessages: function() {
        if (this._xhr != null && typeof (this._xhr.abort) !== undefined) {
            // request still in progress, kill it
            this._xhr.abort();
        }
        this._xhr = $.ajax({
            type: "POST",
            url: "/services/memberservice.asmx/GetBroadcasts",
            data: "{cTimestamp: '" + this._cTimestamp + "', mTimestamp: '" + this._mTimestamp + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: Function.createDelegate(this,
                function(results) {
                    this._xhr = null;
                    var ctx = this;
                    if (!results || !results.d) return;
                    if (results.d.c) {
                        if (results.d.ct !== '') this._cTimestamp = results.d.ct;
                        $.each(results.d.c, function() {
                            openChatWindow(this.FromUsername, ctx._args.UsernameKey, this.Id);
                        });
                    }
                    if (results.d.m) {
                        if (results.d.mt !== '') this._mTimestamp = results.d.mt;
                        var flashAds = $('#adspot');
                        $.each(results.d.m, function(i) {
                            $.jGrowl(this.Message,
                                { header: LushResource.Message_Growl_Header,
                                    sticky: results.d.m[i].IsSticky,
                                    beforeOpen: function(e, m, o) {
                                        if (flashAds.length > 0) {
                                            flashAds.css('visibility', 'hidden');
                                        }
                                        if (results.d.m[i].Audio !== null) {
                                            soundManager.url = '/js/'; // directory where SM2 .SWFs live
                                            soundManager.debugMode = false;
                                            soundManager.useHighPerformance = false;
                                            soundManager.setVolume('poke', 50);
                                            soundManager.play('poke', '/js/' + results.d.m[i].Audio);
                                        }
                                    },
                                    beforeClose: function(e, m, p) {
                                        if (flashAds.length > 0) {
                                            flashAds.css('visibility', 'visible');
                                        }
                                    }
                                }
                            );
                        });
                    }
                }
            ),
            error: Function.createDelegate(this,
                function(XMLHttpRequest, textStatus, errorThrown) {
                    this._xhr = null;
                }
            )
        });
    }
};

var ChatClient = function(args) {
    this._args = args;
    this._xhr = null;
    this._writingNewMessage = false;
    this._writingTimerId;
    this._lastMessageTimestamp = '';
    this._jqChatMessage;
    this._jqChatWindow;
    this._jqChatStatus;
    this._jqChatLastMessage;
    this._init();
}

ChatClient.prototype = {
    _init: function() {
        this._jqChatMessage = $('#idChatMessage');
        this._jqChatWindow = $('.chat-window');
        this._jqChatStatus = $('.chat-status');
        this._jqChatLastMessage = $('.chat-window .last-message');

        if (this._args.IsOnline === false) {
            this._jqChatStatus.html(this._args.YouMember + ' ' + LushResource.Not_Online);
            $('#idSend').attr('disabled', 'true');
            return;
        }
        if (this._args.AvailableToChat === false) {
            this._jqChatStatus.html(this._args.YouMember + ' ' + LushResource.Not_Available);
            $('#idSend').attr('disabled', 'true');
            return;
        }

        this._jqChatMessage.bind('keydown', this, function(e) {
            if (e.keyCode == 13) {
                if (e.ctrlKey == false) {
                    $('#idSend').click();
                    e.preventDefault();
                    e.stopPropagation();
                } else {
                    e.data._jqChatMessage.val(e.data._jqChatMessage.val() + '\n');
                }
            } else if (e.keyCode >= 32) {
                // only printable characters
                if (e.data._jqChatMessage.val().length > 400) {
                    e.preventDefault();
                    e.stopPropagation();
                    return;
                }
                e.data._sendStartConversation();
            }
        });

        $('.emoticons a').bind('click', this, function(e) {
            var img = $(e.target).parent();
            e.data._jqChatMessage.val(e.data._jqChatMessage.val() + img.attr('title'));

            e.preventDefault();
            e.stopPropagation();
        });

        $('#idSend').bind('click', this, function(e) {
            var ctx = e.data;

            e.preventDefault();
            e.stopPropagation();

            ctx._sendNewMessage(ctx._jqChatMessage.val());
            ctx._jqChatMessage.val('');
            ctx._jqChatMessage.focus();
        });

        $('.chat-options input[type=button]').bind('click', this, function(e) {
            switch (e.target.value) {
                case LushResource.Context_Block_User:
                    if (window.opener && !window.opener.closed) {
                        window.opener.location = '/membership/update-details.aspx?action=block&' + e.data._args.UsernameKey + '=' + e.data._args.YouMember + '#friends';
                    }
                    window.close();
                    break;
                case LushResource.Context_Add_Friend:
                    if (window.opener && !window.opener.closed) {
                        window.opener.location = '/membership/update-details.aspx?action=friend&' + e.data._args.UsernameKey + '=' + e.data._args.YouMember;
                    }
                    break;
                case LushResource.Context_Change_Settings:
                    if (window.opener && !window.opener.closed) {
                        window.opener.location = '/membership/update-details.aspx?s=friends';
                        window.focus();
                    }
                    break;
            }
        });

        if (document.attachEvent) {
            var active;
            document.attachEvent("onactivate", function() {
                active = document.activeElement;
                if (!active) return;
                active.attachEvent("onfocus", function() { window.__isblur = false; });
                active.attachEvent("onblur", function() { window.__isblur = true; });
            });
            document.attachEvent("ondeactivate", function() {
                if (!active) return;
                active.detachEvent("onfocus", function() { window.__isblur = false; });
                active.detachEvent("onblur", function() { window.__isblur = true; });
                active = null;
            });
        } else {
            $(window).bind('focus', this, function(e) {
                window.__isblur = false;
            });
            $(window).bind('blur', this, function(e) {
                window.__isblur = true;
            });
        }

        this._checkNewMessages();

        setInterval(Function.createDelegate(this, this._checkNewMessages), this._args.PingTime * 1000);
    },
    _windowHasFocus: function() {
        return window.__isblur ? false : true;
    },
    _blinkWindow: function() {
        if (this._windowHasFocus()) return;
        if (window._isflashingtitle) return;
        window._isflashingtitle = true;
        var backuptitle = document.title;
        var step = 0
        var ctx = this;
        var msg = LushResource.New_Message_From + " " + this._args.YouMember;
        function flash_title() {
            if (ctx._windowHasFocus()) {
                window._isflashingtitle = false;
                document.title = backuptitle;
                return;
            }
            step = step + 1;
            if (step % 2 == 0)
                document.title = msg;
            else
                document.title = ' ';

            setTimeout(flash_title, 800);
        }
        flash_title();
    },
    _addYourMessageToWindow: function(msg) {
        this._jqChatWindow.append('<div class="says">' + this._args.YouMember + ' ' + LushResource.Says + ':</div><div class="you-talk">' + msg + '</div>');
        this._jqChatWindow.attr({ scrollTop: this._jqChatWindow.attr("scrollHeight") });
        this._blinkWindow();
        var now = new Date();
        var suffix = "AM";
        var hours = now.getHours();
        if (hours > 12) {
            suffix = "PM";
            hours -= 12;
        }
        var niceDate = hours + ":" + (now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes()) + " " + suffix + " " + now.toDateString();
        this._jqChatStatus.html(LushResource.Last_Message + " " + niceDate);
    },
    _addMyMessageToWindow: function(msg) {
        this._jqChatWindow.append('<div class="says">' + this._args.MeMember + ' ' + LushResource.Says + ':</div><div class="me-talk">' + msg + '</div>');
        this._jqChatWindow.attr({ scrollTop: this._jqChatWindow.attr("scrollHeight") });
    },
    _publishError: function(msg) {
        this._jqChatStatus.html('<span class="red">' + msg + '</span>');
    },
    _sendStartConversation: function() {
        if (!this._writingNewMessage) {
            this._writingNewMessage = true;
            $.ajax({
                type: "POST",
                url: "/services/memberservice.asmx/StartNewMessage",
                data: "{chatId: '" + this._args.ChatId + "', memberId: '" + this._args.YouId + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
        }
    },
    _checkNewMessages: function() {
        if (this._xhr != null && typeof (this._xhr.abort) !== undefined) {
            // request still in progress, kill it
            this._xhr.abort();
        }
        this._xhr = $.ajax({
            type: "POST",
            url: "/services/memberservice.asmx/GetNewMessages",
            data: "{chatId: '" + this._args.ChatId + "', checkMemberAlive:true, timestamp: '" + this._lastMessageTimestamp + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: Function.createDelegate(this,
                function(results) {
                    this._xhr = null;
                    var ctx = this;
                    if (results.d) {
                        this._lastMessageTimestamp = results.d.Timestamp;
                        if (results.d.Messages != null && results.d.Messages.length == 1 && results.d.Messages[0] === 'WRITING_MESSAGE') {
                            var msg = this._args.YouMember + ' ' + LushResource.Writing_Message;
                            this._jqChatStatus.html(msg);
                            var ctx = this;
                            setTimeout(function() {
                                if (msg === ctx._jqChatStatus.html()) {
                                    ctx._jqChatStatus.html('');
                                }
                            }, 5000);
                        } else {
                            if (results.d.OtherMemberHasLeft) {
                                ctx._jqChatStatus.html(this._args.YouMember + ' ' + LushResource.Left_Conversation);
                            } else if (results.d.Messages != null && results.d.Messages.length > 0) {
                                if (!this._args.DisableSound) {
                                    soundManager.play('newmessage');
                                }
                                this._jqChatStatus.html('');
                                $.each(results.d.Messages, function() {
                                    ctx._addYourMessageToWindow(this);
                                });
                            }
                        }
                    }
                }
            ),
            error: Function.createDelegate(this,
                function(XMLHttpRequest, textStatus, errorThrown) {
                    this._xhr = null;
                }
            )
        });
    },
    _sendNewMessage: function(msg) {
        this._writingNewMessage = false;
        if ($.trim(msg) === '') return;
        $.ajax({
            type: "POST",
            url: "/services/memberservice.asmx/SendNewMessage",
            data: "{chatId: '" + this._args.ChatId + "', message: '" + msg.replace(/\'/g, "\\\'") + "', memberId: '" + this._args.YouId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: Function.createDelegate(this,
                function(results) {
                    this._addMyMessageToWindow(results.d);
                }
            ),
            error: Function.createDelegate(this,
                function(XMLHttpRequest, textStatus, errorThrown) {
                    this._publishError(LushResource.Error_Sending);
                }
            )
        });
    }
};

// jGrowl.js

(function($){$.jGrowl=function(m,o){if($("#jGrowl").size()==0){$("<div id=\"jGrowl\"></div>").addClass($.jGrowl.defaults.position).appendTo("body");}
$("#jGrowl").jGrowl(m,o);};$.fn.jGrowl=function(m,o){if($.isFunction(this.each)){var _6=arguments;return this.each(function(){var _7=this;if($(this).data("jGrowl.instance")==undefined){$(this).data("jGrowl.instance",new $.fn.jGrowl());$(this).data("jGrowl.instance").startup(this);}
if($.isFunction($(this).data("jGrowl.instance")[m])){$(this).data("jGrowl.instance")[m].apply($(this).data("jGrowl.instance"),$.makeArray(_6).slice(1));}else{$(this).data("jGrowl.instance").notification(m,o);}});}};$.extend($.fn.jGrowl.prototype,{defaults:{header:"",sticky:false,position:"top-right",glue:"after",theme:"default",corners:"10px",check:500,life:3000,speed:"normal",easing:"swing",closer:true,closerTemplate:"<div>[ close all ]</div>",log:function(e,m,o){},beforeOpen:function(e,m,o){},open:function(e,m,o){},beforeClose:function(e,m,o){},close:function(e,m,o){},animateOpen:{opacity:"show"},animateClose:{opacity:"hide"}},element:null,interval:null,notification:function(_17,o){var _19=this;var o=$.extend({},this.defaults,o);o.log.apply(this.element,[this.element,_17,o]);var _1a=$("<div class=\"jGrowl-notification\"><div class=\"close\">&times;</div><div class=\"header\">"+o.header+"</div><div class=\"message\">"+_17+"</div></div>").data("jGrowl",o).addClass(o.theme).children("div.close").bind("click.jGrowl",function(){$(this).unbind("click.jGrowl").parent().trigger("jGrowl.beforeClose").animate(o.animateClose,o.speed,o.easing,function(){$(this).trigger("jGrowl.close").remove();});}).parent();(o.glue=="after")?$("div.jGrowl-notification:last",this.element).after(_1a):$("div.jGrowl-notification:first",this.element).before(_1a);$(_1a).bind("mouseover.jGrowl",function(){$(this).data("jGrowl").pause=true;}).bind("mouseout.jGrowl",function(){$(this).data("jGrowl").pause=false;}).bind("jGrowl.beforeOpen",function(){o.beforeOpen.apply(_19.element,[_19.element,_17,o]);}).bind("jGrowl.open",function(){o.open.apply(_19.element,[_19.element,_17,o]);}).bind("jGrowl.beforeClose",function(){o.beforeClose.apply(_19.element,[_19.element,_17,o]);}).bind("jGrowl.close",function(){o.close.apply(_19.element,[_19.element,_17,o]);}).trigger("jGrowl.beforeOpen").animate(o.animateOpen,o.speed,o.easing,function(){$(this).data("jGrowl").created=new Date();}).trigger("jGrowl.open");if($.fn.corner!=undefined){$(_1a).corner(o.corners);}
if($("div.jGrowl-notification:parent",this.element).size()>1&&$("div.jGrowl-closer",this.element).size()==0&&this.defaults.closer!=false){$(this.defaults.closerTemplate).addClass("jGrowl-closer").addClass(this.defaults.theme).appendTo(this.element).animate(this.defaults.animateOpen,this.defaults.speed,this.defaults.easing).bind("click.jGrowl",function(){$(this).siblings().children("div.close").trigger("click.jGrowl");if($.isFunction(_19.defaults.closer)){_19.defaults.closer.apply($(this).parent()[0],[$(this).parent()[0]]);}});}},update:function(){$(this.element).find("div.jGrowl-notification:parent").each(function(){if($(this).data("jGrowl")!=undefined&&$(this).data("jGrowl").created!=undefined&&($(this).data("jGrowl").created.getTime()+$(this).data("jGrowl").life)<(new Date()).getTime()&&$(this).data("jGrowl").sticky!=true&&($(this).data("jGrowl").pause==undefined||$(this).data("jGrowl").pause!=true)){$(this).children("div.close").trigger("click.jGrowl");}});if($(this.element).find("div.jGrowl-notification:parent").size()<2){$(this.element).find("div.jGrowl-closer").animate(this.defaults.animateClose,this.defaults.speed,this.defaults.easing,function(){$(this).remove();});}},startup:function(e){this.element=$(e).addClass("jGrowl").append("<div class=\"jGrowl-notification\"></div>");this.interval=setInterval(function(){jQuery(e).data("jGrowl.instance").update();},this.defaults.check);if($.browser.msie&&parseInt($.browser.version)<7){$(this.element).addClass("ie6");}},shutdown:function(){$(this.element).removeClass("jGrowl").find("div.jGrowl-notification").remove();clearInterval(this.interval);}});$.jGrowl.defaults=$.fn.jGrowl.prototype.defaults;})(jQuery);

var validateScore = function(membersOnly, postBack, loggedOn, reasonField) {
    var combo = $(this);
    if (!loggedOn && membersOnly) {
        if (window.confirm(LushResource.Logged_In_Vote)) {
            window.location = '/join-now.aspx';
        }
        return;
    }
    if (!loggedOn && (combo.val() === '1' || combo.val() === '2')) {
        combo.val('');
        window.alert(LushResource.Logged_In_Score_One);
        return;
    }
    if (combo.val() === '1' || combo.val() === '2') {
        var ads = $('iframe, object, embed');
        $('#reason-dialog p span:last').hide();
        $('#reason-dialog p span:first').text($('#reason-dialog p span:first').text().replace("{score}", combo.val()));
        var dialog = $('#reason-dialog').modal({
            overlayId: 'dialog-overlay',
            onOpen: function(dialog) {
                dialog.overlay.fadeIn('normal', function() {
                    dialog.container.slideDown('normal', function() {
                        dialog.data.fadeIn('normal');
                    });
                });
            },
            onShow: function() {
                ads.css('visibility', 'hidden');
                $('#reason-dialog input.ok').click(function(e) {
                    var reason = $.trim($('#reason-dialog textarea').val());
                    if (reason !== '') {
                        $('#' + reasonField).val(reason);
                        postBack();
                    }
                    combo.val('');
                    $.modal.close();
                });
                $('#reason-dialog input.cancel').click(function(e) {
                    combo.val('');
                    $.modal.close();
                });
            },
            onClose: function(dialog) {
                dialog.data.fadeOut('normal', function() {
                    dialog.container.slideUp('normal', function() {
                        dialog.overlay.fadeOut('normal', function() {
                            ads.css('visibility', 'visible');
                            $('#reason-dialog input.ok').unbind('click');
                            $('#reason-dialog input.cancel').unbind('click');
                            $.modal.close(); // must call this!
                        });
                    });
                });
            }
        });
    } else {
        postBack();
    }
};

var reportBadStory = function(loggedOn) {
    if (!loggedOn) {
        if (window.confirm(LushResource.Logged_In_Inappropriate)) {
            window.location = '/join-now.aspx';
        }
        return;
    }
    $('#reason-dialog p span:first').hide();
    var ads = $('iframe, object, embed');
    var dialog = $('#reason-dialog').modal({
        overlayId: 'dialog-overlay',
        onOpen: function(dialog) {
            dialog.overlay.fadeIn('normal', function() {
                dialog.container.slideDown('normal', function() {
                    dialog.data.fadeIn('normal');
                });
            });
        },
        onShow: function() {
            ads.css('visibility', 'hidden');
            $('#reason-dialog input.ok').click(function(e) {
                var reason = $.trim($('#reason-dialog textarea').val());
                if (reason !== '') {
                    $.ajax({
                        type: "POST",
                        url: "/services/storyservice.asmx/RecordBadStory",
                        data: "{url: '" + window.location + "', reason: '" + reason.replace(/\'/g, "\\\'") + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: Function.createDelegate(this,
                                function(results) {
                                    $('#idReportBadSuccess').show();
                                    $('#idBadStory').hide();
                                }
                            )
                    });
                }
                $.modal.close();
            });
            $('#reason-dialog input.cancel').click(function(e) {
                $.modal.close();
            });
        },
        onClose: function(dialog) {
            dialog.data.fadeOut('normal', function() {
                dialog.container.slideUp('normal', function() {
                    dialog.overlay.fadeOut('normal', function() {
                        $('#reason-dialog input.ok').unbind('click');
                        $('#reason-dialog input.cancel').unbind('click');
                        $.modal.close(); // must call this!
                    });
                });
            });
        }
    });
};

var sendPoke = function(id, user) {
    $.ajax({
        type: "POST",
        url: "/services/memberservice.asmx/Poke",
        data: "{memberId: " + id + ", username: '"+user +"'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
}

var reportBadProfile = function(loggedOn) {
    if (!loggedOn) {
        if (window.confirm(LushResource.Logged_In_Report_Profile)) {
            window.location = '/join-now.aspx';
        }
        return;
    }
    var dialog = $('#reason-dialog').modal({
        overlayId: 'dialog-overlay',
        onOpen: function(dialog) {
            dialog.overlay.fadeIn('normal', function() {
                dialog.container.slideDown('normal', function() {
                    dialog.data.fadeIn('normal');
                });
            });
        },
        onShow: function() {
            $('#reason-dialog input.ok').click(function(e) {
                var reason = $.trim($('#reason-dialog textarea').val());
                if (reason !== '') {
                    $.ajax({
                        type: "POST",
                        url: "/services/memberservice.asmx/RecordBadProfile",
                        data: "{url: '" + window.location + "', reason: '" + reason.replace(/\'/g, "\\\'") + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json"
                    });
                }
                $.modal.close();
            });
            $('#reason-dialog input.cancel').click(function(e) {
                $.modal.close();
            });
        },
        onClose: function(dialog) {
            dialog.data.fadeOut('normal', function() {
                dialog.container.slideUp('normal', function() {
                    dialog.overlay.fadeOut('normal', function() {
                        $('#reason-dialog input.ok').unbind('click');
                        $('#reason-dialog input.cancel').unbind('click');
                        $.modal.close(); // must call this!
                    });
                });
            });
        }
    });
};

var suspendUser = function(username) {
    var dialog = $('#mod-dialog').modal({
        overlayId: 'dialog-overlay',
        onOpen: function(dialog) {
            dialog.overlay.fadeIn('normal', function() {
                dialog.container.slideDown('normal', function() {
                    $('#mod-dialog h2').html('Suspend User');
                    $('#mod-dialog p:first').html('Why is this user being suspended?');
                    dialog.data.fadeIn('normal');
                });
            });
        },
        onShow: function() {
            $('#mod-dialog input.ok').click(function(e) {
                var reason = $.trim($('#mod-dialog textarea').val());
                if (reason !== '') {
                    $.ajax({
                        type: "POST",
                        url: "/services/memberservice.asmx/SuspendUser",
                        data: "{username: '" + username + "', reason: '" + reason.replace(/\'/g, "\\\'") + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(results) {
                            $.modal.close();
                            window.alert('User has been suspended');
                        }
                    });
                }
            });
            $('#mod-dialog input.cancel').click(function(e) {
                $.modal.close();
            });
        },
        onClose: function(dialog) {
            dialog.data.fadeOut('normal', function() {
                dialog.container.slideUp('normal', function() {
                    dialog.overlay.fadeOut('normal', function() {
                        $('#mod-dialog input.ok').unbind('click');
                        $('#mod-dialog input.cancel').unbind('click');
                        $.modal.close(); // must call this!
                    });
                });
            });
        }
    });
};

var deleteUser = function(username) {
    var dialog = $('#mod-dialog').modal({
        overlayId: 'dialog-overlay',
        onOpen: function(dialog) {
            dialog.overlay.fadeIn('normal', function() {
                dialog.container.slideDown('normal', function() {
                    $('#mod-dialog h2').html('Delete User');
                    $('#mod-dialog p:first').html('Why is this user being deleted?');
                    $('#mod-dialog div').before('<p><input type="checkbox" id="banip" style="top:0;width:auto;margin-right:5px" /><label for="banip">Ban IP address for two weeks?</label></p>');
                    dialog.data.fadeIn('normal');
                });
            });
        },
        onShow: function() {
            $('#mod-dialog input.ok').click(function(e) {
                var reason = $.trim($('#mod-dialog textarea').val());
                $.ajax({
                    type: "POST",
                    url: "/services/memberservice.asmx/DeleteUser",
                    data: "{username: '" + username + "', reason: '" + reason.replace(/\'/g, "\\\'") + "', banip: " + $('#banip').is(':checked') + " }",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(results) {
                        $.modal.close();
                        window.alert('User has been deleted');
                    }
                });
            });
            $('#mod-dialog input.cancel').click(function(e) {
                $.modal.close();
            });
        },
        onClose: function(dialog) {
            dialog.data.fadeOut('normal', function() {
                dialog.container.slideUp('normal', function() {
                    dialog.overlay.fadeOut('normal', function() {
                        $('#mod-dialog input.ok').unbind('click');
                        $('#mod-dialog input.cancel').unbind('click');
                        $.modal.close(); // must call this!
                    });
                });
            });
        }
    });
};

var removePicture = function(username) {
    var dialog = $('#mod-dialog').modal({
        overlayId: 'dialog-overlay',
        onOpen: function(dialog) {
            dialog.overlay.fadeIn('normal', function() {
                dialog.container.slideDown('normal', function() {
                    $('#mod-dialog h2').html('Remove Picture');
                    $('#mod-dialog p:first').html('<input type="radio" name="pictype" value="A" checked="checked" />&nbsp;Avatar<br/><input type="radio" value="P" name="pictype" />&nbsp;Profile Background<br/><input type="radio" name="pictype" value="S" />&nbsp;Forum Signature<br/><br/>Why is this picture being removed?');
                    dialog.data.fadeIn('normal');
                });
            });
        },
        onShow: function() {
            $('#mod-dialog input.ok').click(function(e) {
                var reason = $.trim($('#mod-dialog textarea').val());
                if (reason !== '') {
                    $.ajax({
                        type: "POST",
                        url: "/services/memberservice.asmx/RemovePicture",
                        data: "{username: '" + username + "', reason: '" + reason.replace(/\'/g, "\\\'") + "', type: '" + $('#mod-dialog input:radio:checked').val() + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json"
                    });
                }
                $.modal.close();
                window.location.reload();
            });
            $('#mod-dialog input.cancel').click(function(e) {
                $.modal.close();
            });
        },
        onClose: function(dialog) {
            dialog.data.fadeOut('normal', function() {
                dialog.container.slideUp('normal', function() {
                    dialog.overlay.fadeOut('normal', function() {
                        $('#mod-dialog input.ok').unbind('click');
                        $('#mod-dialog input.cancel').unbind('click');
                        $.modal.close(); // must call this!
                    });
                });
            });
        }
    });
};


var NotepadCapture = function(loggedOn, username) {
    $('#notepad').click(function(e) {
        if (!loggedOn) {
            if (window.confirm(LushResource.Logged_In_Notepad)) {
                window.location = '/join-now.aspx';
            }
            return;
        }
        var box = $('#notepad-box');
        $.ajax({
            type: "POST",
            url: "/services/memberservice.asmx/GetMemberNote",
            data: "{username: '" + username + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(results) {
                $('textarea', box).val(results.d);
                box.slideDown();
            }
        });

        $('div a', box).click(function(e) {
            box.slideUp();
            e.preventDefault();
        });

        $('input[type=button]', box).click(function(e) {
            $.ajax({
                type: "POST",
                url: "/services/memberservice.asmx/SaveMemberNote",
                data: "{username: '" + username + "', note: '" + $('textarea', box).val().replace(/\'/g, "\\\'") + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(results) {
                    box.slideUp();
                }
            });
            e.preventDefault();
        });

        e.preventDefault();
    });
}

jQuery.fn.maxLength = function(max) {
    this.each(function() {
        var type = this.tagName.toLowerCase();
        var inputType = this.type ? this.type.toLowerCase() : null;
        if (type == "input" && inputType == "text" || inputType == "password") {
            this.maxLength = max;
        }
        else if (type == "textarea") {
            this.onkeypress = function(e) {
                var ob = e || event;
                var keyCode = ob.keyCode;
                var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
            };
            this.onkeyup = function() {
                if (this.value.length > max) {
                    this.value = this.value.substring(0, max);
                }
            };
        }
    });
};

function replyOnline(scope, username) {
    $(scope).siblings('textarea')
        .show()
        .focus()
        .bind('keypress', function(e) {
            if (e.keyCode == 13) {
                var me = $(this);
                me.css('opacity',0.5);
                $.ajax({
                    type: "POST",
                    url: "/services/memberservice.asmx/SmsMessage",
                    data: "{username: '" + username + "', note: '" + $(this).val().replace(/\'/g, "\\\'") + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(results) {
                        closeGrowl(scope);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        me.css('opacity', 1);
                    }
                });
                e.preventDefault();
            }
        })
        .maxLength(100);
}

function AuthoriseFriend(scope, username, key) {
    var ctx = $(scope);
    $.ajax({
        type: "POST",
        url: "/services/memberservice.asmx/AuthoriseFriend",
        data: "{username: '" + username + "', key: '" + key + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(results) {
            ctx.text(LushResource.Success).removeClass('fail').addClass('success').css('text-decoration','none');
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            ctx.text(LushResource.Error).removeClass('success').addClass('fail');    
        }
    });
    return false;
}