var step_windows_prefix = 'registration_step_' ;
var step_arrow_prefix = 'signup_step_arrow_' ;
var step_arrow_head_prefix = 'signup_step_arrowhead_' ;

var emailRegExp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$/;

var reg_fields_attr = {} ;

var current_step_win = null ;

var current_step = 0 ;

var steps = {} ;

var steps_n = 0 ;

var opened_signup_error = false ;

var passed_step = {} ;

var duplicates_timeout = null ;

var summary_data = {} ;

var duplicates_checking = false ;

var duplicates_errors = {} ;

var textarea_resizer_start_x = 0 ;

var textarea_resizer_start_y = 0 ;

var textare_dragging = false ;

var is_signup_done = false ;

var verified_duplicates = [] ;

function start_signup ( step_list, step_count )
{
    steps_n = step_count ;
    steps = unserialize ( step_list ) ;
    
    show_current_step ( ) ;
}

function signup_next_step ( )
{
   if ( duplicates_checking )
   {
       return false ;
   }
   
   if ( Number ( current_step+2 ) > steps_n )
   {
       return false ;
   }
   
   if ( ! check_signup_fields (  ) )
   {
       return ;
   }
   
   if ( opened_signup_error )
   {
       close_signup_error ( ) ;
   }
   
   passed_step[current_step] = passed_step[current_step+1] = true ;
   
   go_to_step ( current_step+1 )
   
   return ;
   
   passed_step[current_step] = true ;
   
   current_step_win.style.display = 'none' ;
   current_step++ ;
   
   //$(current_step_win).fadeOut(300) ;
   //$(current_step_win).slideUp() ;
   show_current_step ( ) ;
   
   return false ;
}

function signup_prev_step ( )
{
   if ( duplicates_checking )
   {
       return false ;
   }
   
   if ( Number ( current_step-1 ) < 0 )
   {
       return false ;
   }
   
   if ( opened_signup_error ) close_signup_error ( ) ;
   
   go_to_step ( current_step-1 )
   
   return ;
   
   current_step_win.style.display = 'none' ;
   //$(current_step_win).fedeOut(100) ;
   current_step-- ;
   
   show_current_step ( ) ;
}

function recalc_step_arrows ( )
{
    for ( var i = 0 ; i < steps_n; i++ )
    {
        if ( i <= current_step )
        {
            document.getElementById(step_arrow_prefix+String(steps[i])).className = 'step_actived' ;
            
            document.getElementById(step_arrow_head_prefix+String(steps[i])).className = 'step_arrow_actived' ;
            try{document.getElementById(step_arrow_head_prefix+String(steps[i-1])).className = 'step_arrow_cactived' ; }catch(err){}
        }
        else
        {
            document.getElementById(step_arrow_prefix+String(steps[i])).className = '' ;
            document.getElementById(step_arrow_head_prefix+String(steps[i])).className = 'step_arrow' ;
        }
    }
}

function show_current_step ()
{
    
    if ( duplicates_errors[current_step] == undefined )
    {
        duplicates_errors[current_step] = {} ;
        duplicates_errors[current_step]['error_count'] = 0 ;
    }
    
    current_step_win = document.getElementById(step_windows_prefix+String(steps[current_step])) ;
    $('#'+step_windows_prefix+String(steps[current_step])).fadeIn(400) ;
    
    current_step_win.style.display = 'block' ;
    //alert ( current_step_win.style.display );
    recalc_step_arrows ( ) ;
    set_textfield_effects ( current_step_win ) ;
    
    if ( String(steps[current_step]) == 'summary' )
    {
        fill_summary ( ) ;
        is_signup_done = true ;
    }
    else
    {
        is_signup_done = false ;
    }
}

