/**
 * Handles all Gatherings
 */

(function(){
    if(!window.cs) {
        return;
    }
    
    var gathering = window.cs.gathering = {
        // default options/settings
        invitedUserCount: 0,
        invitedUsers: [],
        
        invitedEmailsCount: 0,
        invitedEmails: [],
        
        empty: null
    };
    
    gathering.init = function(gatheringID) {
        // initialize default actions
        $("#shareLink").focus(function(){
            // Select input field contents
            this.select();
        });

        // Hides guests after the first ten
        $('.person-more').hide();

        // Shows extra guests
        $('#seeAllLink').click(function(){$('.person-more').show();});
        /* Commented out just in case Adam changes his mind
        if (!$('#isVisitorLoggedIn').val()) {
            return cs.lightbox.loginRegister();
        }
        */
        
        if ((($('#showInviteLB').val()) && ($('#isVisitorLoggedIn').val()))) {
            return cs.lightbox.inviteGathering(gatheringID);
        }
    };
    
    gathering.initInvite = function() {
        // initialize default actions
        
        // Sets up tabs for all/groups
        $('#crew').tabs({selected:0});        
        
        // Sets up Live Search for All People
        $('#liveSearch-all').focus(function(){
           $(this).removeClass("unselected");
           $(this).val("");     
        }).liveUpdate('#crew-all');
        
        // Sets up Live Search for Groups
        $('#liveSearch-groups').focus(function(){
           $(this).removeClass("unselected");
           $(this).val("");     
        }).liveUpdate('#crew-groups');
        
        // Sets up Email Adder
        $('#inviteGathering_Email').focus(function(){
           $(this).removeClass("unselected");
           $(this).val("");     
        });

        // Prevents Enter from Submitting Form
        $('#inviteGathering_form').submit(function(){return false;});
        $('#inviteGathering_form_submit').click(function(){
            // Show Loading Icon
            // $('.invited_header .loader-light').show();
            return false;
        });                                 
        gathering.invitedUsers.indexOf = function(userID) {
            var index = -1;
            $.each(gathering.invitedUsers, function(i, val) {
                if (val == parseInt(userID)) {
                    index = i;
                }
            });
            return index;
        };
    };
    
    // Adds User To Invited List
    gathering.addUserToInvites = function(gatheringID,userID) {
        $.getJSON('/addUserToGathering.json?gatheringID='+gatheringID+'&userID='+userID,
            function(json){
                if(json.success) {
                    if(gathering.invitedUsers.indexOf(userID) == -1) { // Checks to see if User is already in invitedUsers array               
                        // Removes User Once Added To Invited List
                        $('#member-'+userID).remove();
                        
                        // Adds User To Invited List
                        $('#invitedList').append('<li id="invitedMember-'+userID+'"><a href="#" class="remove" onclick="return cs.gathering.removeUserFromInvites('+gatheringID+','+userID+')"><span class="img_replace">Remove</span></a><span class="name">'+json.Name+'</span><div class="clear"></div></li>');

                        // Adds User To invitedUsers
                        gathering.invitedUsers.push(userID);
                        
                        // Updates Count
                        gathering.invitedUserCount++;                
                        gathering.updateInvitedUserCount();
                    } else {
                        cs.lightbox.message(json.message, 'Add To Gathering Guest List Error');
                    }
                }
            }
        );
        
        return false;
    }
    
    // Adds Group To Invited List
    gathering.addGroupToInvites = function(gatheringID,groupID) {
        $.getJSON('/addGroupToGathering.json?gatheringID='+gatheringID+'&groupID='+groupID,
            function(json){
                if(json.success) {
                    var newUsers = 0;
                    $.each(json.users, function(i,user) {
                        if(gathering.invitedUsers.indexOf(user.UserID) == -1) { // Checks to see if User is already in invitedUsers array                   
                            newUsers = 1;
                            // Removes User Once Added To Invited List
                            $('#member-'+user.UserID).remove();

                            // Adds User(s) To Invited List
                            $('#invitedList').append('<li id="invitedMember-'+user.UserID+'"><a href="#" class="remove" onclick="return cs.gathering.removeUserFromInvites('+gatheringID+','+user.UserID+')"><span class="img_replace">Remove</span></a><span class="name">'+user.Name+'</span><div class="clear"></div></li>');

                            // Adds User To invitedUsers
                            gathering.invitedUsers.push(user.UserID);
                            
                            // Updates Count
                            gathering.invitedUserCount++;
                        }
                    });
                    if (newUsers == 0) {
                        cs.lightbox.message('You have already invited all members of this group', 'Add To Gathering Guest List Error');
                    }
                
                    gathering.updateInvitedUserCount();
                } else {
                    cs.lightbox.message(json.message, 'Add To Gathering Guest List Error');
                }
            }
        );
        
        return false;
    }
    
    // Adds Email To Invited List
    gathering.addEmailToInvites = function(gatheringID) {
        var email = $('#inviteGathering_Email').val();
        
        //Checks for Valid Email Address    
        if($('#inviteGathering_Email').val().match(﻿/^[A-z0-9\._+-]+@[A-z0-9][A-z0-9-]*(\.[A-z0-9_-]+)*\.([A-z]{2,6})$/)) {
            $.getJSON('/addEmailToGathering.json?gatheringID='+gatheringID+'&email='+email,
                function(json){
                    if (json.success) {
                        if(gathering.invitedUsers.indexOf(json.userID) == -1) { // Checks to see if User is already in invitedUsers array    
                            // Adds Email to Invite List
                            $('#invitedList').append("<li id='invitedEmail-"+json.userID+"'>\
                                                          <a href='#' class='remove' onclick='return cs.gathering.removeEmailFromInvites("+gatheringID+","+email+","+json.userID+")'><span class='img_replace'>Remove</span></a><span class='name'>"+email+"</span>\
                                                          <div class='clear'></div>\
                                                      </li>");

                            // Adds Email to invitedEmails Array
                            gathering.invitedEmails.push(email);
                            gathering.invitedUsers.push(json.userID);


                            // Clears Email Upon Adding
                            $('#inviteGathering_Email').val('');

                            // Updates Count
                            gathering.invitedUserCount++;
                            gathering.updateInvitedUserCount();
                        } else {
                            cs.lightbox.message('Already invited the user with email address: ' + email, 'Add To Gathering Guest List Error');
                        }
                    } else {
                        cs.lightbox.message(json.message, 'Add To Gathering Guest List Error');
                    }
                }
            );
        } else {
            cs.lightbox.message('Please enter a valid email address', 'Add To Gathering Guest List Error');
        }
        
        return false;
    }    
    
    // Removes User From Invited List
    gathering.removeUserFromInvites = function(gatheringID,userID) {
        $.getJSON('/removeUserFromGathering.json?gatheringID='+gatheringID+'&userID='+userID,
            function(json){
                if (json.success) { 
                    // Add user to crew list
                    $('#crew-all').append('<li id="member-'+userID+'"><a href="#" class="add" onclick="return cs.gathering.addUserToInvites('+gatheringID+','+userID+')"><span class="img_replace">Add</span></a><span class="name">'+json.Name+'</span><div class="clear"></div></li>');
                    
                    // Removes User From Invite List
                    $('#invitedMember-'+userID).remove();

                    // Removes User From invitedUsers Array
                    gathering.invitedUsers.splice(gathering.invitedUsers.indexOf(userID),1);
                    
                    // Updates Count
                    gathering.invitedUserCount--;                
                    gathering.updateInvitedUserCount();        
                } else {
                    cs.lightbox.message(json.message, 'Add To Gathering Guest List Error');
                }
            }
        );
        
        return false;
    }
    
    // Removes Email From Invited List
    gathering.removeEmailFromInvites = function(gatheringID,emailID,userID) {
        
        // Removes Email From invitedEmails Array
        gathering.invitedEmails.splice(gathering.invitedEmails.indexOf($('#invitedEmail-'+emailID+' .name').html()),1);        
        gathering.invitedUsers.splice(gathering.invitedUsers.indexOf(userID),1);
        
        // Removes Email From Invite List
        $('#invitedEmail-'+emailID).remove();
        
        // Updates Count
        gathering.invitedUserCount--;                
        gathering.updateInvitedUserCount();        
        
        return false;
    }
    
    // Updates Invited User Count
    gathering.updateInvitedUserCount = function() {
        if (gathering.invitedUserCount < 0) {
            gathering.invitedUserCount = 0;
        }
        $('#invitedUserCount').html(gathering.invitedUserCount);
    }                                                           

    // Finalize the invites
    gathering.updateInvitesLock = false;
    gathering.updateInvites = function(gatheringID, obj) {
        
        if (gathering.updateInvitesLock == false) {
            gathering.updateInvitesLock = true;
            $('#inviteGathering_form_submit').hide().addClass('wait').show();
            $('#invited-loader-light').show();
            $(obj).removeAttr('onclick');
            var myData = new Object();
            myData.gatheringID = gatheringID;
            myData.userIDs = gathering.invitedUsers;
            if (gathering.invitedUsers.length > 0) {
                myData = $.toJSON(myData);
                var response = $.ajax({
                    type: "POST",
                    url: "/updateInvites.json",
                    data: myData,
                    async: false,
                    success: function(data, textStatus) {
                        $('#invited-loader-light').hide();
                        var data = $.parseJSON(data);
                        if (data.success == true) {
                            gathering.updateInvitesLock = false;
                            window.location = "/gathering?gatheringID="+gatheringID;
                        } else {
                            $(obj).click(function() {return cs.gathering.updateInvites(gatheringID, obj);});
                            cs.lightbox.message(data.message, 'Add To Gathering Guest List Error', function(hash){
                                hash.w.hide();
                                hash.o.remove();
                                $('#inviteGathering_form_submit').removeClass('wait');
                                window.cs.gathering.updateInvitesLock = false;
                            });
                        }
                    }
                });

            } else {
                $(obj).click(function() {return cs.gathering.updateInvites(gatheringID, obj);});
                cs.lightbox.message("You haven't selected any guests to invite. Please select a guest or close the lightbox.", 'Add To Gathering Guest List Error', function(hash){
                    hash.w.hide();
                    hash.o.remove();
                    $('#inviteGathering_form_submit').removeClass('wait');
                    window.cs.gathering.updateInvitesLock = false;
                });
                $('#invited-loader-light').hide();
            }
        }
    }

})();
