/**
 * ドラッグ＆ドロップでキーワードをウォッチキーワードに登録する
 */
(function() {

var disable_link = 0;

var doAdd = function(draggable, dropzone) {

    var keyword_list = Array();

    // 新しいキーワードを配列の先頭に追加
    var a = draggable.firstDescendant();
    var keyword = a.innerHTML;
    keyword = keyword.strip();
    if (keyword.indexOf('<') >=0 || keyword.indexOf('>') >=0) {
        return;
    }
    keyword_list.push(keyword);

    // 残りのキーワードを配列に追加
    $$('#my_watchkeyword_list .dropzone a').each(function(a) {
        var keyword = a.innerHTML;
        keyword = keyword.strip();
        keyword_list.push(keyword);
    });

    // コールバック
    var callback = function(response) {
        eval('var data = [' + response.responseText + '];');
        var li_list = $$('#my_watchkeyword_list .dropzone');
        // ウォッチキーワードのリフレッシュ
        for (var i = 0; i < li_list.length; i++) {
            var a = li_list[i].firstDescendant();
            if (a) {
                a.remove();
            }
            if (data[i]) {
                a = new Element('a', {href: '/search/list?keyword=' + encodeURIComponent(data[i]) + '&genrekey=1'}).update(data[i]);
                li_list[i].insert(a);
            }
        }
    }

    // 接続
    var myAjax = new Ajax.Request('/index.php', {
        method: 'get',
        parameters: 'action_watchkeyword_update=true' +
                    '&watchkeyword=' + encodeURIComponent(keyword_list.join(' ')),
        onComplete: callback
    });
}

// ドラッグ
var doDrop = {
    hoverclass: 'dragenter',
    onDrop: function(draggable, dropzone) {
        draggable.parentNode.setStyle({zIndex: 0});
        draggable.setStyle({left: 0, top: 0});
        
        // ドラッグ場所がウォッチキーワードならキーワードの追加処理を行う
        // ウォッチキーワードは最大10件とする
        if (dropzone.parentNode.parentNode.id == 'my_watchkeyword_list') {
            var a_list = $$('#my_watchkeyword_list .dropzone a');
            if (a_list.length < 10) {
                doAdd(draggable, dropzone);
            }
        }
    }
}

// ドラッグ
var doDrag = {
    onStart: function(draggable, dropzone) {

        disable_link = true;
        
        // ウォッチキーワードの登録が10件:メッセージを表示する
        var a_list = $$('#my_watchkeyword_list .dropzone a');
        if (a_list.length >= 10) {
            if ($('menubox') == null) {
                new Insertion.Bottom(document.body,
                "<div id='menubox' style='position: absolute;border: 1px solid;padding: 3px;width: 170px;height: 20px;background-color: #ffffff;'>"+
                '登録できるのは10件までです'+
                "</div>");
            }
            Element.show('menubox');
            var obj = $('my_watchkeyword_list');
            var value = Position.cumulativeOffset(obj);
            var left = value[0];
            var top  = value[1];
            Element.setStyle('menubox', {'left': left, 'top': top + 10});
        }
        
        // ウォッチキーワードの登録が0件:説明を消す
        else if (a_list.length == 0) {
            var li_list = $$('#my_watchkeyword_list .dropzone');
            li_list[0].update('');
            for (var i = 0; i < li_list.length; i++) {
                li_list[i].style.display = 'block';
            }
        }
    },
    starteffect: function(draggable) {
        draggable.parentNode.setStyle({zIndex: 1});
        draggable.setStyle({opacity: 0.5});
    },
    endeffect: function(draggable) {
        draggable.parentNode.setStyle({zIndex: 0});
        draggable.setStyle({opacity: 1.0}).setStyle({left: 0, top: 0});
        if ($('menubox') != null){
            Element.hide('menubox');
        }
    }
}

// クリック
var doClick = function() {
    var a = this.firstDescendant();
    var href = a.readAttribute('href');
    if (disable_link) {
        disable_link = false;
    } else {
        location.href = href;
    }
}

// マウスオーバー
var doMouseOver = function() {
    if (this.firstDescendant()) {
        // 画像説明が出ている時もごみ箱が出てしまったのでこの場合を除く
        var a_list = $$('#my_watchkeyword_list .dropzone a');
        if (a_list.length != 0) {
	        if ($('trash_box').getStyle('visibility') == 'hidden') {
	            $('trash_box').setStyle({'visibility':'visible'});
	        }
	        $('trash_box').setStyle({'top':this.offsetTop + 6});
	        $('trash_box').setStyle({'left':this.offsetLeft + 143});
	        $('trash_box').setAttribute('keyword', this.firstDescendant().innerHTML);
	    }
    }
}

document.observe('dom:loaded', function() {

    // ウィンドウサイズを変えるとごみ箱が変更前の位置に表示されたままになり
    // 変なので、変更された場合はごみ箱を非表示にする
    window.onresize = function() {
        var element = $('trash_box');
        if (element) {
            element.setStyle({'visibility':'hidden'});
        }
    };

    // ドロップ対象
    $$('.dropzone').each(function(element) {
        Droppables.add(element, doDrop);
    });

    // ドラッグ対象
    $$('.draggable').each(function(element) {
        element.observe('click', doClick);
        new Draggable(element, doDrag);
    });
    
    // ウォッチキーワードに登録が無い場合は説明（画像）を表示する
    var a_list = $$('#my_watchkeyword_list .dropzone a');
    if (a_list.length == 0) {
        var li_list = $$('#my_watchkeyword_list .dropzone');
        for (var i = 0; i < li_list.length; i++) {
            if (i == 0) {
                // １段目に画像を加える
                var div = new Element('div').update('<img src="/img2/sidebar/blank.gif">');
                li_list[0].insert(div);
            } else {
                // 2段目以降を非表示にする
                li_list[i].style.display = 'none';
            }
        }
    }

    // ウォッチキーワードの列にマウスを合わせたらごみ箱を表示する
    $$('#my_watchkeyword_list .dropzone').each(function(element) {
        element.observe('mouseover', doMouseOver);
    });

    // ごみ箱がクリックされたらその部分のキーワードを表示する
    $('trash_box').observe('click', function() {
    
	    // コールバック
	    var callback2 = function(response) {
            document.location.reload();
	    }
	
	    // 接続
	    if (confirm('ウォッチキーワード『' + $('trash_box').getAttribute('keyword') + '』を削除しますか？')) {
		    var myAjax = new Ajax.Request('/index.php', {
		        method: 'get',
		        parameters: 'action_watchkeyword_update2=true' +
		                    '&keyword=' + encodeURIComponent($('trash_box').getAttribute('keyword')),
		        onComplete: callback2
		    });
		}
    });
});

}());

