function figure_out_position(grid_object) {

    switch(grid_object.attr('id')) {
        
        case 'profile_element_1':
            var position = 1;
            break;
        
        case 'profile_element_2':
            var position = 2;
            break;
        
        case 'profile_element_3':
            var position = 3;
            break;
        
        case 'profile_element_4':
            var position = 4;
            break;
        
        case 'profile_element_5':
            var position = 5;
            break;
        
        case 'profile_element_6':
            var position = 6;
            break;
        
        case 'profile_element_7':
            var position = 7;
            break;
        
        case 'profile_element_8':
            var position = 8;
            break;
        
        case 'profile_element_9':
            var position = 9;
            break;
            
    }
    return position;
}

function name_wizard_form() {
    
    var form_modal = $("#name_wizard").dialog({modal : true, closeText : 'Skip'});
    
    var form_options = {
        dataType : 'json',
        success  : function(json) {
            if(json.success) {
                $('#profile_name .first_name').text(json.first_name);
                $('#profile_name .last_name').text(json.last_name);
                form_modal.dialog('destroy');
                location_wizard_form();
            }
        }
    }
    
    $('.name_wizard_form').ajaxForm(form_options);
}

function location_wizard_form() {
    var form_modal = $("#location_wizard").dialog({ modal : true, closeText : 'Skip' });
    var form_options = {
        dataType : 'json',
        success  : function(json) {
            if(json.success) {
                $('#profile_location').text(json.location);
                form_modal.dialog('destroy');
                profile_picture_wizard_form();
                
            }
        }
    }
    
    $('.location_wizard_form').ajaxForm(form_options);
    
}

function profile_picture_wizard_form() {
    var form_modal = $("#profile_picture_wizard").dialog({modal : true, closeText : 'Skip'});
    console.log(form_modal);
    var form_options = {
        dataType : 'json',
        success  : function(json) {
            if(json.success) {
                console.log('#profile_picture_image');
                $('#profile_picture_image').attr('src', json.src);
                $(this).dialog('destroy');
                talent_wizard_form();
            }
        }
    }
    
    $('.profile_picture_wizard_form').ajaxForm(form_options);
    
}

function talent_wizard_form() {
    
    var form = $("#talent_wizard").dialog({modal:true, closeText : 'Skip'});
    
    $("#talent_wizard_musician").click(function(json){
        $.post('/api/profiles/save_talent/', { 'talent_slug' : 'musician'}, function() {
            $('#talent_wizard').remove();
            $("#profile_talents .talent_icons").append('<li class="talent_icon"><img src="/static/images/talent_icon-small-musician.png" alt="musician"></li>');
        }, 'json');
    });
    
    $("#talent_wizard_model").click(function(json){
        $.post('/api/profiles/save_talent/', { 'talent_slug' : 'model'}, function() {
            $("#profile_talents .talent_icons").append('<li class="talent_icon"><img src="/static/images/talent_icon-small-model.png" alt="model"></li>');
            $('#talent_wizard').remove();
            form.dialog('destory');
            
        }, 'json');
    });
    
    $("#talent_wizard_artist").click(function(json){
        $.post('/api/profiles/save_talent/', { 'talent_slug' : 'artist'}, function() {
            form.dialog('destory');
            $('#talent_wizard').remove();
            $("#profile_talents .talent_icons").append('<li class="talent_icon"><img src="/static/images/talent_icon-small-artist.png" alt="artist"></li>');
            
        }, 'json');
    });
    
    $("#talent_wizard_entertainer").click(function(json){
        $.post('/api/profiles/save_talent/', { 'talent_slug' : 'entertainer'}, function() {
            form.dialog('destory');
            $('#talent_wizard').remove();
            $("#profile_talents .talent_icons").append('<li class="talent_icon"><img src="/static/images/talent_icon-small-entertainer.png" alt="entertainer"></li>');
            
        }, 'json');
    });
    
    $("#talent_wizard_athlete").click(function(json){
        $.post('/api/profiles/save_talent/', { 'talent_slug' : 'athlete'}, function() {
            form.dialog('destory');
            $('#talent_wizard').remove();
            $("#profile_talents .talent_icons").append('<li class="talent_icon"><img src="/static/images/talent_icon-small-athlete.png" alt="athlete"></li>');
            
        }, 'json');
    });
        
}

function twitter_callback(twitters){
    var username = twitters[0].user.screen_name;
    var status   = twitters[0].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
        return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
        return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    
    return status;
}

