Sharebox = new NSObject();
Sharebox.namespace(['shouts','email','blog']);

Object.extend(Sharebox, {
    tab:function(option) {
        $('lightbox-blog-it-tab').removeClassName('active');
        $('lightbox-email-it-tab').removeClassName('active');
        $('lightbox-shout-it-tab').removeClassName('active');

        $('lightbox-' + option  + '-tab').addClassName('active');

        $('lightbox-blog-it').hide();
        $('lightbox-email-it').hide();
        $('lightbox-shout-it').hide();

        $('lightbox-' + option).show();
    }
});

/*
* functions for lightbox shout tab
*/
Object.extend(Sharebox.shouts, {
    select:function(id) {
        if ($('friend' + id ).hasClassName('selected'))
            $('friend' + id ).removeClassName('selected');
        else
            $('friend' + id ).addClassName('selected');
    },
    
    toggleAll:function() {
        var method = 'addClassName', as = $$('#lightbox-shout-friends a');
        
        //note: we're not just using toggleClassName because some elements may be selected already
        
        if(as.all(function(a) {
            if(a.hasClassName('selected')) return true;
            return false;
        })) { method = 'removeClassName'; }
        
        as.each(function(el) {
            el[method].apply(el, ['selected']);
        });
        
        $('lightbox-shout-filter').focus(); //give filter keyboard focus
    },
    
    send:function(itemId) {
        var to = [], selected = $j('#lightbox-shout-friends a.selected');
        
        if(selected.size() < 1) {
            alert('Please select one or more friends to send this shout to');
            return false;
        }
        
        var captcha = '', md5 = '';
        if($('lightbox-shout-captcha-text')) {
            captcha = $j('#lightbox-shout-captcha-text').val();
            md5 = $j('#md5').val();
        }
        
        selected.each(function(){
            to.push($j(this).text() != '' ? $j(this).text() : '' + ',');
        });
        
        sendShout({
            'token' : tokens.shouts.post,
            'to' : to.join(','),
            'shout' : $j('#lightbox-shout-text').val(),
            'activity' : 9,
            'activityid' : itemId,
            'captcha' : captcha,
            'md5' : md5
        }, function(json) {
                $j('#lightbox-share-notice').html('<div class="confirm"><div><h3>Success!</h3>Your shout was successfully sent</div></div>');
                $j('#lightbox-share-notice').show();
                $j('#lightbox-share-notice').fadeTo(3000,1,function(){$j('#lightbox-share-notice').fadeOut(3000);});
                $j('#lightbox-shout-filter').val('');
                $j('#lightbox-shout-text').val('');

                //fill box with blank entry
                if(ups) {
                    ups.prefix='';
                    ups.search();
                }
                
                //unselect all friends
                var as = $$('#lightbox-shout-friends a');
                as.each(function(el) {
                    el['removeClassName'].apply(el, ['selected']);
                });

                $('lightbox-shout-filter').focus(); //give filter keyboard focus
                
        }, function(json) {
            $j('#lightbox-share-notice').html('<div class="warning"><div><h3>ERROR!</h3>' + json.error + '</div></div>');
            $j('#lightbox-share-notice').show();
            $j('#lightbox-share-notice').fadeTo(3000,1,function(){$j('#lightbox-share-notice').fadeOut(3000);});
        });
    }
});

