/*
/*  seeds.js
*/

jQuery.noConflict();

var Seeds = new Object({
  CurrentBannerSlide:    0,
  BannerIsTransitioning: false,
  BannerTimer:           null,
  BannerAppearDuration:  1.0,
  
  BubbleWidth:     280,
  BubbleMargin:    20, 
  BubbleMinHeight: 60,
  
  TabsContentWidth: 940,
  
  SupportsH264AndVideoTag: false,
  
  showBubble: function (at, url) {
    var atCenter = [
      at.cumulativeOffset().left + at.getWidth() / 2.0,
      at.cumulativeOffset().top + at.getHeight()
    ];
    var bubbleOrigin = [
      Math.min(
        Math.max(640, document.viewport.getWidth()) - 
          (Seeds.BubbleWidth + Seeds.BubbleMargin),
        Math.max(20, atCenter[0] - Seeds.BubbleWidth / 2.0)
      ),
      atCenter[1],
    ];
    var arrowOrigin = Math.max(10, 
      Math.min(Seeds.BubbleWidth - 31,
        atCenter[0] - bubbleOrigin[0]));
    
    var bubble = Builder.node("div", { className: "bubble" }, [
      Builder.node("div", { className: "arrow" }),
      Builder.node("div", { className: "content" })
    ]);
    bubble.setStyle({
      top:  bubbleOrigin[1] + "px",
      left: bubbleOrigin[0] + "px"
    });
    bubble.down(".arrow").setStyle({
      left: arrowOrigin + "px"
    });
    
    new Ajax.Request(url, {
      method: "get",
      onSuccess: function (resp) {
        bubble.down(".content").update(resp.responseText);
        
        $("bubbles").update(bubble);
        $("bubbles").addClassName("active");
      },
    });
  },
  
  hideAllBubbles: function (event) {
    if (event)
      if (event.element() != $("bubbles"))
        return;
    
    new Effect.Fade($("bubbles"), {
      duration: 0.15,
      afterFinish: function () {
        $("bubbles").update("");
        $("bubbles").removeClassName("active");
        $("bubbles").show();
      }
    });
    
    $("bubbles").removeClassName("active");
  },
  
  observeBanner: function (banner) {
    banner.select(".slide").each(function (slide, index) {
      if (index != Seeds.CurrentBannerSlide)
        slide.hide();
    });
    Seeds.showBannerSlideAtIndex(banner, Seeds.CurrentBannerSlide);
    
    banner.select(".pager a").each(function (a, index) {
      a.observeClick(function () {
        Seeds.stopBannerRotation(banner);
        Seeds.showBannerSlideAtIndex(banner, index);
      });
    });
    Seeds.BannerTimer = new PeriodicalExecuter(function () {
      Seeds.showNextBannerSlide(banner);
    }, 10.0);
  },
  
  stopBannerRotation: function (banner) {
    Seeds.BannerTimer.stop();
    Seeds.BannerAppearDuration = 0.25;
  },
  
  showNextBannerSlide: function (banner) {
    if (Seeds.BannerIsTransitioning) return;
    
    var nextSlide = Seeds.CurrentBannerSlide + 1;
    if (nextSlide > (banner.select(".slide").length - 1))
      nextSlide = 0;
    Seeds.showBannerSlideAtIndex(banner, nextSlide);
  },
  
  showBannerSlideAtIndex: function (banner, newIndex) {
    if (Seeds.BannerIsTransitioning) return;
    
    banner.select(".slide").each(function (slide, index) {
      if (index == newIndex) {
        if (newIndex != Seeds.CurrentBannerSlide) {
          slide.setStyle({ zIndex: 100, opacity: 0.0 });
          slide.show();
          new Effect.Appear(slide, {
            duration: Seeds.BannerAppearDuration,
            beforeStart: function () { Seeds.BannerIsTransitioning = true; },
            afterFinish: function () { Seeds.BannerIsTransitioning = false; }
          });
        }
      } else if (index == Seeds.CurrentBannerSlide) {
        slide.setStyle({ zIndex: 99, opacity: 1.0 });
      } else {
        slide.setStyle({ zIndex: 98, opacity: 0.0 });
        slide.hide();
      }
    });
    
    banner.select(".pager a").each(function (a, index) {
      if (index == newIndex) a.addClassName("current");
      else                   a.removeClassName("current");
    });
    
    Seeds.CurrentBannerSlide = newIndex;
  },
  
  playWelcomeVideo: function (a) {
    if (!Seeds.SupportsH264AndVideoTag)
      return (document.location = a.href);
    
    Seeds.stopBannerRotation($("banner"));
    $("banner").down(".pager").hide();
    
    var div = Builder.node("div", { className: "video" }, [
      Builder.node("video", {
        src:      a.href,
        autoplay: "yes",
        controls: "yes",
        width:    $("welcome-slide").getWidth(),
        height:   $("welcome-slide").getHeight(),
      }),
      Builder.node("span", { className: "close" })
    ]);
    
    div.setOpacity(0.0);
    
    div.down(".close").observeClick(function () {
      Seeds.stopWelcomeVideo();
    });
    
    $("welcome-slide").insert(div);
    new Effect.Appear(div, { duration: 0.5 });
    
    div.down("video").addEventListener(
      "ended", Seeds.stopWelcomeVideo, true
    );
  },
  
  stopWelcomeVideo: function () {
    $$("#welcome-slide .video").each(function (div) {
      var video = div.down("video");
      if (video) {
        video.controls = false;
        new Effect.Tween(null, 1.0, 0.0, { duration: 0.5 },
          function (value) { video.volume = value }
        );
      }
      
      new Effect.Fade(div, {
        duration: 0.5,
        afterFinish: function () {
          if (video && video.currentTime) {
            video.pause();
            video.currentTime = 0;
          }
          div.remove();
        }
      });
    });
    
    new Effect.Appear($("banner").down(".pager"));
  },
  
  play21Video: function (a) {
    if (!Seeds.SupportsH264AndVideoTag)
      return (document.location = a.href);
    
    Seeds.stopBannerRotation($("banner"));
    $("banner").down(".pager").hide();
    
    var div = Builder.node("div", { className: "video" }, [
      Builder.node("video", {
        src:      a.href,
        autoplay: "yes",
        controls: "yes",
        width:    $("twentyone-promo").getWidth(),
        height:   $("twentyone-promo").getHeight(),
      }),
      Builder.node("span", { className: "close" })
    ]);
    
    div.setOpacity(0.0);
    
    div.down(".close").observeClick(function () {
      Seeds.stop21Video();
    });
    
    $("twentyone-promo").insert(div);
    new Effect.Appear(div, { duration: 0.5 });
    
    div.down("video").addEventListener(
      "ended", Seeds.stop21Video, true
    );
  },
  
  stop21Video: function () {
    $$("#twentyone-promo .video").each(function (div) {
      var video = div.down("video");
      if (video) {
        video.controls = false;
        new Effect.Tween(null, 1.0, 0.0, { duration: 0.5 },
          function (value) { video.volume = value }
        );
      }
      
      new Effect.Fade(div, {
        duration: 0.5,
        afterFinish: function () {
          if (video && video.currentTime) {
            video.pause();
            video.currentTime = 0;
          }
          div.remove();
        }
      });
    });
    
    new Effect.Appear($("banner").down(".pager"));
  },
  
  playConferenceVideo: function (a) {
    Seeds.stopBannerRotation($("banner"));
    $("banner").down(".pager").hide();
    
    var div = Builder.node("div", { className: "video" }, [
      Builder.node("iframe", {
        src:         a.up().down(".vimeo").href,
        width:       $("seeds-conference").getWidth(),
        height:      $("seeds-conference").getHeight(),
        frameborder: 0,
        scroll:      "false"
      }),
      Builder.node("span", { className: "close" })
    ]);
    
    div.down(".close").observeClick(function () {
      Seeds.stopConferenceVideo();
    });
    
    $("seeds-conference").insert(div);
  },
  
  stopConferenceVideo: function () {
    $$("#seeds-conference .video").each(function (div) {
      var video = div.down("video");
      if (video) {
        video.controls = false;
        new Effect.Tween(null, 1.0, 0.0, { duration: 0.5 },
          function (value) { video.volume = value }
        );
      }
      
      new Effect.Fade(div, {
        duration: 0.5,
        afterFinish: function () {
          if (video && video.currentTime) {
            video.pause();
            video.currentTime = 0;
          }
          div.remove();
        }
      });
    });
    
    new Effect.Appear($("banner").down(".pager"));
  },
  
  observeTabs: function (tabs) {
    tabs.select(".nav > li").each(function (li, index) {
      li.down("a").observeClick(function () {
        Seeds.selectTabByIndex(tabs, index);
      });
    });
  },
  
  selectTabByIndex: function (tabs, anIndex) {
    tabs.select(".nav > li").each(function (li, index) {
      if (index == anIndex)
        li.addClassName("current");
      else
        li.removeClassName("current");
    });
    
    new Effect.Move(tabs.down(".content"), {
      x:        -anIndex * Seeds.TabsContentWidth, 
      mode:     "absolute",
      duration: 0.5,
    });
  },
  
  showMoreItems: function (url, ul) {
    new Ajax.Request(url, {
      method: "get",
      onSuccess: function (response) {
        ul.update(response.responseText);
      }
    })
  },
  
  showPreviewAtIndex: function (newIndex) {
    $$("#previews video").each(function (video) {
      new Effect.Tween(null, 1.0, 0.0, {
        duration: 0.5,
        afterFinish: function () {
          video.pause();
          video.volume = 1.0;
        }
      }, function (value) { video.volume = value });
    });
    
    $$("#previews > div").each(function (div, index) {
      if (index == newIndex) {
        if (!div.hasClassName("current")) {
          var previous = div.up().down(".current");
          if (previous) {
            previous.setStyle({ zIndex: 99 });
            previous.removeClassName("current");
            previous.addClassName("previous");
          }
          
          div.setStyle({ zIndex: 100, opacity: 0.0 });
          div.addClassName("current");
          
          new Effect.Appear(div, {
            duration: 0.25,
            afterFinish: function () {
              previous.removeClassName("previous");
            }
          });
        }
      } else if (div.hasClassName("previous")) {
        div.setStyle({ zIndex: 99 });
      } else {
        div.setStyle({ zIndex: 98 });
      }
    });
    
    $$("#preview-thumbs > li").each(function (li, index) {
      if (index == newIndex)
        li.addClassName("current");
      else
        li.removeClassName("current");
    });
  },
  
  hideFlash: function () {
    if (!$("flash")) return;
    new Effect.Fade("flash", {
      duration: 0.25,
      afterFinish: function () {
        $("flash").remove();
      }
    });
  }
});

