var lightboxPostActions = 
{
    // these are used within #addMoreRecipients.onclick
    recipientContainerCounter : 2,
    maxRecipientsCount :  10,
    
    areRegistered : false,
    
    registerBehaviours : function ()
    {
        if (! self.LightboxBase ) { return; }

        if (lightboxPostActions.areRegistered) {
            Behaviour.apply($('lightbox'));
            return;
        }
        
        var loginRuleset = 
        {
            '.login-btn' : function(button)
            {
                button.onclick = function() {
                    var fx = LightboxBase.insertWithParameters.bind(LightboxBase);
                    fx($('loginFormForm').action, $('loginFormForm').serialize(true));
                    return false;
                 };
            }
        };
        
        var shareWithColleaguesRuleset = 
        {
            '#commentsTextarea' : function(textarea) {
                if (textarea.value == ' ') {
                    textarea.value = '';
                }
            },
            '.recipient': function (checkbox) {
                checkbox.onclick = function() {
                    var messages = $('messagesContainerColleagues');
                    if (checkbox.checked && messages.visible()) {
                        messages.hide();
                    }
                }  
            },
            '.share-with-colleagues-btn' : function(button)
            {
                button.onclick = function() {
                    var colleaguesSelected = $('shareWithColleaguesContainer').select('.recipient');
                    // console.log(colleaguesSelected);
                    var associatesSelected = $('shareWithAssociatesContainer').select('.recipient');
                    // console.log(associatesSelected);
                    
                    var formHash = $H($('shareWithColleaguesForm').serialize(true));
                    var formHashKeys = formHash.keys();
                    
                    // Filter the recipients to send to accordingly.
                    var selectedRecipients = [];
                    colleaguesSelected.concat(associatesSelected).each(
                        function(recipient) {
                            var recipientId = recipient.value.strip();
                            if (! recipientId) { return; }
                            if (recipient.checked) {
                                selectedRecipients[recipientId] = recipientId;
                                return;
                            }
                            // Unset from the serialized form's hash any recipients not selected.
                            var regex = new RegExp('.+' + recipientId + '.+');
                            formHashKeys.grep(regex).each(function(key){formHash.unset(key);});
                        }
                    );
                    
                    if (! selectedRecipients.size()) {
                        var messages = $('messagesContainerColleagues');
                        messages.update('<strong>Error:</strong> You must select colleagues or associates you want to share with.');
                        messages.show();
                        return;
                    }
                    
                    var postBody = formHash.toObject();
                    // console.log(postBody);
                    var fx = LightboxBase.insertWithParameters.bind(LightboxBase);
                    fx($('shareWithColleaguesForm').action, postBody);
                    return false;
                 };
            },
            '#checkUncheckAllColleagues' : function(link)
            {
                link.onclick = function() {
                    if (self.Utils) {
                        Utils.setAllCheckBoxes('shareWithColleaguesForm', 'users[]', 'checkUncheckAllColleagues');
                    }
                    return false;
                };
            },
            
            '#btnAddAssociate' : function(button)
            {
                button.onclick = function() {
                    obj = {
                        'associateName' : $('associateName').value,
                        'associateEmail' : $('associateEmail').value
                    };
                    
                    request = new Ajax.Request('/data/associates/add' , {
                    
                        method: 'post',
                        parameters: obj,
                        evalJSON: true,
                        
                        onSuccess: function(transport) {
                            if (transport.responseJSON) {
                                obj = transport.responseJSON;
                                
                                var messages = $('messagesContainerAssociates');
                                messages.hide();
                        
                                switch (obj.status) {
                                    case 'success':
                                        //alert('Associate saved correctly.');
                                        var noAssociatesMessageContainer = $('noAssociatesMessageContainer');
                                        if (noAssociatesMessageContainer) {
                                            noAssociatesMessageContainer.hide();
                                        }
                                        
                                        var div = new Element('div', {'class': 'user'});
                                        var inputHiddenEmail = new Element('input', {type: 'hidden', name: 'associates['+obj.associateId+'][email]', value: obj.associateEmail});
                                        var inputHiddenName = new Element('input', {type: 'hidden', name: 'associates['+obj.associateId+'][full-name]', value: obj.associateName});
                                        var checkboxId = 'associate_' + obj.associateId;
                                        var checkboxName = 'associates[' + obj.associateId + '][selected]';
                                        var inputCheckbox = new Element('input', {'id' : checkboxId, 'class': 'recipient associate', type : 'checkbox', name : checkboxName, value : obj.associateId, checked : 'checked'});
                                        var label = new Element('label', {'for' : checkboxId}).update(obj.associateName);
                                        
                                        Element.insert($('shareWithAssociatesContainer'), div);
                                        Element.insert(div, inputHiddenEmail);
                                        Element.insert(div, inputHiddenName);
                                        Element.insert(div, inputCheckbox);
                                        Element.insert(div, label);
                                        
                                        $('associateName').value = '';
                                        $('associateEmail').value = '';
                                        $('submitContainer').show();
                                        break;
                                    
                                    case 'failure':
                                        messages.update('<strong>Error:</strong> an error occurred. Please try again later.');
                                        messages.show();
                                        break;
                                        
                                    case 'notAuthorised':
                                        messages.update('<strong>Error:</strong> You must be logged in in order to use this functionality.')
                                        messages.show();
                                        break;
                                        
                                    case 'missingData':
                                        messages.update('<strong>Error:</strong> You need to enter both name and email.');
                                        messages.show();
                                        break;
                                        
                                    case 'invalidEmail':
                                        messages.update('<strong>Error:</strong> the email address you entered is not valid.');
                                        messages.show();
                                        break;
                                        
                                    case 'duplicateName':
                                        messages.update('<strong>Error:</strong> The associate you entered already exists.');
                                        messages.show();
                                        break;
                                        
                                    default:
                                        break;
                                }
                            }
                        },
                        onFailure: function(transport) {
                        }
                    });
                };
            }
        };
        
        var shareWithAnyoneRuleset = 
        {
            '#forwardStoryComments' : function(textarea) {
                if (textarea.value == ' ') {
                    textarea.value = '';
                }
            },
            '.share-with-anyone-btn' : function(button)
            {
                button.onclick = function() {
                    var fx = LightboxBase.insertWithParameters.bind(LightboxBase);
                    fx($('shareWithAnyoneForm').action, $('shareWithAnyoneForm').serialize(true));
                    return false;
                 };
            },
            '#addMoreRecipients' : function(linkAddMoreRecipients) 
            {
                linkAddMoreRecipients.onclick = function() {
                    
                    var containerId = 'recipient' + lightboxPostActions.recipientContainerCounter + 'Container';
                    var el = $(containerId);
                    if (el) { el.show(); }
                    if (lightboxPostActions.recipientContainerCounter++ == lightboxPostActions.maxRecipientsCount) { $('addMoreRecipients').hide(); }

                    return false;
                };
            }
        };
        
        var tagThisArticleRuleset = 
        {
            '#tagArticleComment' : function(textarea) {
                if (textarea.value == ' ') {
                    textarea.value = '';
                }
            },
            '#setTagButton' : function(button)
            {
                button.onclick = function() {
                    var fx = LightboxBase.insertWithParameters.bind(LightboxBase);
                    fx('/mini/tag/set/', $('tagThisArticleForm').serialize(true));
                    return false;
                }
            },
            
            '#updateTagButton' : function(button)
            {
                button.onclick = function() {
                    var fx = LightboxBase.insertWithParameters.bind(LightboxBase);
                    fx('/mini/tag/set/', $('tagThisArticleForm').serialize(true));
                    return false;
                }
            },
            
            '#removeTagButton' : function(button)
            {
                button.onclick = function() {
                    var fx = LightboxBase.insertWithParameters.bind(LightboxBase);
                    fx('/mini/tag/unset/', $('tagThisArticleForm').serialize(true));
                    return false;
                }
            }
        };
        
        var suggestACompanyRuleset =
        {
            '#suggestACompanyButton' : function(button) {
                button.onclick = function() {
                    var fx = LightboxBase.insertWithParameters.bind(LightboxBase);
                    fx($('suggestACompanyForm').action, $('suggestACompanyForm').serialize(true));
                    return false;
                }
            }
        }
        
        Behaviour.register(loginRuleset);
        // Behaviour.register(shareWithColleaguesRuleset);
        // Behaviour.register(shareWithAnyoneRuleset);
        Behaviour.register(tagThisArticleRuleset);
        Behaviour.register(suggestACompanyRuleset);
        
        lightboxPostActions.areRegistered = true;
        
        Behaviour.apply($('lightbox'));
    }
}

