stripSpace = function()
{
    var aa = $('#asciiart');
    aa.val(aa.val().replace(/\r\n/g, '\n'));
    aa.val(aa.val().replace(/\r/g, '\n'));
    aa.val(aa.val().replace(/[　 ]*\n/g, '\n'));
    aa.val(aa.val().replace(/[　 ]*$/g, ''));
    aa.val(aa.val().replace(/\n*$/, ''));    
}

previewAa = function()
{
    var mask = $(document.createElement('div'));
    mask.attr('id', 'mask');
    
    var preview = $(document.createElement('pre'));
    preview.attr('id', 'preview');
    preview.addClass('aa');
    preview.empty();
    
    if ($('#asciiart').val() == '') {
        alert("アスキーアートを入力してください。");
        return 0;
    }
    
    /* カスなIEのための処理 */
    if($.browser.msie){
        preview.text($('#asciiart').val().replace(/\x0D\x0A|\x0D|\x0A/g,'\n'));
    }else{
        preview.text($('#asciiart').val());
    }
    
    $('body').append(mask);
    
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();
    
    mask.css({'top': 0,
              'left': 0,
              'width':    maskWidth,
              'height':   maskHeight,
              'position': 'absolute',
              'z-index':  9000,
              'background-color': '#000'});
    
    var winH = $(window).height();
    var winW = $(window).width();
    
    $('body').append(preview);
    
    preview.css({'position': 'absolute',
                 'z-index':  9999,
                 'max-width': winW-50,
                 'max-height': winH-50,
                 'border': '3px solid #000'});
                 
    preview.css('top',  winH/2-preview.height()/2);
    preview.css('left', winW/2-preview.width()/2);
    
    mask.click(function(){
        $(this).remove();
        $('#preview').remove();
    });
    
    $(window).resize(function(){
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        
        mask.css({'top': 0,
                  'left': 0,
                  'width':    maskWidth,
                  'height':   maskHeight,
                  'position': 'absolute',
                  'z-index':  9000,
                  'background-color': '#000'});

        var winH = $(window).height();
        var winW = $(window).width();

        preview.css({'position': 'absolute',
                     'z-index':  9999,
                     'max-width': winW-50,
                     'max-height': winH-50,
                     'border': '3px solid #000'});

        preview.css('top',  winH/2-preview.height()/2);
        preview.css('left', winW/2-preview.width()/2);
    });
    
    mask.fadeIn(1000);      
    mask.fadeTo('normal', 0.8);
}

createStripSpaceButton = function()
{
    var button = $(document.createElement('button'));
    button.html('行末空白を削除');
    button.click(stripSpace);
    return button;
}

createPreviewAaButton = function()
{
    var button = $(document.createElement('button'));
    button.html('AAプレビュー');
    button.click(previewAa);
    return button;
}

// ツールチップ表示
viewTooltip = function()
{
    var tooltip = $(document.createElement('p'));
    tooltip.html($(this).attr('title'));
    tooltip.attr('id', 'tooltip');
    $(this).attr('title', '');
    $('body').append(tooltip);
    
    $(this).mouseout(function(){
        $(this).attr('title', tooltip.html());
        tooltip.remove();
    }).mousemove(function(e){
        var x, y;
        if($(window).width() <= e.pageX + tooltip.width() + 50){
            x = e.pageX-tooltip.width()-40;
        }else{
            x = e.pageX+10;
        }
        if($(window).height() <= (e.pageY - $(window).scrollTop()) + tooltip.height() + 50){
            y = e.pageY-tooltip.height()-40;
        }else{
            y = e.pageY+10;
        }
        tooltip.css({
            "top":y+"px",
            "left":x+"px"
        });
    });
}