Element.addMethods({
  observeClick: function (el, func) {
    el = $(el);
    if (el.tagName == "A")
      el.onclick = Prototype.K.bind(el, false);
    el.observe("click", func);
  }
});

document.observe("dom:loaded", function () {
  var videoTest = document.createElement("video") || false;
  var videoTag  = videoTest && typeof videoTest.canPlayType !== "undefined";
  var h264      = videoTag && (videoTest.canPlayType("video/mp4") === "maybe" ||
                               videoTest.canPlayType("video/mp4") === "probably");
  Seeds.SupportsH264AndVideoTag = !!h264;
  
  (new Image()).src = "/images/banners/conf-app-on.png";
  (new Image()).src = "/images/banners/conf-mobile-on.png";
  (new Image()).src = "/images/banners/conf-download-on.png";
  
  (new Image()).src = "/images/banners/cwf-download-hover.png";
  (new Image()).src = "/images/banners/cwf-blog-hover.png";
  
  var cwf = new Image();
  cwf.onload = function () {
    $("cwf2009").setStyle({backgroundImage: "url(" + this.src + ")"});
  };
  cwf.src = "/images/banners/cwf.png";
  
  (new Image()).src = "/images/search-on.png";
  (new Image()).src = "/images/button-green.png";
  (new Image()).src = "/images/button-orange.png";
  
  $$("#login, p.login a, a.login, a.bubble").each(function (a) {
    a.observeClick(function () {
      Seeds.showBubble(this, this.href);
    });
  });
  
  $("bubbles").observeClick(Seeds.hideAllBubbles);
  
  $$(".home #banner").each(Seeds.observeBanner);
  $$(".home #new").each(Seeds.observeTabs);
  
  $$(".home #welcome-slide .play").each(function (a) {
    a.observeClick(function () {
      Seeds.playWelcomeVideo(a);
    });
  });
  
  $$(".home #twentyone-promo .play").each(function (a) {
    a.observeClick(function () {
      Seeds.play21Video(a);
    });
  });
  
  $$(".home #seeds-conference .conf-play").each(function (a) {
    a.observeClick(function () {
      Seeds.playConferenceVideo(a);
    });
  });
  
  $$(".list .items .more a").each(function (a) {
    a.observeClick(function () {
      Seeds.showMoreItems(a.href, a.up("ul"));
    });
  });
  
  $$(".view #preview-thumbs a").each(function (a, index) {
    a.observeClick(function () {
      Seeds.showPreviewAtIndex(index);
    });
  });
  
  $$(".view a.play").each(function (a) {
    a.observeClick(function () {
      if (!Seeds.SupportsH264AndVideoTag)
        return (document.location = a.href);
      
      a.up().insert(Builder.node("div", { className: "video" }, [
        Builder.node("video", {
          src:      a.href,
          autoplay: "yes",
          controls: "yes",
          width:    a.up().getWidth(),
          height:   a.up().getHeight()
        })
      ]));
    });
  });
  
  var mimeTypes = $A(navigator.mimeTypes).map(function (type) {
    return type["type"];
  });
  if (!mimeTypes.include("application/x-shockwave-flash")) {
    $$(".blog .vimeo").each(function (div) {
      var id  = parseInt(div.identify().split("-")[1]);
      var url = "http://vimeo.com/" + id;
      if (id > 0)
        div.update("<p><a href=\"" + url + "\">Watch on Vimeo</a></p>");
    });
  }
  
  var flash = $("flash");
  if (flash) {
    flash.observeClick(Seeds.hideFlash);
    window.setTimeout(Seeds.hideFlash, 2000);
  }
  
  $$(".blog .post .wrapper").each(function (wrapper) {
    var inner    = wrapper.down(".inner-wrapper");
    var readMore = wrapper.up().down(".read-more");
    
    var topEles   = inner.childElements().slice(0, 3);
    var maxHeight = topEles.inject(0.0, function (sum, ele) {
      return sum + ele.measure("margin-box-height");
    }) - topEles.last().measure("margin-bottom");
    
    var isEmbedOnly = inner.childElements().length == 1 &&
                      inner.childElements()[0].tagName == "IFRAME";
    
    if (inner.getHeight() > maxHeight && !isEmbedOnly) {
      wrapper.addClassName("on");
      wrapper.setStyle({ maxHeight: maxHeight + "px" });
      readMore.addClassName("on");
      
      var fromHeight = maxHeight;
      var toHeight   = inner.getHeight();
      var duration   = (toHeight - fromHeight) / 4000.0;
      if (duration < 0.25)
        duration = 0.25;
      
      readMore.down("a").observeClick(function () {
        if (event.shiftKey)
          duration = duration / 0.1;
        
        if (event.altKey) {
          $$(".blog .post").each(function (post) {
            var wrapper = post.down(".wrapper");
            wrapper.removeClassName("on");
            wrapper.setStyle({ maxHeight: null });
            
            var readMore = post.down(".read-more");
            if (readMore)
              readMore.remove();
          });
        } else {
          new Effect.Tween(null, 1.0, 0.0, {
            duration: duration
          }, function (value) {
            readMore.setStyle({ opacity: value });
          });
          
          new Effect.Tween(null, readMore.getHeight(), 0, {
            duration: duration
          }, function (value) {
            readMore.setStyle({ height: value + "px" });
          });
          
          new Effect.Tween(null, fromHeight, toHeight, {
            duration: duration,
            afterFinish: function () {
              wrapper.removeClassName("on");
              wrapper.setStyle({ maxHeight: null });
              readMore.remove();
            }
          }, function (value) {
            wrapper.setStyle({ maxHeight: value + "px" });
          });
        }
      });
    } else {
      readMore.remove();
    }
  });
  
  $$(".blog #comment form")[0].observe("submit", function () {
    $(this).down("input[type=submit]").disabled = true;
  });
});

Event.observe(window, "load", function () {
  $$(".blog #authors .photo img").each(function (img) {
    var newImage = new Image();
    newImage.onload = function () {
      img.src = newImage.src;
    }
    newImage.src = img.src.replace("38x38", "152x152");
  });
});

