if (Buzz == undefined) { var Buzz = {} }
if (Buzz == undefined) { Buzz = {} }

if (!Buzz.Charts) { Buzz.Charts = {} }
if (!Buzz.Activity) { Buzz.Activity = {} }

Buzz.Activity = new function() {
  // v is a key-value hash of url parameters
  this.Load = function(v) {
    var q = [];
    for (var k in v) {
      q.push(k + "=" + v[k]);
    };
    //report_url_root is a global variable embedded in haml
    window.location = report_url_root + "/?" + q.join("&");
  }
}

Buzz.Charts = new function() {
  var MIN_PERCENTAGE_FOR_LABEL = 10.0;

  this.PieTooltipFormat = function(label, value, total, suffix) {
    var percentage = (value / total) * 100;
    return '<b>'+ label +'</b>: '+ value + suffix + ' (' + percentage.toFixed(1) + '%)';
  }

  this.PieLabelFormat = function(label, value, total) {
    var percentage = (value / total) * 100;
    if(percentage > MIN_PERCENTAGE_FOR_LABEL)
      return label;
  }

  this.PieLabelStyle = function() {
    return { font: '13px Trebuchet MS, Verdana, sans-serif' }
  }

}

$j(document).ready(function() {
   $j('a.help').each(function() {
     var helpContent = $j(this).next(".help_content:first");
     var title = helpContent.attr("title");
     var content = helpContent.html();
     $j(this).qtip({
        content: {
           title: {
              text: title,
              button: '<a href="#" class="qtip_close">Close<a>'
           },
           text: content
        },
        position: {
           target: $j(document.body), // Position it via the document body...
           corner: 'center' // ...at the center of the viewport
        },
        show: {
           when: 'click', // Show it on click
           solo: true // And hide all other tooltips
        },
        hide: false,
        style: {
           width: { max: 450 },
           padding: '8px 16px 16px 16px',
           border: {
             width: 5,
             radius: 4,
             color: '#666666'
           },
           title: {
            background: "none",
            color: "#939598",
            "font-weight": "normal",
           },
           classes: {
             title: "help_title",
             content: "help_content"
           },
           name: 'light'
        },
        api: {
           beforeShow: function()
           {
              // Fade in the modal "blanket" using the defined show speed
              $j('#qtip-blanket').fadeIn(this.options.show.effect.length);
           },
           beforeHide: function()
           {
              // Fade out the modal "blanket" using the defined hide speed
              $j('#qtip-blanket').fadeOut(this.options.hide.effect.length);
           }
        }
     });
  });

  // Create the modal backdrop on document load so all modal tooltips can use it
  $j('<div id="qtip-blanket">')
    .css({
       position: 'absolute',
       top: $j(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
       left: 0,
       height: $j(document).height(), // Span the full document height...
       width: '100%', // ...and full width

       opacity: 0.7, // Make it slightly transparent
       backgroundColor: 'black',
       zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
    })
    .appendTo(document.body) // Append to the document body
    .hide(); // Hide it initially
});

Buzz.ReplyManager = new function() {
  var pointer = this;
  
  this.Replying = function(container) {
    $j(".reply_button", container).attr("disabled", "disabled");
    $j(".reply_loading", container).show();
  }
  
  this.ReplyDone = function(container) {
    $j(".reply_button", container).removeAttr("disabled");
    $j(".reply_loading", container).hide();
  }
  
  this.ReplyAuth = function(container) {
    this.Replying(container);
    $j.post("/businesses/update_status/" + Buzz.ColumnManager.BusinessId(),
      { status: $j(".reply_text", container).val() },
      function(response) {
        $j(".reply_finished_link", container).attr("href", "http://twitter.com/" + response.screenname + "/status/" + response.id);
        $j(".reply_finished", container).show();
        pointer.ReplyDone(container);
      },
      "json"
    );
  } 
  
  this.ReplyNoAuth = function(container) {
    window.open("http://twitter.com/home?status=" + $j(".reply_text", container).val());
  }
}

Buzz.Dashboard = new function() {
  var pointer = this;
  
  this.UpdateStatus = function(status) {
    $j.post("/businesses/update_status/" + Buzz.ColumnManager.BusinessId(), {"status": status}, function(data) { $j("#status_response").html(data.response); }, "json")
  }
  
  // update chart with my data
  this.UpdateChart = function(chartName, data) {
    var tmp = findSWF(chartName);
    if (tmp == null || tmp.load == null) {
      return; 
    }
    tmp.load(data);
  }
  
  // item click
  this.ItemClicked = function(series, index) {
    alert(chart_data["elements"][series]["values"][index].month);
  }
  
  var gotData = function(data) {
    pointer.SetData(data);
    pointer.UpdateChart();
  }
  
  this.LoadData = function() {
    $j.getJSON("/business/json", gotData)
  }
  
  // *** sentiment
  this.LoadSentiment = function(ele) {
    // toggle sentiment
    if ($j(ele).hasClass("expanded")) {
      $j(".expanded").removeClass("expanded");
      $j(".sentiment_details").hide();
      $j("span.arrow", $j(ele)).removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
    } else {
      $j(ele).addClass("expanded");
      var rowDiv = $j(ele).parent().parent().parent().parent();
      $j(".sentiment_list").hide();
      rowDiv.find(".positive_sentiment").append($j("#sentiment_positive"));
      rowDiv.find(".negative_sentiment").append($j("#sentiment_negative"));
      $j(".sentiment_details").show();
      $j(".sentiment_loading").show();
      $j("span.ui-icon-triangle-1-s").removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
      $j("span.arrow", $j(ele)).removeClass("ui-icon-triangle-1-e").addClass("ui-icon-triangle-1-s");
    }
  }
  
  this.LoadSentimentFinished = function() {
    $j(".qtip").qtip("hide");
    $j(".sentiment").each(function() {
      var $sentiment = $j(this);
      $sentiment.qtip({
        content: {
          text: "Loading...",
          title: { text: "Opinion", button: 'Close' },
          url: $j(this).attr("rel") + "?keyword=" + $sentiment.text()
        },
        position: {
          corner: { target: "topMiddle", tooltip: "bottomMiddle" },
          adjust: { screen: true }
        },
        style: {
          border: { width: 2, radius: 5, color: '#ABC639' },
          width: { min: 400, max: 500 },
          title: { 'font-size': 12, 'padding': 5, 'background-color': '#F2EEE2' },
          tip: true,
          name: 'light'
        },
        show: {
          when: {
            event: "click"
          }
        },
        hide: {
          when: { event: 'unfocus' }
        },
        api: {
          beforeShow: function() {
            $j(".qtip").qtip("hide");
          },
          beforeRender: function() {
            $j(".qtip").qtip("hide");
          }
        }
      });
    });
  }
  
  // *** resizing
  this.ContentWidth = function() {
    var w = $j(".full_container:first").width();
    return w;
  }

  this.Resize = function() {
    //var h = $(window).height();

    $j(".ofc_half").each(function() {
      var width_offset = $j(this).attr("width_offset");
      var offset = width_offset == null ? 0 : parseInt(width_offset);
      $j(this).children().each(function() {
        $j(this).css("width", pointer.HalfContentWidth() - offset);
      })
    });

    $j(".ofc_full").each(function() {
      var width_offset = $j(this).attr("width_offset");
      var offset = width_offset == null ? 0 : parseInt(width_offset);
      $j(this).children().each(function() {
        $j(this).css("width", pointer.ContentWidth() - offset);
      })
    });

    Buzz.ColumnManager.Resize();
  }
  
}
