jQuery.noConflict();

function openWindowCentered(url, name, height, width, features) {
  var top = screen.height && height < screen.height ? (screen.height - height) / 2 : 0;
  var left = screen.width && width < screen.width ? (screen.width - width) / 2 : 0;
  return window.open(url, name, "top=" + top + ",left=" + left + ",width=" + width + ",height=" + height + "," + features);
}

var Browser = {
  ua: function() {
    return navigator.userAgent;
  },
  engine: function() {
    var agent = this.ua();
    if (agent.match(/WebKit/))  return "webkit"
    if (agent.match(/Gecko\//)) return "gecko"
    if (agent.match(/MSIE/))    return "ie"
    if (agent.match(/Opera/))   return "opera"
  },
  version: function() {
    var agent = this.ua();
    var v, r = [];
    if (v = agent.match(/Version\/(\d).*Mobile.*Safari/))  r = ["mobile"]
    if (v = agent.match(/Chrome\/(\d)/))                   r = ["chrome", v[1]]
    if (v = agent.match(/Version\/(\d).*Safari/))          r = ["safari", v[1]]
    if (v = agent.match(/Firefox\/(\d)\.([1-9])/))         r = ["ff", v[1], "_", v[2]]
    if (v = agent.match(/Firefox\/(\d)/))                  r = ["ff", v[1]]
    if (v = agent.match(/MSIE (\d)/))                      r = ["ie", v[1]]
    return r.join("")
  },
  platform: function() {
    var agent = this.ua();
    if (agent.match(/Macintosh/)) return "mac"
    if (agent.match(/iPhone/))    return "iphone"
    if (agent.match(/Windows/))   return "win"
    if (agent.match(/Linux/))     return "linux"
  },
  to_s: function() {
    return [
      this.engine(),
      this.version(),
      this.platform()
    ].join(" ")
  }
};

if (typeof(VideoJS) != "undefined")
  VideoJS.setupAllWhenReady();

// Prototype stuff
// TODO: Convert to jQuery

if (typeof(Prototype) != "undefined") {
  var Gallery = Class.create({
    initialize: function(element) {
      this.anchorId = location.hash.gsub("#", "");
      this.element = $(element);
      this.firstImageLink = this.element.getAttribute("data:firstImageLink");
      this.lastImageLink  = this.element.getAttribute("data:lastImageLink");
      this.selectedThumb = null;
      this.selectedPage  = this.element.down("#pager a.selected");
      this.viewer  = new Gallery.Viewer(this.element.down("#viewer"), this);
      this.thumbs  = this.element.select("#thumbs > a")
                         .map(function(el){return new Gallery.Thumb(el, this)}.bind(this));
      
      if (this.selectedThumbCandidate)
        this.selectedThumbCandidate.select();
      else
        this.thumbs.first().select();
    },
    previousThumb: function() {
      if (this.selectedThumb != this.thumbs.first())
        this.thumbs[this.thumbs.indexOf(this.selectedThumb)-1].select();
      else
        if (prevPage = this.selectedPage.previousSiblings().first())
          location.href = prevPage.href;
    },
    nextThumb: function() {
      if (this.selectedThumb != this.thumbs.last())
        this.thumbs[this.thumbs.indexOf(this.selectedThumb)+1].select();
      else
        if (nextPage = this.selectedPage.nextSiblings().first())
          location.href = nextPage.href;
    },
    firstThumb: function() {
      location.href = this.firstImageLink;
    },
    lastThumb: function() {
      location.href = this.lastImageLink;
    }
  });
  Gallery.Viewer = Class.create({
    initialize: function(element, gallery) {
      this.gallery = gallery;
      this.element = $(element);
      this.image   = this.element.down("img");
      this.imagePosition = this.element.down("#image_position");
      this.video   = this.element.down("#video");
      this.info    = this.element.down("#info");
      this.controls= this.element.down("#controls");
    
      this._buildControls();
    },
    loadThumb: function(thumb) {
      this.imagePosition.update(thumb.position);
      this.info.update(thumb.info);
      
      if (!flash_detected)
        location.href = "#"+ thumb.id;
      
      if (thumb.isVideo) {
        this.image.hide();
        this.video.update("");
        this.video.show();
        this._buildVideoElement(thumb);
        VideoJS.setup(this.video.down("video"));
      } else {
        this.image.src = thumb.bigSrc;
        this.image.show();
        this.video.update("");
        this.video.hide();
      }
      
      this._manageControls();
    },
    _buildVideoElement: function(thumb) {
      useFlowPlayer = false;
      flashMovieSrc = useFlowPlayer ? 
                        "http://releases.flowplayer.org/swf/flowplayer-3.2.3.swf" : 
                        fvpUrl;
      flashVars     = useFlowPlayer ? 
                        "config={'playlist':['"+ thumb.posterURL +"', {'autoBuffering':true, 'autoPlay':true, 'url':'"+ thumb.flashVideoURL +"'}]}" :
                        "buffer=4&theSound=1&playAuto=1&width=623&height=400&flvPath="+ thumb.flashVideoURL +"&startImagePath="+ thumb.posterURL;

      videoElement = new Element("video", {
        "width": 623, "controls": false, "preload": true, "poster": thumb.posterURL, 
        "className": "video-js-single"
      });
      sourceElement = new Element("source", {"src": thumb.videoURL, "type": "video/mp4"});
      videoElement.appendChild(sourceElement);
      
      flashElement = new Element("object", {
        "class": "vjs-flash-fallback",
        "data": flashMovieSrc, 
        "type": "application/x-shockwave-flash", 
        "height": (useFlowPlayer ? 346 : 440),
        "width": 623
      });
      flashElement.appendChild(new Element("param", {"name": "movie", "value": flashMovieSrc}));
      flashElement.appendChild(new Element("param", {"name": "flashvars", "value": flashVars}));
      flashElement.appendChild(new Element("param", {"name": "allowFullscreen", "value": "true"}));
      flashElement.appendChild(new Element("param", {"name": "allowNetworking", "value": "all"}));
      flashElement.appendChild(new Element("param", {"name": "allowScriptAccess", "value": "always"}));
      flashElement.appendChild(new Element("param", {"name": "wmode", "value": "transparent"}));
      
      videoElement.appendChild(flashElement);
      this.video.appendChild(videoElement);
    },
    _manageControls: function() {
      if (this.gallery.selectedThumb == this.gallery.thumbs.first() &&
          this.gallery.selectedPage.previousSiblings().size() == 0) {
        this.prevLink.addClassName("inactive");
        this.firstLink.addClassName("inactive");
      } else {
        this.prevLink.removeClassName("inactive");
        this.firstLink.removeClassName("inactive");
      }
      
      if (this.gallery.selectedThumb == this.gallery.thumbs.last() &&
          this.gallery.selectedPage.nextSiblings().size() == 0) {
        this.nextLink.addClassName("inactive");
        this.lastLink.addClassName("inactive");
      } else {
        this.nextLink.removeClassName("inactive");
        this.lastLink.removeClassName("inactive");
      }
    },
    _buildControls: function() {
      if (this.gallery.firstImageLink) {
        this.firstLink = new Element("a", {"id": "firstLink"});
        this.firstLink.observe("click", this.gallery.firstThumb.bind(this.gallery));
        this.controls.appendChild(this.firstLink);
      }

      this.prevLink = new Element("a", {"id": "previousLink"});
      this.prevLink.observe("click", this.gallery.previousThumb.bind(this.gallery));
      this.controls.appendChild(this.prevLink);
    
      if (this.gallery.lastImageLink) {
        this.lastLink = new Element("a", {"id": "lastLink"});
        this.lastLink.observe("click", this.gallery.lastThumb.bind(this.gallery));
        this.controls.appendChild(this.lastLink);
      }

      this.nextLink = new Element("a", {"id": "nextLink"});
      this.nextLink.observe("click", this.gallery.nextThumb.bind(this.gallery));
      this.controls.appendChild(this.nextLink);
    }
  })
  Gallery.Thumb = Class.create({
    initialize: function(element, gallery) {
      this.gallery = gallery;
      this.element = $(element);
      this.id      = this.element.readAttribute("data:id");
      this.bigSrc  = this.element.href;
      this.position= this.element.readAttribute("data:position");
      this.info           = this.element.readAttribute("title");
      this.videoURL       = this.element.readAttribute("data:videourl");
      this.flashVideoURL  = this.element.readAttribute("data:flash_videourl") || this.videoURL;
      this.posterURL      = this.element.readAttribute("data:posterurl");
      this.isVideo        = (this.videoURL) ? true : false;
      
    
      this.element.observe("click", this.click.bind(this));
    
      if (this.element.hasClassName("selected") ||
          this.id == this.gallery.anchorId)
        this.gallery.selectedThumbCandidate = this;
    },
    click: function(ev) {
      ev.stop();
      location.href = "#" + this.id;
      this.select();
    },
    select: function() {
      if (this.gallery.selectedThumb != this) {
        if (this.gallery.selectedThumb != undefined)
          this.gallery.selectedThumb.unselect();
      
        this.gallery.selectedThumb = this;
        this.element.addClassName("selected");
        this.gallery.viewer.loadThumb(this);
      }
    },
    unselect: function() {
      this.element.removeClassName("selected");
    }
  });

  $(document).observe("dom:loaded", function() {
    var gallery = $("gallery");
    if (gallery)
      new Gallery(gallery);
  });
}

// jQuery stuff

if (typeof(jQuery) != "undefined") {
  var ButtonHelper = {
    spanify: function() {
      jQuery("#pager a, .filter a, .filter_modus a").wrapInner("<span />");
    },
    iconify: function() {
      jQuery(".button.with_icon span").wrapInner("<em />");
    }
  };
  var HomepageTeaser = {
    enhance: function() {
      jQuery("#homepage_teaser a.image").wrapInner("<span />");
      jQuery("#homepage_teaser div").click(function() {
        location.href = jQuery(this).children("a.image").attr("href");
      });
    }
  };
  var Galleries = {
    enhance: function() {
      jQuery("#galleries a img").wrap("<span />");
      jQuery("#galleries .gallery").click(function() {
        location.href = jQuery(this).children("a").attr("href");
      })
    }
  }
  
  jQuery().ready(function() {
    jQuery("html").addClass(Browser.to_s());
    jQuery("html").addClass("js");
    
    // ============
    // = AGE GATE =
    // ============
    if (jQuery("#agegate").length > 0) {
      jQuery("#page").hide();
      
      jQuery("#agegate input").keypress(function(e) {
        if (e.keyCode == 13) {
          jQuery("#agegate .actions a")[0].click();
        };
      });
      
      if (jQuery().uniform) {
        jQuery("#agegate select").uniform();
      }

      if (jQuery().autotab) {
        jQuery("#agegate .date input").autotab_magic().autotab_filter("numeric");
      }
    }
    
    // ===========
    // = GENERAL =
    // ===========
    
    if (jQuery().colorbox) {
      jQuery(".popup").colorbox({innerWidth:500, innerHeight:500, iframe:true});
      if (jQuery("#agegate .error-message").length > 0) {
        jQuery.colorbox({inline:true, href:"#agegate .error-message", innerWidth:500});
      }
    }
    
    if (jQuery().placeholder) {
      jQuery("input").placeholder();
    }
    
    ButtonHelper.spanify();
    ButtonHelper.iconify();
    
    HomepageTeaser.enhance();
    Galleries.enhance();
  });
}
