        var searchCond = {}; // 検索条件
        var VIEW_COUNT = 6;  // 画面に表示する件数
        // --- 初期化 ---
        $(function(){
            // --- イベントハンドラ ---
            // 検索
            $("#frmSearch").submit(function(){
                searchNew({"keyword": $("#keyword").val()});
                $("#keyword").select();
                return false;
            });

            // 並び替え
            $("#sort > 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 searchHistory(cond) {
            if ($("#history li").size() == 0) return;
            search($.extend({}, searchCond, cond, {"fromHistory": true}));
        }

        // --- 検索 ---
        function search(cond) {
            // 検索取得開始インデックス
            var index = (cond.page-1)*VIEW_COUNT+1;

            // 検索条件の保存
            $.extend(searchCond, cond);

            // サムネイル表示を初期化
            $("#videos").text("Loading...");

            // ajax通信定義
            $.ajax({
                dataType: "jsonp",
                data: {
                    "orderby": cond.orderby,
                    "author": "pandadraftwebmaster",
                    "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 video_info = $("<div/>").addClass("video_info")
	                                        .append($("<span/>").addClass("title").text("投稿者　：")).append(item.author[0].name.$t).append('<br/>')
	                                        .append($("<span/>").addClass("title").text("投稿日　：")).append(item.published.$t.replace(/^(\d{4})-(\d{2})-(\d{2}).*/, "$1年$2月$3日")).append('<br/>')
	                                        .append($("<span/>").addClass("title").text("再生回数：")).append(((item.yt$statistics == null) ? "0" : item.yt$statistics.viewCount)).append('<br/>')
	                                        .append($("<span/>").addClass("title").text("説明　　：")).append(item.content.$t).append('<br/>')

	                    // 埋め込み用ビデオのURL
	                    var video_url = group.media$content == null ? '' : group.media$content[0].url;

	                    // サムネイルを生成
	                    $("<div/>").addClass("thumbnail")
	                        .append($("<img/>").attr("src", group.media$thumbnail[0].url).addClass("thumbnail_img")).append("<br/>")
	                        .append($("<span/>").addClass("title").text(item.title.$t)).append("<br/>")
	                        .append($("<span/>").addClass("info").text("公開日：" + item.published["$t"].split("T")[0])).append("<br/>")
	                        .append($("<span/>").addClass("info").text("再生回数：" + ((item.yt$statistics == null) ? "0" : item.yt$statistics.viewCount)))
	                        // クリックしたらプレーヤーを表示
	                        .click(function(){
	                            if (video_url == '') {
	                                // プレーヤーページ（Youtube）
	                                window.open(group.media$player[0].url, null)
	                            } else {
	                                // プレーヤー（ダイアログ）
	                                showPlayer({
	                                    url  : video_url,
	                                    title: item.title.$t,
	                                    info : video_info
	                                });
	                            }
	                        })
	                        .draggable({helper: 'clone', zIndex: 10})  // ドラッグを可能にする
	                        .appendTo("#videos");
                    });

                    // 検索履歴に追加
                    if (!cond.fromHistory) {
                        addHistory($("#videos img:first").clone(), cond.keyword);
                    }
                }
            });
        }

        // --- 検索結果件数表示 ---
        function showTotal(index, total) {
            $("#result").text(
                ((total == 0) ? 0 : index)
                + " - "
                + (index+VIEW_COUNT > total ? total : index+VIEW_COUNT-1)
                + " / "
                + total
                + "件"
            );
        }

        // --- 検索履歴追加 ---
        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"));
            }
        }
        
        // --- プレイヤー表示 ---
        function showPlayer(options){
	        $("<div/>")
	            .append('<object width="425" height="355"><param name="movie" value="'+ options.url +'"></param><param name="wmode" value="transparent"></param><embed src='+ options.url +' type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></embed></object>')
	            .append('<br/>')
	            .append(options.info.show())
	            .dialog({
	                title: options.title,
	                width: 640,
	                height: 480,
	                close: function(){$(this).parents(".ui-dialog").remove()
	            }
	        });
    	}

