(function () {

var MONTH_NAMES = [
    'Jan', 'Feb', 'Mar', 'Apr',
    'May', 'Jun', 'Jul', 'Aug',
    'Sep', 'Oct', 'Nov', 'Dec'];

var g_offset = 0;
var g_tbtimer = null;
var g_articles;

function ps_create_article(o) {

    var e = $($('#tmpl-photostream-article').text());

    e.css({
        'background-image': 'url(' + o.grid_image + ')'
    });
    e.addClass(o.grid_css);
    e.find('h2').text(o.grid_type);
    if (!o.is_new) {
        e.find('p.newIcon').remove();
    }
    e.find('p.text').text(o.title);
    e.find('p.date').text(o.date);
    e.find('a').attr('href', o.permalink);
    return e;
}

function ps_create_element(o) {
    var e = $($('#tmpl-photostream-entry').text());

    var size = [o.grid.w, o.grid.h];
    var w = size[0] * kGridSize - kMargin;
    var h = size[1] * kGridSize - kMargin;

    var img_container = e.find('div.image');

    var img_link = img_container.find('a');
    img_link.attr({
        href: o.url
    });

    var img = img_container.find('img');
    var imgsrc, imgw, imgh;
    if (1 == size[0] && 1 == size[1]) {
        imgsrc = o.image.s.url;
        imgw = o.image.s.w;
        imgh = o.image.s.h;
    }
    else if (3 < size[0] || 3 < size[1]) {
        imgsrc = o.image.l.url;
        imgw = o.image.l.w;
        imgh = o.image.l.h;
    }
    else {
        imgsrc = o.image.m.url;
        imgw = o.image.m.w;
        imgh = o.image.m.h;
    }

    var scale = Math.max(w / imgw, h / imgh);
    imgw = Math.ceil(imgw * scale);
    imgh = Math.ceil(imgh * scale);

    var imgx = w * 0.5 - imgw * 0.5;
    var imgy = h * 0.5 - imgh * 0.5;

    img_container.css({
        left: imgx,
        top: imgy
    });

    img.attr({
        'src': imgsrc,
        'width': imgw,
        'height': imgh
    });

    e.css({
        'width': w,
        'height': h
    });

    var nm = e.find('div.namecard');
    nm.css({
        'top': h - 20,
        'width': w
    });

    var screen_name = o.tweet.from_user;
    nm.html('<img src="' + o.tweet.profile_image_url + '" width="20" height="20" align="absmiddle" />' +
        '&nbsp;<a href="http://twitter.com/' + screen_name + '">' + screen_name + '</a>');

    if (o.url.match(/[\.\/]youtube\.com/)) {
        e.append($('<a class="video_play" target="_blank"></a>'));
        e.find('.video_play').css({
            left: (w * 0.5) - (101 * 0.5),
            top: (h * 0.5) - (101 * 0.5)
        }).attr({
            href: o.url
        });
    }

    e.mouseenter(function () {
        clearTimeout(g_tbtimer);

        var pos = e.offset();

        var padding = 20;
        var tbw = Math.max((kGridSize * 2) - kMargin + padding, e.width() + padding);

        var left = pos.left + (e.width() * 0.5) - (tbw * 0.5);
        if ($(window).width() < (left + tbw)) {
            left = pos.left - tbw + e.width() + (padding * 0.5);
        }
        else if (left < 0) {
            left = pos.left - (padding * 0.5);
        }

        left = pos.left - (padding * 0.5);
        if ($(window).width() < (left + tbw)) {
            left = pos.left - tbw + e.width() + (padding * 0.5);
        }

        var tb = $('#photostream-tweetbox');

        tb.attr('data-id', o.id);

        var twurl = 'http://twitter.com/#!/' + o.tweet.from_user;
        tb.find('.tweet-date').attr('href', twurl + '/status/' + o.tweet.id_str);
        var date = new Date(o.tweet.created_at);
        tb.find('.tweet-date').text(MONTH_NAMES[date.getMonth()] + ' ' + date.getDate());
        tb.find('.tweet-reply').attr('href',
            //'http://twitter.com/intent/tweet?in_reply_to=' + o.tweet.id_str);
            'http://twitter.com/?status=' +
            encodeURIComponent(' RT @' + o.tweet.from_user + ' ' + o.tweet.text));
        tb.find('.tweet-retweet').attr('href',
            'http://twitter.com/intent/retweet?tweet_id=' + o.tweet.id_str);
        if (1 < o.count_tw) {
            tb.find('.tweet-count').text(o.count_tw + 'RTs');
        }
        else {
            tb.find('.tweet-count').text('RT');
        }

        var tbt = tb.find('.text').html(
            '<a href="http://twitter.com/' + o.tweet.from_user + '" target="_blank">' +
            '<img src="' + o.tweet.profile_image_url + '" width="30" height="30" align="left" /> ' +
            '</a>' +
            '<a href="http://twitter.com/' + o.tweet.from_user + '" target="_blank" class="screen_name">' +
            o.tweet.from_user + '</a> ' +
            twttr.txt.autoLink(o.tweet.text) + '<br clear="all" />');
        tb.css({
            width: tbw,
            left: left,
            top: -10000
        }).show();

        tb.css({
            top: pos.top - tb.height() - padding + 30
        });
    }).mouseleave(function () {
        clearTimeout(g_tbtimer);
        g_tbtimer = setTimeout(function () {
            $('#photostream-tweetbox').hide();
        }, 100);
    });

    return e;
};

$(function () {
    //
    var ps = $('#photostream');
    ps.oreoregrid({
        margin: kMargin,
        columnWidth: kColumnWidth,
        sideMargin: kSideMargin
    });

    $(window).bind('smartresize.oreoregrid', function() {
        ps.oreoregrid('arrange');
    }).smartresize();

    //
    $('#photostream-tweetbox').mouseenter(function () {
        clearTimeout(g_tbtimer);
    }).mouseleave(function () {
        clearTimeout(g_tbtimer);
        g_tbtimer = setTimeout(function () {
            $('#photostream-tweetbox').hide();
        }, 100);
    });

    if (window.g_control_tool !== undefined && window.g_control_tool) {
        ps_install_control_tool();
    }

    //
    var fixels = [];

    ps.find('div.fixed').each(function () {
        fixels.push($(this));
    });

    ps.oreoregrid('append_fixed', fixels);
    ps.oreoregrid('arrange');

    //
    $.ajax({
        url: 'http://lovecars.jp/cms2/photostream-json.php',
        dataType: 'jsonp',
        jsonpCallback: '__photostream'
    }).success(function (data) {
        g_articles = data;

        ps_load_more();
    });
});

function ps_load_more() {
    if (0 < g_offset) {
        _gaq.push(['_trackPageview', '/index.html?page=' + g_offset]);
    }

    $.ajax({
        url: 'http://www2.lovecars.jp/data/result_1_' + g_offset + '.js',
        dataType: 'jsonp',
        jsonpCallback: '__photostream'
    }).success(function (data) {
        g_offset++;

        ps_append_box(data);

        $(window).scroll(ps_autopagerize);
    });
}

function ps_autopagerize() {
    var w = $(window);
    var top = w.scrollTop();
    var h = $(document.body).height();
    if (h - (w.height() * 2) < top) {
        ps_load_more();
        w.unbind('scroll', ps_autopagerize);
    }
}

function ps_append_box(data) {
    //$.benchmark.start();  

    var ldata = [];
    var sdata = [];
    $(data).each(function (idx, o) {
        if (o.grid.w == 1 && o.grid.h == 1) {
            sdata.push(o);
        }
        else {
            ldata.push(o);
        }
    });
    data = null;

    var els = [];

    var i = 0;

    $(ldata).each(function (idx, o) {
        if (i % 5 == 0) {
            var a = g_articles.shift();
            if (a != null) {
                els.push(ps_create_article(a));
            }
        }

        els.push(ps_create_element(o));

        if (i % 1 == 0) {
            if (0 < sdata.length) {
                els.push(ps_create_element(sdata.shift()));
            }
        }

        i++;
    });

    $(sdata).each(function (idx, o) {
        els.push(ps_create_element(o));
    });

    //$.benchmark.end();

    var ps = $('#photostream');
    ps.oreoregrid('append_box', els);
    ps.oreoregrid('arrange');
}

})();


