mpog-user-validations.js 13 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
(function(){
  /*
  * "Class" for select and option html generation
  */
  var SelectElement = (function() {
    function SelectElement(name, id) {
      this.select = document.createElement("select");
    }

    SelectElement.prototype.setAttr = function(attr, value) {
      return this.select.setAttribute(attr, value);
    };

    SelectElement.prototype.addOption = function(option) {
      return this.select.add(option);
    };

    SelectElement.prototype.getSelect = function() {
      return this.select;
    };

    SelectElement.generateOption = function(value, text) {
      var option;
      option = document.createElement("option");
      option.setAttribute("value", value);
      option.text = text;
      return option;
    };

    return SelectElement;
  })();

  /*
  * "Class" that switch state field between input and select
  * If the Country if Brazil, set state to select field
  * else set it as a input field
  */
  function SelectFieldChoices() {
    // Get the initial state html
    var input_select = jQuery("#state_field").parent().html();
    var old_value = jQuery("#state_field").val();
    var city_parent_div = jQuery("#city_field").parent().parent().parent();

    function replace_with(html) {
      var parent_div = jQuery("#state_field").parent();
      parent_div.html(html);
    }

    function generate_select(state_list) {
      var select_element = new SelectElement();

      select_element.setAttr("name", "profile_data[state]");
      select_element.setAttr("id", "state_field");
      select_element.setAttr("class", "type-select valid");

      state_list.forEach(function(state){
        var option = SelectElement.generateOption(state, state);
        select_element.addOption(option);
      });

      return select_element.getSelect();
    }

    function replace_state_with_select() {
      jQuery.get("/plugin/mpog_software/get_brazil_states", function(response){
        if( response.length > 0 ) {
          var select_html = generate_select(response);
          replace_with(select_html);

          if( old_value.length != 0 && response.include(old_value) ) {
            jQuery("#state_field").val(old_value);
          }
        }
      });
    }

    function hide_city(){
      city_parent_div.addClass("mpog_hidden_field");
    }

    function show_city(){
      city_parent_div.removeClass("mpog_hidden_field");
    }

    function replace_state_with_input() {
      replace_with(input_select);
    }

    return {
      actualFieldIsInput : function() {
        return jQuery("#state_field").attr("type") == "text";
      },

      setSelect : function() {
        replace_state_with_select();
      },

      setInput : function() {
        replace_state_with_input();
      },
      
      setHideCity : function(){
        hide_city();
      },

      setShowCity : function(){
        show_city();
      }
    }
  }

  function set_form_count_custom_data() {
    var divisor_option = SelectElement.generateOption("-1", "--------------------------------");
    var default_option = SelectElement.generateOption("BR", "Brazil");

    jQuery('#profile_data_country').find("option[value='']").remove();
    jQuery('#profile_data_country').prepend(divisor_option);
    jQuery('#profile_data_country').prepend(default_option);
    jQuery('#profile_data_country').val("BR");
  }

  function set_initial_form_custom_data(selectFieldChoices) {
    set_form_count_custom_data();

    jQuery("#password-balloon").html(jQuery("#user_password_menssage").val());
    jQuery("#profile_data_email").parent().append(jQuery("#email_public_message").remove());

    if( jQuery("#state_field").length != 0 ) selectFieldChoices.setSelect();
  }

  function check_reactivate_account(value, input_object){
    jQuery.ajax({
      url : "/plugin/mpog_software/check_reactivate_account",
      type: "GET",
      data: { "email": value },
      success: function(response) {
        if( jQuery("#forgot_link").length == 0 )
          jQuery(input_object).parent().append(response);
        else
          jQuery("#forgot_link").html(response);
      },
      error: function(type, err, message) {
        console.log(type+" -- "+err+" -- "+message);
      }
    });
  }

  function put_brazil_based_on_email(){
    var suffixes = ['gov.br', 'jus.br', 'leg.br', 'mp.br'];
    var value = this.value;
    var input_object = this;
    var gov_suffix = false;

    suffixes.each(function(suffix){
      var has_suffix = new RegExp("(.*)"+suffix+"$", "i");

      if( has_suffix.test(value) ) {
        gov_suffix = true;
        jQuery("#profile_data_country").val("BR");
      }
    });

    jQuery("#profile_data_country").find(':not(:selected)').css('display', (gov_suffix?'none':'block'));

    check_reactivate_account(value, input_object)
  }

  function validate_email_format(){
    var correct_format_regex = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;

    if( this.value.length > 0 ) {
      if(correct_format_regex.test(this.value))
        this.className = "validated";
      else
        this.className = "invalid";
    } else
      this.className = "";
  }

  function verify_user_password_size() {
    if( this.value.length < 6 ) {
      jQuery(this).switchClass("validated", "invalid");
    } else {
      jQuery(this).switchClass("invalid", "validated");
    }
  }

  function show_or_hide_phone_mask() {
    if(jQuery("#profile_data_country").val() == "BR") {
      if( (typeof jQuery("#profile_data_cell_phone").data("rawMaskFn") === 'undefined') ) {
        jQuery("#profile_data_cell_phone").mask("(99) 9999?9-9999");
        jQuery("#profile_data_comercial_phone").mask("(99) 9999?9-9999");
        jQuery("#profile_data_contact_phone").mask("(99) 9999?9-9999");
      }
    } else {
      jQuery("#profile_data_cell_phone").unmask();
      jQuery("#profile_data_comercial_phone").unmask();
      jQuery("#profile_data_contact_phone").unmask();
    }
  }

  function fix_phone_mask_format(id) {
    jQuery(id).blur(function() {
      var last = jQuery(this).val().substr( jQuery(this).val().indexOf("-") + 1 );

      if( last.length == 3 ) {
          var move = jQuery(this).val().substr( jQuery(this).val().indexOf("-") - 1, 1 );
          var lastfour = move + last;
          var first = jQuery(this).val().substr( 0, 9 );

          jQuery(this).val( first + '-' + lastfour );
      }
    });
  }

  // Sorry, I know its ugly. But I cant get ([^\w\*\s*])|(^|\s)([a-z]|[0-9])
  // to ignore Brazilian not so much special chars in names
  function replace_some_special_chars(text) {
    return text.replace(/([áàâãéèêíïóôõöú])/g, function(value){
      if( ["á","à","â","ã"].indexOf(value) != -1 )
        return "a";
      else if( ["é","è","ê"].indexOf(value) != -1 )
        return "e";
      else if( ["í","ï"].indexOf(value) != -1 )
        return "i";
      else if ( ["ó","ô","õ","ö"].indexOf(value) != -1 )
        return "o";
      else if( ["ú"].indexOf(value) != -1 )
        return "u";
      else
        return value;
    });
  }

  function invalid_name_validation(text) {
    if( text.trim().length == 0 ) {
      return true;
    }

    var full_validation = /([^\w\*\s*])|(^|\s)([a-z]|[0-9])/; // no special chars and do not initialize with no capital latter
    var partial_validation = /[^\w\*\s*]/; // no special chars
    text = replace_some_special_chars(text);
    var slices = text.split(" ");
    var invalid = false;

    for(var i = 0; i < slices.length; i++) {
      if( slices[i].length > 3 || text.length <= 3 ) {
        invalid = full_validation.test(slices[i]);
      } else {
        invalid = partial_validation.test(slices[i]);
      }

      if(invalid) break;
    }

    return invalid;
  }

  // Generic
  function show_plugin_error_message(field_selector, hidden_message_id ) {
    var field = jQuery(field_selector);

    field.removeClass("validated").addClass("invalid");

    if(!jQuery("." + hidden_message_id)[0]) {
      var message = jQuery("#" + hidden_message_id).val();
      field.parent().append("<div class='" + hidden_message_id + " errorExplanation'>"+message+"</span>");
    } else {
      jQuery("." + hidden_message_id).show();
    }
  }

  function hide_plugin_error_message(field_selector, hidden_message_id) {
    jQuery(field_selector).removeClass("invalid").addClass("validated");
    jQuery("." + hidden_message_id).hide();
  }

  function addBlurFields(field_selector, hidden_message_id, validation_function, allow_blank) {
    jQuery(field_selector).blur(function(){
      jQuery(this).attr("class", "");

      if( validation_function(this.value, !!allow_blank) ) {
        show_plugin_error_message(field_selector, hidden_message_id);
      } else {
        hide_plugin_error_message(field_selector, hidden_message_id);
      }
    });
  }

  function invalid_email_validation(value, allow_blank) {
    if( allow_blank && value.trim().length == 0 ) {
      return false;
    }

    var correct_format_regex = new RegExp(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);

    return !correct_format_regex.test(value);
  }

  function invalid_site_validation(value) {
    var correct_format_regex = new RegExp(/(^|)(http[s]{0,1})\:\/\/(\w+[.])\w+/g);

    return !correct_format_regex.test(value);
  }
  //End generic

  function get_privacy_selector_parent_div(field_id, actual) {
    if( actual == undefined ) actual = jQuery(field_id);

    if( actual.is("form") || actual.length == 0 ) return null; // Not allow recursion over form

    if( actual.hasClass("field-with-privacy-selector") ) {
      return actual;
    } else {
      return get_privacy_selector_parent_div(field_id, actual.parent());
    }
  }

  function try_to_remove(list, field) {
    try {
      list.push(field.remove());
    } catch(e) {
      console.log("Cound not remove field");
    }
  }

  function get_edit_fields_in_insertion_order() {
    var containers = [];

    try_to_remove(containers, get_privacy_selector_parent_div("#profile_data_name"));
    try_to_remove(containers, get_privacy_selector_parent_div("#profile_data_email"));
    try_to_remove(containers, jQuery("#user_secondary_email").parent().parent());
    try_to_remove(containers, jQuery("#select_institution"));
    try_to_remove(containers, get_privacy_selector_parent_div("#profile_data_cell_phone"));
    try_to_remove(containers, get_privacy_selector_parent_div("#profile_data_contact_phone"));
    try_to_remove(containers, get_privacy_selector_parent_div("#profile_data_comercial_phone"));
    try_to_remove(containers, get_privacy_selector_parent_div("#profile_data_personal_website"));
    try_to_remove(containers, get_privacy_selector_parent_div("#profile_data_organization_website"));
    try_to_remove(containers, get_privacy_selector_parent_div("#profile_data_birth_date"));
    try_to_remove(containers, get_privacy_selector_parent_div("#profile_data_country"));
    try_to_remove(containers, get_privacy_selector_parent_div("#state_field"));
    try_to_remove(containers, get_privacy_selector_parent_div("#city_field"));

    return containers;
  }

  function change_edit_fields_order() {
    var form = jQuery("#profile-data");
    if( form.length != 0 ) {
      var containers = get_edit_fields_in_insertion_order();

      containers.reverse();

      containers.forEach(function(container){
        form.prepend(container);
      });
    }
  }

  jQuery(document).ready(function(){
    change_edit_fields_order(); // To change the fields order, it MUST be the first function executed

    var selectFieldChoices = new SelectFieldChoices();
    set_initial_form_custom_data(selectFieldChoices);

    jQuery('#secondary_email_field').blur(
      validate_email_format
    );

    jQuery("#user_email").blur(put_brazil_based_on_email);

    jQuery('#secondary_email_field').focus(function() { jQuery('#secondary-email-balloon').fadeIn('slow'); });
    jQuery('#secondary_email_field').blur(function() { jQuery('#secondary-email-balloon').fadeOut('slow'); });

    jQuery("#user_pw").blur(verify_user_password_size);

    jQuery("#profile_data_country").blur(show_or_hide_phone_mask);

    // Event that calls the "Class" to siwtch state field types
    jQuery("#profile_data_country").change(function(){
      if( this.value == "-1" ) jQuery(this).val("BR");

      if( this.value == "BR" && selectFieldChoices.actualFieldIsInput() ) {
        selectFieldChoices.setSelect();
        selectFieldChoices.setShowCity();
      } else if( this.value != "BR" && !selectFieldChoices.actualFieldIsInput() ) {
        selectFieldChoices.setInput();
        selectFieldChoices.setHideCity();
      }
    });

    show_or_hide_phone_mask();

    fix_phone_mask_format("#profile_data_cell_phone");
    fix_phone_mask_format("#profile_data_comercial_phone");
    fix_phone_mask_format("#profile_data_contact_phone");

    addBlurFields("#profile_data_name", "full_name_error", invalid_name_validation);
    addBlurFields("#profile_data_email", "email_error", invalid_email_validation);
    addBlurFields("#user_secondary_email", "email_error", invalid_email_validation, true);
    addBlurFields("#profile_data_personal_website", "site_error", invalid_site_validation);
    addBlurFields("#profile_data_organization_website", "site_error", invalid_site_validation);
  });
})();