 ONSUGAR.Facebook = ONSUGAR.Facebook || function() {

    return {
        suggestFriends: function(element) {
            new Ajax.Updater(element, '/onsugar-facebook-ajax-friends/false', {
                method: 'get',
                onSuccess: function(response) {}
            })
        },
        accountsNotFollowed: function(element) {
            new Ajax.Updater({success: element}, '/onsugar-facebook-ajax-friends-number', {
                method: 'get',
                onSuccess: function(response) {}
            })
        }
    }

}();

ONSUGAR.Twitter = ONSUGAR.Twitter || function() {

    return {
        suggestFriends: function(element) {
            new Ajax.Updater(element, '/onsugar-twitter-ajax-friends/false', {
                method: 'get',
                onSuccess: function(response) {}
            })
        },
        accountsNotFollowed: function(element) {
            new Ajax.Updater({success: element}, '/onsugar-twitter-ajax-friends-number', {
                method: 'get',
                onSuccess: function(response) {}
            })
        }
    }

}();

ONSUGAR.Stream = ONSUGAR.Stream || function() {
    return {
        init: function() {
            ONSUGAR.Stream.ajaxLinks();
            ONSUGAR.Stream.commentInit();
            ONSUGAR.Stream.reblogInit();
            ONSUGAR.Stream.images();
            ONSUGAR.Stream.controls();
            ONSUGAR.Stream.shopSense();
            ONSUGAR.Stream.analytics();

            $$('.fancybutton').invoke('observe', 'mouseover', function(e) {
               e.target.addClassName('over');
            });
            $$('.fancybutton').invoke('observe', 'mouseout', function(e) {
               e.target.removeClassName('over');
            });

        },
        analytics: function() {

            $$('#social-stats-toggle a').invoke('observe','click', function (e) {
                $$('.charts-container').each(function (e){
                    e.update("<div class='top-ten-list loading-big'></div>")
                });
            });

            //handle click
            $$('#analytics-menu a').invoke('observe','click', function (e) {
                var el = e.target;
                fetchData(el.getAttribute('data-url'), el.getAttribute('data-show'));
                el.removeAttribute('data-url');
                window.location.hash = '#!view-' + el.getAttribute('data-show');
                //submenu link
                if ($(el).up().hasClassName('submenu')) {
                    el.siblings('a').invoke('removeClassName', 'active');
                    el.addClassName('active');
                }
                //top level link
                else {
                    setupUI();
                    el.addClassName('active');
                    el.up('div').addClassName('active');
                    el.next('.submenu').show();
                    if (el.next('.submenu').down('a', 2)) {
                        el.next('.submenu').down('a', 2).addClassName('active');
                    }
                }
                Event.stop(e);
            });

            //handle url
            if(window.location.hash.indexOf('#!view-') === 0){
                var e = window.location.hash.replace('#!view-', 'id-');
                setupUI();
                $(e).up('.submenu').show();
                $(e).up(1).addClassName('active');
                $(e).addClassName('active');
                var showId = window.location.hash.replace('#!view-', '');
                var url = $(e).up().previous().getAttribute('data-url');
                $(e).up().previous().removeAttribute('data-url');
                fetchData(url, showId, true);
            }
            else {
                if ($('reach-week')) {
                    $('reach-week').show();
                }
            }

            function setupUI(){
                $$('#analytics-menu div').invoke('removeClassName', 'active');
                $$('#analytics-menu a').invoke('removeClassName', 'active');
                $$('.submenu').invoke('hide');
            }

            function fetchData(url, showId, showSubChart){
                $$('.charts-container').invoke('hide');
                if (url) {
                    $(showId).show(); //shows loading spinner
                    $(showId).down().update("<div class='top-ten-list loading-big'></div>")
                    new Ajax.Request(url, {
                        onSuccess: function(transport) {
                            $(showId).up().update(transport.responseText);
                            $(showId).show();
                        }
                    });
                }
                else {
                    $(showId).show();
                }
            }
        },
        shopSense: function(){
            new Ajax.Request('/shopsense/data', {
                onSuccess: function(transport) {
                    data = eval('('+transport.responseText+')');
                    var revenueToday;
                    if (data.revenueThisWeek) {
                        revenueToday = "$" + Number(data.revenueThisWeek / 100).toFixed(2);
                    }
                    else {
                        revenueToday = "$0.00";
                    }

                    $('shopsense-amount').update(revenueToday);
                    if ($('shopsense-content')) {
                        $('shopsense-content').removeClassName('loading');
                    }
                }
            });

        },
        controls: function() {
            $$('.clear-to-default').invoke('observe', 'click', function(e) {
                e.target.up('.sidebar-section').removeClassName('active');
            });
            $$('.tag-header').each(function(e) {
                e.observe('mouseover', function(event) {
                    e.addClassName('over');
                });
                e.observe('mouseout', function(event) {
                    e.removeClassName('over');
                });
            });
            $$('.link-items a').each(function(e) {
                e.observe('click', function(event) {
                    doClick(e, event);
                    $('sugar').scrollTo();
                });
            });
            $$('.sidebar-section h3').invoke('observe','mouseover', function(e) {
                e.target.up('.sidebar-section').addClassName('hover');
                e.target.addClassName('hover');
            });
            $$('.sidebar-section h3').invoke('observe','mouseout', function(e) {
                e.target.up('.sidebar-section').removeClassName('hover');
                e.target.removeClassName('hover');
            });
            $$('.sidebar-section h3').invoke('observe','click', function(e) {
                if (e.target.up('.sidebar-section').hasClassName('active')) {
                    e.target.up('.sidebar-section').removeClassName('active');
                }
                else {
                    e.target.up('.sidebar-section').addClassName('active');
                }
            });
            $$('.ajax').each(function(e) {
                e.observe('click', function(event) {
                    new Ajax.Request(event.target.href, {
                        onSuccess: function(transport) {
                            if (transport.responseText == 1) {
                                if (event.target.innerHTML == 'Save') {
                                    event.target.href.replace('save-tag', 'save-tag-delete');
                                    event.target.innerHTML = 'x';
                                }
                                else if (event.target.innerHTML == 'x') {
                                    event.target.up('.tag-header').hide();
                                }
                                console.log(event);
                            }
                            else{
                                $('tag-status').innerHTML = transport.responseText;
                            }
                        }
                    });
                    Event.stop(event);
                    return false;
                })
            });
            if ($('onsugar-search')) {
                $('onsugar-search').observe('focus', function(event) {
                    if ($F('onsugar-search') == 'Search Tags') {
                        $('onsugar-search').value = "";
                    }
                });
                $('onsugar-search').observe('blur', function(event) {
                    if ($F('onsugar-search') == '') {
                        $('onsugar-search').value = "Search Tags";
                    }
                });
                $('onsugar_tag_search_form').observe('submit', function(event) {
                    window.location = "?sites=all&tags=" + $F('onsugar-search');
                    Event.stop(event);
                });
                $('onsugar-search').observe('keypress', function(event) {
                    var key = event.which || event.keyCode;
                    switch (key) {
                        default:
                        break;
                        case Event.KEY_RETURN:
                            window.location = "?sites=all&tags=" + $F('onsugar-search');
                            Event.stop(event);
                        break;
                    }
                });
            }
            if ($('follow-all-facebook-friends')) {
                $('follow-all-facebook-friends').observe('click', function(event) {
                    new Ajax.Request('/onsugar-facebook-ajax-follow-friends');
                    $$('.toggle-links-ajax').each(function (e) {
                        $(e).childElements()[0].hide();
                        $(e).childElements()[1].show();
                        $('follow-all-facebook-friends').hide();
                        $('following-all-facebook-friends').show();
                    });
                });
            }
            var follow_count = 0;
            $$('.toggle-links-ajax').each(function(e) {
                if (e.down('a').getStyle('display') != 'none') {
                    follow_count++;
                }
                if (follow_count === 0) {
                    if ($('follow-all-twitter-friends')) {
                        $('follow-all-twitter-friends').hide();
                        $('following-all-twitter-friends').show();
                    }
                    if ($('follow-all-facebook-friends')) {
                        $('follow-all-facebook-friends').hide();
                        $('following-all-facebook-friends').show();
                    }
                }
            });
            if ($('follow-all-twitter-friends')) {
                $('follow-all-twitter-friends').observe('click', function(event) {
                    new Ajax.Request('/onsugar-twitter-ajax-follow-friends');
                    $$('.toggle-links-ajax').each(function (e) {
                        $(e).childElements()[0].hide();
                        $(e).childElements()[1].show();
                        $('follow-all-twitter-friends').hide();
                        $('following-all-twitter-friends').show();
                    });
                });
            }

            function doClick(e, event) {
                if (!e.getAttribute('data-name')) {
                    return;
                }
                $('loading-container').show();
                $('stream-content-container').hide();

                var params = new Hash();

                params.set('sites', 'all');
                params.set(e.getAttribute('data-name'), e.getAttribute('data-value'));
                params = params.toObject();
                params = ONSUGAR.Util.buildQueryString(params);

                window.location = '?' + params;

                Event.stop(event);
                return false;
            }

        },
        images: function() {
            $$('.stream .images').each(function(e) {
                Event.stopObserving(e, 'click');
                Event.observe(e, 'click', function(event) {
                    e.childElements().each(function(image) {
                        image.toggle();
                    })
                });
            });
        },
        commentInit: function() {
            if ($$('.comment-icon')) {
                $$('.comment-icon').each(function(e) {
                    Event.observe(e, 'click', function(event) {
                        event.target.up(1).down('textarea').focus();
                        event.target.up('.stream').scrollTo();
                        Event.stop(event);
                    });
                });
            }
            if ($$('.comment-link')) {
                $$('.comment-link').each(function(e) {
                    Event.observe(e, 'click', function(event) {
                        event.target.up(2).down('.stream-comment-textarea').down('textarea').focus();
                        Event.stop(event);
                    });
                });
            }
            if ($$('.stream-comment-textarea textarea')) {
                $$('.stream-comment-textarea textarea').each(function(textarea) {
                    new Widget.Textarea(textarea);
                    Event.observe(textarea, 'focus', function(event) {
                        event.target.up('.stream').down('.account-comment-picture').show();
                        textarea.value = textarea.value.replace('Write a comment...','');
                        //event.target.up('.stream').down('.comment-icon').addClassName('active');
                        textarea.addClassName('active');
                    });
                    textarea.onkeyup = function(e) {
                        e = e || event;
                        if (e.keyCode === 13 && !e.ctrlKey) {
                            var comment = textarea.value;
                            textarea.value = '';
                            //this append the comments to the page
                            var newComment;
                            newComment = textarea.up(3).cloneNode(true);
                            newComment.down(1).next(0).down().next(0).down().next(0).update(comment);
                            newComment.down(1).next(0).down().remove();
                            newComment.down(1).next(0).down().show();
                            textarea.up(3).insert({before:newComment});
                            new Ajax.Request('/ajax-comment', {
                                method: 'POST',
                                parameters: {
                                    'comment': comment,
                                    'nid': textarea.getAttribute('data-nid')
                                    },
                                onSuccess: function(transport) {

                                }
                            });
                        }
                        return false;
                     }
                });
            }
        },
        reblogInit: function() {
            if ($$('.stream-reblog-link')) {
                $$('.stream-reblog-link').each(function(l) {
                    Event.observe(l, 'click', function(event) {
                        var nidValue = l.getAttribute('data-nid');
                        var streamReblogField = 'stream-reblog-' + nidValue;
                        $(streamReblogField).show();
                        $(streamReblogField).focus();
                        Event.stop(event);
                    });
			    });
            }
            if ($$('.stream-reblog-textarea textarea')) {
                $$('.stream-reblog-textarea textarea').each(function(textarea) {
                    new Widget.MiniTextarea(textarea);
                    Event.observe(textarea, 'focus', function(event) {
                        textarea.value = textarea.value.replace('Reblog caption...','');
                        textarea.addClassName('active');
                    });
                    textarea.onkeyup = function(e) {
                        e = e || event;
                        if (e.keyCode === 13 && !e.ctrlKey) {
                            var reblogCaption = textarea.value;
                            var reblogInfo =  textarea.up(0).previous(0).down().value;
                            var reblogInfoSplit = reblogInfo.split(":", 2);
                            textarea.value = '';
                            var reblogSiteText = '<a href=\"/' + reblogInfoSplit[0] + '\">' + reblogInfoSplit[1] + '</a>';
                            //this append the reblog to the page
                            var newReblog;
                            newReblog = textarea.up(3).cloneNode(true);
                            newReblog.down(2).next(2).down(0).update(reblogSiteText);
                            newReblog.down(2).next(2).down(0).next(0).update(reblogCaption);
                            newReblog.down(2).remove();
                            newReblog.down(2).remove();
                            newReblog.down(2).remove();
                            newReblog.down(2).show();
                            newReblog.id = textarea.id + "-reblogged";
                            textarea.up(3).insert({before:newReblog});
                            textarea.up(3).hide();
                            new Ajax.Request('/ajax-reblog', {
                                method: 'POST',
                                parameters: {
                                    'caption': reblogCaption,
                                    'nid': textarea.getAttribute('data-nid'),
                                    'reblog-nid': reblogInfoSplit[0]
                                    },
                                onSuccess: function(transport) {

                                }
                            });
                        }
                        return false;
                     }
                });

 			}
        },
        ajaxLinks: function() {
            $$('.toggle-links-ajax a').each(function(e) {
                e.observe('click', function(event) {
                    new Ajax.Request(event.target.href, {
                        onSuccess: function(transport) {
                            if (event.target.getAttribute('data-replace-class')) {
                                event.target.up(2).down(event.target.getAttribute('data-replace-class')).update(transport.responseText);
                            }
                            if (event.target.getAttribute('data-show-class')) {
                                event.target.up(2).down(event.target.getAttribute('data-show-class')).show();
                            }
                            event.target.hide();
                            e.siblings().each(function(e) {
                                e.show();
                            });
                            var icon = e.up('.toggle-links-ajax').down('i');
                            if (icon) {
                                icon.show();
                                if (icon.hasClassName('active')) {
                                    icon.removeClassName('active');
                                }
                                else {
                                    icon.addClassName('active');
                                }
                            }

                        }
                    });
                    Event.stop(event);
                    return false;
                })
            });
            $$('.website-thumbnail').each(function(e) {
                e.observe('mouseover', function(event) {
                   e.addClassName('over');
                });
                e.observe('mouseout', function(event) {
                   e.removeClassName('over');
                })
            });
            $$('.website-container').each(function(e) {
                e.observe('mouseover', function(event) {
                   e.addClassName('over');
                });
                e.observe('mouseout', function(event) {
                   e.removeClassName('over');
                })
            });
        }
    }
}();

