$(document).ready(function(){
    
    if ($('.form .open-box :radio:checked').size() > 0){
        var index = $('.form .open-box :radio').index($('.form .open-box :radio:checked'))
        $('.form .open-box .open').not(':eq('+ index +')').hide();
    }
    else{
        $('.form .open-box .open').hide();
    }
    
    $('.form .open-box :radio').click(function(){
        var index = $('.form .open-box :radio').index($(this))
        $('.form .open-box .open').filter(':eq('+ index +')').show();
        $('.form .open-box .open').not(':eq('+ index +')').hide();
    });
    
    
    $('.fill-color').each(function(){
        var el = $(this);
        var fill = $('<select></select>');
        var row = $('<p class="row"></p>')
        el.before(row);
        el.hide();
        
        //fill
        $('.fill', el).each(function(){
            fill.append('<option>'+ $(this).text() +'</option>');
        });
        
        // ROW CONSTRUCT
        row.append('<span class="number bold">1. </span>')
        row.append('<span class="fill"></span>')
        $('.fill', row).append($('tr:first-child td.fill', el).attr('title'));
        $('.fill', row).append(fill);
        row.append($('tr:first-child span.color', el).clone());
        row.append('<a class="add" href="#"><img src="http://www.madekop.cz/img/ico-thick.png" alt="-" /></a>');
        
        var number = function(){
            for(var i = 0; i < $('.js-door p.row').size(); i++){
                $('.js-door p.row:eq('+i+') .number').text((i+1)+'. ');
            }  
        }
        
        var change = function(){
            var index = $('option', this).index($('option:selected', this));
            var copy = $('tr:eq('+index+') span.color', el).clone();
            $(this).parents('.row').children('.color').replaceWith(copy);
        };
        
        var remove = function(){
            $(this).parents('.row').remove();
            number();
            return false;
        }
        
        var add = function(){
            var clone = $(this).parents('.row').clone();
            el.before(clone);
            $(clone).prev().find('.add').unbind('click').removeClass('add').addClass('remove').html('<img src="http://www.madekop.cz/img/ico-cross.png" alt="-" />').bind('click', remove);
            $('.add', clone).bind('click', add);
            var index = $(clone).prev().find('.fill option').index($(clone).prev().find('.fill option:selected'));
            $('.fill select option:eq('+ index +')', clone).attr('selected', true);
            $('.fill select', clone).bind('change', change);
            number();
            return false;
        };
        
        $('.add', row).bind('click', add);
        fill.bind('change', change);

        
        
    });
});
