var hidden_alerts = [];

/* alerts */
function show_alert_portfolio(portfolio_id) {
    $('.portfolio_collapse_container').hide();
    $('#portfolio_' + portfolio_id).slideDown();
    $('.trade_links a').removeClass('selected_link');
    $('#portfolio_select_' + portfolio_id).addClass('selected_link');
    $('#portfolio_' + portfolio_id).find('.trade-table').css('width','').find('a.expanded').removeClass('expanded');
}

function more_closed_positions(portfolio_id) {
    var last_id = $('#portfolio_' + portfolio_id + ' tr').last()[0].id;
    last_id = last_id.match(/position_row_(\d+)/)[1];
    $.ajax({
            'url': '/alerts/more_closed/' + last_id + '/',
            'success': function(data, textStatus, request) {
                $('#portfolio_' + portfolio_id + ' table:last').append(data);
            }
            });
}
function create_entry_alert() {
    $('#entry_alert_form').slideToggle();
}

function create_comment_alert() {
    $('#comment_alert_form').slideToggle();
}
function show_exit_alerts() {
    if ($("#exit_alert_holder").is(':visible')) {
        $("#exit_alert_holder").slideUp();
    }
    else {
        $("#exit_alert_holder").load("/alerts/exit/", function(
                    response, textStatus, xhr) {
            $("#exit_alert_holder").slideDown();
        });
    }
}
function submit_exit_form() {
    $(this.form).ajaxSubmit({
            'target': '#exit_alert_holder',
            'data': {'num_exits': this.value}
            });
}

/* chat */
function refresh_chat_archive() {
    $.ajax({
        url: "/trade-room/ajax/",
        success: function(data, textStatus, request) {
            $('#archive_contents').html(data);
            $('#archive_box h3').html("Today's Archive");
            $('#archive_box button').html("Refresh");
        }
    });
}

/* aggregator */
function disable_entire_form() {
    $('select', this).attr('readonly', 'readonly');
    $('input[type=text]', this).attr('readonly', 'readonly');
    $('textarea', this).attr('readonly', 'readonly');
    /* delay the button disable until after the actual submit so the
     * button attributes go with the POST, else preview doesn't work. */
    setTimeout(function() {
        $('input[type=submit]', this).attr('disabled', 'disabled');
    }, 0);
    return true;
}

var alerts_json = '';
function refresh_tweets() {
    $.ajax({
        url: "/aggregator/refresh/",
        data: null,
        success: function(data, textStatus, request) {
            if (textStatus == 'notmodified') {
                return;
            }
            if (alerts_json == '') {
                alerts_json = data.alerts;
            }
            else if (data.alerts != alerts_json) {
                if (play_alert == true) {
                    $("#jquery_jplayer").jPlayer("play");
                }
                alerts_json = data.alerts;
            }
            /* check the follow/unfollow text for question items, and leave it how it was */
            var selector = $("#aggregates_container .followed_question");
            selector = $.map(selector, function(s) { return '#' + $(s).attr('id'); }).join(', ');
            var base = $(data.aggregates);
            base.filter(selector).addClass('followed_question');
            base.filter(selector).find('.question-follow').html('Unfollow');
            $("#aggregates_container").html(base);

            selector = $.map(hidden_alerts,function(s){return '#alert-' + s;}).join(', ');
            base = $(data.alerts);
            var count = base.find(selector).size();
            base.find(selector).css('display','none');
            base.find('.titleBox strong').text(function(i,t){return parseInt(t - count)});
            $("#alerts_container").html(base);
            update_show_hide_button();
        },
        dataType: 'json',
        ifModified: true
    });
}

/* bootcamp aggregator */
/* I feel the bootcamp code is kind of a hack right now and am reluctant
 * to even include this in the main js file. For performance sake, however,
 * it makes sense to load it only once.
 * 
 * bootcamp doesn't auto-refresh (currently), so the number of tweets is set in
 * the url instead.
 *
 * either the url does not contain a number of tweets, in which case, we
 * default to 20 tweets and the next request is for 40 tweets. Or the url
 * contains the number of tweets, and we add 20 to that.
 *
 * Could this code be uglier? We have a silly regex, hard-coded urls, magic
 * numbers and special cases. Only thing missing is a goto!
 */
function request_more_bootcamp() {
    parse = /(.*)\/([^\/]*)\/$/.exec(window.location.href);
    tail = parse[2];
    path = parse[1];
    if (tail == "aggregator") {
        path = path + "/aggregator/40/";
    }
    else {
        count = parseInt(tail) + 20;
        path = path + "/" + count + "/";
    }
    window.location = path;
}
/* answers */
function toggle_follow_question(event) {
    event.preventDefault();
    var link = $(this);
    if(link.text() == "Follow") {
        follow = 'follow';
    } else {
        follow = 'unfollow';
    }
    update_follow_question(0, link, follow);
}

/* index is a bogus param so we can use this with $().each() */
function update_follow_question(index, link, value) {
    link = $(link);
    if(value) {
        data = {'follow': value};
    } else {
        data = {};
    }
    $.post(link.attr('href'),
        data,
        function(data, textStatus, request) {
            link.html(data);
            /* on aggregator, mark the whole question node as followed */
            if(data == 'Follow') {
                link.parents('.aggregate_question').removeClass('followed_question');
            } else {
                link.parents('.aggregate_question').addClass('followed_question');
            }
    });
}
function vote_question(question_id, rating) {
    $.post("/answers/vote_question/" + question_id + "/",
            {'rating': rating},
            function(data, textStatus, request) {
                $("#question_vote_rating").html('<span class="rating">' + data.rating + '</span>');
                $("#question_vote_rating").attr(
                    "class", "vote_" + data.vote_direction);
                $("#question_vote_links").remove();
            },
            'json'
            );
}
function vote_answer(answer_id, rating) {
    $.post("/answers/vote_answer/" + answer_id + "/",
            {'rating': rating},
            function(data, textStatus, request) {
                $("#answer_vote_" + answer_id).html('<span class="rating">' + data.rating + '</span>');
                $("#answer_vote_" + answer_id).addClass(
                    "vote_" + data.vote_direction);
                $("#answer_vote_links_" + answer_id).remove();
            },
            'json'
            );
}
/* account profile */
function show_profile_box(profile_type) {
    $(".settings_box").hide();
    $("#settings_" + profile_type).slideDown();
    $(".settings_link").removeClass("selected_link");
    $("#settings_link_" + profile_type).addClass("selected_link");
}

function update_show_hide_button() {
  if ( $('#allAlert .aggregate_alert:visible').size() > 0 ) {
    $('#show-hide-all-alerts').text('Hide all');
  } else {
    $('#show-hide-all-alerts').text('Show all');
  }
}

jQuery(function($){
  $('#show-hide-all-alerts').bind('click', function(e) {
    e.preventDefault();
    if ( $('#allAlert .aggregate_alert:visible').size() > 0 ) {
      $('#allAlert .aggregate_alert:visible .closeAlert a').click();
    } else {
      $('#alerts_container .titleBox strong').text($('#allAlert .aggregate_alert').slideDown(update_show_hide_button).size());
      hidden_alerts = [];
    }
  });
  
  $('#allAlert .closeAlert a').live('click', function(e){
    if ( e ) { e.preventDefault(); }
    id = $(this).closest('.aggregate_alert').attr('id').replace(/\D*/,'');
    hidden_alerts.push(id);
    $(this).closest('.aggregate_alert').slideUp(update_show_hide_button);
    $('#alerts_container .titleBox strong').text(function(i,txt){return parseInt(txt) - 1});
  });
  
  update_show_hide_button();
});

