$(document).ready(function(){
    
    $('.smartfinder').change(function() {
        
        var _index = $('.smartfinder').index($(this));
        var _toSend = $('.smartfinder:lt('+(_index+1)+')');
        var _data = _toSend.fieldSerialize();
        
        toUpdate = $('.smartfinder:gt('+_index+')');
        toUpdate.css('visibility', 'hidden');
        toUpdate.parent().find('.loadinfo').css('visibility','visible');
        
        $.ajax({
            url: $('form[name=SmartFinder] input[name=smartresponse]').val(),
            processDataBoolean: false,
            data: _data,
            dataType: 'json',
            success: formReload
        });
    })

    function formReload(response, statusText){

        for(i=0; i<response.itens.length; i++){

            r_item = response.itens[i];
            //alert("Recebendo " + item.paramName);

            toUpdate.each(function(){
                
                if($(this).attr('name') != r_item.paramName){
                    //alert(item.paramName + " não vai atualizar");
                    return;
                }
                
                //alert(item.paramName + "  vai atualizar !!!");
                
                select = $('[name='+r_item.paramName+']');

//                if(select.length <= 0){
//                    alert('Não encontrou:' + item.paramName);
//                    continue;
//                }

                hasSelected = select.find('option:selected');
                if(hasSelected.length > 0){
                    selected_value = hasSelected.val();
                }
                else{
                    selected_value = '';
                }
                selected_value = '';

                optionsHtml = '';
                for(op=0; op < r_item.options.length; op++){
                    option = r_item.options[op];
                    selectedAttr = selected_value == option.value ? 'selected="selected"' : '';
                    optionsHtml += '<option class="smartoption" value="'+ option.value + '" ' + selectedAttr +'>'+ option.label +'</option>';
                }
                
                select.find('option.smartoption').remove();
                select.find('option.loadinfo').remove();
                select.append(optionsHtml);
                select.css('visibility', 'visible');
                select.parent().find('.loadinfo').css('visibility','hidden');                
            })
        }
    }
})
