/**
 * Implementiert verschiedene Container für "Social"-Dienste wie zum Beispiel Facebook, Twitter oder YouTube.
 * Duch bearbeiten der eingebetteten Templates können die Boxen angepasst werden.
 *
 * @requires Handlebars, jQuery
 *
 */

var applicationUrl = '/cms/';

var SocialBox = {

    linkify : function (context, fn) {

        var replaceText, replacePattern1, replacePattern2, replacePattern3;
        var inputText = fn(this);

        //URLs starting with http://, https://, or ftp://
        replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
        replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

        //URLs starting with www. (without // before it, or it'd re-link the ones done above)
        replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
        replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

        return replacedText;
    }
};


/**
 * Wall Objekt. Enthält alle Nachrichten und den Autor der an die Wall schreibt.
 * Alle Nachrichten sind vom selben Autor. AppID in FB.init nicht vergessen.
 *
 * @param Seiten ID für die die facebook-box angezeigt werden soll.
 */
function LikeBox(pageId) {

    LikeBox.temp;

    /**
     * Die Page Id die von Facebook vergeben wurde.
     * @type {number}
     * @const
     */
    LikeBox.PAGE_ID = pageId;


    /**
     * Das Template mit dem die Wall gerendert werden soll.
     * @type {String}
     * @const
     */
    LikeBox.WALL_TEMPLATE = '<div id="fb-root"><img class="fb_profile_picture" src="{{picture}}" width="52px" height="52px"/><div class="rightFloat"><h3 class="fb_profile_autor"><a href="{{link}}">{{author}}</a></h3><div class="fb_like_button"><a href="{{link}}"><img src="' + applicationUrl + 'img/modules/social_media/like_btn.png" /></a></div></div><div class="fb_trenner"></div><div id="fb_messages">' +


            '{{#messages}}<div class="fb_message"><div class="fb_message_autor"><a href="{{#actions}}{{link}}{{/actions}}">{{#from}}{{name}}{{/from}}</a>' +
            '</div>{{#linkify}}{{message}}{{/linkify}}<div class="fb_message_attachment">{{#attachmentHandler}}{{picture}}{{/attachmentHandler}}</div>' +
            '<div class="fb_message_meta">{{#formatTime}}{{created_time}}{{/formatTime}}</div>' +
            '</div><div class="fb_trenner_short"></div>{{/messages}}</div>' +
            '' +
            '<div class="fb_trenner"></div><div id="fb_fan_count">{{fanCount}} Personen gefällt das.</div></div>';

    /**
     * Link zur Facebookseite, deren LikeBox angezeigt wird
     */
    LikeBox.link;

    /**
     * Das Template mit dem die Wall gerendert werden soll.
     * @type{Object}
     */
    var template = Handlebars.compile(LikeBox.WALL_TEMPLATE);

    /**
     * Nachrichten die Angezeigt werden sollen.
     * @type {Array.<string>}
     */
    LikeBox.messages;

    /**
     * Author der angezeigt wird.
     * Dies kann überschrieben werden, um einen anderen Autor als den aus Facebook auszugeben
     * @type{string}
     */
    LikeBox.author;

    /**
     * URL des quadratischen Profilbilds.
     * @type {String}
     */
    LikeBox.picture;

    /**
     * Anzahl der Fans
     * @type{number}
     */
    LikeBox.fanCount;

    LikeBox.render = function() {


        result = template(this, {"formatTime": LikeBox.formatTime, "attachmentHandler": LikeBox.attachment, "linkify": SocialBox.linkify});


        $('#fb-root').replaceWith(result);
        $('#fb_messages').jScrollPane({
            showArrows : true,
            scrollbarWidth : 18,
            animateTo : true,
            reinitialiseOnImageLoad: true
        });
        Cufon.refresh();
    };

    /**
     * Formatiert die Zeitangabe von Facebook
     * @param {number} Die Zeit in Millisekunden seit der Unix-Epoche
     * @return {string} Formatierte Zeitangabe. z.B. vor 6 Stunden, Gestern 14.30, 28. November um 18:31
     */
    LikeBox.formatTime = function (context, fn) {
        /**
         * Füllt auf 2 Stellen mit vorgestellten Nullen auf.
         */

        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };


        // timestamp = fn(this) * 1000;
        timestamp = parseInt(fn(this) * 1000);

        var HOURS_48 = 3600 * 48 * 1000; // 48h in Millisekunden
        var HOURS_24 = 3600 * 24 * 1000; // 24h in Millisekunden
        var currentDate = new Date();
        var diff = currentDate.getTime() - timestamp;
        if (diff > HOURS_24) {
            var result = new Date();
            result.setTime(timestamp);
            return 'am ' + result.getDate() + '.' + (result.getMonth() + 1) + '.' + result.getFullYear() + ' um ' + pad(result.getHours()) + ':' + pad(result.getMinutes()) + ' Uhr';
        }
        if (diff < HOURS_24) {
            var result = diff / (3600 * 1000);
            result = Math.round(result);
            return 'vor ' + result + ' Stunden';
        }
    };

    LikeBox.attachment = function(context, fn) {

        if (fn(this) != "") {
            return '<img alt="" class="fb_attachment_photo" src="' + fn(context) + '"/>';
        }

        return '';

    };

    this.init = function() {
       /* FB.init({
            appId  : '167631139943750',
            status : false, // check login status
            cookie : true, // enable cookies to allow the server to access the session
            xfbml  : false  // parse XFBML
        });*/
        $('#fb-root').html('<div style="margin-left: 113px;position: absolute;height:42px;width: 42px;background: url(/cms/img/pages/marketfinder/loader03.gif) no-repeat"></div>');
        $.getJSON("http://dm.weitclick.de/alverde_fb_fetcher/fetcher.php?messages&callback=?",
                {

                    format: "json"
                },
                function(data) {

                    LikeBox.messages = data.data;

                    $.getJSON("http://dm.weitclick.de/alverde_fb_fetcher/fetcher.php?info&callback=?",
                            {

                                format: "json"
                            },
                            function(data) {

                                LikeBox.fanCount = data.likes;
                                LikeBox.link = data.link;
                                LikeBox.author = data.name;
                                LikeBox.picture = data.picture;
                                LikeBox.render();
                            });


                });



    };
}
;


