// @codekit-prepend "gui.js"
// @koala-prepend "gui_ck_fw/gui.js"

(function($) {

MaterioUser = function(){

  var _isAdhesion = $('body').is('.page-node-11187') || $('body').is('.page-node-11186');

  function init() {
    //trace('MaterioUser init compile test 3');
    if(_isAdhesion)
      initAdhesion();
  };

  function initAdhesion(){
    // trace('initAdhesion');
    $('.get-link a').bind('click', function(event) {
      // trace('get-link click');

      // do not show the registration form if already logged-in
      if($('body').is('.logged-in'))
        return true;

      // else show the ajaxified registration form
      event.preventDefault();

      var  $this = $(this),
             href = $this.attr("href"),
             destination = href.match('/\?destination=([^,]+)');

      destination = "/" + destination[1];
      destination = destination.replace('//', '/');
      // trace('destination', destination);

      // if($this.parents('.gratos').size()){
      //   loadRegisterBlock(destination);
      // }else{
        loadLoginAndRegisterBlock(destination);
      // }
      return false;
    });
  };

  // function loadRegisterBlock (destination) {
  //   // trace("loadRegisterBlock :: dest = "+destination);
  //   $.getJSON(Drupal.settings.basePath+Drupal.settings.pathPrefix+'materio_user/registerblock', function(json){formLoaded(json, destination);});
  // }

  function loadLoginAndRegisterBlock(destination){
    // trace('loadRegistrationBlock :: dest = '+destination);
    $.getJSON(Drupal.settings.basePath+Drupal.settings.pathPrefix+'materio_user/loginandregisterblock', function(json){formLoaded(json, destination);});
  };

  function formLoaded(json, destination){
    //trace('formLoaded | json', json);
    var $modal = $('<div>').addClass('modal-content').append(json.block);

    var id,label, description;
    $('input.form-text', $modal).each(function(i) {
      id = $(this).attr('id');
      label = $('label[for='+id+']').hide().text();
      description = $(this).parent().find('.description').hide().text();
      $(this).attr('placeholder', label).attr('title', description);
    });

    // $('.homepage-textfield', $modal).hide();

    $('body').append($('<div>').addClass('modal-wrapper').append($modal));

    $('.modal-wrapper').bind('click', function(event) {
      $(this).remove();
    });

    $('.modal-content').bind('click', function(event) {
     event.stopPropagation();
    });

    // doesn't work
    // Drupal.attachBehaviors('bodi>.modal-wrapper');

    $.event.trigger('ajax-register-block-loaded');

    $("#user-register-form #edit-submit, #user-register-form #edit-submit--2", $modal).click(function(event){
      event.preventDefault();

      // disable submit button to avoid duplicate user creation
      // console.log('click', this);
      $(this).attr('disabled', 'true');

      $.ajax({
        type: 'POST',
        dataType:'json',
        url: Drupal.settings.basePath+Drupal.settings.pathPrefix+"materio_user/register/submit",
        data: $('#user-register-form', $modal).serialize(),
        success: function(data) { onUserLoginRegisterSubmit($('#user-register-form'), data, destination);},
        error: function(jqXHR, textStatus, errorThrown) { trace('error : '+textStatus+' | '+errorThrown); }
      });
      return false;
    });

     $("#user-login #edit-submit", $modal).click(function(event){
      event.preventDefault();
      $.ajax({
        type: 'POST',
        dataType:'json',
        url: Drupal.settings.basePath+Drupal.settings.pathPrefix+"materio_user/login/submit",
        data: $('#user-login', $modal).serialize(),
        success: function(data){ onUserLoginRegisterSubmit($('#user-login'), data, destination); },
        error: function(jqXHR, textStatus, errorThrown) { trace('error : '+textStatus+' | '+errorThrown); }
      });
      return false;
    });

    // google analytics
    // $.event.trigger({
    //   type : "record-stat",
    //   categorie : 'Search',
    //   action : keys,
    //   label : 'filters : '+ stringTypes.join(' ,'),
    //   value : json.count
    // });


  };

  function onUserLoginRegisterSubmit($form, data, destination){
    // console.log('data', data);
    cleanModalErrors();
    if(data.errors != null){
      for(field in data.errors){
        $('input[name='+field+']', $form).addClass('error');
        $form.prepend($('<div>').addClass('message-error').html(data.errors[field]));
      }

      (function($form){
        setTimeout(function(){
          console.log('enabled');
          $('input[type=submit]', $form).removeAttr('disabled');
        }, 0.5*1000);
      })($form);

    }else{
      // trace('destination = '+destination);
      window.location = destination.replace('%23', '#');
    }
  };

  function cleanModalErrors() {
    $('.message-error', '.modal-content').remove();
    $('input', '.modal-content').removeClass('error');
  }

  init();
};

$(document).ready(function() {
  var materiouser = new MaterioUser();
});

})(jQuery);