itemKeys = []
ratingItems = []
ratingItemsOverall = []
ratingItemsFrequency = []
ratingItemsDesign = []
ratingItemsRelevancy = []
ratingItemsValue = []
surveyItems = []
npsItems = []
reviewItems = []
sxiItems = []

feedItems = []
feedItemFKs = []

#Save Current States
currentGraph = ""
currentData = ""
currentRange = ""

#Dashboard Quick Indicator Values
tempEngagements = 0
tempChurn = 0
numMessages = 0
numResponses = 0

#Globals for D3
graphMin = ""
graphMax = ""

engagementGraph = "#VOSGraph"
unsubGraph = "#unsubGraph"
messageGraph = "#messageGraph"

margin = {top: 30, right: 30, bottom: 70, left: 60}

containerHeight = $(engagementGraph).height()
containerWidth = $(engagementGraph).width()


width = containerWidth-100
height = 290
padding = 0

#Set Default type
type = "sxi"

#substantiate ratingType
ratingType = "all"

#Substantiate Response_id
response_id = ""

currentDate = moment()

weekDate = currentDate.subtract(1, "w").format("YYYYMMDDHHmmss")

monthDate = currentDate.subtract(1, "M").format("YYYYMMDDHHmmss")

yearDate = currentDate.subtract(1, "y").format("YYYYMMDDHHmmss")

#Set to get all engagement events
start = 0
limit = 1000000000000

String.prototype.capitalize = ->
  return this.replace(/(?:^|\s)\S/g,(a) ->
    return a.toUpperCase()
  )

#ENGAGEMENTS GRAPH
parseDate = d3.time.format("%d-%b-%y").parse
bisectDate = d3.bisector((d) -> return d.x).left

x = d3.time.scale()
  .range([0, width])

y = d3.scale.linear()
  .range([height, 0])


xAxis = d3.svg.axis()
  .scale(x)
  .ticks(8)
  .tickFormat((d) -> return moment(d).format("ddd DD"))
  .orient("bottom")

xAxisWeek = d3.svg.axis()
  .scale(x)
  .ticks(7)
  .tickFormat((d) -> return moment(d).add(1, 'days').format("ddd M/D"))
  .orient("bottom")

xAxisMonth = d3.svg.axis()
  .scale(x)
  .ticks(13)
  .tickFormat((d) -> return moment(d).format("MMM"))
  .orient("bottom")

yAxis = d3.svg.axis()
  .scale(y)
  .ticks(5)
  .orient("left")

#engagement Graph
svg = d3.select(engagementGraph).append("svg")
  .attr("class", "graph")
  .attr("width", width + margin.left + margin.right + 20)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("class", "container")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")  

rectangle = svg.append("rect")
  .attr("x", 0)
  .attr("y", -20)
  .attr("rx", 5)
  .attr("ry", 5)
  .attr("width", 820)
  .attr("height", 330)
  .attr("stroke", "#dbe0e2")
  .attr("stroke-width" , 1)
  .attr("fill", "#ffffff")

#Draw Bar Chart
#Churn Graph
chart = d3.select(".chart").append("svg")
  .attr("width", width + margin.left + margin.right + 20)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("class", "container")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

rectangle = chart.append("rect")
  .attr("class", "bg")
  .attr("x", 0)
  .attr("y", -20)
  .attr("rx", 5)
  .attr("ry", 5)
  .attr("width", 820)
  .attr("height", 330)
  .attr("stroke", "#dbe0e2")
  .attr("stroke-width" , 1)
  .attr("fill", "#ffffff")

xChart = d3.scale.ordinal().rangeRoundBands([0, 780], .1)
yChart = d3.scale.linear().range([320, 0])

yAxisChart = d3.svg.axis()
  .scale(yChart)
  .ticks(4)
  .orient("left")
  .tickFormat((d) -> return d + "%")

xAxisChart = d3.svg.axis()
  .scale(xChart)
  .ticks(6)
  .orient("bottom")

#Setup SXI Graph
sxi = d3.select(messageGraph).append("svg")
  .attr("class", "graph")
  .attr("width", width + margin.left + margin.right + 20)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("class", "container")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")  

rectangle = sxi.append("rect")
  .attr("x", 0)
  .attr("y", -20)
  .attr("rx", 5)
  .attr("ry", 5)
  .attr("width", 820)
  .attr("height", 330)
  .attr("stroke", "#dbe0e2")
  .attr("stroke-width" , 1)
  .attr("fill", "#ffffff")

#sets the size of the left nav
options = $(".accountOptions")
nav = $("#accountNav")
mainHeight = $("#rightContent").height()

updatePos = ->
  mainHeight = $("#rightContent").height()
  nav.height(mainHeight)
  $("#mainContent").height(mainHeight)
  if options.hasClass("fixed")
    if $(window).scrollTop() + $(window).height() > mainHeight + 39
      options.removeClass("fixed").addClass("relative")
      nav.removeClass("fixed").addClass("relative")
  if options.hasClass("relative")
    if $(window).scrollTop() + $(window).height() < mainHeight + 39
      options.removeClass("relative").addClass("fixed")
      nav.removeClass("relative").addClass("fixed")

#loads ratings initially
initialLoadGraph = ->
  #append axes and line to graphs
  svg.append("g")
    .attr("class", "x axis")
    .attr("stroke", "none")
    .attr("transform", "translate(0,310)")
    .call(xAxis)

  svg.selectAll(".x.axis g.tick line")
    .attr("y2", 320)
    .style("stroke", "#dbe0e2")
    .attr("transform", "translate(10,0)")

  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .attr("transform", "translate(-10,0)")
    .attr("opacity", 0)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")

  svg.selectAll(".y.axis g.tick line")
    .attr("x2", 820)
    .style("stroke", "#dbe0e2")
    .attr("transform", "translate(10,0)")
   
  svg.select(".y.axis")
    .attr("opacity", 0)
    .style("stroke", "none")

  svg.append("path")
    .attr("class", "line")
    .attr("stroke", "#6f90ab")
    .attr("stroke-width", 5)
    .attr("fill", "none")

  sxi.append("g")
    .attr("class", "x axis")
    .attr("stroke", "none")
    .attr("transform", "translate(0,310)")
    .call(xAxis)

  sxi.selectAll(".x.axis g.tick line")
    .attr("y2", 320)
    .style("stroke", "#dbe0e2")
    .attr("transform", "translate(10,0)")

  sxi.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .attr("transform", "translate(-10,0)")
    .attr("opacity", 0)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")

  sxi.selectAll(".y.axis g.tick line")
    .attr("x2", 820)
    .style("stroke", "#dbe0e2")
    .attr("transform", "translate(10,0)")
   
  sxi.select(".y.axis")
    .attr("opacity", 0)
    .style("stroke", "none")

  sxi.append("path")
    .attr("class", "line")
    .attr("stroke", "#6f90ab")
    .attr("stroke-width", 5)
    .attr("fill", "none")
  #get Total number of engagement ratings
  getItemList(weekDate)
  #get Total number of churn
  getChurnList("7d", false)
  #initially on ratings
  getSXIList("7d")

resetLine = (graphType) ->
  if graphType == "VOS"
    graph = d3.select("#VOSGraph")
  else
    graph = d3.select("#messageGraph")
  graph.select(".axis")
    .attr("opacity", 0)
  graph.selectAll(".line")
    .transition()
    .styleTween("opacity", -> return d3.interpolate(1,0))
    .duration(1500)
  setTimeout( ->
    graph.selectAll(".line")
    .remove()
  ,1000)
  #reset CircleGroup
  graph.selectAll(".circleGroup")
    .transition()
    .styleTween("opacity", -> return d3.interpolate(1,0))
    .duration(1500)
  setTimeout( ->
    graph.selectAll(".circleGroup")
    .remove()
  ,1000)

hardResetLine = (graphType) ->
  if graphType == "VOS"
    graph = d3.select("#VOSGraph")
  else
    graph = d3.select("#messageGraph")
  graph.select(".axis")
    .attr("opacity", 0)
  graph.selectAll(".line")
    .remove()
  graph.selectAll(".circleGroup")
    .remove()

updateChurnGraph = (feeds) ->
  chart.selectAll("rect")
    .data(feeds)
    .transition()
    .attr("y", (d) -> return yChart(d.value))
    .attr("height", (d) -> return height-yChart(d.value))
    .attr("width", 40)
    .attr("x", (d,i) -> return i)
    .attr("fill", "steelblue" )

