
/* :::::::::: RegisrationHelper :::::::::::::: */
var RegisrationHelper = Class.create(); 
RegisrationHelper.prototype =
{
    initialize: function()
    {
    },
    
    init: function (form_name)
    {
         this.form = $(form_name);
         this.msg = $('msg');
         this.result = new Hash({});
         this.locksubmit = true;
         this.lockajax = 0; 

         var thisCopy = this;
         var inputs = this.form.select('input[type="text"]', 'input[type="password"]');
             inputs.each(function(el)     
             {
                if(el.id=='login') thisCopy.input_login = el;
                else if(el.id=='email') thisCopy.input_email = el;
                else if(el.id=='password') thisCopy.input_password1 = el;
                else if(el.id=='password2') thisCopy.input_password2 = el;
                //else if(el.id=='day') thisCopy.input_day = el; 
//                else if(el.id=='month') thisCopy.input_month = el; 
//                else if(el.id=='year') thisCopy.input_year = el; 
                
                el.observe('keyup', function(event)  { thisCopy.onKeyPress( event, el ); });
             });
         
         var selects = this.form.select('select');
             selects.each(function(el)     
             {
                if(el.id=='sex') thisCopy.select_sex = el;
             });
         
         this.input_lic = $('lic');
    },

    submit: function ()
    {
        //this.checkForm( this.msg );
//        if(this.locksubmit == false)
            this.form.submit();
    },
                               
    showMessage: function( text )
    {
        if(text.blank())
            this.msg.update(''); 
        else
            this.msg.update('| '+text);
    },
    
    onKeyPress: function(event, input) {
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_ESC:
       case Event.KEY_RETURN: 
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
       case Event.KEY_UP:
       case Event.KEY_DOWN:
       case Event.KEY_HOME:
       case Event.KEY_END:
       case Event.KEY_PAGEUP:
       case Event.KEY_PAGEDOWN:
       case Event.KEY_INSERT:
         return;
      }
      this.checkForm(input);
    },
    
    checkForm: function( input )
    {
        this.locksubmit = true;
       
        if(this.result.get('login') != 1 || input.id=='login')
        {   
            if( this.result.get('login') == 0 && input.id!='login')
            {
                this.showMessage('такой ЛОГИН уже есть в системе');  
                return;
            } 

            input = (input.id=='login'? input : this.input_login );
            if( this.checkLogin( input )) {
                this.result.set('login', 1);
            } else {
                this.result.unset('login'); return; 
            }
        }
        if(this.result.get('email') != 1 || input.id=='email')
        {
            if( this.result.get('email') == 0 && input.id!='email')
            {
                this.showMessage('такой EMAIL уже есть в системе');  
                return;
            }

            input = (input.id=='email'? input : this.input_email );
            if( this.checkEmail( input ) ) {
                this.result.set('email', 1);
            } else {
                this.result.unset('email'); return; 
            }
        }        
        if(this.result.get('pass1') != 1 || input.id=='password')
        {
            input = (input.id=='password' ? input : this.input_password1 );
            if( this.checkPassword1( input ) ) {
                this.result.set('pass1', 1);
                this.result.set('pass2', 0); //recheck pass1 == pass2
            } else {
                this.result.unset('pass1'); return; 
            }
        }
        if(this.result.get('pass2') != 1 || input.id=='password2')
        {
            input = (input.id=='password2' ? input : this.input_password2 );
            if( this.checkPassword2( input ) ) {
                this.result.set('pass2', 1);
            } else {
                this.result.unset('pass2'); return; 
            }
        }
        if(this.result.get('sex') != 1 || input.id=='sex')
        {
            input = (input.id=='sex' ? input : this.select_sex );
            if(input.value=='no') {
               this.showMessage('укажите ПОЛ'); 
               this.result.unset('sex'); return;
            }
            else {
                this.result.set('sex', 1);
            }
        }

        if(this.result.get('bd') != 1 || input.id=='day' || input.id=='month' || input.id=='year')
        {
            if( this.checkBD( ) ) {
                this.result.set('bd', 1);
            } else {
                this.result.unset('bd'); return; 
            }
        }
        
        if( ( this.input_lic.checked) == false )
        {
           this.showMessage('ознакомтесь с ПОЛЬЗОВАТЕЛЬСКИМ СОГЛАШЕНИЕМ');  
           return; 
        }
           
        this.showMessage('');
        this.locksubmit = false;
    },

    checkLogin: function( input )
    {
         do
         {
            if(input.value.length == 0)
            {
                this.showMessage('не заполнено поле ЛОГИН');  
                break;
            }
            if(input.value.length<3)
            {
                this.showMessage('ЛОГИН должен содержать не менее 3-х символов');  
                break;
            }
            
            var reg = new RegExp ("^[a-zA-Z0-9_]*$", 'i');
            if( reg.test(input.value) == false )
            {
                this.showMessage('ЛОГИН должен содержать только латиницу и цифры');  
                break;
            }
            
            this.ajaxCheck(input);
                              
            return true;
         }while(false);
         return false;       
    },

    checkEmail: function( input )
    {
         do
         {
            if(input.value.length == 0)
            {
                this.showMessage('не заполнено поле E-MAIL!');  
                break;
            }
            if(!this.isEmail(input.value))
            {
                this.showMessage('E-MAIL указан некорректно');  
                break;
            }
            
            this.ajaxCheck(input);
                              
            return true;
         }while(false);
         return false;       
    },

    checkBD: function( )
    {
        //alert('('+this.input_day.value+')');
       if(this.input_day.value=='ДД' || this.input_day.value == '' ||
          this.input_month.value == 'ММ' || this.input_month.value == '' ||
          this.input_year == 'ГГГГ' || this.input_year.value == '' ) {
           this.showMessage('укажите ДАТУ РОЖДЕНИЯ'); 
           return false;
       }

        if( !( (this.input_day.value > 0 && this.input_day.value < 32) &&
               (this.input_month.value > 0 && this.input_month.value < 13) &&
               (this.input_year.value > 1900 && this.input_year.value <2600) )
          )
        {
            this.showMessage('не корректно указана ДАТА РОЖДЕНИЯ');  
            return false;
        }
      
        return true;     
    },
    
    checkPassword1: function( input )
    {
         do
         {
            if(input.value.length == 0)
            {
                this.showMessage('не заполнено поле ПАРОЛЬ');  
                break;
            }
            if(input.value.length<3)
            {
                this.showMessage('ПАРОЛЬ должен содержать не менее 3-х символов');  
                break;
            }
                              
            return true;
         }while(false);
         return false;       
    },

    checkPassword2: function( input )
    {
         do
         {
            if(input.value.length == 0)
            {
                this.showMessage('не заполнено поле ПОВТОР ПАРОЛЯ');  
                break;
            }
            //if(input.value!= this.input_password1.value)
//            {
//                this.showMessage('ошибка подтверждения ПАРОЛЯ');  
//                break;
//            }
                              
            return true;
         }while(false);
         return false;       
    },
    
    isEmail: function(item)
    {
        var at="@";
        var dot=".";
        var lat=item.indexOf(at);
        var litem=item.length;
        var ldot=item.indexOf(dot);

           var reg= new RegExp ("^[_0-9a-z-]+@[-0-9a-z_^\\.]+\\.[a-z]{2,6}$", 'i');
           if (!reg.test(item)) {
                   return false;
           }
        if (item.indexOf(at)==-1) return false;
        if (item.indexOf(at)==-1 || item.indexOf(at)==0 || item.indexOf(at)==litem) return false;
        if (item.indexOf(dot)==-1 || item.indexOf(dot)==0 || item.indexOf(dot) >= litem - 2) return false;
        if (item.indexOf(at,(lat+1))!=-1) return false;
        if (item.substring(lat-1,lat)==dot || item.substring(lat+1,lat+2)==dot) return false;
        if (item.indexOf(dot,(lat+2))==-1) return false;
        if (item.indexOf(" ")!=-1)  return false;

        return true;
    },
    
    ajaxCheck: function(input)
    {
        //if(this.lockajax == 1)
        //    return;
    
        //this.lockajax = 1;
    
        new Ajax.Request('/user/ajax_registation_check/', {
            method: 'post',
            parameters: {'type': input.id, 'value': input.value},
            asynchronous: true,

            onSuccess: function(response)
            {
                var res = response.responseText;
                //this.lockajax = 0; 
                if(res == 0) {
                    this.result.set(input.id, 0);
                    this.checkForm( this.msg );
                }
                else if(res == 1)
                    this.result.set(input.id, 1);
                    
            }.bind(this),

            onFailure: function() 
            {                
            }.bind(this)
        } );   
    } 
}
