// JavaScript Document
/*
---

script: Array.Extras.js

description: Extends the Array native object to include useful methods to work with arrays.

license: MIT-style license

authors:
- Christoph Pojer

requires:
- core:1.2.4/Array

provides: [Array.Extras]

...
*/
Array.prototype.shuffle = function(){
		for (var i = this.length; i && --i;){
			var temp = this[i], r = Math.floor(Math.random() * ( i + 1 ));
			this[i] = this[r];
			this[r] = temp;
		}
		return this;
	};

var TimeCounter = {
														
	 init: function(){
		 this.counter = $('counter');
		 this.day = this.counter.getElement('.days');
		 this.time = this.counter.getElement('.time');
		 this.end = Date.parse('Apr 24, 2009 17:15:00');
		 this.seconds = 1000;
		 this.minutes = this.seconds * 60;
		 this.hours = this.minutes * 60;
		 this.days = this.hours * 24;
	 
		 this.update.periodical(1000, this);
	 },
	 
	 update: function(){
		 var diff = this.getDiff();
		 this.day.setText(diff.days);
		 this.time.setText(diff.time);
	 },
	 
	 getDiff: function(){
		 var current = new Date().getTime();
		 var delta = this.end - current;
		 var days = Math.floor(delta / this.days);
		     delta = delta - days*this.days;
		 var time = new Array();
		 time[0] = Math.floor(delta / this.hours);
		   delta = delta - time[0]*this.hours;
		 time[0] = (time[0] < 10 ? '0'+time[0].toString() : time[0].toString());
		 
		 time[1] = Math.floor(delta / this.minutes);
		   delta = delta - time[1]*this.minutes;
		 time[1] = (time[1] < 10 ? '0'+time[1].toString() : time[1].toString());
		 
		 time[2] = Math.floor(delta / this.seconds);
		 time[2] = (time[2] < 10 ? '0'+time[2].toString() : time[2].toString());
		 var diff = {
			 days: days.toString(),
			 time: time.join(':')
		 };
		 return diff;
	 }
 };

var ViewChange = {
	
	  init: function(){
			    
					var box = $('box');
					
					// Cookie
					if (Cookie.get('viewStatus') == 'list-view') {
						if (!box.hasClass('list-view')) { box.addClass('list-view'); }
						$$('#view-switch a').toggleClass('selected');
					} else {
						if (box.hasClass('list-view')) { box.removeClass('list-view'); }
					}
					
					// switch actions
					$('box-view').onclick = function(event){
						event = new Event(event);
						event.preventDefault();
						if (box.hasClass('list-view')) { box.removeClass('list-view'); }
						$$('#view-switch a').toggleClass('selected');
						Cookie.set('viewStatus','box-view', { path: '/' });
					}
					
					$('list-view').onclick = function(event){
						event = new Event(event);
						event.preventDefault();
						if (!box.hasClass('list-view')) { box.addClass('list-view'); }
						$$('#view-switch a').toggleClass('selected');
						Cookie.set('viewStatus','list-view', { path: '/' });
					}
		}

 };

var Mapa = {
	
	  init: function(){
			 
		 
			 var field = $('mapa-cr-wrapper');
			 
			 field.getElement('img').setOpacity(0.001);

			 
			 // kraje
			 var areas = $('mapa-cr-large').getElements('area');
			 
			 var kraje = new Hash({
						'zlinsky'         : [1, 2],
						'praha'           : [2, 1],
						'kralovehradecky' : [3, 2],
						'vysocina'        : [1, 0],
						'jihocesky'       : [0, 2],
						'karlovarsky'     : [2, 0],
						'plzensky'        : [3, 1],
						'jihomoravsky'    : [0, 3],
						'moravskoslezsky' : [2, 3],
						'olomoucky'       : [1, 3],
						'pardubicky'      : [2, 2],
						'liberecky'       : [0, 1],
						'ustecky'         : [3, 0],
						'stredocesky'     : [1, 1] 
			 });
			 
			 var bubbles = new Hash({
					  'zlinsky'         : [317, 169],
						'praha'           : [132,  65],
						'kralovehradecky' : [217,  53],
						'vysocina'        : [198, 139],
						'jihocesky'       : [116, 160],
						'karlovarsky'     : [ 34,  45],
						'plzensky'        : [ 53, 102],
						'jihomoravsky'    : [251, 175],
						'moravskoslezsky' : [339, 110],
						'olomoucky'       : [288, 127],
						'pardubicky'      : [233,  98],
						'liberecky'       : [172,  12],
						'ustecky'         : [105,  22],
						'stredocesky'     : [163,  72] 
			 });

       areas.each(function(element){
					var prefix = '/kontakty/technicti-poradci-ceresit/';
					if (element.getProperty('href').test('prodejci')){
						prefix = '/prodejci/';
					}
					if (element.getProperty('href').test('soutez')){
						prefix = '/soutez/fotografie/';
					}
          var kraj = element.getProperty('href').replace(prefix, '').replace('-kraj', '');
								 // bubble
	 			  var bubble = new Element('p', { 'class' : 'bubble' });
				  bubble.setHTML('<span>' + element.getProperty('title') +'</span>');
					bubble.setStyles({
					    'left' : bubbles.get(kraj)[0],
							'top'  : bubbles.get(kraj)[1]
					});
				  var bubbleFx = new Fx.Style(bubble, 'opacity', { duration: 200, wait: false });
				  bubbleFx.set(0);
				  bubble.injectInside(field);
					
					element.addEvent('mouseenter', function(event){
					    Mapa.move(kraje.get(kraj), field);
							bubbleFx.start(1);
					});
					
					element.addEvent('mouseleave', function(event){
							Mapa.move([0, 0], field); 
							bubbleFx.start(0);
					});
			 });
			
		},
		
		move: function(coords, field){
			var col = coords[0];
			var row = coords[1];
			var width = 422;
			var height = 259;
			field.setStyle('background-position', (-422*col) + 'px ' + (-259*row) + 'px');
		}
		
 };