#Draw the Graph
setupChurnGraph = (feeds) ->
  total = feeds.too_frequent + feeds.inbox_overflow + feeds.not_expected + feeds.not_relevant + feeds.repetitive + feeds.other
  container = "#unsubGraph"
  chart.selectAll("rect.bar")
    .remove()
  chart.selectAll(".axis")
    .remove()
  yChart.domain([0,100])
  chart.append("g")
    .attr("class", "y axis")
    .call(yAxisChart)
    .attr("transform", "translate(-5,-10)")
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
  chart.selectAll(".y.axis g.tick line")
    .attr("x2", 820)
    .style("stroke", "#dbe0e2")
    .attr("transform", "translate(5,0)")
  xChart.domain(["Frequency","Overload","Expectation","Relevancy","Repetition","Other"])
  chart.append("g")
    .attr("class", "x axis")
    .attr("stroke", "none")
    .attr("transform", "translate(20,310)")
    .call(xAxisChart)
  chart.selectAll("path.domain")
    .remove()

  chart.selectAll("text")
    .attr("fill", "#586874")
  if total == 0
    chart.select("rect.bg")
      .attr("fill", "#ffffff")
    $('div#noDataAlpha.alpha').addClass('active')
    $('div#noDataAlpha h4').text("We're not seeing anything yet. Please contact us to add the unsubscribe seal to your unsubscribe landing page.")
    $('div#noDataAlpha a.btn.important').attr("href", "mailto:contact@subscribervoice.com?subject=Unsubscribe Seal Request")
    $('#timeToggle button').removeClass('disabled')
    $('li.sub button.subSelector').removeClass('disabled')
    return
  
  chart.append("rect")
    .attr("class", "bar")
    .attr("id", "Frequency")
    .attr("x", 45)
    .attr("y", yChart(feeds.too_frequent * 100) - 10)
    .attr("height", yChart(100 - (feeds.too_frequent * 100)))
    .attr("value", feeds.too_frequent * 100)
  chart.append("rect")
    .attr("class", "bar")
    .attr("id", "Overload")
    .attr("x", 172)
    .attr("y", yChart(feeds.inbox_overflow * 100) - 10)
    .attr("height", yChart(100 - (feeds.inbox_overflow * 100)))
    .attr("value", feeds.inbox_overflow * 100)
  chart.append("rect")
    .attr("class", "bar")
    .attr("id", "Expectation")
    .attr("x", 299)
    .attr("y", yChart(feeds.not_expected * 100) - 10)
    .attr("height", yChart(100 - (feeds.not_expected * 100)))
    .attr("value", feeds.not_expected * 100)
  chart.append("rect")
    .attr("class", "bar")
    .attr("id", "Relevancy")
    .attr("x", 426)
    .attr("y", yChart(feeds.not_relevant * 100) - 10)
    .attr("height", yChart(100 - (feeds.not_relevant * 100)))
    .attr("value", feeds.not_relevant * 100)
  chart.append("rect")
    .attr("class", "bar")
    .attr("id", "Repetition")
    .attr("x", 553)
    .attr("y", yChart(feeds.repetitive * 100) - 10)
    .attr("height", yChart(100 - (feeds.repetitive * 100)))
    .attr("value", feeds.repetitive * 100)
  chart.append("rect")
    .attr("class", "bar")
    .attr("id", "Other")
    .attr("x", 680)
    .attr("y", yChart(feeds.other * 100) - 10)
    .attr("height", yChart(100 - (feeds.other * 100)))
    .attr("value", feeds.other * 100)

  chart.selectAll("rect.bar")
    .attr("width", 97)
    .style("fill", "#6f90ab")
    .on("mouseover", barMouseOver)
    .on("mouseout", barMouseOut)
    .on("click", barClick)
  $('#timeToggle button').removeClass('disabled')

type = (d) ->
  d.value = +d.value #coerce to number
  return d

stripNoData = (feeds) ->
  newData = []
  iter = 0
  newIter = 0 
  period = $('#VOS #timeToggle button.active').attr('id')
  if type == "sxi"
    while (feeds.length > iter) 
      if feeds[iter].y != -1
        newData[newIter] = feeds[iter]
        newIter++
      iter++
  else if type == "satisfaction"
    while (feeds.length > iter) 
      if feeds[iter].y != "noData"
        newData[newIter] = feeds[iter]
        newIter++
      iter++

  else
    while (feeds.length > iter) 
      if feeds[iter].y != 0
        newData[newIter] = feeds[iter]
        newIter++
      iter++
  return newData

#Update data section (Called from the onclick)
updateChart = (container,feeds,type) ->
  if container == "#VOSGraph"
    range = $('#VOS #timeToggle button.active').attr("id")
  else
    range = $('#message #timeToggle button.active').attr("id")
  line = d3.svg.line()
    .x((d) -> return x(parseDate(d.x)))
    .y((d) -> return y(d.y))
    .interpolate("linear")
  #Select the section we want to apply our changes to
  graph = d3.select(container)
  graph.selectAll("rect")
    .attr("fill", "#ffffff")
  switch type
    when "ratings"
      y.domain([1,5])
    when "sentiment"
      y.domain([1,5])
    when "satisfaction"
      y.domain([-100,100])
    when "sxi"
      y.domain([0,100])
  feeds = stripNoData(feeds)
  if feeds.length == 0
    graph.selectAll("rect")
      .attr("fill", "#f4f4f4")
    $('div#noDataAlpha.alpha').addClass('active')
    $('div#noDataAlpha button').removeClass('hidden')
    $('div#noDataAlpha h4').text("We're not seeing anything yet. Please contact us to add the message seal to your emails.")
    $('div#noDataAlpha a.btn.important').attr("href", "mailto:contact@subscribervoice.com?subject=Message Seal Request")
    $('#timeToggle button').removeClass('disabled')
    $('li.sub button.subSelector').removeClass('disabled')
    xDomain = []
    xDomain[0] = parseDate(moment(weekDate, "YYYYMMDDHHmmss").format("DD-MMM-YY"))
    switch range
      when "7d"
        xDomain[1] = parseDate(moment(weekDate, "YYYYMMDDHHmmss").add(8, "d").format("DD-MMM-YY"))
      when "6w"
        xDomain[1] = parseDate(moment(monthDate, "YYYYMMDDHHmmss").add(6, "w").format("DD-MMM-YY"))
      when "1y"
        xDomain[1] = parseDate(moment(yearDate, "YYYYMMDDHHmmss").add(1, "y").add(1, "M").format("DD-MMM-YY"))
    x.domain(xDomain)
    graph.select(".x.axis")
      .transition()
      .styleTween("opacity", -> return d3.interpolate(0,1))
      .duration(500)
      .attr("opacity", 1)
    if range == "6w"
      firstDate = moment(feeds[0].x,"DD-MMM-YY").format("ddd M/D")
      graph.select(".x.axis")
        .attr("transform", "translate(20,310)")
        .call(xAxisWeek)
      graph.select(".x.axis")
        .insert("g")
        .attr("class", "tick")
        .append("text")
        .attr("y", 9)
        .attr("x", 0)
        .attr("transform", "translate(-20,0)")
        .attr("dy", ".71em")
        .attr("fill", "#586874")
        .style("text-anchor", "middle")
        .style("display", "block")
        .html(firstDate)
    else if range == "1y"
      graph.select(".x.axis")
        .attr("transform", "translate(0,310)")
        .call(xAxisMonth)
    else
      graph.select(".x.axis")
        .attr("transform", "translate(0,310)")
        .call(xAxis)
    graph.select(".y.axis")
      .transition()
      .styleTween("opacity", -> return d3.interpolate(0,1))
      .duration(500)
      .attr("opacity", 1)
      .call(yAxis)
      .select("path")
      .style("stroke", "none")
    graph.selectAll("text")
      .attr("fill", "#586874")
      .style("display", "block")

    graph.selectAll("image").remove()

    if type == "sentiment" || type == "ratings" 
      graph.selectAll(".y text")
        .style("display", "none")  
    setTimeout( ->
      graph.select(".container")
        .select(".y.axis")
        .selectAll("g.tick line")
        .attr("x2", 820)
        .style("stroke", "#dbe0e2")
        .attr("transform", "translate(10,0)")
        .transition()
        .styleTween("opacity", -> return d3.interpolate(0,1))  

      if type == "ratings"
        graph.selectAll("image").remove()
        graph.selectAll(".y .tick").each( ->
          d3.select(this)
            .append("image")
            .attr("width", 28)
            .attr("height", 28)
            .attr("x", -34)
            .attr("y", -14)
            .attr("xlink:href", "/static/images/star.svg")
        )

      if type == "sentiment"
        graph.selectAll("image").remove()
        graph.selectAll(".y .tick").each( (ind) ->
          switch ind
            when 1
              face = "veryunhappy"
            when 2 
              face = "unhappy"
            when 3
              face = "neutral"
            when 4
              face = "happy"
            when 5
              face = "veryhappy"
          d3.select(this)
            .append("image")
            .attr("width", 28)
            .attr("height", 28)
            .attr("x", -34)
            .attr("y", -14)
            .attr("xlink:href", "/static/images/#{face}.svg")
        )

      graph.select(".container")
        .select(".x.axis")
        .selectAll("g.tick line")
        .attr("y2", -330)
        .style("stroke", "#dbe0e2")
        .transition()
        .styleTween("opacity", -> return d3.interpolate(0,1))
      if range == "year"
        graph.select(".container")
          .select(".x.axis")
          .selectAll("g.tick line")
          .attr("transform", "translate(-2,0)")
      $('#timeToggle button').removeClass('disabled')
      $('li.sub button').removeClass('disabled')
    , 1500)
    return
  #Scale the range of the data again 
  xDomain = []
  xDomain[0] = parseDate(feeds[0].x)
  switch range
    when "7d"
      xDomain[1] = parseDate(moment(feeds[0].x, "DD-MMM-YY").add(8, "d").format("DD-MMM-YY"))
    when "6w"
      xDomain[1] = parseDate(moment(feeds[0].x, "DD-MMM-YY").add(6, "w").format("DD-MMM-YY"))
    when "1y"
      xDomain[1] = parseDate(moment(feeds[0].x, "DD-MMM-YY").add(1, "y").add(1, "M").format("DD-MMM-YY"))

  x.domain(xDomain)

  setTimeout( ->
    graph.select(".container")
      .append("path")
      .attr("class", "line")
      .attr("stroke", "#6f90ab")
      .attr("stroke-width", 5)
      .attr("fill", "none")
      .attr("opacity", 0)
      .attr("d", line(feeds))
      .transition()
      .styleTween("opacity", -> return d3.interpolate(0,1))
      .duration(1500)
  , 1500)
  #Make the changes
  graph.select(".x.axis")
    .transition()
    .styleTween("opacity", -> return d3.interpolate(0,1))
    .duration(500)
    .attr("opacity", 1)
  if range == "6w"
    firstDate = moment(feeds[0].x,"DD-MMM-YY").format("ddd M/D")
    graph.select(".x.axis")
      .attr("transform", "translate(20,310)")
      .call(xAxisWeek)
    graph.select(".x.axis")
      .insert("g")
      .attr("class", "tick")
      .append("text")
      .attr("y", 9)
      .attr("x", 0)
      .attr("transform", "translate(-20,0)")
      .attr("dy", ".71em")
      .attr("fill", "#586874")
      .style("text-anchor", "middle")
      .style("display", "block")
      .html(firstDate)
  else if range == "1y"
    graph.select(".x.axis")
      .attr("transform", "translate(0,310)")
      .call(xAxisMonth)
  else
    graph.select(".x.axis")
      .attr("transform", "translate(0,310)")
      .call(xAxis)

  graph.select(".y.axis")
    .transition()
    .styleTween("opacity", -> return d3.interpolate(0,1))
    .duration(500)
    .attr("opacity", 1)
    .call(yAxis)
    .select("path")
    .style("stroke", "none")

  graph.selectAll("text")
    .attr("fill", "#586874")
    .style("display", "block")

  graph.selectAll(".y image")
    .remove()

  if type == "sentiment" || type == "ratings" 
    graph.selectAll(".y text")
      .style("display", "none")   
  
  setTimeout( ->
    circleGroup = graph.select(".container").append("g")
      .attr("class", "circleGroup")
      .attr("opacity", 0)
    circles = circleGroup.selectAll("circle")
      .data(feeds)
      .enter()  
      .append("circle")
      .attr("r", 8)
      .attr("style", "fill: #ffffff; stroke: #6f90ab; stroke-width: 3;")
      .attr("cx", (d) -> return x(parseDate(d.x)))
      .attr("cy", (d) -> return y(d.y))
      .attr("value", (d) -> return d.responses)
      .on("mouseover", circleMouseOver)
      .on("mouseout", circleMouseOut)
    circleGroup
      .transition()
      .styleTween("opacity", -> return d3.interpolate(0,1))
      .duration(1500)
    graph.select(".container")
      .select(".y.axis")
      .selectAll("g.tick line")
      .attr("x2", 820)
      .style("stroke", "#dbe0e2")
      .attr("transform", "translate(10,0)")
      .transition()
      .styleTween("opacity", -> return d3.interpolate(0,1))  

    if type == "ratings"
      graph.selectAll("image").remove()
      graph.selectAll(".y .tick").each( ->
        d3.select(this)
          .append("image")
          .attr("width", 28)
          .attr("height", 28)
          .attr("x", -34)
          .attr("y", -14)
          .attr("xlink:href", "/static/images/star.svg")
      )

    if type == "sentiment"
      graph.selectAll("image").remove()
      graph.selectAll(".y .tick").each( (ind) ->
        switch ind
          when 1
            face = "veryunhappy"
          when 2 
            face = "unhappy"
          when 3
            face = "neutral"
          when 4
            face = "happy"
          when 5
            face = "veryhappy"
        d3.select(this)
          .append("image")
          .attr("width", 28)
          .attr("height", 28)
          .attr("x", -34)
          .attr("y", -14)
          .attr("xlink:href", "/static/images/#{face}.svg")
      )

    graph.select(".container")
      .select(".x.axis")
      .selectAll("g.tick line")
      .attr("y2", -330)
      .style("stroke", "#dbe0e2")
      .transition()
      .styleTween("opacity", -> return d3.interpolate(0,1))
    if range == "year"
      graph.select(".container")
        .select(".x.axis")
        .selectAll("g.tick line")
        .attr("transform", "translate(-2,0)")
    $('#timeToggle button').removeClass('disabled')
    $('li.sub button').removeClass('disabled')
  , 1500)