/**
 * Erzuegt eine Twitterbox
 *
 * @param username Twitterbenutzername
 * @returns {TwitterBox}
 */
function TwitterBox(username) {

    /**
     * Enthält das Template für die Box.
     * @const
     */
    TwitterBox.TWITTER_BOX = '<div id="twitter-root"><img class="twitter_profile_picture" src="http://api.twitter.com/1/users/profile_image/{{username}}.json?size=normal" width="52px" height="52px"/><div class="rightFloat"><h3 class="twitter_profile_autor"><a href="http://twitter.com/{{username}}">{{username}}</a></h3><div class="twitter_follow_button"><a href="http://www.twitter.com/{{username}}"><img src="' + applicationUrl + 'img/modules/social_media/follow_btn.png" alt="Follow {{username}} on Twitter"/></a></div></div><div class="twitter_trenner"></div><div id="twitter_messages">{{#tweets}}<div class="twitter_message"><div class="fb_message_autor"><a href="{{../link}}">{{../author}}</a></div>{{#linkify}}{{text}}{{/linkify}}<div class="fb_message_attachment">{{#attachmentHandler}}{{attachment}}{{/attachmentHandler}}</div><div class="twitter_message_meta">{{#formatTime}}{{created_at}}{{/formatTime}} via {{{source}}}</div></div><div class="twitter_trenner_short"></div>{{/tweets}}</div></div>';

    /**
     * Das Template mit dem die Wall gerendert werden soll.
     * @type{Object}
     */
    var template = Handlebars.compile(TwitterBox.TWITTER_BOX);

    /**
     * Von diesem Benutzer werden die Tweets angezeigt
     * @type(String)
     */
    TwitterBox.username = username;

    /**
     * Array mit den Tweets des Benutzers
     * @type(Array)
     */
    TwitterBox.tweets;

    /**
     * Formatiert die Zeitangabe
     * @param {number} Die Zeit in Millisekunden seit der Unix-Epoche
     * @return {string} Formatierte Zeitangabe. z.B. vor 6 Stunden, Gestern 14.30, 28. November um 18:31
     */
    TwitterBox.formatTime = function (context, fn) {
        /**
         * Füllt auf 2 Stellen mit vorgestellten Nullen auf.
         */
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };
        var date = Date.parse(fn(this));
        var timestamp = date.getTime();
        var HOURS_48 = 3600 * 48 * 1000; // 48h in Millisekunden
        var HOURS_24 = 3600 * 24 * 1000; // 24h in Millisekunden
        var currentDate = new Date();
        var diff = currentDate.getTime() - timestamp;
        if (diff > HOURS_24) {
            var result = new Date();
            result.setTime(timestamp);
            return 'am ' + result.getDate() + '.' + (result.getMonth() + 1) + '.' + result.getFullYear() + ' um ' + pad(result.getHours()) + ':' + pad(result.getMinutes()) + ' Uhr';
        }
        if (diff < HOURS_24) {
            var result = diff / (3600 * 1000);
            result = Math.round(result);
            if (result == 0) {
                return 'kürzlich';
            }
            return 'vor ' + result + ' Stunden';
        }
    };

    TwitterBox.render = function() {
        result = template(this, {"formatTime":TwitterBox.formatTime, "linkify": SocialBox.linkify});
        $('#twitter-root').replaceWith(result);
        $('#twitter_messages').jScrollPane({
            showArrows : true,
            scrollbarWidth : 18,
            animateTo : true
        });
        Cufon.refresh();
    };

    this.init = function() {
        // timeline abholen
        $('#twitter-root').html('<div style="margin-left: 113px;position: absolute;height:42px;width: 42px;background: url(/cms/img/pages/marketfinder/loader03.gif) no-repeat"></div>');
        $.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?callback=?', {'screen_name': TwitterBox.username}, function(data) {
            TwitterBox.tweets = data;
            TwitterBox.render();
        });
    };


}
;


