var REFRESH_INTERVAL = 30000;

var is_any_request_running = false;

function jsonpRequestToAllServices() {
    is_any_request_running = true;
    bpluv.items.length = 0;
    if (ui.twitter_is_selected) bpluv.jsonpTwitterRequest(ui.hashtag);
    if (ui.flickr_is_selected) bpluv.jsonpFlickrRequest(ui.hashtag);
    if (ui.instagram_is_selected) bpluv.jsonpInstagramRequest(ui.hashtag);
}

var bpluv = {
    jsonpRequest: function(URL) {
        is_any_request_running = true
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = URL+"&timestamps="+(new Date().getTime());
        head.appendChild(script);
    },
    jsonpTwitterRequest: function(hashtag) {
        this.jsonpRequest("http://search.twitter.com/search.json?result_type=recent&callback=bpluv.jsonpTwitterCallback&rpp=100&q=" + hashtag)
    },
    jsonpTwitterCallback: function(data) {
        for (var i = 0; i < data.results.length; i++) {
            data.results[i].bpluv_type = "twitter";
            var date = new Date(data.results[i].created_at);
            data.results[i].unix_time = date.getTime();
            this.items.push(data.results[i]);
        }
        ui.switch_to_show();
        is_any_request_running = false;
    },
    jsonpFlickrRequest: function(hashtag) {
        this.jsonpRequest("http://api.flickr.com/services/rest/?method=flickr.photos.search&per_page=80&extras=url_l,date_upload&api_key=b0d1d1baa24ae61abd138f0b0c25d45c&format=json&jsoncallback=bpluv.jsonpFlickrCallback&text=" + hashtag)
    },
    jsonpFlickrCallback: function(data) {
        var image_url;
        for (var i = 0; i < data.photos.photo.length; i++) {
            data.photos.photo[i].bpluv_type = "flickr";
            data.photos.photo[i].unix_time = data.photos.photo[i].dateupload*1000;
            image_url = data.photos.photo[i].url_l;
            if (image_url) {
                this.items.push(data.photos.photo[i]);
            }
        }
        ui.switch_to_show();
        is_any_request_running = false;
    },
    jsonpInstagramRequest: function(hashtag) {
        this.jsonpRequest("https://api.instagram.com/v1/tags/" + hashtag + "/media/recent?client_id=bbf40ed56ce94073978690fc6ff0f1bb&callback=bpluv.jsonpInstagramCallback")
    },
    jsonpInstagramCallback: function(data) {
        if (!data.data) {
            return false;
        };
        var image_url;
        for (var i = 0; i < data.data.length; i++) {
            data.data[i].bpluv_type = "instagram";
            data.data[i].unix_time = data.data[i].created_time*1000;
            image_url = data.data[i].images.standard_resolution
            if (image_url) {
                this.items.push(data.data[i]);
            }
        }
        ui.switch_to_show();
        is_any_request_running = false;
    },
    items: [],
    showedItems: {},
    findRandomItem: function() {
        return this.items[Math.floor(Math.random()*this.items.length)];
    },
    nextRandomItem: null
};