circleMouseOut = ->
  circle = d3.select(this)
  circle.transition().duration(500).attr("r", 8)
  $(".toolTip").addClass("fade").removeClass("visible")

circleMouseOver = (container) ->
  circle = d3.select(this)
  circle.transition().duration(500).attr("r", 11)
  circleData = circle.data()[0]
  left = x(parseDate(circleData.x))+33
  top = y(circleData.y)+110
  $("#message .toolTip").removeClass('sxi')
  $("#message .toolTip .tip").removeClass('sxi')
  dataStr = circleData.y.toString()
  decimals = dataStr.length - dataStr.lastIndexOf('.') - 1
  if type == "satisfaction" or type == "sxi"
    value = Math.round(circleData.y)
  else if decimals >= 2
    value = parseFloat(circleData.y).toFixed(1)
  else 
    value = circleData.y
  if type == 'sxi'
    timeRange = $('#message #timeToggle button.active').attr('id')
  else
    timeRange = $('#VOS #timeToggle button.active').attr('id')
  if timeRange == '1y'
    dateStr = moment(circleData.x, "DD-MMM-YY").format('MMMM')
  else
    dateStr = moment(circleData.x, "DD-MMM-YY").format('ddd MMMM D')
  if type == 'sxi'
    if value > 50 then direction = "up"
    if value <= 50 
      direction = "down"
      top -= 221
    $("#message .toolTip").addClass('sxi')
    $("#message .toolTip .tip").addClass('sxi')
    $("#message .toolTip.#{direction} .dataValue p").html("""
		<p>
			<div style='text-align: left'>#{dateStr}:</div>
			<span class="value">#{value}</span>
      <span>Sentiment: #{ switch
                        when circleData.extra.review == -1 then "No data"
                        when circleData.extra.review < ((1.25+6.25) / 2.0) then "Very Unhappy"
                        when circleData.extra.review < ((6.25+12.5) / 2.0) then "Unhappy"
                        when circleData.extra.review < ((12.5+18.75) / 2.0) then "Neutral"
                        when circleData.extra.review < ((18.75+25) / 2.0) then "Happy"
                        else "Very Happy"       
                    }</span>
			<span>Satisfaction: #{ switch
                        when circleData.extra.score == -1 then "No data"
                        else ((parseFloat(circleData.extra.score) - 1.25) / 2.375).toFixed(1)
                    }</span>
      <span>Value: #{ switch
                        when circleData.extra.value == -1 then "No data"
                        when circleData.extra.value < ((0.75+3) / 2.0) then "1 star"
                        when circleData.extra.value < ((3+7.5) / 2.0) then "2 stars"
                        when circleData.extra.value < ((7.5+11.25) / 2.0) then "3 stars"
                        when circleData.extra.value < ((11.25+15) / 2.0) then "4 stars"
                        else "5 stars"
                    }</span>
      <span>Frequency: #{ switch
                        when circleData.extra.frequency == -1 then "No data"
                        when circleData.extra.frequency < ((1+5) / 2.0) then "1 star"
                        when circleData.extra.frequency < ((5+10) / 2.0) then "2 stars"
                        when circleData.extra.frequency < ((10+15) / 2.0) then "3 stars"
                        when circleData.extra.frequency < ((15+20) / 2.0) then "4 stars"
                        else "5 stars"
                    }</span>
      <span>Relevancy: #{ switch
                        when circleData.extra.relevancy == -1 then "No data"
                        when circleData.extra.relevancy < ((0.5+2.5) / 2.0) then "1 star"
                        when circleData.extra.relevancy < ((2.5+5) / 2.0) then "2 stars"
                        when circleData.extra.relevancy < ((5+7.5) / 2.0) then "3 stars"
                        when circleData.extra.relevancy < ((7.5+10) / 2.0) then "4 stars"
                        else "5 stars"
                    }</span>
      <span>Design: #{ switch
                        when circleData.extra.design == -1 then "No data"
                        when circleData.extra.design < ((0.25+1.25) / 2.0) then "1 star"
                        when circleData.extra.design < ((1.25+2.5) / 2.0) then "2 stars"
                        when circleData.extra.design < ((2.5+3.75) / 2.0) then "3 stars"
                        when circleData.extra.design < ((3.75+5) / 2.0) then "4 stars"
                        else "5 stars"
                    }</span>
		</p>
    """)
    $("#message .toolTip.#{direction}").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
    $("#message .toolTip.#{direction}").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
  else if type == 'ratings'
    if value > 3.5 then direction = "up"
    if value <= 3.5 
      direction = "down"
      top -= 207
    responses = circle.attr("value")
    $('#VOS .toolTip').removeClass('satisfaction')
    $("#VOS .toolTip.#{direction} .dataValue p").html('<span class="date">' + dateStr + '</span><p><span class="value">' + value + '</span><span>' + circleData.extra[0] + '% 1 Star</span><span>' + circleData.extra[1] + '% 2 Stars</span><span>' + circleData.extra[2] + '% 3 Stars</span><span>' + circleData.extra[3] + '% 4 Stars</span><span>' + circleData.extra[4] + '% 5 Stars</span>')
    $("#VOS .toolTip.#{direction}").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
  else if type == 'sentiment'
    if value > 3.5 then direction = "up"
    if value <= 3.5 
      direction = "down"
      top -= 207
    responses = circle.attr("value")
    $('#VOS .toolTip').removeClass('satisfaction')
    $("#VOS .toolTip.#{direction} .dataValue p").html('<span class="date">' + dateStr + '</span><p><span class="value">' + value + '</span><span>' + circleData.extra[0] + '% Very Unhappy</span><span>' + circleData.extra[1] + '% Unhappy</span><span>' + circleData.extra[2] + '% Neutral</span><span>' + circleData.extra[3] + '% Happy</span><span>' + circleData.extra[4] + '% Very Happy</span>')
    $("#VOS .toolTip.#{direction}").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
  else if type == 'satisfaction'
    responses = circle.attr("value")
    promotersRatio = 0
    passivesRatio = 0
    detractorsRatio = 0
    if value > 0 then direction = "up"
    if value <= 0
      direction = "down"
      top -= 177
    if responses != 0
      if circleData.promoters != 0
        promotersRatio = Math.round((circleData.promoters / responses) * 100)
      if circleData.passives != 0
        passivesRatio = Math.round((circleData.passives / responses) * 100)
      if circleData.detractors != 0
        detractorsRatio = Math.round((circleData.detractors / responses) * 100)
    $('#VOS .toolTip').addClass('satisfaction')
    $("#VOS .toolTip.#{direction} .dataValue p").html('<span class="date">' + dateStr + '</span><p><span class="value">' + value + '</span><span>' + promotersRatio + '% promoters</span><span>' + passivesRatio + '% passives</span><span>' + detractorsRatio + '% detractors</span>')
    $("#VOS .toolTip.#{direction}").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
    
