        var searchCond = {}; // 検索条件
        var VIEW_COUNT = 6;  // 画面に表示する件数

        // --- 初期化 ---
        $(function(){
            // --- イベントハンドラ ---
            // 検索
            $("#frmSearch").submit(function(){
                searchNew({"keyword": $("#keyword").val()});
                $("#keyword").select();
                return false;
            });

            // 並び替え
            $("#sort > li > a").click(function(){
                searchHistory({"orderby": this.id, "page":1});
            });

            // 前へ
            $("#back").click(function(){
                if (searchCond.page <= 1) return;
                searchHistory({"page": searchCond.page-1});
            });

            // 次へ
            $("#next").click(function(){
                if (searchCond.page*VIEW_COUNT+1 > searchCond.total) return;
                searchHistory({"page": searchCond.page+1});
            });

            // クリア
            $("#clear").click(function(){
                /*$("#history > ul").empty();*/
                $("#videos").empty();
                $("#result").empty();
            });

            // --- 初期処理 ---
            // 検索テキストボックスをフォーカス
            $("#keyword").focus();
        });

        // --- 新規検索 ---
        function searchNew(cond) {
            search({
                "keyword": cond.keyword,
                "page": 1,
                "orderby": "relevance",
                "fromHistory": false
            });
        }

        // --- 履歴検索 ---
        function searchHistory(cond) {
            /*if ($("#history li").size() == 0) return;*/
            search($.extend({}, searchCond, cond, {"fromHistory": true}));
        }

        // --- 検索 ---
        function search(cond) {
            // 検索条件の検査
            if (cond == null) return;
            if (cond.keyword == null || cond.keyword.length == 0) {
                alert("検索キーワードを入力してください。");
                return;
            }

            // 検索取得開始インデックス
            var index = (cond.page-1)*VIEW_COUNT+1;

            // 検索条件の保存
            $.extend(searchCond, cond);

            // サムネイル表示を初期化
            $("#videos").text("");
            $("#videos").append($("<img>").attr("src", '/images/ajax-loader.gif'));

            // ajax通信定義
            $.ajax({
                dataType: "jsonp",
                data: {
                    "vq": cond.keyword,
                    "orderby": cond.orderby,
                    "start-index": index,
                    "max-results": VIEW_COUNT,
                    "alt":"json-in-script"
                },
                cache: true,
                url: "http://gdata.youtube.com/feeds/api/videos",
                success: function (data) {
                    // サムネイル表示をクリア
                    $("#videos").empty();

                    // 検索結果件数を取得・表示
                    searchCond.total = parseInt(data.feed.openSearch$totalResults.$t,10);
                    showTotal(index, searchCond.total);

                    // 検索結果が0件
                    if (searchCond.total == 0) {
                        //alert("検索キーワードにマッチするビデオはありませんでした。");
                        return;
                    }

                    // エントリを参照してサムネイルを生成
                    $.each(data.feed.entry, function(i,item){
                        var group = item.media$group;
                        var vid = group.media$thumbnail[0].url.substring(22,33);

                        $("<li/>")
                            //.append($("<object width='160px'height='130px'/>").append($("<param name='movie'>").attr("value", 'http://www.youtube.com/v/' + vid)))
                            .append($("<param param name='allowFullScreen' value='true'>"))
                            .append($("<param param name='allowscriptaccess' value='always'>"))
                            .append($("<embed name='movie' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='160px'height='130px' />").attr("src", 'http://www.youtube.com/v/' + vid + '?color1=0x402061&amp;color2=0x9461ca'))
                            //.append($("<p/>").append($("<img width='160px'height='130px' style='padding:5px 6px 0 5px;font-size:12px;float:left;cursor:pointer;'/>").attr("src", group.media$thumbnail[0].url)))
                            .append($("<div/>").attr("style", 'height:45px;').append($("<p/>").text(item.title.$t))
                            .append($("<p/>").text("再生回数：" + ((item.yt$statistics == null) ? "0" : item.yt$statistics.viewCount))))
                            //.click(function(){window.open(group.media$player[0].url, null)})
                            .appendTo("#videos");
                    });

                    // 検索履歴に追加
                    /*if (!cond.fromHistory) {
                        addHistory($("#videos img:first").clone(), cond.keyword);
                    }*/
                }
            });
        }

        // --- 検索結果件数表示 ---
        function showTotal(index, total) {
            $("#result").text(
                "全"+total+"件（"+((total == 0) ? 0 : index)+"～"+(index+VIEW_COUNT > total ? total : index+VIEW_COUNT-1)+"件表示）"
            );
        }

        // --- 検索履歴追加 ---
        function addHistory(img, keyword) {
            // (1) 履歴に検索キーワードが存在するか
            var exists = $.grep($("#history li"), function(item, index){
                return ($(item).children(".key").text() == keyword);
            });

            if (exists.length == 0) {    // (2) 存在しない
                $("<li/>")
                    .append(img).append("<br/>")
                    .append($("<span/>").addClass("key").append(keyword))
                    .append(
                        $("<a/>").addClass("del").append("[x]")
                        .click(function(){
                            $(this).parent().remove();
                            if (searchCond.keyword == keyword) {
                                $("#videos").empty();
                                $("#result").empty();
                            }
                        })
                    )
                    .click(function(){searchHistory({"keyword":keyword, "page":1, "orderby":"relevance"});})
                    .prependTo("#history > ul");
            } else {    // (3) 存在する
                $(exists)
                    .prependTo($(exists).parent())
                    .children("img").attr("src", img.attr("src"));
            }

        }