function show_module_form(grid_space, str_form_container) {
    
    /* 
        Grab the contents of jQuery object matched by str_form_container
        and place it in the grid module (expecting jQuery object).
    */
    
    var form_container = $(str_form_container);
    var module_contents = form_container.html();
    grid_space.html(module_contents);

    return grid_space;
}

$(document).ready(function() {
    
    // *******************************************
    // Profile Wizard
    // *******************************************
    
    var requested_user = $("#metadata_requested_user").val()
    var profile_step   = $("#metadata_profile_step").val()

    // Depending on what step the user is on, display the proper modal
    // ***NOTE*** Will probably want to look up a good modal window for this.
    
    if(profile_step == 1) { name_wizard_form(); }
    if(profile_step == 2) { location_wizard_form(); }
    if(profile_step == 3) { profile_picture_wizard_form(); }
    if(profile_step == 4) { talent_wizard_form(); }
    
   
    
    // Show the user their wizard if they have a profile_step assigned
    
    // *******************************************
    // *** Profile Grid Stuff                  ***
    // *******************************************

    // Add to a grid sapce        
    $("#profile_grid .empty").live('click', function() {

        $(this).removeClass("empty").addClass("editing");       
        $(this).html($('#available_grid_modules').html());
        
    });
    
    // *****
    // Load Profile Grid Menus
    // *****
    
    $('.select_picture_module').live('click', function() {
        show_module_form($(this).closest('.grid_space'), '#picture_grid_module');
    });
    
    $('.select_text_module').live('click', function() {
        show_module_form($(this).closest('.grid_space'), '#text_grid_module');
    });
    
    $('.select_tweet_module').live('click', function() {
        show_module_form($(this).closest('.grid_space'), '#tweet_grid_module');
    });
    
    $('.select_audio_module').live('click', function() {
        show_module_form($(this).closest('.grid_space'), '#audio_grid_module');
    })
    
    $('.select_embedded_video_module').live('click', function() {
        show_module_form($(this).closest('.grid_space'), '#embedded_video_grid_module');
    });
    
    $('input[type=submit].submit_embedded_video_module').live('click', function() {
        var form = $(this).parent('form');
        var grid_space = form.closest('.grid_space');
        var form_options = {
            dataType: 'json',
            success: function(json){
                window.location.reload();
            }
        }
        
        var position_field = $('<input type="hidden" name="position">');
        position_field.val(figure_out_position(grid_space));
        form.append(position_field);
        form.ajaxSubmit(form_options);
        return false;
        
    });
    
    $('input[type=submit].submit_audio_module').live('click', function() {
        var form = $(this).parent('form');
        var grid_space = form.closest('.grid_space');
        var form_options = {
            dataType: 'json',
            success: function(json){
                window.location.reload();
            }
        }
        
        var position_field = $('<input type="hidden" name="position">');
        position_field.val(figure_out_position(grid_space));
        form.append(position_field);
        form.ajaxSubmit(form_options);
        return false;
        
    });
    
    $("input[type=submit].submit_tweet_module").live('click', function() {
        var form = $(this).parent('form');
        var grid_space = form.closest('.grid_space');
        var form_options = {
            dataType : 'json',
            success: function(json) {
                window.location.reload();
            }
        }
        var position_field = $('<input type="hidden" name="position">');
        position_field.val(figure_out_position(grid_space));
        form.append(position_field);
        form.ajaxSubmit(form_options);
        return false;
    });
        
    $("input[type=submit].submit_picture_module").live('click', function() {
        var form = $(this).parent('form');
        var grid_space = form.closest('.grid_space');                    

        var form_options = {
            dataType: 'json',
            success: function(json) {

                if(json.success) {
                    var new_image = $('<img>');
                    var grid_editor = form.closest('.grid_module_editor');
                    new_image.attr('src', json.datastore.media_src);
                    grid_space.append(new_image).removeClass('editing');
                    grid_editor.remove();
                    
                } else {
                    
                    $(this).val('Try Again');
                    
                }
            }
        }
        
        var position_field = $('<input type="hidden" name="position">');
        position_field.val(figure_out_position(grid_space));
        form.append(position_field);
        form.ajaxSubmit(form_options);
        return false;
    });
    
    // // Show the grid actions on hover
    //     $('li.has_content').hover(
    //         function() {
    //             var grid_actions = $(this).find('.grid_actions');
    //             var grid_contents = $(this).html();
    //             
    //             $(this).html(grid_actions.html());
    //             
    //         },
    //         
    //         function() {
    //             console.log('hovering out of content');
    //         });
    
    $("input[type=submit].submit_text_module").live('click', function() {
        var form           = $(this).parent('form');
        var grid_space     = form.closest('.grid_space');
        var position_field = $('<input type="hidden" name="position">');

        var form_options   = {
            dataType : 'json',
            success  : function(json) {
                if(json.success) {
                    var new_content = $('<div class="text_module_content">');
                    new_content.append('<h3 class="text_module_header">' + json.datastore.title + '</h3>');
                    new_content.append('<div class="text_module_body">' + json.datastore.body + '</div>');
                    var grid_editor = form.closest('.grid_module_editor');
                    grid_space.append(new_content).removeClass('editing').addClass('text');
                    grid_editor.remove();

                } else {
                    $(this).val('Try Again');
                }

            }
        }

        position_field.val(figure_out_position(grid_space));
        form.append(position_field);
        form.ajaxSubmit(form_options);

        return false;

    });
    
    $("#bio_copy.empty").live('click', function() {
        var form_content = $("#bio_copy_form").html();
        var form_target = $(this).parent().find('#update_bio_copy_form');
        $(this).removeClass('empty').addClass('editing');
        form_target.html(form_content);

    });
    
    $(".edit_bio_copy").live('click', function() {
        var bio_copy_form = $('#bio_copy_form').html();
        var grid_space = $(this).parent();
        var form = $('<div id="update_bio_copy_form">' + trim(bio_copy_form) + '</div>').addClass('editing').removeClass('has_copy');
        grid_space.html('');
        grid_space.append(form.hide().fadeIn(2000));
    })
    
    $(".submit_bio_copy_update").live('click', function() {

       // Create the form object
       var form = $(this).parent('form');
       var grid_space = form.parent();
       // Configure the form's options
       var form_options = {
            dataType: 'json',
            success : function(json) {
                // Call back for successful request

                // Check is data was successfully processed
                if(json.success) {
                    $("#bio_copy").html('<div id="bio_copy_text">' + json.bio + '</div><button class="edit_bio_copy">Edit Your Bio</button>').removeClass('editing').addClass('has_copy');
                    $('.bio_textarea').text(json.bio);
                    
                } else {
                    $(this).text('Try Again');
                }
            }
       }
       
       // Submit the form
       form.ajaxSubmit(form_options);
       
       // Stupid JS
       return false;
        
    });
    
    
    // ***
    // Hover options ftw
    // ***
    
    var hover_options_overlay = $('<div id="hover_options_overlay"></div>').append($('<ul id="hover_options" />').html($('#hover_options_list').html()));
    
    $('.show_hover_options').hover(function() {
        var _self = $(this);
        var recommend = _self.next('.hover_item').clone().show().appendTo(hover_options_overlay.find('#hover_options'));
        _self.prepend(hover_options_overlay);
    }, function() {
        hover_options_overlay.find('.hover_item').remove();
        hover_options_overlay.remove();
    });
    
    $('.remove_item a').live('click', function() {
        var _self = $(this);
        var _element = $(this).closest('.grid_space');
        $.ajax({
            url: _self.attr('href'),
            type: "GET",
            dataType: "json",
            success: function(json) {
                if(json.success){
                    _element.html('').removeClass('has_content').addClass('empty');
                }
            }
        });
        
        return false;
    });
    
    $(".recommend_item a").live('click', function() {
        var _self = $(this);
        $.ajax({
            url: _self.attr('href'),
            type: "POST",
            dataType: "json",
            data: {},
            success: function(data) {
                if (_self.text() == 'Recommend')
                {
                    _self.text('Remove recommendation');
                }
                else
                {
                    _self.text('Recommend');
                }
            },
            error: function() {
            //called when there is an error
            },
        });        
        return false;
    });
    
    $(".change_profile_picture_link").live('click', function() {
        var form_modal = $("#profile_picture_wizard").dialog({modal : true, closeText : 'Skip'});
        var form_options = {
            dataType : 'json',
            success  : function(json) {
                if(json.success) {
                    $('#profile_picture_image').attr('src', json.src);
                    $('#profile_picture_wizard').dialog('destroy');
                }
            }
        }

        $('.profile_picture_wizard_form').ajaxForm(form_options);
    });
    
});