barMouseOver = ->
  if $('#unsub li.sub.active').length == 0
    bar = d3.select(this)
    bar.classed('active', true)
    barData = bar.attr("value")
    left = parseInt(bar.attr("x")) + 80
    top = parseInt(bar.attr("y"))
    value = Math.round(barData)
    if value != 0
      if value < 50
        top -= 47 
        $("#unsub .toolTip.down .dataValue p").html('<span class="value">' + value + '%</span><span>of surveys included "' + bar.attr("id") + '" as a reason for unsubscribing</span>')
        $("#unsub .toolTip.down").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
      else 
        top += 100
        $("#unsub .toolTip.up .dataValue p").html('<span class="value">' + value + '%</span><span>of surveys included "' + bar.attr("id") + '" as a reason for unsubscribing</span>')
        $("#unsub .toolTip.up").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")

barMouseOut = ->
  if $('#unsub li.sub.active').length == 0
    bar = d3.select(this)
    bar.classed('active', true)
    $("#unsub .toolTip").addClass("fade").removeClass("visible")

barClick = ->
  $('.toolTip').unbind("mouseover")
  bar = d3.select(this)
  thisID = bar.attr("id")
  d3.selectAll("rect.bar").on("mouseover", null)
  if !bar.classed('active')
    $('#unsub li.sub').removeClass('active')
    $("#unsub .toolTip").addClass("fade").removeClass("visible")
    d3.selectAll("rect.bar").classed('active', false)
  $("#unsub li##{thisID}.sub").addClass('active')
  bar.classed('active', true)
  barData = bar.attr("value")
  left = parseInt(bar.attr("x")) + 80
  top = parseInt(bar.attr("y"))
  value = Math.round(barData)
  if value != 0
    if value < 50
        top -= 47
        setTimeout(->  
          $("#unsub .toolTip.down .dataValue p").html('<span class="value">' + value + '%</span><span>of surveys included "' + bar.attr("id") + '" as a reason for unsubscribing</span>')
          $("#unsub .toolTip.down").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
        ,300) 
       else 
        top += 100
        setTimeout(->  
          $("#unsub .toolTip.up .dataValue p").html('<span class="value">' + value + '%</span><span>of surveys included "' + bar.attr("id") + '" as a reason for unsubscribing</span>')
          $("#unsub .toolTip.up").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
        ,300)

toolTipShow = ->
  bar = d3.select(this)
  value = Math.round(bar.attr("value"))
  if value != 0
    if value < 50
        top -= 47 
        $("#unsub .toolTip.down .dataValue p").html('<span class="value">' + value + '%</span><span>of surveys included "' + bar.attr("id") + '" as a reason for unsubscribing</span>')
        $("#unsub .toolTip.down").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
      else 
        top += 100
        $("#unsub .toolTip.up .dataValue p").html('<span>% of surveys that included "' + bar.attr("id") + '" as a reason for unsubscrbing:</span>' + value + '%')
        $("#unsub .toolTip.up").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")

toolTipBind = ->
  $('.toolTip').mouseover ->
    $(this).addClass('show')

toolTipBind()

$('.toolTip').mouseout ->
  $(this).removeClass('show')

$('#unsub li.sub').click ->
  if $(this).find('button').hasClass('btn-disabled')
    return false
  if !$(this).hasClass('active')
    $('#unsub li.sub').removeClass('active')
    $(this).addClass('active')
    thisID = $(this).attr("id")
    bar = d3.select("rect##{thisID}")
    if !bar.classed('active')
      $("#unsub .toolTip").addClass("fade").removeClass("visible")
      d3.selectAll("rect.bar").classed('active', false)
    bar.classed('active', true)
    barData = bar.attr("value")
    left = parseInt(bar.attr("x")) + 80
    top = parseInt(bar.attr("y"))
    value = Math.round(barData)
    if value != 0
      if value < 50
        top -= 47
        setTimeout(->  
          $("#unsub .toolTip.down .dataValue p").html('<span class="value">' + value + '%</span><span>of surveys included "' + bar.attr("id") + '" as a reason for unsubscribing</span>')
          $("#unsub .toolTip.down").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
        ,300) 
      else
        top += 100
        setTimeout(->  
          $("#unsub .toolTip.up .dataValue p").html('<span class="value">' + value + '%</span><span>of surveys included "' + bar.attr("id") + '" as a reason for unsubscribing</span>')
          $("#unsub .toolTip.up").css("left", "#{left}px").css("top", "#{top}px").addClass("visible").removeClass("fade")
        ,300)
  else
    toolTipBind()
    d3.selectAll("rect.bar").on("mouseover", barMouseOver)
    $(this).removeClass("active")
    $("#unsub .toolTip").addClass("fade").removeClass("visible")

interpolateSankey = (points) ->
  x0 = points[0][0]
  y0 = points[0][1] 
  path = [x0, ",", y0]
  i = 0
  n = points.length
  while (++i < n) 
    x1 = points[i][0]
    y1 = points[i][1]
    x2 = (x0 + x1) / 2
    path.push("C", x2, ",", y0, " ", x2, ",", y1, " ", x1, ",", y1)
    x0 = x1
    y0 = y1

  return path.join("")

setSXIBreakdown = (category, data) ->
  if category == "Satisfaction"
    promoters = 0
    passives = 0
    detractors = 0
    if data.score.total
      if data.score.score1 then detractors += data.score.score1
      if data.score.score2 then detractors += data.score.score2
      if data.score.score3 then detractors += data.score.score3
      if data.score.score4 then detractors += data.score.score4
      if data.score.score5 then detractors += data.score.score5
      if data.score.score6 then detractors += data.score.score6
      if data.score.score7 then passives += data.score.score7
      if data.score.score8 then passives += data.score.score8
      if data.score.score9 then promoters += data.score.score9
      if data.score.score10 then promoters += data.score.score10
      promotersRatio = Math.round((promoters / data.score.total) * 100)
      passivesRatio = Math.round((passives / data.score.total) * 100)
      detractorsRatio = Math.round((detractors / data.score.total) * 100)
      $('ul.sxiBreakdown li#Promoters span').text(promotersRatio + '%')
      $('ul.sxiBreakdown li#Passives span').text(passivesRatio + '%')
      $('ul.sxiBreakdown li#Detractors span').text(detractorsRatio + '%')
    else
      $('ul.sxiBreakdown li span').text('No data')

  else
    stat1 = 0
    stat2 = 0
    stat3 = 0
    stat4 = 0
    stat5 = 0
    ratios = []
    switch category
      when "Sentiment"
        total = data.review.total
        if total != 0
          if data.review.review1 then stat1 += data.review.review1
          if data.review.review2 then stat2 += data.review.review2
          if data.review.review3 then stat3 += data.review.review3
          if data.review.review4 then stat4 += data.review.review4
          if data.review.review5 then stat5 += data.review.review5
      when "Value"
        total = data.value.total
        if total != 0
          if data.value.value1 then stat1 += data.value.value1
          if data.value.value2 then stat2 += data.value.value2
          if data.value.value3 then stat3 += data.value.value3
          if data.value.value4 then stat4 += data.value.value4
          if data.value.value5 then stat5 += data.value.value5
      when "Relevancy"
        total = data.relevancy.total
        if total != 0
          if data.relevancy.relevancy1 then stat1 += data.relevancy.relevancy1
          if data.relevancy.relevancy2 then stat2 += data.relevancy.relevancy2
          if data.relevancy.relevancy3 then stat3 += data.relevancy.relevancy3
          if data.relevancy.relevancy4 then stat4 += data.relevancy.relevancy4
          if data.relevancy.relevancy5 then stat5 += data.relevancy.relevancy5
      when "Design"
        total = data.design.total
        if total != 0
          if data.design.design1 then stat1 += data.design.design1
          if data.design.design2 then stat2 += data.design.design2
          if data.design.design3 then stat3 += data.design.design3
          if data.design.design4 then stat4 += data.design.design4
          if data.design.design5 then stat5 += data.design.design5
      when "Frequency"
        total = data.frequency.total
        if total != 0
          if data.frequency.frequency1 then stat1 += data.frequency.frequency1
          if data.frequency.frequency2 then stat2 += data.frequency.frequency2
          if data.frequency.frequency3 then stat3 += data.frequency.frequency3
          if data.frequency.frequency4 then stat4 += data.frequency.frequency4
          if data.frequency.frequency5 then stat5 += data.frequency.frequency5
    ratios.push(Math.round((stat5 / total) * 100))
    ratios.push(Math.round((stat4 / total) * 100))
    ratios.push(Math.round((stat3 / total) * 100))
    ratios.push(Math.round((stat2 / total) * 100))
    ratios.push(Math.round((stat1 / total) * 100))
    iter = 0   
    $("li.#{category}.sub .sxiBreakdown li").each ->
      if total
        $(this).find('span').text(ratios[iter] + '%')
      else
        $(this).find('span').text('No data')
      iter++  
  