function fill_summary ( )
{
    var summary_data_str = '' ;
    
    var current_title = '' ;
    
    summary_data_str += '<table border="0" cellspacing="0" cellpadding="0">' ;
    
    for ( var i in summary_data )
    {
        if ( summary_data[i]['show'] == 'true' )
        {
            if ( current_title != summary_data[i]['step'] )
            {
                var str = '</table><div class="registration-fields fieldtitle">'+
                          ' <div class="shadow">' + summary_data[i]['step'] + '</div> '+
                          summary_data[i]['step'] +
                          '</div><table border="0" cellspacing="0" cellpadding="0">' ;
                summary_data_str += str ;
                
                current_title = summary_data[i]['step'] ;
            }
            
            if ( summary_data[i]['type'] == 'password' )
            {
                var ast = '' ;
                for ( var z = 0 ; z < summary_data[i]['value'].length-2 ; z++ )
                {
                    ast += '*' ;
                }
                summary_data[i]['value'] = summary_data[i]['value'][0] + ast + summary_data[i]['value'][summary_data[i]['value'].length-1] ;
            }
            
            summary_data_str += '<tr><td style="padding:12px;width:120px;text-align:right;font-weight:bold;vertical-align:middle;">' + summary_data[i]['label'] + '</td>'+
            '<td style="padding:12px;vertical-align:middle;border-left:2px solid #35608F;text-align:left;">' + summary_data[i]['value'] + '</td></tr>' ;
        }
    }
    
    summary_data_str += '</table>' ;
    
    $('#signup_summary_container').attr('innerHTML', summary_data_str ) ;
}

function set_textfield_effects ( el )
{
    var els = el.getElementsByTagName('input') ;
    
    for ( var i in els )
    {
        //alert ( 'here1' ) ;
        if ( els[i].type != undefined && ( els[i].type == 'text' || els[i].type == 'password' ) )
        {
            els[i].onfocus = function ( ) { if ( this.className != 'error_field' ) this.className = 'actived_field' ; }
            els[i].onblur = function ( ) { if ( this.className != 'error_field' ) this.className = 'cfield' ; }
            
            //alert ( 'here' ) ;
            
            $(els[i]).keyup(function(event)
            {
                if ( event.keyCode == 13 )
                {
                    signup_next_step ( ) ;
                }
                else
                {
                    if ( reg_fields_attr[current_step]['check_duplicates'][this.id] == 'true' )
                        signup_check_duplicates ( this, String(this.id+'_darea'), reg_fields_attr[current_step]['id'][this.id] ) ;
                }
            });
        }
    }
    
    var elst = el.getElementsByTagName('textarea') ;
    
    for ( var i in elst )
    {
        if ( elst[i].type == 'textarea' )
        {
            elst[i].onfocus = function ( ) { if ( this.className != 'error_field' ) this.className = 'actived_field' ; }
            elst[i].onblur = function ( ) { if ( this.className != 'error_field' ) this.className = 'cfield' ; }
        }
    }
}

