/**
* Handles the behavior of the AJAX returns for this view.
*
* @author Dario Javier Cravero <dario@starlight.ie>
* 
* @param    data    Object  A JSON object describing the action to execute
* and its parameters.
* General structure:
* data = {
*   method: "...",
*   parameters: {...}
* }
*
* Possible methods/parameters:
*   > successHighlight
*       - message
*   > errorHighlight
*       - message
*   > errorForm
*       - list
*/
function handler(data) {
    // Parse the data string into a JSON object.
    data = JSON.parse(data);

    var logElement = "#mailing_list_log";
    var formElement = "form[data-ajax-form]";

    AjaxHelper.clearForm(formElement);
    AjaxHelper.clearLog(logElement);

    if (data.method == "successHighlight") {
        AjaxHelper.highlight(data.parameters.message, logElement, "success");

        // Reset the form. This should be set in an external method.
        $(formElement + " input[type=email]").val("");
        var action = $(formElement).attr("data-ajax-form") + "/add";
        $(formElement).attr("action", action);
        $("form[data-ajax-form] input[type='submit']").val("Subscribe").attr("disabled", "disabled");
    } else if (data.method == "errorForm") {
        AjaxHelper.errorForm(data.parameters.list, formElement);
   } else if (data.method == "error") {
        AjaxHelper.highlight(data.parameters.message, logElement, "error");
    }
}

$(document).ready(function() {
  $("form[data-ajax-form]").ajaxForm(handler);

  $("form[data-ajax-form] .input_text").bind("keyup change", function(event) {
    // E-mail base regex. The one used below is slightly modified.
    // http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html

    // Filter strings that look like e-mails, i.e. have something before the @, 
    // the @ and at least a . afterwards.
    var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]*(\.[\w\-\+_]*)*\s*$/;

    var value = $(this).val();
    var form = $("form[data-ajax-form]");

    if (value.match(filter) && $(this).attr("data-check") != value) {
      $(this).attr("data-check", value); 
      $.getJSON(form.attr("data-ajax-form") + "/check/" + $(this).val(), function(data) {
        var text = "Unsubscribe";
        var method = "/remove";

        if (data.subscribe) {
          text = "Subscribe";
          method = "/add";
        }
        
        var action = form.attr("data-ajax-form") + method;
        form.attr("action", action);
        $("form[data-ajax-form] input[type='submit']").val(text).removeAttr("disabled");
      });
    } else if ($(this).attr("data-check") != value) {
      $("form[data-ajax-form] input[type='submit']").attr("disabled", "disabled");
    }
    });
  });