getSXIBreakdown = (category) ->
  period = $('#VOS #timeToggle button.active').attr("id")
  if category == "sentiment" then category = "Sentiment"
  else if category == "frequencyR" then category = "Frequency"
  else category = category.capitalize()
  $.get("breakdown-json/?period=" + period)
  .done((data) -> 
      setSXIBreakdown(category, data)
  )

npsCalculate = (item) ->
  total = item.total
  promoters = item.promoters
  detractors = item.detractors
  return parseFloat(((promoters / total)*100) - ((detractors / total)*100))

#Update Graph Data
#PARAM: container - DOM #ID
#PARAM: feeds - list of date, value pairs
updateGraph = (container,feeds) ->
  #Parse the data to average by date    
  line = d3.svg.line()
    .x((d) -> return x(parseDate(d.x)))
    .y((d) -> return y(d.y))
    .interpolate("linear")

  x.domain(d3.extent(feeds, (d) -> return parseDate(d.x)))
  y.domain(d3.extent(feeds, (d) -> return d.y))

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0,430)")
    .call(xAxis)

  svg.append("g")
    .attr("class", "y axis")
    .attr("stroke", "none" )
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")

  svg.append("path")
    .datum(feeds)
    .attr("class", "line")
    .attr("stroke", "#6f90ab")
    .attr("stroke-width", 5)
    .attr("fill", "none")
    .attr("d", line)

#Returns Formated Date Objects for D3
reverseParse = (tempDate) ->
  month = new Array()
  month[0] = "Jan"
  month[1] = "Feb"
  month[2] = "Mar"
  month[3] = "Apr"
  month[4] = "May"
  month[5] = "Jun"
  month[6] = "Jul"
  month[7] = "Aug"
  month[8] = "Sep"
  month[9] = "Oct"
  month[10] = "Nov"
  month[11] = "Dec"

  tempDate = new Date(tempDate)

  newDay1 = tempDate.getUTCDate()
  newMonth1 = month[tempDate.getUTCMonth()]
  newYear1 = tempDate.getUTCFullYear() % 100

  reverseDate = newDay1 + "-" + newMonth1 + "-" + newYear1
  return reverseDate

calculateEngagements = (items) ->
  tempEngagements = 0
  tempChurn = 0

  currentData = new Array()
  currentData = items
    
  for thisItem in items
      
    #Rating Type
    if (thisItem.ratings) 

      numRatings = 0

      thisRelevancy = thisItem.ratings.relevancy #relevancy
      thisFrequency = thisItem.ratings.frequency #frequency
      thisDesign = thisItem.ratings.design #design
      thisValue = thisItem.ratings.value #value

      tempRelevancyObj = {
        'y' : thisItem.ratings.relevancy,
        'x': reverseParse(thisItem.created_at),
      }

      ratingItemsRelevancy.push(tempRelevancyObj)

      tempDesignObj = {
        'y' : thisItem.ratings.design,
        'x': reverseParse(thisItem.created_at),
      }

      ratingItemsDesign.push(tempDesignObj)

      tempValueObj = {
        'y' : thisItem.ratings.value,
        'x': reverseParse(thisItem.created_at),
      }

      ratingItemsValue.push(tempValueObj)

      tempFrequencyObj = {
        'y' : thisItem.ratings.frequency,
        'x': reverseParse(thisItem.created_at),
      }

      ratingItemsFrequency.push(tempFrequencyObj)

      if (thisRelevancy != 0 ) 
        numRatings++
    
      if (thisDesign != 0 ) 
        numRatings++

      if (thisValue != 0 ) 
        numRatings++

      if (thisFrequency != 0 )
        numRatings++

      ratingItems.push(thisItem.ratings)

      tempEngagements += numRatings

    #REVIEW Type         
    if (thisItem.review)
      tempReviewObj = {
        'y' : thisItem.review.review,
        'x': reverseParse(thisItem.created_at),
      }

      reviewItems.push(tempReviewObj)

      tempEngagements += 1

    #NPS Score Type
    if (thisItem.net_promoter_score) 
      tempNPSObj = {
        'y' : thisItem.net_promoter_score.score,
        'x' : reverseParse(thisItem.net_promoter_score.date),
      }

      npsItems.push(tempNPSObj)

      tempEngagements += 1
    
  if tempEngagements > 9999
    $('h2#engagement').find("span").text( (Math.round(tempEngagements / 100) / 10) + "K" )
  else
    $('h2#engagement').find("span").text( tempEngagements || '-' )


#DEFAULT CALL BEFORE FILTERING

 #getFeedItemList(limit,start)

 #Gets a list of all feed items with a limit parameter and a counter: start to track which feed item
 #we are currently at. This way we can implement ajax scroll to load

#ENGAGEMENTS SECTION 

#All Engagement Items
#Returns a list of response items
getItemList = (date) -> 
  $("h2#engagement span").html('<i class="fa fa-spinner fa-spin"></i>')
  $.get("all-items/?start=" + date + "&offset=" + start + "&limit=" + limit)
  .done((data) -> 
      #Calculate Number of:
      #  Engagements
      #  Add Data to Sub Lists
      calculateEngagements(data)
  )
  .always((e) ->

    setTimeout(-> 
      updatePos()
    ,10)
  )

