if (typeof $ != "function") {
    var $ = function(id) {
        return document.getElementById(id);
    }
}

if (location.href.match(/\/youtube\/tag\/([-_.!~*()a-zA-Z0-9;:@+$,%]+)$/)) {
    $("q").value = decodeURI(RegExp.$1).replace(/\+/, " ");
}

var per_page = 100;
var timer = undefined;
var scrollValue = { "ie":0, "other":0 };
var user_id = undefined;
var type = '0';
var q = '';

var owner_id = {};
var target;

var ua = '';
if (window.navigator.userAgent.match(/MSIE/)) {
 ua = 'ie';
}

if (GBrowserIsCompatible()) {
 var map = new GMap2(document.getElementById("map"));
 map.removeMapType(G_SATELLITE_MAP);
 map.removeMapType(G_HYBRID_MAP);
 map.removeMapType(G_NORMAL_MAP);
}

function doHopScroll() {
 if (timer) {
  clearInterval(timer);
 }
 scrollValue.ie = -1;
 scrollValue.other = -1;
 autoScroll();
 timer = setInterval('autoScroll()', 1750);
}

function doSmoothScroll(direction) {
    if (timer) {
        clearInterval(timer);
    }
    scrollValue.ie = 0.06;
    scrollValue.other = 0.03;
    if (direction == "left") {
        scrollValue.ie *= -1;
        scrollValue.other *= -1;
    }
    autoScroll();
    timer = setInterval('autoScroll()', 1);
}

function stopScroll() {
 clearInterval(timer);
}

function doYoutubeSearch() {
 $('search-button').disabled = true;
 return callYoutube();
}

function callYoutube() {
    if (timer) {
        clearInterval(timer);
    }

    var script = document.createElement("script");
    script.charset = 'UTF-8';
    script.type = 'text/javascript';

    var developerId = "ZalPorIoEWo";
    var tag = $("q").value.replace(/[ 　]+/g, "+").replace(/^\+/, "").replace(/\+$/, "");
    var startIndex = 1;
    var maxResults = 50;
    var apiUrl = [
        "http://gdata.youtube.com/feeds/api/videos?vq=" + encodeURIComponent(tag),
        "start-index=" + startIndex,
        "max-results=" + maxResults
    ].join("&");

    script.src = "http://api.fkoji.com/xml_to_json.php?url=" + encodeURIComponent(apiUrl) + "&callback=callbackYoutube";
    var head = document.getElementsByTagName("head");
    head[0].appendChild(script);

    $('this_url').innerHTML = '<a href="/youtube/tag/'+encodeURI(tag).toLowerCase()+'">URL of this slide show</a>';
    $('go_youtube').innerHTML = '<a href="http://www.youtube.com/results?search_query='+encodeURI(tag)+'&search=Search" target="_blank">Open this results by Youtube</a>';
    return false;
}

function autoScroll() {
    // IEだとスムーズに動かないので
    if (ua == 'ie') {
        map.panDirection(scrollValue.ie, 0);
    } else {
        map.panDirection(scrollValue.other, 0);
    }
}

var title = {};
var second = {};
var videoUrl = {};
var imageUrl = [];
function callbackYoutube(json) {
    json = eval(json);
    $('search-button').disabled = false;
    if (!json.entry || !json.entry.length) {
        alert('No Movies. / 条件に一致する動画はありません。');
        return false;
    }

    // register keyword
    if ($("this_url").firstChild.href) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.charset = "utf-8";
        script.src = "http://map.fkoji.com/youtube/script/keyword.php?k=" + encodeURIComponent($("q").value.replace(/[ 　]+/g, " ").replace(/^\ /, "").replace(/\ $/, ""));
        var head = document.getElementsByTagName("head");
        head[0].appendChild(script);
    }

    var video = json.entry;
    if (!video.length) {
        video = [video];
    }
    for (var i = 0; i < video.length; i++) {
        video[i]['media:group']['media:thumbnail'][0]['url'].match(/^http:\/\/(i\.ytimg\.com|img\.youtube\.com)\/vi\/([^\/]+)\/.+\.jpg$/);
        var id = RegExp.$2;
        title[id] = video[i]['title']['_content'];
        second[id] = video[i]['media:group']['yt:duration']['seconds'];
        videoUrl[id] = video[i]['link'][0]['href'];
        imageUrl[i] = video[i]['media:group']['media:thumbnail'][0]['url'];
    }
    
    map.setCenter(new GLatLng(33, (Math.random() * 180) % 180), 10);
    var layer = G_NORMAL_MAP.getTileLayers()[0];
    layer.getTileUrl = function(tile, zoom) {
        var len = video.length;
        return imageUrl[(tile.x + tile.y) % len];
    };
    layer.getOpacity = function() {
        return 1;
    };
    map.addOverlay(new GTileLayerOverlay(layer));
}

var selectedVideo = {
    isSelected: false,
    video: null
};

function clickHandler(event) {
    event = event || window.event;
    target = event.target || event.srcElement;
    if (target.src) {
        if (target.src.match(/^http:\/\/img\.youtube\.com\/vi\/([^\/]+)\/.+\.jpg$/)
            || target.src.match(/^http:\/\/i\.ytimg\.com\/vi\/([^\/]+)\/.+\.jpg$/)) {
            var id = RegExp.$1;
            $("detail-title").innerHTML = title[id];
            $("detail-second").innerHTML = ' [' + second[id] + 'seconds]' ;
            $("detail-url").innerHTML = videoUrl[id];
            if (selectedVideo.video) {
                selectedVideo.video.style.border = "none";
                selectedVideo.video.style.width = "256px";
                selectedVideo.video.style.height = "256px";
            }
            target.style.border = "2px solid #f33";
            target.style.width = "252px";
            target.style.height = "252px";
            selectedVideo.isSelected = true;
            selectedVideo.video = target;
            $("play-video").disabled = false;
        }
    }
}

function play() {
    if (selectedVideo.isSelected) {
        if (selectedVideo.video.src.match(/^http:\/\/img\.youtube\.com\/vi\/([^\/]+)\/.+\.jpg$/)
            || selectedVideo.video.src.match(/^http:\/\/i\.ytimg\.com\/vi\/([^\/]+)\/.+\.jpg$/)) {
            var iframe = document.createElement("iframe");
            iframe.src = "http://www.youtube.com/?v=" + RegExp.$1;
            with(iframe.style) {
                width = "99%";
                height = "550px";
            }
            $("iframe-container").appendChild(iframe);
            $("iframe-container").style.display = 'block';
            return;
        }
    }
}

function iframeClose() {
 var ic = $("iframe-container");
 ic.removeChild(ic.lastChild);
 ic.style.display = 'none';
}

function setIframePosition() {
    var w = document.body.clientWidth;
    var left = (w - 800) / 2;
    $("iframe-container").style.left = left + "px";
}

window.onload = callYoutube;
$("map").onclick = clickHandler;
setIframePosition();

