
  /* ---------------------------------------------------------------------------

    Copyright (C) 2009   Vintage Media Ltd   www.vintagewebworks.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    A copy of the GNU General Public License is included in the 'docs' folder
    and online at: http://www.gnu.org/licenses/gpl.txt

  --------------------------------------------------------------------------- */

  /*

    SCRIPT INFO:
    ************

    Description:   Validate forms using ajax. Requires Mootools Core
    Revision No:   001
    Created:       01 Jan 2009
    Last updated:  01 Jan 2009
    Author:        Vintage Web Works - www.vintagewebworks.com
    Help:          www.typepublish.org/v1/manual

  */



  window.addEvent('domready', function() {

    $each($$('.input_form'), function(el) {

      el.addEvent('submit', function(e) {

        e.stop();                                     // Prevent default form submimt from going ahead
        var messages = $(document.body).getElement('.messages');           // Set form_error div
        messages.empty()
        messages.removeClass('clean');
        messages.removeClass('info');
        messages.removeClass('success');
        messages.removeClass('warning');
        messages.removeClass('error');
        messages.addClass('spinner');      // Empty errors div and add spinner
        messages.setStyle('display', '');

        new Fx.Scroll(window).toTop();                // Return to top
        //scroll(0,0);

        this.set('send', {                            // 'this' refers to $('input_form')

          onComplete: function(response) {

            var data = eval('(' + response + ')'); // JSON will be returned
            var success = 1;                       // We'll change this to 0 if form fails validation

            if (data.results.length > 0) {         // There should always be results of some sort
              for (var i=0;i<data.results.length;i++) {

                if (data.results[i].errors) {       // Deal with errors
                  success = 0;
                  for (var e=0;e<data.results[i].errors.length;e++) {
                    var input_id = data.results[i].errors[e].error.item;  // Highlight field with error
                    var note_id = data.results[i].errors[e].error.item + '_note';    // Show error message in field 'note'
                    $(note_id).innerHTML = data.results[i].errors[e].error.message;
                    $(note_id).addClass('error');
                  }
                } else if (data.results[i].onsuccess) {                  // Grab message for onsuccess and onfailure
                  var msg_onsuccess = data.results[i].onsuccess;
                } else if (data.results[i].onfailure) {
                  var msg_onfailure = data.results[i].onfailure;
                }

              }

              messages.removeClass('spinner');

              if (success == 1) {

                messages.addClass('success');
                messages.set('html', msg_onsuccess);

              } else if (success == 0) {

                messages.addClass('error');
                messages.set('html', msg_onfailure);

              }

            }

          }

        });

        this.send();                                  // Send the form

      });

    });

  });




  // Validates individual fields - usually onblur
  var AjaxFieldValidator = new Class({

    initialize: function(element, url) {

      // Set error div - it's the name of the element + _note
      var result_div = $(element).getProperty('id') + '_note';

      if ($(result_div)) {

        // Run validation

        var form = $(element).getParent('form');   // Get parent form
        var params = $(form).toQueryString();      // Serialize form values - do the whole form in case we want to cross reference stuff, e.g. passwords
        var req = new Request.HTML({               // Send Ajax request
          url: url,
          data: params,
          onSuccess: function(html) {              // If something return, item has failed validation
            if (html != '') {
              $(result_div).empty();               // Clear the text currently inside the results div
              $(result_div).addClass('error');     // Highlight as error
              $(result_div).adopt(html);           // Inject the new DOM elements into the results div
            } else {
              $(result_div).empty();               // Clear the text currently inside the results div
              $(result_div).removeClass('error');  // Remove error highlight
            }
          }
        }).post();

      }

    }

  });


  //Countdown number of characters left - usually applied onkeyup
  var CharCountdown = new Class({

    initialize: function(element, max_chars, lang_chars_left, lang_too_long) {

      // Set error div - it's the name of the element + _note
      var result_div = $(element).getProperty('id') + '_note';

      if ($(result_div)) {

        // Tidy up
        $(result_div).empty();
        $(result_div).removeClass('error');

        // Run validation
        if ($(element).value.length > max_chars) {
          $(result_div).innerHTML = lang_too_long;
        } else {
          $(result_div).innerHTML = (max_chars - $(element).value.length) + ' ' + lang_chars_left;
        }

      }

    }

  });
