var $dlg_signup = $('#dlg_signup'),$captcha = $('#captcha'),$verify_img = $('#verify_img'),$agree = $('#agree'),$accept_msg = $('#accept_msg');
var $login_name = $('#login_name'),$password = $('#password'),$repassword = $('#repassword'),$first_name = $('#first_name'), $last_name = $('#last_name'), $job_title = $('#job_title'), $email = $('#email');
var $phone = $('#phone'),$organization_name = $('#organization_name'), $website = $('#website'), $country = $('#countrycode'), $time_zone = $('#timezone');

var $check_login_name = $('#check_login_name'),$check_password = $('#check_password'),$check_first_name = $('#check_first_name'), $check_last_name = $('#check_last_name'), $check_job_title = $('#check_job_title'), $check_email = $('#check_email');
var $check_phone = $('#check_phone'),$check_organization_name = $('#check_organization_name'), $check_website = $('#check_website'), $check_country = $('#check_countrycode'), $check_time_zone = $('#check_timezone');
var $signup = $('#signup'), $check_signup = $('#check_signup'),$btn_backhome = $('#btn_backhome'),$btn_side_signup = $('#btn_side_signup'),$dlg_signup_ok = $('#dlg_signup_ok,#overlay_ok');
var arr_country = {},arr_timezone = {};
var captcha_url = $captcha.attr('src').match(/\S*.securimage\//)[0];

$dlg_signup = $( "#dlg_signup" ).dialog({
    modal: true,
    width: 940,
    autoOpen : false,
    closeText: 'hide',
    position: ['center','top'],
    show: 'blind',
    hide: 'blind',
    closeOnEscape: false,
    open: function(event, ui) { 
    },
    close: function(event, ui) { 
        enable_btns();
    }
});

$('#btn_signup').add($btn_side_signup).click(function(){
    resetform();
    $dlg_signup.dialog('open');
});

$btn_backhome.click(function(){
    if($(this).hasClass('disable')){
        return;
    }
    $dlg_signup.dialog('close');
});
$captcha.click(function(){
    $captcha.attr('src',captcha_url + 'securimage_show.php?' + Math.random());
    return false;
});

var stringLength = function(str) {
    var length = 0;
    for(var i = 0;i < str.length;i++) {
        var charCode = str.charCodeAt(i);
        if (charCode < 0x007f) {
            length += 1;
        } else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {
            length += 2;
        } else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {
            length += 3;
        } else if (charCode > 0xffff) {
            length += 4;
        }
    }
    return length;
};

var rangeLength = function(string, maxLength, minLength){
    if(!minLength){
        minLength = 0;
    }
    return minLength <= stringLength(string) && stringLength(string) <= maxLength;
};

var isName = function(name) {
    var pattern = /^[a-z][\w-]{3,29}$/i;
    if (!pattern.exec(name)){
        return false;
    }
    return true;
};

var isPassword = function(password) {
    var pattern = /[\w-]{6,50}$/i;
    if (!pattern.exec(password)){
        return false;
    }
    return true;
};

var isEmail = function(mail) {
    var pattern = /^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    if (!pattern.exec(mail)){
        return false;
    }
    return true;
};
var isPhoneNum = function(num){
    var pattern = /^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,30})+$/;
    if (!pattern.exec(num)){
        return false;
    }
    return true;
};
var escape = function(str) {
    if (!str){
        return null;
    }
    var character = {'<':'&lt;','>':'&gt;','"':'&quot;','\'':'&apos;','\n':'<br/>'};
    str = str.replace(/(<|>|'|"|\n)/g,function(regexp){
         return character[regexp];
    });
    return str;
}
var isUrl = function(str){
    var pattern = /^(http(s?)\:\/\/){0,1}[a-zA-Z0-9\-\._]+(\.[a-zA-Z0-9\-\._]+){1,}(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$/i;
    if (!pattern.exec(str)){
        return false;
    }
    return true;
};

var showMsg = function(obj,message){
    obj.next().html(message).show();
}
var showError = function(obj,message){
    obj.next().html(message).show();
    obj.addClass('ipt_signup_error');
}

var clearError = function(obj){
    obj.next().html('').hide();
    obj.removeClass('ipt_signup_error');
}

var clearAllError = function(){
    $('#signup_form input').removeClass('ipt_signup_error');
    $('.show_error').html('').hide();
}
var _$btns = $('#btn_signup_sub,#btn_return,#btn_backhome,#btn_accept');
function disable_btns(){
    _$btns.addClass('disable');
}
function enable_btns(){
    _$btns.removeClass('disable');
}
$('#btn_cancel').click(function(){
    if($(this).hasClass('disable')){
        return;
    }
    $dlg_signup.dialog('close');
});
$('#btn_next').click(function(){
    if($(this).hasClass('disable')){
        return;
    }
    if(!checkSignUp()){return;}
    disable_btns();
    $.get(captcha_url+'check.php?code='+$verify_img.val(),function(res){
        enable_btns();
        if(res == 0){
            showError($verify_img,'Please input correct verify code!');
        }else{
            $check_login_name.html(escape($login_name.val()));
            $check_password.html(escape($password.val()));
            $check_first_name.html(escape($first_name.val()));
            $check_last_name.html(escape($last_name.val()));
            $check_job_title.html(escape($job_title.val()));
            $check_email.html(escape($email.val()));
            $check_phone.html(escape($phone.val()));
            $check_organization_name.html(escape($organization_name.val()));
            $check_website.html(escape($website.val()));
            $check_country.html(arr_country[$country.val()]);
            $check_time_zone.html(arr_timezone[$time_zone.val()]);
            
            $signup.hide();
            $check_signup.show();
        }
        $captcha.click();
    });
});
$('#btn_return').click(function(){
    if($(this).hasClass('disable')){
        return;
    }
    $signup.show();
    $check_signup.hide();
})
$('#btn_signup_sub').click(function(){
    if($(this).hasClass('disable')){
        return;
    }
    disable_btns();
    var url = '/wp-content/themes/asteria/regedit.php',data = '';
    data = 'username=' + encodeURIComponent($login_name.val());
    data = data + '&password=' + encodeURIComponent($password.val());
    data = data + '&first_name=' + encodeURIComponent($first_name.val());
    data = data + '&last_name=' + encodeURIComponent($last_name.val());
    data = data + '&email=' + encodeURIComponent($email.val());
    data = data + '&job_title=' + encodeURIComponent($job_title.val());
    data = data + '&phone=' + encodeURIComponent($phone.val());
    data = data + '&organization=' + encodeURIComponent($organization_name.val());
    data = data + '&website=' + encodeURIComponent($website.val());
    data = data + '&country=' + encodeURIComponent($country.val());
    data = data + '&timezone=' + encodeURIComponent($time_zone.val());
    $.post(url,data,function(res){
        if(res && res.success){
             $dlg_signup_ok.show();
        }else{
             enable_btns();
             if(res.error){
                 alert(res.error);
             }else{
                 alert('regedit fail');
             }
        }
    },'json')
})
$('#btn_signup_ok').click(function(){
    $dlg_signup_ok.hide();
    enable_btns();
    $dlg_signup.dialog('close');
});
var checkData = {
    login_name : function($login_name){
        if (!$login_name.val()) {
            showError($login_name,'Login name is required!');
            return false;
        } else if(!isName($login_name.val())){
            showError($login_name,'Login name must be 4-30 Alphanumeric!');
            return false;
        }
        return true;
    },
    password : function($password,$repassword){
        if (!$password.val()) {
            showError($password,'Password is required!');
            return false;
        } else if(!isPassword($password.val())){
            showError($password,'Password must be 6-50 Alphanumeric!');
            return false;
        } else if($repassword.val() && $password.val()!== $repassword.val()){
            showError($repassword,'Password is not matched!');
            return false;
            }
        return true;
    },
    first_name : function($first_name){
        if (!$first_name.val()) {
            showError($first_name,'First name is required!');
            return false;
        } else if(!rangeLength($first_name.val(),30)){
            showError($first_name,'First name length must be less 30!');
            return false;
        }
        return true;
    },
    last_name : function($last_name){
        if (!$last_name.val()) {
            showError($last_name,'Last name is required!');
            return false;
        } else if(!rangeLength($last_name.val(),30)){
            showError($last_name,'Last name length must be less 30!');
            return false;
        }
        return true;
    },
    job_title : function($job_title){
        if (!$job_title.val()) {
            showError($job_title,'Job title is required!');
            return false;
        } else if(!rangeLength($job_title.val(),50)){
            showError($job_title,'Job title length must be less 50!');
            return false;
        }
        return true;
    },
    email : function($email){
        if (!$email.val()) {
            showError($email,'Email is required!');
            return false;
        }else if(!isEmail($email.val())){
            showError($email,'Please input a correct Email!');
            return false;
        }else if(!rangeLength($email.val(),100)){
            showError($email,'Email length must be less 100!');
            return false;
        }
        return true;
    },
    phone : function($phone){
        if (!$phone.val()) {
            showError($phone,'Phone is required!');
            return false;
        }else if(!isPhoneNum($phone.val())){
            showError($phone,'Please input a correct phone number!');
            return false;
        }else if(!rangeLength($phone.val(),30)){
            showError($phone,'Phone number length must be less 30!');
            return false;
        }
        return true;
    },
    organization_name : function($organization_name){
        if (!$organization_name.val()) {
            showError($organization_name,'Organization name is required!');
            return false;
        }else if(!rangeLength($organization_name.val(),255)){
            showError($organization_name,'Organization length must be less 255!');
            return false;
        }
        return true;
    },
    website : function($website){
        if ($website.val()) {
            if(!rangeLength($website.val(),255)){
                showError($website,'Website length must be less 255!');
                return false;
            } else if(!isUrl($website.val())){
                showError($website,'Please input a correct Website!');
                return false;
            }
        }
        return true;
    },
    country : function($country){
        if (!$country.val()) {
            showMsg($country,'Country is required!');
            return false;
        }
        return true;
    },
    time_zone : function($time_zone){
        if (!$time_zone.val()) {
            showMsg($time_zone,'Time zone is required!');
            return false;
        }
        return true;
    },
    verify_img : function($verify_img){
    	if (!$verify_img.val()) {
            showError($verify_img,'Please input verify code!');
            return false;
        }
        return true;
    }
};

var signup = function(){
    $login_name.focus(function(){
        clearError($login_name);
    });
    
    $password.focus(function(){
        clearError($password);
    });
    $repassword.focus(function(){
        clearError($repassword);
    });
    
    $first_name.focus(function(){
        clearError($first_name);
    });
    
    $last_name.focus(function(){
        clearError($last_name);
    });
    
    $job_title.focus(function(){
        clearError($job_title);
    });
    
    $email.focus(function(){
        clearError($email);
    });
    
    $phone.focus(function(){
        clearError($phone);
    });
    
    $organization_name.focus(function(){
        clearError($organization_name);
    });
    
    $website.focus(function(){
        clearError($website);
    });
    
    $country.focus(function(){
        clearError($country);
    });
    
    $time_zone.focus(function(){
        clearError($time_zone);
    });
    $verify_img.focus(function(){
        clearError($verify_img);
    })
    $('#timezone option').each(function(i,n){
        if(n.value){
            arr_timezone[n.value] = n.text;
        }
    });
    $('#countrycode option').each(function(i,n){
        if(n.value){
            arr_country[n.value] = n.text;
        }
    });
    $agree.click(function(){
        if($(this).attr('checked')) {
            $accept_msg.show();
            $(this).attr('checked',false);
        } else {
            $accept_msg.hide();
            $(this).attr('checked',true);
        }
    });
};
signup();

var resetform = function(){
    $('#signup_form').find('input').val('');
    $('#signup_form').find('select').val('');
    clearAllError();
    $agree.attr('checked',true).prop('checked',true);
    $accept_msg.hide();
    $signup.show();
    $check_signup.hide();
};

function checkSignUp(){
    var flag = true;
    if(!$agree.attr('checked')){
        flag = false;
    }
    if(!checkData.login_name($login_name)){
        flag = false;
    }
    if(!checkData.password($password,$repassword)){
        flag = false;
    }
    if(!checkData.first_name($first_name)){
        flag = false;
    }
    if(!checkData.last_name($last_name)){
        flag = false;
    }
    if(!checkData.job_title($job_title)){
        flag = false;
    }
    if(!checkData.email($email)){
        flag = false;
    }
    if(!checkData.phone($phone)){
        flag = false;
    }
    if(!checkData.organization_name($organization_name)){
        flag = false;
    }
    if(!checkData.website($website)){
        flag = false;
    }
    if(!checkData.country($country)){
        flag = false;
    }
    if(!checkData.time_zone($time_zone)){
        flag = false;
    }
    if(!checkData.verify_img($verify_img)){
        flag = false;
    }
    return flag;
};


