﻿// ////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) IT Pro Solutions BVBA 2010
//
// This material contains unpublished, copyrighted work, which includes
// confidential and proprietary information of IT Pro Solutions BVBA,
// Dijk 21/1, BE-2861 OLV-Waver, info@itprosolutions.be.
//
// All rights reserved. No copy of any part of this document is permitted
// without explicit written authorization from IT Pro Solutions BVBA.
//
// $Revision: $
// Last modified by $Author: $ on $Date: $
//
// ////////////////////////////////////////////////////////////////////////////

var jform =
{
  Stage: { Start: 1, ErrorReceived: 2, ErrorMessageReceived: 3, AllErrorsReceived: 4, NoErrors: 5 },

  bindButton: function(button, validation)
  {
    $(button).click(function() { jform.submitForm($(button)[0].form, $(button).attr("name"), validation); return false; });
  },
  
  submitForm: function(form, button, validation, callback)
  {
    if (!callback)
      callback = this.updateLayout;

    callback(jform.Stage.Start);
    
    var validate = eval(validation);
    
    validate($(form), function(result)
    {
      if (result.Success)
      {
        callback(jform.Stage.NoErrors);
        
        if (button && button.length > 0)
          $("<input type='hidden' value='*' />").prependTo($(form)).attr("name", button).val($("input[name=" + button + "]").val());
        
        $(form).submit();
        
        return;
      }

      $.each(result.Messages, function(i, message) { callback(jform.Stage.ErrorMessageReceived, message.Message, message.ControlNames); });
      
      callback(jform.Stage.AllErrorsReceived);
    });
  },
  
  updateLayout: function(stage, message, fields)
  {
    var $summary = $(".Summary ul");
    var $success = $(".Success");

    if (stage == jform.Stage.Start)
    {
      $success.hide();

      $summary.parent().hide();
      $summary.empty();

      $("form .Failure").removeClass("Failure");

      return;
    }

    if (stage == jform.Stage.ErrorMessageReceived)
    {
      $("<li>").appendTo($summary).text(message);

      $.each(fields, function(i, name) { $("[name=" + name + "]").addClass("Failure"); });

      return;
    }

    if (stage == jform.Stage.ErrorReceived)
    {
      $("<li>").appendTo($summary).text(message);

      $("[name=" + message + "]").addClass("Failure");
      $("[name=" + message + "]:checkbox").parents("div:first").children().addClass("Failure");
        
      return;
    }

    if (stage == jform.Stage.AllErrorsReceived)
    {
      $summary.parent().fadeIn("medium");

      return;
    }
  }
}
