document.observe("dom:loaded", initPortfolio);
conversionProcessed = false; 
function initPortfolio(){
	var carousels = [];
	$$("div.horizontal_carousel").each(function(div){
		var carousel = new UI.Carousel(div);
		carousels.push(carousel);
		carousel.observe("scroll:ended", onScrollEnded.bind(this, carousel));
		carousel.observe("scroll:started", onScrollStarted.bind(this, carousel));
		onScrollEnded(carousel);
	});
	Event.observe(window, "resize", function(){
		carousels.each(function(carousel){carousel.updateSize(); onScrollStarted(carousel); onScrollEnded(carousel);});
	});
	$$("#project h2 a, p.tags a").each(function(a){
		var id = a.href.replace(/.*#/, "");
		if(!id){return;}
		var target = $(id);
		if(target){
			a.observe("click", function(event){event.stop(); smothScrollTo(target);});
		}
	});
	
	try{
	if($("getELROform")){
		var processResponse = function(xhr){
			$("getELROform").down("fieldset").className = "";
			if(xhr.status == 200){
				var response = null;
				try{
					response = eval('('+xhr.responseText+')');
				}catch(e){};
				if(response && response.status == "ok"){
					$("getELROform").down("fieldset").className = "success";
					if(!conversionProcessed){conversion();}
					return;
				}
			}
			$("getELROform").down("fieldset").className = "error";
		};
		var contactSubmitCallback = function(errors, event){
			if(commonSubmitCallback(errors, event)){
				$("getELROform").down("fieldset").className = "progress";
				var startTime = new Date().getTime();
				$("getELROform").request({onComplete: function(xhr){
					var endTime = new Date().getTime();
					var delta = endTime - startTime;
					var timeout = 2000;
					if(delta < timeout){
						setTimeout(processResponse.bind(null, xhr), timeout-delta);
					}else{
						processResponse(xhr);
					}
				}});
			}
		};
		var conditions = {};
		if($("email") && $("subject") && $("message")){
			conditions = Object.extend(required("subject", "message"), {email: {submit: ['notBlank', 'email']}});
		}
		if($("name") && $("company") && $("email") && $("phone") && $("time")){
			conditions = Object.extend(required("name", "company", "phone", "time"), {email: {submit: ['notBlank', 'email']}});
		}
    var validator = new Validator(conditions, {afterValidate: contactSubmitCallback});
		if($("getELROformSubmit")){
			$("getELROformSubmit").observe("click", function(event){
				event.stop(); 
				validator.validateAllByType("submit", contactSubmitCallback);
			});
		}
		if($("oneMoreMessage")){$("oneMoreMessage").observe("click", function(event){event.stop(); $("getELROform").down("fieldset").className = ""; $("getELROform").reset();});}
	}
	}catch(e){};
}
function conversion(){
	var sc = document.createElement("iframe");
	sc.setAttribute("src", "/services/form-google-track?t="+(new Date()).valueOf());
	sc.style.display = "none";
	document.body.appendChild(sc);
	conversionProcessed = true;
}
function smothScrollTo(id, options){
	var element = $(id);
	if(!element){return;}
	var offset = element.cumulativeOffset()[1]-document.viewport.getScrollOffsets()[1];
	var params = Object.extend({
		duration: 0.5,
		fps: 100
	}, options);
	var interval = params.duration*params.fps;
	var frames = Math.floor(params.duration*1000/interval);
	var frameOffset = Math.floor(offset/frames);
	if(!frameOffset){return;}
	var scrollByFrame = function(){
		window.scrollBy(0, frameOffset);
		frames--;
		if(frames){
			setTimeout(scrollByFrame, interval);
		}
	}
	scrollByFrame();
}
try{
	Object.extend(UI.Carousel.prototype, {
		scroll: function(deltaPixel) {
	    if (this.animating)
	      return this;
	
	    // Compute new position
	    var position =  this.currentPosition() + deltaPixel;
	
	    // Check bounds
	    position = this.checkScroll(position, false);
	
	    // Compute shift to apply
	    deltaPixel = position - this.currentPosition();
	    if (deltaPixel != 0) {
	      this.animating = true;
	      this.fire("scroll:started");
	
	      var that = this;
	      // Move effects
	      //this.container.morph("opacity:0.5", {duration: 0.2, afterFinish: function() {
	        that.container.morph(that.posAttribute + ": " + position + "px", {
	          duration: 0.4,
	          delay: 0.2,
	          afterFinish: function() {
	            that.container.morph("opacity:1", {
	              duration: 0.2,
	              afterFinish: function() {
	                that.animating = false;
	                that.updateButtons()
	                  .fire("scroll:ended", { shift: deltaPixel / that.currentSize() });
	              }
	            });
	          }
	        });
	      //}});
	    }
	    return this;
	  },
	  updateNextButton: function() {
	    var lastPosition = this.currentLastPosition();
	    var size = this.currentSize();
	    var nextClassName = "next_button" + this.options.disabledButtonSuffix;
	
	    if (this.nextButton.hasClassName(nextClassName) && lastPosition > size) {
	      this.nextButton.removeClassName(nextClassName);
	      this.fire('nextButton:enabled');
	    }
	    if (!this.nextButton.hasClassName(nextClassName) && lastPosition <= size) {
		    this.nextButton.addClassName(nextClassName);
	      this.fire('nextButton:disabled');
	    }
	  }
	});
}catch(e){};

function onScrollEnded(carousel){
	var elementSize = carousel.computeElementSize();
	var carouselSize = carousel.currentSize();
	var currentIndex = carousel.currentIndex();
	var currentLastIndex = carouselSize/elementSize + currentIndex;
	if(Math.floor(currentIndex) != currentIndex && carousel.elements[Math.floor(currentIndex)]){
		carousel.elements[Math.floor(currentIndex)].addClassName("cut");
	}
	if(Math.floor(currentLastIndex) != currentLastIndex && carousel.elements[Math.floor(currentLastIndex)]){
		carousel.elements[Math.floor(currentLastIndex)].addClassName("cut");
	}
}
function onScrollStarted(carousel){
	carousel.elements.each(function(element){element.removeClassName("cut");});
}

var FlashGallery = Class.create();
FlashGallery.prototype = {
  initialize: function(options){
		if(!(options && options.items)){return;}
		this.activeItem = null;
		this.activeItemHTML = null;
		this.defaultParams = Object.extend({
			version: "6.0.0",
			expressInstall: "", 
			flashvars: {}, 
			params: {}, 
			attributes: {},
			callback: null
		}, options.defaultParams);
		$H(options.items).each(function(item){
			this.addHandler(item.key, Object.extend(Object.clone(this.defaultParams), item.value));
		}.bind(this));
	},
	addHandler: function(element, args){
		$(element).observe("click", function(event){
			event.stop();
			if(this.activeItem){this.activeItem.innerHTML = this.activeItemHTML; }
			this.activeItem = $(element);
			this.activeItemHTML = $(element).innerHTML;
			$(element).down("span").insert({after: "<em></em>"});
			swfobject.embedSWF(args.url, $(element).down("span").id, args.width, args.height, args.version, args.expressInstall, args.flashvars, args.params, args.attributes, args.callback);
		}.bind(this));
	}
};