/*
* UserPrefixSearch requires tokens for /ajax/usersearch/mutual and /ajax/usersearch/mutualCount to be present
*/
UserPrefixSearch = Class.create();
UserPrefixSearch.prototype = {
    initialize:function(field, url, callbacks) {
        this.jfield = $j('#'+field);
        this.field = $(field);
        this.url = url;
        this.limit = 500;
        this.callback = callbacks.success || function(){};
        this.errorFunc = callbacks.error || function(){};
        this.change = false;
        this.updater = false;
        this.prefix = '';
        this.oldValue = false;
        
        //safari 2 has a potential infinite loop issue. let's take it easy on the poor thing.
        if($j.browser.safari && Number($j.browser.version) < 500) {
            this.limit = 30;
        }
        
        this.getMutualFriendCount(function(count) {
            Event.observe(this.field, 'keyup', function(e) {
                clearTimeout(this.change);
                
                this.prefix = this.field.value;
                
                if(count < this.limit || this.prefix.length > 0) {
                    //an empty search string takes longer, since it can be empty in between filters
                    //i.e. k -> backspace -> f would result in 3 searches, where only 2 were intended
                    var delay = this.prefix.length > 0 ? 500 : 1000;
                    
                    //we can wrongly hit the last else below if this if block is combined with the one above
                    if(this.prefix != this.oldValue) this.change = setTimeout(this.search.bind(this), delay);
                } else if(count > this.limit && this.prefix.length == 0) {
                    this.errorFunc.apply(this, [{'title': 'Crikey!', 'message': 'You have lots of friends! Type below to filter them down a bit.'}]);
                } else {
                    this.errorFunc.apply(this, [{'message': 'We didn\'t really like your input. Please try again.'}]);
                }
                
                this.oldValue = this.prefix;
            }.bind(this));
            
            (count < this.limit) ? this.search() : this.errorFunc.apply(this, [{'title': 'Crikey!', 'message': 'You have lots of friends! Type below to filter them down a bit.'}]); //run once on startup
        });
    },
    
    search:function() {
        $j.ajax({
            'url': '/ajax/usersearch/mutual.html',
            'type': 'POST',
            'data': {
                'prefix': this.prefix,
                'token': tokens.usersearch.mutual
            },
            'success': function(html) {
                html.length > 0 ? this.callback.apply(this, [html]) : this.errorFunc.apply(this, [{'title': 'Darn!', 'message': 'Your filter had no results. Try being less specific.'}]);
            }.bind(this),
            'error': function(xml) {
                this.errorFunc.apply(this, [{
                    'title': 'Whoops!',
                    'message': 'We couldn\'t fetch your friends. Please reopen this window.'
                }]);
            }.bind(this)
        });
    },
    
    getMutualFriendCount:function(callback) {
        callback = callback || false;
        $j.ajax({
            'url': '/ajax/usersearch/mutualCount',
            'type': 'POST',
            'dataType' : 'json',
            'data': {
                'token': tokens.usersearch.mutualCount
            },
            'success': function(json) {
                return callback ? callback.apply(this, [json.mutualFriendCount]) : json.mutualFriendCount;
            }.bind(this),
            'error': function(xml) {
                //if we fail to get this count, the user is going to have to reload the lightbox
                this.errorFunc.apply(this, [{
                    'message': 'A pretty bad error occurred. Please reload and try again.'
                }]);
            }.bind(this)
        });
    }
}

/*
* functions for lightbox email tab
*/
Object.extend(Sharebox.email, {
    add:function() {
        var emails = $j('.lightbox-email-wrapper');
        var count = emails.length + 1;
        var last = $j('.lightbox-email-wrapper:last');
        
        if(count < 7) {
            last.after('<div class="lightbox-email-wrapper" style="margin-right: 200px; clear: left;"><input style="width: 200px; margin-bottom: 3px;" class="lightbox-email" type="text" name="email'+count+'" id="email'+count+'" value="" /></div>');
        }
        
        if(count == 6) $j('.lightbox-add').hide();
    },
    
    viewMessage:function() {
        $('lightbox-message-text-toggle').hide();
        $('lightbox-message-text').show();
    },
    
    updateAppLink:function() {
        var addresses = '';
        $$('.lightbox-email').each(function(item) {
            addresses += item.value != '' ? item.value + ',' : '';
        });
        addresses = addresses.replace(/,$/,'');
        
        var el = $('lightbox-email-app');
        el.href = el.href.replace(/mailto:[^\?]*\?/,'mailto:' + addresses + '?');
    }
});