# GET LIST OF RATINGS 
getRatingList = (ratingType, dateRange) ->
  $('#timeToggle button').addClass('disabled')
  $('li.sub button').addClass('disabled')
  resetLine("VOS")
  $.get("ratings-json/?period=" + dateRange)
  .done( (data) ->
    ratingItemsValue = []
    ratingItemsRelevancy = []
    ratingItemsFrequency = []
    ratingItemsDesign = []
    ratingItemsOverall = []

    iter = 0
    while (data.length > iter) 
      tempD = reverseParse(data[iter].date)
      tempValue = data[iter].value
      tempRelevancy = data[iter].relevancy
      tempFrequency = data[iter].frequency
      tempDesign = data[iter].design
      tempValueExtra = []
      tempRelevancyExtra = []
      tempFrequencyExtra = []
      tempDesignExtra = []
      tempOverallExtra = []
      #console.log("Data Overall - RATING RATING RATING: " + tempRelevancy)

      #calculate average for data point
      total = 0
      tempOverall = tempValue.avg + tempRelevancy.avg + tempFrequency.avg + tempDesign.avg
      if tempValue.avg != 0
        total++
        tempValueTotal = tempValue.star1 + tempValue.star2 + tempValue.star3 + tempValue.star4 + tempValue.star5
        tempValueExtra.push(Math.round((tempValue.star1 / tempValueTotal) * 100))
        tempValueExtra.push(Math.round((tempValue.star2 / tempValueTotal) * 100))
        tempValueExtra.push(Math.round((tempValue.star3 / tempValueTotal) * 100))
        tempValueExtra.push(Math.round((tempValue.star4 / tempValueTotal) * 100))
        tempValueExtra.push(Math.round((tempValue.star5 / tempValueTotal) * 100))
      if tempRelevancy.avg != 0
        total++
        tempRelevancyTotal = tempRelevancy.star1 + tempRelevancy.star2 + tempRelevancy.star3 + tempRelevancy.star4 + tempRelevancy.star5
        tempRelevancyExtra.push(Math.round((tempRelevancy.star1 / tempRelevancyTotal) * 100))
        tempRelevancyExtra.push(Math.round((tempRelevancy.star2 / tempRelevancyTotal) * 100))
        tempRelevancyExtra.push(Math.round((tempRelevancy.star3 / tempRelevancyTotal) * 100))
        tempRelevancyExtra.push(Math.round((tempRelevancy.star4 / tempRelevancyTotal) * 100))
        tempRelevancyExtra.push(Math.round((tempRelevancy.star5 / tempRelevancyTotal) * 100))
      if tempFrequency.avg != 0
        total++
        tempFrequencyTotal = tempFrequency.star1 + tempFrequency.star2 + tempFrequency.star3 + tempFrequency.star4 + tempFrequency.star5
        tempFrequencyExtra.push(Math.round((tempFrequency.star1 / tempFrequencyTotal) * 100))
        tempFrequencyExtra.push(Math.round((tempFrequency.star2 / tempFrequencyTotal) * 100))
        tempFrequencyExtra.push(Math.round((tempFrequency.star3 / tempFrequencyTotal) * 100))
        tempFrequencyExtra.push(Math.round((tempFrequency.star4 / tempFrequencyTotal) * 100))
        tempFrequencyExtra.push(Math.round((tempFrequency.star5 / tempFrequencyTotal) * 100))
      if tempDesign.avg != 0
        total++
        tempDesignTotal = tempDesign.star1 + tempDesign.star2 + tempDesign.star3 + tempDesign.star4 + tempDesign.star5
        tempDesignExtra.push(Math.round((tempDesign.star1 / tempDesignTotal) * 100))
        tempDesignExtra.push(Math.round((tempDesign.star2 / tempDesignTotal) * 100))
        tempDesignExtra.push(Math.round((tempDesign.star3 / tempDesignTotal) * 100))
        tempDesignExtra.push(Math.round((tempDesign.star4 / tempDesignTotal) * 100))
        tempDesignExtra.push(Math.round((tempDesign.star5 / tempDesignTotal) * 100))

      if total != 0
        tempOverallTotal = 0
        if tempValueTotal then tempOverallTotal += tempValueTotal 
        if tempRelevancyTotal then tempOverallTotal += tempRelevancyTotal 
        if tempFrequencyTotal then tempOverallTotal += tempFrequencyTotal 
        if tempDesignTotal then tempOverallTotal += tempDesignTotal
        tempOverall = tempOverall / total
        tempOverallExtra.push(Math.round(((tempValue.star1+tempRelevancy.star1+tempFrequency.star1+tempDesign.star1) / tempOverallTotal) * 100))
        tempOverallExtra.push(Math.round(((tempValue.star2+tempRelevancy.star2+tempFrequency.star2+tempDesign.star2) / tempOverallTotal) * 100))
        tempOverallExtra.push(Math.round(((tempValue.star3+tempRelevancy.star3+tempFrequency.star3+tempDesign.star3) / tempOverallTotal) * 100))
        tempOverallExtra.push(Math.round(((tempValue.star4+tempRelevancy.star4+tempFrequency.star4+tempDesign.star4) / tempOverallTotal) * 100))
        tempOverallExtra.push(Math.round(((tempValue.star5+tempRelevancy.star5+tempFrequency.star5+tempDesign.star5) / tempOverallTotal) * 100))

      tempObj1 = {
        'y' : tempValue.avg,
        'x' : tempD,
        'extra' : tempValueExtra,
        'responses' : data[iter].responses,
      }
      tempObj2 = {
        'y' : tempRelevancy.avg,
        'x' : tempD,
        'extra' : tempRelevancyExtra,
        'responses' : data[iter].responses,
      }
      tempObj3 = {
        'y' : tempFrequency.avg,
        'x' : tempD,
        'extra' : tempFrequencyExtra,
        'responses' : data[iter].responses,
      }
      tempObj4 = {
        'y' : tempDesign.avg,
        'x' : tempD,
        'extra' : tempDesignExtra,
        'responses' : data[iter].responses,
      }
      tempObj5 = {
        'y' : tempOverall,
        'x' : tempD,
        'extra' : tempOverallExtra,
        'responses' : data[iter].responses,
      }                              

      ratingItemsValue.push(tempObj1)
      ratingItemsRelevancy.push(tempObj2)
      ratingItemsFrequency.push(tempObj3)
      ratingItemsDesign.push(tempObj4)
      ratingItemsOverall.push(tempObj5)

      iter++
  )
  .always( ->
    #console.log("<- Returning Rating Items: " + ratingType)
    #console.log(ratingType)

    #refreshGraph("#VOSGraph")
    type = "ratings"
    switch (ratingType)
      when "all"
        updateChart("#VOSGraph",ratingItemsOverall,type)
      when "value"
        updateChart("#VOSGraph",ratingItemsValue,type)
      when "relevancy"
        updateChart("#VOSGraph",ratingItemsRelevancy,type)
      when "frequency"
        updateChart("#VOSGraph",ratingItemsFrequency,type)
      when "design"
        updateChart("#VOSGraph",ratingItemsDesign,type)
    setTimeout(-> 
      updatePos()
    ,10)
  )


# GET LIST OF REVIEWS 
getReviewList = (dateRange) ->
  $('#timeToggle button').addClass('disabled')
  $('li.sub button').addClass('disabled')
  resetLine("VOS")
  $.get("review-json?period=" + dateRange) 
  .done( (data) ->
    reviewItems = []
    iter = 0
    while(data.length > iter)
      tempReviewExtra = []
      tempReviewExtra.push(Math.round((data[iter].review.face1 / data[iter].responses) * 100))
      tempReviewExtra.push(Math.round((data[iter].review.face2 / data[iter].responses) * 100))
      tempReviewExtra.push(Math.round((data[iter].review.face3 / data[iter].responses) * 100))
      tempReviewExtra.push(Math.round((data[iter].review.face4 / data[iter].responses) * 100))
      tempReviewExtra.push(Math.round((data[iter].review.face5 / data[iter].responses) * 100))
      tempObj = {
        'y' : data[iter].review.avg,
        'x' : reverseParse(data[iter].date),
        'extra' : tempReviewExtra,
        'responses' : data[iter].responses,
      }
      reviewItems.push(tempObj)
      iter++
  )
  .always( ->
    #console.log("<- Returning Review Items: " + reviewItems)
    #console.log(reviewItems)

    #refreshGraph("#VOSGraph")
    type = "sentiment"
    updateChart("#VOSGraph",reviewItems,type)
    setTimeout(-> 
      updatePos()
    ,10)

  )

#GET LIST OF NPS Items 
getNPSList = (dateRange) ->
  $('#timeToggle button').addClass('disabled')
  $('li.sub button').addClass('disabled')
  resetLine("VOS")
  $.get("satisfaction-json/?period=" + dateRange)
  .done((data) ->
    #console.log("<- Survey Items")
    #console.log("Original Data: " + data)
    #console.log("Length: " + data.length)
    npsItems = []
    iter = 0
    dataNotSet = true
    lastObj = []
    tempNPSObj = []
    while (data.length > iter) 
      if data[iter].responses == 0
        data[iter].nps = "noData"
      tempNPSObj[iter] = {
        'y' : data[iter].nps,
        'x' : reverseParse(data[iter].date),
        'promoters' : data[iter].promoters,
        'detractors' : data[iter].detractors,
        'passives' : data[iter].passives,
        'responses' : data[iter].responses,
        'dataNotSet' : dataNotSet,
      }
      npsItems.push(tempNPSObj[iter])
      iter++    
    
  )
  .always( ->
    #refreshGraph("#VOSGraph")
    type = "satisfaction"
    updateChart("#VOSGraph",npsItems,type)
    setTimeout(-> 
      updatePos()
    ,10)
  )

# GET LIST OF REVIEWS 
getSXIList = (dateRange) ->
  $('#timeToggle button').addClass('disabled')
  resetLine("SXI")
  $("h2#message span").html('<i class="fa fa-spinner fa-spin"></i>')
  average = 0
  $('#timeToggle button').addClass('disabled')
  $.get("sxi-json/?period=" + dateRange) 
  .done( (data) ->
    sxiItems = []
    iter = 0
    setIter = 0
    dataNotSet = true
    while(data.length > iter) 
      if data[iter].sxi < 0
        iter++
        continue
      else if data[iter].sxi > 0 and dataNotSet
        dataNotSet = false
        setIter = 1
      else if data[iter].sxi > 0
        setIter++
      tempObj = {
        'y' : data[iter].sxi,
        'x' : reverseParse(data[iter].date),
        'extra': data[iter].extra
      }
      sxiItems.push(tempObj)
      average += data[iter].sxi
      iter++
    average = Math.round(average / setIter) || '-'
    $('h2#message span').text(average)
  )
  .always( ->
    #console.log("<- Returning Review Items: " + reviewItems)
    #console.log(reviewItems)

    #refreshGraph("#VOSGraph")
    type = "sxi"
    updateChart("#messageGraph",sxiItems,type)
  )

