///////////////////
//// SPOILER
//////////////

function loading() {
    $("#loader").fadeIn();
}

function doneLoading() {
    // remove loader
    $("#loader").fadeOut("slow");
    // show new spoiler
    // sometimes the resize trigger below is fired before this begins showing, so call it again at the end
    $(".all, .backdrop").not(".old").fadeIn("slow", function() {$(window).triggerHandler("resize")});
    // remove old spoiler
    $(".all.old, .backdrop.old").fadeOut("slow", function() {$(this).remove()});
    // resize new spoiler
    $(window).triggerHandler("resize");
}

function load_spoiler(title, year, spoiler, author, backdrop) {
    old = $(".all, .backdrop").addClass("old");

    all = $("<div></div>").addClass("all").hide().appendTo($("body"));
    title_box = $("<div></div>").addClass("spollywood title").appendTo(all);
    $("<span></span>").addClass("title-text").text(title).appendTo(title_box);
    $("<span></span>").addClass("year").text("(" + year + ")").appendTo(title_box);
    spoiler_box = $("<div></div>").addClass("spollywood spoiler").appendTo(all);
    $("<span></span>").addClass("spoiler-text").text(spoiler).appendTo(spoiler_box);
    $("<span></span>").addClass("author").text("-" + author).appendTo(spoiler_box);

    if (backdrop != null) {
        $("<img>").attr("src", backdrop).addClass("backdrop").hide().prependTo($("body")).load(doneLoading);
    } else {
        doneLoading();
    }
}

function load_state_spoiler() {
    if (History.getState()["title"] == "")
        // sometimes we get this call for the original page, without the user actually going back/forward
        // in this case, we haven't set the "title" yet, so it's empty
        return;

    loading();
    
    data = History.getState()["data"];
    load_spoiler(data["movie_name"], data["movie_year"], data["spoiler"], data["author"], data["movie_bg"]);

    // trigger event
    $(document).trigger('spoiler', [ data["key"], data["pending"] ]);
}

function load_random() {
    loading();

    $.ajax({
        url: "/api/random",
        context: document.body,
        success: function(data) {
            var title = "Spollywood - " + data["movie_name"];
            var url = "/" + data["id"];

            if (data["id"] == History.getState()["data"]["id"]) {
                if (data["pending"]) {
                    // the only spoiler left pending, no more random!
                    doneLoading();
                } else {
                    // try again
                    load_random();
                }
            } else {
                // load
                History.pushState(data, title, url);
            }
        }
    }).error(ajax_error_handler);

    return false;
}

function ajax_error_handler(event) {
    // TODO figure out if it's a quota error
    if (event["status"] == 0) {
        // zero means the user just stopped the request
        ajax_error_handler_close();
        return;
    }

    text = '<p class="error">Oops! Something broke <small>[code=' +
        event["status"] +
        ']</small>... Most of the time the hero dies, this time it was our server. Please try again.</p>';
    $.fancybox(text, {afterClose: ajax_error_handler_close});
}

function ajax_error_handler_close() {
    doneLoading();
}

$(document).ready(function() {
    $(".menuajax").fancybox(
        {
            autoSize:true, fitToView:true, maxWidth:'80%', maxHeight:'80%',
            afterShow:function () {
                $("#add-movie-name").focus();
            }
        }
    );
    load_social_buttons();

    if (History.enabled) {
        // only enable ajax loading if browser supports History.js
        // we don't want to revert to hashes as we want users to share real urls that can be indexed
        console.log("History.js enabled!");
        set_initial_state();
        History.Adapter.bind(window, 'statechange', load_state_spoiler);
        $("#randomlink").click(load_random);
    }
});

$(window).load(doneLoading);

///////////////////
//// SOCIAL
//////////////

function reposition_spoiler() {
    // set spoiler position in case the title is more than one line
    // TODO use just html/css for it
    all = $(".all").not(".old");
    title_box = all.find(".title");
    spoiler_box = all.find(".spoiler");
    newtop = title_box.offset()["top"] + title_box.height() + 90;
    spoiler_box.css("top", newtop + "px");
}

// http://bavotasan.com/2011/full-sizebackground-image-jquery-plugin/
function resizeBackdrop() {
    var bgImg = $(".backdrop").not(".old");

    var imgwidth = bgImg.width();
    var imgheight = bgImg.height();

    var winwidth = $(window).width();
    var winheight = $(window).height();

    var widthratio = winwidth / imgwidth;
    var heightratio = winheight / imgheight;

    var widthdiff = heightratio * imgwidth;
    var heightdiff = widthratio * imgheight;

    if (heightdiff > winheight) {
        bgImg.css({
            width: winwidth + 'px',
            height: heightdiff + 'px'
        });
    } else {
        bgImg.css({
            width: widthdiff + 'px',
            height: winheight + 'px'
        });
    }
}

$(window).resize(function () {
    reposition_spoiler();
    resizeBackdrop();
});

// google tracking

$(document).bind('spoiler', function(event, spoiler_key, pending) {
    _gaq.push(['_trackPageview', window.location.pathname]);
});

// social sharing

window.fbAsyncInit = function()
{
    FB.init({appId: '125635440805106', status: true, cookie: true, xfbml: true});
};

function load_facebook() {
    var e = document.createElement('script');
    e.async = true;
    e.src = document.location.protocol +  '//connect.facebook.net/en_US/all.js';
    $('#fb-root').append(e);
}

function load_social_buttons() {
    gapi.plusone.go("plusone");
    load_facebook();
}

function update_social_buttons() {
    var url = window.parent.document.URL;

    $('#plusone').html('<g:plusone href="'+url+'" size="small" align="right"></g:plusone>');
    gapi.plusone.go("plusone");

    $('#fblike').html('<fb:like href="'+url+'" font="tahoma" width="70" layout="button_count"></fb:like>').each(function() {
        if (window.FB) window.FB.XFBML.parse(this);
    });

    $("meta[property=og\\:url]").attr("content", url);
    $("meta[property=og\\:title]").attr("content", $("title").text());
    $("meta[property=og\\:image]").attr("content", $(".backdrop").attr("src"));
}

$(document).bind('spoiler', update_social_buttons);

///////////////////
//// SEARCH
//////////////

function search_spoilers(form) {
    q = $(form).children("input").val();
    var url = '/api/search?q=' + encodeURIComponent(q);
    $.fancybox({href:url, title:'Search'}, {type: 'iframe', fitToView: true});

    return false;
}
