document.observe("dom:loaded", initPortfolio);
conversionProcessed = false; 
function initPortfolio(){
	var carousels = [];
	$$("div.horizontal_carousel").each(function(div){
		var carousel = new UI.Carousel(div);
		if(location.href.indexOf("/services/") != -1 || location.href.indexOf("/create/") != -1){new AutoCarousel(carousel);}
		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($("getELROStatic")){
		var processResponse1 = function(xhr){
			$("getELROStatic").down("fieldset").className = "";
			if(xhr.status == 200){
				var response = null;
				try{
					response = eval('('+xhr.responseText+')');
				}catch(e){};
				if(response && response.status == "ok"){
					$("getELROStatic").down("fieldset").className = "success";
					if(!conversionProcessed){conversion();}
					return;
				}
			}
			$("getELROStatic").down("fieldset").className = "error";
		};
		var contactSubmitCallback1 = function(errors, event){
			if(commonSubmitCallback(errors, event)){
				$("getELROStatic").down("fieldset").className = "progress";
				var startTime = new Date().getTime();
				$("getELROStatic").request({onComplete: function(xhr){
					var endTime = new Date().getTime();
					var delta = endTime - startTime;
					var timeout = 2000;
					if(delta < timeout){
						setTimeout(processResponse1.bind(null, xhr), timeout-delta);
					}else{
						processResponse1(xhr);
					}
				}});
			}
		};
		var conditions = {};
		if($("emailStatic") && $("subjectStatic") && $("messageStatic")){
			conditions = Object.extend(required("subjectStatic", "messageStatic"), {emailStatic: {submit: ['notBlank', 'email']}});
		}
		//if($("name") && $("company") && $("email") && $("phone") && $("time")){
		//	conditions = Object.extend(required("name", "company", "phone", "time"), {email: {submit: ['notBlank', 'email']}});
		//}
		var validator1 = new Validator(conditions, {afterValidate: contactSubmitCallback1});
		if($("getELROstaticSubmit")){
			$("getELROstaticSubmit").observe("click", function(event){
				event.stop(); 
				validator1.validateAllByType("submit", contactSubmitCallback1);
			});
		}
		if($("oneMoreMessageStatic")){$("oneMoreMessageStatic").observe("click", function(event){event.stop(); $("getELROStatic").down("fieldset").className = ""; $("getELROStatic").reset();});}
	}
	if($("getELROform")){
		//var dialogDiv = document.createElement("div");
		//document.body.appendChild(dialogDiv);
		//dialogDiv.appendChild($("getELROform").remove());
		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();});}
	}
	ModalDialog = new Modal();
	$("Content").select(".getQuoteModal").each(function(getQuoteElement){
		getQuoteElement.observe("click", function(event){
			event.stop();
			ModalDialog.show("getFreeQuoteDialog");
		});
	});
	}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));
	}
};
var Modal = Class.create();
Modal.prototype = {
	initialize: function(overlay){
    this.overlay = overlay ? $(overlay) : $("modalOverlay");
    this.curDialog = null;
    this.opened = false;
    Event.observe(document, 'keyup', this.checkClose.bind(this));
    Event.observe(document, 'click', this.checkCloseClick.bind(this));
  },
  show: function(dialog){
    var oldDialog = this.curDialog;
    this.curDialog = $(dialog);
    if(!this.curDialog){return;}
    if(!this.opened && this.overlay){
		//this.overlay.style.display = "block";
		this.curDialog.style.display = "block";
		//this.opened = true;
      
	  this.overlay.appear({
        duration: 0.5,
        to: 0.7,
        afterFinish: function(){
          //this.curDialog.style.display = "block";
		  this.opened = true;
        }.bind(this)
      });
	  
    }else{
      if(oldDialog){oldDialog.hide();}
      this.curDialog.style.display = "block";
      this.opened = true;
    }
    $(document.body).addClassName("modalOn");
  },
  checkClose: function(event){
   	var key = event.keyCode || event.which;
  	if(key == 27){
  		event.stop();
     	this.close();
  	}
  },
  checkCloseClick: function(event){
    if(this.opened){
      var target = event.target;
      if(target && (target == this.curDialog.down("a.close") || target == this.overlay)){
        event.stop();
        this.close();
      }
    }
  },
  close: function(){
    if(this.opened){
      $(document.body).removeClassName("modalOn");
      this.curDialog.hide();
      this.overlay.hide();
      this.opened = false;
    }
  }
};
var AutoCarousel = Class.create();
AutoCarousel.prototype = {
	initialize: function(carousel){
		this.carousel = carousel;
		this.curIndex = 0;
		this.offset = 1;
		this.switcher = $("AutoSlideshow");
		this.carousel.observe("nextButton:disabled", this.toggleOffset.bind(this));
		this.carousel.observe("previousButton:disabled", this.toggleOffset.bind(this));
		this.carousel.element.observe("click", this.end.bind(this));
		this.switcher.observe("click", this.switcherOnclick.bind(this));
		this.delayScroll();
	},
	switcherOnclick: function(event){
		event.stop();
		var a = event.findElement("a");
		if(a && a.href && a.href.indexOf("#slideshow")!=-1){
			var action = a.href.replace(/.*#slideshow/, "").toLowerCase();
			this.switcher.className = action;
			if(action == "on"){
				this.stopped = false;
				this.curIndex = parseInt(this.carousel.currentIndex());
				this.scroll();
			}else{
				this.stopped = true;
			}
		}
	},
	toggleOffset: function(){
		this.offset *= -1;
	},
	delayScroll: function(){
		var scrollDelay = 5000;
		this.scrollTimer = setTimeout(this.checkScroll.bind(this), scrollDelay);
	},
	checkScroll: function(){
		if(this.scrollTimer){ this.scroll(); }
	},
	scroll: function(){
		if(!this.stopped){
			this.switcher.className = "on";
			if(this.curIndex == 0){
				this.offset = 1;
			}
			if(this.curIndex == this.carousel.elements.length - 1){
				this.offset = -1;
			}
			this.curIndex += this.offset
			this.carousel.scrollTo(this.curIndex);
			this.delayScroll();
		}
	},
	end: function(){
		this.stopped = true;
		clearTimeout(this.scrollTimer);
		this.switcher.className = "off";
	}
};
