// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

$.ajaxSetup({
  'beforeSend': function (xhr) { xhr.setRequestHeader('Accept', 'text/javascript'); }
});

$.fn.submitWithAjax = function() {
  this.submit(function() {
    $.post($(this).attr('action'), $(this).serialize(), null, 'script');
    return false;
  });
};

$(function() {
  $('fieldset input:first').focus();

  $('input.focusme').live('click', function() { $(this).focus().select(); });

  // Disable submit buttons after click
  /*
  $("form input[type='submit']").click(function() {
    $(this).attr('disabled', 'disabled');
    return true;
  });
  */

  // No auto complete on sensitive form data
  $('.no_auto_complete').each(function() { $(this).attr('autocomplete','off'); });
  
  // Flash messages
  $('body').bind('flash_notice', function () {
    $('#flash-notice').animate( { top:"0px" }, 300, 'linear', function() {
      window.setTimeout(function () {
        $('#flash-notice').animate( { top:"-40px" }, 300);
      }, 3000);
    });
  });
  if ($('#flash-notice').length > 0) {
    $('body').trigger('flash_notice');
  };

  // Dialog Behavior
  $('#dialog_window').jqm({
    overlay: 75,
    modal: true,
    trigger: '.dialog_trigger'
  });

  $('#standby_window').jqm({
    overlay: 75,
    modal: true,
    trigger: '.standby_trigger'
  });


  $('#dialog_window .cancel').live('click',function() {
    if ($('body').hasClass('login')) { return true; }
    $('#dialog_window').jqmHide();
    $('#dialog_window .bd').empty();
    return false;
  });
  $("#dialog_window input[type='submit']").live('click',function() {
    if ($('body').hasClass('login')) { return true; }
    $(this).attr('disabled', 'disabled');
    $('#errorExplanation').remove();
    $('#dialog_window li.fieldWithErrors').removeClass('fieldWithErrors');
    var $form = $('#dialog_window form');
    $.post($form.attr('action'), $form.serialize(), null, 'script');
    return false;
  });

  $('.ajax_dialog_trigger').live('click', function(){
    $.get($(this).attr('href'), function(data, textStatus) {
      if (textStatus == "success") {
        $('#dialog_window .bd').html(data);
        $('#dialog_window').jqmShow();
        $('#dialot_window input:first').focus();
      }
    });
    return false;
  });

  // Storage Meter
  if($('#meter').length > 0) {
    var className = $('#meter').attr('class');
    var val = className.replace('used_','');
    $('#meter .value').css('width', val+'%');
    if (val > 0) {
      $('#meter').show();
    }
  }

  // New/Update Plan
  $('.new_payment #plan_comparison .buttons input').click(function() {
    $('#plan_comparison .buttons input').attr('disabled','');
    $(this).attr('disabled','disabled');
    $('#plan_comparison')[0].className = '';
    $('#plan_comparison').addClass($(this)[0].className);
    $('#user_plan_id').val($(this).attr('id').replace('plan_',''));
  });
  $('#user_plan_id').each(function() {
    id = '#plan_' + $(this).val();
    $(id).click();
  });
  $(".edit_plan input[type='submit']").click(function() {
    $('#standby_window').jqmShow();
  });

  $('form.edit_user .switch').click(function() {
    $('form').submit();
  });

  // API Docs
  $('#api_methods li').click(function() {
    var is_parent = ($(this).parent().attr('id') == 'api_methods');
    if (is_parent) {
      var $methodsUL = $(this).parent();
      $methodsUL.find('li ul').hide('fast');
      if ($(this).find('ul').css('display') == 'block') {
        return false;
      }
      $(this).find('ul').show('fast');
      $(this).find('ul li:first').click();
      return false;
    }
    else {
      var $method = $('#'+$(this).attr('id').replace('_trigger',''));
      if ($method.css('display') == 'block') {
        return false;
      }
      $('.api_method').hide('fast');
      $method.show('fast');
      return false;
    }
  });

  // continue to check if there are incomplete recordings
  var checkCompleteRecordings = setInterval(checkIncompleteStatus, 60000); // 60 seconds
});

// Checks if all the scenario results that are not complete become complete and updates the result.
function checkIncompleteStatus() {
  $('.test_time .incomplete').each(function() {
    var result = $(this);
    $.get('/update_result/' + $(this).attr('id'), function(data) {
      if (data.length > 1) { // some result
        result.text(data); // update status
        if (  data.match(/complete/i) ) {
          var projectID = $('.project').attr('id').match(/^project_(.+)/)[1];
          var scenarioID = $('.test_time .incomplete').closest('.scenario').attr('id').match(/^scenario_(.+)/)[1];
          var scenarioResultID = $('.test_time .incomplete').attr('id');
          var resultName = result.parent().prev().find('span');
          var linkText = $.trim(resultName.text());
          var resultLink = $('<a title="View" href="/projects/' + projectID + '/scenarios/' + scenarioID + '/scenario_results/' + scenarioResultID + '">' + linkText + '</a>');

          resultName.html(resultLink); // add link to results
          result.parent().parent().addClass('new');
          result.removeClass('incomplete');
        }
      }
    });
  });
  clearStatusCheck();
}

// Stop checkIncompleteStatus if there are no more incomplete results.
function clearStatusCheck() {
  var numberLeft = $('.test_time .incomplete').length;
  if (numberLeft < 1) {
    clearInterval(2); // TODO: get the id of checkComplete programmatically
  }
}