#get just the average
getSXIAverage = (dateRange) ->
  $("h2#message span").html('<i class="fa fa-spinner fa-spin"></i>')
  average = 0
  $.get("sxi-json/?period=" + dateRange) 
  .done( (data) ->
    sxiItems = []
    iter = 0
    setIter = 0
    dataNotSet = true
    while(data.length > iter) 
      if data[iter].sxi > 0 and dataNotSet
        dataNotSet = false
        setIter = 1
      else if !dataNotSet
        setIter++
      tempObj = {
        'y' : data[iter].sxi,
        'x' : reverseParse(data[iter].date),
      }
      sxiItems.push(tempObj)
      average += data[iter].sxi
      iter++
    average = Math.round(average / setIter)
    $('h2#message span').text(average)
  )
  .always( ->
    #console.log("<- Returning Review Items: " + reviewItems)
    #console.log(reviewItems)

    #refreshGraph("#VOSGraph")
    setTimeout(-> 
      updatePos()
    ,10)
  )

getChurnList = (dateRange, updateGraph) ->
  $('#timeToggle button').addClass('disabled')
  $.get("churn-json/")
  .done((data) ->
    #console.log("<- Survey Items")
    #console.log("Original Data: " + data)
    #console.log("Length: " + data.length)
    switch dateRange
      when "7d"
        surveyItems = data.seven_days
      when "6w"
        surveyItems = data.six_weeks
      when "1y"
        surveyItems = data.one_year
    $("h2#unsub span").html('<i class="fa fa-spinner fa-spin"></i>')
    if surveyItems.total > 9999
      $('h2#unsub').find("span").text( surveyItems.total / 1000 + "K" )
    else
      $('h2#unsub').find("span").text( surveyItems.total || '-' )
  )
  .always( ->
    if updateGraph
      setupChurnGraph(surveyItems)
  )

#Engagements
$('h2#engagement').click (e) ->
  $('li.sub button').prop('disabled', false).removeClass('btn-disabled')
  $('.alpha').removeClass('active')
  hardResetLine("VOS")
  #console.log("Clicked Engagements")
  $("h2").removeClass("active")
  $(this).addClass("active")
  $('.dash').hide().removeClass('active')
  $('#VOS').show().addClass('active')
  $("ul.subBreakdown li").removeClass("active")
  $('ul.subBreakdown').hide()
  updatePos()
  $("#VOS li.sub").removeClass("active")
  $("#VOS li.sub#sentiment").addClass("active")
  getSXIBreakdown($('#VOS li.sub.active').attr('id'))
  timeRange = $("div#VOS #timeToggle button.active").attr("name")
  $("div#unsub #timeToggle").removeAttr('data-step')
  $("div#unsub #timeToggle").removeAttr('data-intro')
  $("div#message #timeToggle").removeAttr('data-step')
  $("div#message #timeToggle").removeAttr('data-intro')
  $("div#VOS #timeToggle").attr('data-step', "4")
  $("div#VOS #timeToggle").attr('data-intro', "<b>Trends:</b> Track your near and longer term performance with daily, weekly, and monthly views.")
  switch timeRange
    when "7d"
      getItemList(weekDate)
    when "6w"
      getItemList(monthDate)
    when "1y"
      getItemList(yearDate)
  if app.subscription_type == "free"
    $('span.unseen-amount').text(app.total_sentiment)
    $('span.sub-type').text('sentiment')
    $('span.sub-type.ratings').text('sentiment ratings')
    $("#subscriptionAlpha").addClass('active')
    $('div#image-icon').removeClass().addClass('sentiment')
    $('#timeToggle button').addClass('disabled')
    return false
  getReviewList(timeRange)
  app.setNavPosition()

#Churn
$('h2#unsub').click (e) ->
  $('.alpha').removeClass('active')
  $("#unsub ul.subs li").removeClass("active")
  $('.toolTip').removeClass("visible").removeClass('show').addClass('fade')
  $("h2").removeClass("active")
  $(this).addClass("active")
  $('.dash').hide().removeClass('active')
  $('div#unsub').show().addClass('active')
  updatePos()
  timeRange = $("div#unsub #timeToggle button.active").attr("name")
  $("div#VOS #timeToggle").removeAttr('data-step')
  $("div#VOS #timeToggle").removeAttr('data-intro')
  $("div#message #timeToggle").removeAttr('data-step')
  $("div#message #timeToggle").removeAttr('data-intro')
  $("div#unsub #timeToggle").attr('data-step', "4")
  $("div#unsub #timeToggle").attr('data-intro', "<b>Trends:</b> Track your near and longer term performance with daily, weekly, and monthly views.")
  if app.subscription_type == "free"
    $('span.unseen-amount').text(app.total_churn)
    $('span.sub-type').text('surveys')
    $('span.sub-type.ratings').text('churn events')
    $("#subscriptionAlpha").addClass('active')
    $('#subscriptionAlpha div.right h3').text(
      "Upgrade your plan to monitor your
      subscribers' reasons for visiting your
      unsubscribe page with premium features."
    )
    $('div#image-icon').removeClass().addClass('survey')
    $('li.sub button').prop('disabled', true).addClass('btn-disabled')
    getChurnList(timeRange, false)
    return false
  getChurnList(timeRange, true)
  app.setNavPosition()

#SXI
$('h2#message').click (e) ->
  $('li.sub button').prop('disabled', false).removeClass('btn-disabled')
  hardResetLine("SXI")
  $("h2").removeClass("active")
  $(this).addClass("active")
  $('.dash').hide().removeClass('active')
  $('div#message').show().addClass('active')
  updatePos()
  timeRange = $("div#message #timeToggle button.active").attr("name")
  $("div#unsub #timeToggle").removeAttr('data-step')
  $("div#unsub #timeToggle").removeAttr('data-intro')
  $("div#VOS #timeToggle").removeAttr('data-step')
  $("div#VOS #timeToggle").removeAttr('data-intro')
  $("div#message #timeToggle").attr('data-step', "4")
  $("div#message #timeToggle").attr('data-intro', "<b>Trends:</b> Track your near and longer term performance with daily, weekly, and monthly views.")
  getSXIList(timeRange)
  $('.alpha').removeClass('active')
  app.setNavPosition()

#If I Use this Approach it is important too....
#Clear the old array for new data items for each section
#check how long this process is actually taking
$('div#unsub #timeToggle button').click ->
  if !$(this).hasClass("active") and !$(this).hasClass("disabled")
    $('div#unsub #timeToggle button').removeClass("active")
    $(this).addClass("active") 
    timeRange = $(this).attr("id")
    getChurnList(timeRange, true)
    $('#unsub li.sub').removeClass("active")
    $('.toolTip').removeClass("visible").removeClass('show').addClass('fade')
    $('#noDataAlpha').removeClass('active')

$('div#VOS #timeToggle button').click ->
  if !$(this).hasClass("active") and !$(this).hasClass("disabled")
    $('div#VOS #timeToggle button').removeClass("active")
    $(this).addClass("active")
    timeRange = $(this).attr("id")
    getSXIBreakdown($('#VOS li.sub.active').attr('id'))
    switch (type)
      when "ratings"
        getRatingList(ratingType, timeRange)
      when "sentiment"
        getReviewList(timeRange)
      when "satisfaction"
        getNPSList(timeRange)
    switch (timeRange) 
      when "7d"
        getItemList(weekDate)
      when "6w"
        getItemList(monthDate)
      when "1y"
        getItemList(yearDate)
    $('#noDataAlpha').removeClass('active')

$('div#message #timeToggle button').click ->
  if !$(this).hasClass("active") and !$(this).hasClass("disabled")
    $('div#message #timeToggle button').removeClass("active")
    $(this).addClass("active")
    timeRange = $(this).attr("id")
    getSXIList(timeRange)
    $('#noDataAlpha').removeClass('active')

$('li.sub#value button.subSelector').click (e) ->
  $parent = $(this).parent("li")
  if !$parent.hasClass("active") and !$(this).hasClass("disabled")
    #$('div#VOS li.sub').removeClass('shiftUp').removeClass('shiftLeft').removeClass('shiftRight').removeClass('shift')
    $("#VOS li.sub").removeClass("active")
    $("ul.subBreakdown li").removeClass("active")
    $parent.addClass("active")
    #getSXIBreakdown($('#VOS li.sub.active').attr('id'))
    $("#VOS .graphWrapper h3").text("Value Trend")
    currentTime = $('div#VOS').find("#timeToggle button.active").attr("id")
    #$('div#VOS li#frequencyR.sub').addClass('shiftUp').addClass('shift')
    #$('div#VOS li#relevancy.sub').addClass('shiftUp').addClass('shift')
    ratingType = "value"
    $('#noDataAlpha').removeClass('active')
    if app.subscription_type == "free"
      $("#subscriptionAlpha").addClass('active')
      $('#subscriptionAlpha div.right h3').text(
        'Upgrade your plan to monitor whether or
        not your subscribers find your emails valuable
        with premium features.'
      )
      $('span.unseen-amount').text(app.total_ratings)
      $('span.sub-type').text('ratings')
      $('span.sub-type').text('message ratings')
      $('div#image-icon').removeClass().addClass('ratings')
      $('#timeToggle button').addClass('disabled')
      return false
    getRatingList("value",currentTime)

