newFromTemplate = function(options) {
  var newId = new Date().getTime();
  $(options.appendTo).append(options.template.replace(/NEW_RECORD/g, newId));
  if(options.success) options.success();
}

// Shwaag tabs uses #!/tabhash in the url to maintain tab state without jumping
// down the page on load. Pass a selector in options.prioritySelector to give
// precedence to a tab that contains that selector - for example '.error'
$.fn.shwaagTabs = function(tabContainers, options) {
    var options = $.extend({}, options);
    return this.each(function() {
        var self = this;
        var $tabs = $(this).find('a');
        var $currentTab = $tabs.filter('[href=#' + location.hash.substring(3) + ']');
        var $tabWithErrors = $(tabContainers).find(options.prioritySelector).first().parents(tabContainers);

        if (options.prioritySelector && $tabWithErrors.length) {
            $currentTab = $('a[href=#' + $tabWithErrors.attr('id') + ']')
        }

        $(tabContainers).hide();

        $tabs.click(function(event) {
            $(tabContainers).hide().filter(this.hash).show();
            $tabs.removeClass('active');
            $(this).addClass('active');
            window.location.hash = "!/" + this.hash.substring(1);
            event.preventDefault();
        });

        if ($currentTab.length) {
            $currentTab.trigger('click');
        } else {
            $tabs.first().trigger('click')
        }
    });
}

// Given a collection of items (like items in a list), rearrange them randomly.
$.fn.randomizeOrder = function() {
    return this.sort(function(a,b){
        var temp = parseInt( Math.random()*10 );
        var isOddOrEven = temp%2;
        var isPosOrNeg = temp>5 ? 1 : -1;
        return( isOddOrEven*isPosOrNeg );
    }).appendTo($(this).parent());
}

Shwaag = function() {
    var self = this;

    var updateTweetCounter = function () {
      var length = 140
      var tweet = $('textarea#tweet-box').val()
      var tweetContents = $('#tweet-ending').html()
      var remainingLength = length - tweet.length - tweetContents.length - 1
      $('#char-count').html(remainingLength)

      if (remainingLength < 0) {
        $('#new_entry input[type=submit]').attr('disabled','disabled')
      } else {
        $('#new_entry input[type=submit]').removeAttr('disabled')
      }
    }

    var campaignCarousel = function() {
        eligibleCampaigns =  $('li.campaign').length

        if (eligibleCampaigns > 1) {
            $(".campaignsWrapper").jCarouselLite({
                auto: 6000,
                speed: 800,
                visible: 1,
                easing: 'easeInOutSine'
            });
        }
    }

    var upcomingCoverFlow = function() {
        $coverflip  = $('.upcoming .upcomingProducts');
          if ($coverflip.length) {
            var queItems    = $('.upcoming .upcomingProducts').html();

            for(i=0; i<9; i++) {
              $coverflip.append(queItems);
            }

            $('.upcoming .upcomingProducts').jcoverflip({
              current: 2,
              beforeCss: function( el, container, offset ){
                el.css({'z-index' : 1 });
                return [
                  $.jcoverflip.animationElement( el, { left: ( container.width( )/2 - 185 - 110*offset + 20*offset )+'px', bottom: '20px' }, { } ),
                  $.jcoverflip.animationElement( el.find( 'img' ), { width: Math.max(10,100-20*offset*offset) + 'px' }, {} )
                ];
              },
              afterCss: function( el, container, offset ){
                el.css({'z-index' : 1 });
                return [
                  $.jcoverflip.animationElement( el, { left: ( container.width( )/2 + 85 + 110*offset )+'px', bottom: '20px' }, { } ),
                  $.jcoverflip.animationElement( el.find( 'img' ), { width: Math.max(10,100-20*offset*offset) + 'px' }, {} )
                ];
              },
              currentCss: function( el, container ){
                el.css({'z-index' : 2 });
                return [
                  $.jcoverflip.animationElement( el, { left: ( container.width( )/2 - 125 )+'px', bottom: 0 }, { } ),
                  $.jcoverflip.animationElement( el.find( 'img' ), { width: '250px' }, { } )
                ];
              }
            });

            var coverflipLength = $coverflip.jcoverflip('length') - 1
            var coverflipDirection = 1
            var coverflipRotate = window.setInterval(function () {
              var currentPosition = $coverflip.jcoverflip('current');

              if (currentPosition == 0 || currentPosition == coverflipLength) {
                coverflipDirection = -coverflipDirection
              }
              if (coverflipDirection == 1) {
                $coverflip.jcoverflip('next');
              } else {
                $coverflip.jcoverflip('previous');
              }
            }, 4000);

            $('.upcoming li').click(function(){
              clearInterval(coverflipRotate);
            })
          }
    }

    var homepage = function() {
        campaignCarousel();
        upcomingCoverFlow();
    }

    var editUser = function() {
        // Bind foodie checkbox to it's subfields
        $("#user_foodie").bind('change', function(){
            var foodie = $(this).filter(':checked').val();
            if (foodie) {
                $('.foodie').show();
            } else {
                $('.foodie').hide();
            }
        }).trigger('change');

        // Bind text notification checkbox to phone number field
        $("#user_text_notification").bind("change", function(){
            var textNotify = $(this).filter(":checked").val();
            if (textNotify) {
                $('.phone').show();
            } else {
                $('.phone').hide();
            }
        }).trigger("change");

        $('a.editToggle').click(function(){
            var container = $(this).parents('.editToggle');
            container.find('.tabContent').toggle();
            container.find('form').toggle();
        });
    }

    var campaign = function() {
        if (window.location.hash == '#!/twitterentry') {
              $("a#twitterentry").trigger("click");
        } else if (window.location.hash == "#!/facebookentry") {
              $("a#facebookentry").trigger("click");
        }

        $('textarea#tweet-box').live("keyup", function (event) {
            updateTweetCounter();
        });

        $("a#twitterentry, a#facebookentry")
            .bind("ajax:loading", function() { $.fancybox.showActivity(); })
            .bind("ajax:complete", function() { $.fancybox.hideActivity(); })
            .bind("ajax:success", function(event, data, status, xhr) {
                $.fancybox(data, {
                    autoDimensions: false,
                    width: 560,
                    height: 'auto'
                });

                if ($('textarea#tweet-box').length) { updateTweetCounter(); }
            });

        $("form#new_entry")
          .live("ajax:loading", function() { $.fancybox.showActivity(); })
          .live("ajax:complete", function() { $.fancybox.hideActivity(); })

        // Product image gallery
        $('figure.polaroid li.thumbnail a').click(function (event) {
            event.preventDefault();
            $('img#productImage').attr('src', this.href)
        });
    }

    return {
        homepage: homepage,
        editUser: editUser,
        campaign: campaign
    }
}();