var ui = {
    next: function() {
        if (bpluv.items.length == 0) {
            if (is_any_request_running == true) {
                ui.next();
                return false
            } else {
                bpluv.showedItems = {};
                jsonpRequestToAllServices();
                ui.next();
                return false;
            }
        }

        bpluv.items.sort(function(a,b){
            return b.unix_time-a.unix_time
        });

        var randomItem = bpluv.nextRandomItem || bpluv.items.shift();
        bpluv.nextRandomItem = bpluv.items.shift();

        jQuery("#screen-1 .temp").remove();
        if (bpluv.nextRandomItem.bpluv_type == "flickr") {
            jQuery("#screen-1").append("<img class='temp' src='"+bpluv.nextRandomItem.url_l+"'/>");
        } else if (bpluv.nextRandomItem.bpluv_type == "instagram") {
            jQuery("#screen-1").append("<img class='temp' src='"+bpluv.nextRandomItem.images.standard_resolution.url+"'/>");
        }

        if (bpluv.showedItems[randomItem.unix_time]) {
            ui.next();
            return
        } else {
            bpluv.showedItems[randomItem.unix_time] = true;
        }

        jQuery("#screen-2").fadeOut(function(){
            try {
                if (randomItem.bpluv_type == "twitter") {
                    ui.apply_twitter_data(randomItem);
                    jQuery("#screen-2").fadeIn();
                    jQuery('#message.content').textfill({
                        maxFontPixels: 408,
                        innerTag: 'span'
                    });
                } else if (randomItem.bpluv_type=="flickr") {
                    ui.apply_flickr_data(randomItem);
                } else {
                    ui.apply_instagram_data(randomItem);
                }
            } catch(error) {
                ui.next();
            };
        });
    },
    reset: function() {
        jQuery("#message, #picture, .footer .in .hash .pic").hide();
        jQuery("b, i, #message span").html("");
        jQuery("div.hashtag").html("");
    },
    apply_twitter_data: function(tweet) {
        ui.reset();
        jQuery("#message span").html(tweet.text);
        jQuery("#message").show();
        jQuery("b").html("@"+tweet.from_user);
        jQuery("i").html(prettyDate(tweet.created_at));
        jQuery(".footer .in .hash .pic").show();
        jQuery(".footer .in .hash .pic img ").attr("src", tweet.profile_image_url);
        jQuery("div.hashtag").html("#"+ui.hashtag);
    },
    apply_flickr_data: function(flicrk_image) {
        ui.reset();
        jQuery("#picture").show();
        jQuery("#picture img").attr("src", flicrk_image.url_l);
        jQuery("i").html(flicrk_image.title);
        jQuery("div.hashtag").html("#"+ui.hashtag);
    },
    apply_instagram_data: function(instagram_image) {
        ui.reset();
        jQuery("#picture").show();
        jQuery("#picture img").attr("src", instagram_image.images.standard_resolution.url);
        jQuery("b").html(instagram_image.caption.from.username);
        jQuery(".footer .in .hash .pic").show();
        jQuery(".footer .in .hash .pic img ").attr("src", instagram_image.caption.from.profile_picture);
        jQuery("div.hashtag").html("#"+ui.hashtag);
    },
    switch_to_show: function() {
        if (jQuery("#screen-1").is(":visible") == true) {
            jQuery("#screen-1").hide();
            ui.next();
            setInterval("ui.next();",12000);
            setInterval(jsonpRequestToAllServices, REFRESH_INTERVAL);
        }
    }
}

jQuery(document).ready(function($) {
    jQuery("#hashtag").click(function(){
        jQuery(this).val("");
    });

    jQuery("#picture img").load(function() {
        jQuery("#screen-2").fadeIn();
        var verticalDelta = jQuery(window).height() - jQuery(this).height();
        var topMargin = Math.floor(verticalDelta / 2);
        jQuery(this).css("margin-top", topMargin);
    } );

    jQuery(window).bind("load resize", function(){
        jQuery('.content .img img').each(function () {
            var verticalDelta = jQuery(window).height() - jQuery(this).height();
            var topMargin = Math.floor(verticalDelta / 2);
            jQuery(this).css("margin-top", topMargin);
        });

        jQuery('#message.content').each(function () {
            var height = jQuery(window).height() - 110;
            jQuery(this).css("height", height);
        });

        jQuery('#message.content').textfill({
            maxFontPixels: 408,
            innerTag: 'span'
        });
    });

    jQuery("#screen-1 form").submit(function() {
        ui.hashtag = jQuery("#hashtag").val();
        ui.twitter_is_selected = jQuery("#twitter-checkbox").attr("checked");
        ui.instagram_is_selected = jQuery("#instagram-checkbox").attr("checked");
        ui.flickr_is_selected = jQuery("#flickr-checkbox").attr("checked");

        if (ui.hashtag == "" || ui.twitter_is_selected == undefined && ui.flickr_is_selected == undefined && ui.instagram_is_selected == undefined) return false;

        if (ui.twitter_is_selected) bpluv.jsonpTwitterRequest(ui.hashtag);
        if (ui.flickr_is_selected) bpluv.jsonpFlickrRequest(ui.hashtag);
        if (ui.instagram_is_selected) bpluv.jsonpInstagramRequest(ui.hashtag);

        return false;
    });
});

