/*
 * class FormValidator
 * 
 * config format to validate 
 * 	[
 * 		{id:'personal-nickname', type: 'text', label:'Nickname', check:['required']},
 *   	{name:'shop[category_id][]', type: 'multiCheckbox', label:'Category', check:['required']}
 * 	]
 * version 0.1 
 */
FormValidator = function(){
	this.errors = new Array();
	this.valid = true;
}
FormValidator.prototype = {
	
	
	//errors : [],
	translations : {
	    is_required : 'обязательное поле',
	    form_error: 'Ошибки'
	},
	
    validate : function(config)
    {
        for(var i = 0; i < config.length; i++){
        	for(var y = 0; y < config[i].check.length; y++){
	        	switch(config[i].check[y]){
	        		case 'required':
	        			this.checkRequired(config[i]);
	        			break;
	        	}
        	}
        }
        
        
        
        if(!this.valid){
            this.alertErrors();
            return false;
        }
        else{
        	return true;
        }
    },
    
    checkRequired : function(fieldConfig)
    {
    	switch(fieldConfig.type)
    	{
    		case 'text':
    		case 'textarea':
    		case 'password':
    		case 'captcha':
    		case 'select':
    			this.isNotEmpty(fieldConfig);
    			break;
    		case 'multicheckbox':
    			this.isCheckedMultiCheckbox(fieldConfig);
    			break;
    	}
    },
    
    alertErrors : function()
    {
    	var errorsStr = new String();
    	for(var i in this.errors){
    		errorsStr += this.errors[i] + "<br/>";
    	}
    	//alert(errorsStr);
    	/*if(!$('#form_validation_errors_dialog').length){
    		$(document.body).append('');
    	}*/
    	$('#form_validation_errors_dialog p').html(errorsStr);
    	$('#form_validation_errors_dialog').dialog({
    		title: this.translations.form_error,
    		width: 312,
    		draggable: false,
			autoOpen:false,
			modal:true,
			resizable: false,
			close: function(){
				jQuery('#form_validation_errors_dialog').dialog('destroy');
			}
    	});
    	$('#form_validation_errors_dialog').dialog('open');
    	$('#form_validation_errors_dialog_ok').click(function(){
    		$('#form_validation_errors_dialog').dialog('close');
    	});

    },
    
    isNotEmpty : function(fieldConfig){
        var field = document.getElementById(fieldConfig.id);
        if(!field.value.length){
            this.valid = false;
            this.errors.push('<b>' + fieldConfig.label + '</b> '+ this.translations.is_required);
        }
    },

    isCheckedMultiCheckbox : function(fieldConfig){
        var checked = false;
        var fields = document.getElementsByTagName('input');
        
        for(var i = 0; i < fields.length; i++){
            if((fields[i].type == 'checkbox') && (fields[i].name == fieldConfig.name) && fields[i].checked){
                checked = true;
            }
        }
        if(!checked){
            this.valid = false;
            this.errors.push('<b>' + fieldConfig.label + '</b> '+ this.translations.is_required);
        }
    }

}