$(function(){
    if (window.location.pathname == '/') {
        Shwaag.homepage();
    } else if (window.location.pathname.match(/campaigns\/(.+)/)) {
        Shwaag.campaign();
    } else if (window.location.pathname.match(/users/)) {
        Shwaag.editUser();
        $("a.toggle-user-search").click(function(){
          $(this).parent().next("form").slideToggle();
          event.preventDefault();
        })
    }

    // Everything past this point should run on every page
    if ($('#entry-form .fieldWithErrors').length) {
        $("#entry-button a").trigger('click')
    }

    $('ul.tabs.activetabs').shwaagTabs('.tabs > div.tab', {
        prioritySelector: '.fieldWithErrors, .formError, .entrybutton'
    });

    $('a#signin, .fancybox:not(form):not(section)').fancybox({
        'transitionIn'   : 'elastic',
        'transitionOut'  : 'elastic'
    });

    $('#flash, #env').click(function () {
        $(this).slideUp();
    });

    window.setTimeout(function(){
        $("#flash").slideUp();
    }, 2000);

    $("ul#nav-actions").hide();
    $("a#nav-actions-button").click(function(){
    $("ul#nav-actions").toggle();
        return false;
    });

    $('a#new-image').click(function(){
        newFromTemplate({
            template: image,
            appendTo: '#imageFields'
        });
        event.preventDefault();
    });

    $(".tabs a").each(function(i, element){
        link = $(element)
        if (link.attr("href") == location.pathname) {
            link.addClass("active");
        }
    })
});

(function($) {
    if (!$("meta[name=campaign-twitter-search]").length) return;

    var searchTerm = $("meta[name=campaign-twitter-search]").attr("content"),
        searchLanguage = $("meta[name=campaign-twitter-language]").attr("content"),
        twitterSearchURL = "http://search.twitter.com/search.json?q=" +
          searchTerm + "&lang=" + searchLanguage + "&callback=?";

    $.getJSON(twitterSearchURL, function(data) {
        var template = $("script[name=tweets]").html(),
            output = Mustache.to_html(template, data);

        $(function() {
            $("ul#reviews").append(output);
            if ($('.reviewsWrapper > ul > li').length > 7) {
                var reviewsCarousel = $(".reviewsWrapper").jCarouselLite({
                    speed: 1000,
                    vertical: true,
                    visible: 7,
                    btnPrev: '.reviewsPrev',
                    btnNext: '.reviewsNext',
                    easing: 'easeInSine',
                    beforeStart: function(a) {
                        a.first().prev().find('.img, .imgExt, .content').hide();
                    },
                    afterEnd: function(a) {
                        a.first().find('.img, .imgExt, .content').fadeIn(600);
                    }
                });

                // trigger slide to next element
                // set random delay between 5 and 11 seconds before next slide
                function rotateReview() {
                    $('.reviewsPrev').trigger('click');
                    var delay = (5 + Math.floor(Math.random()*6)) * 1000;
                    window.setTimeout(rotateReview, delay);
                }
                rotateReview();
            }
        });
    });
})(jQuery);

(function($) {
    if (location.pathname !== "/") return;

    $.getJSON("/entries/winners", function(data) {
        var template = $("script[name=winners]").html(),
            output = Mustache.to_html(template, { winners: data });

        $(function(){
            $("#winners").html(output);

            // On the homepage, rearrange the ordered list of all Shwaagees
            // then create a vertical carousel
            $('#winners ul li.winner').randomizeOrder()
            $("#winners").jCarouselLite({
                auto: 4000,
                vertical: true,
                visible: 4,
                easing: 'easeInOutSine'
            });
        });
    });
})(jQuery);