$('li.sub#frequencyR button.subSelector').click (e) ->
  $parent = $(this).parent("li")
  if !$parent.hasClass("active") and !$(this).hasClass("disabled")
    #$('div#VOS li.sub').removeClass('shiftUp').removeClass('shiftLeft').removeClass('shiftRight').removeClass('shift')
    $("#VOS li.sub").removeClass("active")
    $("ul.subBreakdown li").removeClass("active")
    $parent.addClass("active")
    #getSXIBreakdown($('#VOS li.sub.active').attr('id'))
    $("#VOS .graphWrapper h3").text("Frequency Trend")
    currentTime = $('div#VOS').find("#timeToggle button.active").attr("id")
    ratingType = "frequency"
    $('#noDataAlpha').removeClass('active')
    if app.subscription_type == "free"
      $("#subscriptionAlpha").addClass('active')
      $('#subscriptionAlpha div.right h3').text(
        'Upgrade your plan to monitor how your
        subscribers feel about the frequency of
        your emails with premium features.'
      )
      $('span.unseen-amount').text(app.total_ratings)
      $('span.sub-type').text('message ratings')
      $('div#image-icon').removeClass().addClass('ratings')
      $('#timeToggle button').addClass('disabled')
      return false
    getRatingList("frequency",currentTime)

$('li.sub#relevancy button.subSelector').click (e) ->
  $parent = $(this).parent("li")
  if !$parent.hasClass("active") and !$(this).hasClass("disabled")
    #$('div#VOS li.sub').removeClass('shiftUp').removeClass('shiftLeft').removeClass('shiftRight').removeClass('shift')
    $("#VOS li.sub").removeClass("active")
    $("ul.subBreakdown li").removeClass("active")
    $parent.addClass("active")
    #getSXIBreakdown($('#VOS li.sub.active').attr('id'))
    $("#VOS .graphWrapper h3").text("Relevancy Trend")
    currentTime = $('div#VOS').find("#timeToggle button.active").attr("id")
    ratingType = "relevancy"
    $('#noDataAlpha').removeClass('active')
    if app.subscription_type == "free"
      $("#subscriptionAlpha").addClass('active')
      $('#subscriptionAlpha div.right h3').text(
        'Upgrade your plan to monitor whether or
        not your subscribers find your emails relevant
        with premium features.'
      )
      $('span.unseen-amount').text(app.total_ratings)
      $('span.sub-type').text('ratings')
      $('span.sub-type').text('message ratings')
      $('div#image-icon').removeClass().addClass('ratings')
      $('#timeToggle button').addClass('disabled')
      return false
    getRatingList("relevancy",currentTime)

$('li.sub#design button.subSelector').click (e) ->
  $parent = $(this).parent("li")
  if !$parent.hasClass("active") and !$(this).hasClass("disabled")
    #$('div#VOS li.sub').removeClass('shiftUp').removeClass('shiftLeft').removeClass('shiftRight').removeClass('shift')
    $("#VOS li.sub").removeClass("active")
    $("ul.subBreakdown li").removeClass("active")
    $parent.addClass("active")
    #getSXIBreakdown($('#VOS li.sub.active').attr('id'))
    $("#VOS .graphWrapper h3").text("Design Trend")
    currentTime = $('div#VOS').find("#timeToggle button.active").attr("id")
    ratingType = "design"
    $('#noDataAlpha').removeClass('active')
    if app.subscription_type == "free"
      $("#subscriptionAlpha").addClass('active')
      $('#subscriptionAlpha div.right h3').text(
        'Upgrade your plan to monitor how your
        subscribers feel about your email design
        with premium features.'
      )
      $('span.unseen-amount').text(app.total_ratings)
      $('span.sub-type').text('message ratings')
      $('div#image-icon').removeClass().addClass('ratings')
      $('#timeToggle button').addClass('disabled')
      return false
    getRatingList("design",currentTime)

$('li.sub#sentiment button.subSelector').click (e) ->
  $parent = $(this).parent("li")
  if !$parent.hasClass("active") and !$(this).hasClass("disabled")
    #$('div#VOS li.sub').removeClass('shiftUp').removeClass('shiftLeft').removeClass('shiftRight').removeClass('shift')
    $("#VOS li.sub").removeClass("active")
    $parent.addClass("active")
    #getSXIBreakdown($('#VOS li.sub.active').attr('id'))
    $("#VOS .graphWrapper h3").text("Sentiment Trend")
    currentTime = $('div#VOS').find("#timeToggle button.active").attr("id")
    #$('div#VOS li#relevancy.sub').addClass('shiftUp').addClass('shift')
    #$('div#VOS li#design.sub').addClass('shiftUp').addClass('shift')
    $('ul.subBreakdown').hide()
    $('#noDataAlpha').removeClass('active')
    if app.subscription_type == "free"
      $("#subscriptionAlpha").addClass('active')
      $('#subscriptionAlpha div.right h3').text(
        'Upgrade your plan to monitor how your
        subscribers feel about your emails
        with premium features.'
      )
      $('span.unseen-amount').text(app.total_sentiment)
      $('span.sub-type').text('sentiment')
      $('span.sub-type.ratings').text('sentiment ratings')
      $('div#image-icon').removeClass().addClass('sentiment')
      $('#timeToggle button').addClass('disabled')
      return false
    getReviewList(currentTime)

$('li.sub#satisfaction button.subSelector').click (e) ->
  $parent = $(this).parent("li")
  if !$parent.hasClass("active") and !$(this).hasClass("disabled")
    #$('div#VOS li.sub').removeClass('shiftUp').removeClass('shiftLeft').removeClass('shiftRight').removeClass('shift')
    $("#VOS li.sub").removeClass("active")
    $parent.addClass("active")
    #getSXIBreakdown($('#VOS li.sub.active').attr('id'))
    $("#VOS .graphWrapper h3").text("Satisfaction Trend")
    currentTime = $('div#VOS').find("#timeToggle button.active").attr("id")
    #$('div#VOS li#design.sub').addClass('shiftUp')
    #$('div#VOS li#relevancy.sub').addClass('shift')
    #$('div#VOS li#frequencyR.sub').addClass('shiftUp')
    $('ul.subBreakdown').hide()
    $('#noDataAlpha').removeClass('active')
    if app.subscription_type == "free"
      $("#subscriptionAlpha").addClass('active')
      $('#subscriptionAlpha div.right h3').text('Upgrade your plan to identify
        detractors, passives, and promotors with premium features.'
      )
      $('span.unseen-amount').text(app.total_satisfaction)
      $('span.sub-type').text('satisfaction')
      $('span.sub-type.ratings').text('satisfaction ratings')
      $('div#image-icon').removeClass().addClass('satisfaction')
      $('#timeToggle button').addClass('disabled')
      return false
    getNPSList(currentTime)
 
#SUB SELECTOR
#VOS
#$('div#VOS li#ratings.active button.subSelector').click (e) ->
#  if !$(this).hasClass('disabled')
#    #console.log("Clicked : VOS Sub Selector")
#    $('ul.subBreakdown').toggle()
#    updatePos()


openSurveyFactor = (thisID) ->
  #console.log("Opening Survey Factor: " + thisID)
  switch (thisID) 
    when "surveyFrequency"
      updateChurnGraph(surveyItemsFrequent)
    when "surveyOverload"
      updateChurnGraph(surveyItemsOverflow) 
    when "surveyExpectation"
      updateChurnGraph(surveyItemsExpected) 
    when "surveyRelevancy"
      updateChurnGraph(surveyItemsRelevant) 
    when "surveyRepetitive"
      updateChurnGraph(surveyItemsRepetitive) 
    when "surveyOther"
      updateChurnGraph(surveyItemsOther)  

#SUBs for ratings
$('div#VOS ul.subBreakdown').find("li").click (e) ->
  #console.log("Clicked : Sub Selector: " + $(this).attr("id"))
  #Toggle Sub Section Graph with Data
  $('div#VOS li').removeClass("active")
  if !$(this).hasClass('active') and !$(this).hasClass("disabled")
    $(this).addClass("active")
    switch ($(this).attr("id")) 
      when "value"
        currentTime = $('div#VOS').find("#timeToggle button.active").attr("id")
        ratingType = "value"
        getRatingList(ratingType,currentTime)
      when "relevancy"
        currentTime = $('div#VOS').find("#timeToggle button.active").attr("id")
        ratingType = "relevancy"
        getRatingList(ratingType,currentTime)
      when "frequencyR"
        currentTime = $('div#VOS').find("#timeToggle button.active").attr("id")
        ratingType = "frequency"
        getRatingList(ratingType,currentTime)
      when "design"
        currentTime = $('div#VOS').find("#timeToggle button.active").attr("id")
        ratingType = "design"
        getRatingList(ratingType,currentTime)

$('.graphHolder').css({
  'min-height' : '330px',
  'height' : '90%',
})

$('#messageGraph.graphHolder').css({
  'min-height' : '484px'
})

#sets line and gets initial ratings
initialLoadGraph()

#set engagement number
$('.axis line').css({
  'fill': 'none',
  'stroke': 'none',
})

$('.axis path').css({
  'fill': 'none',
  'stroke': 'none',
})

updatePos()

trySwitch = (elem) ->
  if elem.hasClass('disabled')
    setTimeout((() -> trySwitch elem), 500)
  else
    setTimeout((() -> elem.click()), 1000)


params = document.location.search.substring(1).split('&').map((x) -> x.split('='))
section_params = params.filter((x) -> x[0] == 'section')
section = null
if section_params.length
  section = section_params[0][1]
if section
  $("#engagement").click()
  trySwitch $("##{section} button")

