var scrollVal = 0;
var isTouch = false;

var last = {}, end = false;
var allPosts = new Array();
var blockCount = 0; 
var distanceToEnd;
var makingBlock = false;

$(function(){
    LoadNextBlock()
});

function onContentLoaded()
{
    resize();
    $(window).resize(resize);
    $('nav').draggable({containment: "body"}).addTouch();

    setTimeout(function(){$('nav').fadeIn('slow')}, 3000);

    $('.blog').live('click', blogItemClick);

    enableMouseWheel();
    $(window).scroll(onScroll);

    activateTextResizing();

    isTouch = Modernizr.touch;
    if(!isTouch) $('nav').css('position','fixed');

    $('#webshop').insertBefore($('.item')[3 + Math.round(Math.random() * 18)]);
    
    //** Make share button link
    $('#detail .share').click(function(e){
        e.preventDefault();
        FB.ui({method: 'feed',
                display: 'popup',
                link: 'http://lafilledo.com',
                picture: 'http://lafilledo.com' + $('#detail img').attr('src'),
                description: $('#detail h1').text()
                });
    });
    
    setInterval(resize, 1500);
    
    //** Check for deeplink
    if(window.location.hash)
    {
        if(window.location.hash.indexOf('/detail/') > -1)
        {
            var id = window.location.hash.split('/').reverse()[0];
            showDetail(id);
        }
    }
}

function activateTextResizing()
{
	var maxH = 400;
  	var size = function(){
    	var winH = document.body.clientHeight || window.innerHeight; 
	    document.body.style.fontSize = ( (winH/maxH)*60 ) + "%";
  	}
      
  	window.onresize = size;
  	size();815
}

function onScroll()
{
    if(blockCount > 0 && !makingBlock)
    {
        distanceToEnd = $(document).width() - $(window).width() - $(window).scrollLeft();
        if(distanceToEnd < 1100) LoadNextBlock();
    }
    
    if(isTouch){
            var diff = $(window).scrollLeft() - scrollVal;
            scrollVal = $(window).scrollLeft();
            $('nav').css('left', $('nav').position().left + diff);
            return false;
    }
}	

//*** Main loading functions
function LoadNextBlock()
{
    makingBlock = true;
    
    if (end === true) return;

    $.getJSON(postUrl, last)
        .success(function(posts) {
            if (posts.length < 20) {
                end = true;
            } else {
                var l = posts.pop();
                last = {
                    start: l['unix-timestamp'],
                    id: l['_id']
                };
            }
            drawPosts(posts);
       });
}

function drawPosts(posts)
{
    var block = $("<div class='timeBlock'/>");               

    for(var i = 0; i < posts.length; i++)
    {
            var post = posts[i];
            allPosts.push(post);

            if(post.type == "photo"){
                var thumbUrl = "/post/" + post.id + "/attachment/" + post.photos.small;
                var incomingHtml = $(post['photo-caption']);
                incomingHtml.find('em').remove();        
                var title = strip(incomingHtml.html());
                var newItem = $("<a class='item blog'/>")
                                           .attr('href','#/detail/' + post.id)
                                           .append(
                                             $("<img/>")
                                                .attr("src", thumbUrl)
                                                .attr("width",post["width"])
                                                .attr("height",post["height"])
                                                //.attr("alt", title)
                                           ).append(
                                                 $("<div class='alt'/>").append($('<span/>').text(title))
                                           );
                //if(i == 5) newItem.addClass("itemBig");
                block.append(newItem);
            }
            
            if(post.type == "video")
            {
                var title = strip(post['video-caption']);
                var newItem = $("<a class='item blog video'/>")
                                           .attr('href','#/detail/' + post.id)
                                           .append(
                                             $(post["video-player"])
                                           );
                //if(i == 5) newItem.addClass("itemBig");
                block.append(newItem);
            }
    }

    if (!Modernizr.touch) $('img').bind('mousedown',preventDefault);

    $('#main').append(block)
    
    
    
    if(blockCount == 0)
    {
        setTimeout(function(){
                block.find('.item').each(function(i){
                    $(this).delay(i * 30).fadeIn('slow');
                });
                blockCount++;

        }, 1000);
    }
    else
    {
        resize();
        block.find('.item').each(function(i){$(this).show();});
        blockCount++;        
    }
    
    resize();
    
    $('#spacer').width($(document).width());
    
    
    if(blockCount == 0)
    {
        onContentLoaded();
    }
    makingBlock = false;
    
    var date = posts[0]['date-gmt'].split(' ')[0].split('-').reverse().join(' ').replace(' 20',' ');
    block.find('.item:first').prepend($("<div class='date'/>").text(date));
}



function findPostById(id)
{
    for(var i = 0; i < allPosts.length; i++)
        if(allPosts[i].id == id)
            return allPosts[i];
    
    return false;
}

var count = 0;
var scrollVal;