// 保存用フォーム表示
viewSaveForm = function()
{
    var url = $(this).attr('href');
    
    var post = $(this).parent().parent().parent();
    
    // 非表示
    post.children('.header').hide();
    post.children('.aa').hide();
    post.children('.notes').hide();
    post.children('.footer').hide();
    
    var form = $(document.createElement('div'));
    var loading = $(document.createElement('p'));
    loading.attr('class', 'loading');
    loading.html('読み込み中...');
    
    form.load('/js/form.html');
    
    form.hide();
    post.append(loading);
    post.append(form);

    $.getJSON('/json' + url, function(data){
        if(data.result == 'success'){
            var c = form.children().children();
            
            c.children('.asciiart').val(data.asciiart);
            c.children('.title').val(data.title);
            c.children('.notes').val(data.notes);
            c.children('.tags').val(data.tags.join(' ') + ' ');
            
            c.children('.close').click(function(){
                post.children('.header').show();
                post.children('.aa').show();
                post.children('.notes').show();
                post.children('.footer').show();
                
                form.remove();
                
                return false;
            });
            
            form.show();
            loading.remove();
        }
    });
    
    form.submit(function(){
        var c = form.children().children();
        var d = {
            'asciiart': c.children('.asciiart').val(),
            'title': c.children('.title').val(),
            'notes': c.children('.notes').val(),
            'tags': c.children('.tags').val()
        };
        $.post('/json' + url, d, function(data){
            if(data.result == 'success'){
                // タイトル更新
                post.children('.header').children('a').text(data.title);
                
                // AA更新
                post.children('.aa').text(data.asciiart);
                
                // メモ更新
                post.children('.notes').text(data.notes);
                
                // タグ更新
                post.children('.footer').children('.tags').html('');
                
                for(var i in data.tags){
                    var a = $(document.createElement('a'));
                    a.text(data.tags[i]);
                    a.attr('href', '/' + data.username + '/' + encodeURIComponent(data.tags[i]));
                    
                    if(data.tags[i] == 'system:untagged'){
                        break;
                    }
                    
                    if(i > 0){
                        post.children('.footer').children('.tags').append(', ')
                    }
                    
                    post.children('.footer').children('.tags').append(a);
                }
                
                post.children('.header').show();
                post.children('.aa').show();
                post.children('.notes').show();
                post.children('.footer').show();
                
                form.remove();
            }else{
                alert('error!!');
            }
        }, 'json');
        
        return false;
    });
    
    return false;
}

// AA削除
deletePost = function(){
    $(this).hide();
    
    var desc = $(document.createElement('span'));
    desc.text('ほんとうに削除しますか？');
    
    var yes = $(document.createElement('a'));
    yes.text('削除する');
    yes.attr('href', $(this).attr('href')+'/checked');
    
    $(this).after(yes);
    $(this).after(' ');
    $(this).after(desc);
    
    return false;
}

$(document).ready(function(){
    $('#query').focus();
    
    // ツールボックス
    if ($('#aasave')) {
        var toolbox = $('#toolbox');
        toolbox.empty();
        toolbox.append(createStripSpaceButton());
        toolbox.append(createPreviewAaButton());
    }
    
    // サイドバー周り
    $('.toggle').each(function(){
        var cookieName = $(this).attr('id');
            
        if ($.cookie(cookieName) == 'off') {
            $(this).removeClass('on');
        }
    });
    
    // toggleまわり
    $('.toggleHead').click(function(){
        var toggle = $(this).parent('.toggle');
        var cookieName = toggle.attr('id');
        
        if (toggle.hasClass('on')) {
            toggle.removeClass('on');
            $.cookie(cookieName, 'off', {path: '/', expires: 30});
        } else {
            toggle.addClass('on');
            $.cookie(cookieName, 'on', {path: '/', expires: 30});
        }
    });
    
    // 削除
    $('.delete').click(deletePost);
    
    // 保存
    $('.save').click(viewSaveForm);
    
    // ツールチップ表示
    $('.tags.cloud').children().children().mouseover(viewTooltip);
    
    // メッセージバー
    $('#messageBar').click(function(){
        $(this).fadeOut('slow');
    });

    // 特殊文字変換
    /*$('pre.aa').dblclick(function(){
        $(this).html($(this).html().replace(/&amp;#(\d+);/ig, "&#$1;"));
    });*/
});