﻿(function ($) {
    function DateString(date) {
        var month = (date.getMonth() + 1) + '',
        day = date.getDate() + '',
        year = date.getFullYear() + '',
        hours = date.getHours() + '',
        minutes = date.getMinutes() + '';

        return (month.length == 1 ? '0' + month : month) +
        '/' + (day.length == 1 ? '0' + day : day) +
        '/' + year +
        ' ' + (hours.length == 1 ? '0' + hours : hours) +
        ':' + (minutes.length == 1 ? '0' + minutes : minutes);
    }

    if ($.browser.msie && $.browser.version < 10 && window.XDomainRequest) {
        $.ajaxTransport("+json", function (options, originalOptions, jqXHR) {


            var xdr;

            return {

                send: function (headers, completeCallback) {

                    // Use Microsoft XDR
                    if (options.url[0] == '/')
                        xdr = new XMLHttpRequest();
                    else
                        xdr = new XDomainRequest();

                    xdr.open("get", options.url);

                    xdr.onload = function () {

                        if (this.contentType && this.contentType.match(/\/xml/)) {

                            var dom = new ActiveXObject("Microsoft.XMLDOM");
                            dom.async = false;
                            dom.loadXML(this.responseText);
                            completeCallback(200, "success", [dom]);

                        } else {

                            completeCallback(200, "success", [this.responseText]);

                        }

                    };

                    xdr.ontimeout = function () {
                        completeCallback(408, "error", ["The request timed out."]);
                    };

                    xdr.onerror = function () {
                        completeCallback(404, "error", ["The requested resource could not be found."]);
                    };

                    xdr.send();
                },
                abort: function () {
                    if (xdr) xdr.abort();
                }
            };
        });
    }

    $.extend({

        ShowLiveFeedOverlay: function (callback) {
            $('.feedContent').animate({ scrollTop: 0 }, 'fast');
            $('#feedoverlay').fadeIn('fast', callback);
        },
        HideLiveFeedOverlay: function (callback) {
            $('#feedoverlay').fadeOut('fast', callback);
        },
        GetTumblrFeed: function (elm) {
            $.ShowLiveFeedOverlay(function () {

                $.getJSON('http://normik.tumblr.com/api/read/json?callback=?',
                function (e) {
                    elm.html('');
                    for (var i = 0; i < 5; i++) {

                        var post = e.posts[i],
                        item = $(document.createElement('div')),
                        content = $(document.createElement('div')),
                        createdBy = $(document.createElement('div')),
                        createdTime = $(document.createElement('div')),
                        creatorBox = $(document.createElement('div')),
                        clear = $(document.createElement('div')),
                        header = $(document.createElement('h2')),
                        link = $(document.createElement('a')),
                        text = $(document.createElement('p')),
                        postText = $(post['regular-body']).first().text(),
                        textLength = 75;

                        item.addClass('feedPost');
                        clear.addClass('clear');
                        content.addClass('tumblrPostContent');
                        if (i == 0)
                            item.addClass('first');
                        link.text(post['regular-title']);
                        link.attr('href', post['url-with-slug']);
                        link.click(function (e) {
                            e.preventDefault();
                            window.open($(this).attr('href'));
                            return false;
                        });
                        text.text(postText);


                        creatorBox.addClass('creatorBox');

                        var date = new Date(post.date);
                        createdTime.text(DateString(date));

                        creatorBox.append(createdTime);
                        creatorBox.append(createdBy);

                        header.append(link);
                        content.append(header);
                        content.append(text);
                        item.append(content);
                        item.append(creatorBox);
                        item.append(clear);
                        elm.append(item);
                    }

                    $.HideLiveFeedOverlay();
                });
            });
        },
        GetFlickrFeed: function (elm) {
            $.ShowLiveFeedOverlay();

            //getJSON: URL [, data]         - The data from the url is put into the function
            $.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?id=62540312@N07&lang=en-us&format=json&jsoncallback=?',
                function (e) {
                    elm.html(''); // remove the content of the .feedContent div
                    var list = $(document.createElement('ul'));
                    for (var i = 0; i < 5; i++) { // run 5 times

                        var post = e.items[i], // save the item array element in a variable
                        item = $(document.createElement('li')), // create a div element, called item
                        link = $(document.createElement('a')),  // create an a element, called link
                        image = $(document.createElement('img'));
                        item.addClass('feedPost');
                        if (i == 0)
                            item.addClass('first');
                        if (i % 2 == 0) {
                            item.addClass('first');
                        }

                        image.attr('src', post.media.m);
                        link.append(image); // post "media" from the array
                        link.attr('href', post.link); // post "link" from the array
                        link.click(function (e) {
                            e.preventDefault();
                            window.open($(this).attr('href'));
                            return false;
                        });

                        item.append(link);
                        list.append(item);
                    }

                    elm.append(list);

                    $.HideLiveFeedOverlay();
                });
        },
        GetYoutubeFeed: function (elm) {
            $.ShowLiveFeedOverlay();

            $.getJSON('http://gdata.youtube.com/feeds/base/users/normikdigital/uploads?orderby=updated&alt=json&client=ytapi-youtube-rss-redirect&v=2',
                function (e) {
                    elm.html('');
                    var list = $(document.createElement('ul'));
                    for (var i = 0; i < 5; i++) {

                        var post = e.feed.entry[i],
                        item = $(document.createElement('li')),
                        link = $(document.createElement('a')),
                        //title = $(document.createElement('h2')),
                        iframe = $(document.createElement('iframe')),
                        id = post.id.$t.split(/:/g).reverse()[0];

                        if (i % 3 == 0) {
                            item.addClass('first');
                        }

                        //title.text(post.title.$t);

                        iframe.attr('frameborder', '0');
                        iframe.attr('allowfullscreen', 'true');
                        iframe.attr('src', 'http://www.youtube.com/embed/' + id + '?theme=light&showinfo=0&wmode=transparent');

                        /*link.append(iframe);
                        link.attr('href', post.link);
                        link.click(function (e) {
                        e.preventDefault();
                        window.open($(this).attr('href'));
                        return false;
                        });*/

                        //item.append(title);
                        item.append(iframe);
                        list.append(item);
                    }
                    elm.append(list);

                    $.HideLiveFeedOverlay();
                });
        },

        GetFaceBookFeed: function (elm) {
            $.ShowLiveFeedOverlay(function () {

                $.getJSON('/FBProxy.ashx',
            function (e) {
                elm.html('');
                var counter = 0;
                for (var i = 0; i < e.data.length; i++) {
                    if (counter == 5)
                        break;
                    if (!e.data[i].message)
                        continue;
                    var post = e.data[i],
                        item = $(document.createElement('div')),
                        content = $(document.createElement('div')),
                        createdBy = $(document.createElement('div')),
                        createdTime = $(document.createElement('div')),
                        creatorBox = $(document.createElement('div')),
                        clear = $(document.createElement('div')),
                        header = $(document.createElement('h2')),
                        link = $(document.createElement('a')),
                        text = $(document.createElement('p')),
                        img = $(document.createElement('img')),
                        postText = post.message.replace(/<[^>]*>/g, '');

                    item.addClass('fbContent');
                    img.addClass('fbImg');
                    if (!post.name && !post.message) {
                        continue;
                    }
                    else {
                        text.text(postText || post.message);

                        img.attr('id', 'img_' + counter);
                        link.attr('href', post.actions[0].link);
                        link.html(post.name || '&nbsp;');
                        item.addClass('feedPost');
                        if (counter == 0)
                            item.addClass('first');
                        clear.addClass('clear');
                        content.addClass('postContent');

                        link.click(function (e) {
                            e.preventDefault();
                            window.open($(this).attr('href'));
                            return false;
                        });

                        creatorBox.addClass('creatorBox');

                        var parts = post.created_time.split(/[T|+|\-|:]/),
                            date = new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);

                        createdBy.text(post.from.name);
                        createdTime.text(DateString(date));

                        creatorBox.append(createdTime);
                        creatorBox.append(createdBy);

                        header.append(link);
                        item.append(img);
                        content.append(header);
                        content.append(text);
                        item.append(content);
                        item.append(creatorBox);
                        item.append(clear);
                        elm.append(item);

                        img.attr('src', post.picture || '/css/images/logo.jpg');
                        img.attr('alt', post.name);
                        img.attr('title', post.name);
                        /*(function (img, fromId)
                        {
                        var imgelm = $('#' + img);

                        setTimeout(function ()
                        {
                        $.getJSON('http://graph.facebook.com/' + fromId, function (e)
                        {
                        imgelm.attr('src', e.picture || '/');
                        imgelm.attr('alt', e.name);
                        imgelm.attr('title', e.name);
                        });
                        }, 100 * counter);
                        })('img_' + counter, post.from.id);*/
                        counter++;
                    }
                }

                $.HideLiveFeedOverlay();
            });

            });
        }
    });
    $(document).bind('pageReady', function () {
        var counter = defaultCounter = 14;

        $('#tumblrLink').click(function (e) {
            e.preventDefault();
            counter = 0;
            $.GetTumblrFeed($('.feedContent:first'));
            $('.contentTiles li.social div.liveFeeds div.feedLinks a.active').removeClass('active');
            $(this).addClass('active');

            return false;
        });

        /*$('#flickrLink').click(function (e)
        { // when flickerLink is clicked
        e.preventDefault();               // Stop the default operation

        $.GetFlickrFeed($('.feedContent:first')); // call GetFlickrFeed and include the .feedContent div
        $('.contentTiles li.social div.liveFeeds div.feedLinks a.active').removeClass('active');
        $(this).addClass('active');

        return false;
        });*/

        $('#youtubeLink, #flickrLink').click(function (e) {
            e.preventDefault();

            window.open($(this).attr('href'));

            /*$.GetYoutubeFeed($('.feedContent:first'));
            $('.contentTiles li.social div.liveFeeds div.feedLinks a.active').removeClass('active');
            $(this).addClass('active');*/

            return false;
        });

        $('#facebookLink').click(function (e) {
            e.preventDefault();
            counter = 0;

            $.GetFaceBookFeed($('.feedContent:first'));
            $('.contentTiles li.social div.liveFeeds div.feedLinks a.active').removeClass('active');
            $(this).addClass('active');

            return false;
        });
        function load() {
            counter++;
            if (counter == defaultCounter + 1) {
                var links = $('#tumblrLink , #facebookLink'), initClick = Math.floor(Math.random() * links.length);
                $(links[initClick]).click();
            }
        }

        load();

        setInterval(load, 1000);
        // Fjæsbog: facebook id, access token
        // Linkedin: apikey, secretkey,membertoken,membersecret
        // $.getJSON('http://normik.tumblr.com/api/read/json?callback=?',function(e){console.log(e);})
        // $.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?id=62540312@N07&lang=en-us&format=json&jsoncallback=?',function(e){console.log(e);})
        // $.getJSON('http://gdata.youtube.com/feeds/base/users/normikdigital/uploads?orderby=updated&alt=json&client=ytapi-youtube-rss-redirect&v=2',function(e){console.log(e);})
    });
})(jQuery);


//http: //normik.tumblr.com/api/read/json?callback=?
