var check = function(pattern, check_uncheck) {
    if(['check', 'uncheck'].indexOf(check_uncheck) == -1) {
        check_uncheck = 'check';
    }
    
    var inputs = $(pattern).find(':checkbox');
    
    if(check_uncheck == 'check') {
        $(pattern).find('li').attr('class', 'active');
        $(inputs).attr('checked', 'checked');
    }
    else {
        $(pattern).find('li').attr('class', 'inactive');
        $(inputs).removeAttr('checked');
    }
}

$(function() {
    if($('#sortable').length) {
        $('#currency_list').before('<a href="#" onclick="check(\'#currency_list\');return false;">Check all</a> / <a href="#" onclick="check(\'#currency_list\', \'uncheck\');return false;">Check none</a>');
        
        $('#currency_list').sortable({
            'axis': 'y',
            'scroll': true,
            'tolerance': 'pointer',
            'update': function(e, ui) {
                var elements = $('#currency_list').sortable('toArray');
                var cls = 'odd';
                
                for(var i=0;i<elements.length;i++) {
                    $('#'+elements[i]).find('input[name^="sort"]').val(i+1);
                }
            }
        });
        
        $('#currency_list :checkbox').click(function() {
            $(this).parent().parent().toggleClass('inactive');
        });
    };
    
    if($('.currency').length) {
        $('.currency').dblclick(function() {
            var old_html = $(this).html();
            var value = $(this).find('.amount').html() + ' ' + 
                $(this).find('.code').html();
            
            $(this).html('<form method="get" action="/get_curr/"><div><input type="text" name="curr" value="' + value + '"></div></form>');
            $(this).find('input').focus();
            
            $(this).find('input').blur(function() {
                if($(this).val() != value) {
                    $(this).parent().parent().submit();
                }
                else {
                    $(this).parents('.currency').html(old_html);
                };
            });
        });
    };
});
