/*
	Modified by ZSE [Tomislav Cimerman] for use on zse.hr (v2)
   This file is part of JonDesign's SmoothGallery v2.0.

   JonDesign's SmoothGallery is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   JonDesign's SmoothGallery is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with JonDesign's SmoothGallery; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

   Main Developer: Jonathan Schemoul (JonDesign: http://www.jondesign.net/)
   Contributed code by:
   - Christian Ehret (bugfix)
	- Nitrix (bugfix)
	- Valerio from Mad4Milk for his great help with the carousel scrolling and many other things.
	- Archie Cowan for helping me find a bugfix on carousel inner width problem.
	- Tomocchino from #mootools for the preloader class
	Many thanks to:
	- The mootools team for the great mootools lib, and it's help and support throughout the project.
*/

// declaring the class
var gallery = {
	initialize: function(element, options) {
	this.setOptions({
			random: false,
			fadeDuration: 1000,
			delay: 9000,
			preloader: true,
			manualData: [],
			defaultTransition: "fade",
			baseClass: 'jdGallery'
		}, options);
		this.fireEvent('onInit');
		this.galleryElement = element;
		this.galleryData = this.options.manualData;
		this.galleryInit = true;
		this.galleryElements = Array();
		this.galleryElement.addClass(this.options.baseClass);
		element.style.display="block";
		
		this.maxIter = this.galleryData.length;
		this.currentIter = ( this.options.random ? Math.floor(Math.random() * this.maxIter ) : 0);
		
		this.constructElements();
		this.loadingElement = new Element('div').addClass('loadingElement').injectInside(element);
		this.doSlideShow();
	},
	constructElements: function() {
		el = this.galleryElement;
		el.innerHTML='';
		var currentImg;
		for(i=0;i<this.galleryData.length;i++)
		{
			var zigzagDirection = (i % 2 != 0);
			
			var slideElement = new Element('div').addClass('slideElement').setStyles({
				'cursor':'default',
				'position':'absolute',
				'left':'0px',
				'right':'0px',
				'margin':'0px',
				'padding':'0px',
				'backgroundPosition':"center center",
				'backgroundRepeat':"no-repeat",
				'opacity':'0'
			}).addClass(zigzagDirection ? 'right' : 'left');

			if (typeof this.galleryData[i].link != 'undefined') {
				eval("slideElement.addEvent('click',function(){ window.location='" + this.galleryData[i].link + "' } ).setStyle('cursor','pointer')");
			}
			
			/*
			//globaldizajn: setHTML se vise ne koristi.
			slideElement.setHTML(
				( typeof this.galleryData[i].title != 'undefined' ?  '<p class="titleShadow">' + this.galleryData[i].title + '</p>' + '<p class="title">' + this.galleryData[i].title + '</p>' : '' ) +
				(typeof this.galleryData[i].text != 'undefined' ? '<p class="text">' + this.galleryData[i].text + '</p>' : '')
			);
			*/

			slideElement.set('html',
				( typeof this.galleryData[i].title != 'undefined' ?  '<p class="titleShadow">' + this.galleryData[i].title + '</p>' + '<p class="title">' + this.galleryData[i].title + '</p>' : '' ) +
				(typeof this.galleryData[i].text != 'undefined' ? '<p class="text">' + this.galleryData[i].text + '</p>' : '')
			);

			slideElement.injectInside(el);
			
			
			/*
			//globaldizajn: Fx.Styles() se vise ne koristi.
			var currentImg = new Fx.Morph(
				slideElement,
				'opacity',
				{duration: this.options.fadeDuration}
			);
			*/
			
			var currentImg = new Fx.Morph(
				slideElement,
				'opacity',
				{duration: this.options.fadeDuration}
			);
			
			
			if (this.options.preloader)
			{
				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);
			} else {
				currentImg.element.setStyle('backgroundImage',
									"url('" + this.galleryData[i].image + "')");
			}
			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.loadingElement.style.display = "none";
		this.galleryInit = false;
		this.galleryElements[parseInt(this.currentIter)].set({opacity: 1});
		this.prepareTimer();
		if (this.options.embedLink)
			this.makeLink(this.currentIter);
	},
	nextItem: function() {
		this.fireEvent('onNextCalled');
		this.nextIter = this.currentIter+1;
		if (this.nextIter >= this.maxIter)
			this.nextIter = 0;
		this.galleryInit = false;
		this.goTo(this.nextIter);
	},
	goTo: function(num) {
		this.clearTimer();
		if(this.options.preloader)
		{
			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();
				
		}
		if (this.options.embedLink)
			this.clearLink();
		this.currentChangeDelay = this.changeItem.delay(500, this, num);
		if (this.options.embedLink)
			this.makeLink(num);
		this.prepareTimer();
	},
	changeItem: function(num) {
		this.fireEvent('onStartChanging');
		this.galleryInit = false;
		if (this.currentIter != num)
		{
			for(i=0;i<this.maxIter;i++)
			{
				if ((i != this.currentIter)) this.galleryElements[i].set({opacity: 0});
			}
			
			var transition = (typeof this.galleryData[num].transition == 'undefined' ? this.options.defaultTransition : this.galleryData[num].transition);
			
			gallery.Transitions[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(this.options.delay + this.options.fadeDuration, this);
	},
	doSlideShow: function() {
		if (this.galleryInit)
		{
			imgPreloader = new Image();
			imgPreloader.onload=function(){
				this.startSlideShow.delay(10, this);
			}.bind(this);
			imgPreloader.src = this.galleryData[this.currentIter].image;
			if(this.options.preloader)
				this.galleryElements[this.currentIter].load();
		}
	},
	/* To change the gallery data, those two functions : */
	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.galleryInit=true;
		this.currentIter=0;
		this.doSlideShow();
	}
};
gallery = new Class(gallery);
gallery.implement(new Events);
gallery.implement(new Options);

gallery.Transitions = new Hash ({
	fade: function(oldFx, newFx, oldPos, newPos){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
		oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
		if (newPos > oldPos) newFx.start({opacity: 1});
		else
		{
			newFx.set({opacity: 1});
			oldFx.start({opacity: 0});
		}
	},
	slide: function(oldFx, newFx, oldPos, newPos){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.Circ.easeOut;
		oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
			var offset = this.galleryElement.getParent().getCoordinates().height;
			newFx.set({opacity: 1});
			newFx.set({top:'-' + offset + 'px'});
			newFx.start({top:'0'});
			oldFx.set({top:'0'});
			oldFx.start({top: offset + 'px'});
	},
	zigzag: function(oldFx, newFx, oldPos, newPos){
		zigzagDirection = (newPos % 2 != 0);
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.Pow.easeInOut;
		oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
		var offset = this.galleryElement.getParent().getCoordinates().width - 2;
		
		newFx.set({opacity: 1, 'left': (zigzagDirection ? '-' : '') + offset + 'px'});
		newFx.start({'left':'0'});
		oldFx.set({'left':'0'});
		oldFx.start({'left': (zigzagDirection ? '' : '-') + offset + 'px'});		
		
	},
	slideLeft: function(oldFx, newFx, oldPos, newPos){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.Pow.easeInOut;
		oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
		var offset = this.galleryElement.getParent().getCoordinates().width - 2;
		
		newFx.set({opacity: 1, 'left': offset + 'px'});
		newFx.start({'left':'0'});
		oldFx.set({'left':'0'});
		oldFx.start({'left': '-' + offset + 'px'});		
		
	},
	fadebg: function(oldFx, newFx, oldPos, newPos){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
		oldFx.options.duration = newFx.options.duration = this.options.fadeDuration / 2;
		oldFx.start({opacity: 0}).chain(newFx.start.pass([{opacity: 1}], newFx));
	}
});

/* All code copyright 2007 Jonathan Schemoul */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Follows: Preloader (class)
 * Simple class for preloading images with support for progress reporting
 * Copyright 2007 Tomocchino.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

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);
