var cf_validation = new Array();

function performCustomFieldValidation(errors) {
	for (var i = 0; i < cf_validation.length; i++ ) {
	    var field   = cf_validation[i];
        var failed  = false;
        
        // If the id doesn't exist we probably dealing with radio buttons
        // whos values don't need to be validated. Still need to check if
        // mandatory though
        if ($(field.id) == null) {
            if (field.mandatory=='t') {
                var fields = $$('input[name="' + field.id + '"]');
                var checked = false;
                for (var j = 0; j < fields.length; j++ ) {
                    if (fields[j].checked) {
                        checked = true;
                    }
                }
                if (!checked) {
                    failed = true;
                }
            } else {
                continue;
            }
        } else {
    	    if (field.mandatory!='t' && $F(field.id) == '') {
    	       continue;
    	    }
	    
    	    var vld = field.validation.split(":");
    	    if (vld[0] == 'is_regex' && !field.rx_fixed) {
    	        field.rx_fixed = true;
    	        field.validation = vld[0];
    	        field.regex = new RegExp(vld.slice(1, vld.length).join(""));
    	    }
	    
    	    if ($(field.id) && ($F(field.id) != '' || field.mandatory == 't')) {
        	    switch (field.validation) {
        	        case 'is_int':
        	            if (!$F(field.id).match(/^(-|\+)?\d+$/)) {
        	                failed = true;
    					}
        	            break;
	        
        	        case 'is_float':
        	            if (!$F(field.id).match(/^(-|\+)?(\d+)?\.\d+$/)) {
        	                failed = true;
    					}
        	            break;
	        
        	        case 'is_numeric':
            	        if (!$F(field.id).match(/^(-|\+)?(\d)?\.?\d+$/)) {
        	                failed = true;
    					}
        	            break;
	        
        	        case 'is_email':
        	            if (!$F(field.id).match(/^[-+_.'a-zA-Z0-9]+@[-.a-zA-Z0-9]+$/)) {
        	                failed = true;
    					}
        	            break;
    	            
        	        case 'is_date':
        	            if (!$F(field.id).match(/^(\d{4}-\d{2}-\d{2}|\d{1,2}\/\d{1,2}\/\d{4})$/)) {
        	                failed = true;
    					}
        	            break;
	        
        	        case 'is_regex':
        	            if (!field.regex.match($F(field.id))) {
        	                failed = true;
    					}
        	            break;   
        	    }
            }           
	    }
	    
	    if (failed) {
	        if (field.message) {
                message = field.message + "\n"
			} else {
          		message = field.description + " invalid \n";
			}
        
            if (typeof(errors.addError) == 'function') {
                errors.addError(field.description, message);
            } else {
                errors.err_count++;
                errors.err_msg += " - " + message + "\n";
            }
        }
	}
}

 
function categoryChange() {		
	$('custom_fields_div').update("");
	new Ajax.Request("customfields.html", {
		parameters: { fa: 'ajax_custom_fields_html', category_id: $F('category_id') },
		onSuccess: function (transport) {
			var response = transport.responseText.evalJSON();
			
			$('custom_fields_div').update(response.html);
			cf_validation = new Array();
			if (response.jscript != "") {
				eval(response.jscript);
			}
		}
	});
}

function categoryChangeForAdvancedSearch() {		
	$('advanced_search_fields').update("");
	
	if ($('advanced_search').checked) {
		new Ajax.Request("customfields.html", {
			parameters: { fa: 'ajax_custom_fields', category_id: $F('category') },
			onSuccess: function (transport) {
				var res = transport.responseText.evalJSON(true);
				var h = new Hash(res.custom_fields);
				
				h.each(function (val, key) {
					var item = val[1];
					
					if (item.searchable == 't') {
					    var elt = get_html_input_node(item);
					    $('advanced_search_fields').appendChild(elt);
					}
				});
				
			}
		});
	}
}

function get_html_input_node(item) {
    if (item.visible != 't')
        return false;
    
    var wrapper = Builder.node('div', {id:'span_cf_' + item.name, className:'searchrow'});
    wrapper.appendChild(Builder.node('label', {htmlFor:'cf_' + item.name}, item.description + ': '));
    
    
	switch(item['type']) {
		case 'textfield':
		    wrapper.appendChild(Builder.node('input', {type:'text', name:'cf_' + item.name, id:'cf_' + item.name, className: 'searchfield'}));
			break;

		case 'textarea':
		    wrapper.appendChild(Builder.node('textarea', {name: 'cf_' + item.name, id: 'cf_' + item.name, className: 'textarea'}));
			break;

		case 'checkbox':
		    wrapper.appendChild(Builder.node('input', {type: 'checkbox', name: 'cf_' + item.name, id: 'cf_' + item.name, value: 't', className: 'checkbox'}));
			break;
			
		case 'yesno':
		    wrapper.appendChild(Builder.node('input', {type: 'radio', name: 'cf_' + item.name, id: 'cf_' + item.name + '_t', value: 'yes', className: 'radio'}));
		    wrapper.appendChild(Builder.node('span', "Yes"));
		    wrapper.appendChild(Builder.node('input', {type: 'radio', name: 'cf_' + item.name, id: 'cf_' + item.name + '_t', value: 'no', className: 'radio'}));
		    wrapper.appendChild(Builder.node('span', "No"));
			break;
		
		case 'radio':
			var opts = item.options.split("\n");
			opts.each(function(v) {
			    wrapper.appendChild(Builder.node('input', {type: 'radio', name: 'cf_' + item.name, id: 'cf_' + item.name + '_' + v, value: v, className: 'radio'}));
			    wrapper.appendChild(Builder.node('span', v));
			});
			break;
			
		case 'selection':
			var opts = item.options.split("\n");
			var select = Builder.node('select', {name: 'cf_' + item.name, id: 'cf_' + item.name, className: 'searchdrop'});
			
			var first = true;
			opts.each(function (v) {
			    if (first || item.value == "")
			        var opt = Builder.node('option', {value: v.strip(), selected:"selected"}, v.strip());
			    else
			        var opt = Builder.node('option', {value: v.strip()}, v.strip());
			    select.appendChild(opt);
			});
			
			wrapper.appendChild(select);
			break;
		
		default:
		    break;
	}
	
	return wrapper;
}

function toggleEnabledCustomField (id, state) {
    // toggle the state
	state = state == 't' ? 'f' : 't';

    $('fa').value       = 'toggle_f';
	$('id').value       = id;
	$('state').value    = state;
	$('custom_field_form').submit();
	
    return true;
}

function deleteCustomField (id) {
    var msg = "Are you sure you wish to delete this field and all associated data?";
    if (confirm(msg)) {
        $('fa').value       = 'delete_f';
    	$('id').value       = id;
    	$('custom_field_form').submit();
    }
}