/**
 * Erzeugt eine YouTube Box.
 *
 *
 * @param username Benutzername
 * @param profilePicture URL zum Profilbild
 * @returns {YouTubeBox}
 */
function YouTubeBox(username, profilePicture) {

    /**
     * Enthält das Template für die Box.
     * @const
     */
    YouTubeBox.YOUTUBE_BOX = '<div id="youtube-root"><img class="youtube_profile_picture" src="{{profilePicture}}" width="52px" height="52px"/><div class="rightFloat"><h3 class="youtube_profile_autor"><a href="http://www.youtube.com/user/{{username}}">{{username}}</a></h3><div class="youtube_follow_button"><a href="http://www.youtube.com/user/{{username}}"><img src="' + applicationUrl + 'img/modules/social_media/youtube_btn.png"/></a></div></div><div class="youtube_trenner"></div><div id="youtube_messages">{{#videos}}<div class="youtube_message"><div class="youtube_video_thumbnail"><a href="{{player/default}}"><img src="{{thumbnail/sqDefault}}" width="97px" height="54px"/></a></div><div class="youtube_message_title"><a href="{{player/default}}">{{title}}</a></div><div class="youtube_message_meta">von {{uploader}}<br>{{viewCount}} Aufrufe</div></div><div class="youtube_trenner_short"></div>{{/videos}}</div></div>';

    /**
     * Das Template mit dem die Wall gerendert werden soll.
     * @type{Object}
     */
    var template = Handlebars.compile(YouTubeBox.YOUTUBE_BOX);


    /**
     * Benutzername für die YouTubeBox.
     * @type(String)
     */
    YouTubeBox.username = username;

    /**
     *Profilbild des YouTube Benutzers.
     * @type(String) URL
     */
    YouTubeBox.profilePicture = profilePicture;

    /**
     * Videos des Benutzers die in der Box angezeigt werden sollen.
     * @type{Array}
     */
    YouTubeBox.videos;

    YouTubeBox.render = function() {
        result = template(this, {"formatTime": YouTubeBox.formatTime});
        $('#youtube-root').replaceWith(result);
        $('#youtube_messages').jScrollPane({
            showArrows : true,
            scrollbarWidth : 18,
            animateTo : true,
            reinitialiseOnImageLoad: true
        });
        Cufon.refresh();
    };

    this.init = function() {
        // timeline abholen
        $('#youtube-root').html('<div style="margin-left: 113px;position: absolute;height:42px;width: 42px;background: url(/cms/img/pages/marketfinder/loader03.gif) no-repeat"></div>');
        $.getJSON('http://gdata.youtube.com/feeds/api/users/' + YouTubeBox.username + '/uploads?v=2&alt=jsonc&callback=?', function(data) {
            YouTubeBox.videos = data.data.items;
            YouTubeBox.render();
        });
    };
}
;


$(document).ready(function() {

    var twitterBoxInitialized = false;
    var youTubeBoxInitialized = false;

    $(window).load(function() {
        var likeBox = new LikeBox(247046691118);
        likeBox.init();

        var twitterBox = new TwitterBox('dm_alverde');

        var youTubeBox = new YouTubeBox('alverdeNATURKOSMETIK', applicationUrl + 'img/modules/social_media/alverde.png');


        $('.tabSocialNavigation ul li').click(function() {
            $obj = $(this).find('a').attr('class');
            $parent = $(this).parents('.moduleContainer').eq(0);

            $parent.find('.tabSocialNavigation ul li.active').removeClass('active');
            $parent.find('.tabSocialNavigation ul li a.' + $obj).parent().addClass('active');

            $parent.find('.tab_social_content').css('display', 'none');
            $parent.find('.tab_social_content.' + $obj).css('display', 'block');

            /* Rounded Corners */
            $parent.find('.tab_social_content.' + $obj + ' div.rounded').each(function() {
                $(this).css('width', +$(this).find('img').width() + 'px').css('height', +$(this).find('img').height() + 'px');
            });
            if ($obj == 'tab2') {
                $('#twitter_messages').jScrollPaneRemove();
                $('#twitter_messages').jScrollPane({
                    showArrows : true,
                    scrollbarWidth : 18,
                    animateTo : true
                });
                if (!twitterBoxInitialized) {
                    twitterBox.init();
                    twitterBoxInitialized = true;
                }
            }

            if ($obj == 'tab3') {
                $('#youtube_messages').jScrollPaneRemove();
                $('#youtube_messages').jScrollPane({
                    showArrows : true,
                    scrollbarWidth : 18,
                    animateTo : true,
                    reinitialiseOnImageLoad: true
                });
                if (!youTubeBoxInitialized) {
                    youTubeBox.init();
                    youTubeBoxInitialized = true;
                }
            }
            return false;
        });
    });


    $('#twitter').hide();
    $('#youtube').hide();
});

