var gallery = {
	initialize: function(element, options) {
		this.setOptions(options);
		this.fireEvent('onInit');
		this.currentIter = 0;
		this.lastIter = 0;
		this.maxIter = 0;
		this.galleryElement = element;
		this.galleryData = this.options;
		this.galleryInit = 1;
		this.galleryElements = Array();
		this.galleryElement.addClass('yogaSlide');		
		this.populateFrom = element;
		this.populateData();
		element.style.display="block";
		this.currentLink = new Element('a').addClass('click').setProperties({
				href: '#',
				title: ''
			}).injectInside(element);
		
				this.galleryElement = element = this.currentLink;

		
		this.constructElements();		
		this.loadingWrap = new Element('div').addClass('loadingWrap').injectInside(element);
		this.initInfoSlideshow();
		this.doSlideShow(1);
	},
	populateData: function() {
		currentArrayPlace = this.galleryData.length; 
		var data = $A(this.galleryData);
		data.extend(this.populateGallery(this.populateFrom, currentArrayPlace));
		this.galleryData = data;
		this.fireEvent('onPopulated');
	},
	populateGallery: function(element, startNumber) {
		var data = [];
		currentArrayPlace = startNumber;
		element.getElements('div.imageWrap').each(function(el) {
			elementDict = {
				image: el.getElement('img.full').getProperty('src'),
				number: currentArrayPlace,
				transition: 'fade'
			};
			elementDict.extend = $extend;
				elementDict.extend({
					title: el.getElement('h3').innerHTML,
					description: el.getElement('p').innerHTML
				});

				elementDict.extend({
					link: el.getElement('a.click').href||false,
					linkTitle: el.getElement('a.click').title||false,
					linkTarget: el.getElement('a.click').getProperty('target')||false
				});		
			
			data.extend([elementDict]);
			currentArrayPlace++;
			el.remove();
		});
		return data;
	},
	constructElements: function() {
		el = this.galleryElement;
		this.maxIter = this.galleryData.length;
		var currentImg;
		for(i=0;i<this.galleryData.length;i++)
		{
			var currentImg = new Fx.Styles(
				new Element('div').addClass('slideWrap').setStyles({
					'position':'absolute',
					'left':'0px',
					'right':'0px',
					'margin':'0px',
					'padding':'0px',
					'backgroundPosition':"center center",
					'opacity':'0'
				}).injectInside(el),
				'opacity',
				{duration: 700}
			);

				currentImg.source = this.galleryData[i].image;
				currentImg.loaded = false;
				currentImg.load = function(imageStyle) {
					if (!imageStyle.loaded)	{
						new Asset.image(imageStyle.source, {
		                            'onload'  : function(img){
													img.element.setStyle(
													'backgroundImage',
													"url('" + img.source + "')")
													img.loaded = true;
												}.bind(this, imageStyle)
						});
					}
				}.pass(currentImg, this);
			
			this.galleryElements[parseInt(i)] = currentImg;
		}
	},
	destroySlideShow: function(element) {
		var myClassName = element.className;
		var newElement = new Element('div').addClass('myClassName');
		element.parentNode.replaceChild(newElement, element);
	},
	startSlideShow: function() {
		this.fireEvent('onStart');
		this.loadingWrap.style.display = "none";
		this.lastIter = this.maxIter - 1;
		this.currentIter = 0;
		this.galleryInit = 0;
		this.galleryElements[parseInt(this.currentIter)].set({opacity: 1});
		this.showInfoSlideShow();
		this.prepareTimer();
		this.makeLink(this.currentIter);
	},
	nextItem: function() {
		this.fireEvent('onNextCalled');
		this.nextIter = this.currentIter+1;
		if (this.nextIter >= this.maxIter)
			this.nextIter = 0;
		this.galleryInit = 0;
		this.goTo(this.nextIter);
	},
	prevItem: function() {
		this.fireEvent('onPreviousCalled');
		this.nextIter = this.currentIter-1;
		if (this.nextIter <= -1)
			this.nextIter = this.maxIter - 1;
		this.galleryInit = 0;
		this.goTo(this.nextIter);
	},
	goTo: function(num) {
		this.clearTimer();

			this.galleryElements[num].load();
			if (num==0)
				this.galleryElements[this.maxIter - 1].load();
			else
				this.galleryElements[num - 1].load();
			if (num==(this.maxIter - 1))
				this.galleryElements[0].load();
			else
				this.galleryElements[num + 1].load();

			this.clearLink();
			this.captionSlide.clearChain();
			this.hideInfoSlideShow().chain(this.changeItem.pass(num, this));
			this.makeLink(num);
		this.prepareTimer();

	},
	changeItem: function(num) {
		this.fireEvent('onStartChanging');
		this.galleryInit = 0;
		if (this.currentIter != num)
		{
			for(i=0;i<this.maxIter;i++)
			{
				if ((i != this.currentIter)) this.galleryElements[i].set({opacity: 0});
			}
			gallery.Transitions[this.galleryData[num].transition].pass([
				this.galleryElements[this.currentIter],
				this.galleryElements[num],
				this.currentIter,
				num], this)();
			this.currentIter = num;
		}

		this.doSlideShow.bind(this)();
		this.fireEvent('onChanged');
	},
	clearTimer: function() {
			$clear(this.timer);
	},
	prepareTimer: function() {
			this.timer = this.nextItem.delay(4000, this);
	},
	doSlideShow: function(position) {
		if (this.galleryInit == 1)
		{
			imgPreloader = new Image();
			imgPreloader.onload=function(){
				this.startSlideShow.delay(10, this);
			}.bind(this);
			imgPreloader.src = this.galleryData[0].image;
			this.galleryElements[0].load();
		} else {
					this.showInfoSlideShow(700, this);
		}
	},
	initInfoSlideshow: function() {
		this.captionSlide = new Fx.Styles(new Element('div').addClass('captionSlide').injectInside($(this.galleryElement))).set({'opacity':0});
		var captionSlideTitle = new Element('h2').injectInside(this.captionSlide.element);
		var captionSlideDescription = new Element('p').injectInside(this.captionSlide.element);
		this.captionSlide.normalHeight = this.captionSlide.element.offsetHeight;
		this.captionSlide.element.setStyle('opacity',0);
	},
	changeInfoSlideShow: function()
	{
		this.hideInfoSlideShow();
		this.showInfoSlideShow();
	},
	showInfoSlideShow: function() {
		this.fireEvent('onShowInfopane');
		this.captionSlide.clearTimer();
		element = this.captionSlide.element;
		element.getElement('h2').setHTML(this.galleryData[this.currentIter].title);
		element.getElement('p').setHTML(this.galleryData[this.currentIter].description);
		this.captionSlide.start({'opacity': [0, 1], 'height': [0, '70px']});
		return this.captionSlide;
	},
	hideInfoSlideShow: function() {
		this.fireEvent('onHideInfopane');
		this.captionSlide.clearTimer();
		this.captionSlide.start({'opacity': 0, 'height': 0});
		return this.captionSlide;
	},
	makeLink: function(num) {
		this.currentLink.setProperties({
			href: this.galleryData[num].link,
			title: this.galleryData[num].linkTitle
		})
	},
	clearLink: function() {
		this.currentLink.setProperties({href: '', title: ''});
	},

	flushGallery: function() {
		this.galleryElements.each(function(myFx) {
			myFx.element.remove();
			myFx = myFx.element = null;
		});
		this.galleryElements = [];
	},
	changeData: function(data) {
		this.galleryData = data;
		this.clearTimer();
		this.flushGallery();
		this.constructElements();
		this.hideInfoSlideShow();
		this.galleryInit=1;
		this.lastIter=0;
		this.currentIter=0;
		this.doSlideShow(1);
	}
};
gallery = new Class(gallery);
gallery.implement(new Events);
gallery.implement(new Options);