ONSUGAR.InfiniteScroll = ONSUGAR.InfiniteScroll || function() {
    var loadingContent = false; // loading semaphore
    var currentPage = 0; // curent page
    var viewportSizeY = 0; // viewport height
    var viewportOffsetY = 0; // viewport offset-y
    var infiniteScrollActived = false; // if scroll is actived

    var pagePosts = null; // all the post divs on the page
    var oldestTimestamp = null; // keep track of the oldest timestamp we have

    var POST_CSS_SELECTOR = ".infinite-item"; // CSS selector
    var BOTTOM_SCROLL_BUFFER = 600; // Threshold for scroll trigger, loading new content
    var POSTS_PER_PAGE = 10; // Total posts per page

    // scroll handler
    var doScroll = function() {
        var viewportDim = document.viewport.getDimensions();
        viewportSizeY = viewportDim.height;

        var viewportLoc = document.viewport.getScrollOffsets();
        viewportOffsetY = viewportLoc[1];

        var posts = pagePosts;

        var postMax = posts.last();

        var paneMaxY = postMax.viewportOffset()[1] + postMax.getHeight();

        // scrolling down, load more content
        if (paneMaxY - viewportSizeY < BOTTOM_SCROLL_BUFFER) {
            if (!loadingContent) {
                fetch();
            }
        }

    };

    // function updates the pagePosts variable
    var updatePagePosts = function() {
        pagePosts = $$(POST_CSS_SELECTOR);
    };

    // updates to the created time of the oldest node we have
    var updateTimestamp = function() {
        oldestTimestamp = pagePosts.last().getAttribute('data-created');
    }

    var fetch = function() {

        var pageToFetch = currentPage + 1
        // url to fetch new posts
        var url = window.location.pathname +  window.location.search;

        var params = {
            "page": pageToFetch,
            "format": "ajax"
            };

        var urlToTrack = '/?page=' + pageToFetch + "&format=ajax";

        // lock for loading
        loadingContent = true;

        // fire request
        new Ajax.Request(url, {
            method: "GET",
            parameters: params,
            onSuccess: function(transport) {
                if (transport.responseText.length === 0 ) {
                    $('infinite-scroll-loading').hide();
                    $('infinite-scroll-loading').insert({before: "<div id='ajax-end'>No more information to display. <a href='#sugar'>Return to top</a>.</div>"});
                }
                else {

                    // unlock loading
                    loadingContent = false;

                    // fire all analytics
                    //ajaxLoadAnalytics(urlToTrack);

                    // insert new posts
                    $('infinite-scroll-loading').insert({before: transport.responseText});

                    ONSUGAR.Stream.init();

                    // increment index
                    currentPage++;

                    // update page posts
                    updatePagePosts();

                    // keep track of the oldest node
                    updateTimestamp();

                    // execute harness ajax
                    SUGAR.AjaxHarness.executeAjax();
                }
            }
        });
    };

    return {
        init: function() {
            if ($$(POST_CSS_SELECTOR).length == 0) {
                return;
            }
            if (!$('pager')) {
                return;
            }

            infiniteScrollActived = true;

            // add spiner div to show user when data it loading
            $('pager').insert({before: "<div id='infinite-scroll-loading'>Loading More</div>"});
            $('pager').hide();

            //$('sugar').insert("<a id='return-to-top' href='#sugar'>Return to Top</a>");

            // wire the scroll events
            Event.observe(window, 'scroll', doScroll);

            // force the doScroll function to run every 500 millis, to make sure
            // state is being properly enforced
            setInterval(doScroll, 500);

            // update the pagePosts variable
            updatePagePosts();

            // keep track of the oldest node we have
            updateTimestamp();


        }
    }
}();