function check_signup_fields ( )
{
    var els = current_step_win.getElementsByTagName('input') ;
    
    var errors = {} ;
    var errors_n = 0 ;
    
    for ( var i in els )
    {
        if ( reg_fields_attr[current_step]['obligatory'][els[i].id] != undefined )
        {
            var error_string = '' ;
            
            if ( reg_fields_attr[current_step]['type'][els[i].id] == 'checkbox' )
            {
                if ( ! els[i].checked )
                    error_string = 'Il campo "' + reg_fields_attr[current_step]['label'][els[i].id] + '" deve essere spuntato.' ;
            }
            
            if ( reg_fields_attr[current_step]['type'][els[i].id] == 'textfield' )
            {
                if ( els[i].value == '' )
                    error_string = 'Il campo "' + reg_fields_attr[current_step]['label'][els[i].id] + '" non pu&ograve; essere vuoto.' ;
            }
            
            if ( reg_fields_attr[current_step]['type'][els[i].id] == 'password' )
            {
                if ( els[i].value == '' )
                    error_string = 'Il campo "' + reg_fields_attr[current_step]['label'][els[i].id] + '" non pu&ograve; essere vuoto.' ;
            }
            
            if ( reg_fields_attr[current_step]['type'][els[i].id] == 'email' )
            {
                if ( els[i].value == '' )
                    error_string = 'Il campo "' + reg_fields_attr[current_step]['label'][els[i].id] + '" non pu&ograve; essere vuoto.' ;
                else if ( ! emailRegExp.test ( els[i].value ) )
                    error_string = 'Il campo "' + reg_fields_attr[current_step]['label'][els[i].id] + '" non &egrave: stato compilato in modo corretto.' ;
            }
            
            if ( error_string == '' )
            {
                var minchar = reg_fields_attr[current_step]['minchar'][els[i].id] ;
                var maxchar = reg_fields_attr[current_step]['maxchar'][els[i].id] ;
                var field_value = String( els[i].value ) ;
                
                if ( minchar > 0 && field_value.length < minchar )
                {
                    error_string = 'Il campo "' + reg_fields_attr[current_step]['label'][els[i].id] + '" deve essere composto di almeno ' + minchar + ' caratteri.' ;
                }
                if ( maxchar > 0 && field_value.length > maxchar )
                {
                    error_string = 'Il campo "' + reg_fields_attr[current_step]['label'][els[i].id] + '" pu&ograve; contenere massimo ' + maxchar + ' caratteri.' ;
                }
            }
            
            if ( error_string == '' )
            {
                if ( reg_fields_attr[current_step]['check_duplicates'][els[i].id] == 'true' )
                {
                //alert ( verified_duplicates[els[i].id] ) ;
                //alert ( verified_duplicates[els[i].id] ) ;
                    if ( verified_duplicates[els[i].id] == undefined )
                    {
                        error_string = 'Bisogna controllare la disponibilita del campo "' + reg_fields_attr[current_step]['label'][els[i].id] + '"' ;
                    }
                    else if ( verified_duplicates[els[i].id] == 'exists' )
                    {
                        error_string = reg_fields_attr[current_step]['label'][els[i].id] + ' &egrave; gia in uso da un altro utente.' ;
                    }
                }
            }
            
            if ( error_string != '' )
            {
                els[i].className = 'error_field' ;
                errors[errors_n] = error_string 
                errors_n++ ;
            }
            else if ( duplicates_errors[current_step][els[i].id] != undefined )
            {
                els[i].className = 'error_field' ;
                errors[errors_n] = duplicates_errors[current_step][els[i].id] 
                errors_n++ ;
            }
            else
            {
                els[i].className = 'cfield' ;
            }
        }
    }
    
    if ( errors_n > 0 )
    {
        show_signup_error ( errors ) ;
        return false;
    }
    
    return true ;
}

function change_step_to ( step_id )
{
    
    if ( duplicates_checking )
    {
        return false ;
    }
    if ( passed_step[step_id] != undefined && step_id != current_step && passed_step[step_id]  )
    {
        if ( step_id != 'summary' && step_id > current_step && ! check_signup_fields ( ) )
            return false ;
        
        go_to_step ( step_id ) ;
    }
    
    return false ;
}

function go_to_step ( step_n )
{
    refresh_summary ( ) ;
    current_step_win.style.display = 'none' ;
    current_step = step_n ;
    show_current_step ( ) ;
}

function refresh_summary ( )
{
    //summary_data
    
    if ( String(steps[current_step]) == 'summary' )
        return false ;
    
    for ( var i in reg_fields_attr[current_step]['id'] )
    {
        var _field_value = '' ;
        
        if ( reg_fields_attr[current_step]['type'][i] == 'datepicker' )
        {
            var dp1 = document.getElementById(i+'_dd') ;
            var dp2 = document.getElementById(i+'_mm') ;
            var dp3 = document.getElementById(i+'_aaaa') ;
            if
            (
                dp1.value != undefined && dp1.value != '0' && dp1.value != '' &&
                dp2.value != undefined && dp2.value != '0' && dp2.value != '' &&
                dp3.value != undefined && dp3.value != '0' && dp3.value != ''
            )
            {
                _field_value = dp1.value + '/' + dp2.value + '/' + dp3.value ;
            }
            else
            {
                _field_value = '<em>N/D</em>' ;
            }
        }
        else
        {
            _field_value = document.getElementById(i) != undefined ? document.getElementById(i).value : '<em>N/D</em>' ;
        }
        summary_data[i] =
        {
            step:reg_fields_attr[current_step]['step_title'][i],
            label:reg_fields_attr[current_step]['label'][i],
            id:reg_fields_attr[current_step]['id'][i],
            show:reg_fields_attr[current_step]['show_in_summary'][i],
            type:reg_fields_attr[current_step]['type'][i],
            value:_field_value
        } ;
    }
}

