/* All code copyright 2008 Grzegorz Jaskowiec */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Follows: ProductPresenter ver 0.9b (class)
 * Simple class for showing product information with titles and descriptions
 * Copyright 2008 GJ.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

var ProductPresenter = new Class({
	initialize: function(element, options) {
	this.setOptions({
	productScroller:"product_scroller",
	scrNbOfElements:"3",
	populateFrom:false,
	prevId:"previousProduct",
	nextId:"nextProduct",
	contentPrefix : "ipr",
	moreText: "więcej &raquo;",
	elementSelector: "div.productElement",
	titleSelector: "h2.titleElement",
	subtitleSelector: "h3.subtitleElement",
	descSelector: "div.descElement",
	moreSelector: "a.moreElement",
	defaultTransition: "fade",
	fadeDuration: 500,
	timed: false,
	delay: 9000,
	imageSelector: "a.imageElement",
	populateFrom: "products_presenter",
	destroyAfterPopulate: true,
	onlyGallery: false
	}, options);

	this.presenterData = "";
	this.presenterElement = element; 
	this.populateFrom = element;
	this.presenterElements = Array();
	this.thumbElements = Array();
	this.currentChosen=0;

	this.contentPrefix = this.options.contentPrefix;
	this.contentCount=0;
	this.presenterInit=1;

	this.populateData();
	this.constructElements();
	this.constructThumbs();

	this.loadingElement = new Element('div').addClass('loadingElement').injectInside($('products_viewer'));
	
	this.initScroller();
	this.doSlideShow(1);
	
 },

 changeActivity: function() {
 if(this.currentChosen>0) this.prevElement.removeClass('notActive'); else this.prevElement.addClass('notActive');
 if(this.currentChosen<this.contentCount-1) this.nextElement.removeClass('notActive'); else this.nextElement.addClass('notActive');
 },
 
populateData: function() {
		currentArrayPlace = this.presenterData.length;
		options = this.options;
		var data = $A(this.presenterData);
		data.extend(this.populatePresenter(this.populateFrom, currentArrayPlace));
		this.presenterData = data;
		this.fireEvent('onPopulated');
	},
populatePresenter: function(element, startNumber) {
		var data = [];
		options = this.options;
		currentArrayPlace = startNumber;
		element.getElements(options.elementSelector).each(function(el) {
			elementDict = {
				image: el.getElement(options.imageSelector).getProperty('href'),
				number: currentArrayPlace,
				thumbimage: el.getElement(options.imageSelector).getElement('img').getProperty('src'),
				transition: this.options.defaultTransition,
				title: el.getElement(options.titleSelector).innerHTML,
				subtitle: el.getElement(options.subtitleSelector).innerHTML,
				description: el.getElement(options.descSelector).innerHTML,
				morelink: el.getElement(options.moreSelector).getProperty('href'),
				morelinkText: el.getElement(options.moreSelector).getText()
				};
			
			
			data.extend([elementDict]);
			currentArrayPlace++;
			if (this.options.destroyAfterPopulate)
				el.remove();
		});
		return data;
	},
constructElements: function() {
		var elem = this.presenterElement;
		var el = new Element('div',{'id':'products_viewer'});
		this.titleElement = new Element('h2',{'class':'pp_name'}).injectInside(el);
		this.subtitleElement = new Element('h3',{'class':'pp_cat'}).injectInside(el);	
				
		this.maxIter = this.presenterData.length;
		var currentImg;
		
		for(i=0;i<this.presenterData.length;i++)
		{
			var currentImg = new Fx.Styles(
				new Element('div').addClass('photoElement').setStyles({
					'position':'absolute',
					'left':'0px',
					'right':'0px',
					'margin':'0px',
					'padding':'0px',
					'backgroundPosition':"center center",
					'opacity':'0'
				}).injectInside(el),
				'opacity',
				{duration: this.options.fadeDuration}
			);
			if (this.options.preloader)
			{
				currentImg.source = this.presenterData[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.presenterData[i].image + "')");
			}
			this.presenterElements[parseInt(i)] = currentImg;
		}
		this.descriptionElement = new Element('div', {'class':'description'}).injectInside(el);
		var moreElC = new Element('div',{'class': 'more'}).injectInside(el);
		this.moreElement = new Element('a').injectInside(moreElC);
		el.injectInside(elem);
	},
	
constructThumbs: function() {
	el = this.presenterElement;
	//other_products = $("other_products");
	this.prevElement = $(this.options.prevId);
	this.productScrollerElement = $(this.options.productScroller);
	this.nextElement = $(this.options.nextId);	
	
	
	for(i=0;i<this.presenterData.length;i++)
	{
	var currentDiv = new Element ('div').addClass("item").injectInside(this.productScrollerElement);
	
	if(i%this.options.scrNbOfElements==0) {
	currentDiv.setProperty('id', this.contentPrefix +'_' + i/this.options.scrNbOfElements);
	this.contentCount=this.contentCount+1;
	}
	
	var currentImg = new Element('img',{src: this.presenterData[i].thumbimage}).injectInside(currentDiv);
	
	currentImg.addEvents({
		'mouseover': function (myself) {
		myself.addClass('hover')
		}.pass(currentImg, this),
		'mouseout': function (myself) {
		myself.removeClass('hover')			
		}.pass(currentImg, this),
		'click': function (myself) {
			this.changeCurrent(myself.relatedImage.number);
			this.goTo(myself.relatedImage.number);
		}.pass(currentImg, this)
	});
	
	currentImg.relatedImage = this.presenterData[i];
	this.thumbElements[parseInt(i)] = currentImg;
	}
	
	},
	
	changeCurrent: function(num) {
	this.thumbElements.each(function(ten){
	ten.removeClass('current');								 
	});	
	this.thumbElements[num].addClass('current');

	},
	
	initScroller: function() {
		this.scroll_fx = new Fx.Scroll(this.options.productScroller, {
		wait: false,
		duration: 1200,
		offset: {'x': 0, 'y': 0},
		transition: Fx.Transitions.Bounce.easeOut
	});
		
		
	this.scroll_fx.toElement(this.contentPrefix +'_0');
	
	this.changeActivity();

	this.nextElement.addEvent('click', function(event) {
							event = new Event(event).stop();
							if(this.currentChosen<(this.contentCount-1)) {
							this.scroll_fx.toElement(this.contentPrefix +'_' + (this.currentChosen+1));
							this.currentChosen=this.currentChosen+1;
							}
							this.changeActivity();
							}.bind(this));
	
	this.prevElement.addEvent('click', function(event) {
							event = new Event(event).stop();
							if(this.currentChosen>0) {
							this.scroll_fx.toElement(this.contentPrefix +'_' + (this.currentChosen-1));
							this.currentChosen=this.currentChosen-1;
							}
							this.changeActivity();
							}.bind(this));
	
	},
	doSlideShow: function(position) {
		if (this.presenterInit == 1)
		{
			imgPreloader = new Image();
			imgPreloader.onload=function(){
				this.startSlideShow.delay(10, this);
			}.bind(this);
			imgPreloader.src = this.presenterData[0].image;
			if(this.options.preloader)
				this.presenterElements[0].load();
			
	this.titleElement.innerHTML = this.presenterData[0].title;	
	this.subtitleElement.innerHTML = this.presenterData[0].subtitle;
	this.descriptionElement.innerHTML = this.presenterData[0].description;
	this.moreElement.href = this.presenterData[0].morelink;
	this.moreElement.innerHTML = this.presenterData[0].morelinkText;
	this.changeCurrent(0);
		}
	},
	startSlideShow: function() {
		this.fireEvent('onStart');
		this.loadingElement.style.display = "none";
		this.lastIter = this.maxIter - 1;
		this.currentIter = 0;
		this.presenterInit = 0;
		this.presenterElements[parseInt(this.currentIter)].set({opacity: 1});
		this.prepareTimer();

	},
	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);
	},
	goTo: function(num) {
		this.clearTimer();
		if(this.options.preloader)
		{
			this.presenterElements[num].load();
			if (num==0)
				this.presenterElements[this.maxIter - 1].load();
			else
				this.presenterElements[num - 1].load();
			if (num==(this.maxIter - 1))
				this.presenterElements[0].load();
			else
				this.presenterElements[num + 1].load();
				
		}
		
		this.currentChangeDelay = this.changeItem.delay(500, this, num);
		
		this.changeCurrent(num);
		
		this.prepareTimer();

	},
	
	changeItem: function(num) {
		this.fireEvent('onStartChanging');
		this.presenterInit = 0;
		if (this.currentIter != num)
		{
			for(i=0;i<this.maxIter;i++)
			{
				if ((i != this.currentIter)) this.presenterElements[i].set({opacity: 0});
			}
			ProductPresenter.Transitions[this.presenterData[num].transition].pass([
				this.presenterElements[this.currentIter],
				this.presenterElements[num],
				this.currentIter,
				num], this)();
			
			this.titleElement.innerHTML = this.presenterData[num].title;	
			this.subtitleElement.innerHTML = this.presenterData[num].subtitle;
			this.descriptionElement.innerHTML = this.presenterData[num].description;
			this.moreElement.href=this.presenterData[num].morelink;
			this.moreElement.innerHTML = this.presenterData[num].morelinkText;
			this.currentIter = num;
		}
		
		this.doSlideShow.bind(this)();
		this.fireEvent('onChanged');
	},
	clearTimer: function() {
		if (this.options.timed)
			$clear(this.timer);
	},
	prepareTimer: function() {
		if (this.options.timed)
			{
		//var gotothis = ((this.currentChosen + 1)<this.contentCount)?this.currentChosen + 1:0;
		//this.thumbElements[gotothis].fireEvent('click');
		this.timer = this.nextItem.delay(this.options.delay, this);
			}
	}
 
 
 });

ProductPresenter.implement(new Events, new Options);

ProductPresenter.Transitions = new Abstract ({
	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});
		}
	},
	crossfade: function(oldFx, newFx, oldPos, newPos){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
		oldFx.options.duration = newFx.options.duration = this.options.fadeDuration;
		newFx.start({opacity: 1});
		oldFx.start({opacity: 0});
	},
	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);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Follows: formatString (function)
 * Original name: Yahoo.Tools.printf
 * Copyright Yahoo.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

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; 
}