
// document ready
$(document).ready(function() {
  var metrics,theform,metric_set,numDone,numExpected,timer,numberTimers;
  inlineFieldLabel("Your brand", "#id");
  inlineFieldLabel("Your email address", "#tracker_email_address");

/*  function isSearchStartedAutomatically() {
    return(window._autoSearch == true)
  }*/

  function initialize() {
    metrics = null;
    theform = null;
    metric_set = null;
    numDone = 0;
    numExpected = null;
    timer = null;
    numberTimers = new Array();
  }

  
  function poll() {               
    timer = setInterval(function() { // do this every n seconds
      // polling session. First of all, check if all are done.
      if(numDone == numExpected) {
        cleanUp();
      } else { // poll
        setTimeout(function() {
          $.ajax({
            type: 'get',
            url: '/metric_sets/' + metric_set,
            dataType: 'json',
            success: function(data) {
              $('#total_score').text(data.score);
              $.each(data.list, function(n, metric) {
                numDone++;
                          
                var target = $('#metric_' + metric.id);
                var img = $('#metric_' + metric.id + ' img.lg');
                img.css('border', '1px solid black');
                target.replaceWith(metric.partial);
              });
            },
            error: function(xhr) {
              // TODO error loading metric
              // handled on serverside atm, I believe.rob
            }
          })
        }, 0.01);
      }
    }, 2500);

    setTimeout(function() {
      cleanUp();
    }, 90000);      // cancel polling after max n seconds, if it isn't done above
  }
  
  function injectEmptyMetrics(data) {
    numExpected = data.list.length;

    if(window._autoSearch != true) {
      $('.metric_set').before(data.metric_set_heading_partial);
    }
    
    $.each(data.list, function(n,metric) {
      var element;
      metric_set = data.metric_set;

      $('.metric_set').prepend(metric.partial);

      setTimeout(function() {
        $('#' + "metric_" + metric.id).fadeIn(200);
      }, n * 50);
    });

    poll();

    setTimeout(function() {
      $('#loading_query').hide();
    }, data.length * 100);

  }
  
  function submitSearchForm(params) {   
    initialize();   
    var data = params + '&' + 'authenticity_token=' + window._token;

    // set the results running    
    $.ajax({
      type: 'post',
      url: '/metric_sets',
      dataType: 'json',
      data: data,
      success: function(data) { 
        injectEmptyMetrics(data); 
      }
      // TODO some error handling here
    });
    
  
        
    // make sure the form is not really submitted
    return false;
  }
  
  function cleanUp() {
    clearInterval(timer);

    $.each(numberTimers, function(n, aTimer) {
      clearInterval(aTimer);
    });
  }
  
  
  // Brand search: submit button is pressed
  $("form.query").submit(function() {
    if(($('input#id').val().length == 0) || ($('input#id').val() == 'Your brand')){
      alert("Please enter a brand name and try again.")
      return false;
    } else if(validBrandName($("input#id").val())) {
      $('.metric_set_heading').slideUp(500);
      $('.metric_set_heading').remove(); 

      $('.metric_set').slideUp(500);
      $('.metric').remove();
      $('.metric_set').slideDown();
      $('div.stats').slideUp(500);
      $('#loading_query').show();   // show the loading image
      $('div.stats').slideUp(500);
    
      submitSearchForm($("form.query").serialize());
    } else {
      alert("Sorry - a brand should only contain letters, numbers, spaces, dots and hyphens.")
      return false;
    }
  })
  

  // Brand search: autostart (replaces HTTP headers)
/*  if(isSearchStartedAutomatically()) {
    submitSearchForm("id=" + window._searchQuery);
  }*/



})