function show_signup_error ( errors )
{
    var error_string = '<ul>' ;
    
    for ( var i in errors )
    {
        error_string += '<li>' + errors[i] + '</li>' ;
    }
    
    error_string += '</ul>' ;
    
    location.href = '#error_area' ;
    $('#signup_errors').css("display","block") ;
    $('#signup_errors').slideDown(1000);
    $('#signup_errors_list').attr ( 'innerHTML', error_string ) ;
    
    opened_signup_error = true ;
}

function close_signup_error ( )
{
    $('#signup_errors_list').attr ( 'innerHTML', '' ) ;
    $('#signup_errors').fadeOut(400);
    opened_signup_error = false ;
}

function signup_check_duplicates ( field, area, id )
{
    if ( reg_fields_attr[current_step]['type'][field.id] == 'email' )
    {
        if ( ! emailRegExp.test ( field.value ) )
        {
            return ;
        }
    }
    if ( duplicates_timeout != undefined && duplicates_timeout != null )
    {
        clearTimeout(duplicates_timeout) ;
    }
    var f = function ( ) { on_signup_check_duplicates ( field, area, id ) ; } ;
    duplicates_timeout = setTimeout(f, 600, field, area, id) ;
    duplicates_checking = true ;
}

function on_signup_check_duplicates ( field, area, id )
{
    if ( field.value != '' )
    {
        $('#'+area).css("display", "block") ;
        $('#'+area).attr("innerHTML", '<img src="' + fm_images_dir + 'hourglass.png" alt="Loading" />' + reg_fields_attr[current_step]['check_duplicates_message'][field.id]) ;
        //var duplicates_check_handle = new LoadVars ( ) ;
        
        
        
        var duplicates_check_handle = function ( servdata )
        {
            //if ( success )
            //{
                if ( servdata == 'exists' )
                {
                    $('#'+area).attr("innerHTML", '<img src="' + fm_images_dir + 'cross.png" />' + reg_fields_attr[current_step]['check_duplicates_cross'][field.id]) ;
                    
                    duplicates_errors[current_step][field.id] = reg_fields_attr[current_step]['check_duplicates_cross'][field.id] ;
                    duplicates_errors[current_step]['error_count']++ ;
                    verified_duplicates[field.id] = 'exists' ;
                }
                else
                {
                    if ( duplicates_errors[current_step][field.id] != undefined )
                    {
                        duplicates_errors[current_step][field.id] = undefined ;
                        delete duplicates_errors[current_step][field.id] ;
                        duplicates_errors[current_step]['error_count']-- ;
                    }
                    verified_duplicates[field.id] = 'ok' ;
                    $('#'+area).attr("innerHTML", '<img src="' + fm_images_dir + 'tick.png" />' + reg_fields_attr[current_step]['check_duplicates_tick'][field.id]) ;
                }
                
                duplicates_checking = false ;
            //}
        }
        
    $.post(
        fm_base_url+'signup/ba/ba/check_duplicates/id/' + id + '.htm',
        {value_to_check:field.value},
        duplicates_check_handle
    )
        
        //alert ( fm_base_url+'index.php'+fm_getvars+'act=backactions&ba=check_duplicates&id=' + id ) ;
        //duplicates_check_handle.value_to_check = field.value ;
        //duplicates_check_handle.sendAndLoad ( fm_base_url+'signup/ba/ba/check_duplicates/id/' + id + '.htm', duplicates_check_handle, 'POST' ) ;
    }
    else
    {
        $('#'+area).css("display", "none") ;
        $('#'+area).attr("innerHTML", '' ) ;
        duplicates_checking = false ;
    }
}

function check_signup_submit ( )
{
    if ( is_signup_done )
    {
        return true ;
    }
    
    return false ;
}