if (window.Widget == undefined) window.Widget = {};
Widget.Textarea = Class.create({
  initialize: function(textarea, options)
  {
    this.textarea = $(textarea);
    this.options = $H({
      'min_height' : 26,
      'max_length' : 400,
      'show_remaining' :false
    }).update(options);
    this.textarea.observe('keyup', this.refresh.bind(this));
    this._shadow = new Element('div').setStyle({
      lineHeight : this.textarea.getStyle('lineHeight'),
      fontSize : this.textarea.getStyle('fontSize'),
      fontFamily : this.textarea.getStyle('fontFamily'),
      position : 'absolute',
      top: '-10000px',
      left: '-10000px',
      width: this.textarea.getWidth() + 'px'
    });
    this.textarea.insert({ after: this._shadow });
    this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
    this.textarea.insert({after: this._remainingCharacters});
    this.refresh();
  },

  refresh: function()
  {
    this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
    this.textarea.setStyle({
      height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
    });

    if (this.options.show_remaining) {
        var remaining = this.options.get('max_length') - $F(this.textarea).length;
        this._remainingCharacters.update(Math.abs(remaining)  + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));
    }
  }
});

Widget.MiniTextarea = Class.create({
  initialize: function(textarea, options)
  {
    this.textarea = $(textarea);
    this.options = $H({
      'min_height' : 13,
      'max_length' : 400,
      'show_remaining' :false
    }).update(options);
    this.textarea.observe('keyup', this.refresh.bind(this));
    this._shadow = new Element('div').setStyle({
      lineHeight : this.textarea.getStyle('lineHeight'),
      fontSize : this.textarea.getStyle('fontSize'),
      fontFamily : this.textarea.getStyle('fontFamily'),
      position : 'absolute',
      top: '-10000px',
      left: '-10000px',
      width: this.textarea.getWidth() + 'px'
    });
    this.textarea.insert({ after: this._shadow });
    this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
    this.textarea.insert({after: this._remainingCharacters});
    this.refresh();
  },

  refresh: function()
  {
    this.textarea.setStyle({
      height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
    });

    if (this.options.show_remaining) {
        var remaining = this.options.get('max_length') - $F(this.textarea).length;
        this._remainingCharacters.update(Math.abs(remaining)  + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));
    }
  }
});