gallery.Transitions = new Abstract ({
	fade: function(lastEffect, newEffect, lastPosition, nextPosition){
		lastEffect.options.transition = newEffect.options.transition = Fx.Transitions.linear;
		lastEffect.options.duration = newEffect.options.duration = 700;
		if (nextPosition > lastPosition) newEffect.start({opacity: 1});
		else
		{
			newEffect.set({opacity: 1});
			lastEffect.start({opacity: 0});
		}
	}
});

var Preloader = new Class({
  
  Implements: [Events, Options],

  options: {
    root        : '',
    period      : 100
  },
  
  initialize: function(options){
    this.setOptions(options);
  },
  
  load: function(sources) {
    this.index = 0;
    this.images = [];
    this.sources = this.temps = sources;
    this.total = this. sources.length;
    
    this.fireEvent('onStart', [this.index, this.total]);
    this.timer = this.progress.periodical(this.options.period, this);
    
    this.sources.each(function(source, index){
      this.images[index] = new Asset.image(this.options.root + source, {
        'onload'  : function(){ this.index++; if(this.images[index]) this.fireEvent('onLoad', [this.images[index], index, source]); }.bind(this),
        'onerror' : function(){ this.index++; this.fireEvent('onError', [this.images.splice(index, 1), index, source]); }.bind(this),
        'onabort' : function(){ this.index++; this.fireEvent('onError', [this.images.splice(index, 1), index, source]); }.bind(this)
      });
    }, this);
  },
  
  progress: function() {
    this.fireEvent('onProgress', [Math.min(this.index, this.total), this.total]);
    if(this.index >= this.total) this.complete();
  },
  
  complete: function(){
    $clear(this.timer);
    this.fireEvent('onComplete', [this.images]);
  },
  
  cancel: function(){
    $clear(this.timer);
  }
  
});

Preloader.implement(new Events, new Options);

function formatString() {
	var num = arguments.length;
	var oStr = arguments[0];
	for (var i = 1; i < num; i++) {
		var pattern = "\\{" + (i-1) + "\\}"; 
		var re = new RegExp(pattern, "g");
		oStr = oStr.replace(re, arguments[i]);
	}
	return oStr; 
}

window.addEvent('domready', function() {
    $$('.main_menu .page_item').each(function(el) {
		var sub = el.getElement('li');
        var fadeMe = el.getElement('ul');
		
        if(sub)  
        { 			
			
			var slide = new Fx.Slide(sub, { duration: 300, mode: 'horizontal', link: 'cancel'}).hide();
			fadeMe.setStyle('opacity', '0');
			el.getElement('div').setStyle('display', 'inline');
             el.addEvents({  
                 'mouseenter': function(){  
                    slide.slideIn();
					var fadein = new Fx.Style(fadeMe, 'opacity', {duration:300}).custom(0,1);
                },
                 'mouseleave': function(){  
                     
					 var fadeout = new Fx.Style(fadeMe, 'opacity', {duration:300}).custom(1,0);
					 slide.slideOut();
                 }
						 
             }); 			
         }  
     });
	
	
	$$('#sidebar li li').each(function(el) {  
        var sub = el.getElement('a');
        if(sub)  
        {
             el.addEvents({  
                 'mouseenter': function(){
					 
					var bumpin = new Fx.Style(sub, 'padding-left', {duration:150}).custom(0,'3px');
					
                },
                 'mouseleave': function(){  
				  
					 var bumpout = new Fx.Style(sub, 'padding-left', {duration:150}).custom('3px',0);
				 
                 }
						 
             }); 			
         }  
     });

 });