var HF = {};

HF.ajaxHandler = function(fn) {
  return function(transport) {
    var safe = transport.responseText.substring(14);
    eval('var response = ' + safe);
    fn(response);
  };
}

HF.showSection = function(name) {
  if (HF.shown == name) {
    return false;
  }
  var show_content = $(name+'_content');
  var show_action = $(name+'_menu_action');
  var showmation = function() {
    show_action.addClassName('menu_action_active');
    new Animation(show_content)
      .to('opacity', '1')
        .from('0')
          .duration(100)
              .show()
                .ondone(function() {
                    show_content.removeClassName('hidden');
                    HF.shown = name;
                })
                  .go();
  };
  if (HF.shown) {
    var hide_content = $(HF.shown+'_content');
    var hide_action = $(HF.shown+'_menu_action');
    new Animation(hide_content)
      .to('opacity', '0')
        .from('1')
          .duration(100)
            .hide()
              .ondone(function() {
                  hide_action.removeClassName('menu_action_active');
                  hide_content.addClassName('hidden');
                  showmation();
              })
                .go();
  } else {
    showmation();
  }
  return false;
}

HF.testMessage = function(button) {
  button.disabled = true;
  $(button).addClassName('disabled');

  new Ajax.Request('/test_message.php', {
    method: 'post',
    parameters: { action: 'send' },
    onSuccess: HF.ajaxHandler(function(response) {
      if (response.id) {
        $('test_content').addClassName('awaiting_reply');
        new PeriodicalExecuter(HF.waitForResponse(response.id), 5);
      } else {
        $('test_content').addClassName('sending_failed');
      }
    })
  });
}

HF.waitForResponse = function(notification_id) {
  return function(pe) {
    new Ajax.Request('/test_message.php', {
      method: 'post',
      parameters: { action: 'check',
                    notification_id: notification_id },
      onSuccess: HF.ajaxHandler(function(response) {
        if (response.text) {
          $('response_sent').innerHTML = 'Response received! Your phone is properly configured.';
          var target = $('response_text');
          target.innerHTML = response.text;
          target.style.fontWeight='bold';
          new Animation(target)
            .to('opacity', '1')
              .from('0')
                .duration(500)
                  .show()
                    .go();
          pe.stop();
        }
      })
    });
  }
}

HF.refreshProfile = function() {
  new Ajax.Request('/refresh_profile.php', {
    method: 'post',
    onSuccess: HF.ajaxHandler(function(response) {
      var container = $('user_profile_container');
      if (response.html) {
        container.innerHTML = response.html;
        new Animation(container.select('dl')[0])
          .to('opacity', '1')
            .from('0')
              .duration(700)
                .ease(Animation.ease.end)
                  .go();
      } else {
          new Animation(container)
          .to('background', '#f7f7f7')
            .from('#f7c0c0')
              .duration(500)
                .ease(Animation.ease.end)
                  .go();
      }
    })
  });
}

HF.saveSettings = function(button) {
  button = $(button);
  button.disabled = true;
  button.addClassName('disabled');
  
  new Ajax.Request('/save_settings.php', {
    method: 'post',
    parameters: { start: HF.getSelectValue('startTimeOffset'),
                  end: HF.getSelectValue('endTimeOffset'),
                  freq: HF.getSelectValue('notificationFrequency') },

    onSuccess: HF.ajaxHandler(function(response) {
      if (response.insertDate) {
        button.disabled = false;
        button.removeClassName('disabled');

        var tip = $('dnd_tip');
        if (tip) {
          tip.innerHTML = 'You\'re all set! <span>Sit tight, your first message should arrive within 48 hours.</span>';
        }

        $('settings_footer').removeClassName('hidden');
        var last_saved = $('last_saved');
        last_saved.innerHTML = 'Saved: ' + response.insertDate;
        new Animation(last_saved)
          .to('opacity', '1')
            .from('0')
              .duration(500)
                .go();
      }
    })
  });
        
}

HF.getSelectValue = function(name) {
  var select = $(name);
  return select.options[select.selectedIndex].value;
}

HF.rotateGraph = function(graph_id, data_id) {
  var graph = $(graph_id);
  var data = $(data_id);
  
  var target = graph.select('.graph_data')[0];
  var source = data.select('.graph_data')[0];
  HF.fadeAndSwap(target, source);

  target = graph.select('.graph_x_scale_container')[0];
  source = data.select('.graph_x_scale')[0];
  HF.fadeAndSwap(target, source);

  target = graph.select('.graph_footer')[0];
  source = data.select('.graph_footer')[0];
  HF.fadeAndSwap(target, source);

}

HF.fadeAndSwap = function(target, source) {
  new Animation(target)
    .to('opacity', '0')
      .from('1')
        .duration(400)
          .ondone(function() {
              target.innerHTML = source.innerHTML;
              new Animation(target)
                .to('opacity', '1')
                  .from('0')
                    .duration(400)
                      .go();
          })
            .go();
}
