Form Functions

$(document).ready(function(){
    form_funs.init();

});

var form_funs = {
    get_form: function(){
        return $('#myform');
    },
    init: function(){
        var wrap = this;
        var $form = wrap.get_form();

        $form.find('.bt_submit').on('click', function(e){
            if(wrap.validate_form($form) == false){
                return false;
            }

            if(wrap.validate_password() == false){
                return false;
            }

            if(confirm(err_lang.submit_confirm)){
                $form.submit();
            }
        });
    },
    validate_form: function($form){
        var wrap = this;
        var result = true;

        $form.find('input[type="text"], input[type="radio"], input[type="checkbox"], textarea, select').each(function(index){
            var $field = $(this);
            var field = $field[0];
            var field_type = field.type.toLowerCase();
            var tag_name = field.tagName.toLowerCase();


            //console.log($field.attr('name') + ': ' + $field.prop('required'));
            if(typeof $field.attr('required') == 'undefined' || $field.attr('required') == false){
                return;
            }
            

            if(field_type == 'text' || tag_name == 'textarea'){
                value = $field.val();
                if(value == ''){
                    var msg = '請輸入 ' + wrap.get_label($field);
                    wrap.warning(msg);
                    $field.focus();
                    result = false;
                    return false;
                }
            }else if(tag_name == 'select'){
                value = $field.val();
                if(value == '' || value == "0"){
                    var msg = '請選擇 ' + wrap.get_label($field);
                    wrap.warning(msg);
                    $field.focus();
                    result = false;
                    return false;
                }
            }else{//Checkbox or radio
                var name = $field.attr('name');
                var $checked = $form.find('input[name="' + name + '"]:checked');
                if($checked.size() == 0){
                    var msg = '請選擇 ' + wrap.get_label($field);
                    wrap.warning(msg);
                    $field.focus();
                    result = false;
                    return false;
                }
            }
        });

        //console.log(result);
        return result;
    }, 
    get_label: function($field){
        var label = $field.attr('title');
        //console.log(label);

        if(typeof label == 'undefined' || label == null){
            return '必填欄位';
        }else{
            return label;
        }
    }, 
    warning: function(msg){
        alert(msg);
    }, 
    reset: function(){
        var wrap = this;
        var $form = wrap.get_form();
        $form[0].reset();
    }
}