SR.Toolbar = {};

// SR Toolbar Dropdown Menu
SR.Toolbar.Menu = {
    settings: {},
    init: function() {
        var self = this;
        $('.srToolbarDropdown').children('a.dropdownToggle').bind('click', function(event) {
            self.toggle($(this));
            return false;
        });
    },
    toggle: function(toggle) {
        var self = this;
        var dropdown = $('.srToolbarDropdown');
        if (dropdown.hasClass('expanded')) {
            dropdown.removeClass('expanded');
            $(document).unbind('click');
        } else {
            dropdown.addClass('expanded');
            $(document).bind('click', function(event) {
                if (event.target !== dropdown) { self.toggle(); }
            });
        }
    }
};

// SR Toolbar Notifications
SR.Toolbar.Notify = {
    settings: {},
    init: function(options) {
        var self = this;
        
        this.site_id = options.site_id;
        this.username = options.username;
        
        var notifyContent = new Array(
            '<div class="left"><p>If you would like to recieve email notifications when this webpage changes, enter your email in the address below.<br/><br/>',
            '<input type="text" name="notifyMeEmail" class="dialogTextInput short" id="notifyMeEmail" value="Enter your email address here..." /></p></div>',
            '<div class="right"><p>Sign up for a free account to follow updates to this website in real-time!</p><br/>',
            '<p><a href="/register/" class="btn target"><span><span>Sign up for Free!</span></span></a></div>',
            '<div class="clearfix"></div>'
        );
        
        // Create payload for Dialog
        var notifyPayload = {
            title: 'Subscribe to Updates',
            content: notifyContent.join(''),
            onLoad: function() {
                $('#srDialog #notifyMeEmail').each(function(index) {
                    var orig = $(this).val();
                    $(this).focus(function() {
                        if ($(this).val() == orig) {
                            $(this).val('');
                        }
                    }).blur(function() {
                        if ($(this).val() === '' || null) {
                            $(this).val(orig);
                        }
                    }).keydown(function(event) {
                        if (event.keyCode == 13) { self.subscribe_nonmember(); }
                    });
                });
            },
            buttons: [
                { 
                    label: 'Subscribe to Updates', type: 'target',
                    callback: function() { self.subscribe_nonmember(); }
                },
                {
                    label: 'Cancel', type: 'grey',
                    callback: function() { 
                        SR.Dialog.destroy();
                        $('#notifyMeButton').parent().removeClass('adding');
                        $('#notifyMeButton').children('span').text('Notify Me When Page is Updated');
                    }
                }
            ]
        };
        
        // Select Group
        var selectGroupContent = new Array('<p>Select which group to subscribe to below:</p><ul>');
        
        for (group in SR.GLOBAL.groups) {
            selectGroupContent.push('<li class="groupSelect"><a id="group-'+group+'" href="#'+group+'">'+SR.GLOBAL.groups[group]+'</a></li>');
        }
        
        selectGroupContent.push('<li class="groupSelect"><a id="group-ghost" class="ghost" href="#">I\'m not sure which group to join.</a></li>');
        
        selectGroupContent.push('</ul>');
        
        var selectGroupPayload = {
            title: 'Join A Group',
            content: selectGroupContent.join(''),
            onLoad: function() {
                $('#srDialog li.groupSelect a').bind('click', function(event) {
                    if ($(this).hasClass('ghost')) {
                        self.subscribe_user_to_group();
                    } else {
                        var group_id = $(this).getID();
                        self.subscribe_user_to_group(group_id);
                    }
                    return false;
                });
            }
        };
        
        $('a.notifyMe.unauthenticated').bind('click', function(event) {
            if (!$(this).hasClass('subscribed')) {
                SR.Dialog.createWithPayload(notifyPayload);
            }
            return false;
        });
        
        $('a.notifyMe.authenticated').bind('click', function(event) {
            if (!$(this).hasClass('subscribed')) {
                // If the teacher has groups, show a widget and subscribe_user_to_group(), else do subscribe_user();
                if (SR.GLOBAL.groups) {
                    SR.Dialog.createWithPayload(selectGroupPayload);
                } else {
                    self.subscribe_user_to_group();
                }
            }
            return false;
        });
        
    },
    
    subscribe_nonmember: function() {
        var self = this;
        var email = $('#srDialog #notifyMeEmail').val();
        var site_id = this.site_id;
        var username = this.username;
        if (SR.Util.validEmail(email)) {
            $.ajax({
                url: '/'+username+'/rpc/notify/add-nonmember/'+self.site_id+'/',
                type: 'GET',
                data: { 'email': email },
                dataType: 'json',
                success: function(json) {
                    if (json.response == 'success') {
                        SR.Dialog.reloadWithPayload({
                            title: 'You\'ve Been subscribed!',
                            content: '<p>You\'ve been subscribed! Notifications will be sent to <strong>'+email+'</strong>.</p>',
                            buttons: [{
                                label: 'Close', type: 'target',
                                callback: function() { 
                                    SR.Dialog.destroy();
                                    $('#notifyMeButton').parent().removeClass('adding');
                                    $('#notifyMeButton').children('span').text('Subscribed');
                                    $('a.notifyMe.unauthenticated').unbind().bind('click', function() {
                                        return false;
                                    });
                                }
                            }]
                        });
                    } else {
                        alert('An error occured while trying to subscribe you.\nPlease try again momentarily.\nResponse:'+json.reason);
                    }
                },

                error: function(json) {
                    alert('An error occured while trying to subscribe you.\nPlease try again momentarily.');
                }
            });
        } else {
            alert('Please enter a valid email address!');
            $('#srDialog #notifyMeEmail').select();
        }
    },
    
    subscribe_user_to_group: function(group_id) {
        var self = this;
        
        var data = (group_id) ? { group_id: group_id } : {};
        
        $.ajax({
            url: '/'+self.username+'/rpc/notify/add-user/'+self.site_id+'/',
            type: 'GET',
            data: data,
            dataType: 'json',
            success: function(json) {
                if (json.response == 'success') {
                    var reloadContent = (group_id) ? '<p>You are now a member of the '+SR.GLOBAL.groups[group_id]+' group.</p>' : '<p>You\'ve been subscribed successfully to the default group!</p>';
                    SR.Dialog.reloadWithPayload({
                        title: 'Subscribed',
                        content: reloadContent,
                        buttons: [{
                            label: 'Close', type: 'target',
                            callback: function() { 
                                SR.Dialog.destroy();
                            }
                        }]
                    });
                    
                    $('#notifyMeButton').children('span').text('Subscribed');
                    $('a.notifyMe').unbind().bind('click', function() { return false; });
                } else {
                    SR.Dialog.reloadWithError('An error occured while trying to subscribe you. Please try again momentarily.');
                }
            },
        
            error: function(json) {
                SR.Dialog.reloadWithError('An error occured while trying to subscribe you. Please try again momentarily.');
            }
        });
        
    }
};

SR.Toolbar.Protect = {
    init: function() {
        $('label input').each(function(index) {
            var speed = 100;
            
            $(this).focus(function() {
                $(this).siblings('span.label').fadeOut(speed);
            }).blur(function() {
                if (!$(this).val()) { $(this).siblings('span.label').fadeIn(speed); }
            });
            
            var input = $(this);
                        
            if ($(this).val()) { $(this).siblings('span.label').fadeOut(speed); }
            
            $(this).siblings('span.label').bind('click', function(event) {
                input.focus();
            });
            
        });
    },
    
    locked: function() {
        $('a#siteLocked').bind('click', function(event) {
            SR.Dialog.createWithPayload({
                title: 'Locked Website',
                content: '<p>You are seeing the small padlock icon in the lower right corner of this website because you are viewing a protected teacher website.</p>',
                buttons: [ 
                    { label: 'Close', type: 'target', callback: function() { SR.Dialog.destroy(); }}
                ]
            });
            return false;
        });
    }
}