function resize()
{
    var xOffset = [0,0,0,0];
    var yOffset = 0;
    var yPos = 0;
    var gridCount = 0;

    var obj;
    var h;
    var w;
    var ratio;
    
    $('.timeBlock').each(function(j){
        gridCount = 0;
        $(this).find('.item').each(function(i){
            gridCount++;
            yPos = gridCount % 4;

            obj = $(this);

            if(!h)
            {
                h = obj.height();
                $('.item img, .item object, .item embed, .item iframe').height(h);
            }

            if(obj.hasClass("itemBig"))
            {
                obj.find('img, object').height(h * 2);
                gridCount++;
                xOffset[yPos + 1] = xOffset[yPos] + obj.find('img, object, embed').width();
            }
            
            w = obj.find('img').width();
            obj.width(w);
            
            if(obj.hasClass('video'))
            {
                ratio = parseInt(obj.find('object, iframe').attr('width'))/parseInt(obj.find('object, iframe').attr('height'));
                w= h * ratio;
                obj.width(w);
                obj.find('object, embed, iframe').width(w);
            }
            
            if(yPos == 1) yOffset = 0;
            
            
            obj.css('left', xOffset[yPos]);
            xOffset[yPos] += w;

            obj.css('top', yOffset);
            yOffset += Math.floor(obj.height());
        });

        //** Ok, end of the block, now reset the positions for the next block
        xOffset.sort(function(a,b){return b - a});
        var largest = xOffset[0] + 20;
        xOffset = [largest,largest,largest,largest];
    })

    if(h < 120) $('nav').css("visibility","hidden");
    else $('nav').css("visibility","visible");
}

//---------- Detail Popup
function blogItemClick()
{
    showDetail($(this).attr('href').split('/').reverse()[0]);
}

function showDetail(postId)
{       
    $.getJSON("/post/" + postId).success(function(post) {
        var incomingHtml = $(post['photo-caption']);
        $('#detail p.content').empty();
        var s = incomingHtml.find('em').map(function() {
            return $(this).html();
        }).get().join('');
        $('#detail p.content').html(s);
        incomingHtml.find('em').remove();        
        var title = strip(incomingHtml.html());
        
        $('#detail h1').text(title);
        if(title == undefined || title == "") $('#detail h1').hide();
        else $('#detail h1').show();

        var dateParts = post.date.split(' '); 
        $('#detail h2 span').text([dateParts[2], dateParts[1], dateParts[3]].join(' '));
        $('#detail img').attr('src',"/post/" + post.id + "/attachment/" + post.photos.large);

        $('#detail .webshop').hide();
        if(post.tags && post.tags.indexOf('webshop') > -1)
        {
            $('#detail .webshop').show();
            $('#detail .webshop').attr('href', post["photo-link-url"] != "" ? post["photo-link-url"] : "http://shop.lafilledo.com/webshop/");
        }

        //Animate in
        $('#detail').hide()
        $('#detail').css('left', getScrollVal() + $(window).width());
        $('#overlay').click(hideDetail);

        scrollVal = getScrollVal();

        $('html, #main').css('overflow-x','hidden');	
        $('html, body').scrollLeft(scrollVal);

        if(isTouch) $('.item.video').hide();

        $('nav').fadeOut('slow');

        $('#overlay').css('left', scrollVal);

        if($.browser.msie) $('#overlay').show();
        else $('#overlay').fadeIn('slow');

        $('#detail').show();
        $('#detail').width($(window).width() / 2);
        $('#detail').css('left',scrollVal + $(window).width());
        $('#detail').animate({left: (scrollVal + $(window).width() / 2)}, 1000);

        $('#close').animate({opacity: 1}, 1000);

        resize();
        $(window).resize(resizeDetail);

        if(document.addEventListener)
                document.addEventListener("touchmove", preventDefault, false);

        disableMouseWheel();
    });
}

function hideDetail()
{
    $('#close').css({opacity: 0});

    $('nav').fadeIn('slow');

    if($.browser.msie) $('#overlay').hide();
    else $('#overlay').fadeOut('slow');

    $(window).unbind('resize', resizeDetail);

    if(document.removeEventListener)
            document.removeEventListener("touchmove", preventDefault, false);

    $('#overlay').unbind('click', hideDetail);

    resize();
    enableMouseWheel();

    $('#detail').animate({left: getScrollVal() + $(window).width()}, 400, function(){
        $('html, #main').css('overflow-x','visible');
        $('html, body').scrollLeft(scrollVal);
        $('#detail').hide();
        if(isTouch) $('.video').show();
    });
}

function resizeDetail()
{
    var scrollVal = getScrollVal()
    $('#overlay').css('left', scrollVal);
    $('#detail').width($(window).width() / 2);
    $('#detail').css('left', (scrollVal + $(window).width() / 2));
}

function getScrollVal()
{
	var scrollVal = $('html').scrollLeft();
	if(scrollVal == 0) scrollVal = $('body').scrollLeft();
	return scrollVal;
}

//--------------- Stop default behaviour handler
function preventDefault(event) {if(event.preventDefault) event.preventDefault();}

//--------------- Mousewheel horizontal scroll FIX
function enableMouseWheel()
{
	if ("onmousewheel" in document.body) document.body.onmousewheel = mouseWheelEvt;
	else window.addEventListener("DOMMouseScroll", mouseWheelEvt, false);
}

function disableMouseWheel()
{
	if ("onmousewheel" in document.body) document.body.onmousewheel = null;
	else window.removeEventListener("DOMMouseScroll", mouseWheelEvt, false);
}


var mouseWheelEvt = function (e)
{
    var event = e || window.event;
    //alert(event.detail);
    if (document.body.doScroll) document.body.doScroll(event.wheelDelta>0?"left":"right");
    else if(event.wheelDelta)
    {
        if ((event.wheelDelta || event.detail) > 0) {
            var scrl = getScrollVal() - 80;
            $('html, body').scrollLeft(scrl);
        }
        else {
            var scrl = getScrollVal() + 80;
            $('html, body').scrollLeft(scrl);
        }
    }
    else
    {
        if ((event.wheelDelta || event.detail) > 0) {
            var scrl = getScrollVal() + 80;
            $('html, body').scrollLeft(scrl);
        }
        else {
            var scrl = getScrollVal() - 80;
            $('html, body').scrollLeft(scrl);
        }   
            
    }
    
    onScroll();
    return false;
}

//--------------- Helper Functions
function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}


