var question_chart_info;
var quiz_chart_info;
var category_chart_info;

function write_chart(chart_info) {
  var width = chart_info['width'] ? chart_info['width'] : 640;
  var chart = new FusionCharts(
    $('base').attr('href') + 'static/flash/charts/' + chart_info['type'] + '.swf',
    chart_info['div'] + '_swf',
    width,
    chart_info['height'],
    0, 1, '', '', '', 1, -1
  );
  chart.setDataXML(encodeURIComponent(chart_info['xml']));
  return chart.render(chart_info['div']);
}
function update_question_chart(q_id) {
  write_chart(question_chart_info[q_id]);
  if ($('div.quiz_navigation').length) {
    show_question_info(q_id);
    show_arrows();
  }
}
function show_arrows() {
  var qs = $('#question_results_select');
  if (qs[0].selectedIndex == 0) {
    $('#arrow_left').addClass('disabled');
    $('#arrow_right').removeClass('disabled');
  } else if (qs[0].selectedIndex == qs[0].options.length - 1) {
    $('#arrow_left').removeClass('disabled');
    $('#arrow_right').addClass('disabled');
  } else {
    $('#arrow_left').removeClass('disabled');
    $('#arrow_right').removeClass('disabled');
  }
}
function next_question() {
  var qs = $('#question_results_select');
  if (qs[0].selectedIndex != qs[0].options.length - 1) {
    qs[0].selectedIndex++;
    update_question_chart(qs.val());
  }
}
function previous_question() {
  var qs = $('#question_results_select');
  if (qs[0].selectedIndex != 0) {
    qs[0].selectedIndex--;
    update_question_chart(qs.val());
  }
}
function show_question_info(q_id) {
  $('ol.question_info li').each(function(){
    if ($(this).attr('id') == 'quiz_question_' + q_id + '_info') {
      $(this).show();
    } else {
      $(this).hide();
    }
  });
}

var inital_urls_per_domain;
var more_urls_per_domain;
var domain_length;

$(document).ready(function(){

  var any_charts = 0;

  if (question_chart_info != undefined) {

    any_charts = 1;

    var q_id;
    if ($('#question_results_select').length) {
      q_id = $('#question_results_select').val();
    } else {
      for (var question_id in question_chart_info) {
        q_id = question_id;
        break;
      }
    }

    if (write_chart(question_chart_info[q_id])) {
      if ($('div.quiz_navigation').length) {
        show_question_info(q_id);
        show_arrows();
      }
    } else {
      $(".no_flash").show();
    }

    $('#arrow_left').click(function(){
      previous_question();
      return false;
    });
    $('#arrow_right').click(function(){
      next_question();
      return false;
    });
    $('#question_results_select').change(function(){
      update_question_chart($(this).val());
    });

  }

  if (quiz_chart_info != undefined) {

    any_charts = 1;

    if (!write_chart(quiz_chart_info)) {
      $('.no_flash').show();
    }

  }

  if (category_chart_info != undefined) {

    any_charts = 1;

    if (!write_chart(category_chart_info)) {
      $('.no_flash').show();
    }

  }

  if (any_charts && document.location.hash) {
    document.location.hash = document.location.hash;
  }
  
  /* source_domains table */
  
  var qs = qs_deserialize(document.location.search);
  
  $("table.source_domains tr:not(.source_domain)")
    .filter(function(){ return $(this).find("td").wrapInner("<span/>").length; })
    .addClass("hidden");
    
  $("table.source_domains tr.source_domain").each(function(){
    $(this)
      .hover(
        function(){
          $(this).find("td").addClass("over");
        },
        function (){
          $(this).find("td").removeClass("over");
        })
      .click(function(){
        var current = $(this).hasClass("selected");
        
        if (current) {
          $(this).removeClass("selected");
        } else {
          $(this).addClass("selected");
          //$(this).siblings(".selected").click(); // collapse others
        }
        
        var cur_num = 0;
        $(this).nextAll().each(function(){
          if ($(this).hasClass("source_domain")) {
            return false;
          } else {
            if (current) {
              $(this).addClass("hidden");
            } else if (cur_num < inital_urls_per_domain || $(this).hasClass("more_urls")) {
              $(this).removeClass("hidden");
              $(this).find("span").hide().fadeIn();
            }
          }
          cur_num++;
        });
      })
      .find("td:first")
      .html("<img src='static/images/plus.gif' alt='' class='plus'><img src='static/images/minus.gif' alt='' class='minus'>")
      .parent().filter(function(){
        if (qs.source_domain) {
          var domain = $.trim($(this).find("td.col2").text());
          return domain == qs.source_domain;
        } else {
          return false;
        }
      })
      .click();
      
  });

  $('table.source_domains tr.more_urls a').click(function(){
    $(this).addClass('hidden');
    var load_tr = $(this).parents('tr:first');
    
    // get amount currently shown and domain
    var cur_num = 0;
    var domain;
    $(this).parents('tr:first').prevAll().each(function(){
      if ($(this).hasClass('source_domain')) {
        domain = $.trim($(this).find('td.col2 a').html());
        if (!domain) {
          domain = $.trim($(this).find('td.col2').html());
        }
        return false;
      } else {
        $(this).removeClass("hidden");
      }
      cur_num++;
    });
    
    if ($(this).data("all_urls_fetched")) {
      load_tr.addClass('hidden');
      $(this).removeClass('hidden');
      return false;
    }
    
    var loader = $('<div><img class="source_spinner" src="' + $('base').attr('href') + 'static/images/ajax-loader.gif"> loading...</div>');
    $(this).after(loader);
    
    // make call to server to get domains
    var _this = $(this);
    $.ajax({
      type: "GET",
      url: _this.attr('href'),
      dataType: 'json',
      data: {
        'fetch_source_urls': 1,
        'domain': domain,
        'cur_num': cur_num,
        'more_urls_per_domain': more_urls_per_domain
      },
      success: function(response) {
        if (response['source_urls']) {

          // loop over new urls
          for (var x=0; x < response['source_urls'].length; x++) {

            var source_url   = response['source_urls'][x]['source_url'];
            var num_response = response['source_urls'][x]['num_response'];

            // clone last url
            var new_tr = load_tr.prev().clone();

            // insert new url
            if (source_url.match('^https', 'i')) {
              new_tr.find('td.col2').html(source_url);
            } else {
              new_tr.find('td.col2').html('<a href="' + source_url + '">' + elide_middle(source_url, domain_length) + '</a>');
            }
            // insert new response num
            new_tr.find('td.col3').html(num_response);

            // insert into dom
            load_tr.before(new_tr);
          }
        }
        
        if (response['num_urls_remaining'] == "0") {
          _this.data("all_urls_fetched", true);
          load_tr.addClass('hidden');
        }
        loader.remove();
        _this.removeClass('hidden');
      },
      error: function() {
      }
    });
    return false;
  });
  
});

function elide_middle(string, max_length) {
  if (string.length <= max_length) {
    return string;
  }
  var marker = '...';
  var keep = max_length - marker.length;
  var keep_right;var keep_left;
  keep_left = keep_right = Math.floor(keep/2);
  if ((keep_left + keep_right) < keep) {
    keep_left++;
  }
  return string.substr(0, keep_left) + marker + string.substr(string.length - 1 - keep_right, keep_right);
}
