/*
    Title:  Twitter Repair and Protect JavaScript
*/

var repair = {
    current_word:       false,
    active_class:       'active',
    drop_down_class:    'dropdown',
    error_class:        'error',
    savebox_class:      'savebox',
    
    init: function() {
        this.addEvents();
        
        // Close any open drop-downs
        //$(document).bind('click', repair.closeDropdown);
    },
    
    // AJAX call for alternative words
    fetchWords: function(word) {
    
    },
    
    // Add edit events
    addEvents : function() {
        // What elements to add the click event to
        target = '.tweet STRONG';
        
        // Search the DOM and add the events
        jQuery.each($(target), function() {
          $(this).bind('click', repair.dropdown);
        });
        
        
        // Add edit events
        jQuery.each($('.edit'), function() {
            $(this).bind('click', repair.editText);
        });
        
        // Add save events
        jQuery.each($('.save'), function() {
            $(this).bind('click', repair.saveTweet);
        });
    },
    
    // Present user with drop-down list of options
    dropdown: function() {
        // Setup some variables 
        var word = $(this).text();
        var url = 'thesaurus.php?word=';
        
        // If clicked on the same word
        if ($(this).hasClass(repair.active_class)) {
            repair.closeDropdown();
            // finish and return
            return;
        }
        
        // Close any exiting word drop-downs
        repair.closeDropdown();
        
        // Set new current word
        repair.current_word = this;
        
        // Build Drop-down HTML
        var html = $('<div class="' + repair.drop_down_class + '"></div>');
        html.css('top', $(this).height());
        
        // Fetch words
        jQuery.getJSON(url + word, function(data) {
            
            // Check if there was an error
            if (data.error != undefined) {
                html.append('<p>No alternative words found</p>');
            } else {
            
                // Loop through each result
                jQuery.each(data, function() {
                    
                    // Loop again
                    jQuery.each(this, function() {
                        var noun_html = $('<div><ul></ul></div>');
                        
                        // Loop through each word
                        jQuery.each(this, function() {
                            // Build alt word HTML
                            var alt_word = $('<li>' + this + '</li>\n');
                            // Add an event handler
                            alt_word.bind('click', repair.swapWord);
                            noun_html.append(alt_word);
     
                        });
                        
                        // now add them to the drop-down HTML
                        html.append(noun_html);
                    });
              
                    
                });
            
            }

        });
        
        // Add the drop-down HTML to the DOM
        $(this).append(html);
        
        // Set current word to active
        $(this).addClass(repair.active_class);
    },
    
    // Replace the selected word with the alternative
    swapWord : function() {
        $(repair.current_word).text($(this).text());
        return;
    },
    
    closeDropdown : function() {
        if($('.' + repair.active_class).length <= 0) {
            return false;
        }
        $('.' + repair.active_class).find('.'+ repair.drop_down_class).remove();
        $('.' + repair.active_class).removeClass(repair.active_class);
        return;
    },
    
    editText: function() {
        var overlimit_class = 'overlimit';
        
        var tweet = $(this).parents('.tweet');
        var tweet_text = tweet.find('.tweet_text');
        var wrapper = $('<div class="textarea"></div>');
        
        var textbox = $('<textarea>' + $.trim(tweet_text.text()) +'</textarea>');
        
        
        var char_count = $('<div class="char_count">' + $.trim(tweet_text.text()).length + '</div>)');
        
       
        
        
        textbox.bind('keydown', function(e) {
            $(char_count).text( $(textbox).val().length );
            if($(textbox).val().length > 140) {
                $(char_count).addClass(overlimit_class);
            } else {
                $(char_count).removeClass(overlimit_class);
            }
        });

        
        tweet_text.hide();
        
        wrapper.append(textbox);
        wrapper.append(char_count);
        tweet.prepend(wrapper);
        
        // Change button text
        $(this).text('Finish edit');
        // Remove the original event
        $(this).unbind('click', repair.editText);
        // Add new event
        $(this).bind('click', repair.saveEdit);
        
        // Hide save tweet button
        var save_button = tweet.find('.save');
        save_button.hide();
        
    },
    
    saveEdit: function() {
        // Grab the needed DOM elements
        var tweet = $(this).parents('.tweet');
        var tweet_text = tweet.find('.tweet_text');
        var edit_text = tweet.find('textarea');
        
        
        // Check if the text is over the 140 character limit
        if (edit_text.val().length > 140) {
            // Add an error message
            repair.addError('Tweet is over 140 characters. Please shorten it.', tweet);
            // end here
            return;
        } else {
            repair.removeError(tweet);
        }
        
        
        // The tweet is the right length, lets update the tweet text and remove
        // the textarea
        tweet_text.text(edit_text.val());
        tweet_text.show();
        edit_text.parent().remove();
        
        // Replace button text and event handle
        $(this).text('Edit tweet');
        $(this).unbind('click', repair.saveEdit);
        $(this).bind('click', repair.editText);
        
        // Show save tweet button
        var save_button = tweet.find('.save');
        save_button.show();
    },
    
    // Add Tweet error message box
    addError: function(msg, elm) {
        // Check if there is an error massage already open
        if ($(elm).find('.'+repair.error_class).length > 0) {
            // Update the existing error box with the new message
            $(elm).find('.'+repair.error_class).text(msg);
            return true;
        }
        
        // Create the HTML
        var errorbox = $('<div></div>');
        errorbox.addClass(repair.error_class);
        
        // add the error message to the HTML
        errorbox.text(msg);
        
        // Hide the message from view so we can slide animate it opening
        errorbox.hide();
        
        // Prepend the HTML to the DOM
        $(elm).prepend(errorbox);
        
        // Animate the error box opening
        errorbox.slideDown();
    },
    
    // Remove Tweet error message box
    removeError: function(elm) {
        // Check for the existence of the error box
        if ($(elm).find('.'+repair.error_class).length > 0) {
            // Once the error box is found, remove it
            var errorbox = $(elm).find('.'+repair.error_class);
            errorbox.slideUp('normal', function() {
                $(this).remove();   
            });
            return true;
        }
    },
    
    // Show Tweet save dialogue box
    saveTweet: function() {
        // Collect DOM elements
        var tweet = $(this).parents('.tweet');
        var tweet_text = tweet.find('.tweet_text');
        tweet.find('.edit').hide();
        $(this).hide();
        
        
        // Create save box HTML
        var savebox = $('<div><p><input type="checkbox" selected="" /> Delete original tweet. <a href="#">Re-tweet the edited tweet</a></p></div>');
        savebox.addClass(repair.savebox_class);
        
        // Create confirm button
        
        // Create Cancel button
        var cancel = $('<div class="cancel button">Cancel</div>');
        // Add Event
        cancel.bind('click', repair.cancelSave);
        // Add it to the DOM
        $(this).after(cancel);
        
        
        // Add POST event handler to the re-tweet link
        savebox.find('a').bind('click', function(e) {
            // Prevent following the anchor link
            e.preventDefault();
            
            // POST data object
            data = {};
            // Get the tweet data
            var tweet = $(this).parents('.tweet');
            var tweet_text = tweet.find('.tweet_text');
            
            
            // check if delete option is checked
            if ($(this).siblings('input').attr('checked')) {
                data.delete_id = tweet.attr('id');
            }
            
            // Add tweet text to data object
            data.text = tweet_text.text().trim();
            
            // Send the data via POST
            $.post("send.php", data,
                function(data){
                    if (data == '200') {
                        alert('Tweet successfully sent.');
                    } else {
                        alert('Ups, there was a problem. Error code:' + data);
                    }

                }, "json");
                
            $(this).parent().text('Saving...');
                
        });
        
        
        // Add the save box to the DOM
        tweet.prepend(savebox);
        
    },
    
    cancelSave: function() {
        var tweet = $(this).parents('.tweet');
        var savebox = tweet.find('.'+repair.savebox_class);
        savebox.remove();
        tweet.find('.edit').show();
        tweet.find('.save').show();
        $(this).remove();
    },
    
};

$(document).ready(function() {
    repair.init();
});