var BoxShow = new Class({
	
	initialize: function(container){
		this.container = container;
		this.box = this.container.getElements('div')[1];
		if (this.box){
			this.boxFx = new Fx.Style(this.box, 'opacity', { duration: 1000, wait: true });
			this.status = 1;
			this.opacityToggle.periodical(10000, this);
		}
	},

  opacityToggle: function(){
		if (this.status){
			this.boxFx.start(0);
			this.status = 0;
		} else {
			this.boxFx.start(1);
			this.status = 1;
		}
	}
});

var PdfTargetBlank = {
	  init: function(){
			  var links = $$('.product-docs a');
				links = links.filter(function(item){
				 return item.getProperty('href').test('(.*)pdf$');
				});
				links.each(function(element){
				  element.addEvent('click', function(event){
					  var event = new Event(event);
						event.stop();
						window.open(element.getProperty('href'));
					});
				});
		}
 };
 
var BackgroundSlideshow = new Class({

  options: {
		// onStart: $emtpy()
		// onReady: $empty()
		path: '/images/page-bg-{i}.jpg', // dynamic loading OR image folder
		images: [], // predefined images
		auto: true,
		duration: 10000,
		fxDuration: 500,
		range: 0
	},
	
  initialize: function(container, options){
		
		var self = this;
		
		this.container = $(container);
		
		$extend(this.options, options || {});
		
		this.paths = [];
		if (this.options.images.length){
			var length = this.options.images.length;
			for (var i = 1; i < length; i++){
				this.paths.push(this.options.path + this.options.images[i]);
			}
		} else {
			for (var i = 1; i < this.options.range; i++){
				this.paths.push(this.options.path.substitute({i: i}));
			}
		}
		
		this.slides = [];
		this.slides.push(this.container.getElement('.image'));
		this.current = 0;
		this.slideFx = [];
		this.slideFx[0] = new Fx.Style(this.slides[0], 'opacity', {duration: this.options.fxDuration, link: 'cancel' }).set(0);
		this.count = 1;
		this.timer = null;
		
		
		this.images = new Asset.images(this.paths, {
		  onComplete: function(){
				self.createSlides();
			}
		});
		
	},
	
	createSlides: function(){
		this.images.each(function(image, index){
			this.slides[index+1] = new Element('div', {
			  'class': 'image',
				'styles': {
					'background-image': 'url('+image.src+')'
				}
			});
			this.slideFx.include(new Fx.Style(this.slides[index+1], 'opacity', {duration: this.options.fxDuration, link: 'cancel' }).set(0));
			this.slides[index+1].inject(this.container);
		}, this);
		
		this.count = this.slides.length;
		
		this.container.fireEvent('ready');
		if (this.options.auto) this.start();
	},
	
	start: function(){
		this.timer = this.move.periodical(this.options.duration, this);
	},
	
	move: function(){
		this.slideFx[this.current].start(0);
		this.current = ++this.current%this.count;
		this.slideFx[this.current].start(1);
	},
	
	show: function(index){
		this.slideFx[this.current].start(0);
		this.current = index;
		this.slideFx[this.current].start(1);
	}
	
});

window.addEvent('domready', function(){
	if ($('view-switch')) { ViewChange.init(); }
	
	if ($('mapa-cr-large')) Mapa.init();
	
	PdfTargetBlank.init();
	
	if ($$('a._blank')){
		//alert('sss');
		$$('a._blank').each(function(item){
		  item.setAttribute('target', '_blank');
		});
	}
	
	if ($$('.boxshow')){
		$$('.boxshow').each(function(element, index){
		  (function(){ new BoxShow(element); }).delay(index*0);
		});
	}
	
	$$('table.dealers a[href^=http]').each(function(web){
		web.addEvent('click', function(event){
		  event = new Event(event);
			event.stop();
			window.open(web.href);
		});
	});
	
	if ($('counter')) TimeCounter.init();
		
	
	$$('.clickable, #box .box, #used-products .item, #blocks .box').each(function(element){
	  element.setStyle('cursor', 'pointer');
		element.addEvent('click', function(){
		  if(!element.getElement('a').hasClass('_blank')) {
				window.location = element.getElement('a').href;
			} else {
				window.open(element.getElement('a').href, "_blank");
			}
		});
		element.getElements('a').addEvent('click', function(event){
		  var event = new Event(event);
			event.stopPropagation();
		});
	});
	
	// backgrounds
	this.backgrounds = ['bg-1.jpg', 'bg-2.jpg', 'bg-3.jpg', 'bg-4.jpg'].shuffle();
	// prepare first element
	var pageBg = new Element('div', {
		id: 'page-bg'
	});
	pageBg.adopt(new Element('div', {
		'class': 'image',
		styles: {
			opacity: 0
		}
	}));
	pageBg.inject(document.body, 'top');
	
	this.slideshow = new BackgroundSlideshow('page-bg', {
		path: '/img/backgrounds/',
		images: this.backgrounds,
		auto: true,
		fxDuration: 1000
	});
});
